Commit 66063dca authored by mdj33's avatar mdj33 Committed by vipwzw

add coinsx exec to support transfer

parent 8ad855c5
...@@ -366,6 +366,7 @@ function transfer() { ...@@ -366,6 +366,7 @@ function transfer() {
hashes=() hashes=()
for ((i = 0; i < 10; i++)); do for ((i = 0; i < 10; i++)); do
hash=$(${1} send coins transfer -a 1 -n test -t 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01) hash=$(${1} send coins transfer -a 1 -n test -t 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01)
echo "hash=$hash"
hashes=("${hashes[@]}" "$hash") hashes=("${hashes[@]}" "$hash")
done done
block_wait "${1}" 1 block_wait "${1}" 1
...@@ -383,7 +384,7 @@ function transfer() { ...@@ -383,7 +384,7 @@ function transfer() {
fi fi
done done
echo "=========== # withdraw =============" echo "=========== # transfer 2 ============="
hash=$(${1} send coins transfer -a 2 -n deposit -t 1wvmD6RNHzwhY4eN75WnM6JcaAvNQ4nHx -k CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944) hash=$(${1} send coins transfer -a 2 -n deposit -t 1wvmD6RNHzwhY4eN75WnM6JcaAvNQ4nHx -k CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944)
echo "${hash}" echo "${hash}"
# block_wait "${1}" 2 # block_wait "${1}" 2
...@@ -394,6 +395,7 @@ function transfer() { ...@@ -394,6 +395,7 @@ function transfer() {
exit 1 exit 1
fi fi
echo "=========== # withdraw ============="
hash=$(${1} send coins withdraw -a 1 -n withdraw -e retrieve -k CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944) hash=$(${1} send coins withdraw -a 1 -n withdraw -e retrieve -k CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944)
echo "${hash}" echo "${hash}"
# block_wait "${1}" 1 # block_wait "${1}" 1
......
...@@ -177,10 +177,10 @@ enableStat=false ...@@ -177,10 +177,10 @@ enableStat=false
enableMVCC=false enableMVCC=false
[exec.sub.relay] [exec.sub.relay]
genesis="1JmFaA6unrCFYEWPGRi7uuXY1KthTJxJEP" genesis="12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv"
[exec.sub.manage] [exec.sub.manage]
superManager=["1JmFaA6unrCFYEWPGRi7uuXY1KthTJxJEP"] superManager=["12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv"]
[exec.sub.token] [exec.sub.token]
saveTokenTxList=true saveTokenTxList=true
...@@ -230,6 +230,9 @@ ForkRootHash=7200000 ...@@ -230,6 +230,9 @@ ForkRootHash=7200000
[fork.sub.coins] [fork.sub.coins]
Enable=0 Enable=0
[fork.sub.coinsx]
Enable=0
[fork.sub.ticket] [fork.sub.ticket]
Enable=0 Enable=0
ForkTicketId =0 ForkTicketId =0
......
...@@ -412,7 +412,7 @@ func (client *Client) GetGenesisBlockTime() int64 { ...@@ -412,7 +412,7 @@ func (client *Client) GetGenesisBlockTime() int64 {
// CreateGenesisTx ... // CreateGenesisTx ...
func (client *Client) CreateGenesisTx() (ret []*types.Transaction) { func (client *Client) CreateGenesisTx() (ret []*types.Transaction) {
var tx types.Transaction var tx types.Transaction
tx.Execer = []byte("coins") tx.Execer = []byte(client.GetAPI().GetConfig().GetCoinExec())
tx.To = genesis tx.To = genesis
//gen payload //gen payload
g := &cty.CoinsAction_Genesis{} g := &cty.CoinsAction_Genesis{}
......
...@@ -585,7 +585,7 @@ func sendTransferTx(cfg *types.Chain33Config, fromKey, to string, amount int64) ...@@ -585,7 +585,7 @@ func sendTransferTx(cfg *types.Chain33Config, fromKey, to string, amount int64)
v := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: amount, Note: []byte(""), To: to}} v := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: amount, Note: []byte(""), To: to}}
transfer.Value = v transfer.Value = v
transfer.Ty = cty.CoinsActionTransfer transfer.Ty = cty.CoinsActionTransfer
execer := []byte("coins") execer := []byte(cfg.GetCoinExec())
tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: to, Fee: fee} tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: to, Fee: fee}
tx, err := types.FormatTx(cfg, string(execer), tx) tx, err := types.FormatTx(cfg, string(execer), tx)
if err != nil { if err != nil {
......
...@@ -314,7 +314,7 @@ func (client *client) GetStartMainHash(height int64) []byte { ...@@ -314,7 +314,7 @@ func (client *client) GetStartMainHash(height int64) []byte {
func (client *client) CreateGenesisTx() (ret []*types.Transaction) { func (client *client) CreateGenesisTx() (ret []*types.Transaction) {
var tx types.Transaction var tx types.Transaction
cfg := client.GetAPI().GetConfig() cfg := client.GetAPI().GetConfig()
tx.Execer = []byte(cfg.ExecName(cty.CoinsX)) tx.Execer = []byte(cfg.ExecName(cfg.GetCoinExec()))
tx.To = client.Cfg.Genesis tx.To = client.Cfg.Genesis
//gen payload //gen payload
g := &cty.CoinsAction_Genesis{} g := &cty.CoinsAction_Genesis{}
......
...@@ -116,7 +116,7 @@ func (client *Client) GetGenesisBlockTime() int64 { ...@@ -116,7 +116,7 @@ func (client *Client) GetGenesisBlockTime() int64 {
// CreateGenesisTx get genesis tx // CreateGenesisTx get genesis tx
func (client *Client) CreateGenesisTx() (ret []*types.Transaction) { func (client *Client) CreateGenesisTx() (ret []*types.Transaction) {
var tx types.Transaction var tx types.Transaction
tx.Execer = []byte("coins") tx.Execer = []byte(client.GetAPI().GetConfig().GetCoinExec())
tx.To = genesis tx.To = genesis
//gen payload //gen payload
g := &cty.CoinsAction_Genesis{} g := &cty.CoinsAction_Genesis{}
......
...@@ -130,7 +130,7 @@ func createReplyList(cfg *types.Chain33Config, account string) { ...@@ -130,7 +130,7 @@ func createReplyList(cfg *types.Chain33Config, account string) {
//tx := &types.Transaction{} //tx := &types.Transaction{}
val := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: 10}} val := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: 10}}
action := &cty.CoinsAction{Value: val, Ty: cty.CoinsActionTransfer} action := &cty.CoinsAction{Value: val, Ty: cty.CoinsActionTransfer}
tx := &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(action), Fee: 0} tx := &types.Transaction{Execer: []byte(cfg.GetCoinExec()), Payload: types.Encode(action), Fee: 0}
tx.To = "14qViLJfdGaP4EeHnDyJbEGQysnCpwn1gZ" tx.To = "14qViLJfdGaP4EeHnDyJbEGQysnCpwn1gZ"
tx.Nonce = random.Int63() tx.Nonce = random.Int63()
......
...@@ -382,7 +382,7 @@ func (client *Client) GetGenesisBlockTime() int64 { ...@@ -382,7 +382,7 @@ func (client *Client) GetGenesisBlockTime() int64 {
// CreateGenesisTx ... // CreateGenesisTx ...
func (client *Client) CreateGenesisTx() (ret []*types.Transaction) { func (client *Client) CreateGenesisTx() (ret []*types.Transaction) {
var tx types.Transaction var tx types.Transaction
tx.Execer = []byte("coins") tx.Execer = []byte(client.GetAPI().GetConfig().GetCoinExec())
tx.To = genesis tx.To = genesis
//gen payload //gen payload
g := &cty.CoinsAction_Genesis{} g := &cty.CoinsAction_Genesis{}
......
...@@ -51,7 +51,7 @@ func (client *Client) GetGenesisBlockTime() int64 { ...@@ -51,7 +51,7 @@ func (client *Client) GetGenesisBlockTime() int64 {
// CreateGenesisTx get genesis tx // CreateGenesisTx get genesis tx
func (client *Client) CreateGenesisTx() (ret []*types.Transaction) { func (client *Client) CreateGenesisTx() (ret []*types.Transaction) {
var tx types.Transaction var tx types.Transaction
tx.Execer = []byte(cty.CoinsX) tx.Execer = []byte(client.GetAPI().GetConfig().GetCoinExec())
tx.To = genesis tx.To = genesis
//gen payload //gen payload
g := &cty.CoinsAction_Genesis{} g := &cty.CoinsAction_Genesis{}
......
...@@ -352,7 +352,7 @@ func (client *Client) GetGenesisBlockTime() int64 { ...@@ -352,7 +352,7 @@ func (client *Client) GetGenesisBlockTime() int64 {
// CreateGenesisTx ... // CreateGenesisTx ...
func (client *Client) CreateGenesisTx() (ret []*types.Transaction) { func (client *Client) CreateGenesisTx() (ret []*types.Transaction) {
var tx types.Transaction var tx types.Transaction
tx.Execer = []byte("coins") tx.Execer = []byte(client.GetAPI().GetConfig().GetCoinExec())
tx.To = genesis tx.To = genesis
//gen payload //gen payload
g := &cty.CoinsAction_Genesis{} g := &cty.CoinsAction_Genesis{}
......
...@@ -120,7 +120,7 @@ func (client *Client) CreateGenesisTx() (ret []*types.Transaction) { ...@@ -120,7 +120,7 @@ func (client *Client) CreateGenesisTx() (ret []*types.Transaction) {
//316190000 coins //316190000 coins
func createTicket(cfg *types.Chain33Config, 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 := types.Transaction{}
tx1.Execer = []byte("coins") tx1.Execer = []byte(cfg.GetCoinExec())
//给hotkey 10000 个币,作为miner的手续费 //给hotkey 10000 个币,作为miner的手续费
tx1.To = minerAddr tx1.To = minerAddr
...@@ -132,7 +132,7 @@ func createTicket(cfg *types.Chain33Config, minerAddr, returnAddr string, count ...@@ -132,7 +132,7 @@ func createTicket(cfg *types.Chain33Config, minerAddr, returnAddr string, count
tx2 := types.Transaction{} tx2 := types.Transaction{}
tx2.Execer = []byte("coins") tx2.Execer = []byte(cfg.GetCoinExec())
tx2.To = driver.ExecAddress("ticket") tx2.To = driver.ExecAddress("ticket")
//gen payload //gen payload
g = &cty.CoinsAction_Genesis{} g = &cty.CoinsAction_Genesis{}
......
...@@ -269,7 +269,7 @@ func (a *Action) Apply(payload *et.Apply) (*types.Receipt, error) { ...@@ -269,7 +269,7 @@ func (a *Action) Apply(payload *et.Apply) (*types.Receipt, error) {
accountM.Status = et.Normal accountM.Status = et.Normal
//TODO 这里只做coins主笔资产得自动划转,token资产转移,放在转transfer中执行 fromAccountID == toAccountID //TODO 这里只做coins主笔资产得自动划转,token资产转移,放在转transfer中执行 fromAccountID == toAccountID
cfg := a.api.GetConfig() cfg := a.api.GetConfig()
coinsAssetDB, err := account.NewAccountDB(cfg, "coins", cfg.GetCoinSymbol(), a.statedb) coinsAssetDB, err := account.NewAccountDB(cfg, cfg.GetCoinExec(), cfg.GetCoinSymbol(), a.statedb)
if err != nil { if err != nil {
return nil, err return nil, err
} }
......
all:
bash build.sh $(OUT) $(FLAG)
#!/bin/bash
strpwd=$(pwd)
strcmd=${strpwd##*dapp/}
strapp=${strcmd%/cmd*}
OUT_DIR="${1}/system/$strapp"
#FLAG=$2
mkdir -p "${OUT_DIR}"
cp ./build/* "${OUT_DIR}"
#!/usr/bin/env bash
coinsTxHashs1=("")
#coinsTxHashs2=("")
coinsgStr=""
coinsRepeatTx=1 #重复发送交易次数
coinsTotalAmount1="0"
coinsTxAmount="5" #每次发送交易数
#defaultTxFee="0.001"
coinsAddr1=""
coinsTxSign=("")
function initCoinsAccount() {
name="${CLI}"
label="coinstest1"
createAccount "${name}" $label
coinsAddr1=$coinsgStr
sleep 1
name="${CLI}"
fromAdd="12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv"
showCoinsBalance "${name}" $fromAdd
coinsTotalAmount1=$coinsgStr
shouAccountList "${name}"
}
function genFirstChainCoinstx() {
echo "====== 发送coins交易 ======"
name=$CLI
echo "当前链为:${name}"
for ((i = 0; i < coinsRepeatTx; i++)); do
From="12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv"
to=$coinsAddr1
note="coinstx"
amount=$coinsTxAmount
genCoinsTx "${name}" $From $to $note $amount
coinsTxSign[$i]="${coinsgStr}"
block_wait_timeout "${CLI}" 1 20
#发送交易
sendCoinsTxHash "${name}" "${coinsgStr}"
coinsTxHashs1[$i]="${coinsgStr}"
sleep 1
height=$(${name} block last_header | jq ".height")
printf '发送第 %d 笔交易当前高度 %s \n' $i "${height}"
done
}
function genSecondChainCoinstx() {
echo "====== 发送交易 ======"
name=$CLI
echo "当前链为:${name}"
#将第一条链产生的签名交易发送出去
for ((i = 0; i < ${#coinsTxSign[*]}; i++)); do
#发送交易
sign="${coinsTxSign[$i]}"
sendCoinsTxHash "${name}" "${sign}"
sleep 1
height=$(${name} block last_header | jq ".height")
printf '发送第 %d 笔交易当前高度 %s \n' $i "${height}"
done
}
function checkCoinsResult() {
name=$CLI
echo "====================检查第一组docker运行结果================="
totalCoinsTxAmount="0"
for ((i = 0; i < ${#coinsTxHashs1[*]}; i++)); do
txHash=${coinsTxHashs1[$i]}
echo $txHash
txQuery "${name}" $txHash
result=$?
if [ $result -eq 0 ]; then
#coinsTxFee1=$(echo "$coinsTxFee1 + $defaultTxFee" | bc)
totalCoinsTxAmount=$(echo "$totalCoinsTxAmount + $coinsTxAmount" | bc)
fi
sleep 1
done
sleep 1
fromAdd="12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv"
showCoinsBalance "${name}" $fromAdd
value1=$coinsgStr
sleep 1
fromAdd=$coinsAddr1
showCoinsBalance "${name}" $fromAdd
value2=$coinsgStr
actTotal=$(echo "$value1 + $value2 " | bc)
echo "${name} 实际金额:$actTotal"
#if [ `echo "${actTotal} > ${coinsTotalAmount1}" | bc` -eq 1 ]; then
if [ "$(echo "${actTotal} > ${coinsTotalAmount1}" | bc)" -eq 1 ]; then
echo "${name} 出现双花"
exit 1
else
echo "${name} 未出现双花"
fi
}
function sendcoinsTx() {
name=$1
fromAdd=$2
toAdd=$3
note=$4
amount=$5
#组合形式交易
#hash=$(sudo docker exec -it $1 ./chain33-cli coins transfer -t $2 -a $5 -n $4 | tr '\r' ' ')
#echo $hash
#sign=$(sudo docker exec -it $1 ./chain33-cli wallet sign -a $3 -d $hash | tr '\r' ' ')
#echo $sign
#sudo docker exec -it $1 ./chain33-cli wallet send -d $sign
#单个命令形式交易
#sudo docker exec -it $1 ./chain33-cli send coins transfer -a $5 -n $4 -t $2 -k $From
result=$($name send coins transfer -a "${amount}" -n "${note}" -t "${toAdd}" -k "${fromAdd}" | tr '\r' ' ')
echo "hash: $result"
coinsgStr=$result
}
function genCoinsTx() {
name=$1
fromAdd=$2
toAdd=$3
note=$4
amount=$5
expire="600s"
#组合形式交易
hash=$(${name} coins transfer -t "${toAdd}" -a "${amount}" -n "${note}" | tr '\r' ' ')
echo "${hash}"
sign=$(${name} wallet sign -a "${fromAdd}" -d "${hash}" -e "${expire}" | tr '\r' ' ')
echo "sign: $sign"
coinsgStr=$sign
}
function sendCoinsTxHash() {
name=$1
sign=$2
result=$(${name} wallet send -d "${sign}" | tr '\r' ' ')
echo "hash: $result"
coinsgStr=$result
}
function showCoinsBalance() {
name=$1
fromAdd=$2
printf '==========showCoinBalance name=%s addr=%s==========\n' "${name}" "${fromAdd}"
result=$($name account balance -e coins -a "${fromAdd}" | jq -r ".balance")
printf 'balance %s \n' "${result}"
coinsgStr=$result
}
function createAccount() {
name=$1
label=$2
printf '==========CreateAccount name=%s ==========\n' "${name}"
result=$($name account create -l "${label}" | jq -r ".acc.addr")
printf 'New account addr %s \n' "${result}"
coinsgStr=$result
}
function shouAccountList() {
name=$1
printf '==========shouAccountList name=%s ==========\n' "${name}"
$name account list
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
import (
"github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/types"
coinsTy "github.com/33cn/plugin/plugin/dapp/coinsx/types"
"github.com/spf13/cobra"
)
// CoinsxCmd coinsx 命令行
func CoinsxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "coinsx",
Short: "coins management",
Args: cobra.MinimumNArgs(1),
}
cmd.AddCommand(
CoinsXConfigCmd(),
coinsXQueryCmd(),
)
return cmd
}
// CoinsXConfigCmd create coinsx config cmd
func CoinsXConfigCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "config",
Short: "Create coins config transaction",
}
cmd.AddCommand(transferFlagCmd())
cmd.AddCommand(manageAccountsCmd())
return cmd
}
func transferFlagCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "transfer",
Short: "config p2p transfer limit flag",
Run: createTransferFlagTx,
}
addTransferFlags(cmd)
return cmd
}
func addTransferFlags(cmd *cobra.Command) {
cmd.Flags().Uint32P("flag", "f", 0, "set p2p transfer flag,1:enable,2:disable")
cmd.MarkFlagRequired("flag")
}
func createTransferFlagTx(cmd *cobra.Command, args []string) {
flag, _ := cmd.Flags().GetUint32("flag")
paraName, _ := cmd.Flags().GetString("paraName")
config := &coinsTy.CoinsConfig{}
config.Ty = coinsTy.ConfigType_TRANSFER
config.Value = &coinsTy.CoinsConfig_TransferFlag{&coinsTy.TransferFlagConfig{Flag: coinsTy.TransferFlag(flag)}}
params := &rpctypes.CreateTxIn{
Execer: getRealExecName(paraName, coinsTy.CoinsxX),
ActionName: "Config",
Payload: types.MustPBToJSON(config),
}
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
ctx := jsonclient.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, nil)
ctx.RunWithoutMarshal()
}
func manageAccountsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "manager",
Short: "config manage accounts",
Run: createManageAccountsTx,
}
addManageAccountsFlags(cmd)
return cmd
}
func addManageAccountsFlags(cmd *cobra.Command) {
cmd.Flags().Uint32P("op", "o", 0, "modify manager accounts,0:add,1:delete")
cmd.MarkFlagRequired("op")
cmd.Flags().StringP("accounts", "a", "", "accounts to modify, seperate with ',' ")
cmd.MarkFlagRequired("accounts")
}
func createManageAccountsTx(cmd *cobra.Command, args []string) {
op, _ := cmd.Flags().GetUint32("op")
accounts, _ := cmd.Flags().GetString("accounts")
paraName, _ := cmd.Flags().GetString("paraName")
config := &coinsTy.CoinsConfig{}
config.Ty = coinsTy.ConfigType_ACCOUNTS
config.Value = &coinsTy.CoinsConfig_ManagerAccounts{
&coinsTy.ManagerAccountsConfig{
Op: coinsTy.AccountOp(op),
Accounts: accounts,
},
}
params := &rpctypes.CreateTxIn{
Execer: getRealExecName(paraName, coinsTy.CoinsxX),
ActionName: "Config",
Payload: types.MustPBToJSON(config),
}
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
ctx := jsonclient.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, nil)
ctx.RunWithoutMarshal()
}
// coinsXConfigCmd create coinsx query cmd
func coinsXQueryCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "query",
Short: "query coinsx config status",
}
cmd.AddCommand(queryManagerAddrsCmd())
return cmd
}
// queryManagerAddrsCmd get transfer flag cmd
func queryManagerAddrsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "manager",
Short: "Query manager status",
Run: queryManager,
}
return cmd
}
func queryManager(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var params rpctypes.Query4Jrpc
params.Execer = "coinsx"
params.FuncName = "GetManagerStatus"
params.Payload = types.MustPBToJSON(&types.ReqNil{})
var res coinsTy.ManagerStatus
ctx := jsonclient.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
ctx.Run()
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
import (
"strings"
"github.com/33cn/chain33/common/address"
"github.com/33cn/chain33/types"
)
// GetExecAddr 获取执行器地址
func GetExecAddr(exec string) (string, error) {
if ok := types.IsAllowExecName([]byte(exec), []byte(exec)); !ok {
return "", types.ErrExecNameNotAllow
}
addrResult := address.ExecAddress(exec)
result := addrResult
return result, nil
}
func getRealExecName(paraName string, name string) string {
if strings.HasPrefix(name, "user.p.") {
return name
}
return paraName + name
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"strings"
"github.com/33cn/chain33/account"
"github.com/33cn/chain33/client"
dbm "github.com/33cn/chain33/common/db"
"github.com/33cn/chain33/system/dapp"
manager "github.com/33cn/chain33/system/dapp/manage/types"
"github.com/33cn/chain33/types"
coinTy "github.com/33cn/plugin/plugin/dapp/coinsx/types"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
)
type action struct {
coinsAccount *account.DB
db dbm.KV
localdb dbm.KVDB
txhash []byte
fromaddr string
blocktime int64
height int64
execaddr string
api client.QueueProtocolAPI
tx *types.Transaction
exec *Coinsx
}
func newAction(t *Coinsx, tx *types.Transaction) *action {
hash := tx.Hash()
fromaddr := tx.From()
return &action{t.GetCoinsAccount(), t.GetStateDB(), t.GetLocalDB(), hash, fromaddr,
t.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI(), tx, t}
}
func makeManagerStatusReceipt(prev, current *coinTy.ManagerStatus) *types.Receipt {
key := calcManagerStatusKey()
log := &coinTy.ReceiptManagerStatus{
Prev: prev,
Curr: current,
}
return &types.Receipt{
Ty: types.ExecOk,
KV: []*types.KeyValue{
{Key: key, Value: types.Encode(current)},
},
Logs: []*types.ReceiptLog{
{
Ty: coinTy.TyCoinsxManagerStatusLog,
Log: types.Encode(log),
},
},
}
}
// isSuperManager is supper manager or not
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
}
}
return false
}
func getSuperManager(cfg *types.Chain33Config) []string {
confManager := types.ConfSub(cfg, manager.ManageX)
return confManager.GStrList("superManager")
}
func getManagerStatus(db dbm.KV) (*coinTy.ManagerStatus, error) {
key := calcManagerStatusKey()
val, err := db.Get(key)
if err != nil {
return nil, err
}
var status coinTy.ManagerStatus
err = types.Decode(val, &status)
return &status, err
}
func (a *action) configTransfer(config *coinTy.TransferFlagConfig) (*types.Receipt, error) {
if config.Flag != coinTy.TransferFlag_DISABLE && config.Flag != coinTy.TransferFlag_ENABLE {
return nil, errors.Wrapf(types.ErrInvalidParam, "flag=%d", config.Flag)
}
stat, err := getManagerStatus(a.db)
if err == types.ErrNotFound {
stat = &coinTy.ManagerStatus{TransferFlag: config.Flag}
return makeManagerStatusReceipt(nil, stat), nil
}
if err != nil {
return nil, errors.Wrap(err, "get manager status")
}
if stat != nil && stat.TransferFlag == config.Flag {
return nil, errors.Wrapf(types.ErrInvalidParam, "same flag set, cur=%d,config=%d", stat.TransferFlag, config.Flag)
}
copyStat := proto.Clone(stat).(*coinTy.ManagerStatus)
stat.TransferFlag = config.Flag
return makeManagerStatusReceipt(copyStat, stat), nil
}
func filterAddrs(addrs []string) []string {
f := make(map[string]bool)
var newAddrs []string
for _, k := range addrs {
if !f[k] {
f[k] = true
newAddrs = append(newAddrs, k)
}
}
return newAddrs
}
func (a *action) addAccounts(addrs []string) (*types.Receipt, error) {
curStat, err := getManagerStatus(a.db)
if err == types.ErrNotFound {
stat := &coinTy.ManagerStatus{TransferFlag: coinTy.TransferFlag_DISABLE}
stat.ManagerAccounts = append(stat.ManagerAccounts, addrs...)
return makeManagerStatusReceipt(nil, stat), nil
}
if err != nil {
return nil, err
}
copyStat := proto.Clone(curStat).(*coinTy.ManagerStatus)
curStat.ManagerAccounts = append(curStat.ManagerAccounts, addrs...)
curStat.ManagerAccounts = filterAddrs(curStat.ManagerAccounts)
return makeManagerStatusReceipt(copyStat, curStat), nil
}
func filterByAddrs(curr, del []string) []string {
f := make(map[string]bool)
for _, k := range del {
f[k] = true
}
var newAddrs []string
for _, k := range curr {
if !f[k] {
newAddrs = append(newAddrs, k)
}
}
return newAddrs
}
func (a *action) delAccounts(addrs []string) (*types.Receipt, error) {
curStat, err := getManagerStatus(a.db)
if err != nil || err == types.ErrNotFound {
return nil, err
}
copyStat := proto.Clone(curStat).(*coinTy.ManagerStatus)
curStat.ManagerAccounts = filterByAddrs(curStat.ManagerAccounts, addrs)
return makeManagerStatusReceipt(copyStat, curStat), nil
}
func (a *action) configAccounts(config *coinTy.ManagerAccountsConfig) (*types.Receipt, error) {
if config.Op != coinTy.AccountOp_ADD && config.Op != coinTy.AccountOp_DEL {
return nil, errors.Wrapf(types.ErrInvalidParam, "unsupport op=%d ", config.Op)
}
if len(config.Accounts) <= 0 {
return nil, errors.Wrapf(types.ErrInvalidParam, "config accounts=%s", config.Accounts)
}
addrs := strings.Split(config.Accounts, ",")
if config.Op == coinTy.AccountOp_ADD {
return a.addAccounts(addrs)
}
return a.delAccounts(addrs)
}
func (a *action) config(config *coinTy.CoinsConfig, tx *types.Transaction, index int) (*types.Receipt, error) {
cfg := a.api.GetConfig()
from := tx.From()
//from 必须是超级管理员
if !isSuperManager(cfg, from) {
return nil, errors.Wrapf(types.ErrNotAllow, "from=%s is not super manager", from)
}
switch config.Ty {
case coinTy.ConfigType_TRANSFER:
return a.configTransfer(config.GetTransferFlag())
case coinTy.ConfigType_ACCOUNTS:
return a.configAccounts(config.GetManagerAccounts())
}
return nil, errors.Wrapf(types.ErrInvalidParam, "config type=%d not support", config.Ty)
}
func isManager(addr string, managers []string) bool {
for _, m := range managers {
if addr == m {
return true
}
}
return false
}
func checkTransferEnable(cfg *types.Chain33Config, db dbm.KV, from, to string) bool {
stat, _ := getManagerStatus(db)
if stat != nil {
//如果转账不受限,则可以任意转账
if stat.TransferFlag == coinTy.TransferFlag_ENABLE {
return true
}
//如果转账受限,则任一方是管理员才允许转账
if isManager(from, stat.ManagerAccounts) || isManager(to, stat.ManagerAccounts) {
return true
}
}
//转账受限,允许节点配置的超级管理员
suppers := getSuperManager(cfg)
if isManager(from, suppers) || isManager(to, suppers) {
return true
}
return false
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package executor coins执行器
package executor
/*
coins 是一个货币的exec。内置货币的执行器。
主要提供两种操作:
EventTransfer -> 转移资产
*/
// package none execer for unknow execer
// all none transaction exec ok, execept nofee
// nofee transaction will not pack into block
import (
log "github.com/33cn/chain33/common/log/log15"
drivers "github.com/33cn/chain33/system/dapp"
"github.com/33cn/chain33/types"
coinsTy "github.com/33cn/plugin/plugin/dapp/coinsx/types"
)
// var clog = log.New("module", "execs.coins")
var (
driverName = coinsTy.CoinsxX
clog = log.New("module", "execs.paracross")
)
// Init defines a register function
func Init(name string, cfg *types.Chain33Config, sub []byte) {
if name != driverName {
panic("system dapp can't be rename")
}
// 需要先 RegisterDappFork才可以Register dapp
drivers.Register(cfg, driverName, newCoinsx, cfg.GetDappFork(driverName, "Enable"))
InitExecType()
setPrefix()
}
//InitExecType the initialization process is relatively heavyweight, lots of reflect, so it's global
func InitExecType() {
ety := types.LoadExecutorType(driverName)
ety.InitFuncList(types.ListMethod(&Coinsx{}))
}
// GetName return name string
func GetName() string {
return newCoinsx().GetName()
}
// Coins defines coins
type Coinsx struct {
drivers.DriverBase
}
func newCoinsx() drivers.Driver {
c := &Coinsx{}
c.SetChild(c)
c.SetExecutorType(types.LoadExecutorType(driverName))
return c
}
// GetDriverName get drive name
func (c *Coinsx) GetDriverName() string {
return driverName
}
// CheckTx check transaction amount 必须不能为负数
func (c *Coinsx) CheckTx(tx *types.Transaction, index int) error {
ety := c.GetExecutorType()
amount, err := ety.Amount(tx)
if err != nil {
return err
}
if amount < 0 {
return types.ErrAmount
}
return nil
}
// IsFriend Coinsx contract the mining transaction that runs the ticket contract
func (c *Coinsx) IsFriend(myexec, writekey []byte, othertx *types.Transaction) bool {
//step1 先判定自己合约的权限
if !c.AllowIsSame(myexec) {
return false
}
//step2 判定 othertx 的 执行器名称(只允许主链,并且是挖矿的行为)
types.AssertConfig(c.GetAPI())
types := c.GetAPI().GetConfig()
if othertx.ActionName() == "miner" {
for _, exec := range types.GetMinerExecs() {
if types.ExecName(exec) == string(othertx.Execer) {
return true
}
}
}
return false
}
// CheckReceiptExecOk return true to check if receipt ty is ok
func (c *Coinsx) CheckReceiptExecOk() bool {
return true
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
/*
coins 是一个货币的exec。内置货币的执行器。
主要提供两种操作:
EventTransfer -> 转移资产
*/
// package none execer for unknow execer
// all none transaction exec ok, execept nofee
// nofee transaction will not pack into block
import (
"fmt"
dbm "github.com/33cn/chain33/common/db"
"github.com/33cn/chain33/types"
)
// calcAddrKey store information on the receiving address
func calcAddrKey(addr string) []byte {
return []byte(fmt.Sprintf("LODB-coinsx-Addr:%s", addr))
}
func geAddrReciverKV(addr string, reciverAmount int64) *types.KeyValue {
reciver := &types.Int64{Data: reciverAmount}
amountbytes := types.Encode(reciver)
kv := &types.KeyValue{Key: calcAddrKey(addr), Value: amountbytes}
return kv
}
func getAddrReciver(db dbm.KVDB, addr string) (int64, error) {
reciver := types.Int64{}
addrReciver, err := db.Get(calcAddrKey(addr))
if err != nil && err != types.ErrNotFound {
return 0, err
}
if len(addrReciver) == 0 {
return 0, nil
}
err = types.Decode(addrReciver, &reciver)
if err != nil {
return 0, err
}
return reciver.Data, nil
}
func setAddrReciver(db dbm.KVDB, addr string, reciverAmount int64) error {
kv := geAddrReciverKV(addr, reciverAmount)
return db.Set(kv.Key, kv.Value)
}
func updateAddrReciver(cachedb dbm.KVDB, addr string, amount int64, isadd bool) (*types.KeyValue, error) {
recv, err := getAddrReciver(cachedb, addr)
if err != nil && err != types.ErrNotFound {
return nil, err
}
if isadd {
recv += amount
} else {
recv -= amount
}
err = setAddrReciver(cachedb, addr, recv)
if err != nil {
return nil, err
}
//keyvalue
return geAddrReciverKV(addr, recv), nil
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"encoding/hex"
"github.com/33cn/chain33/common/address"
drivers "github.com/33cn/chain33/system/dapp"
"github.com/33cn/chain33/types"
"github.com/pkg/errors"
coinTy "github.com/33cn/plugin/plugin/dapp/coinsx/types"
)
// Exec_Transfer transfer of exec
func (c *Coinsx) Exec_Transfer(transfer *types.AssetsTransfer, tx *types.Transaction, index int) (*types.Receipt, error) {
from := tx.From()
to := tx.GetRealToAddr()
if !checkTransferEnable(c.GetAPI().GetConfig(), c.GetStateDB(), from, to) {
return nil, errors.Wrapf(types.ErrNotAllow, "transfer is limited from=%s to=%s", from, to)
}
//to 是 execs 合约地址
if drivers.IsDriverAddress(to, c.GetHeight()) {
return c.GetCoinsAccount().TransferToExec(from, to, transfer.Amount)
}
return c.GetCoinsAccount().Transfer(from, to, transfer.Amount)
}
// Exec_TransferToExec the transfer to exec address
func (c *Coinsx) Exec_TransferToExec(transfer *types.AssetsTransferToExec, tx *types.Transaction, index int) (*types.Receipt, error) {
types.AssertConfig(c.GetAPI())
cfg := c.GetAPI().GetConfig()
if !cfg.IsFork(c.GetHeight(), "ForkTransferExec") {
return nil, types.ErrActionNotSupport
}
from := tx.From()
to := tx.GetRealToAddr()
//to 是 execs 合约地址
if !isExecAddrMatch(transfer.ExecName, to) {
return nil, types.ErrToAddrNotSameToExecAddr
}
if !checkTransferEnable(cfg, c.GetStateDB(), from, to) {
return nil, errors.Wrapf(types.ErrNotAllow, "transfer is limited from=%s to=%s", from, to)
}
return c.GetCoinsAccount().TransferToExec(from, to, transfer.Amount)
}
// Exec_Withdraw withdraw exec
func (c *Coinsx) Exec_Withdraw(withdraw *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) {
types.AssertConfig(c.GetAPI())
cfg := c.GetAPI().GetConfig()
if !cfg.IsFork(c.GetHeight(), "ForkWithdraw") {
withdraw.ExecName = ""
}
from := tx.From()
to := tx.GetRealToAddr()
if !checkTransferEnable(cfg, c.GetStateDB(), from, to) {
return nil, errors.Wrapf(types.ErrNotAllow, "transfer is limited from=%s to=%s", from, to)
}
//to 是 execs 合约地址
if drivers.IsDriverAddress(tx.GetRealToAddr(), c.GetHeight()) || isExecAddrMatch(withdraw.ExecName, tx.GetRealToAddr()) {
return c.GetCoinsAccount().TransferWithdraw(from, tx.GetRealToAddr(), withdraw.Amount)
}
return nil, types.ErrActionNotSupport
}
// Exec_Genesis genesis of exec
func (c *Coinsx) Exec_Genesis(genesis *types.AssetsGenesis, tx *types.Transaction, index int) (*types.Receipt, error) {
if c.GetHeight() == 0 {
if drivers.IsDriverAddress(tx.GetRealToAddr(), c.GetHeight()) {
return c.GetCoinsAccount().GenesisInitExec(genesis.ReturnAddress, genesis.Amount, tx.GetRealToAddr())
}
return c.GetCoinsAccount().GenesisInit(tx.GetRealToAddr(), genesis.Amount)
}
return nil, types.ErrReRunGenesis
}
func isExecAddrMatch(name string, to string) bool {
toaddr := address.ExecAddress(name)
return toaddr == to
}
// Exec_Config genesis of exec
func (c *Coinsx) Exec_Config(config *coinTy.CoinsConfig, tx *types.Transaction, index int) (*types.Receipt, error) {
a := newAction(c, tx)
receipt, err := a.config(config, tx, index)
if err != nil {
clog.Error("Coins config failed", "error", err, "hash", hex.EncodeToString(tx.Hash()))
return nil, err
}
return receipt, nil
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
)
// ExecDelLocal_Transfer delete transfer of local exec
func (c *Coinsx) ExecDelLocal_Transfer(transfer *types.AssetsTransfer, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := updateAddrReciver(c.GetLocalDB(), tx.GetRealToAddr(), transfer.Amount, false)
if err != nil {
return nil, err
}
return &types.LocalDBSet{KV: []*types.KeyValue{kv}}, nil
}
// ExecDelLocal_TransferToExec delete transfer of local exec to exec
func (c *Coinsx) ExecDelLocal_TransferToExec(transfer *types.AssetsTransferToExec, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := updateAddrReciver(c.GetLocalDB(), tx.GetRealToAddr(), transfer.Amount, false)
if err != nil {
return nil, err
}
return &types.LocalDBSet{KV: []*types.KeyValue{kv}}, nil
}
// ExecDelLocal_Withdraw delete withdraw of local exec
func (c *Coinsx) ExecDelLocal_Withdraw(withdraw *types.AssetsWithdraw, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
from := tx.From()
kv, err := updateAddrReciver(c.GetLocalDB(), from, withdraw.Amount, false)
if err != nil {
return nil, err
}
return &types.LocalDBSet{KV: []*types.KeyValue{kv}}, nil
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
)
// ExecLocal_Transfer transfer of local exec
func (c *Coinsx) ExecLocal_Transfer(transfer *types.AssetsTransfer, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := updateAddrReciver(c.GetLocalDB(), tx.GetRealToAddr(), transfer.Amount, true)
if err != nil {
return nil, err
}
return &types.LocalDBSet{KV: []*types.KeyValue{kv}}, nil
}
// ExecLocal_TransferToExec transfer of local exec to exec
func (c *Coinsx) ExecLocal_TransferToExec(transfer *types.AssetsTransferToExec, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := updateAddrReciver(c.GetLocalDB(), tx.GetRealToAddr(), transfer.Amount, true)
if err != nil {
return nil, err
}
return &types.LocalDBSet{KV: []*types.KeyValue{kv}}, nil
}
// ExecLocal_Withdraw withdraw local exec
func (c *Coinsx) ExecLocal_Withdraw(withdraw *types.AssetsWithdraw, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
from := tx.From()
kv, err := updateAddrReciver(c.GetLocalDB(), from, withdraw.Amount, true)
if err != nil {
return nil, err
}
return &types.LocalDBSet{KV: []*types.KeyValue{kv}}, nil
}
// ExecLocal_Genesis Genesis of local exec
func (c *Coinsx) ExecLocal_Genesis(gen *types.AssetsGenesis, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := updateAddrReciver(c.GetLocalDB(), tx.GetRealToAddr(), gen.Amount, true)
if err != nil {
return nil, err
}
return &types.LocalDBSet{KV: []*types.KeyValue{kv}}, nil
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
var (
managerStatus string
)
func setPrefix() {
managerStatus = "mavl-coinsx-managerStatus-"
}
func calcManagerStatusKey() []byte {
return []byte(managerStatus)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
)
// Query_GetAddrReciver query of get address reciver
func (c *Coinsx) Query_GetAddrReciver(in *types.ReqAddr) (types.Message, error) {
return c.GetAddrReciver(in)
}
// Query_GetTxsByAddr query get txs by address
func (c *Coinsx) Query_GetTxsByAddr(in *types.ReqAddr) (types.Message, error) {
return c.GetTxsByAddr(in)
}
// Query_GetPrefixCount query key counts in the prefix
func (c *Coinsx) Query_GetPrefixCount(in *types.ReqKey) (types.Message, error) {
return c.GetPrefixCount(in)
}
// Query_GetAddrTxsCount query count of txs in the address
func (c *Coinsx) Query_GetAddrTxsCount(in *types.ReqKey) (types.Message, error) {
return c.GetAddrTxsCount(in)
}
// GetAddrReciver get address reciver by address
func (c *Coinsx) GetAddrReciver(addr *types.ReqAddr) (types.Message, error) {
reciver := types.Int64{}
db := c.GetLocalDB()
addrReciver, err := db.Get(calcAddrKey(addr.Addr))
if addrReciver == nil || err != nil {
return &reciver, types.ErrEmpty
}
err = types.Decode(addrReciver, &reciver)
if err != nil {
return &reciver, err
}
return &reciver, nil
}
func (c *Coinsx) Query_GetManagerStatus(in *types.ReqNil) (types.Message, error) {
return getManagerStatus(c.GetStateDB())
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package coins 系统级coins dapp插件
package coinsx
import (
"github.com/33cn/chain33/pluginmgr"
"github.com/33cn/plugin/plugin/dapp/coinsx/commands"
"github.com/33cn/plugin/plugin/dapp/coinsx/executor"
"github.com/33cn/plugin/plugin/dapp/coinsx/types"
)
func init() {
pluginmgr.Register(&pluginmgr.PluginBase{
Name: types.CoinsxX,
ExecName: executor.GetName(),
Exec: executor.Init,
Cmd: commands.CoinsxCmd,
RPC: nil,
})
}
all:
sh ./create_protobuf.sh
syntax = "proto3";
package types;
import "transaction.proto";
option go_package = "types";
// message for execs.coinsx
message CoinsxAction {
oneof value {
AssetsTransfer transfer = 1;
AssetsWithdraw withdraw = 4;
AssetsGenesis genesis = 2;
AssetsTransferToExec transferToExec = 5;
CoinsConfig config = 6;
}
int32 ty = 3;
}
//kvmvcc statedb not support 0 value
enum TransferFlag {
NONE = 0;
ENABLE = 1;
DISABLE = 2;
}
message TransferFlagConfig {
TransferFlag flag = 1;
}
message ManagerStatus {
TransferFlag transferFlag = 1;
repeated string managerAccounts = 2;
}
message ReceiptManagerStatus {
ManagerStatus prev = 2;
ManagerStatus curr = 3;
}
enum AccountOp {
ADD = 0;
DEL = 1;
}
message ManagerAccountsConfig {
AccountOp op = 1;
string accounts = 2;
}
enum ConfigType {
INVALID = 0;
TRANSFER = 1;
ACCOUNTS = 2;
}
message CoinsConfig {
ConfigType ty = 1;
oneof value {
TransferFlagConfig transferFlag = 2;
ManagerAccountsConfig managerAccounts = 3;
}
}
\ No newline at end of file
#!/bin/sh
chain33_path=$(go list -f '{{.Dir}}' "github.com/33cn/chain33")
protoc --go_out=plugins=grpc:../types ./*.proto --proto_path=. --proto_path="${chain33_path}/types/proto/"
This diff is collapsed.
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"testing"
cty "github.com/33cn/chain33/system/dapp/coins/types"
"github.com/33cn/chain33/types"
"github.com/stretchr/testify/assert"
)
func TestMethodCall(t *testing.T) {
action := &CoinsxAction{Value: &CoinsxAction_Transfer{Transfer: &types.AssetsTransfer{}}}
funclist := types.ListMethod(action)
name, ty, v, err := types.GetActionValue(action, funclist)
assert.Nil(t, err)
assert.Equal(t, int32(0), ty)
assert.Equal(t, "Transfer", name)
assert.Equal(t, &types.AssetsTransfer{}, v.Interface())
}
func TestListMethod(t *testing.T) {
action := &CoinsxAction{Value: &CoinsxAction_Transfer{Transfer: &types.AssetsTransfer{}}}
funclist := types.ListMethod(action)
excpect := []string{"GetWithdraw", "GetGenesis", "GetTransfer", "GetTransferToExec", "GetValue"}
for _, v := range excpect {
if _, ok := funclist[v]; !ok {
t.Error(v + " is not in list")
}
}
}
func TestListType(t *testing.T) {
excpect := []string{"Value_Withdraw", "Withdraw", "Value_Transfer", "Value_Genesis", "Value_TransferToExec", "Value_Config"}
cfg := types.NewChain33Config(types.GetDefaultCfgstring())
for _, v := range excpect {
if _, ok := NewType(cfg).GetValueTypeMap()[v]; !ok {
t.Error(v + " is not in list")
}
}
}
func BenchmarkGetActionValue(b *testing.B) {
action := &CoinsxAction{Value: &CoinsxAction_Transfer{Transfer: &types.AssetsTransfer{}}}
funclist := types.ListMethod(action)
b.ResetTimer()
for i := 0; i < b.N; i++ {
action, ty, _, _ := types.GetActionValue(action, funclist)
if action != "Transfer" || ty != 0 {
b.Fatal(action)
}
}
}
func BenchmarkDecodePayload(b *testing.B) {
action := &CoinsxAction{Value: &CoinsxAction_Transfer{Transfer: &types.AssetsTransfer{}}}
payload := types.Encode(action)
tx := &types.Transaction{Payload: payload}
ty := NewType(types.NewChain33Config(types.GetDefaultCfgstring()))
b.ResetTimer()
for i := 0; i < b.N; i++ {
ty.DecodePayload(tx)
}
}
func BenchmarkDecodePayloadValue(b *testing.B) {
b.ReportAllocs()
action := &CoinsxAction{Value: &CoinsxAction_Transfer{Transfer: &types.AssetsTransfer{}}, Ty: cty.CoinsActionTransfer}
payload := types.Encode(action)
tx := &types.Transaction{Payload: payload}
ty := NewType(types.NewChain33Config(types.GetDefaultCfgstring()))
b.ResetTimer()
for i := 0; i < b.N; i++ {
ty.DecodePayloadValue(tx)
}
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"reflect"
log "github.com/33cn/chain33/common/log/log15"
cty "github.com/33cn/chain33/system/dapp/coins/types"
"github.com/33cn/chain33/types"
)
const (
//CoinsActionConfig Config transfer or manager addrs
CoinsActionConfig = 20
//TyCoinsxManagerStatusLog config manager status log
TyCoinsxManagerStatusLog = 601
)
var (
CoinsxX = "coinsx"
// ExecerCoins execer coins
ExecerCoins = []byte(CoinsxX)
actionName = map[string]int32{
//Transfer..Genesis same as to coins, not redefine
"Transfer": cty.CoinsActionTransfer,
"TransferToExec": cty.CoinsActionTransferToExec,
"Withdraw": cty.CoinsActionWithdraw,
"Genesis": cty.CoinsActionGenesis,
//new add Config action to coinsx
"Config": CoinsActionConfig,
}
clog = log.New("module", "execs.coinsx.types")
)
func init() {
types.AllowUserExec = append(types.AllowUserExec, ExecerCoins)
types.RegFork(CoinsxX, InitFork)
types.RegExec(CoinsxX, InitExecutor)
}
// InitFork initials coins forks.
func InitFork(cfg *types.Chain33Config) {
cfg.RegisterDappFork(CoinsxX, "Enable", 0)
}
// InitExecutor registers coins.
func InitExecutor(cfg *types.Chain33Config) {
types.RegistorExecutor(CoinsxX, NewType(cfg))
}
// CoinsType defines exec type
type CoinsxType struct {
types.ExecTypeBase
}
// NewType new coinstype
func NewType(cfg *types.Chain33Config) *CoinsxType {
c := &CoinsxType{}
c.SetChild(c)
c.SetConfig(cfg)
return c
}
// GetPayload return payload
func (c *CoinsxType) GetPayload() types.Message {
return &CoinsxAction{}
}
// GetName return coins string
func (c *CoinsxType) GetName() string {
return CoinsxX
}
// GetLogMap return log for map
func (c *CoinsxType) GetLogMap() map[int64]*types.LogInfo {
return map[int64]*types.LogInfo{
TyCoinsxManagerStatusLog: {Ty: reflect.TypeOf(ReceiptManagerStatus{}), Name: "LogConfigManagerStatus"},
}
}
// GetTypeMap return actionname for map
func (c *CoinsxType) GetTypeMap() map[string]int32 {
return actionName
}
//DecodePayloadValue 为了性能考虑,coins 是最常用的合约,我们这里不用反射吗,做了特殊化的优化
func (c *CoinsxType) DecodePayloadValue(tx *types.Transaction) (string, reflect.Value, error) {
name, value, err := c.decodePayloadValue(tx)
return name, value, err
}
func (c *CoinsxType) decodePayloadValue(tx *types.Transaction) (string, reflect.Value, error) {
var action CoinsxAction
if tx.GetPayload() == nil {
return "", reflect.ValueOf(nil), types.ErrActionNotSupport
}
err := types.Decode(tx.Payload, &action)
if err != nil {
return "", reflect.ValueOf(nil), err
}
var name string
var value types.Message
switch action.Ty {
case cty.CoinsActionTransfer:
name = "Transfer"
value = action.GetTransfer()
case cty.CoinsActionTransferToExec:
name = "TransferToExec"
value = action.GetTransferToExec()
case cty.CoinsActionWithdraw:
name = "Withdraw"
value = action.GetWithdraw()
case cty.CoinsActionGenesis:
name = "Genesis"
value = action.GetGenesis()
case CoinsActionConfig:
name = "Config"
value = action.GetConfig()
}
if value == nil {
return "", reflect.ValueOf(nil), types.ErrActionNotSupport
}
return name, reflect.ValueOf(value), nil
}
// RPC_Default_Process default process fo rpc
func (c *CoinsxType) RPC_Default_Process(action string, msg interface{}) (*types.Transaction, error) {
var create *types.CreateTx
if _, ok := msg.(*types.CreateTx); !ok {
return nil, types.ErrInvalidParam
}
create = msg.(*types.CreateTx)
if create.IsToken {
return nil, types.ErrNotSupport
}
tx, err := c.AssertCreate(create)
if err != nil {
return nil, err
}
//to地址的问题,如果是主链交易,to地址就是直接是设置to
types := c.GetConfig()
if !types.IsPara() {
tx.To = create.To
}
return tx, err
}
// GetAssets return asset list
func (c *CoinsxType) GetAssets(tx *types.Transaction) ([]*types.Asset, error) {
assets, err := c.ExecTypeBase.GetAssets(tx)
if err != nil || len(assets) == 0 {
return nil, err
}
types := c.GetConfig()
assets[0].Symbol = types.GetCoinSymbol()
if assets[0].Symbol == "bty" {
assets[0].Symbol = "BTY"
}
return assets, nil
}
...@@ -544,7 +544,7 @@ func sendTransferTx(cfg *types.Chain33Config, fromKey, to string, amount int64) ...@@ -544,7 +544,7 @@ func sendTransferTx(cfg *types.Chain33Config, fromKey, to string, amount int64)
v := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: amount, Note: []byte(""), To: to}} v := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: amount, Note: []byte(""), To: to}}
transfer.Value = v transfer.Value = v
transfer.Ty = cty.CoinsActionTransfer transfer.Ty = cty.CoinsActionTransfer
execer := []byte("coins") execer := []byte(cfg.GetCoinExec())
tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: to, Fee: fee} tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: to, Fee: fee}
tx, err := types.FormatTx(cfg, string(execer), tx) tx, err := types.FormatTx(cfg, string(execer), tx)
if err != nil { if err != nil {
...@@ -579,7 +579,7 @@ func sendTransferToExecTx(cfg *types.Chain33Config, fromKey, execName string, am ...@@ -579,7 +579,7 @@ func sendTransferToExecTx(cfg *types.Chain33Config, fromKey, execName string, am
v := &cty.CoinsAction_TransferToExec{TransferToExec: &types.AssetsTransferToExec{Amount: amount, Note: []byte(""), ExecName: execName, To: execAddr}} v := &cty.CoinsAction_TransferToExec{TransferToExec: &types.AssetsTransferToExec{Amount: amount, Note: []byte(""), ExecName: execName, To: execAddr}}
transfer.Value = v transfer.Value = v
transfer.Ty = cty.CoinsActionTransferToExec transfer.Ty = cty.CoinsActionTransferToExec
execer := []byte("coins") execer := []byte(cfg.GetCoinExec())
tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: address.ExecAddress("guess"), Fee: fee} tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: address.ExecAddress("guess"), Fee: fee}
tx, err := types.FormatTx(cfg, string(execer), tx) tx, err := types.FormatTx(cfg, string(execer), tx)
if err != nil { if err != nil {
......
...@@ -762,7 +762,7 @@ func sendTransferTx(cfg *types.Chain33Config, fromKey, to string, amount int64) ...@@ -762,7 +762,7 @@ func sendTransferTx(cfg *types.Chain33Config, fromKey, to string, amount int64)
v := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: amount, Note: []byte(""), To: to}} v := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: amount, Note: []byte(""), To: to}}
transfer.Value = v transfer.Value = v
transfer.Ty = cty.CoinsActionTransfer transfer.Ty = cty.CoinsActionTransfer
execer := []byte("coins") execer := []byte(cfg.GetCoinExec())
tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: to, Fee: fee} tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: to, Fee: fee}
tx, err := types.FormatTx(cfg, string(execer), tx) tx, err := types.FormatTx(cfg, string(execer), tx)
if err != nil { if err != nil {
...@@ -797,7 +797,7 @@ func sendTransferToExecTx(cfg *types.Chain33Config, fromKey, execName string, am ...@@ -797,7 +797,7 @@ func sendTransferToExecTx(cfg *types.Chain33Config, fromKey, execName string, am
v := &cty.CoinsAction_TransferToExec{TransferToExec: &types.AssetsTransferToExec{Amount: amount, Note: []byte(""), ExecName: execName, To: execAddr}} v := &cty.CoinsAction_TransferToExec{TransferToExec: &types.AssetsTransferToExec{Amount: amount, Note: []byte(""), ExecName: execName, To: execAddr}}
transfer.Value = v transfer.Value = v
transfer.Ty = cty.CoinsActionTransferToExec transfer.Ty = cty.CoinsActionTransferToExec
execer := []byte("coins") execer := []byte(cfg.GetCoinExec())
tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: address.ExecAddress("guess"), Fee: fee} tx = &types.Transaction{Execer: execer, Payload: types.Encode(transfer), To: address.ExecAddress("guess"), Fee: fee}
tx, err := types.FormatTx(cfg, string(execer), tx) tx, err := types.FormatTx(cfg, string(execer), tx)
if err != nil { if err != nil {
......
...@@ -5,6 +5,7 @@ import ( ...@@ -5,6 +5,7 @@ import (
_ "github.com/33cn/plugin/plugin/dapp/autonomy" //auto gen _ "github.com/33cn/plugin/plugin/dapp/autonomy" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/blackwhite" //auto gen _ "github.com/33cn/plugin/plugin/dapp/blackwhite" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/cert" //auto gen _ "github.com/33cn/plugin/plugin/dapp/cert" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/coinsx" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/collateralize" //auto gen _ "github.com/33cn/plugin/plugin/dapp/collateralize" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/dposvote" //auto gen _ "github.com/33cn/plugin/plugin/dapp/dposvote" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/echo" //auto gen _ "github.com/33cn/plugin/plugin/dapp/echo" //auto gen
......
...@@ -11,6 +11,7 @@ PARANAME="para" ...@@ -11,6 +11,7 @@ PARANAME="para"
PARANAME_GAME="game" PARANAME_GAME="game"
PARA_COIN_FROZEN="5.0000" PARA_COIN_FROZEN="5.0000"
MainLoopCheckForkHeight="60" MainLoopCheckForkHeight="60"
COINSEXEC="coinsx"
BLSPUB_E5="8920442cf306fccd11e7bde3cfffe183a138a941f471df0818edff5580b3ad7df42850a5cec15e09aef0fdd4489f7c12" BLSPUB_E5="8920442cf306fccd11e7bde3cfffe183a138a941f471df0818edff5580b3ad7df42850a5cec15e09aef0fdd4489f7c12"
BLSPUB_KS="a3d97d4186c80268fe6d3689dd574599e25df2dffdcff03f7d8ef64a3bd483241b7d0985958990de2d373d5604caf805" BLSPUB_KS="a3d97d4186c80268fe6d3689dd574599e25df2dffdcff03f7d8ef64a3bd483241b7d0985958990de2d373d5604caf805"
...@@ -384,7 +385,7 @@ function para_cross_transfer_withdraw() { ...@@ -384,7 +385,7 @@ function para_cross_transfer_withdraw() {
local times=200 local times=200
while true; do while true; do
acc=$(${CLI} account balance -e paracross -a 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq -r ".balance") acc=$(${CLI} account balance -e paracross -a 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq -r ".balance")
acc_para=$(${PARA_CLI} asset balance -a 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv --asset_exec paracross --asset_symbol coins.bty | jq -r ".balance") acc_para=$(${PARA_CLI} asset balance -a 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv --asset_exec paracross --asset_symbol "${COINSEXEC}".bty | jq -r ".balance")
echo "account balance is ${acc}, expect 9.3, para acct balance is ${acc_para},expect 0.7 " echo "account balance is ${acc}, expect 9.3, para acct balance is ${acc_para},expect 0.7 "
if [ "${acc}" != "9.3000" ] || [ "${acc_para}" != "0.7000" ]; then if [ "${acc}" != "9.3000" ] || [ "${acc_para}" != "0.7000" ]; then
block_wait "${CLI}" 2 block_wait "${CLI}" 2
...@@ -393,7 +394,7 @@ function para_cross_transfer_withdraw() { ...@@ -393,7 +394,7 @@ function para_cross_transfer_withdraw() {
echo "para_cross_transfer_withdraw failed" echo "para_cross_transfer_withdraw failed"
${CLI} tx query -s "$hash2" ${CLI} tx query -s "$hash2"
${PARA_CLI} tx query -s "$hash2" ${PARA_CLI} tx query -s "$hash2"
${PARA_CLI} asset balance -a 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv --asset_exec paracross --asset_symbol coins.bty ${PARA_CLI} asset balance -a 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv --asset_exec paracross --asset_symbol "${COINSEXEC}".bty
exit 1 exit 1
fi fi
else else
...@@ -536,7 +537,7 @@ function para_create_nodegroup_gamechain() { ...@@ -536,7 +537,7 @@ function para_create_nodegroup_gamechain() {
function para_cross_transfer_from_parachain() { function para_cross_transfer_from_parachain() {
echo "=========== # para cross transfer from parachain test =============" echo "=========== # para cross transfer from parachain test ============="
balance=$(${PARA_CLI5} account balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -e user.p.game.coins | jq -r ".balance") balance=$(${PARA_CLI5} account balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -e user.p.game."${COINSEXEC}" | jq -r ".balance")
if [ "${balance}" != "1000.0000" ]; then if [ "${balance}" != "1000.0000" ]; then
echo "para account 1BM2xhBk should be 1000, real is $balance" echo "para account 1BM2xhBk should be 1000, real is $balance"
exit 1 exit 1
...@@ -553,25 +554,25 @@ function para_cross_transfer_from_parachain() { ...@@ -553,25 +554,25 @@ function para_cross_transfer_from_parachain() {
fi fi
echo "========== #1. user.p.game chain transfer to main chain 300 user.p.game.coins.para, remain=0 ===========" echo "========== #1. user.p.game chain transfer to main chain 300 user.p.game.coins.para, remain=0 ==========="
hash=$(${PARA_CLI5} send para cross_transfer -a 300 -e user.p.game.coins -s para -t 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -k 0x128de4afa7c061c00d854a1bca51b58e80a2c292583739e5aebf4c0f778959e1) hash=$(${PARA_CLI5} send para cross_transfer -a 300 -e user.p.game."${COINSEXEC}" -s para -t 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -k 0x128de4afa7c061c00d854a1bca51b58e80a2c292583739e5aebf4c0f778959e1)
echo "${hash}" echo "${hash}"
query_tx "${PARA_CLI5}" "${hash}" query_tx "${PARA_CLI5}" "${hash}"
check_cross_transfer_game_balance "300.0000" "0.0000" "${hash}" check_cross_transfer_game_balance "300.0000" "0.0000" "${hash}"
echo "========== #2. main transfer 200 user.p.game.coins.para game chain asset to para chain, main remain=100, parachain=200 ====" echo "========== #2. main transfer 200 user.p.game.coins.para game chain asset to para chain, main remain=100, parachain=200 ===="
hash=$(${CLI} --paraName=user.p.para. send para cross_transfer -a 200 -e paracross -s user.p.game.coins.para -t 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -k 0x128de4afa7c061c00d854a1bca51b58e80a2c292583739e5aebf4c0f778959e1) hash=$(${CLI} --paraName=user.p.para. send para cross_transfer -a 200 -e paracross -s user.p.game."${COINSEXEC}".para -t 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -k 0x128de4afa7c061c00d854a1bca51b58e80a2c292583739e5aebf4c0f778959e1)
echo "${hash}" echo "${hash}"
query_tx "${CLI}" "${hash}" query_tx "${CLI}" "${hash}"
check_cross_transfer_para_balance "100.0000" "200.0000" "${hash}" check_cross_transfer_para_balance "100.0000" "200.0000" "${hash}"
echo "========== #3. withdraw game chain asset to main chain from para chain 50 user.p.game.coins.para,parachain=150,main=150 ====" echo "========== #3. withdraw game chain asset to main chain from para chain 50 user.p.game.coins.para,parachain=150,main=150 ===="
hash=$(${CLI} --paraName=user.p.para. send para cross_transfer -a 50 -e user.p.para.paracross -s paracross.user.p.game.coins.para -t 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -k 0x128de4afa7c061c00d854a1bca51b58e80a2c292583739e5aebf4c0f778959e1) hash=$(${CLI} --paraName=user.p.para. send para cross_transfer -a 50 -e user.p.para.paracross -s paracross.user.p.game."${COINSEXEC}".para -t 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -k 0x128de4afa7c061c00d854a1bca51b58e80a2c292583739e5aebf4c0f778959e1)
echo "${hash}" echo "${hash}"
query_tx "${CLI}" "${hash}" query_tx "${CLI}" "${hash}"
check_cross_transfer_para_balance "150.0000" "150.0000" "${hash}" check_cross_transfer_para_balance "150.0000" "150.0000" "${hash}"
echo "========== #4. withdraw game chain asset to game chain from main chain 50 user.p.game.coins.para,parachain=150,main=100,game=50 ======" echo "========== #4. withdraw game chain asset to game chain from main chain 50 user.p.game.coins.para,parachain=150,main=100,game=50 ======"
hash=$(${CLI} --paraName=user.p.game. send para cross_transfer -a 50 -e paracross -s user.p.game.coins.para -t 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -k 0x128de4afa7c061c00d854a1bca51b58e80a2c292583739e5aebf4c0f778959e1) hash=$(${CLI} --paraName=user.p.game. send para cross_transfer -a 50 -e paracross -s user.p.game."${COINSEXEC}".para -t 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -k 0x128de4afa7c061c00d854a1bca51b58e80a2c292583739e5aebf4c0f778959e1)
echo "${hash}" echo "${hash}"
query_tx "${CLI}" "${hash}" query_tx "${CLI}" "${hash}"
check_cross_transfer_game_balance "100.0000" "50.0000" "${hash}" check_cross_transfer_game_balance "100.0000" "50.0000" "${hash}"
...@@ -581,8 +582,8 @@ function check_cross_transfer_para_balance() { ...@@ -581,8 +582,8 @@ function check_cross_transfer_para_balance() {
local times=200 local times=200
local hash="$3" local hash="$3"
while true; do while true; do
acc=$(${CLI} asset balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu --asset_exec paracross --asset_symbol user.p.game.coins.para -e paracross | jq -r ".balance") acc=$(${CLI} asset balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu --asset_exec paracross --asset_symbol user.p.game."${COINSEXEC}".para -e paracross | jq -r ".balance")
acc_para=$(${PARA_CLI} asset balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu --asset_exec paracross --asset_symbol paracross.user.p.game.coins.para -e paracross | jq -r ".balance") acc_para=$(${PARA_CLI} asset balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu --asset_exec paracross --asset_symbol paracross.user.p.game."${COINSEXEC}".para -e paracross | jq -r ".balance")
res=$(${CLI} para asset_txinfo -s "${hash}") res=$(${CLI} para asset_txinfo -s "${hash}")
echo "$res" echo "$res"
succ=$(jq -r ".success" <<<"$res") succ=$(jq -r ".success" <<<"$res")
...@@ -608,7 +609,7 @@ function check_cross_transfer_game_balance() { ...@@ -608,7 +609,7 @@ function check_cross_transfer_game_balance() {
local times=200 local times=200
local hash="$3" local hash="$3"
while true; do while true; do
acc=$(${CLI} asset balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu --asset_exec paracross --asset_symbol user.p.game.coins.para -e paracross | jq -r ".balance") acc=$(${CLI} asset balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu --asset_exec paracross --asset_symbol user.p.game."${COINSEXEC}".para -e paracross | jq -r ".balance")
acc_para=$(${PARA_CLI5} account balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -e user.p.game.paracross | jq -r ".balance") acc_para=$(${PARA_CLI5} account balance -a 1BM2xhBk95qoae8zKNDWwAVGgBERhb7DQu -e user.p.game.paracross | jq -r ".balance")
res=$(${CLI} para asset_txinfo -s "${hash}") res=$(${CLI} para asset_txinfo -s "${hash}")
echo "$res" echo "$res"
...@@ -1067,22 +1068,22 @@ function privacy_transfer_test() { ...@@ -1067,22 +1068,22 @@ function privacy_transfer_test() {
block_wait "${1}" 2 block_wait "${1}" 2
echo "#privacy pub2priv, to=14KEKbYtKKQm4wMthSK9J4La4nAiidGozt" echo "#privacy pub2priv, to=14KEKbYtKKQm4wMthSK9J4La4nAiidGozt"
${1} send privacy pub2priv -a 9 -p fcbb75f2b96b6d41f301f2d1abc853d697818427819f412f8e4b4e12cacc0814d2c3914b27bea9151b8968ed1732bd241c8788a332b295b731aee8d39a060388 -e coins -s BTY -k 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 ${1} send privacy pub2priv -a 9 -p fcbb75f2b96b6d41f301f2d1abc853d697818427819f412f8e4b4e12cacc0814d2c3914b27bea9151b8968ed1732bd241c8788a332b295b731aee8d39a060388 -e "${COINSEXEC}" -s BTY -k 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4
${1} send privacy pub2priv -a 9 -p fcbb75f2b96b6d41f301f2d1abc853d697818427819f412f8e4b4e12cacc0814d2c3914b27bea9151b8968ed1732bd241c8788a332b295b731aee8d39a060388 -e token -s GD -k 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 ${1} send privacy pub2priv -a 9 -p fcbb75f2b96b6d41f301f2d1abc853d697818427819f412f8e4b4e12cacc0814d2c3914b27bea9151b8968ed1732bd241c8788a332b295b731aee8d39a060388 -e token -s GD -k 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4
check_privacy_utxo "${1}" 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt token GD 9.0000 check_privacy_utxo "${1}" 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt token GD 9.0000
check_privacy_utxo "${1}" 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt coins BTY 9.0000 check_privacy_utxo "${1}" 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt "${COINSEXEC}" BTY 9.0000
echo "#privacy priv2priv, to=1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4" echo "#privacy priv2priv, to=1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4"
${1} send privacy priv2priv -a 3 -p 5b0ff936ec2d2825a67a270e34d741d96bf6afe5d4b5692de0a1627f635fd0b3d7b14e44d3f8f7526030a7c59de482084161b441a5d66b483d80316e3b91482b -f 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -e coins -s BTY -k 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt ${1} send privacy priv2priv -a 3 -p 5b0ff936ec2d2825a67a270e34d741d96bf6afe5d4b5692de0a1627f635fd0b3d7b14e44d3f8f7526030a7c59de482084161b441a5d66b483d80316e3b91482b -f 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -e "${COINSEXEC}" -s BTY -k 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt
${1} send privacy priv2priv -a 3 -p 5b0ff936ec2d2825a67a270e34d741d96bf6afe5d4b5692de0a1627f635fd0b3d7b14e44d3f8f7526030a7c59de482084161b441a5d66b483d80316e3b91482b -f 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -e token -s GD -k 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt ${1} send privacy priv2priv -a 3 -p 5b0ff936ec2d2825a67a270e34d741d96bf6afe5d4b5692de0a1627f635fd0b3d7b14e44d3f8f7526030a7c59de482084161b441a5d66b483d80316e3b91482b -f 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -e token -s GD -k 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt
check_privacy_utxo "${1}" 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 token GD 3.0000 check_privacy_utxo "${1}" 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 token GD 3.0000
check_privacy_utxo "${1}" 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 coins BTY 3.0000 check_privacy_utxo "${1}" 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 "${COINSEXEC}" BTY 3.0000
echo "#privacy priv2pub, to=1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4" echo "#privacy priv2pub, to=1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4"
${1} send privacy priv2pub -a 6 -t 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 -f 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -e coins -s BTY -k 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt ${1} send privacy priv2pub -a 6 -t 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 -f 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -e "${COINSEXEC}" -s BTY -k 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt
${1} send privacy priv2pub -a 6 -t 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 -f 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -e token -s GD -k 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt ${1} send privacy priv2pub -a 6 -t 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 -f 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt -e token -s GD -k 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt
check_privacy_utxo "${1}" 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt token GD 0.0000 check_privacy_utxo "${1}" 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt token GD 0.0000
check_privacy_utxo "${1}" 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt coins BTY 0.0000 check_privacy_utxo "${1}" 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt "${COINSEXEC}" BTY 0.0000
} }
function para_test() { function para_test() {
......
...@@ -11,7 +11,6 @@ import ( ...@@ -11,7 +11,6 @@ import (
"github.com/33cn/chain33/common" "github.com/33cn/chain33/common"
"github.com/33cn/chain33/common/address" "github.com/33cn/chain33/common/address"
"github.com/33cn/chain33/common/db" "github.com/33cn/chain33/common/db"
coins "github.com/33cn/chain33/system/dapp/coins/types"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
pt "github.com/33cn/plugin/plugin/dapp/paracross/types" pt "github.com/33cn/plugin/plugin/dapp/paracross/types"
token "github.com/33cn/plugin/plugin/dapp/token/types" token "github.com/33cn/plugin/plugin/dapp/token/types"
...@@ -315,7 +314,7 @@ func (a *action) assetTransfer(transfer *types.AssetsTransfer) (*types.Receipt, ...@@ -315,7 +314,7 @@ func (a *action) assetTransfer(transfer *types.AssetsTransfer) (*types.Receipt,
Note: string(transfer.Note), Note: string(transfer.Note),
ToAddr: transfer.To, ToAddr: transfer.To,
} }
adaptNullAssetExec(tr) adaptNullAssetExec(a.api.GetConfig(), tr)
return a.mainAssetTransfer(tr, a.tx) return a.mainAssetTransfer(tr, a.tx)
} }
...@@ -332,7 +331,7 @@ func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types ...@@ -332,7 +331,7 @@ func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types
if withdraw.Cointoken != "" { if withdraw.Cointoken != "" {
tr.AssetExec = token.TokenX tr.AssetExec = token.TokenX
} }
adaptNullAssetExec(tr) adaptNullAssetExec(a.api.GetConfig(), tr)
return a.mainAssetWithdraw(tr, withdrawTx) return a.mainAssetWithdraw(tr, withdrawTx)
} }
...@@ -388,9 +387,9 @@ func (a *action) createAccount(cfg *types.Chain33Config, db db.KV, exec, symbol ...@@ -388,9 +387,9 @@ func (a *action) createAccount(cfg *types.Chain33Config, db db.KV, exec, symbol
return account.NewAccountDB(cfg, exec, symbol, db) return account.NewAccountDB(cfg, exec, symbol, db)
} }
func adaptNullAssetExec(transfer *pt.CrossAssetTransfer) { func adaptNullAssetExec(cfg *types.Chain33Config, transfer *pt.CrossAssetTransfer) {
if transfer.AssetSymbol == "" { if transfer.AssetSymbol == "" {
transfer.AssetExec = coins.CoinsX transfer.AssetExec = cfg.GetCoinExec()
transfer.AssetSymbol = SymbolBty transfer.AssetSymbol = SymbolBty
return return
} }
......
...@@ -194,7 +194,7 @@ func (c *Paracross) udpateLocalParaTxs(paraTitle string, paraHeight int64, cross ...@@ -194,7 +194,7 @@ func (c *Paracross) udpateLocalParaTxs(paraTitle string, paraHeight int64, cross
} }
func (c *Paracross) getAssetTransferInfo(tx *types.Transaction, coinToken string, isWithdraw bool) (*pt.ParacrossAsset, error) { func (c *Paracross) getAssetTransferInfo(tx *types.Transaction, coinToken string, isWithdraw bool) (*pt.ParacrossAsset, error) {
exec := "coins" exec := c.GetAPI().GetConfig().GetCoinExec()
symbol := types.BTY symbol := types.BTY
if coinToken != "" { if coinToken != "" {
exec = "token" exec = "token"
...@@ -223,7 +223,7 @@ func (c *Paracross) getCrossAssetTransferInfo(payload *pt.CrossAssetTransfer, tx ...@@ -223,7 +223,7 @@ func (c *Paracross) getCrossAssetTransferInfo(payload *pt.CrossAssetTransfer, tx
symbol := payload.AssetSymbol symbol := payload.AssetSymbol
if payload.AssetSymbol == "" { if payload.AssetSymbol == "" {
symbol = types.BTY symbol = types.BTY
exec = "coins" exec = c.GetAPI().GetConfig().GetCoinExec()
} }
amount, err := tx.Amount() amount, err := tx.Amount()
......
...@@ -138,17 +138,16 @@ func (p *privacy) Exec_Privacy2Public(payload *ty.Privacy2Public, tx *types.Tran ...@@ -138,17 +138,16 @@ func (p *privacy) Exec_Privacy2Public(payload *ty.Privacy2Public, tx *types.Tran
} }
func (p *privacy) createAccountDB(exec, symbol string) (*account.DB, error) { func (p *privacy) createAccountDB(exec, symbol string) (*account.DB, error) {
cfg := p.GetAPI().GetConfig()
if exec == "" || exec == "coins" { if exec == "" || exec == cfg.GetCoinExec() {
return p.GetCoinsAccount(), nil return p.GetCoinsAccount(), nil
} }
cfg := p.GetAPI().GetConfig()
return account.NewAccountDB(cfg, exec, symbol, p.GetStateDB()) return account.NewAccountDB(cfg, exec, symbol, p.GetStateDB())
} }
func (p *privacy) buildPrivacyReceiptLog(assetExec, assetSymbol string, output *ty.PrivacyOutput) *ty.ReceiptPrivacyOutput { func (p *privacy) buildPrivacyReceiptLog(assetExec, assetSymbol string, output *ty.PrivacyOutput) *ty.ReceiptPrivacyOutput {
if assetExec == "" { if assetExec == "" {
assetExec = "coins" assetExec = p.GetAPI().GetConfig().GetCoinExec()
} }
receipt := &ty.ReceiptPrivacyOutput{ receipt := &ty.ReceiptPrivacyOutput{
AssetExec: assetExec, AssetExec: assetExec,
......
...@@ -560,7 +560,7 @@ func (policy *privacyPolicy) createPrivacy2PrivacyTx(req *privacytypes.ReqCreate ...@@ -560,7 +560,7 @@ func (policy *privacyPolicy) createPrivacy2PrivacyTx(req *privacytypes.ReqCreate
//需要燃烧的utxo //需要燃烧的utxo
var utxoBurnedAmount int64 var utxoBurnedAmount int64
cfg := policy.getWalletOperate().GetAPI().GetConfig() cfg := policy.getWalletOperate().GetAPI().GetConfig()
isMainetCoins := !cfg.IsPara() && (req.AssetExec == "coins") isMainetCoins := !cfg.IsPara() && (req.AssetExec == cfg.GetCoinExec())
if isMainetCoins { if isMainetCoins {
utxoBurnedAmount = privacytypes.PrivacyTxFee utxoBurnedAmount = privacytypes.PrivacyTxFee
} }
......
...@@ -105,7 +105,7 @@ func (c *Retrieve) ExecLocal_Perform(perf *rt.PerformRetrieve, tx *types.Transac ...@@ -105,7 +105,7 @@ func (c *Retrieve) ExecLocal_Perform(perf *rt.PerformRetrieve, tx *types.Transac
cfg := c.GetAPI().GetConfig() cfg := c.GetAPI().GetConfig()
if cfg.IsDappFork(c.GetHeight(), rt.RetrieveX, rt.ForkRetriveAssetX) { if cfg.IsDappFork(c.GetHeight(), rt.RetrieveX, rt.ForkRetriveAssetX) {
if len(perf.Assets) == 0 { if len(perf.Assets) == 0 {
perf.Assets = append(perf.Assets, &rt.AssetSymbol{Exec: "coins", Symbol: cfg.GetCoinSymbol()}) perf.Assets = append(perf.Assets, &rt.AssetSymbol{Exec: cfg.GetCoinExec(), Symbol: cfg.GetCoinSymbol()})
} }
} }
for _, asset := range perf.Assets { for _, asset := range perf.Assets {
......
...@@ -53,7 +53,7 @@ func (g *channelClient) CreateBindMiner(ctx context.Context, in *ty.ReqBindMiner ...@@ -53,7 +53,7 @@ func (g *channelClient) CreateBindMiner(ctx context.Context, in *ty.ReqBindMiner
return nil, types.ErrAmount return nil, types.ErrAmount
} }
getBalance := &types.ReqBalance{Addresses: []string{in.OriginAddr}, Execer: "coins", AssetSymbol: "bty", AssetExec: "coins"} getBalance := &types.ReqBalance{Addresses: []string{in.OriginAddr}, Execer: cfg.GetCoinExec(), AssetSymbol: "bty", AssetExec: cfg.GetCoinExec()}
balances, err := g.GetCoinsAccountDB().GetBalance(g, getBalance) balances, err := g.GetCoinsAccountDB().GetBalance(g, getBalance)
if err != nil { if err != nil {
return nil, err return nil, err
......
...@@ -25,6 +25,8 @@ type Signatory struct { ...@@ -25,6 +25,8 @@ type Signatory struct {
Privkey string Privkey string
} }
const coinExec = "coins"
// Echo echo // Echo echo
func (*Signatory) Echo(in *string, out *interface{}) error { func (*Signatory) Echo(in *string, out *interface{}) error {
if in == nil { if in == nil {
...@@ -97,7 +99,7 @@ func (signatory *Signatory) SignTransfer(in *string, out *interface{}) error { ...@@ -97,7 +99,7 @@ func (signatory *Signatory) SignTransfer(in *string, out *interface{}) error {
} }
tx := &types.Transaction{ tx := &types.Transaction{
Execer: []byte("coins"), Execer: []byte(coinExec),
Payload: types.Encode(transfer), Payload: types.Encode(transfer),
To: *in, To: *in,
Nonce: rand.New(rand.NewSource(time.Now().UnixNano())).Int63(), Nonce: rand.New(rand.NewSource(time.Now().UnixNano())).Int63(),
......
...@@ -159,11 +159,12 @@ func (a *action) procChain33ToEth_lock(msgLock *x2eTy.Chain33ToEth) (*types.Rece ...@@ -159,11 +159,12 @@ func (a *action) procChain33ToEth_lock(msgLock *x2eTy.Chain33ToEth) (*types.Rece
var accDB *account.DB var accDB *account.DB
exec, symbol, _ := x2eTy.DivideDot(msgLock.IssuerDotSymbol) exec, symbol, _ := x2eTy.DivideDot(msgLock.IssuerDotSymbol)
if exec == "coins" { cfg := a.api.GetConfig()
accDB = account.NewCoinsAccount(a.api.GetConfig()) if exec == cfg.GetCoinExec() {
accDB = account.NewCoinsAccount(cfg)
accDB.SetDB(a.db) accDB.SetDB(a.db)
} else { } else {
accDB, err = account.NewAccountDB(a.api.GetConfig(), exec, strings.ToLower(symbol), a.db) accDB, err = account.NewAccountDB(cfg, exec, strings.ToLower(symbol), a.db)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "newAccountDB") return nil, errors.Wrap(err, "newAccountDB")
} }
...@@ -233,11 +234,12 @@ func (a *action) procEth2Chain33_burn(withdrawEth *x2eTy.Eth2Chain33) (*types.Re ...@@ -233,11 +234,12 @@ func (a *action) procEth2Chain33_burn(withdrawEth *x2eTy.Eth2Chain33) (*types.Re
var accDB *account.DB var accDB *account.DB
exec, symbol, _ := x2eTy.DivideDot(withdrawEth.IssuerDotSymbol) exec, symbol, _ := x2eTy.DivideDot(withdrawEth.IssuerDotSymbol)
if exec == "coins" { cfg := a.api.GetConfig()
accDB = account.NewCoinsAccount(a.api.GetConfig()) if exec == cfg.GetCoinExec() {
accDB = account.NewCoinsAccount(cfg)
accDB.SetDB(a.db) accDB.SetDB(a.db)
} else { } else {
accDB, err = account.NewAccountDB(a.api.GetConfig(), exec, strings.ToLower(symbol), a.db) accDB, err = account.NewAccountDB(cfg, exec, strings.ToLower(symbol), a.db)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "newAccountDB") return nil, errors.Wrap(err, "newAccountDB")
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment