diff --git a/plugin/consensus/dpos/dpos.go b/plugin/consensus/dpos/dpos.go index 2c2b2e0452b85b4ff6059832c5f4ce85e4eaa45a..f99f897c2c7c9e2922889db8234bafa9af103a4a 100644 --- a/plugin/consensus/dpos/dpos.go +++ b/plugin/consensus/dpos/dpos.go @@ -436,13 +436,14 @@ func (client *Client) ProcEvent(msg *queue.Message) bool { // CreateBlock a routine monitor whether some transactions available and tell client by available channel func (client *Client) CreateBlock() { lastBlock := client.GetCurrentBlock() - txs := client.RequestTx(int(types.GetP(lastBlock.Height+1).MaxTxNumber), nil) + cfg := client.GetAPI().GetConfig() + txs := client.RequestTx(int(cfg.GetP(lastBlock.Height+1).MaxTxNumber), nil) if len(txs) == 0 { block := client.GetCurrentBlock() if createEmptyBlocks { emptyBlock := &types.Block{} emptyBlock.StateHash = block.StateHash - emptyBlock.ParentHash = block.Hash() + emptyBlock.ParentHash = block.Hash(cfg) emptyBlock.Height = block.Height + 1 emptyBlock.Txs = nil emptyBlock.TxHash = zeroHash[:] @@ -461,11 +462,11 @@ func (client *Client) CreateBlock() { //check dup txs = client.CheckTxDup(txs, client.GetCurrentHeight()) var newblock types.Block - newblock.ParentHash = lastBlock.Hash() + newblock.ParentHash = lastBlock.Hash(cfg) newblock.Height = lastBlock.Height + 1 client.AddTxsToBlock(&newblock, txs) // - newblock.Difficulty = types.GetP(0).PowLimitBits + newblock.Difficulty = cfg.GetP(0).PowLimitBits newblock.TxHash = merkle.CalcMerkleRoot(newblock.Txs) newblock.BlockTime = client.blockTime @@ -580,7 +581,8 @@ func (client *Client) CreateRecordCBTx(info *dty.DposCBInfo) (tx *types.Transact RecordCB: info, } action.Ty = dty.DposVoteActionRecordCB - tx, err = types.CreateFormatTx("dpos", types.Encode(&action)) + cfg := client.GetAPI().GetConfig() + tx, err = types.CreateFormatTx(cfg, "dpos", types.Encode(&action)) if err != nil { return nil, err } @@ -595,7 +597,8 @@ func (client *Client) CreateRegVrfMTx(info *dty.DposVrfMRegist) (tx *types.Trans RegistVrfM: info, } action.Ty = dty.DposVoteActionRegistVrfM - tx, err = types.CreateFormatTx("dpos", types.Encode(&action)) + cfg := client.GetAPI().GetConfig() + tx, err = types.CreateFormatTx(cfg, "dpos", types.Encode(&action)) if err != nil { return nil, err } @@ -610,7 +613,8 @@ func (client *Client) CreateRegVrfRPTx(info *dty.DposVrfRPRegist) (tx *types.Tra RegistVrfRP: info, } action.Ty = dty.DposVoteActionRegistVrfRP - tx, err = types.CreateFormatTx("dpos", types.Encode(&action)) + cfg := client.GetAPI().GetConfig() + tx, err = types.CreateFormatTx(cfg, "dpos", types.Encode(&action)) if err != nil { return nil, err } @@ -708,7 +712,8 @@ func (client *Client) CreateTopNRegistTx(reg *dty.TopNCandidatorRegist) (tx *typ RegistTopN: reg, } action.Ty = dty.DPosVoteActionRegistTopNCandidator - tx, err = types.CreateFormatTx("dpos", types.Encode(&action)) + cfg := client.GetAPI().GetConfig() + tx, err = types.CreateFormatTx(cfg, "dpos", types.Encode(&action)) if err != nil { return nil, err } diff --git a/plugin/consensus/dpos/state_machine.go b/plugin/consensus/dpos/state_machine.go index 3eb9382d7b3556382848dfdba6ffc97d22d5f27a..5544a2bc9fcceda61bcf75ff1fa1230e791bfd30 100644 --- a/plugin/consensus/dpos/state_machine.go +++ b/plugin/consensus/dpos/state_machine.go @@ -572,6 +572,7 @@ func (voted *VotedState) timeOut(cs *ConsensusState) { now := time.Now().Unix() block := cs.client.GetCurrentBlock() task := DecideTaskByTime(now) + cfg := cs.client.GetAPI().GetConfig() dposlog.Info("address info", "privValidatorAddr", hex.EncodeToString(cs.privValidator.GetAddress()), "VotedNodeAddress", hex.EncodeToString(cs.currentVote.VotedNodeAddress)) if bytes.Equal(cs.privValidator.GetAddress(), cs.currentVote.VotedNodeAddress) { @@ -598,7 +599,7 @@ func (voted *VotedState) timeOut(cs *ConsensusState) { info := &dty.DposCBInfo{ Cycle: cs.currentVote.Cycle, StopHeight: block.Height, - StopHash: hex.EncodeToString(block.Hash()), + StopHash: hex.EncodeToString(block.Hash(cfg)), Pubkey: strings.ToUpper(hex.EncodeToString(cs.privValidator.GetPubKey().Bytes())), } @@ -622,7 +623,7 @@ func (voted *VotedState) timeOut(cs *ConsensusState) { DPosNotify: &dpostype.DPosNotify{ Vote: cs.currentVote, HeightStop: block.Height, - HashStop: block.Hash(), + HashStop: block.Hash(cfg), NotifyTimestamp: now, NotifyNodeAddress: cs.privValidator.GetAddress(), NotifyNodeIndex: int32(cs.privValidatorIndex), @@ -833,6 +834,7 @@ func (wait *WaitNofifyState) sendNotify(cs *ConsensusState, notify *dpostype.DPo func (wait *WaitNofifyState) recvNotify(cs *ConsensusState, notify *dpostype.DPosNotify) { dposlog.Info("WaitNofifyState recvNotify") + cfg := cs.client.GetAPI().GetConfig() //记录Notify,校验区块,标记不可逆区块高度 if !cs.VerifyNotify(notify) { dposlog.Info("VotedState verify notify failed") @@ -843,7 +845,7 @@ func (wait *WaitNofifyState) recvNotify(cs *ConsensusState, notify *dpostype.DPo if block.Height > notify.HeightStop { dposlog.Info("Local block height is advanced than notify, discard it.", "localheight", block.Height, "notify", printNotify(notify)) return - } else if block.Height == notify.HeightStop && bytes.Equal(block.Hash(), notify.HashStop) { + } else if block.Height == notify.HeightStop && bytes.Equal(block.Hash(cfg), notify.HashStop) { dposlog.Info("Local block height is sync with notify", "notify", printNotify(notify)) } else { dposlog.Info("Local block height is not sync with notify", "localheight", cs.client.GetCurrentHeight(), "notify", printNotify(notify)) @@ -856,7 +858,7 @@ func (wait *WaitNofifyState) recvNotify(cs *ConsensusState, notify *dpostype.DPo case <-hint.C: dposlog.Info("Still catching up max height......", "Height", cs.client.GetCurrentHeight(), "notifyHeight", notify.HeightStop, "cost", time.Since(beg)) if cs.client.IsCaughtUp() && cs.client.GetCurrentHeight() >= notify.HeightStop { - dposlog.Info("This node has caught up max height", "Height", cs.client.GetCurrentHeight(), "isHashSame", bytes.Equal(block.Hash(), notify.HashStop)) + dposlog.Info("This node has caught up max height", "Height", cs.client.GetCurrentHeight(), "isHashSame", bytes.Equal(block.Hash(cfg), notify.HashStop)) break OuterLoop } diff --git a/plugin/consensus/raft/block.go b/plugin/consensus/raft/block.go index fefb16fa810137257c385bd3cb4b9ba9ebe92b5e..dfaec2867b4c693d257149b9ef6a5eb404ae023b 100644 --- a/plugin/consensus/raft/block.go +++ b/plugin/consensus/raft/block.go @@ -112,7 +112,7 @@ func (client *Client) CreateBlock() { retry := 0 infoflag := 0 count := 0 - + cfg := client.GetAPI().GetConfig() //打包区块前先同步到最大高度 for { if client.IsCaughtUp() { @@ -147,7 +147,7 @@ func (client *Client) CreateBlock() { block := client.GetCurrentBlock() emptyBlock := &types.Block{} emptyBlock.StateHash = block.StateHash - emptyBlock.ParentHash = block.Hash() + emptyBlock.ParentHash = block.Hash(cfg) emptyBlock.Height = block.Height + 1 emptyBlock.Txs = nil emptyBlock.TxHash = zeroHash[:] @@ -166,7 +166,7 @@ func (client *Client) CreateBlock() { } lastBlock := client.GetCurrentBlock() - txs := client.RequestTx(int(types.GetP(lastBlock.Height+1).MaxTxNumber), nil) + txs := client.RequestTx(int(cfg.GetP(lastBlock.Height+1).MaxTxNumber), nil) if len(txs) == 0 { issleep = true continue @@ -175,7 +175,7 @@ func (client *Client) CreateBlock() { count = 0 rlog.Debug("==================start create new block!=====================") var newblock types.Block - newblock.ParentHash = lastBlock.Hash() + newblock.ParentHash = lastBlock.Hash(cfg) newblock.Height = lastBlock.Height + 1 client.AddTxsToBlock(&newblock, txs) newblock.TxHash = merkle.CalcMerkleRoot(newblock.Txs) diff --git a/plugin/consensus/tendermint/tendermint.go b/plugin/consensus/tendermint/tendermint.go index 51463895a35936459e132a3981d8554a84a6b77d..9f65ce3391e9a985751917ae047d1c35c3eb2a0a 100644 --- a/plugin/consensus/tendermint/tendermint.go +++ b/plugin/consensus/tendermint/tendermint.go @@ -419,7 +419,8 @@ func (client *Client) CheckTxDup(txs []*types.Transaction, height int64) (transa // BuildBlock build a new block contains some transactions func (client *Client) BuildBlock() *types.Block { lastHeight := client.GetCurrentHeight() - txs := client.RequestTx(int(types.GetP(lastHeight+1).MaxTxNumber)-1, nil) + cfg := client.GetAPI().GetConfig() + txs := client.RequestTx(int(cfg.GetP(lastHeight+1).MaxTxNumber)-1, nil) newblock := &types.Block{} newblock.Height = lastHeight + 1 client.AddTxsToBlock(newblock, txs) @@ -434,13 +435,16 @@ func (client *Client) CommitBlock(propBlock *types.Block) error { tendermintlog.Error("RequestBlock fail", "err", err) return err } - newblock.ParentHash = lastBlock.Hash() + cfg := client.GetAPI().GetConfig() + + newblock.ParentHash = lastBlock.Hash(cfg) newblock.TxHash = merkle.CalcMerkleRoot(newblock.Txs) newblock.BlockTime = time.Now().Unix() if lastBlock.BlockTime >= newblock.BlockTime { newblock.BlockTime = lastBlock.BlockTime + 1 } - newblock.Difficulty = types.GetP(0).PowLimitBits + + newblock.Difficulty = cfg.GetP(0).PowLimitBits err = client.WriteBlock(lastBlock.StateHash, &newblock) if err != nil { diff --git a/plugin/consensus/ticket/ticket.go b/plugin/consensus/ticket/ticket.go index f7bc63cb33cd7532a5525e49ec248c10f2a15f8b..55723550d1aad199ff751183cfdc0e38c3fcd9bc 100644 --- a/plugin/consensus/ticket/ticket.go +++ b/plugin/consensus/ticket/ticket.go @@ -109,15 +109,16 @@ func (client *Client) Close() { // CreateGenesisTx ticket create genesis tx func (client *Client) CreateGenesisTx() (ret []*types.Transaction) { + cfg := client.GetAPI().GetConfig() for _, genesis := range client.subcfg.Genesis { - tx1 := createTicket(genesis.MinerAddr, genesis.ReturnAddr, genesis.Count, 0) + tx1 := createTicket(cfg, genesis.MinerAddr, genesis.ReturnAddr, genesis.Count, 0) ret = append(ret, tx1...) } return ret } //316190000 coins -func createTicket(minerAddr, returnAddr string, count int32, height int64) (ret []*types.Transaction) { +func createTicket(cfg *types.Chain33Config, minerAddr, returnAddr string, count int32, height int64) (ret []*types.Transaction) { tx1 := types.Transaction{} tx1.Execer = []byte("coins") @@ -125,7 +126,7 @@ func createTicket(minerAddr, returnAddr string, count int32, height int64) (ret tx1.To = minerAddr //gen payload g := &cty.CoinsAction_Genesis{} - g.Genesis = &types.AssetsGenesis{Amount: ty.GetTicketMinerParam(height).TicketPrice} + g.Genesis = &types.AssetsGenesis{Amount: ty.GetTicketMinerParam(cfg, height).TicketPrice} tx1.Payload = types.Encode(&cty.CoinsAction{Value: g, Ty: cty.CoinsActionGenesis}) ret = append(ret, &tx1) @@ -135,7 +136,7 @@ func createTicket(minerAddr, returnAddr string, count int32, height int64) (ret tx2.To = driver.ExecAddress("ticket") //gen payload g = &cty.CoinsAction_Genesis{} - g.Genesis = &types.AssetsGenesis{Amount: int64(count) * ty.GetTicketMinerParam(height).TicketPrice, ReturnAddress: returnAddr} + g.Genesis = &types.AssetsGenesis{Amount: int64(count) * ty.GetTicketMinerParam(cfg, height).TicketPrice, ReturnAddress: returnAddr} tx2.Payload = types.Encode(&cty.CoinsAction{Value: g, Ty: cty.CoinsActionGenesis}) ret = append(ret, &tx2) @@ -307,7 +308,8 @@ func (client *Client) getModify(beg, end int64) ([]byte, error) { // CheckBlock ticket implete checkblock func func (client *Client) CheckBlock(parent *types.Block, current *types.BlockDetail) error { - cfg := ty.GetTicketMinerParam(current.Block.Height) + chain33Cfg := client.GetAPI().GetConfig() + cfg := ty.GetTicketMinerParam(chain33Cfg, current.Block.Height) if current.Block.BlockTime-types.Now().Unix() > cfg.FutureBlockTime { return types.ErrFutureBlock } @@ -367,7 +369,7 @@ func (client *Client) CheckBlock(parent *types.Block, current *types.BlockDetail return types.ErrBlockSize } //vrf verify - if types.IsDappFork(current.Block.Height, ty.TicketX, "ForkTicketVrf") { + if chain33Cfg.IsDappFork(current.Block.Height, ty.TicketX, "ForkTicketVrf") { var input []byte if current.Block.Height > 1 { LastTicketAction, err := client.getMinerTx(parent) @@ -413,8 +415,9 @@ func vrfVerify(pub []byte, input []byte, proof []byte, hash []byte) error { } func (client *Client) getNextTarget(block *types.Block, bits uint32) (*big.Int, []byte, error) { + cfg := client.GetAPI().GetConfig() if block.Height == 0 { - powLimit := difficulty.CompactToBig(types.GetP(0).PowLimitBits) + powLimit := difficulty.CompactToBig(cfg.GetP(0).PowLimitBits) return powLimit, defaultModify, nil } targetBits, modify, err := client.getNextRequiredDifficulty(block, bits) @@ -440,12 +443,13 @@ func (client *Client) getCurrentTarget(blocktime int64, id string, modify []byte // the exported version uses the current best chain as the previous block node // while this function accepts any block node. func (client *Client) getNextRequiredDifficulty(block *types.Block, bits uint32) (uint32, []byte, error) { + chain33Cfg := client.GetAPI().GetConfig() // Genesis block. if block == nil { - return types.GetP(0).PowLimitBits, defaultModify, nil + return chain33Cfg.GetP(0).PowLimitBits, defaultModify, nil } - powLimitBits := types.GetP(block.Height).PowLimitBits - cfg := ty.GetTicketMinerParam(block.Height) + powLimitBits := chain33Cfg.GetP(block.Height).PowLimitBits + cfg := ty.GetTicketMinerParam(chain33Cfg, block.Height) blocksPerRetarget := int64(cfg.TargetTimespan / cfg.TargetTimePerBlock) // Return the previous block's difficulty requirements if this block // is not at a difficulty retarget interval. @@ -527,6 +531,7 @@ func printBInt(data *big.Int) string { } func (client *Client) searchTargetTicket(parent, block *types.Block) (*ty.Ticket, crypto.PrivKey, *big.Int, []byte, string, error) { + cfg := client.GetAPI().GetConfig() bits := parent.Difficulty diff, modify, err := client.getNextTarget(parent, bits) if err != nil { @@ -543,7 +548,7 @@ func (client *Client) searchTargetTicket(parent, block *types.Block) (*ty.Ticket continue } //已经到成熟期 - if !ticket.GetIsGenesis() && (block.BlockTime-ticket.GetCreateTime() <= ty.GetTicketMinerParam(block.Height).TicketFrozenTime) { + if !ticket.GetIsGenesis() && (block.BlockTime-ticket.GetCreateTime() <= ty.GetTicketMinerParam(cfg, block.Height).TicketFrozenTime) { continue } // 查找私钥 @@ -632,6 +637,7 @@ func genPrivHash(priv crypto.PrivKey, tid string) ([]byte, error) { func (client *Client) addMinerTx(parent, block *types.Block, diff *big.Int, priv crypto.PrivKey, tid string, modify []byte) error { //return 0 always + cfg := client.GetAPI().GetConfig() fee := calcTotalFee(block) var ticketAction ty.TicketAction @@ -639,14 +645,14 @@ func (client *Client) addMinerTx(parent, block *types.Block, diff *big.Int, priv miner.TicketId = tid miner.Bits = difficulty.BigToCompact(diff) miner.Modify = modify - miner.Reward = ty.GetTicketMinerParam(block.Height).CoinReward + fee + miner.Reward = ty.GetTicketMinerParam(cfg, block.Height).CoinReward + fee privHash, err := genPrivHash(priv, tid) if err != nil { return err } miner.PrivHash = privHash //add vrf - if types.IsDappFork(block.Height, ty.TicketX, "ForkTicketVrf") { + if cfg.IsDappFork(block.Height, ty.TicketX, "ForkTicketVrf") { var input []byte if block.Height > 1 { LastTicketAction, err := client.getMinerTx(parent) @@ -686,7 +692,8 @@ func (client *Client) addMinerTx(parent, block *types.Block, diff *big.Int, priv } func (client *Client) createMinerTx(ticketAction proto.Message, priv crypto.PrivKey) *types.Transaction { - tx, err := types.CreateFormatTx("ticket", types.Encode(ticketAction)) + cfg := client.GetAPI().GetConfig() + tx, err := types.CreateFormatTx(cfg, "ticket", types.Encode(ticketAction)) if err != nil { return nil } @@ -695,20 +702,22 @@ func (client *Client) createMinerTx(ticketAction proto.Message, priv crypto.Priv } func (client *Client) createBlock() (*types.Block, *types.Block) { + cfg := client.GetAPI().GetConfig() lastBlock := client.GetCurrentBlock() var newblock types.Block - newblock.ParentHash = lastBlock.Hash() + newblock.ParentHash = lastBlock.Hash(cfg) newblock.Height = lastBlock.Height + 1 newblock.BlockTime = types.Now().Unix() if lastBlock.BlockTime >= newblock.BlockTime { newblock.BlockTime = lastBlock.BlockTime } - txs := client.RequestTx(int(types.GetP(newblock.Height).MaxTxNumber)-1, nil) + txs := client.RequestTx(int(cfg.GetP(newblock.Height).MaxTxNumber)-1, nil) client.AddTxsToBlock(&newblock, txs) return &newblock, lastBlock } func (client *Client) updateBlock(block *types.Block, txHashList [][]byte) (*types.Block, *types.Block, [][]byte) { + chain33Cfg := client.GetAPI().GetConfig() lastBlock := client.GetCurrentBlock() newblock := *block newblock.BlockTime = types.Now().Unix() @@ -718,9 +727,9 @@ func (client *Client) updateBlock(block *types.Block, txHashList [][]byte) (*typ newblock.Txs = client.CheckTxDup(newblock.Txs) newblock.Txs = client.CheckTxExpire(newblock.Txs, lastBlock.Height+1, newblock.BlockTime) } - newblock.ParentHash = lastBlock.Hash() + newblock.ParentHash = lastBlock.Hash(chain33Cfg) newblock.Height = lastBlock.Height + 1 - cfg := types.GetP(newblock.Height) + cfg := chain33Cfg.GetP(newblock.Height) var txs []*types.Transaction if len(newblock.Txs) < int(cfg.MaxTxNumber-1) { txs = client.RequestTx(int(cfg.MaxTxNumber)-1-len(newblock.Txs), txHashList) diff --git a/plugin/dapp/blackwhite/executor/action.go b/plugin/dapp/blackwhite/executor/action.go index 3f01a4cc36ae765443620483f27dd0e02c907516..f109bda8678270597414239a973e6b63c532e7d7 100644 --- a/plugin/dapp/blackwhite/executor/action.go +++ b/plugin/dapp/blackwhite/executor/action.go @@ -16,6 +16,7 @@ import ( "github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/types" gt "github.com/33cn/plugin/plugin/dapp/blackwhite/types" + "github.com/33cn/chain33/client" ) const ( @@ -41,6 +42,7 @@ type action struct { height int64 index int32 execaddr string + api client.QueueProtocolAPI } type resultCalc struct { @@ -59,7 +61,7 @@ func newAction(t *Blackwhite, tx *types.Transaction, index int32) *action { hash := tx.Hash() fromaddr := tx.From() return &action{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr, - t.GetBlockTime(), t.GetHeight(), index, dapp.ExecAddress(string(tx.Execer))} + t.GetBlockTime(), t.GetHeight(), index, dapp.ExecAddress(string(tx.Execer)), t.GetAPI()} } func (a *action) Create(create *gt.BlackwhiteCreate) (*types.Receipt, error) { @@ -180,7 +182,8 @@ func (a *action) Play(play *gt.BlackwhitePlay) (*types.Receipt, error) { key1 := calcMavlRoundKey(round.GameID) value1 := types.Encode(&round) - if types.IsDappFork(a.height, gt.BlackwhiteX, "ForkBlackWhiteV2") { + cfg := a.api.GetConfig() + if cfg.IsDappFork(a.height, gt.BlackwhiteX, "ForkBlackWhiteV2") { //将当前游戏状态保存,便于同一区块中游戏参数的累加 a.db.Set(key1, value1) } @@ -264,7 +267,8 @@ func (a *action) Show(show *gt.BlackwhiteShow) (*types.Receipt, error) { key1 := calcMavlRoundKey(round.GameID) value1 := types.Encode(&round) - if types.IsDappFork(a.height, gt.BlackwhiteX, "ForkBlackWhiteV2") { + cfg := a.api.GetConfig() + if cfg.IsDappFork(a.height, gt.BlackwhiteX, "ForkBlackWhiteV2") { //将当前游戏状态保存,便于同一区块中游戏参数的累加 a.db.Set(key1, value1) } @@ -360,7 +364,8 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er key1 := calcMavlRoundKey(round.GameID) value1 := types.Encode(&round) - if types.IsDappFork(a.height, gt.BlackwhiteX, "ForkBlackWhiteV2") { + cfg := a.api.GetConfig() + if cfg.IsDappFork(a.height, gt.BlackwhiteX, "ForkBlackWhiteV2") { //将当前游戏状态保存,便于同一区块中游戏参数的累加 a.db.Set(key1, value1) } @@ -528,12 +533,13 @@ func (a *action) getWinner(round *gt.BlackwhiteRound) ([]*addrResult, *gt.ReplyL addrRes := round.AddrResult loop := int(round.Loop) + cfg := a.api.GetConfig() for _, address := range addrRes { if len(address.ShowSecret) > 0 && len(address.HashValues) == loop { var isBlack []bool // 加入分叉高度判断:分叉高度在ForkV25BlackWhite到ForkV25BlackWhiteV2之间的执行原来逻辑,大于ForkV25BlackWhiteV2执行新逻辑, // 小于ForkV25BlackWhite则无法进入 - if !types.IsDappFork(a.height, gt.BlackwhiteX, "ForkBlackWhiteV2") { + if !cfg.IsDappFork(a.height, gt.BlackwhiteX, "ForkBlackWhiteV2") { for _, hash := range address.HashValues { if bytes.Equal(common.Sha256([]byte(address.ShowSecret+black)), hash) { isBlack = append(isBlack, true) diff --git a/plugin/dapp/blackwhite/rpc/rpc.go b/plugin/dapp/blackwhite/rpc/rpc.go index 6336ed0c22c08364db18b5aa3713caa11e22d205..ecaa893379711c08f8a59dd7460b62ba7cd21e09 100644 --- a/plugin/dapp/blackwhite/rpc/rpc.go +++ b/plugin/dapp/blackwhite/rpc/rpc.go @@ -19,7 +19,8 @@ func (c *channelClient) Create(ctx context.Context, head *bw.BlackwhiteCreate) ( tx := &types.Transaction{ Payload: types.Encode(val), } - data, err := types.FormatTxEncode(types.ExecName(string(bw.ExecerBlackwhite)), tx) + cfg := c.GetConfig() + data, err := types.FormatTxEncode(cfg, cfg.ExecName(string(bw.ExecerBlackwhite)), tx) if err != nil { return nil, err } @@ -34,7 +35,8 @@ func (c *channelClient) Show(ctx context.Context, head *bw.BlackwhiteShow) (*typ tx := &types.Transaction{ Payload: types.Encode(val), } - data, err := types.FormatTxEncode(types.ExecName(string(bw.ExecerBlackwhite)), tx) + cfg := c.GetConfig() + data, err := types.FormatTxEncode(cfg, cfg.ExecName(string(bw.ExecerBlackwhite)), tx) if err != nil { return nil, err } @@ -49,7 +51,8 @@ func (c *channelClient) Play(ctx context.Context, head *bw.BlackwhitePlay) (*typ tx := &types.Transaction{ Payload: types.Encode(val), } - data, err := types.FormatTxEncode(types.ExecName(string(bw.ExecerBlackwhite)), tx) + cfg := c.GetConfig() + data, err := types.FormatTxEncode(cfg, cfg.ExecName(string(bw.ExecerBlackwhite)), tx) if err != nil { return nil, err } @@ -64,7 +67,8 @@ func (c *channelClient) TimeoutDone(ctx context.Context, head *bw.BlackwhiteTime tx := &types.Transaction{ Payload: types.Encode(val), } - data, err := types.FormatTxEncode(types.ExecName(string(bw.ExecerBlackwhite)), tx) + cfg := c.GetConfig() + data, err := types.FormatTxEncode(cfg, cfg.ExecName(string(bw.ExecerBlackwhite)), tx) if err != nil { return nil, err } diff --git a/plugin/dapp/echo/types/echo/echo.go b/plugin/dapp/echo/types/echo/echo.go index e261516aa3d3200e198996ccee5af2c73684add7..5caef81039103f8e406700dd3b45156bda766366 100644 --- a/plugin/dapp/echo/types/echo/echo.go +++ b/plugin/dapp/echo/types/echo/echo.go @@ -14,6 +14,7 @@ import ( func (e *Type) CreateTx(action string, message json.RawMessage) (*types.Transaction, error) { elog.Debug("echo.CreateTx", "action", action) // 只接受ping/pang两种交易操作 + cfg := e.GetConfig() if action == "ping" || action == "pang" { var param Tx err := json.Unmarshal(message, ¶m) @@ -21,12 +22,12 @@ func (e *Type) CreateTx(action string, message json.RawMessage) (*types.Transact elog.Error("CreateTx", "Error", err) return nil, types.ErrInvalidParam } - return createPingTx(action, ¶m) + return createPingTx(cfg, action, ¶m) } return nil, types.ErrNotSupport } -func createPingTx(op string, parm *Tx) (*types.Transaction, error) { +func createPingTx(cfg *types.Chain33Config, op string, parm *Tx) (*types.Transaction, error) { var action *EchoAction var err error if strings.EqualFold(op, "ping") { @@ -38,10 +39,10 @@ func createPingTx(op string, parm *Tx) (*types.Transaction, error) { return nil, err } tx := &types.Transaction{ - Execer: []byte(types.ExecName(EchoX)), + Execer: []byte(cfg.ExecName(EchoX)), Payload: types.Encode(action), Nonce: rand.New(rand.NewSource(time.Now().UnixNano())).Int63(), - To: address.ExecAddress(types.ExecName(EchoX)), + To: address.ExecAddress(cfg.ExecName(EchoX)), } return tx, nil } diff --git a/plugin/dapp/evm/executor/evm.go b/plugin/dapp/evm/executor/evm.go index 09835a3e2599f6fb46379993887bc989f0de8d1e..d043d1847f1b3a288856a2ce569b6d5b242d9404 100644 --- a/plugin/dapp/evm/executor/evm.go +++ b/plugin/dapp/evm/executor/evm.go @@ -25,7 +25,7 @@ var ( evmDebug = false // EvmAddress 本合约地址 - EvmAddress = address.ExecAddress(types.ExecName(evmtypes.ExecutorName)) + EvmAddress = address.ExecAddress(evmtypes.ExecutorName) ) var driverName = evmtypes.ExecutorName @@ -137,7 +137,8 @@ func (evm *EVMExecutor) CheckReceiptExecOk() bool { // 生成一个新的合约对象地址 func (evm *EVMExecutor) getNewAddr(txHash []byte) common.Address { - return common.NewAddress(txHash) + cfg := evm.GetAPI().GetConfig() + return common.NewAddress(cfg, txHash) } // CheckTx 校验交易 diff --git a/plugin/dapp/evm/executor/exec.go b/plugin/dapp/evm/executor/exec.go index fde1f202c052c4de6c8de923491c79eaf1245822..f145a13157908fdfce0285c202915be38e2c545a 100644 --- a/plugin/dapp/evm/executor/exec.go +++ b/plugin/dapp/evm/executor/exec.go @@ -48,6 +48,7 @@ func (evm *EVMExecutor) innerExec(msg *common.Message, txHash []byte, index int, execName string methodName string ) + cfg := evm.GetAPI().GetConfig() // 为了方便计费,即使合约为新生成,也将地址的初始化放到外面操作 if isCreate { @@ -57,7 +58,7 @@ func (evm *EVMExecutor) innerExec(msg *common.Message, txHash []byte, index int, return receipt, model.ErrContractAddressCollision } // 只有新创建的合约才能生成合约名称 - execName = fmt.Sprintf("%s%s", types.ExecName(evmtypes.EvmPrefix), common.BytesToHash(txHash).Hex()) + execName = fmt.Sprintf("%s%s", cfg.ExecName(evmtypes.EvmPrefix), common.BytesToHash(txHash).Hex()) } else { contractAddr = *msg.To() } @@ -67,17 +68,17 @@ func (evm *EVMExecutor) innerExec(msg *common.Message, txHash []byte, index int, if isCreate { // 如果携带ABI数据,则对数据合法性进行检查 - if len(msg.ABI()) > 0 && types.IsDappFork(evm.GetHeight(), "evm", evmtypes.ForkEVMABI) { + if len(msg.ABI()) > 0 && cfg.IsDappFork(evm.GetHeight(), "evm", evmtypes.ForkEVMABI) { _, err = abi.JSON(strings.NewReader(msg.ABI())) if err != nil { return receipt, err } } - ret, snapshot, leftOverGas, vmerr = env.Create(runtime.AccountRef(msg.From()), contractAddr, msg.Data(), context.GasLimit, execName, msg.Alias(), msg.ABI()) + ret, snapshot, leftOverGas, vmerr = env.Create(cfg, runtime.AccountRef(msg.From()), contractAddr, msg.Data(), context.GasLimit, execName, msg.Alias(), msg.ABI()) } else { inData := msg.Data() // 在这里进行ABI和十六进制的调用参数转换 - if len(msg.ABI()) > 0 && types.IsDappFork(evm.GetHeight(), "evm", evmtypes.ForkEVMABI) { + if len(msg.ABI()) > 0 && cfg.IsDappFork(evm.GetHeight(), "evm", evmtypes.ForkEVMABI) { funcName, packData, err := abi.Pack(msg.ABI(), evm.mStateDB.GetAbi(msg.To().String()), readOnly) if err != nil { return receipt, err @@ -85,7 +86,7 @@ func (evm *EVMExecutor) innerExec(msg *common.Message, txHash []byte, index int, inData = packData methodName = funcName } - ret, snapshot, leftOverGas, vmerr = env.Call(runtime.AccountRef(msg.From()), *msg.To(), inData, context.GasLimit, msg.Value()) + ret, snapshot, leftOverGas, vmerr = env.Call(cfg, runtime.AccountRef(msg.From()), *msg.To(), inData, context.GasLimit, msg.Value()) } log.Debug("call(create) contract ", "input", common.Bytes2Hex(msg.Data())) @@ -126,7 +127,7 @@ func (evm *EVMExecutor) innerExec(msg *common.Message, txHash []byte, index int, kvSet, logs := evm.mStateDB.GetChangedData(curVer.GetID()) contractReceipt := &evmtypes.ReceiptEVMContract{Caller: msg.From().String(), ContractName: execName, ContractAddr: contractAddr.String(), UsedGas: usedGas, Ret: ret} // 这里进行ABI调用结果格式化 - if len(methodName) > 0 && len(msg.ABI()) > 0 && types.IsDappFork(evm.GetHeight(), "evm", evmtypes.ForkEVMABI) { + if len(methodName) > 0 && len(msg.ABI()) > 0 && cfg.IsDappFork(evm.GetHeight(), "evm", evmtypes.ForkEVMABI) { jsonRet, err := abi.Unpack(ret, methodName, evm.mStateDB.GetAbi(msg.To().String())) if err != nil { // 这里出错不影响整体执行,只打印错误信息 @@ -137,7 +138,7 @@ func (evm *EVMExecutor) innerExec(msg *common.Message, txHash []byte, index int, logs = append(logs, &types.ReceiptLog{Ty: evmtypes.TyLogCallContract, Log: types.Encode(contractReceipt)}) logs = append(logs, evm.mStateDB.GetReceiptLogs(contractAddr.String())...) - if types.IsDappFork(evm.GetHeight(), "evm", evmtypes.ForkEVMKVHash) { + if cfg.IsDappFork(evm.GetHeight(), "evm", evmtypes.ForkEVMKVHash) { // 将执行时生成的合约状态数据变更信息也计算哈希并保存 hashKV := evm.calcKVHash(contractAddr, logs) if hashKV != nil { @@ -153,7 +154,7 @@ func (evm *EVMExecutor) innerExec(msg *common.Message, txHash []byte, index int, } // 替换导致分叉的执行数据信息 - state.ProcessFork(evm.GetHeight(), txHash, receipt) + state.ProcessFork(cfg, evm.GetHeight(), txHash, receipt) evm.collectEvmTxLog(txHash, contractReceipt, receipt) @@ -163,7 +164,7 @@ func (evm *EVMExecutor) innerExec(msg *common.Message, txHash []byte, index int, // CheckInit 检查是否初始化数据库 func (evm *EVMExecutor) CheckInit() { if evm.mStateDB == nil { - evm.mStateDB = state.NewMemoryStateDB(evm.GetStateDB(), evm.GetLocalDB(), evm.GetCoinsAccount(), evm.GetHeight()) + evm.mStateDB = state.NewMemoryStateDB(evm.GetStateDB(), evm.GetLocalDB(), evm.GetCoinsAccount(), evm.GetHeight(), evm.GetAPI()) } } diff --git a/plugin/dapp/evm/executor/vm/common/address.go b/plugin/dapp/evm/executor/vm/common/address.go index d7932b070081cf1fec0d19259da0491e54a5abe4..571a7b55bbc76ffa460e6fb0a59213b38778ab0f 100644 --- a/plugin/dapp/evm/executor/vm/common/address.go +++ b/plugin/dapp/evm/executor/vm/common/address.go @@ -91,8 +91,8 @@ func (h Hash160Address) ToAddress() Address { } // NewAddress xHash生成EVM合约地址 -func NewAddress(txHash []byte) Address { - execAddr := address.GetExecAddress(types.ExecName("user.evm.") + BytesToHash(txHash).Hex()) +func NewAddress(cfg *types.Chain33Config, txHash []byte) Address { + execAddr := address.GetExecAddress(cfg.ExecName("user.evm.") + BytesToHash(txHash).Hex()) return Address{addr: execAddr} } diff --git a/plugin/dapp/evm/executor/vm/runtime/evm.go b/plugin/dapp/evm/executor/vm/runtime/evm.go index 0a638569c056f021c260be04722fc1a8abe4ecfe..d0ac6d969759036e68b641b4e920703b33f6d3f0 100644 --- a/plugin/dapp/evm/executor/vm/runtime/evm.go +++ b/plugin/dapp/evm/executor/vm/runtime/evm.go @@ -169,7 +169,7 @@ func (evm *EVM) preCheck(caller ContractRef, recipient common.Address, value uin // Call 此方法提供合约外部调用入口 // 根据合约地址调用已经存在的合约,input为合约调用参数 // 合约调用逻辑支持在合约调用的同时进行向合约转账的操作 -func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value uint64) (ret []byte, snapshot int, leftOverGas uint64, err error) { +func (evm *EVM) Call(cfg *types.Chain33Config, caller ContractRef, addr common.Address, input []byte, gas uint64, value uint64) (ret []byte, snapshot int, leftOverGas uint64, err error) { pass, err := evm.preCheck(caller, addr, value) if !pass { return nil, -1, gas, err @@ -223,7 +223,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas } // 从ForkV20EVMState开始,状态数据存储发生变更,需要做数据迁移 - if types.IsDappFork(evm.BlockNumber.Int64(), "evm", evmtypes.ForkEVMState) { + if cfg.IsDappFork(evm.BlockNumber.Int64(), "evm", evmtypes.ForkEVMState) { evm.StateDB.TransferStateData(addr.String()) } @@ -357,7 +357,7 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte // 使用传入的部署代码创建新的合约; // 目前chain33为了保证账户安全,不允许合约中涉及到外部账户的转账操作, // 所以,本步骤不接收转账金额参数 -func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []byte, gas uint64, execName, alias, abi string) (ret []byte, snapshot int, leftOverGas uint64, err error) { +func (evm *EVM) Create(cfg *types.Chain33Config, caller ContractRef, contractAddr common.Address, code []byte, gas uint64, execName, alias, abi string) (ret []byte, snapshot int, leftOverGas uint64, err error) { pass, err := evm.preCheck(caller, contractAddr, 0) if !pass { return nil, -1, gas, err @@ -388,7 +388,7 @@ func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []b if contract.UseGas(createDataGas) { evm.StateDB.SetCode(contractAddr.String(), ret) // 设置 ABI (如果有的话),这个动作不单独计费 - if len(abi) > 0 && types.IsDappFork(evm.StateDB.GetBlockHeight(), "evm", evmtypes.ForkEVMABI) { + if len(abi) > 0 && cfg.IsDappFork(evm.StateDB.GetBlockHeight(), "evm", evmtypes.ForkEVMABI) { evm.StateDB.SetAbi(contractAddr.String(), abi) } } else { diff --git a/plugin/dapp/evm/executor/vm/state/account.go b/plugin/dapp/evm/executor/vm/state/account.go index 4ff9ea90f380dfebe143bdc2c710865426b24092..e8daba1c7d9791d378a9ced9a6646855dfea31db 100644 --- a/plugin/dapp/evm/executor/vm/state/account.go +++ b/plugin/dapp/evm/executor/vm/state/account.go @@ -50,7 +50,8 @@ func NewContractAccount(addr string, db *MemoryStateDB) *ContractAccount { // 获取数据分为两层,一层是从当前的缓存中获取,如果获取不到,再从localdb中获取 func (ca *ContractAccount) GetState(key common.Hash) common.Hash { // 从ForkV19开始,状态数据使用单独的KEY存储 - if types.IsDappFork(ca.mdb.blockHeight, "evm", evmtypes.ForkEVMState) { + cfg := ca.mdb.api.GetConfig() + if cfg.IsDappFork(ca.mdb.blockHeight, "evm", evmtypes.ForkEVMState) { if val, ok := ca.stateCache[key.Hex()]; ok { return val } @@ -76,7 +77,8 @@ func (ca *ContractAccount) SetState(key, value common.Hash) { key: key, prevalue: ca.GetState(key), }) - if types.IsDappFork(ca.mdb.blockHeight, "evm", evmtypes.ForkEVMState) { + cfg := ca.mdb.api.GetConfig() + if cfg.IsDappFork(ca.mdb.blockHeight, "evm", evmtypes.ForkEVMState) { ca.stateCache[key.Hex()] = value //需要设置到localdb中,以免同一个区块中同一个合约多次调用时,状态数据丢失 keyStr := getStateItemKey(ca.Addr, key.Hex()) @@ -107,7 +109,8 @@ func (ca *ContractAccount) TransferState() { func (ca *ContractAccount) updateStorageHash() { // 从ForkV20开始,状态数据使用单独KEY存储 - if types.IsDappFork(ca.mdb.blockHeight, "evm", evmtypes.ForkEVMState) { + cfg := ca.mdb.api.GetConfig() + if cfg.IsDappFork(ca.mdb.blockHeight, "evm", evmtypes.ForkEVMState) { return } var state = &evmtypes.EVMContractState{Suicided: ca.State.Suicided, Nonce: ca.State.Nonce} @@ -183,7 +186,8 @@ func (ca *ContractAccount) SetCode(code []byte) { // SetAbi 设置合约绑定的ABI数据 func (ca *ContractAccount) SetAbi(abi string) { - if types.IsDappFork(ca.mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMABI) { + cfg := ca.mdb.api.GetConfig() + if cfg.IsDappFork(ca.mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMABI) { ca.mdb.addChange(abiChange{ baseChange: baseChange{}, account: ca.Addr, diff --git a/plugin/dapp/evm/executor/vm/state/fork.go b/plugin/dapp/evm/executor/vm/state/fork.go index 39eca2f1f82809e270619f875fa0067a9d6efcf7..9c54f2f75cb78bc64d15d0ed5c3ae2c06874d6b0 100644 --- a/plugin/dapp/evm/executor/vm/state/fork.go +++ b/plugin/dapp/evm/executor/vm/state/fork.go @@ -75,13 +75,13 @@ func InitForkData() { } // ProcessFork 处理硬分叉逻辑 -func ProcessFork(blockHeight int64, txHash []byte, receipt *types.Receipt) { - if types.IsLocal() { +func ProcessFork(cfg *types.Chain33Config, blockHeight int64, txHash []byte, receipt *types.Receipt) { + if cfg.IsLocal() { return } // 目前的分叉信息只在测试网中存在 - if !types.IsTestNet() { + if !cfg.IsTestNet() { return } diff --git a/plugin/dapp/evm/executor/vm/state/snapshot.go b/plugin/dapp/evm/executor/vm/state/snapshot.go index 10b23c6b28944ef6e0ec29e04c5e8dabc053c252..ae525bc3f15ab2434019ec1a24589bbcf1fb3468 100644 --- a/plugin/dapp/evm/executor/vm/state/snapshot.go +++ b/plugin/dapp/evm/executor/vm/state/snapshot.go @@ -275,7 +275,8 @@ func (ch storageChange) getData(mdb *MemoryStateDB) []*types.KeyValue { } func (ch storageChange) getLog(mdb *MemoryStateDB) []*types.ReceiptLog { - if types.IsDappFork(mdb.blockHeight, "evm", evmtypes.ForkEVMState) { + cfg := mdb.api.GetConfig() + if cfg.IsDappFork(mdb.blockHeight, "evm", evmtypes.ForkEVMState) { acc := mdb.accounts[ch.account] if acc != nil { currentVal := acc.GetState(ch.key) diff --git a/plugin/dapp/evm/executor/vm/state/statedb.go b/plugin/dapp/evm/executor/vm/state/statedb.go index 05bce34068b560e367245c7b5dc6fafe6dc273a3..0a5d2260bd1ec11ecd974a50beace45a96a1b586 100644 --- a/plugin/dapp/evm/executor/vm/state/statedb.go +++ b/plugin/dapp/evm/executor/vm/state/statedb.go @@ -15,6 +15,7 @@ import ( "github.com/33cn/plugin/plugin/dapp/evm/executor/vm/common" "github.com/33cn/plugin/plugin/dapp/evm/executor/vm/model" evmtypes "github.com/33cn/plugin/plugin/dapp/evm/types" + "github.com/33cn/chain33/client" ) // MemoryStateDB 内存状态数据库,保存在区块操作时内部的数据变更操作 @@ -61,12 +62,13 @@ type MemoryStateDB struct { // 用户保存合约账户的状态数据或合约代码数据有没有发生变更 stateDirty map[string]interface{} dataDirty map[string]interface{} + api client.QueueProtocolAPI } // NewMemoryStateDB 基于执行器框架的三个DB构建内存状态机对象 // 此对象的生命周期对应一个区块,在同一个区块内的多个交易执行时共享同一个DB对象 // 开始执行下一个区块时(执行器框架调用setEnv设置的区块高度发生变更时),会重新创建此DB对象 -func NewMemoryStateDB(StateDB db.KV, LocalDB db.KVDB, CoinsAccount *account.DB, blockHeight int64) *MemoryStateDB { +func NewMemoryStateDB(StateDB db.KV, LocalDB db.KVDB, CoinsAccount *account.DB, blockHeight int64, api client.QueueProtocolAPI) *MemoryStateDB { mdb := &MemoryStateDB{ StateDB: StateDB, LocalDB: LocalDB, @@ -79,6 +81,7 @@ func NewMemoryStateDB(StateDB db.KV, LocalDB db.KVDB, CoinsAccount *account.DB, blockHeight: blockHeight, refund: 0, txIndex: 0, + api: api, } return mdb } @@ -131,7 +134,8 @@ func (mdb *MemoryStateDB) GetBalance(addr string) uint64 { isExec := mdb.Exist(addr) var ac *types.Account if isExec { - if types.IsDappFork(mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMFrozen) { + cfg := mdb.api.GetConfig() + if cfg.IsDappFork(mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMFrozen) { ac = mdb.CoinsAccount.LoadExecAccount(addr, addr) } else { contract := mdb.GetAccount(addr) @@ -268,7 +272,8 @@ func (mdb *MemoryStateDB) SetState(addr string, key common.Hash, value common.Ha if acc != nil { acc.SetState(key, value) // 新的分叉中状态数据变更不需要单独进行标识 - if !types.IsDappFork(mdb.blockHeight, "evm", evmtypes.ForkEVMState) { + cfg := mdb.api.GetConfig() + if !cfg.IsDappFork(mdb.blockHeight, "evm", evmtypes.ForkEVMState) { mdb.stateDirty[addr] = true } } @@ -481,7 +486,8 @@ func (mdb *MemoryStateDB) checkExecAccount(execAddr string, value int64) bool { } var accFrom *types.Account - if types.IsDappFork(mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMFrozen) { + cfg := mdb.api.GetConfig() + if cfg.IsDappFork(mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMFrozen) { // 分叉后,需要检查合约地址下的金额是否足够 accFrom = mdb.CoinsAccount.LoadExecAccount(execAddr, execAddr) } else { @@ -613,7 +619,8 @@ func (mdb *MemoryStateDB) transfer2Contract(sender, recipient string, amount int ret = &types.Receipt{} - if types.IsDappFork(mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMFrozen) { + cfg := mdb.api.GetConfig() + if cfg.IsDappFork(mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMFrozen) { // 用户向合约转账时,将钱转到合约地址下execAddr:execAddr rs, err := mdb.CoinsAccount.ExecTransfer(sender, execAddr, execAddr, amount) if err != nil { @@ -653,7 +660,8 @@ func (mdb *MemoryStateDB) transfer2External(sender, recipient string, amount int execAddr := sender - if types.IsDappFork(mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMFrozen) { + cfg := mdb.api.GetConfig() + if cfg.IsDappFork(mdb.GetBlockHeight(), "evm", evmtypes.ForkEVMFrozen) { // 合约向用户地址转账时,从合约地址下的钱中转出到用户合约地址 ret, err = mdb.CoinsAccount.ExecTransfer(execAddr, recipient, execAddr, amount) if err != nil { diff --git a/plugin/dapp/evm/rpc/rpc.go b/plugin/dapp/evm/rpc/rpc.go index 5dc3d0da1d3cb71d4c0452af0e62add5296d6ea9..3c73922fdd7b6255c4e90238b631e5fd91b53ca5 100644 --- a/plugin/dapp/evm/rpc/rpc.go +++ b/plugin/dapp/evm/rpc/rpc.go @@ -28,11 +28,12 @@ func (c *channelClient) Create(ctx context.Context, in evmtypes.EvmContractCreat action := evmtypes.EVMContractAction{Amount: 0, Code: bCode, GasLimit: 0, GasPrice: 0, Note: in.Note, Abi: in.Abi} - execer := types.ExecName(in.ParaName + "evm") - addr := address.ExecAddress(types.ExecName(in.ParaName + "evm")) + cfg := c.GetConfig() + execer := cfg.ExecName(in.ParaName + "evm") + addr := address.ExecAddress(cfg.ExecName(in.ParaName + "evm")) tx := &types.Transaction{Execer: []byte(execer), Payload: types.Encode(&action), Fee: 0, To: addr} - tx.Fee, _ = tx.GetRealFee(types.GInt("MinFee")) + tx.Fee, _ = tx.GetRealFee(cfg.GInt("MinFee")) if tx.Fee < in.Fee { tx.Fee += in.Fee } @@ -60,7 +61,8 @@ func (c *channelClient) Call(ctx context.Context, in evmtypes.EvmContractCallReq tx := &types.Transaction{Execer: []byte(in.Exec), Payload: types.Encode(&action), Fee: 0, To: toAddr} - tx.Fee, _ = tx.GetRealFee(types.GInt("MinFee")) + cfg := c.GetConfig() + tx.Fee, _ = tx.GetRealFee(cfg.GInt("MinFee")) if tx.Fee < feeInt64 { tx.Fee += feeInt64 } @@ -86,14 +88,15 @@ func (c *channelClient) Transfer(ctx context.Context, in evmtypes.EvmContractTra transfer.Value = &cty.CoinsAction_TransferToExec{TransferToExec: &types.AssetsTransferToExec{Amount: amountInt64, ExecName: execName, To: address.ExecAddress(execName)}} transfer.Ty = cty.CoinsActionTransferToExec } + cfg := c.GetConfig() if in.ParaName == "" { - tx = &types.Transaction{Execer: []byte(types.ExecName(in.ParaName + "coins")), Payload: types.Encode(transfer), To: address.ExecAddress(execName)} + tx = &types.Transaction{Execer: []byte(cfg.ExecName(in.ParaName + "coins")), Payload: types.Encode(transfer), To: address.ExecAddress(execName)} } else { - tx = &types.Transaction{Execer: []byte(types.ExecName(in.ParaName + "coins")), Payload: types.Encode(transfer), To: address.ExecAddress(types.ExecName(in.ParaName + "coins"))} + tx = &types.Transaction{Execer: []byte(cfg.ExecName(in.ParaName + "coins")), Payload: types.Encode(transfer), To: address.ExecAddress(cfg.ExecName(in.ParaName + "coins"))} } var err error - tx.Fee, err = tx.GetRealFee(types.GInt("MinFee")) + tx.Fee, err = tx.GetRealFee(cfg.GInt("MinFee")) if err != nil { return nil, err } diff --git a/plugin/dapp/game/executor/gamedb.go b/plugin/dapp/game/executor/gamedb.go index 075792028d0e59d7fe645c5a63665ce42ea74480..d69faf98d694e458a1da7da89ab5a37a15bb5fe8 100644 --- a/plugin/dapp/game/executor/gamedb.go +++ b/plugin/dapp/game/executor/gamedb.go @@ -17,6 +17,7 @@ import ( "github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/types" gt "github.com/33cn/plugin/plugin/dapp/game/types" + "github.com/33cn/chain33/client" ) const ( @@ -166,6 +167,7 @@ type Action struct { execaddr string localDB dbm.Lister index int + api client.QueueProtocolAPI } // NewAction new action @@ -173,7 +175,7 @@ func NewAction(g *Game, tx *types.Transaction, index int) *Action { hash := tx.Hash() fromaddr := tx.From() return &Action{g.GetCoinsAccount(), g.GetStateDB(), hash, fromaddr, - g.GetBlockTime(), g.GetHeight(), dapp.ExecAddress(string(tx.Execer)), g.GetLocalDB(), index} + g.GetBlockTime(), g.GetHeight(), dapp.ExecAddress(string(tx.Execer)), g.GetLocalDB(), index, g.GetAPI()} } func (action *Action) checkExecAccountBalance(fromAddr string, ToFrozen, ToActive int64) bool { @@ -189,12 +191,13 @@ func (action *Action) GameCreate(create *gt.GameCreate) (*types.Receipt, error) gameID := common.ToHex(action.txhash) var logs []*types.ReceiptLog var kv []*types.KeyValue - maxGameAmount := getConfValue(action.db, ConfNameMaxGameAmount, MaxGameAmount) + cfg := action.api.GetConfig() + maxGameAmount := getConfValue(cfg, action.db, ConfNameMaxGameAmount, MaxGameAmount) if create.GetValue() > maxGameAmount*types.Coin { glog.Error("Create the game, the deposit is too big ", "value", create.GetValue(), "err", gt.ErrGameCreateAmount.Error()) return nil, gt.ErrGameCreateAmount } - minGameAmount := getConfValue(action.db, ConfNameMinGameAmount, MinGameAmount) + minGameAmount := getConfValue(cfg, action.db, ConfNameMinGameAmount, MinGameAmount) if create.GetValue() < minGameAmount*types.Coin || math.Remainder(float64(create.GetValue()), 2) != 0 { return nil, fmt.Errorf("%s", "The amount you participate in cannot be less than 2 and must be an even number!") } @@ -486,7 +489,8 @@ func (action *Action) GameClose(close *gt.GameClose) (*types.Receipt, error) { // 检查开奖是否超时,若超过一天,则不让庄家开奖,但其他人可以开奖, // 若没有一天,则其他人没有开奖权限,只有庄家有开奖权限 func (action *Action) checkGameIsTimeOut(game *gt.Game) bool { - activeTime := getConfValue(action.db, ConfNameActiveTime, ActiveTime) + cfg := action.api.GetConfig() + activeTime := getConfValue(cfg, action.db, ConfNameActiveTime, ActiveTime) DurTime := 60 * 60 * activeTime return action.blocktime > (game.GetMatchTime() + DurTime) } @@ -551,26 +555,26 @@ func (action *Action) readGame(id string) (*gt.Game, error) { } // List query game list -func List(db dbm.Lister, stateDB dbm.KV, param *gt.QueryGameListByStatusAndAddr) (types.Message, error) { - return QueryGameListByPage(db, stateDB, param) +func List(cfg *types.Chain33Config, db dbm.Lister, stateDB dbm.KV, param *gt.QueryGameListByStatusAndAddr) (types.Message, error) { + return QueryGameListByPage(cfg, db, stateDB, param) } // QueryGameListByPage 分页查询 -func QueryGameListByPage(db dbm.Lister, stateDB dbm.KV, param *gt.QueryGameListByStatusAndAddr) (types.Message, error) { +func QueryGameListByPage(cfg *types.Chain33Config, db dbm.Lister, stateDB dbm.KV, param *gt.QueryGameListByStatusAndAddr) (types.Message, error) { switch param.GetStatus() { case gt.GameActionCreate, gt.GameActionMatch, gt.GameActionClose, gt.GameActionCancel: - return queryGameListByStatusAndAddr(db, stateDB, param) + return queryGameListByStatusAndAddr(cfg, db, stateDB, param) } return nil, fmt.Errorf("%s", "the status only fill in 1,2,3,4!") } -func queryGameListByStatusAndAddr(db dbm.Lister, stateDB dbm.KV, param *gt.QueryGameListByStatusAndAddr) (types.Message, error) { +func queryGameListByStatusAndAddr(cfg *types.Chain33Config, db dbm.Lister, stateDB dbm.KV, param *gt.QueryGameListByStatusAndAddr) (types.Message, error) { direction := ListDESC if param.GetDirection() == ListASC { direction = ListASC } - count := int32(getConfValue(stateDB, ConfNameDefaultCount, DefaultCount)) - maxCount := int32(getConfValue(stateDB, ConfNameMaxCount, MaxCount)) + count := int32(getConfValue(cfg, stateDB, ConfNameDefaultCount, DefaultCount)) + maxCount := int32(getConfValue(cfg, stateDB, ConfNameMaxCount, MaxCount)) if 0 < param.GetCount() && param.GetCount() <= maxCount { count = param.GetCount() } @@ -679,9 +683,9 @@ func GetGameList(db dbm.KV, values []string) []*gt.Game { } return games } -func getConfValue(db dbm.KV, key string, defaultValue int64) int64 { +func getConfValue(cfg *types.Chain33Config, db dbm.KV, key string, defaultValue int64) int64 { var item types.ConfigItem - value, err := getManageKey(key, db) + value, err := getManageKey(cfg, key, db) if err != nil { return defaultValue } @@ -705,11 +709,11 @@ func getConfValue(db dbm.KV, key string, defaultValue int64) int64 { } return v } -func getManageKey(key string, db dbm.KV) ([]byte, error) { +func getManageKey(cfg *types.Chain33Config, key string, db dbm.KV) ([]byte, error) { manageKey := types.ManageKey(key) value, err := db.Get([]byte(manageKey)) if err != nil { - if types.IsPara() { //平行链只有一种存储方式 + if cfg.IsPara() { //平行链只有一种存储方式 glog.Error("gamedb getManage", "can't get value from db,key:", key, "err", err.Error()) return nil, err } diff --git a/plugin/dapp/game/executor/query.go b/plugin/dapp/game/executor/query.go index a10515f1717d36ccabc8395557963718c13cb480..b9ab68bc837d04183208bc6c72360b0db2dfbdac 100644 --- a/plugin/dapp/game/executor/query.go +++ b/plugin/dapp/game/executor/query.go @@ -21,7 +21,8 @@ func (g *Game) Query_QueryGameListCount(in *gt.QueryGameListCount) (types.Messag // Query_QueryGameListByStatusAndAddr query game list by status and addr func (g *Game) Query_QueryGameListByStatusAndAddr(in *gt.QueryGameListByStatusAndAddr) (types.Message, error) { - return List(g.GetLocalDB(), g.GetStateDB(), in) + cfg := g.GetAPI().GetConfig() + return List(cfg, g.GetLocalDB(), g.GetStateDB(), in) } // Query_QueryGameById query game by gameID diff --git a/plugin/dapp/guess/executor/guess.go b/plugin/dapp/guess/executor/guess.go index 71465b2e4099403f122bd240da370f0d7bdd743f..a47dd1da7b0c9c3305f660f7628401ffb18ab9c4 100644 --- a/plugin/dapp/guess/executor/guess.go +++ b/plugin/dapp/guess/executor/guess.go @@ -15,19 +15,20 @@ var logger = log.New("module", "execs.guess") var driverName = gty.GuessX -func init() { - ety := types.LoadExecutorType(driverName) - ety.InitFuncList(types.ListMethod(&Guess{})) -} - // Init Guess -func Init(name string, sub []byte) { +func Init(name string, cfg *types.Chain33Config, sub []byte) { driverName := GetName() if name != driverName { panic("system dapp can't be rename") } - drivers.Register(driverName, newGuessGame, types.GetDappFork(driverName, "Enable")) + drivers.Register(cfg, driverName, newGuessGame, cfg.GetDappFork(driverName, "Enable")) + InitExecType() +} + +func InitExecType() { + ety := types.LoadExecutorType(driverName) + ety.InitFuncList(types.ListMethod(&Guess{})) } //Guess 执行器,用于竞猜合约的具体执行 diff --git a/plugin/dapp/guess/types/types.go b/plugin/dapp/guess/types/types.go index 15ff47c0a281cec4318baf7f59d5f4a3ebf5641d..1bf18e3620bf8af2f1e9c0ec24b7d69ba370ca1a 100644 --- a/plugin/dapp/guess/types/types.go +++ b/plugin/dapp/guess/types/types.go @@ -12,9 +12,17 @@ import ( func init() { // init executor type - types.RegistorExecutor(GuessX, NewType()) types.AllowUserExec = append(types.AllowUserExec, ExecerGuess) - types.RegisterDappFork(GuessX, "Enable", 0) + types.RegFork(GuessX, InitFork) + types.RegExec(GuessX, InitExecutor) +} + +func InitFork(cfg *types.Chain33Config) { + cfg.RegisterDappFork(GuessX, "Enable", 0) +} + +func InitExecutor(cfg *types.Chain33Config) { + types.RegistorExecutor(GuessX, NewType(cfg)) } // GuessType struct @@ -23,9 +31,10 @@ type GuessType struct { } // NewType method -func NewType() *GuessType { +func NewType(cfg *types.Chain33Config) *GuessType { c := &GuessType{} c.SetChild(c) + c.SetConfig(cfg) return c } diff --git a/plugin/dapp/hashlock/executor/hashlockdb.go b/plugin/dapp/hashlock/executor/hashlockdb.go index 141839a6278fef810a1e1412012bdc16640ae5f2..6fdf62756154353ded06a12c495882c598f16a04 100755 --- a/plugin/dapp/hashlock/executor/hashlockdb.go +++ b/plugin/dapp/hashlock/executor/hashlockdb.go @@ -15,6 +15,7 @@ import ( log "github.com/33cn/chain33/common/log/log15" "github.com/33cn/chain33/types" pty "github.com/33cn/plugin/plugin/dapp/hashlock/types" + "github.com/33cn/chain33/client" ) var hlog = log.New("module", "hashlock.db") @@ -75,13 +76,14 @@ type Action struct { blocktime int64 height int64 execaddr string + api client.QueueProtocolAPI } // NewAction gen action instance func NewAction(h *Hashlock, tx *types.Transaction, execaddr string) *Action { hash := tx.Hash() fromaddr := tx.From() - return &Action{h.GetCoinsAccount(), h.GetStateDB(), hash, fromaddr, h.GetBlockTime(), h.GetHeight(), execaddr} + return &Action{h.GetCoinsAccount(), h.GetStateDB(), hash, fromaddr, h.GetBlockTime(), h.GetHeight(), execaddr, h.GetAPI()} } // Hashlocklock Action @@ -91,7 +93,8 @@ func (action *Action) Hashlocklock(hlock *pty.HashlockLock) (*types.Receipt, err var kv []*types.KeyValue var err error //不存在相同的hashlock,假定采用sha256 - if types.IsDappFork(action.height, pty.HashlockX, pty.ForkBadRepeatSecretX) { + cfg := action.api.GetConfig() + if cfg.IsDappFork(action.height, pty.HashlockX, pty.ForkBadRepeatSecretX) { _, err = readHashlock(action.db, hlock.Hash) } else { _, err = readHashlock(action.db, common.Sha256(hlock.Hash)) diff --git a/plugin/dapp/js/executor/exec.go b/plugin/dapp/js/executor/exec.go index d6faa2a1aa0032623a71544f1f10cbfe6eb38d63..9a5c2f46b043b6abf3514cf53ae7a3354ab195b2 100644 --- a/plugin/dapp/js/executor/exec.go +++ b/plugin/dapp/js/executor/exec.go @@ -10,7 +10,8 @@ import ( func (c *js) userExecName(name string, local bool) string { execer := "user." + ptypes.JsX + "." + name if local { - execer = types.ExecName(execer) + cfg := c.GetAPI().GetConfig() + execer = cfg.ExecName(execer) } return execer } @@ -18,7 +19,8 @@ func (c *js) userExecName(name string, local bool) string { // execName 在create 时为 jsvm // 在 call 时为 user.jsvm.game func (c *js) checkTxExec(txExec string, execName string) bool { - return txExec == types.ExecName(execName) + cfg := c.GetAPI().GetConfig() + return txExec == cfg.ExecName(execName) } func (c *js) Exec_Create(payload *jsproto.Create, tx *types.Transaction, index int) (*types.Receipt, error) { diff --git a/plugin/dapp/js/executor/js.go b/plugin/dapp/js/executor/js.go index 72b69da1a372b11031c2aad089ee8a35039a836e..1358f097825616bdab0d0d57678ad9ddd71aebaf 100644 --- a/plugin/dapp/js/executor/js.go +++ b/plugin/dapp/js/executor/js.go @@ -193,7 +193,8 @@ func (u *js) getContext(tx *types.Transaction, index int64) *blockContext { } func (u *js) statedbFunc(vm *otto.Otto, name string) { - prefix, _ := calcAllPrefix(name) + cfg := u.GetAPI().GetConfig() + prefix, _ := calcAllPrefix(cfg, name) vm.Set("getstatedb", func(call otto.FunctionCall) otto.Value { key, err := call.Argument(0).ToString() if err != nil { @@ -215,7 +216,8 @@ func (u *js) statedbFunc(vm *otto.Otto, name string) { } func (u *js) localdbFunc(vm *otto.Otto, name string) { - _, prefix := calcAllPrefix(name) + cfg := u.GetAPI().GetConfig() + _, prefix := calcAllPrefix(cfg, name) vm.Set("getlocaldb", func(call otto.FunctionCall) otto.Value { key, err := call.Argument(0).ToString() if err != nil { @@ -261,7 +263,8 @@ func (u *js) randnumFunc(vm *otto.Otto, name string) { func (u *js) listdbFunc(vm *otto.Otto, name string) { //List(prefix, key []byte, count, direction int32) ([][]byte, error) - _, plocal := calcAllPrefix(name) + cfg := u.GetAPI().GetConfig() + _, plocal := calcAllPrefix(cfg, name) vm.Set("listdb", func(call otto.FunctionCall) otto.Value { prefix, err := call.Argument(0).ToString() if err != nil { diff --git a/plugin/dapp/js/executor/key.go b/plugin/dapp/js/executor/key.go index 3826a1033be455b0c62478b879bdcacfea2e054e..91d8f8251b03056528c2429b1a8eb6f2183d8fc0 100644 --- a/plugin/dapp/js/executor/key.go +++ b/plugin/dapp/js/executor/key.go @@ -5,8 +5,8 @@ import ( ptypes "github.com/33cn/plugin/plugin/dapp/js/types" ) -func calcAllPrefix(name string) ([]byte, []byte) { - execer := types.ExecName("user." + ptypes.JsX + "." + name) +func calcAllPrefix(cfg *types.Chain33Config, name string) ([]byte, []byte) { + execer := cfg.ExecName("user." + ptypes.JsX + "." + name) state := types.CalcStatePrefix([]byte(execer)) local := types.CalcLocalPrefix([]byte(execer)) return state, local diff --git a/plugin/dapp/js/executor/table.go b/plugin/dapp/js/executor/table.go index caea8c4aac8991b4315a97f3c5947e99548dacc2..ddeab7362bcbf36751306fd56895f71dc819de15 100644 --- a/plugin/dapp/js/executor/table.go +++ b/plugin/dapp/js/executor/table.go @@ -45,14 +45,15 @@ func (u *js) newTable(name, config, defaultvalue string) (id int64, err error) { if err != nil { return 0, err } + cfg := u.GetAPI().GetConfig() var kvdb db.KV var prefix []byte if row.config["#db"] == "localdb" { kvdb = u.GetLocalDB() - _, prefix = calcAllPrefix(name) + _, prefix = calcAllPrefix(cfg, name) } else if row.config["#db"] == "statedb" { kvdb = u.GetStateDB() - prefix, _ = calcAllPrefix(name) + prefix, _ = calcAllPrefix(cfg, name) } else { return 0, ptypes.ErrDBType } diff --git a/plugin/dapp/lottery/executor/lotterydb.go b/plugin/dapp/lottery/executor/lotterydb.go index c74843a13d10b105b7f6dcae40477ab3d1a81107..8960e7b29dff3cc95d85677a5d1081bd5836a8ba 100755 --- a/plugin/dapp/lottery/executor/lotterydb.go +++ b/plugin/dapp/lottery/executor/lotterydb.go @@ -13,6 +13,7 @@ import ( "github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/types" pty "github.com/33cn/plugin/plugin/dapp/lottery/types" + "github.com/33cn/chain33/client" ) const ( @@ -120,6 +121,7 @@ type Action struct { difficulty uint64 index int lottery *Lottery + api client.QueueProtocolAPI } // NewLotteryAction generate New Action @@ -130,7 +132,9 @@ func NewLotteryAction(l *Lottery, tx *types.Transaction, index int) *Action { coinsAccount: l.GetCoinsAccount(), db: l.GetStateDB(), txhash: hash, fromaddr: fromaddr, blocktime: l.GetBlockTime(), height: l.GetHeight(), execaddr: dapp.ExecAddress(string(tx.Execer)), - difficulty: l.GetDifficulty(), index: index, lottery: l} + difficulty: l.GetDifficulty(), index: index, lottery: l, + api: l.GetAPI(), + } } // GetLottCommonRecipt generate logs for lottery common action @@ -262,7 +266,8 @@ func (action *Action) LotteryCreate(create *pty.LotteryCreate) (*types.Receipt, lott.TotalAddrNum = 0 lott.BuyAmount = 0 llog.Debug("LotteryCreate", "OpRewardRatio", lott.OpRewardRatio, "DevRewardRatio", lott.DevRewardRatio) - if types.IsPara() { + cfg := action.api.GetConfig() + if cfg.IsPara() { lott.CreateOnMain = action.lottery.GetMainHeight() } @@ -306,19 +311,19 @@ func (action *Action) LotteryBuy(buy *pty.LotteryBuy) (*types.Receipt, error) { return nil, pty.ErrLotteryStatus } } - + cfg := action.api.GetConfig() if lott.Status == pty.LotteryCreated || lott.Status == pty.LotteryDrawed { llog.Debug("LotteryBuy switch to purchasestate") lott.LastTransToPurState = action.height lott.Status = pty.LotteryPurchase lott.Round++ - if types.IsPara() { + if cfg.IsPara() { lott.LastTransToPurStateOnMain = action.lottery.GetMainHeight() } } if lott.Status == pty.LotteryPurchase { - if types.IsPara() { + if cfg.IsPara() { mainHeight := action.lottery.GetMainHeight() if mainHeight-lott.LastTransToPurStateOnMain > lott.GetPurBlockNum() { llog.Error("LotteryBuy", "action.height", action.height, "mainHeight", mainHeight, "LastTransToPurStateOnMain", lott.LastTransToPurStateOnMain) @@ -423,8 +428,8 @@ func (action *Action) LotteryDraw(draw *pty.LotteryDraw) (*types.Receipt, error) llog.Error("LotteryDraw", "lott.Status", lott.Status) return nil, pty.ErrLotteryStatus } - - if types.IsPara() { + cfg := action.api.GetConfig() + if cfg.IsPara() { mainHeight := action.lottery.GetMainHeight() if mainHeight-lott.GetLastTransToPurStateOnMain() < lott.GetDrawBlockNum() { llog.Error("LotteryDraw", "action.height", action.height, "mainHeight", mainHeight, "GetLastTransToPurStateOnMain", lott.GetLastTransToPurState()) @@ -688,7 +693,8 @@ func (action *Action) checkDraw(lott *LotteryDB) (*types.Receipt, *pty.LotteryUp lott.BuyAmount = 0 action.recordMissing(lott) - if types.IsPara() { + cfg := action.api.GetConfig() + if cfg.IsPara() { lott.LastTransToDrawStateOnMain = action.lottery.GetMainHeight() } return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, &updateInfo, &gainInfos, luckyAddrNum, totalFund, factor, nil diff --git a/plugin/dapp/multisig/rpc/rpc.go b/plugin/dapp/multisig/rpc/rpc.go index 09fe085726b9626b56402cfb6aa9bc6709bd9496..d5bcb299d715f0863ff513e93fa5e26303c903e2 100644 --- a/plugin/dapp/multisig/rpc/rpc.go +++ b/plugin/dapp/multisig/rpc/rpc.go @@ -16,8 +16,8 @@ func (c *Jrpc) MultiSigAccCreateTx(param *mty.MultiSigAccCreate, result *interfa if param == nil { return types.ErrInvalidParam } - - data, err := types.CallCreateTx(types.ExecName(mty.MultiSigX), "MultiSigAccCreate", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(mty.MultiSigX), "MultiSigAccCreate", param) if err != nil { return err } @@ -30,7 +30,8 @@ func (c *Jrpc) MultiSigOwnerOperateTx(param *mty.MultiSigOwnerOperate, result *i if param == nil { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(mty.MultiSigX), "MultiSigOwnerOperate", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(mty.MultiSigX), "MultiSigOwnerOperate", param) if err != nil { return err } @@ -43,7 +44,8 @@ func (c *Jrpc) MultiSigAccOperateTx(param *mty.MultiSigAccOperate, result *inter if param == nil { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(mty.MultiSigX), "MultiSigAccOperate", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(mty.MultiSigX), "MultiSigAccOperate", param) if err != nil { return err } @@ -56,7 +58,8 @@ func (c *Jrpc) MultiSigConfirmTx(param *mty.MultiSigConfirmTx, result *interface if param == nil { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(mty.MultiSigX), "MultiSigConfirmTx", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(mty.MultiSigX), "MultiSigConfirmTx", param) if err != nil { return err } @@ -70,7 +73,8 @@ func (c *Jrpc) MultiSigAccTransferInTx(param *mty.MultiSigExecTransferTo, result return types.ErrInvalidParam } v := *param - data, err := types.CallCreateTx(types.ExecName(mty.MultiSigX), "MultiSigExecTransferTo", &v) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(mty.MultiSigX), "MultiSigExecTransferTo", &v) if err != nil { return err } @@ -84,7 +88,8 @@ func (c *Jrpc) MultiSigAccTransferOutTx(param *mty.MultiSigExecTransferFrom, res return types.ErrInvalidParam } v := *param - data, err := types.CallCreateTx(types.ExecName(mty.MultiSigX), "MultiSigExecTransferFrom", &v) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(mty.MultiSigX), "MultiSigExecTransferFrom", &v) if err != nil { return err } diff --git a/plugin/dapp/multisig/wallet/multisig.go b/plugin/dapp/multisig/wallet/multisig.go index 3cd17e1734ae20d8583144817ae74181edf7355b..4c3ffd47cdb955732d7186d5ec28ab0b82b6e037 100644 --- a/plugin/dapp/multisig/wallet/multisig.go +++ b/plugin/dapp/multisig/wallet/multisig.go @@ -409,9 +409,9 @@ func (policy *multisigPolicy) rescanOwnerAttrByAddr(addr string) { } operater := policy.getWalletOperate() - + cfg := policy.getWalletOperate().GetAPI().GetConfig() //获取全网中多重签名账户数量 - msg, err := operater.GetAPI().Query(types.ExecName(mtypes.MultiSigX), "MultiSigAccCount", &types.ReqNil{}) + msg, err := operater.GetAPI().Query(cfg.ExecName(mtypes.MultiSigX), "MultiSigAccCount", &types.ReqNil{}) if err != nil { bizlog.Error("rescanOwnerAttrByAddr Query MultiSigAccCount err", "MultiSigX", mtypes.MultiSigX, "addr", addr, "err", err) return @@ -438,7 +438,7 @@ func (policy *multisigPolicy) rescanOwnerAttrByAddr(addr string) { req.End = req.Start + MaxCountPerTime curCount = req.End } - msg, err := operater.GetAPI().Query(types.ExecName(mtypes.MultiSigX), "MultiSigAccounts", &req) + msg, err := operater.GetAPI().Query(cfg.ExecName(mtypes.MultiSigX), "MultiSigAccounts", &req) if err != nil { bizlog.Error("rescanOwnerAttrByAddr", "MultiSigAccounts error", err, "addr", addr) return @@ -458,12 +458,12 @@ func (policy *multisigPolicy) rescanOwnerAttrByAddr(addr string) { } func (policy *multisigPolicy) proceMultiSigAcc(multiSigAccs *mtypes.ReplyMultiSigAccs, owneraddr string) { operater := policy.getWalletOperate() - + cfg := policy.getWalletOperate().GetAPI().GetConfig() for _, multiSigaddr := range multiSigAccs.Address { req := mtypes.ReqMultiSigAccInfo{ MultiSigAccAddr: multiSigaddr, } - msg, err := operater.GetAPI().Query(types.ExecName(mtypes.MultiSigX), "MultiSigAccountInfo", &req) + msg, err := operater.GetAPI().Query(cfg.ExecName(mtypes.MultiSigX), "MultiSigAccountInfo", &req) if err != nil { bizlog.Error("ProceMultiSigAcc", "MultiSigAccountInfo error", err, "multiSigaddr", multiSigaddr) continue diff --git a/plugin/dapp/norm/types/norm.go b/plugin/dapp/norm/types/norm.go index 237cf0c082e330e1ac295bbbc9c3862a22ce0d4d..39d3112c50f4c88c71c018d27ec54a5849ad3151 100644 --- a/plugin/dapp/norm/types/norm.go +++ b/plugin/dapp/norm/types/norm.go @@ -13,8 +13,8 @@ var NormX = "norm" func init() { types.AllowUserExec = append(types.AllowUserExec, []byte(NormX)) - types.RegFork(CoinsX, InitFork) - types.RegExec(CoinsX, InitExecutor) + types.RegFork(NormX, InitFork) + types.RegExec(NormX, InitExecutor) } func InitFork(cfg *types.Chain33Config) { diff --git a/plugin/dapp/paracross/executor/action.go b/plugin/dapp/paracross/executor/action.go index 2f8531e660f79dc8e03c4b09ee633273f7f889df..d667d33c6ca342d4581a028316d367f865a18856 100644 --- a/plugin/dapp/paracross/executor/action.go +++ b/plugin/dapp/paracross/executor/action.go @@ -81,9 +81,9 @@ func getParacrossNodes(db dbm.KV, title string) (map[string]struct{}, []string, return getNodes(db, key) } -func validTitle(title string) bool { - if types.IsPara() { - return types.GetTitle() == title +func validTitle(cfg *types.Chain33Config, title string) bool { + if cfg.IsPara() { + return cfg.GetTitle() == title } return len(title) > 0 } @@ -95,7 +95,7 @@ func validNode(addr string, nodes map[string]struct{}) bool { return false } -func checkCommitInfo(commit *pt.ParacrossCommitAction) error { +func checkCommitInfo(cfg *types.Chain33Config, commit *pt.ParacrossCommitAction) error { if commit.Status == nil { return types.ErrInvalidParam } @@ -109,7 +109,7 @@ func checkCommitInfo(commit *pt.ParacrossCommitAction) error { return nil } - if !pt.IsParaForkHeight(commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { + if !pt.IsParaForkHeight(cfg, commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { if len(commit.Status.MainBlockHash) == 0 || len(commit.Status.Title) == 0 || commit.Status.Height < 0 || len(commit.Status.PreBlockHash) == 0 || len(commit.Status.BlockHash) == 0 || len(commit.Status.StateHash) == 0 || len(commit.Status.PreStateHash) == 0 { @@ -181,7 +181,7 @@ func makeRecordReceipt(addr string, commit *pt.ParacrossCommitAction) *types.Rec } } -func makeDoneReceipt(execMainHeight int64, commit *pt.ParacrossNodeStatus, +func makeDoneReceipt(cfg *types.Chain33Config, execMainHeight int64, commit *pt.ParacrossNodeStatus, most, commitCount, totalCount int32) *types.Receipt { log := &pt.ReceiptParacrossDone{ @@ -201,7 +201,7 @@ func makeDoneReceipt(execMainHeight int64, commit *pt.ParacrossNodeStatus, Height: commit.Height, BlockHash: commit.BlockHash, } - if execMainHeight >= pt.GetDappForkHeight(pt.ForkLoopCheckCommitTxDone) { + if execMainHeight >= pt.GetDappForkHeight(cfg, pt.ForkLoopCheckCommitTxDone) { status.MainHeight = commit.MainBlockHeight status.MainHash = commit.MainBlockHash } @@ -277,7 +277,8 @@ func getConfigNodes(db dbm.KV, title string) (map[string]struct{}, []byte, error } func (a *action) getNodesGroup(title string) (map[string]struct{}, error) { - if a.exec.GetMainHeight() < pt.GetDappForkHeight(pt.ForkCommitTx) { + cfg := a.api.GetConfig() + if a.exec.GetMainHeight() < pt.GetDappForkHeight(cfg, pt.ForkCommitTx) { nodes, _, err := getConfigManageNodes(a.db, title) if err != nil { return nil, errors.Wrapf(err, "getNodes for title:%s", title) @@ -316,12 +317,12 @@ func updateCommitAddrs(stat *pt.ParacrossHeightStatus, nodes map[string]struct{} } func (a *action) Commit(commit *pt.ParacrossCommitAction) (*types.Receipt, error) { - err := checkCommitInfo(commit) + cfg := a.api.GetConfig() + err := checkCommitInfo(cfg, commit) if err != nil { return nil, err } - - if !validTitle(commit.Status.Title) { + if !validTitle(cfg, commit.Status.Title) { return nil, pt.ErrInvalidTitle } @@ -339,7 +340,7 @@ func (a *action) Commit(commit *pt.ParacrossCommitAction) (*types.Receipt, error return nil, errors.Wrapf(err, "getTitle:%s", a.fromaddr) } - if titleStatus.Height+1 == commit.Status.Height && commit.Status.Height > 0 && !pt.IsParaForkHeight(commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { + if titleStatus.Height+1 == commit.Status.Height && commit.Status.Height > 0 && !pt.IsParaForkHeight(cfg, commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { if !bytes.Equal(titleStatus.BlockHash, commit.Status.PreBlockHash) { clog.Error("paracross.Commit", "check PreBlockHash", hex.EncodeToString(titleStatus.BlockHash), "commit tx", hex.EncodeToString(commit.Status.PreBlockHash), "commitheit", commit.Status.Height, @@ -353,7 +354,7 @@ func (a *action) Commit(commit *pt.ParacrossCommitAction) (*types.Receipt, error // 平行链 (2)commit (5) 将得到一个错误的块 // 所以有必要做这个检测 var dbMainHash []byte - if !types.IsPara() { + if !cfg.IsPara() { blockHash, err := getBlockHash(a.api, commit.Status.MainBlockHeight) if err != nil { clog.Error("paracross.Commit getBlockHash", "err", err, @@ -374,7 +375,7 @@ func (a *action) Commit(commit *pt.ParacrossCommitAction) (*types.Receipt, error //对于主链,校验的是主链高度对应的blockhash是否和commit的一致 //对于平行链, 校验的是commit信息的平行链height block对应的mainHash是否和本地相同高度对应的mainHash一致, 在主链hash一致的时候看平行链共识blockhash是否一致 if !bytes.Equal(dbMainHash, commit.Status.MainBlockHash) && commit.Status.Height > 0 { - clog.Error("paracross.Commit blockHash not match", "isMain", !types.IsPara(), "db", hex.EncodeToString(dbMainHash), + clog.Error("paracross.Commit blockHash not match", "isMain", !cfg.IsPara(), "db", hex.EncodeToString(dbMainHash), "commit", hex.EncodeToString(commit.Status.MainBlockHash), "commitHeight", commit.Status.Height, "commitMainHeight", commit.Status.MainBlockHeight, "from", a.fromaddr) return nil, types.ErrBlockHashNoMatch @@ -405,13 +406,13 @@ func (a *action) Commit(commit *pt.ParacrossCommitAction) (*types.Receipt, error BlockHash: [][]byte{commit.Status.BlockHash}, }, } - if pt.IsParaForkHeight(a.exec.GetMainHeight(), pt.ForkCommitTx) { + if pt.IsParaForkHeight(cfg, a.exec.GetMainHeight(), pt.ForkCommitTx) { stat.MainHeight = commit.Status.MainBlockHeight stat.MainHash = commit.Status.MainBlockHash } //用commit.MainBlockHeight 判断更准确,如果用a.exec.MainHeight也可以,但是可能收到MainHeight之前的高度共识tx, // 后面loopCommitTxDone时候也是用当前共识高度大于分叉高度判断 - if pt.IsParaForkHeight(commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { + if pt.IsParaForkHeight(cfg, commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { stat.BlockDetails = &pt.ParacrossStatusBlockDetails{} updateCommitBlockHashs(stat, commit.Status) } @@ -428,13 +429,13 @@ func (a *action) Commit(commit *pt.ParacrossCommitAction) (*types.Receipt, error found, index := hasCommited(stat.Details.Addrs, a.fromaddr) if found { stat.Details.BlockHash[index] = commit.Status.BlockHash - if pt.IsParaForkHeight(commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { + if pt.IsParaForkHeight(cfg, commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { updateCommitBlockHashs(stat, commit.Status) } } else { stat.Details.Addrs = append(stat.Details.Addrs, a.fromaddr) stat.Details.BlockHash = append(stat.Details.BlockHash, commit.Status.BlockHash) - if pt.IsParaForkHeight(commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { + if pt.IsParaForkHeight(cfg, commit.Status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { updateCommitBlockHashs(stat, commit.Status) } } @@ -442,12 +443,12 @@ func (a *action) Commit(commit *pt.ParacrossCommitAction) (*types.Receipt, error receipt = makeCommitReceipt(a.fromaddr, commit, ©Stat, stat) } //平行链fork pt.ForkCommitTx=0,主链在ForkCommitTx后支持nodegroup,这里平行链dappFork一定为true - if types.IsDappFork(commit.Status.MainBlockHeight, pt.ParaX, pt.ForkCommitTx) { + if cfg.IsDappFork(commit.Status.MainBlockHeight, pt.ParaX, pt.ForkCommitTx) { updateCommitAddrs(stat, nodes) } saveTitleHeight(a.db, calcTitleHeightKey(stat.Title, stat.Height), stat) //fork之前记录的stat 没有根据nodes更新而更新 - if pt.IsParaForkHeight(stat.MainHeight, pt.ForkLoopCheckCommitTxDone) { + if pt.IsParaForkHeight(cfg, stat.MainHeight, pt.ForkLoopCheckCommitTxDone) { r := makeCommitStatReceipt(stat) receipt = mergeReceipt(receipt, r) } @@ -491,13 +492,14 @@ func (a *action) commitTxDone(nodeStatus *pt.ParacrossNodeStatus, stat *pt.Parac saveTitleHeight(a.db, calcTitleHeightKey(stat.Title, stat.Height), stat) //之前记录的stat 状态没更新 - if pt.IsParaForkHeight(stat.MainHeight, pt.ForkLoopCheckCommitTxDone) { + cfg := a.api.GetConfig() + if pt.IsParaForkHeight(cfg, stat.MainHeight, pt.ForkLoopCheckCommitTxDone) { r := makeCommitStatReceipt(stat) receipt = mergeReceipt(receipt, r) } //add commit done receipt - receiptDone := makeDoneReceipt(a.exec.GetMainHeight(), nodeStatus, int32(most), int32(commitCount), int32(len(nodes))) + receiptDone := makeDoneReceipt(cfg, a.exec.GetMainHeight(), nodeStatus, int32(most), int32(commitCount), int32(len(nodes))) receipt = mergeReceipt(receipt, receiptDone) r, err := a.commitTxDoneStep2(nodeStatus, stat, titleStatus) @@ -514,7 +516,8 @@ func (a *action) commitTxDoneStep2(nodeStatus *pt.ParacrossNodeStatus, stat *pt. titleStatus.Title = nodeStatus.Title titleStatus.Height = nodeStatus.Height titleStatus.BlockHash = nodeStatus.BlockHash - if pt.IsParaForkHeight(a.exec.GetMainHeight(), pt.ForkLoopCheckCommitTxDone) { + cfg := a.api.GetConfig() + if pt.IsParaForkHeight(cfg, a.exec.GetMainHeight(), pt.ForkLoopCheckCommitTxDone) { titleStatus.MainHeight = nodeStatus.MainBlockHeight titleStatus.MainHash = nodeStatus.MainBlockHash } @@ -523,7 +526,7 @@ func (a *action) commitTxDoneStep2(nodeStatus *pt.ParacrossNodeStatus, stat *pt. clog.Debug("paracross.Commit commit done", "height", nodeStatus.Height, "statusBlockHash", hex.EncodeToString(nodeStatus.BlockHash)) //parallel chain not need to process cross commit tx here - if types.IsPara() { + if cfg.IsPara() { //平行链自共识校验 selfBlockHash, err := getBlockHash(a.api, nodeStatus.Height) if err != nil { @@ -558,15 +561,15 @@ func (a *action) commitTxDoneStep2(nodeStatus *pt.ParacrossNodeStatus, stat *pt. return receipt, nil } -func isHaveCrossTxs(status *pt.ParacrossNodeStatus) bool { +func isHaveCrossTxs(cfg *types.Chain33Config, status *pt.ParacrossNodeStatus) bool { //ForkLoopCheckCommitTxDone分叉后只返回全部txResult的结果,要实际过滤出来后才能确定有没有跨链tx - if pt.IsParaForkHeight(status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { + if pt.IsParaForkHeight(cfg, status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { return true } haveCrossTxs := len(status.CrossTxHashs) > 0 //ForkCommitTx后,CrossTxHashs[][] 所有跨链交易做成一个校验hash,如果没有则[0]为nil - if status.Height > 0 && pt.IsParaForkHeight(status.MainBlockHeight, pt.ForkCommitTx) && len(status.CrossTxHashs[0]) == 0 { + if status.Height > 0 && pt.IsParaForkHeight(cfg, status.MainBlockHeight, pt.ForkCommitTx) && len(status.CrossTxHashs[0]) == 0 { haveCrossTxs = false } return haveCrossTxs @@ -574,7 +577,8 @@ func isHaveCrossTxs(status *pt.ParacrossNodeStatus) bool { } func (a *action) procCrossTxs(status *pt.ParacrossNodeStatus) (*types.Receipt, error) { - if enableParacrossTransfer && status.Height > 0 && isHaveCrossTxs(status) { + cfg := a.api.GetConfig() + if enableParacrossTransfer && status.Height > 0 && isHaveCrossTxs(cfg, status) { clog.Debug("paracross.Commit commitDone do cross", "height", status.Height) crossTxReceipt, err := a.execCrossTxs(status) if err != nil { @@ -599,9 +603,10 @@ func (a *action) loopCommitTxDone(title string) (*types.Receipt, error) { return nil, errors.Wrapf(err, "getTitle:%s", title) } //当前共识高度还未到分叉高度,则不处理 - if !pt.IsParaForkHeight(titleStatus.GetMainHeight(), pt.ForkLoopCheckCommitTxDone) { + cfg := a.api.GetConfig() + if !pt.IsParaForkHeight(cfg, titleStatus.GetMainHeight(), pt.ForkLoopCheckCommitTxDone) { return nil, errors.Wrapf(pt.ErrForkHeightNotReach, - "titleHeight:%d,forkHeight:%d", titleStatus.MainHeight, pt.GetDappForkHeight(pt.ForkLoopCheckCommitTxDone)) + "titleHeight:%d,forkHeight:%d", titleStatus.MainHeight, pt.GetDappForkHeight(cfg, pt.ForkLoopCheckCommitTxDone)) } loopHeight := titleStatus.Height @@ -678,7 +683,8 @@ func (a *action) commitTxDoneByStat(stat *pt.ParacrossHeightStatus, titleStatus } //add commit done receipt - receiptDone := makeDoneReceipt(a.exec.GetMainHeight(), mostStatus, int32(most), int32(commitCount), int32(len(nodes))) + cfg := a.api.GetConfig() + receiptDone := makeDoneReceipt(cfg, a.exec.GetMainHeight(), mostStatus, int32(most), int32(commitCount), int32(len(nodes))) receipt = mergeReceipt(receipt, receiptDone) r, err := a.commitTxDoneStep2(mostStatus, stat, titleStatus) @@ -691,7 +697,8 @@ func (a *action) commitTxDoneByStat(stat *pt.ParacrossHeightStatus, titleStatus //主链共识跳跃条件: 仅支持主链共识初始高度为-1,也就是没有共识过,共识过不允许再跳跃 func (a *action) isAllowMainConsensJump(commit *pt.ParacrossHeightStatus, titleStatus *pt.ParacrossStatus) (bool, error) { - if types.IsDappFork(a.exec.GetMainHeight(), pt.ParaX, pt.ForkLoopCheckCommitTxDone) { + cfg := a.api.GetConfig() + if cfg.IsDappFork(a.exec.GetMainHeight(), pt.ParaX, pt.ForkLoopCheckCommitTxDone) { if titleStatus.Height == -1 { return true, nil } @@ -706,8 +713,8 @@ func (a *action) isAllowParaConsensJump(commit *pt.ParacrossHeightStatus, titleS if titleStatus.Height == -1 { return true, nil } - - selfConsensForkHeight := pt.GetDappForkHeight(pt.ParaSelfConsensForkHeight) + cfg := a.api.GetConfig() + selfConsensForkHeight := pt.GetDappForkHeight(cfg, pt.ParaSelfConsensForkHeight) lastStatusMainHeight := int64(-1) if titleStatus.Height > -1 { s, err := getTitleHeight(a.db, calcTitleHeightKey(commit.Title, titleStatus.Height)) @@ -723,7 +730,8 @@ func (a *action) isAllowParaConsensJump(commit *pt.ParacrossHeightStatus, titleS } func (a *action) isAllowConsensJump(commit *pt.ParacrossHeightStatus, titleStatus *pt.ParacrossStatus) (bool, error) { - if types.IsPara() { + cfg := a.api.GetConfig() + if cfg.IsPara() { return a.isAllowParaConsensJump(commit, titleStatus) } return a.isAllowMainConsensJump(commit, titleStatus) @@ -757,6 +765,7 @@ func (a *action) execCrossTx(tx *types.TransactionDetail, crossTxHash []byte) (* func getCrossTxHashsByRst(api client.QueueProtocolAPI, status *pt.ParacrossNodeStatus) ([][]byte, []byte, error) { //只获取跨链tx + cfg := api.GetConfig() rst, err := hex.DecodeString(string(status.TxResult)) if err != nil { clog.Error("getCrossTxHashs decode rst", "CrossTxResult", string(status.TxResult), "paraHeight", status.Height) @@ -774,7 +783,7 @@ func getCrossTxHashsByRst(api client.QueueProtocolAPI, status *pt.ParacrossNodeS } //抽取平行链交易和跨链交易 - paraAllTxs := FilterTxsForPara(blockDetail.FilterParaTxsByTitle(status.Title)) + paraAllTxs := FilterTxsForPara(cfg, blockDetail.FilterParaTxsByTitle(cfg, status.Title)) var baseHashs [][]byte for _, tx := range paraAllTxs { baseHashs = append(baseHashs, tx.Hash()) @@ -787,10 +796,11 @@ func getCrossTxHashsByRst(api client.QueueProtocolAPI, status *pt.ParacrossNodeS } func getCrossTxHashs(api client.QueueProtocolAPI, status *pt.ParacrossNodeStatus) ([][]byte, []byte, error) { - if pt.IsParaForkHeight(status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { + cfg := api.GetConfig() + if pt.IsParaForkHeight(cfg, status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { return getCrossTxHashsByRst(api, status) } - if !pt.IsParaForkHeight(status.MainBlockHeight, pt.ForkCommitTx) { + if !pt.IsParaForkHeight(cfg, status.MainBlockHeight, pt.ForkCommitTx) { return status.CrossTxHashs, status.CrossTxResult, nil } @@ -805,7 +815,7 @@ func getCrossTxHashs(api client.QueueProtocolAPI, status *pt.ParacrossNodeStatus return nil, nil, err } //校验 - paraBaseTxs := FilterTxsForPara(blockDetail.FilterParaTxsByTitle(status.Title)) + paraBaseTxs := FilterTxsForPara(cfg, blockDetail.FilterParaTxsByTitle(cfg, status.Title)) paraCrossHashs := FilterParaCrossTxHashes(paraBaseTxs) var baseHashs [][]byte for _, tx := range paraBaseTxs { @@ -898,13 +908,14 @@ func (a *action) AssetTransfer(transfer *types.AssetsTransfer) (*types.Receipt, func (a *action) AssetWithdraw(withdraw *types.AssetsWithdraw) (*types.Receipt, error) { //分叉高度之后,支持从平行链提取资产 - if !types.IsDappFork(a.height, pt.ParaX, "ForkParacrossWithdrawFromParachain") { + cfg := a.api.GetConfig() + if !cfg.IsDappFork(a.height, pt.ParaX, "ForkParacrossWithdrawFromParachain") { if withdraw.Cointoken != "" { return nil, types.ErrNotSupport } } - isPara := types.IsPara() + isPara := cfg.IsPara() if !isPara { // 需要平行链先执行, 达成共识时,继续执行 return nil, nil @@ -921,7 +932,8 @@ func (a *action) AssetWithdraw(withdraw *types.AssetsWithdraw) (*types.Receipt, //当前miner tx不需要校验上一个区块的衔接性,因为tx就是本节点发出,高度,preHash等都在本区块里面的blockchain做了校验 func (a *action) Miner(miner *pt.ParacrossMinerAction) (*types.Receipt, error) { - if miner.Status.Title != types.GetTitle() || miner.Status.MainBlockHash == nil { + cfg := a.api.GetConfig() + if miner.Status.Title != cfg.GetTitle() || miner.Status.MainBlockHash == nil { return nil, pt.ErrParaMinerExecErr } @@ -941,8 +953,8 @@ func (a *action) Miner(miner *pt.ParacrossMinerAction) (*types.Receipt, error) { if miner.IsSelfConsensus { //增发coins到paracross合约中,只处理发放,不做分配 totalReward := int64(0) - coinReward := types.MGInt("mver.consensus.paracross.coinReward", a.height) - fundReward := types.MGInt("mver.consensus.paracross.coinDevFund", a.height) + coinReward := cfg.MGInt("mver.consensus.paracross.coinReward", a.height) + fundReward := cfg.MGInt("mver.consensus.paracross.coinDevFund", a.height) if coinReward > 0 { totalReward += coinReward @@ -953,7 +965,7 @@ func (a *action) Miner(miner *pt.ParacrossMinerAction) (*types.Receipt, error) { totalReward *= types.Coin if totalReward > 0 { - issueReceipt, err := a.coinsAccount.ExecIssueCoins(a.execaddr, totalReward) + issueReceipt, err := a.coinsAccount.ExecIssueCoins(cfg, a.execaddr, totalReward) if err != nil { clog.Error("paracross miner issue err", "height", miner.Status.Height, diff --git a/plugin/dapp/paracross/executor/asset.go b/plugin/dapp/paracross/executor/asset.go index 3bc4814a4f863e387f90ac5c985ea4adde39bbf9..2c12738c532d05aacde1c5845f1ccb3c75ef52f4 100644 --- a/plugin/dapp/paracross/executor/asset.go +++ b/plugin/dapp/paracross/executor/asset.go @@ -16,10 +16,11 @@ import ( ) func (a *action) assetTransfer(transfer *types.AssetsTransfer) (*types.Receipt, error) { - isPara := types.IsPara() + cfg := a.api.GetConfig() + isPara := cfg.IsPara() //主链处理分支 if !isPara { - accDB, err := createAccount(a.db, transfer.Cointoken) + accDB, err := createAccount(cfg, a.db, transfer.Cointoken) if err != nil { return nil, errors.Wrap(err, "assetTransferToken call account.NewAccountDB failed") } @@ -53,10 +54,11 @@ func (a *action) assetTransfer(transfer *types.AssetsTransfer) (*types.Receipt, } func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types.Transaction) (*types.Receipt, error) { - isPara := types.IsPara() + cfg := a.api.GetConfig() + isPara := cfg.IsPara() //主链处理分支 if !isPara { - accDB, err := createAccount(a.db, withdraw.Cointoken) + accDB, err := createAccount(cfg, a.db, withdraw.Cointoken) if err != nil { return nil, errors.Wrap(err, "assetWithdrawCoins call account.NewAccountDB failed") } @@ -85,11 +87,11 @@ func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types return assetWithdrawBalance(paraAcc, a.fromaddr, withdraw.Amount) } -func createAccount(db db.KV, symbol string) (*account.DB, error) { +func createAccount(cfg *types.Chain33Config, db db.KV, symbol string) (*account.DB, error) { var accDB *account.DB var err error if symbol == "" { - accDB = account.NewCoinsAccount() + accDB = account.NewCoinsAccount(cfg) accDB.SetDB(db) } else { accDB, err = account.NewAccountDB("token", symbol, db) diff --git a/plugin/dapp/paracross/executor/exec.go b/plugin/dapp/paracross/executor/exec.go index e86ca77253836c71d835267f4a6c648151d9f5a8..837d885e30c69381ec28b41fd4be3f0a6626c1f5 100644 --- a/plugin/dapp/paracross/executor/exec.go +++ b/plugin/dapp/paracross/executor/exec.go @@ -62,7 +62,8 @@ func (e *Paracross) Exec_Miner(payload *pt.ParacrossMinerAction, tx *types.Trans if index != 0 { return nil, pt.ErrParaMinerBaseIndex } - if !types.IsPara() { + cfg := e.GetAPI().GetConfig() + if !cfg.IsPara() { return nil, types.ErrNotSupport } a := newAction(e, tx) diff --git a/plugin/dapp/paracross/executor/exec_del_local.go b/plugin/dapp/paracross/executor/exec_del_local.go index 6a616b3ab43845164f3e9f598776077be832bede..a7fc0bb7a61933cb82271ae0783ed6c6dd9fc729 100644 --- a/plugin/dapp/paracross/executor/exec_del_local.go +++ b/plugin/dapp/paracross/executor/exec_del_local.go @@ -13,6 +13,7 @@ import ( //ExecDelLocal_Commit consensus commit tx del local db process func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet + cfg := e.GetAPI().GetConfig() for _, log := range receiptData.Logs { if log.Ty == pt.TyLogParacrossCommit { //} || log.Ty == types.TyLogParacrossCommitRecord { var g pt.ReceiptParacrossCommit @@ -32,7 +33,7 @@ func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *t key = calcLocalHeightKey(g.Title, g.Height) set.KV = append(set.KV, &types.KeyValue{Key: key, Value: nil}) - if !types.IsPara() && g.Height > 0 { + if !cfg.IsPara() && g.Height > 0 { r, err := e.saveLocalParaTxs(tx, true) if err != nil { return nil, err @@ -55,6 +56,7 @@ func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *t // ExecDelLocal_NodeConfig node config tx delete process func (e *Paracross) ExecDelLocal_NodeConfig(payload *pt.ParaNodeAddrConfig, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet + cfg := e.GetAPI().GetConfig() for _, log := range receiptData.Logs { if log.Ty == pt.TyLogParaNodeConfig { var g pt.ReceiptParaNodeConfig @@ -88,7 +90,7 @@ func (e *Paracross) ExecDelLocal_NodeConfig(payload *pt.ParaNodeAddrConfig, tx * key = calcLocalHeightKey(g.Title, g.Height) set.KV = append(set.KV, &types.KeyValue{Key: key, Value: nil}) - if !types.IsPara() && g.Height > 0 { + if !cfg.IsPara() && g.Height > 0 { r, err := e.saveLocalParaTxsFork(&g, true) if err != nil { return nil, err diff --git a/plugin/dapp/paracross/executor/exec_local.go b/plugin/dapp/paracross/executor/exec_local.go index b162705b4075abeba410472f3450a2389ec17ab3..143cbfa1b18b33445d0d7113c8441f8265f16f8c 100644 --- a/plugin/dapp/paracross/executor/exec_local.go +++ b/plugin/dapp/paracross/executor/exec_local.go @@ -18,6 +18,7 @@ import ( //ExecLocal_Commit commit tx local db process func (e *Paracross) ExecLocal_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet + cfg := e.GetAPI().GetConfig() for _, log := range receiptData.Logs { if log.Ty == pt.TyLogParacrossCommit { var g pt.ReceiptParacrossCommit @@ -35,7 +36,7 @@ func (e *Paracross) ExecLocal_Commit(payload *pt.ParacrossCommitAction, tx *type key = calcLocalHeightKey(g.Title, g.Height) set.KV = append(set.KV, &types.KeyValue{Key: key, Value: types.Encode(&g)}) - if !types.IsPara() && g.Height > 0 { + if !cfg.IsPara() && g.Height > 0 { r, err := e.saveLocalParaTxs(tx, false) if err != nil { return nil, err @@ -58,6 +59,7 @@ func (e *Paracross) ExecLocal_Commit(payload *pt.ParacrossCommitAction, tx *type //ExecLocal_NodeConfig node config add process func (e *Paracross) ExecLocal_NodeConfig(payload *pt.ParaNodeAddrConfig, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet + cfg := e.GetAPI().GetConfig() for _, log := range receiptData.Logs { if log.Ty == pt.TyLogParaNodeConfig { var g pt.ReceiptParaNodeConfig @@ -90,7 +92,7 @@ func (e *Paracross) ExecLocal_NodeConfig(payload *pt.ParaNodeAddrConfig, tx *typ key = calcLocalHeightKey(g.Title, g.Height) set.KV = append(set.KV, &types.KeyValue{Key: key, Value: types.Encode(&g)}) - if !types.IsPara() && g.Height > 0 { + if !cfg.IsPara() && g.Height > 0 { r, err := e.saveLocalParaTxsFork(&g, false) if err != nil { return nil, err @@ -160,14 +162,14 @@ func (e *Paracross) ExecLocal_AssetWithdraw(payload *types.AssetsWithdraw, tx *t return nil, nil } -func setMinerTxResult(payload *pt.ParacrossMinerAction, txs []*types.Transaction, receipts []*types.ReceiptData) error { +func setMinerTxResult(cfg *types.Chain33Config, payload *pt.ParacrossMinerAction, txs []*types.Transaction, receipts []*types.ReceiptData) error { isCommitTx := make(map[string]bool) var curTxHashs, paraTxHashs, crossTxHashs [][]byte for _, tx := range txs { hash := tx.Hash() curTxHashs = append(curTxHashs, hash) //对user.p.xx.paracross ,actionTy==commit 的tx不需要再发回主链 - if types.IsMyParaExecName(string(tx.Execer)) && bytes.HasSuffix(tx.Execer, []byte(pt.ParaX)) { + if cfg.IsMyParaExecName(string(tx.Execer)) && bytes.HasSuffix(tx.Execer, []byte(pt.ParaX)) { var payload pt.ParacrossAction err := types.Decode(tx.Payload, &payload) if err != nil { @@ -179,11 +181,11 @@ func setMinerTxResult(payload *pt.ParacrossMinerAction, txs []*types.Transaction } } //跨链交易包含了主链交易,需要过滤出来 - if types.IsMyParaExecName(string(tx.Execer)) && !isCommitTx[string(hash)] { + if cfg.IsMyParaExecName(string(tx.Execer)) && !isCommitTx[string(hash)] { paraTxHashs = append(paraTxHashs, hash) } } - totalCrossTxHashs := FilterParaMainCrossTxHashes(types.GetTitle(), txs) + totalCrossTxHashs := FilterParaMainCrossTxHashes(cfg.GetTitle(), txs) for _, crossHash := range totalCrossTxHashs { if !isCommitTx[string(crossHash)] { crossTxHashs = append(crossTxHashs, crossHash) @@ -197,14 +199,14 @@ func setMinerTxResult(payload *pt.ParacrossMinerAction, txs []*types.Transaction return nil } -func setMinerTxResultFork(status *pt.ParacrossNodeStatus, txs []*types.Transaction, receipts []*types.ReceiptData) error { +func setMinerTxResultFork(cfg *types.Chain33Config, status *pt.ParacrossNodeStatus, txs []*types.Transaction, receipts []*types.ReceiptData) error { isCommitTx := make(map[string]bool) var curTxHashs [][]byte for _, tx := range txs { hash := tx.Hash() curTxHashs = append(curTxHashs, hash) - if types.IsMyParaExecName(string(tx.Execer)) && bytes.HasSuffix(tx.Execer, []byte(pt.ParaX)) { + if cfg.IsMyParaExecName(string(tx.Execer)) && bytes.HasSuffix(tx.Execer, []byte(pt.ParaX)) { var payload pt.ParacrossAction err := types.Decode(tx.Payload, &payload) if err != nil { @@ -228,7 +230,7 @@ func setMinerTxResultFork(status *pt.ParacrossNodeStatus, txs []*types.Transacti status.TxResult = []byte(hex.EncodeToString(util.CalcSingleBitMap(curTxHashs, receipts))) //ForkLoopCheckCommitTxDone 后只保留全部txreseult 结果 - if !pt.IsParaForkHeight(status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { + if !pt.IsParaForkHeight(cfg, status.MainBlockHeight, pt.ForkLoopCheckCommitTxDone) { //跨链tx结果 crossTxHashs := FilterParaCrossTxHashes(txs) status.CrossTxResult = []byte(hex.EncodeToString(util.CalcBitMap(crossTxHashs, curTxHashs, receipts))) @@ -247,15 +249,16 @@ func (e *Paracross) ExecLocal_Miner(payload *pt.ParacrossMinerAction, tx *types. var set types.LocalDBSet txs := e.GetTxs() + cfg := e.GetAPI().GetConfig() //removed the 0 vote tx - if pt.IsParaForkHeight(payload.Status.MainBlockHeight, pt.ForkCommitTx) { - err := setMinerTxResultFork(payload.Status, txs[1:], e.GetReceipt()[1:]) + if pt.IsParaForkHeight(cfg, payload.Status.MainBlockHeight, pt.ForkCommitTx) { + err := setMinerTxResultFork(cfg, payload.Status, txs[1:], e.GetReceipt()[1:]) if err != nil { return nil, err } } else { - err := setMinerTxResult(payload, txs[1:], e.GetReceipt()[1:]) + err := setMinerTxResult(cfg, payload, txs[1:], e.GetReceipt()[1:]) if err != nil { return nil, err } diff --git a/plugin/dapp/paracross/executor/filtertxs.go b/plugin/dapp/paracross/executor/filtertxs.go index 13843574abb3d521f44fc9cf4c909d9c60c656df..d97133bcee5186d284e2ad265dd24b5dcad691b4 100644 --- a/plugin/dapp/paracross/executor/filtertxs.go +++ b/plugin/dapp/paracross/executor/filtertxs.go @@ -46,7 +46,7 @@ func checkReceiptExecOk(receipt *types.ReceiptData) bool { // 1, 主链+平行链 user.p.xx.paracross 交易组 混合跨链资产转移 paracross主链执行成功 // 2, 平行链 user.p.xx.paracross + user.p.xx.other 混合平行链组合 paracross主链执行成功 // 3, 平行链 user.p.xx.other 交易组 混合平行链组合 other主链pack -func filterParaTxGroup(tx *types.Transaction, allTxs []*types.TxDetail, index int, blockHeight, forkHeight int64) ([]*types.Transaction, int) { +func filterParaTxGroup(cfg *types.Chain33Config, tx *types.Transaction, allTxs []*types.TxDetail, index int, blockHeight, forkHeight int64) ([]*types.Transaction, int) { var headIdx int for i := index; i >= 0; i-- { @@ -58,7 +58,7 @@ func filterParaTxGroup(tx *types.Transaction, allTxs []*types.TxDetail, index in endIdx := headIdx + int(tx.GroupCount) for i := headIdx; i < endIdx; i++ { - if types.IsPara() && blockHeight < forkHeight { + if cfg.IsPara() && blockHeight < forkHeight { if types.IsParaExecName(string(allTxs[i].Tx.Execer)) { continue } @@ -77,13 +77,13 @@ func filterParaTxGroup(tx *types.Transaction, allTxs []*types.TxDetail, index in } //FilterTxsForPara include some main tx in tx group before ForkParacrossCommitTx -func FilterTxsForPara(main *types.ParaTxDetail) []*types.Transaction { +func FilterTxsForPara(cfg *types.Chain33Config, main *types.ParaTxDetail) []*types.Transaction { var txs []*types.Transaction - forkHeight := pt.GetDappForkHeight(pt.ForkCommitTx) + forkHeight := pt.GetDappForkHeight(cfg, pt.ForkCommitTx) for i := 0; i < len(main.TxDetails); i++ { tx := main.TxDetails[i].Tx if tx.GroupCount >= 2 { - mainTxs, endIdx := filterParaTxGroup(tx, main.TxDetails, i, main.Header.Height, forkHeight) + mainTxs, endIdx := filterParaTxGroup(cfg, tx, main.TxDetails, i, main.Header.Height, forkHeight) txs = append(txs, mainTxs...) i = endIdx - 1 continue diff --git a/plugin/dapp/paracross/executor/query.go b/plugin/dapp/paracross/executor/query.go index 0cd1ad9d93c244198822e46124228375f58c333e..283e3e87cfa3c75a65f38098303af29f1f17a844 100644 --- a/plugin/dapp/paracross/executor/query.go +++ b/plugin/dapp/paracross/executor/query.go @@ -94,7 +94,8 @@ func (p *Paracross) Query_GetNodeAddrInfo(in *pt.ReqParacrossNodeInfo) (types.Me if err != nil { return nil, err } - if pt.IsParaForkHeight(mainHeight, pt.ForkLoopCheckCommitTxDone) { + cfg := p.GetAPI().GetConfig() + if pt.IsParaForkHeight(cfg, mainHeight, pt.ForkLoopCheckCommitTxDone) { stat.QuitId = getParaNodeIDSuffix(stat.QuitId) stat.ProposalId = getParaNodeIDSuffix(stat.ProposalId) } @@ -103,7 +104,8 @@ func (p *Paracross) Query_GetNodeAddrInfo(in *pt.ReqParacrossNodeInfo) (types.Me func (p *Paracross) getMainHeight() (int64, error) { mainHeight := p.GetMainHeight() - if types.IsPara() { + cfg := p.GetAPI().GetConfig() + if cfg.IsPara() { block, err := p.GetAPI().GetBlocks(&types.ReqBlocks{Start: p.GetHeight(), End: p.GetHeight()}) if err != nil || block == nil || len(block.Items) == 0 { return -1, types.ErrBlockExist @@ -122,12 +124,13 @@ func (p *Paracross) Query_GetNodeIDInfo(in *pt.ReqParacrossNodeInfo) (types.Mess if err != nil { return nil, err } - stat, err := getNodeIDWithFork(p.GetStateDB(), in.Title, mainHeight, in.Id) + cfg := p.GetAPI().GetConfig() + stat, err := getNodeIDWithFork(cfg, p.GetStateDB(), in.Title, mainHeight, in.Id) if err != nil { return nil, err } - if pt.IsParaForkHeight(mainHeight, pt.ForkLoopCheckCommitTxDone) { + if pt.IsParaForkHeight(cfg, mainHeight, pt.ForkLoopCheckCommitTxDone) { stat.Id = getParaNodeIDSuffix(stat.Id) } return stat, nil @@ -146,7 +149,8 @@ func (p *Paracross) Query_ListNodeStatusInfo(in *pt.ReqParacrossNodeInfo) (types if err != nil { return nil, err } - if !pt.IsParaForkHeight(mainHeight, pt.ForkLoopCheckCommitTxDone) { + cfg := p.GetAPI().GetConfig() + if !pt.IsParaForkHeight(cfg, mainHeight, pt.ForkLoopCheckCommitTxDone) { return resp, err } addrs := resp.(*pt.RespParacrossNodeAddrs) @@ -169,7 +173,8 @@ func (p *Paracross) Query_GetNodeGroupStatus(in *pt.ReqParacrossNodeInfo) (types if err != nil { return nil, err } - if pt.IsParaForkHeight(mainHeight, pt.ForkLoopCheckCommitTxDone) { + cfg := p.GetAPI().GetConfig() + if pt.IsParaForkHeight(cfg, mainHeight, pt.ForkLoopCheckCommitTxDone) { stat.Id = getParaNodeIDSuffix(stat.Id) } return stat, nil @@ -188,7 +193,8 @@ func (p *Paracross) Query_ListNodeGroupStatus(in *pt.ReqParacrossNodeInfo) (type if err != nil { return nil, err } - if pt.IsParaForkHeight(mainHeight, pt.ForkLoopCheckCommitTxDone) { + cfg := p.GetAPI().GetConfig() + if pt.IsParaForkHeight(cfg, mainHeight, pt.ForkLoopCheckCommitTxDone) { addrs := resp.(*pt.RespParacrossNodeGroups) for _, id := range addrs.Ids { id.Id = getParaNodeIDSuffix(id.Id) diff --git a/plugin/dapp/paracross/executor/reward.go b/plugin/dapp/paracross/executor/reward.go index 63f88b3b376493c111a7549783c1146f536590e8..977886ddf6fae59443a27e160686e3e49d35987b 100644 --- a/plugin/dapp/paracross/executor/reward.go +++ b/plugin/dapp/paracross/executor/reward.go @@ -11,9 +11,10 @@ import ( func (a *action) reward(nodeStatus *pt.ParacrossNodeStatus, stat *pt.ParacrossHeightStatus) (*types.Receipt, error) { //获取挖矿相关配置,这里需注意是共识的高度,而不是交易的高度 - coinReward := types.MGInt("mver.consensus.paracross.coinReward", nodeStatus.Height) * types.Coin - fundReward := types.MGInt("mver.consensus.paracross.coinDevFund", nodeStatus.Height) * types.Coin - fundAddr := types.MGStr("mver.consensus.fundKeyAddr", nodeStatus.Height) + cfg := a.api.GetConfig() + coinReward := cfg.MGInt("mver.consensus.paracross.coinReward", nodeStatus.Height) * types.Coin + fundReward := cfg.MGInt("mver.consensus.paracross.coinDevFund", nodeStatus.Height) * types.Coin + fundAddr := cfg.MGStr("mver.consensus.fundKeyAddr", nodeStatus.Height) minerAddrs := getMiners(stat.Details, nodeStatus.BlockHash) //分配给矿工的单位奖励 diff --git a/plugin/dapp/paracross/executor/superaccount.go b/plugin/dapp/paracross/executor/superaccount.go index ed29b14230adc7e771d9e4581b8e5d17511ef366..adc18836057a5fb9bf5724af6636f604b9bfe3e9 100644 --- a/plugin/dapp/paracross/executor/superaccount.go +++ b/plugin/dapp/paracross/executor/superaccount.go @@ -21,10 +21,6 @@ import ( "github.com/pkg/errors" ) -var ( - confManager = types.ConfSub(manager.ManageX) - conf = types.ConfSub(pt.ParaX) -) func deepCopy(dst, src interface{}) error { var buf bytes.Buffer @@ -58,8 +54,8 @@ func getNodeID(db dbm.KV, id string) (*pt.ParaNodeIdStatus, error) { } //分叉之前 id是"mavl-paracros-...0x12342308b"格式,分叉以后只支持输入为去掉了mavl-paracross前缀的交易id,系统会为id加上前缀 -func getNodeIDWithFork(db dbm.KV, title string, height int64, id string) (*pt.ParaNodeIdStatus, error) { - if pt.IsParaForkHeight(height, pt.ForkLoopCheckCommitTxDone) { +func getNodeIDWithFork(cfg *types.Chain33Config, db dbm.KV, title string, height int64, id string) (*pt.ParaNodeIdStatus, error) { + if pt.IsParaForkHeight(cfg, height, pt.ForkLoopCheckCommitTxDone) { id = calcParaNodeIDKey(title, id) } return getNodeID(db, id) @@ -86,8 +82,8 @@ func getDb(db dbm.KV, key []byte) ([]byte, error) { } //分叉之前 id是"mavl-paracros-...0x12342308b"格式,分叉以后只支持输入为去掉了mavl-paracross前缀的交易id,系统会为id加上前缀 -func getNodeGroupID(db dbm.KV, title string, height int64, id string) (*pt.ParaNodeGroupStatus, error) { - if pt.IsParaForkHeight(height, pt.ForkLoopCheckCommitTxDone) { +func getNodeGroupID(cfg *types.Chain33Config, db dbm.KV, title string, height int64, id string) (*pt.ParaNodeGroupStatus, error) { + if pt.IsParaForkHeight(cfg, height, pt.ForkLoopCheckCommitTxDone) { id = calcParaNodeGroupIDKey(title, id) } val, err := getDb(db, []byte(id)) @@ -255,7 +251,8 @@ func (a *action) nodeJoin(config *pt.ParaNodeAddrConfig) (*types.Receipt, error) } receipt := &types.Receipt{Ty: types.ExecOk} - if !types.IsPara() { + cfg := a.api.GetConfig() + if !cfg.IsPara() { r, err := a.nodeGroupCoinsFrozen(a.fromaddr, config.CoinsFrozen, 1) if err != nil { return nil, err @@ -317,7 +314,8 @@ func (a *action) nodeQuit(config *pt.ParaNodeAddrConfig) (*types.Receipt, error) } func (a *action) nodeCancel(config *pt.ParaNodeAddrConfig) (*types.Receipt, error) { - stat, err := getNodeIDWithFork(a.db, config.Title, a.exec.GetMainHeight(), config.Id) + cfg := a.api.GetConfig() + stat, err := getNodeIDWithFork(cfg, a.db, config.Title, a.exec.GetMainHeight(), config.Id) if err != nil { return nil, err } @@ -343,7 +341,8 @@ func (a *action) nodeCancel(config *pt.ParaNodeAddrConfig) (*types.Receipt, erro } if stat.Status == pt.ParacrossNodeJoining { receipt := &types.Receipt{Ty: types.ExecOk} - if !types.IsPara() { + cfg := a.api.GetConfig() + if !cfg.IsPara() { r, err := a.nodeGroupCoinsActive(stat.FromAddr, stat.CoinsFrozen, 1) if err != nil { return nil, err @@ -368,7 +367,8 @@ func (a *action) nodeCancel(config *pt.ParaNodeAddrConfig) (*types.Receipt, erro } // IsSuperManager is supper manager or not -func isSuperManager(addr string) bool { +func isSuperManager(cfg *types.Chain33Config, addr string) bool { + confManager := types.ConfSub(cfg, manager.ManageX) for _, m := range confManager.GStrList("superManager") { if addr == m { return true @@ -403,7 +403,8 @@ func (a *action) superManagerVoteProc(title string) error { if err != nil { return err } - + cfg := a.api.GetConfig() + conf := types.ConfSub(cfg, pt.ParaX) confStopBlocks := conf.GInt("paraConsensusStopBlocks") data, err := a.exec.paracrossGetHeight(title) if err != nil { @@ -444,6 +445,7 @@ func updateVotes(stat *pt.ParaNodeIdStatus, nodes map[string]struct{}) { } func (a *action) updateNodeAddrStatus(stat *pt.ParaNodeIdStatus) (*types.Receipt, error) { + cfg := a.api.GetConfig() addrStat, err := getNodeAddr(a.db, stat.Title, stat.TargetAddr) if err != nil { if !isNotFound(err) { @@ -476,7 +478,7 @@ func (a *action) updateNodeAddrStatus(stat *pt.ParaNodeIdStatus) (*types.Receipt addrStat.QuitId = stat.Id receipt := makeParaNodeStatusReceipt(a.fromaddr, &preStat, addrStat) - if !types.IsPara() { + if !cfg.IsPara() { r, err := a.nodeGroupCoinsActive(proposalStat.FromAddr, proposalStat.CoinsFrozen, 1) if err != nil { return nil, err @@ -494,11 +496,12 @@ func (a *action) nodeVote(config *pt.ParaNodeAddrConfig) (*types.Receipt, error) if err != nil { return nil, errors.Wrapf(err, "getNodes for title:%s", config.Title) } - if !validNode(a.fromaddr, nodes) && !isSuperManager(a.fromaddr) { + cfg := a.api.GetConfig() + if !validNode(a.fromaddr, nodes) && !isSuperManager(cfg, a.fromaddr) { return nil, errors.Wrapf(pt.ErrNodeNotForTheTitle, "not validNode:%s", a.fromaddr) } - stat, err := getNodeIDWithFork(a.db, config.Title, a.exec.GetMainHeight(), config.Id) + stat, err := getNodeIDWithFork(cfg, a.db, config.Title, a.exec.GetMainHeight(), config.Id) if err != nil { return nil, err } @@ -541,9 +544,9 @@ func (a *action) nodeVote(config *pt.ParaNodeAddrConfig) (*types.Receipt, error) most, vote := getMostVote(stat) if !isCommitDone(nodes, most) { superManagerPass := false - if isSuperManager(a.fromaddr) { + if isSuperManager(cfg, a.fromaddr) { //如果主链执行失败,交易不会过滤到平行链,如果主链成功,平行链直接成功 - if !types.IsPara() { + if !cfg.IsPara() { err := a.superManagerVoteProc(config.Title) if err != nil { return nil, err @@ -565,7 +568,7 @@ func (a *action) nodeVote(config *pt.ParaNodeAddrConfig) (*types.Receipt, error) stat.Status = pt.ParacrossNodeClosed stat.Height = a.height //active coins - if !types.IsPara() { + if !cfg.IsPara() { r, err := a.nodeGroupCoinsActive(stat.FromAddr, stat.CoinsFrozen, 1) if err != nil { return nil, err @@ -606,7 +609,7 @@ func (a *action) nodeVote(config *pt.ParaNodeAddrConfig) (*types.Receipt, error) } receipt = mergeReceipt(receipt, r) - if a.exec.GetMainHeight() > pt.GetDappForkHeight(pt.ForkLoopCheckCommitTxDone) { + if a.exec.GetMainHeight() > pt.GetDappForkHeight(cfg, pt.ForkLoopCheckCommitTxDone) { //node quit后,如果committx满足2/3目标,自动触发commitDone r, err = a.loopCommitTxDone(config.Title) if err != nil { @@ -715,6 +718,8 @@ func (a *action) checkNodeGroupExist(title string) error { func (a *action) nodeGroupCoinsFrozen(createAddr string, configCoinsFrozen int64, nodeCounts int64) (*types.Receipt, error) { receipt := &types.Receipt{} + cfg := a.api.GetConfig() + conf := types.ConfSub(cfg, pt.ParaX) confCoins := conf.GInt("nodeGroupFrozenCoins") if configCoinsFrozen < confCoins { return nil, pt.ErrParaNodeGroupFrozenCoinsNotEnough @@ -771,7 +776,8 @@ func (a *action) nodeGroupApply(config *pt.ParaNodeGroupConfig) (*types.Receipt, receipt := &types.Receipt{Ty: types.ExecOk} //main chain - if !types.IsPara() { + cfg := a.api.GetConfig() + if !cfg.IsPara() { r, err := a.nodeGroupCoinsFrozen(a.fromaddr, config.CoinsFrozen, int64(len(addrs))) if err != nil { return nil, err @@ -812,7 +818,8 @@ func (a *action) nodeGroupModify(config *pt.ParaNodeGroupConfig) (*types.Receipt } func (a *action) nodeGroupQuit(config *pt.ParaNodeGroupConfig) (*types.Receipt, error) { - status, err := getNodeGroupID(a.db, config.Title, a.exec.GetMainHeight(), config.Id) + cfg := a.api.GetConfig() + status, err := getNodeGroupID(cfg, a.db, config.Title, a.exec.GetMainHeight(), config.Id) if err != nil { return nil, err } @@ -835,7 +842,7 @@ func (a *action) nodeGroupQuit(config *pt.ParaNodeGroupConfig) (*types.Receipt, receipt := &types.Receipt{Ty: types.ExecOk} //main chain - if !types.IsPara() { + if !cfg.IsPara() { r, err := a.nodeGroupCoinsActive(status.FromAddr, status.CoinsFrozen, int64(len(applyAddrs))) if err != nil { return nil, err @@ -927,11 +934,12 @@ func (a *action) nodeGroupApproveApply(config *pt.ParaNodeGroupConfig, apply *pt // NodeGroupApprove super addr approve the node group apply func (a *action) nodeGroupApprove(config *pt.ParaNodeGroupConfig) (*types.Receipt, error) { - if !isSuperManager(a.fromaddr) { + cfg := a.api.GetConfig() + if !isSuperManager(cfg, a.fromaddr) { return nil, errors.Wrapf(types.ErrNotAllow, "node group approve not super manager:%s", a.fromaddr) } - id, err := getNodeGroupID(a.db, config.Title, a.exec.GetMainHeight(), config.Id) + id, err := getNodeGroupID(cfg, a.db, config.Title, a.exec.GetMainHeight(), config.Id) if err != nil { return nil, err } @@ -992,7 +1000,8 @@ func (a *action) nodeGroupCreate(status *pt.ParaNodeGroupStatus) (*types.Receipt //NodeGroupConfig support super node group config func (a *action) NodeGroupConfig(config *pt.ParaNodeGroupConfig) (*types.Receipt, error) { - if !validTitle(config.Title) { + cfg := a.api.GetConfig() + if !validTitle(cfg, config.Title) { return nil, pt.ErrInvalidTitle } @@ -1029,7 +1038,8 @@ func (a *action) NodeGroupConfig(config *pt.ParaNodeGroupConfig) (*types.Receipt //NodeConfig support super account node config func (a *action) NodeConfig(config *pt.ParaNodeAddrConfig) (*types.Receipt, error) { - if !validTitle(config.Title) { + cfg := a.api.GetConfig() + if !validTitle(cfg, config.Title) { return nil, pt.ErrInvalidTitle } diff --git a/plugin/dapp/paracross/rpc/rpc.go b/plugin/dapp/paracross/rpc/rpc.go index 96ec8cdc6ff9da53d389ad7d6368ce028f1477d1..8d20cb9772d25d3081ca757426d6e62c33c65a68 100644 --- a/plugin/dapp/paracross/rpc/rpc.go +++ b/plugin/dapp/paracross/rpc/rpc.go @@ -13,7 +13,8 @@ import ( ) func (c *channelClient) GetTitle(ctx context.Context, req *types.ReqString) (*pt.ParacrossConsensusStatus, error) { - data, err := c.Query(pt.GetExecName(), "GetTitle", req) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "GetTitle", req) if err != nil { return nil, err } @@ -25,7 +26,7 @@ func (c *channelClient) GetTitle(ctx context.Context, req *types.ReqString) (*pt if resp, ok := data.(*pt.ParacrossStatus); ok { // 如果主链上查询平行链的高度,chain height应该是平行链的高度而不是主链高度, 平行链的真实高度需要在平行链侧查询 - if !types.IsPara() { + if !cfg.IsPara() { chainHeight = resp.Height } return &pt.ParacrossConsensusStatus{ @@ -40,9 +41,10 @@ func (c *channelClient) GetTitle(ctx context.Context, req *types.ReqString) (*pt // GetHeight jrpc get consensus height func (c *Jrpc) GetHeight(req *types.ReqString, result *interface{}) error { + cfg := c.cli.GetConfig() if req == nil || req.Data == "" { - if types.IsPara() { - req = &types.ReqString{Data: types.GetTitle()} + if cfg.IsPara() { + req = &types.ReqString{Data: cfg.GetTitle()} } else { return types.ErrInvalidParam } @@ -58,7 +60,8 @@ func (c *Jrpc) GetHeight(req *types.ReqString, result *interface{}) error { } func (c *channelClient) ListTitles(ctx context.Context, req *types.ReqNil) (*pt.RespParacrossTitles, error) { - data, err := c.Query(pt.GetExecName(), "ListTitles", req) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "ListTitles", req) if err != nil { return nil, err } @@ -79,7 +82,8 @@ func (c *Jrpc) ListTitles(req *types.ReqNil, result *interface{}) error { } func (c *channelClient) GetTitleHeight(ctx context.Context, req *pt.ReqParacrossTitleHeight) (*pt.ParacrossHeightStatusRsp, error) { - data, err := c.Query(pt.GetExecName(), "GetTitleHeight", req) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "GetTitleHeight", req) if err != nil { return nil, err } @@ -103,7 +107,8 @@ func (c *Jrpc) GetTitleHeight(req *pt.ReqParacrossTitleHeight, result *interface } func (c *channelClient) GetDoneTitleHeight(ctx context.Context, req *pt.ReqParacrossTitleHeight) (*pt.RespParacrossDone, error) { - data, err := c.Query(pt.GetExecName(), "GetDoneTitleHeight", req) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "GetDoneTitleHeight", req) if err != nil { return nil, err } @@ -114,7 +119,8 @@ func (c *channelClient) GetDoneTitleHeight(ctx context.Context, req *pt.ReqParac } func (c *channelClient) GetAssetTxResult(ctx context.Context, req *types.ReqHash) (*pt.ParacrossAsset, error) { - data, err := c.Query(pt.GetExecName(), "GetAssetTxResult", req) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "GetAssetTxResult", req) if err != nil { return nil, err } @@ -185,11 +191,11 @@ func (c *channelClient) GetBlock2MainInfo(ctx context.Context, req *types.ReqBlo if err != nil { return nil, err } - + cfg := c.GetConfig() for _, item := range details.Items { data := &pt.ParaBlock2MainMap{ Height: item.Block.Height, - BlockHash: common.ToHex(item.Block.Hash()), + BlockHash: common.ToHex(item.Block.Hash(cfg)), MainHeight: item.Block.MainHeight, MainHash: common.ToHex(item.Block.MainHash), } @@ -216,7 +222,8 @@ func (c *Jrpc) GetBlock2MainInfo(req *types.ReqBlocks, result *interface{}) erro // GetNodeAddrStatus get super node status func (c *channelClient) GetNodeAddrStatus(ctx context.Context, req *pt.ReqParacrossNodeInfo) (*pt.ParaNodeAddrIdStatus, error) { r := *req - data, err := c.Query(pt.GetExecName(), "GetNodeAddrInfo", &r) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "GetNodeAddrInfo", &r) if err != nil { return nil, err } @@ -229,7 +236,8 @@ func (c *channelClient) GetNodeAddrStatus(ctx context.Context, req *pt.ReqParacr // GetNodeIDStatus get super node status func (c *channelClient) GetNodeIDStatus(ctx context.Context, req *pt.ReqParacrossNodeInfo) (*pt.ParaNodeIdStatus, error) { r := *req - data, err := c.Query(pt.GetExecName(), "GetNodeIDInfo", &r) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "GetNodeIDInfo", &r) if err != nil { return nil, err } @@ -270,7 +278,8 @@ func (c *Jrpc) GetNodeIDStatus(req *pt.ReqParacrossNodeInfo, result *interface{} //ListNodeStatus list super node by status func (c *channelClient) ListNodeStatus(ctx context.Context, req *pt.ReqParacrossNodeInfo) (*pt.RespParacrossNodeAddrs, error) { r := *req - data, err := c.Query(pt.GetExecName(), "ListNodeStatusInfo", &r) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "ListNodeStatusInfo", &r) if err != nil { return nil, err } @@ -293,7 +302,8 @@ func (c *Jrpc) ListNodeStatus(req *pt.ReqParacrossNodeInfo, result *interface{}) // GetNodeGroupAddrs get super node group addrs func (c *channelClient) GetNodeGroupAddrs(ctx context.Context, req *pt.ReqParacrossNodeInfo) (*types.ReplyConfig, error) { r := *req - data, err := c.Query(pt.GetExecName(), "GetNodeGroupAddrs", &r) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "GetNodeGroupAddrs", &r) if err != nil { return nil, err } @@ -316,7 +326,8 @@ func (c *Jrpc) GetNodeGroupAddrs(req *pt.ReqParacrossNodeInfo, result *interface // GetNodeGroupStatus get super node group status func (c *channelClient) GetNodeGroupStatus(ctx context.Context, req *pt.ReqParacrossNodeInfo) (*pt.ParaNodeGroupStatus, error) { r := *req - data, err := c.Query(pt.GetExecName(), "GetNodeGroupStatus", &r) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "GetNodeGroupStatus", &r) if err != nil { return nil, err } @@ -339,7 +350,8 @@ func (c *Jrpc) GetNodeGroupStatus(req *pt.ReqParacrossNodeInfo, result *interfac //ListNodeGroupStatus list super node group by status func (c *channelClient) ListNodeGroupStatus(ctx context.Context, req *pt.ReqParacrossNodeInfo) (*pt.RespParacrossNodeGroups, error) { r := *req - data, err := c.Query(pt.GetExecName(), "ListNodeGroupStatus", &r) + cfg := c.GetConfig() + data, err := c.Query(pt.GetExecName(cfg), "ListNodeGroupStatus", &r) if err != nil { return nil, err } diff --git a/plugin/dapp/privacy/wallet/exec.go b/plugin/dapp/privacy/wallet/exec.go index 9d2de38248496ade8932871ee566788ba7bbc9a0..3bccadb2604714296f4ccd6ac88a039f17202fb3 100644 --- a/plugin/dapp/privacy/wallet/exec.go +++ b/plugin/dapp/privacy/wallet/exec.go @@ -40,9 +40,10 @@ func (policy *privacyPolicy) On_CreateTransaction(req *privacytypes.ReqCreatePri return nil, err } + cfg := policy.getWalletOperate().GetAPI().GetConfig() //为空时增加自动设置 if req.GetAssetExec() == "coins" && req.GetTokenname() == "" { - req.Tokenname = types.GetCoinSymbol() + req.Tokenname = cfg.GetCoinSymbol() } if req.AssetExec == "" || req.Tokenname == "" { diff --git a/plugin/dapp/privacy/wallet/privacy.go b/plugin/dapp/privacy/wallet/privacy.go index 40fe85384ed8a0e926903a4221a812036e4f4478..6634118427560f8ee7fd0bf623f8ecc83b9c7c45 100644 --- a/plugin/dapp/privacy/wallet/privacy.go +++ b/plugin/dapp/privacy/wallet/privacy.go @@ -526,24 +526,24 @@ func (policy *privacyPolicy) createPublic2PrivacyTx(req *privacytypes.ReqCreateP Output: privacyOutput, AssetExec: req.GetAssetExec(), } - + cfg := policy.getWalletOperate().GetAPI().GetConfig() action := &privacytypes.PrivacyAction{ Ty: privacytypes.ActionPublic2Privacy, Value: &privacytypes.PrivacyAction_Public2Privacy{Public2Privacy: value}, } tx := &types.Transaction{ - Execer: []byte(types.ExecName(privacytypes.PrivacyX)), + Execer: []byte(cfg.ExecName(privacytypes.PrivacyX)), Payload: types.Encode(action), Nonce: policy.getWalletOperate().Nonce(), - To: address.ExecAddress(types.ExecName(privacytypes.PrivacyX)), + To: address.ExecAddress(cfg.ExecName(privacytypes.PrivacyX)), } - tx.SetExpire(time.Duration(req.Expire)) + tx.SetExpire(cfg, time.Duration(req.Expire)) tx.Signature = &types.Signature{ Signature: types.Encode(&privacytypes.PrivacySignatureParam{ ActionType: action.Ty, }), } - tx.Fee, err = tx.GetRealFee(types.GInt("MinFee")) + tx.Fee, err = tx.GetRealFee(cfg.GInt("MinFee")) if err != nil { bizlog.Error("createPublic2PrivacyTx", "calc fee failed", err) return nil, err @@ -556,7 +556,8 @@ func (policy *privacyPolicy) createPrivacy2PrivacyTx(req *privacytypes.ReqCreate //需要燃烧的utxo var utxoBurnedAmount int64 - isMainetCoins := !types.IsPara() && (req.AssetExec == "coins") + cfg := policy.getWalletOperate().GetAPI().GetConfig() + isMainetCoins := !cfg.IsPara() && (req.AssetExec == "coins") if isMainetCoins { utxoBurnedAmount = privacytypes.PrivacyTxFee } @@ -613,15 +614,15 @@ func (policy *privacyPolicy) createPrivacy2PrivacyTx(req *privacytypes.ReqCreate } tx := &types.Transaction{ - Execer: []byte(types.ExecName(privacytypes.PrivacyX)), + Execer: []byte(cfg.ExecName(privacytypes.PrivacyX)), Payload: types.Encode(action), Fee: privacytypes.PrivacyTxFee, Nonce: policy.getWalletOperate().Nonce(), - To: address.ExecAddress(types.ExecName(privacytypes.PrivacyX)), + To: address.ExecAddress(cfg.ExecName(privacytypes.PrivacyX)), } - tx.SetExpire(time.Duration(req.Expire)) + tx.SetExpire(cfg, time.Duration(req.Expire)) if !isMainetCoins { - tx.Fee, err = tx.GetRealFee(types.GInt("MinFee")) + tx.Fee, err = tx.GetRealFee(cfg.GInt("MinFee")) if err != nil { bizlog.Error("createPrivacy2PrivacyTx", "calc fee failed", err) return nil, err @@ -645,7 +646,8 @@ func (policy *privacyPolicy) createPrivacy2PublicTx(req *privacytypes.ReqCreateP //需要燃烧的utxo //需要燃烧的utxo var utxoBurnedAmount int64 - isMainetCoins := !types.IsPara() && (req.AssetExec == "coins") + cfg := policy.getWalletOperate().GetAPI().GetConfig() + isMainetCoins := !cfg.IsPara() && (req.AssetExec == "coins") if isMainetCoins { utxoBurnedAmount = privacytypes.PrivacyTxFee } @@ -701,15 +703,15 @@ func (policy *privacyPolicy) createPrivacy2PublicTx(req *privacytypes.ReqCreateP } tx := &types.Transaction{ - Execer: []byte(types.ExecName(privacytypes.PrivacyX)), + Execer: []byte(cfg.ExecName(privacytypes.PrivacyX)), Payload: types.Encode(action), Fee: privacytypes.PrivacyTxFee, Nonce: policy.getWalletOperate().Nonce(), - To: address.ExecAddress(types.ExecName(privacytypes.PrivacyX)), + To: address.ExecAddress(cfg.ExecName(privacytypes.PrivacyX)), } - tx.SetExpire(time.Duration(req.Expire)) + tx.SetExpire(cfg, time.Duration(req.Expire)) if !isMainetCoins { - tx.Fee, err = tx.GetRealFee(types.GInt("MinFee")) + tx.Fee, err = tx.GetRealFee(cfg.GInt("MinFee")) if err != nil { bizlog.Error("createPrivacy2PublicTx", "calc fee failed", err) return nil, err @@ -812,7 +814,8 @@ func (policy *privacyPolicy) reqUtxosByAddr(addrs []string) { } policy.store.saveREscanUTXOsAddresses(storeAddrs) - reqAddr := address.ExecAddress(types.ExecName(privacytypes.PrivacyX)) + cfg := policy.getWalletOperate().GetAPI().GetConfig() + reqAddr := address.ExecAddress(cfg.ExecName(privacytypes.PrivacyX)) var txInfo types.ReplyTxInfo i := 0 operater := policy.getWalletOperate() @@ -836,7 +839,7 @@ func (policy *privacyPolicy) reqUtxosByAddr(addrs []string) { } else { ReqAddr.Height = txInfo.GetHeight() ReqAddr.Index = txInfo.GetIndex() - if !types.IsDappFork(ReqAddr.Height, privacytypes.PrivacyX, "ForkV21Privacy") { // 小于隐私分叉高度不做扫描 + if !cfg.IsDappFork(ReqAddr.Height, privacytypes.PrivacyX, "ForkV21Privacy") { // 小于隐私分叉高度不做扫描 break } } @@ -947,13 +950,13 @@ func (policy *privacyPolicy) signatureTx(tx *types.Transaction, privacyInput *pr } ringSign.Items[i] = item } - + cfg := policy.getWalletOperate().GetAPI().GetConfig() ringSignData := types.Encode(ringSign) tx.Signature = &types.Signature{ Ty: privacytypes.RingBaseonED25519, Signature: ringSignData, // 这里填的是隐私合约的公钥,让框架保持一致 - Pubkey: address.ExecPubKey(types.ExecName(privacytypes.PrivacyX)), + Pubkey: address.ExecPubKey(cfg.ExecName(privacytypes.PrivacyX)), } return nil } @@ -1048,6 +1051,7 @@ func (policy *privacyPolicy) addDelPrivacyTxsFromBlock(tx *types.Transaction, in return } + cfg := policy.getWalletOperate().GetAPI().GetConfig() txExecRes := block.Receipts[index].Ty var privateAction privacytypes.PrivacyAction if err := types.Decode(tx.GetPayload(), &privateAction); err != nil { @@ -1101,7 +1105,7 @@ func (policy *privacyPolicy) addDelPrivacyTxsFromBlock(tx *types.Transaction, in Owner: *info.Addr, Height: block.Block.Height, Txindex: index, - Blockhash: block.Block.Hash(), + Blockhash: block.Block.Hash(cfg), } utxoGlobalIndex := &privacytypes.UTXOGlobalIndex{ diff --git a/plugin/dapp/relay/executor/relay.go b/plugin/dapp/relay/executor/relay.go index f49e43a6c9a674dadc3e4597f98a8e51483bd34c..2157c6e1c9b6018efdfd1e84d2b9a7e36b07ce60 100644 --- a/plugin/dapp/relay/executor/relay.go +++ b/plugin/dapp/relay/executor/relay.go @@ -15,7 +15,6 @@ import ( var relaylog = log.New("module", "execs.relay") var driverName = "relay" -var subconfig = types.ConfSub(driverName) // Init relay register driver diff --git a/plugin/dapp/relay/executor/relaydb.go b/plugin/dapp/relay/executor/relaydb.go index d2f935a69376d6716d10ac3453eaaa10522f80f3..dd5473de3441b96a8d8c72cd2dbd2d94d47387e3 100644 --- a/plugin/dapp/relay/executor/relaydb.go +++ b/plugin/dapp/relay/executor/relaydb.go @@ -15,6 +15,7 @@ import ( "github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/types" ty "github.com/33cn/plugin/plugin/dapp/relay/types" + "github.com/33cn/chain33/client" ) const ( @@ -90,6 +91,7 @@ type relayDB struct { height int64 execAddr string btc *btcStore + api client.QueueProtocolAPI } func newRelayDB(r *relay, tx *types.Transaction) *relayDB { @@ -97,7 +99,7 @@ func newRelayDB(r *relay, tx *types.Transaction) *relayDB { fromAddr := tx.From() btc := newBtcStore(r.GetLocalDB()) return &relayDB{r.GetCoinsAccount(), r.GetStateDB(), hash, - fromAddr, r.GetBlockTime(), r.GetHeight(), dapp.ExecAddress(string(tx.Execer)), btc} + fromAddr, r.GetBlockTime(), r.GetHeight(), dapp.ExecAddress(string(tx.Execer)), btc, r.GetAPI()} } func (action *relayDB) getOrderByID(orderID []byte) (*ty.RelayOrder, error) { @@ -676,6 +678,8 @@ func (action *relayDB) saveBtcHeader(headers *ty.BtcHeaders, localDb dbm.KVDB) ( var preHead = &ty.RelayLastRcvBtcHeader{} var receipt = &ty.ReceiptRelayRcvBTCHeaders{} + cfg := action.api.GetConfig() + subconfig := types.ConfSub(cfg, driverName) if action.fromAddr != subconfig.GStr("genesis") { return nil, types.ErrFromAddr } diff --git a/plugin/dapp/relay/rpc/rpc.go b/plugin/dapp/relay/rpc/rpc.go index 432839cda54a5b9f94365a42cd230e4255914d5c..e2baf15a940e1d47cfacab4b6f153dbdf590f730 100644 --- a/plugin/dapp/relay/rpc/rpc.go +++ b/plugin/dapp/relay/rpc/rpc.go @@ -11,37 +11,37 @@ import ( ty "github.com/33cn/plugin/plugin/dapp/relay/types" ) -func createRawRelayOrderTx(parm *ty.RelayCreate) ([]byte, error) { +func createRawRelayOrderTx(cfg *types.Chain33Config, parm *ty.RelayCreate) ([]byte, error) { if parm == nil { return nil, types.ErrInvalidParam } v := *parm - return types.CallCreateTx(types.ExecName(ty.RelayX), "Create", &v) + return types.CallCreateTx(cfg, cfg.ExecName(ty.RelayX), "Create", &v) } -func createRawRelayAcceptTx(parm *ty.RelayAccept) ([]byte, error) { +func createRawRelayAcceptTx(cfg *types.Chain33Config, parm *ty.RelayAccept) ([]byte, error) { if parm == nil { return nil, types.ErrInvalidParam } - return types.CallCreateTx(types.ExecName(ty.RelayX), "Accept", parm) + return types.CallCreateTx(cfg, cfg.ExecName(ty.RelayX), "Accept", parm) } -func createRawRelayRevokeTx(parm *ty.RelayRevoke) ([]byte, error) { +func createRawRelayRevokeTx(cfg *types.Chain33Config, parm *ty.RelayRevoke) ([]byte, error) { if parm == nil { return nil, types.ErrInvalidParam } - return types.CallCreateTx(types.ExecName(ty.RelayX), "Revoke", parm) + return types.CallCreateTx(cfg, cfg.ExecName(ty.RelayX), "Revoke", parm) } -func createRawRelayConfirmTx(parm *ty.RelayConfirmTx) ([]byte, error) { +func createRawRelayConfirmTx(cfg *types.Chain33Config, parm *ty.RelayConfirmTx) ([]byte, error) { if parm == nil { return nil, types.ErrInvalidParam } - return types.CallCreateTx(types.ExecName(ty.RelayX), "ConfirmTx", parm) + return types.CallCreateTx(cfg, cfg.ExecName(ty.RelayX), "ConfirmTx", parm) } -func createRawRelaySaveBTCHeadTx(parm *ty.BtcHeader) ([]byte, error) { +func createRawRelaySaveBTCHeadTx(cfg *types.Chain33Config, parm *ty.BtcHeader) ([]byte, error) { if parm == nil { return nil, types.ErrInvalidParam } @@ -59,12 +59,13 @@ func createRawRelaySaveBTCHeadTx(parm *ty.BtcHeader) ([]byte, error) { v := &ty.BtcHeaders{} v.BtcHeader = append(v.BtcHeader, head) - return types.CallCreateTx(types.ExecName(ty.RelayX), "BtcHeaders", v) + return types.CallCreateTx(cfg, cfg.ExecName(ty.RelayX), "BtcHeaders", v) } //CreateRawRelayOrderTx jrpc create raw relay order func (c *Jrpc) CreateRawRelayOrderTx(in *ty.RelayCreate, result *interface{}) error { - reply, err := createRawRelayOrderTx(in) + cfg := c.cli.GetConfig() + reply, err := createRawRelayOrderTx(cfg, in) if err != nil { return err } @@ -74,7 +75,8 @@ func (c *Jrpc) CreateRawRelayOrderTx(in *ty.RelayCreate, result *interface{}) er //CreateRawRelayAcceptTx jrpc creat relay accept tx func (c *Jrpc) CreateRawRelayAcceptTx(in *ty.RelayAccept, result *interface{}) error { - reply, err := createRawRelayAcceptTx(in) + cfg := c.cli.GetConfig() + reply, err := createRawRelayAcceptTx(cfg, in) if err != nil { return err } @@ -85,7 +87,8 @@ func (c *Jrpc) CreateRawRelayAcceptTx(in *ty.RelayAccept, result *interface{}) e //CreateRawRelayRevokeTx jrpc create revoke tx func (c *Jrpc) CreateRawRelayRevokeTx(in *ty.RelayRevoke, result *interface{}) error { - reply, err := createRawRelayRevokeTx(in) + cfg := c.cli.GetConfig() + reply, err := createRawRelayRevokeTx(cfg, in) if err != nil { return err } @@ -96,7 +99,8 @@ func (c *Jrpc) CreateRawRelayRevokeTx(in *ty.RelayRevoke, result *interface{}) e //CreateRawRelayConfirmTx jrpc create confirm tx func (c *Jrpc) CreateRawRelayConfirmTx(in *ty.RelayConfirmTx, result *interface{}) error { - reply, err := createRawRelayConfirmTx(in) + cfg := c.cli.GetConfig() + reply, err := createRawRelayConfirmTx(cfg, in) if err != nil { return err } @@ -107,7 +111,8 @@ func (c *Jrpc) CreateRawRelayConfirmTx(in *ty.RelayConfirmTx, result *interface{ //CreateRawRelaySaveBTCHeadTx jrpc save btc header func (c *Jrpc) CreateRawRelaySaveBTCHeadTx(in *ty.BtcHeader, result *interface{}) error { - reply, err := createRawRelaySaveBTCHeadTx(in) + cfg := c.cli.GetConfig() + reply, err := createRawRelaySaveBTCHeadTx(cfg, in) if err != nil { return err } diff --git a/plugin/dapp/retrieve/executor/exec_del_local.go b/plugin/dapp/retrieve/executor/exec_del_local.go index 1b23c2c95e38bacf4102504be45b39070c81952b..f577df063ccb3a0c9e1b473cf8606f8ae607fa66 100755 --- a/plugin/dapp/retrieve/executor/exec_del_local.go +++ b/plugin/dapp/retrieve/executor/exec_del_local.go @@ -94,10 +94,10 @@ func (c *Retrieve) ExecDelLocal_Perform(perf *rt.PerformRetrieve, tx *types.Tran if err != nil { return set, nil } - - if types.IsDappFork(c.GetHeight(), rt.RetrieveX, rt.ForkRetriveAssetX) { + cfg := c.GetAPI().GetConfig() + if cfg.IsDappFork(c.GetHeight(), rt.RetrieveX, rt.ForkRetriveAssetX) { if len(perf.Assets) == 0 { - perf.Assets = append(perf.Assets, &rt.AssetSymbol{Exec: "coins", Symbol: types.GetCoinSymbol()}) + perf.Assets = append(perf.Assets, &rt.AssetSymbol{Exec: "coins", Symbol: cfg.GetCoinSymbol()}) } } for _, asset := range perf.Assets { diff --git a/plugin/dapp/retrieve/executor/exec_local.go b/plugin/dapp/retrieve/executor/exec_local.go index ba8f977ed7a6e8611262a0a38556482ff0f0992a..0b610b40e0241876408a727109a3903437252917 100755 --- a/plugin/dapp/retrieve/executor/exec_local.go +++ b/plugin/dapp/retrieve/executor/exec_local.go @@ -102,9 +102,10 @@ func (c *Retrieve) ExecLocal_Perform(perf *rt.PerformRetrieve, tx *types.Transac if err != nil { return set, nil } - if types.IsDappFork(c.GetHeight(), rt.RetrieveX, rt.ForkRetriveAssetX) { + cfg := c.GetAPI().GetConfig() + if cfg.IsDappFork(c.GetHeight(), rt.RetrieveX, rt.ForkRetriveAssetX) { if len(perf.Assets) == 0 { - perf.Assets = append(perf.Assets, &rt.AssetSymbol{Exec: "coins", Symbol: types.GetCoinSymbol()}) + perf.Assets = append(perf.Assets, &rt.AssetSymbol{Exec: "coins", Symbol: cfg.GetCoinSymbol()}) } } for _, asset := range perf.Assets { diff --git a/plugin/dapp/retrieve/executor/retrievedb.go b/plugin/dapp/retrieve/executor/retrievedb.go index b030e97171571de774493b019930b4e0fb7ff561..4acb94605d80a8316263e13c52f1e85f2e2078ce 100755 --- a/plugin/dapp/retrieve/executor/retrievedb.go +++ b/plugin/dapp/retrieve/executor/retrievedb.go @@ -15,6 +15,7 @@ import ( //log "github.com/33cn/chain33/common/log/log15" "github.com/33cn/chain33/system/dapp" rt "github.com/33cn/plugin/plugin/dapp/retrieve/types" + "github.com/33cn/chain33/client" ) const ( @@ -99,6 +100,7 @@ type Action struct { blocktime int64 height int64 execaddr string + api client.QueueProtocolAPI } // NewRetrieveAcction gen instance @@ -106,7 +108,7 @@ func NewRetrieveAcction(r *Retrieve, tx *types.Transaction) *Action { hash := tx.Hash() fromaddr := tx.From() return &Action{r.GetCoinsAccount(), r.GetStateDB(), hash, fromaddr, - r.GetBlockTime(), r.GetHeight(), dapp.ExecAddress(string(tx.Execer))} + r.GetBlockTime(), r.GetHeight(), dapp.ExecAddress(string(tx.Execer)), r.GetAPI()} } // RetrieveBackup Action @@ -116,7 +118,8 @@ func (action *Action) RetrieveBackup(backupRet *rt.BackupRetrieve) (*types.Recei var receipt *types.Receipt var r *DB var newRetrieve = false - if types.IsDappFork(action.height, rt.RetrieveX, rt.ForkRetriveX) { + cfg := action.api.GetConfig() + if cfg.IsDappFork(action.height, rt.RetrieveX, rt.ForkRetriveX) { if err := address.CheckAddress(backupRet.BackupAddress); err != nil { rlog.Debug("retrieve checkaddress") return nil, err @@ -208,10 +211,10 @@ func (action *Action) RetrievePerformAssets(perfRet *rt.PerformRetrieve, default var logs []*types.ReceiptLog var kv []*types.KeyValue var receipt *types.Receipt - + cfg := action.api.GetConfig() // 兼容原来的找回, 在不指定的情况下,找回主币 if len(perfRet.Assets) == 0 { - perfRet.Assets = append(perfRet.Assets, &rt.AssetSymbol{Exec: "coins", Symbol: types.GetCoinSymbol()}) + perfRet.Assets = append(perfRet.Assets, &rt.AssetSymbol{Exec: "coins", Symbol: cfg.GetCoinSymbol()}) //return nil, nil } @@ -248,6 +251,7 @@ func (action *Action) RetrievePerform(perfRet *rt.PerformRetrieve) (*types.Recei var index int var related bool var acc *types.Account + cfg := action.api.GetConfig() retrieve, err := readRetrieve(action.db, perfRet.BackupAddress) if err != nil { @@ -276,7 +280,7 @@ func (action *Action) RetrievePerform(perfRet *rt.PerformRetrieve) (*types.Recei return nil, rt.ErrRetrievePeriodLimit } - if types.IsDappFork(action.height, rt.RetrieveX, rt.ForkRetriveAssetX) { + if cfg.IsDappFork(action.height, rt.RetrieveX, rt.ForkRetriveAssetX) { return action.RetrievePerformAssets(perfRet, r.RetPara[index].DefaultAddress) } diff --git a/plugin/dapp/retrieve/rpc/rpc.go b/plugin/dapp/retrieve/rpc/rpc.go index 372da16e79e54a6ad757ef03e4f5faa159150895..5a0a3ad12c87939f88cab9750cd805e0c120ae19 100755 --- a/plugin/dapp/retrieve/rpc/rpc.go +++ b/plugin/dapp/retrieve/rpc/rpc.go @@ -16,7 +16,8 @@ func (c *channelClient) Backup(ctx context.Context, v *rt.BackupRetrieve) (*type Ty: rt.RetrieveActionBackup, Value: &rt.RetrieveAction_Backup{Backup: v}, } - tx, err := types.CreateFormatTx(types.ExecName(rt.RetrieveX), types.Encode(backup)) + cfg := c.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(rt.RetrieveX), types.Encode(backup)) if err != nil { return nil, err } @@ -29,7 +30,8 @@ func (c *channelClient) Prepare(ctx context.Context, v *rt.PrepareRetrieve) (*ty Ty: rt.RetrieveActionPrepare, Value: &rt.RetrieveAction_Prepare{Prepare: v}, } - tx, err := types.CreateFormatTx(types.ExecName(rt.RetrieveX), types.Encode(prepare)) + cfg := c.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(rt.RetrieveX), types.Encode(prepare)) if err != nil { return nil, err } @@ -44,7 +46,8 @@ func (c *channelClient) Perform(ctx context.Context, v *rt.PerformRetrieve) (*ty Value: &rt.RetrieveAction_Perform{Perform: v}, } payload := types.Encode(perform) - tx, err := types.CreateFormatTx(types.ExecName(rt.RetrieveX), payload) + cfg := c.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(rt.RetrieveX), payload) if err != nil { return nil, err } @@ -58,7 +61,8 @@ func (c *channelClient) Cancel(ctx context.Context, v *rt.CancelRetrieve) (*type Ty: rt.RetrieveActionCancel, Value: &rt.RetrieveAction_Cancel{Cancel: v}, } - tx, err := types.CreateFormatTx(types.ExecName(rt.RetrieveX), types.Encode(cancel)) + cfg := c.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(rt.RetrieveX), types.Encode(cancel)) if err != nil { return nil, err } diff --git a/plugin/dapp/ticket/executor/ticketdb.go b/plugin/dapp/ticket/executor/ticketdb.go index 6bdd2e876eda8829a05ee3c735252f172f8c1ed7..c28f650b2ac8fd5bc19d4edfc36cfd9bddeb1273 100644 --- a/plugin/dapp/ticket/executor/ticketdb.go +++ b/plugin/dapp/ticket/executor/ticketdb.go @@ -21,6 +21,7 @@ import ( "github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/types" ty "github.com/33cn/plugin/plugin/dapp/ticket/types" + "github.com/33cn/chain33/client" ) var tlog = log.New("module", "ticket.db") @@ -35,16 +36,16 @@ type DB struct { } //GetRealPrice 获取真实的价格 -func (t *DB) GetRealPrice() int64 { +func (t *DB) GetRealPrice(cfg *types.Chain33Config) int64 { if t.GetPrice() == 0 { - cfg := ty.GetTicketMinerParam(types.GetFork("ForkChainParamV1")) + cfg := ty.GetTicketMinerParam(cfg, cfg.GetFork("ForkChainParamV1")) return cfg.TicketPrice } return t.GetPrice() } // NewDB new instance -func NewDB(id, minerAddress, returnWallet string, blocktime, height, price int64, isGenesis bool) *DB { +func NewDB(cfg *types.Chain33Config, id, minerAddress, returnWallet string, blocktime, height, price int64, isGenesis bool) *DB { t := &DB{} t.TicketId = id t.MinerAddress = minerAddress @@ -54,7 +55,7 @@ func NewDB(id, minerAddress, returnWallet string, blocktime, height, price int64 t.IsGenesis = isGenesis t.prevstatus = 0 //height == 0 的情况下,不去改变 genesis block - if types.IsFork(height, "ForkChainParamV2") && height > 0 { + if cfg.IsFork(height, "ForkChainParamV2") && height > 0 { t.Price = price } return t @@ -126,6 +127,7 @@ type Action struct { blocktime int64 height int64 execaddr string + api client.QueueProtocolAPI } // NewAction new action type @@ -133,19 +135,20 @@ func NewAction(t *Ticket, tx *types.Transaction) *Action { hash := tx.Hash() fromaddr := tx.From() return &Action{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr, - t.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer))} + t.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI()} } // GenesisInit init genesis func (action *Action) GenesisInit(genesis *ty.TicketGenesis) (*types.Receipt, error) { + chain33Cfg := action.api.GetConfig() prefix := common.ToHex(action.txhash) prefix = genesis.MinerAddress + ":" + prefix + ":" var logs []*types.ReceiptLog var kv []*types.KeyValue - cfg := ty.GetTicketMinerParam(action.height) + cfg := ty.GetTicketMinerParam(chain33Cfg, action.height) for i := 0; i < int(genesis.Count); i++ { id := prefix + fmt.Sprintf("%010d", i) - t := NewDB(id, genesis.MinerAddress, genesis.ReturnAddress, action.blocktime, action.height, cfg.TicketPrice, true) + t := NewDB(chain33Cfg, id, genesis.MinerAddress, genesis.ReturnAddress, action.blocktime, action.height, cfg.TicketPrice, true) //冻结子账户资金 receipt, err := action.coinsAccount.ExecFrozen(genesis.ReturnAddress, action.execaddr, cfg.TicketPrice) if err != nil { @@ -225,6 +228,7 @@ func (action *Action) TicketBind(tbind *ty.TicketBind) (*types.Receipt, error) { // TicketOpen ticket open func (action *Action) TicketOpen(topen *ty.TicketOpen) (*types.Receipt, error) { + chain33Cfg := action.api.GetConfig() prefix := common.ToHex(action.txhash) prefix = topen.MinerAddress + ":" + prefix + ":" var logs []*types.ReceiptLog @@ -240,17 +244,17 @@ func (action *Action) TicketOpen(topen *ty.TicketOpen) (*types.Receipt, error) { } } //action.fromaddr == topen.ReturnAddress or mineraddr == action.fromaddr - cfg := ty.GetTicketMinerParam(action.height) + cfg := ty.GetTicketMinerParam(chain33Cfg, action.height) for i := 0; i < int(topen.Count); i++ { id := prefix + fmt.Sprintf("%010d", i) //add pubHash - if types.IsDappFork(action.height, ty.TicketX, "ForkTicketId") { + if chain33Cfg.IsDappFork(action.height, ty.TicketX, "ForkTicketId") { if len(topen.PubHashes) == 0 { return nil, ty.ErrOpenTicketPubHash } id = id + ":" + fmt.Sprintf("%x:%d", topen.PubHashes[i], topen.RandSeed) } - t := NewDB(id, topen.MinerAddress, topen.ReturnAddress, action.blocktime, action.height, cfg.TicketPrice, false) + t := NewDB(chain33Cfg, id, topen.MinerAddress, topen.ReturnAddress, action.blocktime, action.height, cfg.TicketPrice, false) //冻结子账户资金 receipt, err := action.coinsAccount.ExecFrozen(topen.ReturnAddress, action.execaddr, cfg.TicketPrice) @@ -296,6 +300,7 @@ func (action *Action) TicketMiner(miner *ty.TicketMiner, index int) (*types.Rece if index != 0 { return nil, types.ErrCoinBaseIndex } + chain33Cfg := action.api.GetConfig() ticket, err := readTicket(action.db, miner.TicketId) if err != nil { return nil, err @@ -303,7 +308,7 @@ func (action *Action) TicketMiner(miner *ty.TicketMiner, index int) (*types.Rece if ticket.Status != 1 { return nil, types.ErrCoinBaseTicketStatus } - cfg := ty.GetTicketMinerParam(action.height) + cfg := ty.GetTicketMinerParam(chain33Cfg, action.height) if !ticket.IsGenesis { if action.blocktime-ticket.GetCreateTime() < cfg.TicketFrozenTime { return nil, ty.ErrTime @@ -314,7 +319,7 @@ func (action *Action) TicketMiner(miner *ty.TicketMiner, index int) (*types.Rece return nil, types.ErrFromAddr } //check pubHash and privHash - if !types.IsDappFork(action.height, ty.TicketX, "ForkTicketId") { + if !chain33Cfg.IsDappFork(action.height, ty.TicketX, "ForkTicketId") { miner.PrivHash = nil } if len(miner.PrivHash) != 0 { @@ -327,32 +332,32 @@ func (action *Action) TicketMiner(miner *ty.TicketMiner, index int) (*types.Rece prevstatus := ticket.Status ticket.Status = 2 ticket.MinerValue = miner.Reward - if types.IsFork(action.height, "ForkMinerTime") { + if chain33Cfg.IsFork(action.height, "ForkMinerTime") { ticket.MinerTime = action.blocktime } t := &DB{*ticket, prevstatus} var logs []*types.ReceiptLog var kv []*types.KeyValue //user - receipt1, err := action.coinsAccount.ExecDepositFrozen(t.ReturnAddress, action.execaddr, ticket.MinerValue) + receipt1, err := action.coinsAccount.ExecDepositFrozen(chain33Cfg, t.ReturnAddress, action.execaddr, ticket.MinerValue) if err != nil { tlog.Error("TicketMiner.ExecDepositFrozen user", "addr", t.ReturnAddress, "execaddr", action.execaddr) return nil, err } //fund var receipt2 *types.Receipt - if types.IsFork(action.height, "ForkTicketFundAddrV1") { + if chain33Cfg.IsFork(action.height, "ForkTicketFundAddrV1") { // issue coins to exec addr - addr := types.MGStr("mver.consensus.fundKeyAddr", action.height) - receipt2, err = action.coinsAccount.ExecIssueCoins(addr, cfg.CoinDevFund) + addr := chain33Cfg.MGStr("mver.consensus.fundKeyAddr", action.height) + receipt2, err = action.coinsAccount.ExecIssueCoins(chain33Cfg, addr, cfg.CoinDevFund) if err != nil { tlog.Error("TicketMiner.ExecDepositFrozen fund to autonomy fund", "addr", addr, "error", err) return nil, err } } else { - receipt2, err = action.coinsAccount.ExecDepositFrozen(types.GetFundAddr(), action.execaddr, cfg.CoinDevFund) + receipt2, err = action.coinsAccount.ExecDepositFrozen(chain33Cfg, chain33Cfg.GetFundAddr(), action.execaddr, cfg.CoinDevFund) if err != nil { - tlog.Error("TicketMiner.ExecDepositFrozen fund", "addr", types.GetFundAddr(), "execaddr", action.execaddr, "error", err) + tlog.Error("TicketMiner.ExecDepositFrozen fund", "addr", chain33Cfg.GetFundAddr(), "execaddr", action.execaddr, "error", err) return nil, err } } @@ -369,8 +374,9 @@ func (action *Action) TicketMiner(miner *ty.TicketMiner, index int) (*types.Rece // TicketClose close tick func (action *Action) TicketClose(tclose *ty.TicketClose) (*types.Receipt, error) { + chain33Cfg := action.api.GetConfig() tickets := make([]*DB, len(tclose.TicketId)) - cfg := ty.GetTicketMinerParam(action.height) + cfg := ty.GetTicketMinerParam(chain33Cfg, action.height) for i := 0; i < len(tclose.TicketId); i++ { ticket, err := readTicket(action.db, tclose.TicketId[i]) if err != nil { @@ -409,7 +415,7 @@ func (action *Action) TicketClose(tclose *ty.TicketClose) (*types.Receipt, error if t.prevstatus == 1 { t.MinerValue = 0 } - retValue := t.GetRealPrice() + t.MinerValue + retValue := t.GetRealPrice(chain33Cfg) + t.MinerValue receipt1, err := action.coinsAccount.ExecActive(t.ReturnAddress, action.execaddr, retValue) if err != nil { tlog.Error("TicketClose.ExecActive user", "addr", t.ReturnAddress, "execaddr", action.execaddr, "value", retValue) @@ -421,10 +427,10 @@ func (action *Action) TicketClose(tclose *ty.TicketClose) (*types.Receipt, error kv = append(kv, receipt1.KV...) //如果ticket 已经挖矿成功了,那么要解冻发展基金部分币 if t.prevstatus == 2 { - if !types.IsFork(action.height, "ForkTicketFundAddrV1") { - receipt2, err := action.coinsAccount.ExecActive(types.GetFundAddr(), action.execaddr, cfg.CoinDevFund) + if !chain33Cfg.IsFork(action.height, "ForkTicketFundAddrV1") { + receipt2, err := action.coinsAccount.ExecActive(chain33Cfg.GetFundAddr(), action.execaddr, cfg.CoinDevFund) if err != nil { - tlog.Error("TicketClose.ExecActive fund", "addr", types.GetFundAddr(), "execaddr", action.execaddr, "value", retValue) + tlog.Error("TicketClose.ExecActive fund", "addr", chain33Cfg.GetFundAddr(), "execaddr", action.execaddr, "value", retValue) return nil, err } logs = append(logs, receipt2.Logs...) diff --git a/plugin/dapp/ticket/executor/ticketnum.go b/plugin/dapp/ticket/executor/ticketnum.go index 7c5ae535407d74254549053a1497121b19238457..86321f6a6e105050af70ad3580a3cd5267047c7a 100755 --- a/plugin/dapp/ticket/executor/ticketnum.go +++ b/plugin/dapp/ticket/executor/ticketnum.go @@ -97,8 +97,9 @@ func (ticket *Ticket) getTxActions(blockHash []byte, blockNum int64) ([]*tickett tlog.Error("getTxActions", "blockHash", blockHash, "blockNum", blockNum, "err", err) return txActions, err } + cfg := ticket.GetAPI().GetConfig() for _, block := range blockDetails.Items { - tlog.Debug("getTxActions", "blockHeight", block.Block.Height, "blockhash", common.ToHex(block.Block.Hash())) + tlog.Debug("getTxActions", "blockHeight", block.Block.Height, "blockhash", common.ToHex(block.Block.Hash(cfg))) ticketAction, err := ticket.getMinerTx(block.Block) if err != nil { return txActions, err diff --git a/plugin/dapp/ticket/rpc/rpc.go b/plugin/dapp/ticket/rpc/rpc.go index 41f5bb86ba93e4912ebe9aff6afdbf1cb96a0cf5..7215567ec79584433ce404948fe7529ca37985e6 100644 --- a/plugin/dapp/ticket/rpc/rpc.go +++ b/plugin/dapp/ticket/rpc/rpc.go @@ -13,12 +13,12 @@ import ( context "golang.org/x/net/context" ) -func bindMiner(param *ty.ReqBindMiner) (*ty.ReplyBindMiner, error) { +func bindMiner(cfg *types.Chain33Config, param *ty.ReqBindMiner) (*ty.ReplyBindMiner, error) { tBind := &ty.TicketBind{ MinerAddress: param.BindAddr, ReturnAddress: param.OriginAddr, } - data, err := types.CallCreateTx(types.ExecName(ty.TicketX), "Tbind", tBind) + data, err := types.CallCreateTx(cfg, cfg.ExecName(ty.TicketX), "Tbind", tBind) if err != nil { return nil, err } @@ -32,7 +32,8 @@ func (g *channelClient) CreateBindMiner(ctx context.Context, in *ty.ReqBindMiner if err != nil { return nil, err } - if in.Amount%ty.GetTicketMinerParam(header.Height).TicketPrice != 0 || in.Amount < 0 { + cfg := g.GetConfig() + if in.Amount%ty.GetTicketMinerParam(cfg, header.Height).TicketPrice != 0 || in.Amount < 0 { return nil, types.ErrAmount } err = address.CheckAddress(in.BindAddr) @@ -57,7 +58,7 @@ func (g *channelClient) CreateBindMiner(ctx context.Context, in *ty.ReqBindMiner return nil, types.ErrNoBalance } } - return bindMiner(in) + return bindMiner(cfg, in) } // SetAutoMining set auto mining diff --git a/plugin/dapp/ticket/types/ticket.go b/plugin/dapp/ticket/types/ticket.go index e383e794f1ad8de904aa870c6985653b7e317801..043d9c8fa65eb61dd85a433123a30c3db8e12fcd 100755 --- a/plugin/dapp/ticket/types/ticket.go +++ b/plugin/dapp/ticket/types/ticket.go @@ -146,8 +146,8 @@ type TicketMinerParam struct { } // GetTicketMinerParam 获取ticket miner config params -func GetTicketMinerParam(height int64) *TicketMinerParam { - conf := types.Conf("mver.consensus.ticket") +func GetTicketMinerParam(cfg *types.Chain33Config, height int64) *TicketMinerParam { + conf := types.Conf(cfg, "mver.consensus.ticket") c := &TicketMinerParam{} c.CoinDevFund = conf.MGInt("coinDevFund", height) * types.Coin c.CoinReward = conf.MGInt("coinReward", height) * types.Coin diff --git a/plugin/dapp/ticket/wallet/ticket.go b/plugin/dapp/ticket/wallet/ticket.go index 89836acc22382b458ca1c05cd6109366b95a11e3..e99ca4e29911c35ba8ff5c03779755dd34c5fb31 100644 --- a/plugin/dapp/ticket/wallet/ticket.go +++ b/plugin/dapp/ticket/wallet/ticket.go @@ -402,7 +402,8 @@ func (policy *ticketPolicy) forceCloseTicketList(height int64, priv crypto.PrivK var ids []string var tl []*ty.Ticket now := types.Now().Unix() - cfg := ty.GetTicketMinerParam(height) + chain33Cfg := policy.walletOperate.GetAPI().GetConfig() + cfg := ty.GetTicketMinerParam(chain33Cfg, height) for _, t := range tlist { if !t.IsGenesis { if t.Status == 1 && now-t.GetCreateTime() < cfg.TicketWithdrawTime { @@ -496,7 +497,8 @@ func (policy *ticketPolicy) closeTicketsByAddr(height int64, priv crypto.PrivKey var ids []string var tl []*ty.Ticket now := types.Now().Unix() - cfg := ty.GetTicketMinerParam(height) + chain33Cfg := policy.walletOperate.GetAPI().GetConfig() + cfg := ty.GetTicketMinerParam(chain33Cfg, height) for _, t := range tlist { if !t.IsGenesis { if now-t.GetCreateTime() < cfg.TicketWithdrawTime { @@ -635,7 +637,8 @@ func (policy *ticketPolicy) buyTicketOne(height int64, priv crypto.PrivKey) ([]b } //留一个币作为手续费,如果手续费不够了,不能挖矿 //判断手续费是否足够,如果不足要及时补充。 - cfg := ty.GetTicketMinerParam(height) + chain33Cfg := policy.walletOperate.GetAPI().GetConfig() + cfg := ty.GetTicketMinerParam(chain33Cfg, height) fee := types.Coin if acc1.Balance+acc2.Balance-2*fee >= cfg.TicketPrice { // 如果可用余额+冻结余额,可以凑成新票,则转币到冻结余额 @@ -740,7 +743,8 @@ func (policy *ticketPolicy) buyMinerAddrTicketOne(height int64, priv crypto.Priv } total := 0 var hashes [][]byte - cfg := ty.GetTicketMinerParam(height) + chain33Cfg := policy.walletOperate.GetAPI().GetConfig() + cfg := ty.GetTicketMinerParam(chain33Cfg, height) for i := 0; i < len(addrs); i++ { bizlog.Info("sourceaddr", "addr", addrs[i]) ok := checkMinerWhiteList(addrs[i]) @@ -830,7 +834,8 @@ func (policy *ticketPolicy) autoMining() { defer operater.GetWaitGroup().Done() // 只有ticket共识下ticket相关的操作才有效 - q := types.Conf("config.consensus") + cfg := policy.walletOperate.GetAPI().GetConfig() + q := types.Conf(cfg, "config.consensus") if q != nil { cons := q.GStr("name") if strings.Compare(strings.TrimSpace(cons), ty.TicketX) != 0 { diff --git a/plugin/dapp/token/executor/exec.go b/plugin/dapp/token/executor/exec.go index bdf235d50cb68ceee9f577656e82a04fcd83981e..c93cdbb123c6a133fc9ae7e7d226aa985f745089 100644 --- a/plugin/dapp/token/executor/exec.go +++ b/plugin/dapp/token/executor/exec.go @@ -46,7 +46,8 @@ func (t *token) Exec_TokenPreCreate(payload *tokenty.TokenPreCreate, tx *types.T } func (t *token) Exec_TokenFinishCreate(payload *tokenty.TokenFinishCreate, tx *types.Transaction, index int) (*types.Receipt, error) { - action := newTokenAction(t, types.MGStr("mver.consensus.fundKeyAddr", t.GetHeight()), tx) + cfg := t.GetAPI().GetConfig() + action := newTokenAction(t, cfg.MGStr("mver.consensus.fundKeyAddr", t.GetHeight()), tx) return action.finishCreate(payload) } diff --git a/plugin/dapp/token/executor/token.go b/plugin/dapp/token/executor/token.go index a4161e5e7a5bbce51f8c895c602fe296cde04f74..d1dade8e9c9d06137970eee3628707d31ebcc751 100644 --- a/plugin/dapp/token/executor/token.go +++ b/plugin/dapp/token/executor/token.go @@ -33,7 +33,6 @@ const ( ) var driverName = "token" -var conf = types.ConfSub(driverName) type subConfig struct { SaveTokenTxList bool `json:"saveTokenTxList"` diff --git a/plugin/dapp/token/executor/tokendb.go b/plugin/dapp/token/executor/tokendb.go index d712ba9da475a9ba06430bd632f4a0167f104da7..8d2124fe6a58cdab47ab4c78d78d5f82dce42989 100644 --- a/plugin/dapp/token/executor/tokendb.go +++ b/plugin/dapp/token/executor/tokendb.go @@ -15,13 +15,14 @@ import ( "github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/types" pty "github.com/33cn/plugin/plugin/dapp/token/types" + "github.com/33cn/chain33/client" ) type tokenDB struct { token pty.Token } -func newTokenDB(preCreate *pty.TokenPreCreate, creator string, height int64) *tokenDB { +func newTokenDB(cfg *types.Chain33Config, preCreate *pty.TokenPreCreate, creator string, height int64) *tokenDB { t := &tokenDB{} t.token.Name = preCreate.GetName() t.token.Symbol = preCreate.GetSymbol() @@ -32,7 +33,7 @@ func newTokenDB(preCreate *pty.TokenPreCreate, creator string, height int64) *to t.token.Owner = preCreate.GetOwner() t.token.Creator = creator t.token.Status = pty.TokenStatusPreCreated - if types.IsDappFork(height, pty.TokenX, pty.ForkTokenSymbolWithNumberX) { + if cfg.IsDappFork(height, pty.TokenX, pty.ForkTokenSymbolWithNumberX) { t.token.Category = preCreate.Category } return t @@ -134,17 +135,19 @@ type tokenAction struct { blocktime int64 height int64 execaddr string + api client.QueueProtocolAPI } func newTokenAction(t *token, toaddr string, tx *types.Transaction) *tokenAction { hash := tx.Hash() fromaddr := tx.From() return &tokenAction{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr, toaddr, - t.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer))} + t.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI()} } func (action *tokenAction) preCreate(token *pty.TokenPreCreate) (*types.Receipt, error) { tokenlog.Debug("preCreate") + cfg := action.api.GetConfig() if token == nil { return nil, types.ErrInvalidParam } @@ -157,18 +160,18 @@ func (action *tokenAction) preCreate(token *pty.TokenPreCreate) (*types.Receipt, } else if token.GetTotal() > types.MaxTokenBalance || token.GetTotal() <= 0 { return nil, pty.ErrTokenTotalOverflow } - if types.IsDappFork(action.height, pty.TokenX, pty.ForkTokenCheckX) { + if cfg.IsDappFork(action.height, pty.TokenX, pty.ForkTokenCheckX) { if err := address.CheckAddress(token.Owner); err != nil { return nil, err } } - if !types.IsDappFork(action.height, pty.TokenX, pty.ForkTokenSymbolWithNumberX) { + if !cfg.IsDappFork(action.height, pty.TokenX, pty.ForkTokenSymbolWithNumberX) { if token.Category != 0 { return nil, types.ErrNotSupport } } - if !validSymbolWithHeight([]byte(token.GetSymbol()), action.height) { + if !validSymbolWithHeight(cfg, []byte(token.GetSymbol()), action.height) { tokenlog.Error("token precreate ", "symbol need be upper", token.GetSymbol()) return nil, pty.ErrTokenSymbolUpper } @@ -177,11 +180,11 @@ func (action *tokenAction) preCreate(token *pty.TokenPreCreate) (*types.Receipt, return nil, pty.ErrTokenExist } - if checkTokenHasPrecreateWithHeight(token.GetSymbol(), token.GetOwner(), action.db, action.height) { + if checkTokenHasPrecreateWithHeight(cfg, token.GetSymbol(), token.GetOwner(), action.db, action.height) { return nil, pty.ErrTokenHavePrecreated } - if types.IsDappFork(action.height, pty.TokenX, pty.ForkTokenBlackListX) { + if cfg.IsDappFork(action.height, pty.TokenX, pty.ForkTokenBlackListX) { found, err := inBlacklist(token.GetSymbol(), blacklist, action.db) if err != nil { return nil, err @@ -194,7 +197,7 @@ func (action *tokenAction) preCreate(token *pty.TokenPreCreate) (*types.Receipt, var logs []*types.ReceiptLog var kv []*types.KeyValue - if types.IsDappFork(action.height, pty.TokenX, pty.ForkTokenPriceX) && token.GetPrice() == 0 { + if cfg.IsDappFork(action.height, pty.TokenX, pty.ForkTokenPriceX) && token.GetPrice() == 0 { // pay for create token offline } else { receipt, err := action.coinsAccount.ExecFrozen(action.fromaddr, action.execaddr, token.GetPrice()) @@ -206,10 +209,10 @@ func (action *tokenAction) preCreate(token *pty.TokenPreCreate) (*types.Receipt, kv = append(kv, receipt.KV...) } - tokendb := newTokenDB(token, action.fromaddr, action.height) + tokendb := newTokenDB(cfg, token, action.fromaddr, action.height) var statuskey []byte var key []byte - if types.IsFork(action.height, "ForkExecKey") { + if cfg.IsFork(action.height, "ForkExecKey") { statuskey = calcTokenStatusNewKeyS(tokendb.token.Symbol, tokendb.token.Owner, pty.TokenStatusPreCreated) key = calcTokenAddrNewKeyS(tokendb.token.Symbol, tokendb.token.Owner) } else { @@ -232,6 +235,7 @@ func (action *tokenAction) preCreate(token *pty.TokenPreCreate) (*types.Receipt, func (action *tokenAction) finishCreate(tokenFinish *pty.TokenFinishCreate) (*types.Receipt, error) { tokenlog.Debug("finishCreate") + cfg := action.api.GetConfig() if tokenFinish == nil { return nil, types.ErrInvalidParam } @@ -241,7 +245,7 @@ func (action *tokenAction) finishCreate(tokenFinish *pty.TokenFinishCreate) (*ty } approverValid := false - + conf := types.ConfSub(cfg, driverName) for _, approver := range conf.GStrList("tokenApprs") { if approver == action.fromaddr { approverValid = true @@ -257,7 +261,7 @@ func (action *tokenAction) finishCreate(tokenFinish *pty.TokenFinishCreate) (*ty var logs []*types.ReceiptLog var kv []*types.KeyValue - if types.IsDappFork(action.height, pty.TokenX, "ForkTokenPrice") && token.GetPrice() == 0 { + if cfg.IsDappFork(action.height, pty.TokenX, "ForkTokenPrice") && token.GetPrice() == 0 { // pay for create token offline } else { //将之前冻结的资金转账到fund合约账户中 @@ -285,7 +289,7 @@ func (action *tokenAction) finishCreate(tokenFinish *pty.TokenFinishCreate) (*ty token.Status = pty.TokenStatusCreated tokendb := &tokenDB{*token} var key []byte - if types.IsFork(action.height, "ForkExecKey") { + if cfg.IsFork(action.height, "ForkExecKey") { key = calcTokenAddrNewKeyS(tokendb.token.Symbol, tokendb.token.Owner) } else { key = calcTokenAddrKeyS(tokendb.token.Symbol, tokendb.token.Owner) @@ -309,6 +313,7 @@ func (action *tokenAction) revokeCreate(tokenRevoke *pty.TokenRevokeCreate) (*ty if tokenRevoke == nil { return nil, types.ErrInvalidParam } + cfg := action.api.GetConfig() token, err := getTokenFromDB(action.db, tokenRevoke.GetSymbol(), tokenRevoke.GetOwner()) if err != nil { tokenlog.Error("token revokeCreate ", "Can't get token form db for token", tokenRevoke.GetSymbol()) @@ -330,7 +335,7 @@ func (action *tokenAction) revokeCreate(tokenRevoke *pty.TokenRevokeCreate) (*ty var logs []*types.ReceiptLog var kv []*types.KeyValue - if types.IsDappFork(action.height, pty.TokenX, pty.ForkTokenPriceX) && token.GetPrice() == 0 { + if cfg.IsDappFork(action.height, pty.TokenX, pty.ForkTokenPriceX) && token.GetPrice() == 0 { // pay for create token offline } else { //解锁之前冻结的资金 @@ -346,7 +351,7 @@ func (action *tokenAction) revokeCreate(tokenRevoke *pty.TokenRevokeCreate) (*ty token.Status = pty.TokenStatusCreateRevoked tokendb := &tokenDB{*token} var key []byte - if types.IsFork(action.height, "ForkExecKey") { + if cfg.IsFork(action.height, "ForkExecKey") { key = calcTokenAddrNewKeyS(tokendb.token.Symbol, tokendb.token.Owner) } else { key = calcTokenAddrKeyS(tokendb.token.Symbol, tokendb.token.Owner) @@ -375,8 +380,8 @@ func checkTokenHasPrecreate(token, owner string, status int32, db dbm.KV) bool { return err == nil } -func checkTokenHasPrecreateWithHeight(token, owner string, db dbm.KV, height int64) bool { - if !types.IsDappFork(height, pty.TokenX, pty.ForkTokenCheckX) { +func checkTokenHasPrecreateWithHeight(cfg *types.Chain33Config, token, owner string, db dbm.KV, height int64) bool { + if !cfg.IsDappFork(height, pty.TokenX, pty.ForkTokenCheckX) { return checkTokenHasPrecreate(token, owner, pty.TokenStatusPreCreated, db) } @@ -533,10 +538,10 @@ func validSymbolOriginal(cs []byte) bool { return upSymbol == symbol } -func validSymbolWithHeight(cs []byte, height int64) bool { - if types.IsDappFork(height, pty.TokenX, pty.ForkTokenSymbolWithNumberX) { +func validSymbolWithHeight(cfg *types.Chain33Config, cs []byte, height int64) bool { + if cfg.IsDappFork(height, pty.TokenX, pty.ForkTokenSymbolWithNumberX) { return validSymbolForkTokenSymbolWithNumber(cs) - } else if types.IsDappFork(height, pty.TokenX, pty.ForkBadTokenSymbolX) { + } else if cfg.IsDappFork(height, pty.TokenX, pty.ForkBadTokenSymbolX) { return validSymbolForkBadTokenSymbol(cs) } return validSymbolOriginal(cs) diff --git a/plugin/dapp/token/executor/transwithdraw.go b/plugin/dapp/token/executor/transwithdraw.go index 7f9a81ecaf0a5524fb25393810d3c02880e4eb57..9b6b473ffe0611862c2fa70dad6f3b845b01d5a8 100644 --- a/plugin/dapp/token/executor/transwithdraw.go +++ b/plugin/dapp/token/executor/transwithdraw.go @@ -14,6 +14,7 @@ import ( ) func (t *token) ExecTransWithdraw(accountDB *account.DB, tx *types.Transaction, action *tokenty.TokenAction, index int) (*types.Receipt, error) { + cfg := t.GetAPI().GetConfig() if (action.Ty == tokenty.ActionTransfer) && action.GetTransfer() != nil { transfer := action.GetTransfer() from := tx.From() @@ -24,7 +25,7 @@ func (t *token) ExecTransWithdraw(accountDB *account.DB, tx *types.Transaction, return accountDB.Transfer(from, tx.GetRealToAddr(), transfer.Amount) } else if (action.Ty == tokenty.ActionWithdraw) && action.GetWithdraw() != nil { withdraw := action.GetWithdraw() - if !types.IsFork(t.GetHeight(), "ForkWithdraw") { + if !cfg.IsFork(t.GetHeight(), "ForkWithdraw") { withdraw.ExecName = "" } from := tx.From() @@ -43,7 +44,7 @@ func (t *token) ExecTransWithdraw(accountDB *account.DB, tx *types.Transaction, } return nil, types.ErrReRunGenesis } else if action.Ty == tokenty.TokenActionTransferToExec && action.GetTransferToExec() != nil { - if !types.IsFork(t.GetHeight(), "ForkTransferExec") { + if !cfg.IsFork(t.GetHeight(), "ForkTransferExec") { return nil, types.ErrActionNotSupport } transfer := action.GetTransferToExec() diff --git a/plugin/dapp/token/rpc/rpc.go b/plugin/dapp/token/rpc/rpc.go index da2c1c6b4d72bbe5c2fe7019ecfa0eb6585a3487..29bd41908107847d59a5a623e178f974d81299ce 100644 --- a/plugin/dapp/token/rpc/rpc.go +++ b/plugin/dapp/token/rpc/rpc.go @@ -21,8 +21,9 @@ func (c *channelClient) getTokenBalance(in *tokenty.ReqTokenBalance) ([]*types.A if err != nil { return nil, err } + cfg := c.GetConfig() switch in.GetExecer() { - case types.ExecName(tokenty.TokenX): + case cfg.ExecName(tokenty.TokenX): addrs := in.GetAddresses() var queryAddrs []string queryAddrs = append(queryAddrs, addrs...) @@ -83,7 +84,8 @@ func (c *Jrpc) CreateRawTokenPreCreateTx(param *tokenty.TokenPreCreate, result * if param == nil || param.Symbol == "" { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(tokenty.TokenX), "TokenPreCreate", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(tokenty.TokenX), "TokenPreCreate", param) if err != nil { return err } @@ -96,7 +98,8 @@ func (c *Jrpc) CreateRawTokenFinishTx(param *tokenty.TokenFinishCreate, result * if param == nil || param.Symbol == "" { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(tokenty.TokenX), "TokenFinishCreate", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(tokenty.TokenX), "TokenFinishCreate", param) if err != nil { return err } @@ -109,7 +112,8 @@ func (c *Jrpc) CreateRawTokenRevokeTx(param *tokenty.TokenRevokeCreate, result * if param == nil || param.Symbol == "" { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(tokenty.TokenX), "TokenRevokeCreate", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(tokenty.TokenX), "TokenRevokeCreate", param) if err != nil { return err } @@ -122,7 +126,8 @@ func (c *Jrpc) CreateRawTokenMintTx(param *tokenty.TokenMint, result *interface{ if param == nil || param.Symbol == "" || param.Amount <= 0 { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(tokenty.TokenX), "TokenMint", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(tokenty.TokenX), "TokenMint", param) if err != nil { return err } @@ -135,7 +140,8 @@ func (c *Jrpc) CreateRawTokenBurnTx(param *tokenty.TokenBurn, result *interface{ if param == nil || param.Symbol == "" || param.Amount <= 0 { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(tokenty.TokenX), "TokenBurn", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(tokenty.TokenX), "TokenBurn", param) if err != nil { return err } diff --git a/plugin/dapp/trade/executor/query.go b/plugin/dapp/trade/executor/query.go index 773dcdaaeb7cf6f187eb92d0f6af37930784b4ed..565a3d49d632c021ca9d6265aa23b470d4aa2239 100644 --- a/plugin/dapp/trade/executor/query.go +++ b/plugin/dapp/trade/executor/query.go @@ -87,24 +87,25 @@ func (t *trade) GetOnesOrderWithStatus(req *pty.ReqAddrAssets) (types.Message, e return nil, err } var replys pty.ReplyTradeOrders + cfg := t.GetAPI().GetConfig() for _, row := range rows { o, ok := row.Data.(*pty.LocalOrder) if !ok { tradelog.Error("GetOnesOrderWithStatus", "err", "bad row type") return nil, types.ErrTypeAsset } - reply := fmtReply(o) + reply := fmtReply(cfg, o) replys.Orders = append(replys.Orders, reply) } return &replys, nil } -func fmtReply(order *pty.LocalOrder) *pty.ReplyTradeOrder { +func fmtReply(cfg *types.Chain33Config, order *pty.LocalOrder) *pty.ReplyTradeOrder { priceExec := order.PriceExec priceSymbol := order.PriceSymbol if priceExec == "" { priceExec = defaultPriceExec - priceSymbol = types.GetCoinSymbol() + priceSymbol = cfg.GetCoinSymbol() } return &pty.ReplyTradeOrder{ @@ -143,7 +144,8 @@ func (t *trade) GetOneOrder(req *pty.ReqAddrAssets) (types.Message, error) { tradelog.Error("query GetData failed", "err", "bad row type") return nil, types.ErrTypeAsset } - reply := fmtReply(o) + cfg := t.GetAPI().GetConfig() + reply := fmtReply(cfg, o) return reply, nil } diff --git a/plugin/dapp/trade/executor/tradedb.go b/plugin/dapp/trade/executor/tradedb.go index 8d24ad32090731473c892700abb9204d7fbe8498..4673c29be79cdfbd4d28cfd360d15077dc9411f7 100644 --- a/plugin/dapp/trade/executor/tradedb.go +++ b/plugin/dapp/trade/executor/tradedb.go @@ -252,30 +252,34 @@ type tradeAction struct { blocktime int64 height int64 execaddr string + api client.QueueProtocolAPI } func newTradeAction(t *trade, tx *types.Transaction) *tradeAction { hash := hex.EncodeToString(tx.Hash()) fromaddr := tx.From() return &tradeAction{t.GetStateDB(), hash, fromaddr, - t.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer))} + t.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI()} } func (action *tradeAction) tradeSell(sell *pty.TradeForSell) (*types.Receipt, error) { if sell.TotalBoardlot < 0 || sell.PricePerBoardlot < 0 || sell.MinBoardlot < 0 || sell.AmountPerBoardlot < 0 { return nil, types.ErrInvalidParam } - if !checkAsset(action.height, sell.AssetExec, sell.TokenSymbol) { + cfg := action.api.GetConfig() + + if !checkAsset(cfg, action.height, sell.AssetExec, sell.TokenSymbol) { return nil, types.ErrInvalidParam } - if !checkPrice(action.height, sell.PriceExec, sell.PriceExec) { + if !checkPrice(cfg, action.height, sell.PriceExec, sell.PriceExec) { return nil, types.ErrInvalidParam } - if !notSameAsset(action.height, sell.AssetExec, sell.TokenSymbol, sell.PriceExec, sell.PriceExec) { + if !notSameAsset(cfg, action.height, sell.AssetExec, sell.TokenSymbol, sell.PriceExec, sell.PriceExec) { return nil, pty.ErrAssetAndPriceSame } - accDB, err := createAccountDB(action.height, action.db, sell.AssetExec, sell.TokenSymbol) + + accDB, err := createAccountDB(cfg, action.height, action.db, sell.AssetExec, sell.TokenSymbol) if err != nil { return nil, err } @@ -320,7 +324,8 @@ func (action *tradeAction) tradeSell(sell *pty.TradeForSell) (*types.Receipt, er } func (action *tradeAction) tradeBuy(buyOrder *pty.TradeForBuy) (*types.Receipt, error) { - if types.IsDappFork(action.height, pty.TradeX, pty.ForkTradeIDX) { + cfg := action.api.GetConfig() + if cfg.IsDappFork(action.height, pty.TradeX, pty.ForkTradeIDX) { buyOrder.SellID = calcTokenSellID(buyOrder.SellID) } if buyOrder.BoardlotCnt < 0 || !strings.HasPrefix(buyOrder.SellID, sellIDPrefix) { @@ -347,7 +352,7 @@ func (action *tradeAction) tradeBuy(buyOrder *pty.TradeForBuy) (*types.Receipt, return nil, pty.ErrTCntLessThanMinBoardlot } - priceAcc, err := createPriceDB(action.height, action.db, sellOrder.PriceExec, sellOrder.PriceSymbol) + priceAcc, err := createPriceDB(cfg, action.height, action.db, sellOrder.PriceExec, sellOrder.PriceSymbol) if err != nil { tradelog.Error("createPriceDB", "addrFrom", action.fromaddr, "height", action.height, "price", sellOrder.PriceExec+"-"+sellOrder.PriceSymbol, "err", err) @@ -361,7 +366,7 @@ func (action *tradeAction) tradeBuy(buyOrder *pty.TradeForBuy) (*types.Receipt, return nil, err } //然后实现购买token的转移,因为这部分token在之前的卖单生成时已经进行冻结 - accDB, err := createAccountDB(action.height, action.db, sellOrder.AssetExec, sellOrder.TokenSymbol) + accDB, err := createAccountDB(cfg, action.height, action.db, sellOrder.AssetExec, sellOrder.TokenSymbol) if err != nil { tradelog.Error("createAccountDB", "addrFrom", action.fromaddr, "height", action.height, "price", sellOrder.AssetExec+"-"+sellOrder.TokenSymbol, "err", err) @@ -400,7 +405,8 @@ func (action *tradeAction) tradeBuy(buyOrder *pty.TradeForBuy) (*types.Receipt, } func (action *tradeAction) tradeRevokeSell(revoke *pty.TradeForRevokeSell) (*types.Receipt, error) { - if types.IsDappFork(action.height, pty.TradeX, pty.ForkTradeIDX) { + cfg := action.api.GetConfig() + if cfg.IsDappFork(action.height, pty.TradeX, pty.ForkTradeIDX) { revoke.SellID = calcTokenSellID(revoke.SellID) } if !strings.HasPrefix(revoke.SellID, sellIDPrefix) { @@ -424,7 +430,7 @@ func (action *tradeAction) tradeRevokeSell(revoke *pty.TradeForRevokeSell) (*typ return nil, pty.ErrTSellOrderRevoke } //然后实现购买token的转移,因为这部分token在之前的卖单生成时已经进行冻结 - accDB, err := createAccountDB(action.height, action.db, sellOrder.AssetExec, sellOrder.TokenSymbol) + accDB, err := createAccountDB(cfg, action.height, action.db, sellOrder.AssetExec, sellOrder.TokenSymbol) if err != nil { return nil, err } @@ -477,17 +483,19 @@ func (action *tradeAction) tradeBuyLimit(buy *pty.TradeForBuyLimit) (*types.Rece } } - if !checkAsset(action.height, buy.AssetExec, buy.TokenSymbol) { + cfg := action.api.GetConfig() + + if !checkAsset(cfg, action.height, buy.AssetExec, buy.TokenSymbol) { return nil, types.ErrInvalidParam } - if !checkPrice(action.height, buy.PriceExec, buy.PriceExec) { + if !checkPrice(cfg, action.height, buy.PriceExec, buy.PriceExec) { return nil, types.ErrInvalidParam } - if !notSameAsset(action.height, buy.AssetExec, buy.TokenSymbol, buy.PriceExec, buy.PriceExec) { + if !notSameAsset(cfg, action.height, buy.AssetExec, buy.TokenSymbol, buy.PriceExec, buy.PriceExec) { return nil, pty.ErrAssetAndPriceSame } - priceAcc, err := createPriceDB(action.height, action.db, buy.PriceExec, buy.PriceSymbol) + priceAcc, err := createPriceDB(cfg, action.height, action.db, buy.PriceExec, buy.PriceSymbol) if err != nil { return nil, err } @@ -529,7 +537,8 @@ func (action *tradeAction) tradeBuyLimit(buy *pty.TradeForBuyLimit) (*types.Rece } func (action *tradeAction) tradeSellMarket(sellOrder *pty.TradeForSellMarket) (*types.Receipt, error) { - if types.IsDappFork(action.height, pty.TradeX, pty.ForkTradeIDX) { + cfg := action.api.GetConfig() + if cfg.IsDappFork(action.height, pty.TradeX, pty.ForkTradeIDX) { sellOrder.BuyID = calcTokenBuyID(sellOrder.BuyID) } if sellOrder.BoardlotCnt < 0 || !strings.HasPrefix(sellOrder.BuyID, buyIDPrefix) { @@ -554,7 +563,7 @@ func (action *tradeAction) tradeSellMarket(sellOrder *pty.TradeForSellMarket) (* } // 打token - accDB, err := createAccountDB(action.height, action.db, buyOrder.AssetExec, buyOrder.TokenSymbol) + accDB, err := createAccountDB(cfg, action.height, action.db, buyOrder.AssetExec, buyOrder.TokenSymbol) if err != nil { tradelog.Error("createAccountDB failed", "err", err, "order", buyOrder) return nil, err @@ -570,7 +579,7 @@ func (action *tradeAction) tradeSellMarket(sellOrder *pty.TradeForSellMarket) (* } //首先购买费用的划转 - priceAcc, err := createPriceDB(action.height, action.db, buyOrder.PriceExec, buyOrder.PriceSymbol) + priceAcc, err := createPriceDB(cfg, action.height, action.db, buyOrder.PriceExec, buyOrder.PriceSymbol) if err != nil { return nil, err } @@ -608,7 +617,8 @@ func (action *tradeAction) tradeSellMarket(sellOrder *pty.TradeForSellMarket) (* } func (action *tradeAction) tradeRevokeBuyLimit(revoke *pty.TradeForRevokeBuy) (*types.Receipt, error) { - if types.IsDappFork(action.height, pty.TradeX, pty.ForkTradeIDX) { + cfg := action.api.GetConfig() + if cfg.IsDappFork(action.height, pty.TradeX, pty.ForkTradeIDX) { revoke.BuyID = calcTokenBuyID(revoke.BuyID) } if !strings.HasPrefix(revoke.BuyID, buyIDPrefix) { @@ -630,7 +640,7 @@ func (action *tradeAction) tradeRevokeBuyLimit(revoke *pty.TradeForRevokeBuy) (* return nil, pty.ErrTBuyOrderRevoke } - priceAcc, err := createPriceDB(action.height, action.db, buyOrder.PriceExec, buyOrder.PriceSymbol) + priceAcc, err := createPriceDB(cfg, action.height, action.db, buyOrder.PriceExec, buyOrder.PriceSymbol) if err != nil { return nil, err } diff --git a/plugin/dapp/trade/executor/util.go b/plugin/dapp/trade/executor/util.go index 29fd4fcec9640899dcb4a88a52112190cddd4bee..c701a6598aa2767af11ebf06fb1cb01730f26d9a 100644 --- a/plugin/dapp/trade/executor/util.go +++ b/plugin/dapp/trade/executor/util.go @@ -34,8 +34,8 @@ func GetExecSymbol(order *pt.SellOrder) (string, string) { return order.AssetExec, order.TokenSymbol } -func checkAsset(height int64, exec, symbol string) bool { - if types.IsDappFork(height, pt.TradeX, pt.ForkTradeAssetX) { +func checkAsset(cfg *types.Chain33Config, height int64, exec, symbol string) bool { + if cfg.IsDappFork(height, pt.TradeX, pt.ForkTradeAssetX) { if exec == "" || symbol == "" { return false } @@ -47,8 +47,8 @@ func checkAsset(height int64, exec, symbol string) bool { return true } -func checkPrice(height int64, exec, symbol string) bool { - if types.IsDappFork(height, pt.TradeX, pt.ForkTradePriceX) { +func checkPrice(cfg *types.Chain33Config, height int64, exec, symbol string) bool { + if cfg.IsDappFork(height, pt.TradeX, pt.ForkTradePriceX) { if exec == "" && symbol != "" || exec != "" && symbol == "" { return false } @@ -60,8 +60,8 @@ func checkPrice(height int64, exec, symbol string) bool { return true } -func notSameAsset(height int64, assetExec, assetSymbol, priceExec, priceSymbol string) bool { - if types.IsDappFork(height, pt.TradeX, pt.ForkTradePriceX) { +func notSameAsset(cfg *types.Chain33Config, height int64, assetExec, assetSymbol, priceExec, priceSymbol string) bool { + if cfg.IsDappFork(height, pt.TradeX, pt.ForkTradePriceX) { if assetExec == priceExec && assetSymbol == priceSymbol { return false } @@ -69,30 +69,30 @@ func notSameAsset(height int64, assetExec, assetSymbol, priceExec, priceSymbol s return true } -func createAccountDB(height int64, db db.KV, exec, symbol string) (*account.DB, error) { - if types.IsDappFork(height, pt.TradeX, pt.ForkTradeFixAssetDBX) { +func createAccountDB(cfg *types.Chain33Config, height int64, db db.KV, exec, symbol string) (*account.DB, error) { + if cfg.IsDappFork(height, pt.TradeX, pt.ForkTradeFixAssetDBX) { if exec == "" { exec = defaultAssetExec } return account.NewAccountDB(exec, symbol, db) - } else if types.IsDappFork(height, pt.TradeX, pt.ForkTradeAssetX) { + } else if cfg.IsDappFork(height, pt.TradeX, pt.ForkTradeAssetX) { return account.NewAccountDB(exec, symbol, db) } return account.NewAccountDB(defaultAssetExec, symbol, db) } -func createPriceDB(height int64, db db.KV, exec, symbol string) (*account.DB, error) { - if types.IsDappFork(height, pt.TradeX, pt.ForkTradePriceX) { +func createPriceDB(cfg *types.Chain33Config, height int64, db db.KV, exec, symbol string) (*account.DB, error) { + if cfg.IsDappFork(height, pt.TradeX, pt.ForkTradePriceX) { // 为空默认使用 coins if exec == "" { - acc := account.NewCoinsAccount() + acc := account.NewCoinsAccount(cfg) acc.SetDB(db) return acc, nil } return account.NewAccountDB(exec, symbol, db) } - acc := account.NewCoinsAccount() + acc := account.NewCoinsAccount(cfg) acc.SetDB(db) return acc, nil } diff --git a/plugin/dapp/trade/rpc/rpc.go b/plugin/dapp/trade/rpc/rpc.go index 46798e586c304c79878953948ba1d550d1a6e85c..58281ba06e692792df0cf0f3dbe42c543d6e60b6 100644 --- a/plugin/dapp/trade/rpc/rpc.go +++ b/plugin/dapp/trade/rpc/rpc.go @@ -20,7 +20,8 @@ func (cc *channelClient) CreateRawTradeSellTx(ctx context.Context, in *ptypes.Tr Ty: ptypes.TradeSellLimit, Value: &ptypes.Trade_SellLimit{SellLimit: in}, } - tx, err := types.CreateFormatTx(types.ExecName(ptypes.TradeX), types.Encode(sell)) + cfg := cc.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(ptypes.TradeX), types.Encode(sell)) if err != nil { return nil, err } @@ -37,7 +38,8 @@ func (cc *channelClient) CreateRawTradeBuyTx(ctx context.Context, in *ptypes.Tra Ty: ptypes.TradeBuyMarket, Value: &ptypes.Trade_BuyMarket{BuyMarket: in}, } - tx, err := types.CreateFormatTx(types.ExecName(ptypes.TradeX), types.Encode(buy)) + cfg := cc.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(ptypes.TradeX), types.Encode(buy)) if err != nil { return nil, err } @@ -54,7 +56,8 @@ func (cc *channelClient) CreateRawTradeRevokeTx(ctx context.Context, in *ptypes. Ty: ptypes.TradeRevokeSell, Value: &ptypes.Trade_RevokeSell{RevokeSell: in}, } - tx, err := types.CreateFormatTx(types.ExecName(ptypes.TradeX), types.Encode(buy)) + cfg := cc.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(ptypes.TradeX), types.Encode(buy)) if err != nil { return nil, err } @@ -71,7 +74,8 @@ func (cc *channelClient) CreateRawTradeBuyLimitTx(ctx context.Context, in *ptype Ty: ptypes.TradeBuyLimit, Value: &ptypes.Trade_BuyLimit{BuyLimit: in}, } - tx, err := types.CreateFormatTx(types.ExecName(ptypes.TradeX), types.Encode(buy)) + cfg := cc.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(ptypes.TradeX), types.Encode(buy)) if err != nil { return nil, err } @@ -88,7 +92,8 @@ func (cc *channelClient) CreateRawTradeSellMarketTx(ctx context.Context, in *pty Ty: ptypes.TradeSellMarket, Value: &ptypes.Trade_SellMarket{SellMarket: in}, } - tx, err := types.CreateFormatTx(types.ExecName(ptypes.TradeX), types.Encode(buy)) + cfg := cc.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(ptypes.TradeX), types.Encode(buy)) if err != nil { return nil, err } @@ -105,7 +110,8 @@ func (cc *channelClient) CreateRawTradeRevokeBuyTx(ctx context.Context, in *ptyp Ty: ptypes.TradeRevokeBuy, Value: &ptypes.Trade_RevokeBuy{RevokeBuy: in}, } - tx, err := types.CreateFormatTx(types.ExecName(ptypes.TradeX), types.Encode(buy)) + cfg := cc.GetConfig() + tx, err := types.CreateFormatTx(cfg, cfg.ExecName(ptypes.TradeX), types.Encode(buy)) if err != nil { return nil, err } diff --git a/plugin/dapp/trade/types/trade.go b/plugin/dapp/trade/types/trade.go index 2bb43a4eecb3e3f00810f4d4cee376456fba3ff1..d3449165c61b51134044dba2054975783d1f14d3 100644 --- a/plugin/dapp/trade/types/trade.go +++ b/plugin/dapp/trade/types/trade.go @@ -124,6 +124,7 @@ func (t *tradeType) Amount(tx *types.Transaction) (int64, error) { func (t *tradeType) CreateTx(action string, message json.RawMessage) (*types.Transaction, error) { //var tx *types.Transaction + cfg := t.GetConfig() if action == "TradeSellLimit" { var param TradeSellTx err := json.Unmarshal(message, ¶m) @@ -131,7 +132,7 @@ func (t *tradeType) CreateTx(action string, message json.RawMessage) (*types.Tra tlog.Error("CreateTx", "Error", err) return nil, types.ErrInvalidParam } - return CreateRawTradeSellTx(¶m) + return CreateRawTradeSellTx(cfg, ¶m) } else if action == "TradeBuyMarket" { var param TradeBuyTx err := json.Unmarshal(message, ¶m) @@ -139,7 +140,7 @@ func (t *tradeType) CreateTx(action string, message json.RawMessage) (*types.Tra tlog.Error("CreateTx", "Error", err) return nil, types.ErrInvalidParam } - return CreateRawTradeBuyTx(¶m) + return CreateRawTradeBuyTx(cfg, ¶m) } else if action == "TradeSellRevoke" { var param TradeRevokeTx err := json.Unmarshal(message, ¶m) @@ -147,7 +148,7 @@ func (t *tradeType) CreateTx(action string, message json.RawMessage) (*types.Tra tlog.Error("CreateTx", "Error", err) return nil, types.ErrInvalidParam } - return CreateRawTradeRevokeTx(¶m) + return CreateRawTradeRevokeTx(cfg, ¶m) } else if action == "TradeBuyLimit" { var param TradeBuyLimitTx err := json.Unmarshal(message, ¶m) @@ -155,7 +156,7 @@ func (t *tradeType) CreateTx(action string, message json.RawMessage) (*types.Tra tlog.Error("CreateTx", "Error", err) return nil, types.ErrInvalidParam } - return CreateRawTradeBuyLimitTx(¶m) + return CreateRawTradeBuyLimitTx(cfg, ¶m) } else if action == "TradeSellMarket" { var param TradeSellMarketTx err := json.Unmarshal(message, ¶m) @@ -163,7 +164,7 @@ func (t *tradeType) CreateTx(action string, message json.RawMessage) (*types.Tra tlog.Error("CreateTx", "Error", err) return nil, types.ErrInvalidParam } - return CreateRawTradeSellMarketTx(¶m) + return CreateRawTradeSellMarketTx(cfg, ¶m) } else if action == "TradeRevokeBuy" { var param TradeRevokeBuyTx err := json.Unmarshal(message, ¶m) @@ -171,14 +172,14 @@ func (t *tradeType) CreateTx(action string, message json.RawMessage) (*types.Tra tlog.Error("CreateTx", "Error", err) return nil, types.ErrInvalidParam } - return CreateRawTradeRevokeBuyTx(¶m) + return CreateRawTradeRevokeBuyTx(cfg, ¶m) } return nil, types.ErrNotSupport } //CreateRawTradeSellTx : 创建卖单交易 -func CreateRawTradeSellTx(parm *TradeSellTx) (*types.Transaction, error) { +func CreateRawTradeSellTx(cfg *types.Chain33Config, parm *TradeSellTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam } @@ -199,11 +200,11 @@ func CreateRawTradeSellTx(parm *TradeSellTx) (*types.Transaction, error) { Ty: TradeSellLimit, Value: &Trade_SellLimit{v}, } - return types.CreateFormatTx(types.ExecName(TradeX), types.Encode(sell)) + return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(sell)) } //CreateRawTradeBuyTx :创建想指定卖单发起的买单交易 -func CreateRawTradeBuyTx(parm *TradeBuyTx) (*types.Transaction, error) { +func CreateRawTradeBuyTx(cfg *types.Chain33Config, parm *TradeBuyTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam } @@ -212,11 +213,11 @@ func CreateRawTradeBuyTx(parm *TradeBuyTx) (*types.Transaction, error) { Ty: TradeBuyMarket, Value: &Trade_BuyMarket{v}, } - return types.CreateFormatTx(types.ExecName(TradeX), types.Encode(buy)) + return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(buy)) } //CreateRawTradeRevokeTx :创建取消卖单的交易 -func CreateRawTradeRevokeTx(parm *TradeRevokeTx) (*types.Transaction, error) { +func CreateRawTradeRevokeTx(cfg *types.Chain33Config, parm *TradeRevokeTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam } @@ -226,11 +227,11 @@ func CreateRawTradeRevokeTx(parm *TradeRevokeTx) (*types.Transaction, error) { Ty: TradeRevokeSell, Value: &Trade_RevokeSell{v}, } - return types.CreateFormatTx(types.ExecName(TradeX), types.Encode(buy)) + return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(buy)) } //CreateRawTradeBuyLimitTx :创建买单交易 -func CreateRawTradeBuyLimitTx(parm *TradeBuyLimitTx) (*types.Transaction, error) { +func CreateRawTradeBuyLimitTx(cfg *types.Chain33Config, parm *TradeBuyLimitTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam } @@ -248,11 +249,11 @@ func CreateRawTradeBuyLimitTx(parm *TradeBuyLimitTx) (*types.Transaction, error) Ty: TradeBuyLimit, Value: &Trade_BuyLimit{v}, } - return types.CreateFormatTx(types.ExecName(TradeX), types.Encode(buyLimit)) + return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(buyLimit)) } //CreateRawTradeSellMarketTx : 创建向指定买单出售token的卖单交易 -func CreateRawTradeSellMarketTx(parm *TradeSellMarketTx) (*types.Transaction, error) { +func CreateRawTradeSellMarketTx(cfg *types.Chain33Config, parm *TradeSellMarketTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam } @@ -261,11 +262,11 @@ func CreateRawTradeSellMarketTx(parm *TradeSellMarketTx) (*types.Transaction, er Ty: TradeSellMarket, Value: &Trade_SellMarket{v}, } - return types.CreateFormatTx(types.ExecName(TradeX), types.Encode(sellMarket)) + return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(sellMarket)) } //CreateRawTradeRevokeBuyTx : 取消发起的买单交易 -func CreateRawTradeRevokeBuyTx(parm *TradeRevokeBuyTx) (*types.Transaction, error) { +func CreateRawTradeRevokeBuyTx(cfg *types.Chain33Config, parm *TradeRevokeBuyTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam } @@ -275,5 +276,5 @@ func CreateRawTradeRevokeBuyTx(parm *TradeRevokeBuyTx) (*types.Transaction, erro Ty: TradeRevokeBuy, Value: &Trade_RevokeBuy{v}, } - return types.CreateFormatTx(types.ExecName(TradeX), types.Encode(buy)) + return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(buy)) } diff --git a/plugin/dapp/unfreeze/executor/exec.go b/plugin/dapp/unfreeze/executor/exec.go index 733290b6b7ce8a7e3c9f33d9fa77f722d23e7b55..bc7ed96b5e4cd5ea0bef926dc49ed59331a37c77 100644 --- a/plugin/dapp/unfreeze/executor/exec.go +++ b/plugin/dapp/unfreeze/executor/exec.go @@ -48,7 +48,8 @@ func (u *Unfreeze) Exec_Create(payload *pty.UnfreezeCreate, tx *types.Transactio // Exec_Withdraw 执行冻结合约中提币 func (u *Unfreeze) Exec_Withdraw(payload *pty.UnfreezeWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) { - if types.IsDappFork(u.GetHeight(), pty.UnfreezeX, pty.ForkUnfreezeIDX) { + cfg := u.GetAPI().GetConfig() + if cfg.IsDappFork(u.GetHeight(), pty.UnfreezeX, pty.ForkUnfreezeIDX) { payload.UnfreezeID = unfreezeIDFromHex(payload.UnfreezeID) } unfreeze, err := loadUnfreeze(payload.UnfreezeID, u.GetStateDB()) @@ -87,7 +88,8 @@ func (u *Unfreeze) Exec_Withdraw(payload *pty.UnfreezeWithdraw, tx *types.Transa // Exec_Terminate 执行终止冻结合约 func (u *Unfreeze) Exec_Terminate(payload *pty.UnfreezeTerminate, tx *types.Transaction, index int) (*types.Receipt, error) { - if types.IsDappFork(u.GetHeight(), pty.UnfreezeX, pty.ForkUnfreezeIDX) { + cfg := u.GetAPI().GetConfig() + if cfg.IsDappFork(u.GetHeight(), pty.UnfreezeX, pty.ForkUnfreezeIDX) { payload.UnfreezeID = unfreezeIDFromHex(payload.UnfreezeID) } unfreeze, err := loadUnfreeze(payload.UnfreezeID, u.GetStateDB()) @@ -135,7 +137,8 @@ func (u *Unfreeze) newEntity(payload *pty.UnfreezeCreate, tx *types.Transaction) if unfreeze.StartTime == 0 { unfreeze.StartTime = u.GetBlockTime() } - means, err := newMeans(payload.Means, u.GetHeight()) + cfg := u.GetAPI().GetConfig() + means, err := newMeans(cfg, payload.Means, u.GetHeight()) if err != nil { return nil, err @@ -178,7 +181,8 @@ func getUnfreezeLog(prev, cur *pty.Unfreeze, ty int32) *types.ReceiptLog { // 提取解冻币 func (u *Unfreeze) withdraw(unfreeze *pty.Unfreeze) (int64, *types.Receipt, error) { - means, err := newMeans(unfreeze.Means, u.GetHeight()) + cfg := u.GetAPI().GetConfig() + means, err := newMeans(cfg, unfreeze.Means, u.GetHeight()) if err != nil { return 0, nil, err @@ -210,11 +214,12 @@ func (u *Unfreeze) terminator(unfreeze *pty.Unfreeze) (int64, *types.Receipt, er unfreezeOld := *unfreeze var amount int64 - if types.IsDappFork(u.GetHeight(), pty.UnfreezeX, "ForkTerminatePart") { + cfg := u.GetAPI().GetConfig() + if cfg.IsDappFork(u.GetHeight(), pty.UnfreezeX, "ForkTerminatePart") { if unfreeze.Terminated { return 0, nil, pty.ErrTerminated } - m, err := newMeans(unfreeze.Means, u.GetHeight()) + m, err := newMeans(cfg, unfreeze.Means, u.GetHeight()) if err != nil { return 0, nil, err } diff --git a/plugin/dapp/unfreeze/executor/means.go b/plugin/dapp/unfreeze/executor/means.go index f607910c8e56a7e3c55b2818be50f44689937dc5..f33d11a54dece4b40f8f7f735f9353043c1bbb37 100644 --- a/plugin/dapp/unfreeze/executor/means.go +++ b/plugin/dapp/unfreeze/executor/means.go @@ -15,8 +15,8 @@ type Means interface { calcFrozen(unfreeze *pty.Unfreeze, now int64) (int64, error) } -func newMeans(means string, height int64) (Means, error) { - if types.IsDappFork(height, pty.UnfreezeX, "ForkTerminatePart") { +func newMeans(cfg *types.Chain33Config, means string, height int64) (Means, error) { + if cfg.IsDappFork(height, pty.UnfreezeX, "ForkTerminatePart") { if means == "FixAmount" { return &fixAmountV2{}, nil } else if means == "LeftProportion" { diff --git a/plugin/dapp/unfreeze/executor/query.go b/plugin/dapp/unfreeze/executor/query.go index 27ea3893506bcc1a82935fbaea2dc40fa99ac0d2..65f38d393fd72a8847958d2d43f7557362ba835e 100644 --- a/plugin/dapp/unfreeze/executor/query.go +++ b/plugin/dapp/unfreeze/executor/query.go @@ -15,7 +15,8 @@ import ( // Query_GetUnfreezeWithdraw 查询合约可提币量 func (u *Unfreeze) Query_GetUnfreezeWithdraw(in *types.ReqString) (types.Message, error) { - return QueryWithdraw(u.GetStateDB(), in.GetData()) + cfg := u.GetAPI().GetConfig() + return QueryWithdraw(cfg, u.GetStateDB(), in.GetData()) } // Query_GetUnfreeze 查询合约状态 @@ -34,7 +35,7 @@ func (u *Unfreeze) Query_ListUnfreezeByBeneficiary(in *pty.ReqUnfreezes) (types. } // QueryWithdraw 查询可提币状态 -func QueryWithdraw(stateDB dbm.KV, id string) (types.Message, error) { +func QueryWithdraw(cfg *types.Chain33Config, stateDB dbm.KV, id string) (types.Message, error) { id = unfreezeIDFromHex(id) unfreeze, err := loadUnfreeze(id, stateDB) if err != nil { @@ -43,7 +44,7 @@ func QueryWithdraw(stateDB dbm.KV, id string) (types.Message, error) { } currentTime := time.Now().Unix() reply := &pty.ReplyQueryUnfreezeWithdraw{UnfreezeID: id} - available, err := getWithdrawAvailable(unfreeze, currentTime) + available, err := getWithdrawAvailable(cfg, unfreeze, currentTime) if err != nil { return nil, err } @@ -52,8 +53,8 @@ func QueryWithdraw(stateDB dbm.KV, id string) (types.Message, error) { return reply, nil } -func getWithdrawAvailable(unfreeze *pty.Unfreeze, calcTime int64) (int64, error) { - means, err := newMeans(unfreeze.Means, 1500000) +func getWithdrawAvailable(cfg *types.Chain33Config, unfreeze *pty.Unfreeze, calcTime int64) (int64, error) { + means, err := newMeans(cfg, unfreeze.Means, 1500000) if err != nil { return 0, err } diff --git a/plugin/dapp/unfreeze/rpc/rpc.go b/plugin/dapp/unfreeze/rpc/rpc.go index e2a447ed15ec9010f4191a914b69d26fda8f6444..77dc58503917e6bcefd2a23c1f0967ffee50bce9 100644 --- a/plugin/dapp/unfreeze/rpc/rpc.go +++ b/plugin/dapp/unfreeze/rpc/rpc.go @@ -63,7 +63,8 @@ func (c *Jrpc) CreateRawUnfreezeCreate(param *pty.UnfreezeCreate, result *interf if param == nil { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(pty.UnfreezeX), "Create", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(pty.UnfreezeX), "Create", param) if err != nil { return err } @@ -76,7 +77,8 @@ func (c *Jrpc) CreateRawUnfreezeWithdraw(param *pty.UnfreezeWithdraw, result *in if param == nil { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(pty.UnfreezeX), "Withdraw", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(pty.UnfreezeX), "Withdraw", param) if err != nil { return err } @@ -89,7 +91,8 @@ func (c *Jrpc) CreateRawUnfreezeTerminate(param *pty.UnfreezeTerminate, result * if param == nil { return types.ErrInvalidParam } - data, err := types.CallCreateTx(types.ExecName(pty.UnfreezeX), "Terminate", param) + cfg := c.cli.GetConfig() + data, err := types.CallCreateTx(cfg, cfg.ExecName(pty.UnfreezeX), "Terminate", param) if err != nil { return err } diff --git a/plugin/dapp/unfreeze/types/types.go b/plugin/dapp/unfreeze/types/types.go index 18ad95b0c855d02a051336e3adb52b92af29a170..244ec441b6e61f1571c9f6149fb1b5b0dc43e697 100644 --- a/plugin/dapp/unfreeze/types/types.go +++ b/plugin/dapp/unfreeze/types/types.go @@ -38,8 +38,8 @@ func InitExecutor(cfg *types.Chain33Config) { } //getRealExecName -func getRealExecName(paraName string) string { - return types.ExecName(paraName + UnfreezeX) +func getRealExecName(cfg *types.Chain33Config, paraName string) string { + return cfg.ExecName(paraName + UnfreezeX) } // NewType 生成新的基础类型 @@ -117,11 +117,12 @@ func (u *UnfreezeType) CreateTx(action string, message json.RawMessage) (*types. // RPC_UnfreezeCreateTx 创建冻结合约交易入口 func (u *UnfreezeType) RPC_UnfreezeCreateTx(parm *UnfreezeCreate) (*types.Transaction, error) { - return CreateUnfreezeCreateTx(types.GetParaName(), parm) + cfg := u.GetConfig() + return CreateUnfreezeCreateTx(cfg, cfg.GetParaName(), parm) } // CreateUnfreezeCreateTx 创建冻结合约交易 -func CreateUnfreezeCreateTx(title string, parm *UnfreezeCreate) (*types.Transaction, error) { +func CreateUnfreezeCreateTx(cfg *types.Chain33Config, title string, parm *UnfreezeCreate) (*types.Transaction, error) { tlog.Error("CreateUnfreezeCreateTx", "parm", parm) if parm == nil { tlog.Error("RPC_UnfreezeCreateTx", "parm", parm) @@ -140,22 +141,23 @@ func CreateUnfreezeCreateTx(title string, parm *UnfreezeCreate) (*types.Transact Value: &UnfreezeAction_Create{parm}, } tx := &types.Transaction{ - Execer: []byte(getRealExecName(title)), + Execer: []byte(getRealExecName(cfg, title)), Payload: types.Encode(create), Nonce: rand.New(rand.NewSource(time.Now().UnixNano())).Int63(), - To: address.ExecAddress(getRealExecName(types.GetParaName())), + To: address.ExecAddress(getRealExecName(cfg, cfg.GetParaName())), } - tx.SetRealFee(types.GInt("MinFee")) + tx.SetRealFee(cfg.GInt("MinFee")) return tx, nil } // RPC_UnfreezeWithdrawTx 创建提币交易入口 func (u *UnfreezeType) RPC_UnfreezeWithdrawTx(parm *UnfreezeWithdraw) (*types.Transaction, error) { - return CreateUnfreezeWithdrawTx(types.GetParaName(), parm) + cfg := u.GetConfig() + return CreateUnfreezeWithdrawTx(cfg, cfg.GetParaName(), parm) } // CreateUnfreezeWithdrawTx 创建提币交易 -func CreateUnfreezeWithdrawTx(title string, parm *UnfreezeWithdraw) (*types.Transaction, error) { +func CreateUnfreezeWithdrawTx(cfg *types.Chain33Config, title string, parm *UnfreezeWithdraw) (*types.Transaction, error) { if parm == nil { tlog.Error("RPC_UnfreezeWithdrawTx", "parm", parm) return nil, types.ErrInvalidParam @@ -168,22 +170,23 @@ func CreateUnfreezeWithdrawTx(title string, parm *UnfreezeWithdraw) (*types.Tran Value: &UnfreezeAction_Withdraw{v}, } tx := &types.Transaction{ - Execer: []byte(getRealExecName(title)), + Execer: []byte(getRealExecName(cfg, title)), Payload: types.Encode(withdraw), Nonce: rand.New(rand.NewSource(time.Now().UnixNano())).Int63(), - To: address.ExecAddress(getRealExecName(types.GetParaName())), + To: address.ExecAddress(getRealExecName(cfg, cfg.GetParaName())), } - tx.SetRealFee(types.GInt("MinFee")) + tx.SetRealFee(cfg.GInt("MinFee")) return tx, nil } // RPC_UnfreezeTerminateTx 创建终止冻结合约入口 func (u *UnfreezeType) RPC_UnfreezeTerminateTx(parm *UnfreezeTerminate) (*types.Transaction, error) { - return CreateUnfreezeTerminateTx(types.GetParaName(), parm) + cfg := u.GetConfig() + return CreateUnfreezeTerminateTx(cfg, cfg.GetParaName(), parm) } // CreateUnfreezeTerminateTx 创建终止冻结合约 -func CreateUnfreezeTerminateTx(title string, parm *UnfreezeTerminate) (*types.Transaction, error) { +func CreateUnfreezeTerminateTx(cfg *types.Chain33Config, title string, parm *UnfreezeTerminate) (*types.Transaction, error) { if parm == nil { tlog.Error("RPC_UnfreezeTerminateTx", "parm", parm) return nil, types.ErrInvalidParam @@ -196,12 +199,12 @@ func CreateUnfreezeTerminateTx(title string, parm *UnfreezeTerminate) (*types.Tr Value: &UnfreezeAction_Terminate{v}, } tx := &types.Transaction{ - Execer: []byte(getRealExecName(title)), + Execer: []byte(getRealExecName(cfg, title)), Payload: types.Encode(terminate), Nonce: rand.New(rand.NewSource(time.Now().UnixNano())).Int63(), - To: address.ExecAddress(getRealExecName(types.GetParaName())), + To: address.ExecAddress(getRealExecName(cfg, cfg.GetParaName())), } - tx.SetRealFee(types.GInt("MinFee")) + tx.SetRealFee(cfg.GInt("MinFee")) return tx, nil } diff --git a/plugin/dapp/valnode/types/valnode.go b/plugin/dapp/valnode/types/valnode.go index 7cbcd6a84902d46ea20871b53069dc51659de5b7..a816510548ef427b2dcf63888541d882b89188d7 100644 --- a/plugin/dapp/valnode/types/valnode.go +++ b/plugin/dapp/valnode/types/valnode.go @@ -25,11 +25,6 @@ func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(ValNodeX, NewType(cfg)) } -// GetExecName get exec name -func GetExecName() string { - return types.ExecName(ValNodeX) -} - // ValNodeType stuct type ValNodeType struct { types.ExecTypeBase