Commit 5d7a4b17 authored by hezhengjun's avatar hezhengjun

fix linter issue

parent 91f9d67f
...@@ -51,7 +51,7 @@ func importPrivatekey(cmd *cobra.Command, args []string) { ...@@ -51,7 +51,7 @@ func importPrivatekey(cmd *cobra.Command, args []string) {
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ImportChain33RelayerPrivateKey", importKeyReq, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ImportChain33RelayerPrivateKey", importKeyReq, &res)
ctx.Run() ctx.Run()
} }
...@@ -67,7 +67,7 @@ func ShowValidatorAddrCmd() *cobra.Command { ...@@ -67,7 +67,7 @@ func ShowValidatorAddrCmd() *cobra.Command {
func showValidatorAddr(cmd *cobra.Command, args []string) { func showValidatorAddr(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res string var res string
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowChain33RelayerValidator", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowChain33RelayerValidator", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -84,7 +84,7 @@ func showChain33Relayer2EthTxs(cmd *cobra.Command, args []string) { ...@@ -84,7 +84,7 @@ func showChain33Relayer2EthTxs(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res ebTypes.Txhashes var res ebTypes.Txhashes
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowChain33Relayer2EthTxs", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowChain33Relayer2EthTxs", nil, &res)
if _, err := ctx.RunResult(); nil != err { if _, err := ctx.RunResult(); nil != err {
errInfo := err.Error() errInfo := err.Error()
fmt.Println("errinfo:" + errInfo) fmt.Println("errinfo:" + errInfo)
...@@ -108,6 +108,6 @@ func showChain33RelayerStatus(cmd *cobra.Command, args []string) { ...@@ -108,6 +108,6 @@ func showChain33RelayerStatus(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res ebTypes.RelayerRunStatus var res ebTypes.RelayerRunStatus
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowChain33RelayerStatus", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowChain33RelayerStatus", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -57,7 +57,7 @@ func setPwd(cmd *cobra.Command, args []string) { ...@@ -57,7 +57,7 @@ func setPwd(cmd *cobra.Command, args []string) {
NewPassphase: newPwd, NewPassphase: newPwd,
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.SetPassphase", params, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.SetPassphase", params, &res)
ctx.Run() ctx.Run()
} }
...@@ -74,7 +74,7 @@ func LockCmd() *cobra.Command { ...@@ -74,7 +74,7 @@ func LockCmd() *cobra.Command {
func lock(cmd *cobra.Command, args []string) { func lock(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.Lock", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.Lock", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -100,6 +100,6 @@ func unLock(cmd *cobra.Command, args []string) { ...@@ -100,6 +100,6 @@ func unLock(cmd *cobra.Command, args []string) {
params := pwd params := pwd
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.Unlock", params, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.Unlock", params, &res)
ctx.Run() ctx.Run()
} }
...@@ -76,7 +76,7 @@ func importChain33Privatekey(cmd *cobra.Command, args []string) { ...@@ -76,7 +76,7 @@ func importChain33Privatekey(cmd *cobra.Command, args []string) {
params := privateKey params := privateKey
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ImportChain33PrivateKey4EthRelayer", params, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ImportChain33PrivateKey4EthRelayer", params, &res)
ctx.Run() ctx.Run()
} }
...@@ -96,7 +96,7 @@ func importEthValidtorPrivatekey(cmd *cobra.Command, args []string) { ...@@ -96,7 +96,7 @@ func importEthValidtorPrivatekey(cmd *cobra.Command, args []string) {
params := privateKey params := privateKey
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ImportEthValidatorPrivateKey", params, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ImportEthValidatorPrivateKey", params, &res)
ctx.Run() ctx.Run()
} }
...@@ -113,7 +113,7 @@ func generateEthereumPrivateKey(cmd *cobra.Command, args []string) { ...@@ -113,7 +113,7 @@ func generateEthereumPrivateKey(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res ebTypes.Account4Show var res ebTypes.Account4Show
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.GenerateEthereumPrivateKey", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.GenerateEthereumPrivateKey", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -129,7 +129,7 @@ func ShowValidatorsAddrCmd() *cobra.Command { ...@@ -129,7 +129,7 @@ func ShowValidatorsAddrCmd() *cobra.Command {
func showValidatorsAddr(cmd *cobra.Command, args []string) { func showValidatorsAddr(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res ebTypes.ValidatorAddr4EthRelayer var res ebTypes.ValidatorAddr4EthRelayer
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowEthRelayerValidator", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowEthRelayerValidator", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -146,7 +146,7 @@ func showChain33Txs(cmd *cobra.Command, args []string) { ...@@ -146,7 +146,7 @@ func showChain33Txs(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res ebTypes.Txhashes var res ebTypes.Txhashes
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowEthRelayer2Chain33Txs", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowEthRelayer2Chain33Txs", nil, &res)
if _, err := ctx.RunResult(); nil != err { if _, err := ctx.RunResult(); nil != err {
errInfo := err.Error() errInfo := err.Error()
fmt.Println("errinfo:" + errInfo) fmt.Println("errinfo:" + errInfo)
...@@ -170,7 +170,7 @@ func showEthTxs(cmd *cobra.Command, args []string) { ...@@ -170,7 +170,7 @@ func showEthTxs(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res ebTypes.Txhashes var res ebTypes.Txhashes
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowEthRelayer2Chain33Txs", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowEthRelayer2Chain33Txs", nil, &res)
if _, err := ctx.RunResult(); nil != err { if _, err := ctx.RunResult(); nil != err {
errInfo := err.Error() errInfo := err.Error()
fmt.Println("errinfo:" + errInfo) fmt.Println("errinfo:" + errInfo)
...@@ -194,7 +194,7 @@ func showEthRelayerStatus(cmd *cobra.Command, args []string) { ...@@ -194,7 +194,7 @@ func showEthRelayerStatus(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res ebTypes.RelayerRunStatus var res ebTypes.RelayerRunStatus
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowEthRelayerStatus", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowEthRelayerStatus", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -219,7 +219,7 @@ func IsValidatorActive(cmd *cobra.Command, args []string) { ...@@ -219,7 +219,7 @@ func IsValidatorActive(cmd *cobra.Command, args []string) {
params := addr params := addr
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.IsValidatorActive", params, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.IsValidatorActive", params, &res)
ctx.Run() ctx.Run()
} }
...@@ -235,7 +235,7 @@ func ShowOperatorCmd() *cobra.Command { ...@@ -235,7 +235,7 @@ func ShowOperatorCmd() *cobra.Command {
func ShowOperator(cmd *cobra.Command, args []string) { func ShowOperator(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res string var res string
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowOperator", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowOperator", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -251,7 +251,7 @@ func DeployContrctsCmd() *cobra.Command { ...@@ -251,7 +251,7 @@ func DeployContrctsCmd() *cobra.Command {
func DeployContrcts(cmd *cobra.Command, args []string) { func DeployContrcts(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.DeployContrcts", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.DeployContrcts", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -275,7 +275,7 @@ func ShowTxReceipt(cmd *cobra.Command, args []string) { ...@@ -275,7 +275,7 @@ func ShowTxReceipt(cmd *cobra.Command, args []string) {
txhash, _ := cmd.Flags().GetString("hash") txhash, _ := cmd.Flags().GetString("hash")
para := txhash para := txhash
var res ethTypes.Receipt var res ethTypes.Receipt
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowTxReceipt", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowTxReceipt", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -299,7 +299,7 @@ func CreateBridgeToken(cmd *cobra.Command, args []string) { ...@@ -299,7 +299,7 @@ func CreateBridgeToken(cmd *cobra.Command, args []string) {
token, _ := cmd.Flags().GetString("symbol") token, _ := cmd.Flags().GetString("symbol")
para := token para := token
var res ebTypes.ReplyAddr var res ebTypes.ReplyAddr
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.CreateBridgeToken", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.CreateBridgeToken", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -323,7 +323,7 @@ func CreateEthereumTokenToken(cmd *cobra.Command, args []string) { ...@@ -323,7 +323,7 @@ func CreateEthereumTokenToken(cmd *cobra.Command, args []string) {
token, _ := cmd.Flags().GetString("symbol") token, _ := cmd.Flags().GetString("symbol")
para := token para := token
var res ebTypes.ReplyAddr var res ebTypes.ReplyAddr
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.CreateERC20Token", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.CreateERC20Token", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -365,7 +365,7 @@ func MintErc20(cmd *cobra.Command, args []string) { ...@@ -365,7 +365,7 @@ func MintErc20(cmd *cobra.Command, args []string) {
Amount: realAmount.String(), Amount: realAmount.String(),
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.MintErc20", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.MintErc20", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -408,7 +408,7 @@ func ApproveAllowance(cmd *cobra.Command, args []string) { ...@@ -408,7 +408,7 @@ func ApproveAllowance(cmd *cobra.Command, args []string) {
Amount: realAmount.String(), Amount: realAmount.String(),
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ApproveAllowance", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ApproveAllowance", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -463,7 +463,7 @@ func Burn(cmd *cobra.Command, args []string) { ...@@ -463,7 +463,7 @@ func Burn(cmd *cobra.Command, args []string) {
Chain33Receiver: receiver, Chain33Receiver: receiver,
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.Burn", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.Burn", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -487,7 +487,7 @@ func BurnAsync(cmd *cobra.Command, args []string) { ...@@ -487,7 +487,7 @@ func BurnAsync(cmd *cobra.Command, args []string) {
Chain33Receiver: receiver, Chain33Receiver: receiver,
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.BurnAsync", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.BurnAsync", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -544,7 +544,7 @@ func LockEthErc20Asset(cmd *cobra.Command, args []string) { ...@@ -544,7 +544,7 @@ func LockEthErc20Asset(cmd *cobra.Command, args []string) {
Chain33Receiver: receiver, Chain33Receiver: receiver,
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.LockEthErc20Asset", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.LockEthErc20Asset", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -571,7 +571,7 @@ func LockEthErc20AssetAsync(cmd *cobra.Command, args []string) { ...@@ -571,7 +571,7 @@ func LockEthErc20AssetAsync(cmd *cobra.Command, args []string) {
Chain33Receiver: receiver, Chain33Receiver: receiver,
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.LockEthErc20AssetAsync", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.LockEthErc20AssetAsync", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -587,7 +587,7 @@ func ShowBridgeBankAddrCmd() *cobra.Command { ...@@ -587,7 +587,7 @@ func ShowBridgeBankAddrCmd() *cobra.Command {
func ShowBridgeBankAddr(cmd *cobra.Command, args []string) { func ShowBridgeBankAddr(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res ebTypes.ReplyAddr var res ebTypes.ReplyAddr
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowBridgeBankAddr", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowBridgeBankAddr", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -603,7 +603,7 @@ func ShowBridgeRegistryAddrCmd() *cobra.Command { ...@@ -603,7 +603,7 @@ func ShowBridgeRegistryAddrCmd() *cobra.Command {
func ShowBridgeRegistryAddr(cmd *cobra.Command, args []string) { func ShowBridgeRegistryAddr(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
var res ebTypes.ReplyAddr var res ebTypes.ReplyAddr
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowBridgeRegistryAddr", nil, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowBridgeRegistryAddr", nil, &res)
ctx.Run() ctx.Run()
} }
...@@ -667,7 +667,7 @@ func MakeNewProphecyClaim(cmd *cobra.Command, args []string) { ...@@ -667,7 +667,7 @@ func MakeNewProphecyClaim(cmd *cobra.Command, args []string) {
TxHash: txhash, TxHash: txhash,
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.MakeNewProphecyClaim", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.MakeNewProphecyClaim", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -697,7 +697,7 @@ func GetBalance(cmd *cobra.Command, args []string) { ...@@ -697,7 +697,7 @@ func GetBalance(cmd *cobra.Command, args []string) {
TokenAddr: tokenAddr, TokenAddr: tokenAddr,
} }
var res ebTypes.ReplyBalance var res ebTypes.ReplyBalance
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.GetBalance", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.GetBalance", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -722,7 +722,7 @@ func IsProphecyPending(cmd *cobra.Command, args []string) { ...@@ -722,7 +722,7 @@ func IsProphecyPending(cmd *cobra.Command, args []string) {
para := common.HexToHash(id) para := common.HexToHash(id)
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.IsProphecyPending", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.IsProphecyPending", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -770,7 +770,7 @@ func TransferToken(cmd *cobra.Command, args []string) { ...@@ -770,7 +770,7 @@ func TransferToken(cmd *cobra.Command, args []string) {
Amount: realAmount.String(), Amount: realAmount.String(),
} }
var res rpctypes.Reply var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.TransferToken", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.TransferToken", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -798,6 +798,6 @@ func GetToken2address(cmd *cobra.Command, args []string) { ...@@ -798,6 +798,6 @@ func GetToken2address(cmd *cobra.Command, args []string) {
TokenAddr: tokenSymbol, TokenAddr: tokenSymbol,
} }
var res ebTypes.ReplyAddr var res ebTypes.ReplyAddr
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowTokenAddrBySymbol", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowTokenAddrBySymbol", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -2,7 +2,6 @@ package main ...@@ -2,7 +2,6 @@ package main
import ( import (
"github.com/33cn/chain33/rpc/jsonclient" "github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
ebTypes "github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/types" ebTypes "github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/types"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
...@@ -16,8 +15,6 @@ func StaticsCmd() *cobra.Command { ...@@ -16,8 +15,6 @@ func StaticsCmd() *cobra.Command {
cmd.AddCommand( cmd.AddCommand(
ShowLockStaticsCmd(), ShowLockStaticsCmd(),
//ShowUnlockStaticsCmd(),
//ShowBurnStaticsCmd(),
ShowDepositStaticsCmd(), ShowDepositStaticsCmd(),
) )
...@@ -46,66 +43,7 @@ func ShowLockStatics(cmd *cobra.Command, args []string) { ...@@ -46,66 +43,7 @@ func ShowLockStatics(cmd *cobra.Command, args []string) {
TokenAddr: tokenAddr, TokenAddr: tokenAddr,
} }
var res ebTypes.StaticsLock var res ebTypes.StaticsLock
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowLockStatics", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowLockStatics", para, &res)
ctx.Run()
}
func ShowUnlockStaticsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "unlock",
Short: "show the unlock statics of ETH or ERC20",
Run: ShowUnlockStatics,
}
ShowUnlockStaticsFlags(cmd)
return cmd
}
func ShowUnlockStaticsFlags(cmd *cobra.Command) {
cmd.Flags().StringP("token", "t", "", "token address, optional, nil for ETH")
cmd.Flags().StringP("owner", "o", "", "owner address, optional, nil for all")
}
func ShowUnlockStatics(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
tokenAddr, _ := cmd.Flags().GetString("token")
owner, _ := cmd.Flags().GetString("owner")
para := ebTypes.StaticsRequest{
Owner: owner,
TokenAddr: tokenAddr,
}
var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowUnlockStatics", para, &res)
ctx.Run()
}
func ShowBurnStaticsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "burn",
Short: "show the burn statics of chain33 asset",
Run: ShowBurnStatics,
}
ShowBurnStaticsFlags(cmd)
return cmd
}
func ShowBurnStaticsFlags(cmd *cobra.Command) {
cmd.Flags().StringP("token", "t", "", "token address, optional, nil for ETH")
cmd.Flags().StringP("owner", "o", "", "owner address, optional, nil for all")
}
func ShowBurnStatics(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
tokenAddr, _ := cmd.Flags().GetString("token")
owner, _ := cmd.Flags().GetString("owner")
para := ebTypes.StaticsRequest{
Owner: owner,
TokenAddr: tokenAddr,
}
var res ebTypes.StaticsResponse
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowLockStaticsCmd", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -132,6 +70,6 @@ func ShowDepositStatics(cmd *cobra.Command, args []string) { ...@@ -132,6 +70,6 @@ func ShowDepositStatics(cmd *cobra.Command, args []string) {
TokenAddr: tokenAddr, TokenAddr: tokenAddr,
} }
var res ebTypes.StaticsDeposit var res ebTypes.StaticsDeposit
ctx := jsonclient.NewRPCCtx(rpcLaddr, "RelayerManager.ShowDepositStatics", para, &res) ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ShowDepositStatics", para, &res)
ctx.Run() ctx.Run()
} }
...@@ -245,7 +245,7 @@ func TestBrigeTokenMint(t *testing.T) { ...@@ -245,7 +245,7 @@ func TestBrigeTokenMint(t *testing.T) {
_, err = x2EthContracts.Oracle.NewOracleClaim( _, err = x2EthContracts.Oracle.NewOracleClaim(
authOracle, authOracle,
events.CLAIM_TYPE_LOCK, events.ClaimTypeLock,
chain33Sender, chain33Sender,
ethReceiver, ethReceiver,
logEvent.Token, logEvent.Token,
...@@ -501,7 +501,7 @@ func TestBridgeBankUnlock(t *testing.T) { ...@@ -501,7 +501,7 @@ func TestBridgeBankUnlock(t *testing.T) {
_, err = x2EthContracts.Oracle.NewOracleClaim( _, err = x2EthContracts.Oracle.NewOracleClaim(
authOracle, authOracle,
events.CLAIM_TYPE_BURN, events.ClaimTypeBurn,
chain33Sender, chain33Sender,
ethReceiver, ethReceiver,
ethAddr, ethAddr,
...@@ -535,7 +535,7 @@ func TestBridgeBankUnlock(t *testing.T) { ...@@ -535,7 +535,7 @@ func TestBridgeBankUnlock(t *testing.T) {
_, err = x2EthContracts.Oracle.NewOracleClaim( _, err = x2EthContracts.Oracle.NewOracleClaim(
authOracle, authOracle,
events.CLAIM_TYPE_BURN, events.ClaimTypeBurn,
chain33Sender, chain33Sender,
ethReceiver, ethReceiver,
bridgeTokenAddr, bridgeTokenAddr,
...@@ -666,7 +666,7 @@ func TestBridgeBankSecondUnlockEth(t *testing.T) { ...@@ -666,7 +666,7 @@ func TestBridgeBankSecondUnlockEth(t *testing.T) {
_, err = x2EthContracts.Oracle.NewOracleClaim( _, err = x2EthContracts.Oracle.NewOracleClaim(
authOracle, authOracle,
events.CLAIM_TYPE_BURN, events.ClaimTypeBurn,
chain33Sender, chain33Sender,
ethReceiver, ethReceiver,
ethAddr, ethAddr,
...@@ -696,7 +696,7 @@ func TestBridgeBankSecondUnlockEth(t *testing.T) { ...@@ -696,7 +696,7 @@ func TestBridgeBankSecondUnlockEth(t *testing.T) {
_, err = x2EthContracts.Oracle.NewOracleClaim( _, err = x2EthContracts.Oracle.NewOracleClaim(
authOracle, authOracle,
events.CLAIM_TYPE_BURN, events.ClaimTypeBurn,
chain33Sender, chain33Sender,
ethReceiver, ethReceiver,
ethAddr, ethAddr,
...@@ -828,7 +828,7 @@ func TestBridgeBankSedondUnlockErc20(t *testing.T) { ...@@ -828,7 +828,7 @@ func TestBridgeBankSedondUnlockErc20(t *testing.T) {
require.Nil(t, err) require.Nil(t, err)
_, err = x2EthContracts.Oracle.NewOracleClaim( _, err = x2EthContracts.Oracle.NewOracleClaim(
authOracle, authOracle,
events.CLAIM_TYPE_BURN, events.ClaimTypeBurn,
chain33Sender, chain33Sender,
ethReceiver, ethReceiver,
bridgeTokenAddr, bridgeTokenAddr,
...@@ -852,7 +852,7 @@ func TestBridgeBankSedondUnlockErc20(t *testing.T) { ...@@ -852,7 +852,7 @@ func TestBridgeBankSedondUnlockErc20(t *testing.T) {
require.Nil(t, err) require.Nil(t, err)
_, err = x2EthContracts.Oracle.NewOracleClaim( _, err = x2EthContracts.Oracle.NewOracleClaim(
authOracle, authOracle,
events.CLAIM_TYPE_BURN, events.ClaimTypeBurn,
chain33Sender, chain33Sender,
ethReceiver, ethReceiver,
bridgeTokenAddr, bridgeTokenAddr,
......
package setup
import (
"context"
"fmt"
"log"
"math/big"
"github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/ethcontract/generated"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/crypto"
)
func main() {
// Generate a new random account and a funded simulator
key, _ := crypto.GenerateKey()
alloc := make(core.GenesisAlloc)
addr := crypto.PubkeyToAddress(key.PublicKey)
genesisAccount := core.GenesisAccount{
Balance: big.NewInt(10000000000),
PrivateKey: crypto.FromECDSA(key),
}
alloc[addr] = genesisAccount
gasLimit := uint64(100000000)
sim := backends.NewSimulatedBackend(alloc, gasLimit)
ctx := context.Background()
gasPrice, err := sim.SuggestGasPrice(ctx)
if err != nil {
panic("Failed to SuggestGasPrice due to:" + err.Error())
}
auth := bind.NewKeyedTransactor(key)
//auth.Nonce = big.NewInt(int64(nonce))
auth.Value = big.NewInt(0) // in wei
auth.GasLimit = gasLimit
auth.GasPrice = gasPrice
// Deploy a token contract on the simulated blockchain
cosmosBridgeAddr := common.HexToAddress("0x8afdadfc88a1087c9a1d6c0f5dd04634b87f303a")
bridgeBankAddr := common.HexToAddress("0x0df9a824699bc5878232c9e612fe1a5346a5a368")
oracleAddr := common.HexToAddress("0x92c8b16afd6d423652559c6e266cbe1c29bfd84f")
valsetAddr := common.HexToAddress("0xcb074cb21cdddf3ce9c3c0a7ac4497d633c9d9f1")
_, _, bridgeRegistry, err := generated.DeployBridgeRegistry(auth, sim, cosmosBridgeAddr, bridgeBankAddr, oracleAddr, valsetAddr)
if err != nil {
log.Fatalf("Failed to deploy BridgeRegistry contract: %v", err)
}
balance, _ := sim.BalanceAt(ctx, addr, nil)
fmt.Println("balance before:", balance.String())
// Print the current (non existent) and pending name of the contract
cosmosBridgeAddrRetrive, _ := bridgeRegistry.Chain33Bridge(nil)
fmt.Println("Pre-mining cosmosBridgeAddr:", cosmosBridgeAddrRetrive.String())
cosmosBridgeAddrRetrive, _ = bridgeRegistry.Chain33Bridge(&bind.CallOpts{Pending: true})
fmt.Println("Pre-mining pending cosmosBridgeAddr:", cosmosBridgeAddrRetrive.String())
balance, _ = sim.BalanceAt(ctx, addr, nil)
fmt.Println("balance after:", balance.String())
// Commit all pending transactions in the simulator and print the names again
sim.Commit()
balance, _ = sim.BalanceAt(ctx, addr, nil)
fmt.Println("balance after:", balance.String())
cosmosBridgeAddrRetrive, _ = bridgeRegistry.Chain33Bridge(nil)
fmt.Println("Post-mining cosmosBridgeAddr:", cosmosBridgeAddrRetrive.String())
cosmosBridgeAddrRetrive, _ = bridgeRegistry.Chain33Bridge(&bind.CallOpts{Pending: true})
fmt.Println("Post-mining pending cosmosBridgeAddr:", cosmosBridgeAddrRetrive.String())
cosmosBridgeAddrRetrive, _ = bridgeRegistry.Chain33Bridge(nil)
fmt.Println("Post-mining cosmosBridgeAddr:", cosmosBridgeAddrRetrive.String())
balance, _ = sim.BalanceAt(ctx, addr, nil)
fmt.Println("balance after:", balance.String())
}
...@@ -15,22 +15,22 @@ const ( ...@@ -15,22 +15,22 @@ const (
) )
func LoadABI(contractName string) abi.ABI { func LoadABI(contractName string) abi.ABI {
var abiJson string var abiJSON string
switch contractName { switch contractName {
case BridgeBankABI: case BridgeBankABI:
abiJson = generated.BridgeBankABI abiJSON = generated.BridgeBankABI
case Chain33BankABI: case Chain33BankABI:
abiJson = generated.Chain33BankABI abiJSON = generated.Chain33BankABI
case Chain33BridgeABI: case Chain33BridgeABI:
abiJson = generated.Chain33BridgeABI abiJSON = generated.Chain33BridgeABI
case EthereumBankABI: case EthereumBankABI:
abiJson = generated.EthereumBankABI abiJSON = generated.EthereumBankABI
default: default:
panic("No abi matched") panic("No abi matched")
} }
// Convert the raw abi into a usable format // Convert the raw abi into a usable format
contractABI, err := abi.JSON(strings.NewReader(abiJson)) contractABI, err := abi.JSON(strings.NewReader(abiJSON))
if err != nil { if err != nil {
panic(err) panic(err)
} }
......
...@@ -12,7 +12,6 @@ package ethtxs ...@@ -12,7 +12,6 @@ package ethtxs
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"math/big" "math/big"
"regexp"
"strings" "strings"
chain33Types "github.com/33cn/chain33/types" chain33Types "github.com/33cn/chain33/types"
...@@ -166,30 +165,3 @@ func Chain33MsgToProphecyClaim(event events.Chain33Msg) ProphecyClaim { ...@@ -166,30 +165,3 @@ func Chain33MsgToProphecyClaim(event events.Chain33Msg) ProphecyClaim {
return prophecyClaim return prophecyClaim
} }
// getSymbolAmountFromCoin : Parse (symbol, amount) from coin string
func getSymbolAmountFromCoin(coin string) (string, *big.Int) {
coinRune := []rune(coin)
amount := new(big.Int)
var symbol string
// Set up regex
isLetter := regexp.MustCompile(`[a-z]`)
// Iterate over each rune in the coin string
for i, char := range coinRune {
// Regex will match first letter [a-z] (lowercase)
matched := isLetter.MatchString(string(char))
// On first match, split the coin into (amount, symbol)
if matched {
amount, _ = amount.SetString(string(coinRune[0:i]), 10)
symbol = string(coinRune[i:])
break
}
}
return symbol, amount
}
...@@ -113,13 +113,13 @@ func GetLockedFunds(bridgeBank *generated.BridgeBank, tokenAddrStr string) (stri ...@@ -113,13 +113,13 @@ func GetLockedFunds(bridgeBank *generated.BridgeBank, tokenAddrStr string) (stri
return balance.String(), nil return balance.String(), nil
} }
func GetDepositFunds(client *ethclient.Client, tokenAddrStr string) (string, error) { func GetDepositFunds(backend bind.ContractBackend, tokenAddrStr string) (string, error) {
if tokenAddrStr == "" { if tokenAddrStr == "" {
return "", errors.New("nil token address") return "", errors.New("nil token address")
} }
tokenAddr := common.HexToAddress(tokenAddrStr) tokenAddr := common.HexToAddress(tokenAddrStr)
bridgeToken, err := generated.NewBridgeToken(tokenAddr, client) bridgeToken, err := generated.NewBridgeToken(tokenAddr, backend)
if nil != err { if nil != err {
return "", err return "", err
} }
......
...@@ -4,39 +4,39 @@ import ( ...@@ -4,39 +4,39 @@ import (
"errors" "errors"
"github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/ethcontract/generated" "github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/ethcontract/generated"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
) )
func RecoverContractHandler(client *ethclient.Client, sender, registry common.Address) (*X2EthContracts, *X2EthDeployInfo, error) { func RecoverContractHandler(backend bind.ContractBackend, sender, registry common.Address) (*X2EthContracts, *X2EthDeployInfo, error) {
bridgeBankAddr, err := GetAddressFromBridgeRegistry(client, sender, registry, BridgeBank) bridgeBankAddr, err := GetAddressFromBridgeRegistry(backend, sender, registry, BridgeBank)
if nil != err { if nil != err {
return nil, nil, errors.New("Failed to get addr for bridgeBank from registry") return nil, nil, errors.New("Failed to get addr for bridgeBank from registry")
} }
bridgeBank, err := generated.NewBridgeBank(*bridgeBankAddr, client) bridgeBank, err := generated.NewBridgeBank(*bridgeBankAddr, backend)
if nil != err { if nil != err {
return nil, nil, errors.New("Failed to NewBridgeBank") return nil, nil, errors.New("Failed to NewBridgeBank")
} }
chain33BridgeAddr, err := GetAddressFromBridgeRegistry(client, sender, registry, Chain33Bridge) chain33BridgeAddr, err := GetAddressFromBridgeRegistry(backend, sender, registry, Chain33Bridge)
if nil != err { if nil != err {
return nil, nil, errors.New("Failed to get addr for chain33BridgeAddr from registry") return nil, nil, errors.New("Failed to get addr for chain33BridgeAddr from registry")
} }
chain33Bridge, err := generated.NewChain33Bridge(*chain33BridgeAddr, client) chain33Bridge, err := generated.NewChain33Bridge(*chain33BridgeAddr, backend)
if nil != err { if nil != err {
return nil, nil, errors.New("Failed to NewChain33Bridge") return nil, nil, errors.New("Failed to NewChain33Bridge")
} }
oracleAddr, err := GetAddressFromBridgeRegistry(client, sender, registry, Oracle) oracleAddr, err := GetAddressFromBridgeRegistry(backend, sender, registry, Oracle)
if nil != err { if nil != err {
return nil, nil, errors.New("Failed to get addr for oracleBridgeAddr from registry") return nil, nil, errors.New("Failed to get addr for oracleBridgeAddr from registry")
} }
oracle, err := generated.NewOracle(*oracleAddr, client) oracle, err := generated.NewOracle(*oracleAddr, backend)
if nil != err { if nil != err {
return nil, nil, errors.New("Failed to NewOracle") return nil, nil, errors.New("Failed to NewOracle")
} }
registryInstance, _ := generated.NewBridgeRegistry(registry, client) registryInstance, _ := generated.NewBridgeRegistry(registry, backend)
x2EthContracts := &X2EthContracts{ x2EthContracts := &X2EthContracts{
BridgeRegistry: registryInstance, BridgeRegistry: registryInstance,
BridgeBank: bridgeBank, BridgeBank: bridgeBank,
...@@ -54,12 +54,12 @@ func RecoverContractHandler(client *ethclient.Client, sender, registry common.Ad ...@@ -54,12 +54,12 @@ func RecoverContractHandler(client *ethclient.Client, sender, registry common.Ad
return x2EthContracts, x2EthDeployInfo, nil return x2EthContracts, x2EthDeployInfo, nil
} }
func RecoverOracleInstance(client *ethclient.Client, sender, registry common.Address) (*generated.Oracle, error) { func RecoverOracleInstance(backend bind.ContractBackend, sender, registry common.Address) (*generated.Oracle, error) {
oracleAddr, err := GetAddressFromBridgeRegistry(client, sender, registry, Oracle) oracleAddr, err := GetAddressFromBridgeRegistry(backend, sender, registry, Oracle)
if nil != err { if nil != err {
return nil, errors.New("Failed to get addr for oracleBridgeAddr from registry") return nil, errors.New("Failed to get addr for oracleBridgeAddr from registry")
} }
oracle, err := generated.NewOracle(*oracleAddr, client) oracle, err := generated.NewOracle(*oracleAddr, backend)
if nil != err { if nil != err {
return nil, errors.New("Failed to NewOracle") return nil, errors.New("Failed to NewOracle")
} }
......
...@@ -32,8 +32,8 @@ func (d ContractRegistry) String() string { ...@@ -32,8 +32,8 @@ func (d ContractRegistry) String() string {
} }
// GetAddressFromBridgeRegistry : utility method which queries the requested contract address from the BridgeRegistry // GetAddressFromBridgeRegistry : utility method which queries the requested contract address from the BridgeRegistry
func GetAddressFromBridgeRegistry(client *ethclient.Client, sender, registry common.Address, target ContractRegistry) (address *common.Address, err error) { func GetAddressFromBridgeRegistry(backend bind.ContractBackend, sender, registry common.Address, target ContractRegistry) (address *common.Address, err error) {
header, err := client.HeaderByNumber(context.Background(), nil) header, err := backend.(*ethclient.Client).HeaderByNumber(context.Background(), nil)
if err != nil { if err != nil {
txslog.Error("GetAddressFromBridgeRegistry", "Failed to get HeaderByNumber due to:", err.Error()) txslog.Error("GetAddressFromBridgeRegistry", "Failed to get HeaderByNumber due to:", err.Error())
return nil, err return nil, err
...@@ -48,7 +48,7 @@ func GetAddressFromBridgeRegistry(client *ethclient.Client, sender, registry com ...@@ -48,7 +48,7 @@ func GetAddressFromBridgeRegistry(client *ethclient.Client, sender, registry com
} }
// Initialize BridgeRegistry instance // Initialize BridgeRegistry instance
registryInstance, err := bridgeRegistry.NewBridgeRegistry(registry, client) registryInstance, err := bridgeRegistry.NewBridgeRegistry(registry, backend)
if err != nil { if err != nil {
txslog.Error("GetAddressFromBridgeRegistry", "Failed to NewBridgeRegistry to:", err.Error()) txslog.Error("GetAddressFromBridgeRegistry", "Failed to NewBridgeRegistry to:", err.Error())
return nil, err return nil, err
......
...@@ -20,7 +20,7 @@ import ( ...@@ -20,7 +20,7 @@ import (
// RelayLockToChain33 : RelayLockToChain33 applies validator's signature to an EthBridgeClaim message // RelayLockToChain33 : RelayLockToChain33 applies validator's signature to an EthBridgeClaim message
// containing information about an event on the Ethereum blockchain before relaying to the Bridge // containing information about an event on the Ethereum blockchain before relaying to the Bridge
func RelayLockToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.EthBridgeClaim, rpcUrl string) (string, error) { func RelayLockToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.EthBridgeClaim, rpcURL string) (string, error) {
var res string var res string
params := &types.Eth2Chain33{ params := &types.Eth2Chain33{
...@@ -41,7 +41,7 @@ func RelayLockToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes. ...@@ -41,7 +41,7 @@ func RelayLockToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.
ActionName: types.NameEth2Chain33Action, ActionName: types.NameEth2Chain33Action,
Payload: chain33Types.MustPBToJSON(params), Payload: chain33Types.MustPBToJSON(params),
} }
ctx := jsonclient.NewRPCCtx(rpcUrl, "Chain33.CreateTransaction", pm, &res) ctx := jsonclient.NewRPCCtx(rpcURL, "Chain33.CreateTransaction", pm, &res)
_, _ = ctx.RunResult() _, _ = ctx.RunResult()
data, err := common.FromHex(res) data, err := common.FromHex(res)
...@@ -71,12 +71,12 @@ func RelayLockToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes. ...@@ -71,12 +71,12 @@ func RelayLockToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.
} }
var txhash string var txhash string
ctx = jsonclient.NewRPCCtx(rpcUrl, "Chain33.SendTransaction", pms, &txhash) ctx = jsonclient.NewRPCCtx(rpcURL, "Chain33.SendTransaction", pms, &txhash)
_, err = ctx.RunResult() _, err = ctx.RunResult()
return txhash, err return txhash, err
} }
func RelayBurnToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.EthBridgeClaim, rpcUrl string) (string, error) { func RelayBurnToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.EthBridgeClaim, rpcURL string) (string, error) {
var res string var res string
params := &types.Eth2Chain33{ params := &types.Eth2Chain33{
...@@ -97,7 +97,7 @@ func RelayBurnToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes. ...@@ -97,7 +97,7 @@ func RelayBurnToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.
ActionName: types.NameWithdrawEthAction, ActionName: types.NameWithdrawEthAction,
Payload: chain33Types.MustPBToJSON(params), Payload: chain33Types.MustPBToJSON(params),
} }
ctx := jsonclient.NewRPCCtx(rpcUrl, "Chain33.CreateTransaction", pm, &res) ctx := jsonclient.NewRPCCtx(rpcURL, "Chain33.CreateTransaction", pm, &res)
_, _ = ctx.RunResult() _, _ = ctx.RunResult()
data, err := common.FromHex(res) data, err := common.FromHex(res)
...@@ -127,7 +127,7 @@ func RelayBurnToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes. ...@@ -127,7 +127,7 @@ func RelayBurnToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.
} }
var txhash string var txhash string
ctx = jsonclient.NewRPCCtx(rpcUrl, "Chain33.SendTransaction", pms, &txhash) ctx = jsonclient.NewRPCCtx(rpcURL, "Chain33.SendTransaction", pms, &txhash)
_, err = ctx.RunResult() _, err = ctx.RunResult()
return txhash, err return txhash, err
} }
...@@ -3,12 +3,13 @@ package ethtxs ...@@ -3,12 +3,13 @@ package ethtxs
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/33cn/chain33/common/log/log15" "github.com/33cn/chain33/common/log/log15"
"github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/ethcontract/generated" "github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/ethcontract/generated"
"github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/events" "github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/events"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
) )
var ( var (
...@@ -22,10 +23,10 @@ const ( ...@@ -22,10 +23,10 @@ const (
) )
// RelayOracleClaimToEthereum : relays the provided burn or lock to Chain33Bridge contract on the Ethereum network // RelayOracleClaimToEthereum : relays the provided burn or lock to Chain33Bridge contract on the Ethereum network
func RelayOracleClaimToEthereum(oracleInstance *generated.Oracle, client *ethclient.Client, sender common.Address, event events.Event, claim ProphecyClaim, privateKey *ecdsa.PrivateKey, chain33TxHash []byte) (txhash string, err error) { func RelayOracleClaimToEthereum(oracleInstance *generated.Oracle, backend bind.ContractBackend, sender common.Address, event events.Event, claim ProphecyClaim, privateKey *ecdsa.PrivateKey, chain33TxHash []byte) (txhash string, err error) {
txslog.Info("RelayProphecyClaimToEthereum", "sender", sender.String(), "event", event, "chain33Sender", common.ToHex(claim.Chain33Sender), "ethereumReceiver", claim.EthereumReceiver.String(), "TokenAddress", claim.TokenContractAddress.String(), "symbol", claim.Symbol, "Amount", claim.Amount.String(), "claimType", claim.ClaimType.String()) txslog.Info("RelayProphecyClaimToEthereum", "sender", sender.String(), "event", event, "chain33Sender", common.ToHex(claim.Chain33Sender), "ethereumReceiver", claim.EthereumReceiver.String(), "TokenAddress", claim.TokenContractAddress.String(), "symbol", claim.Symbol, "Amount", claim.Amount.String(), "claimType", claim.ClaimType.String())
auth, err := PrepareAuth(client, privateKey, sender) auth, err := PrepareAuth(backend, privateKey, sender)
if nil != err { if nil != err {
txslog.Error("RelayProphecyClaimToEthereum", "PrepareAuth err", err.Error()) txslog.Error("RelayProphecyClaimToEthereum", "PrepareAuth err", err.Error())
return "", err return "", err
......
...@@ -8,17 +8,16 @@ import ( ...@@ -8,17 +8,16 @@ import (
"sync" "sync"
"time" "time"
ebrelayerTypes "github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/types"
"github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/ethclient"
solsha3 "github.com/miguelmota/go-solidity-sha3"
ebrelayerTypes "github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/types"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/secp256k1" "github.com/ethereum/go-ethereum/crypto/secp256k1"
"github.com/ethereum/go-ethereum/ethclient"
solsha3 "github.com/miguelmota/go-solidity-sha3"
) )
type EthTxStatus int32 type EthTxStatus int32
...@@ -66,14 +65,6 @@ func prefixMessage(message common.Hash, key *ecdsa.PrivateKey) ([]byte, []byte) ...@@ -66,14 +65,6 @@ func prefixMessage(message common.Hash, key *ecdsa.PrivateKey) ([]byte, []byte)
return sig, prefixed return sig, prefixed
} }
func loadPrivateKey(privateKey []byte) (key *ecdsa.PrivateKey, err error) {
key, err = crypto.ToECDSA(privateKey)
if nil != err {
return nil, err
}
return
}
// LoadSender : uses the validator's private key to load the validator's address // LoadSender : uses the validator's private key to load the validator's address
func LoadSender(privateKey *ecdsa.PrivateKey) (address common.Address, err error) { func LoadSender(privateKey *ecdsa.PrivateKey) (address common.Address, err error) {
// Parse public key // Parse public key
...@@ -91,7 +82,7 @@ func getNonce(sender common.Address, backend bind.ContractBackend) (*big.Int, er ...@@ -91,7 +82,7 @@ func getNonce(sender common.Address, backend bind.ContractBackend) (*big.Int, er
if nonceMutex, exist := addr2Nonce[sender]; exist { if nonceMutex, exist := addr2Nonce[sender]; exist {
nonceMutex.rw.Lock() nonceMutex.rw.Lock()
defer nonceMutex.rw.Unlock() defer nonceMutex.rw.Unlock()
nonceMutex.nonce += 1 nonceMutex.nonce++
addr2Nonce[sender] = nonceMutex addr2Nonce[sender] = nonceMutex
txslog.Debug("getNonce from cache", "address", sender.String(), "nonce", nonceMutex.nonce) txslog.Debug("getNonce from cache", "address", sender.String(), "nonce", nonceMutex.nonce)
return big.NewInt(nonceMutex.nonce), nil return big.NewInt(nonceMutex.nonce), nil
...@@ -113,7 +104,7 @@ func revokeNonce(sender common.Address) (*big.Int, error) { ...@@ -113,7 +104,7 @@ func revokeNonce(sender common.Address) (*big.Int, error) {
if nonceMutex, exist := addr2Nonce[sender]; exist { if nonceMutex, exist := addr2Nonce[sender]; exist {
nonceMutex.rw.Lock() nonceMutex.rw.Lock()
defer nonceMutex.rw.Unlock() defer nonceMutex.rw.Unlock()
nonceMutex.nonce -= 1 nonceMutex.nonce--
addr2Nonce[sender] = nonceMutex addr2Nonce[sender] = nonceMutex
txslog.Debug("revokeNonce", "address", sender.String(), "nonce", nonceMutex.nonce) txslog.Debug("revokeNonce", "address", sender.String(), "nonce", nonceMutex.nonce)
return big.NewInt(nonceMutex.nonce), nil return big.NewInt(nonceMutex.nonce), nil
...@@ -122,6 +113,8 @@ func revokeNonce(sender common.Address) (*big.Int, error) { ...@@ -122,6 +113,8 @@ func revokeNonce(sender common.Address) (*big.Int, error) {
} }
func PrepareAuth(backend bind.ContractBackend, privateKey *ecdsa.PrivateKey, transactor common.Address) (*bind.TransactOpts, error) { func PrepareAuth(backend bind.ContractBackend, privateKey *ecdsa.PrivateKey, transactor common.Address) (*bind.TransactOpts, error) {
//var backend bind.ContractBackend = client
//client *ethclient.Client
if nil == privateKey || nil == backend { if nil == privateKey || nil == backend {
txslog.Error("PrepareAuth", "nil input parameter", "backend", backend, "privateKey", privateKey) txslog.Error("PrepareAuth", "nil input parameter", "backend", backend, "privateKey", privateKey)
return nil, errors.New("nil input parameter") return nil, errors.New("nil input parameter")
......
...@@ -25,8 +25,8 @@ const ( ...@@ -25,8 +25,8 @@ const (
) )
const ( const (
CLAIM_TYPE_BURN = uint8(1) ClaimTypeBurn = uint8(1)
CLAIM_TYPE_LOCK = uint8(2) ClaimTypeLock = uint8(2)
) )
// String : returns the event type as a string // String : returns the event type as a string
......
...@@ -69,13 +69,13 @@ func main() { ...@@ -69,13 +69,13 @@ func main() {
mainlog.Info("db info:", " Dbdriver = ", cfg.SyncTxConfig.Dbdriver, ", DbPath = ", cfg.SyncTxConfig.DbPath, ", DbCache = ", cfg.SyncTxConfig.DbCache) mainlog.Info("db info:", " Dbdriver = ", cfg.SyncTxConfig.Dbdriver, ", DbPath = ", cfg.SyncTxConfig.DbPath, ", DbCache = ", cfg.SyncTxConfig.DbCache)
db := dbm.NewDB("relayer_db_service", cfg.SyncTxConfig.Dbdriver, cfg.SyncTxConfig.DbPath, cfg.SyncTxConfig.DbCache) db := dbm.NewDB("relayer_db_service", cfg.SyncTxConfig.Dbdriver, cfg.SyncTxConfig.DbPath, cfg.SyncTxConfig.DbCache)
chain33RelayerService := chain33Relayer.StartChain33Relayer(cfg.SyncTxConfig, cfg.BridgeRegistry, cfg.EthProvider, db, ctx) chain33RelayerService := chain33Relayer.StartChain33Relayer(ctx, cfg.SyncTxConfig, cfg.BridgeRegistry, cfg.EthProvider, db)
ethRelayerService := ethRelayer.StartEthereumRelayer(cfg.SyncTxConfig.Chain33Host, db, cfg.EthProvider, cfg.BridgeRegistry, cfg.Deploy, cfg.EthMaturityDegree, cfg.EthBlockFetchPeriod) ethRelayerService := ethRelayer.StartEthereumRelayer(cfg.SyncTxConfig.Chain33Host, db, cfg.EthProvider, cfg.BridgeRegistry, cfg.Deploy, cfg.EthMaturityDegree, cfg.EthBlockFetchPeriod)
relayerManager := relayer.NewRelayerManager(chain33RelayerService, ethRelayerService, db) relayerManager := relayer.NewRelayerManager(chain33RelayerService, ethRelayerService, db)
log.Info("cfg.JrpcBindAddr = ", cfg.JrpcBindAddr) log.Info("cfg.JrpcBindAddr = ", cfg.JrpcBindAddr)
startRpcServer(cfg.JrpcBindAddr, relayerManager) startRPCServer(cfg.JrpcBindAddr, relayerManager)
ch := make(chan os.Signal, 1) ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGTERM) signal.Notify(ch, syscall.SIGTERM)
...@@ -160,16 +160,16 @@ func (r *RPCServer) HandleHTTP(rpcPath, debugPath string) { ...@@ -160,16 +160,16 @@ func (r *RPCServer) HandleHTTP(rpcPath, debugPath string) {
http.Handle(rpcPath, r) http.Handle(rpcPath, r)
} }
type HttpConn struct { type HTTPConn struct {
in io.Reader in io.Reader
out io.Writer out io.Writer
} }
func (c *HttpConn) Read(p []byte) (n int, err error) { return c.in.Read(p) } func (c *HTTPConn) Read(p []byte) (n int, err error) { return c.in.Read(p) }
func (c *HttpConn) Write(d []byte) (n int, err error) { return c.out.Write(d) } func (c *HTTPConn) Write(d []byte) (n int, err error) { return c.out.Write(d) }
func (c *HttpConn) Close() error { return nil } func (c *HTTPConn) Close() error { return nil }
func startRpcServer(address string, api interface{}) { func startRPCServer(address string, api interface{}) {
listener, err := net.Listen("tcp", address) listener, err := net.Listen("tcp", address)
if err != nil { if err != nil {
fmt.Println("监听失败,端口可能已经被占用") fmt.Println("监听失败,端口可能已经被占用")
...@@ -180,7 +180,7 @@ func startRpcServer(address string, api interface{}) { ...@@ -180,7 +180,7 @@ func startRpcServer(address string, api interface{}) {
srv.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath) srv.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" { if r.URL.Path == "/" {
serverCodec := jsonrpc.NewServerCodec(&HttpConn{in: r.Body, out: w}) serverCodec := jsonrpc.NewServerCodec(&HTTPConn{in: r.Body, out: w})
w.Header().Set("Content-type", "application/json") w.Header().Set("Content-type", "application/json")
w.WriteHeader(200) w.WriteHeader(200)
err := srv.ServeRequest(serverCodec) err := srv.ServeRequest(serverCodec)
......
...@@ -15,7 +15,7 @@ var ( ...@@ -15,7 +15,7 @@ var (
start = int(1) start = int(1)
) )
func (chain33Relayer *Chain33Relayer) GetAccount(passphrase string) (privateKey, addr string, err error) { func (chain33Relayer *Relayer4Chain33) GetAccount(passphrase string) (privateKey, addr string, err error) {
accountInfo, err := chain33Relayer.db.Get(chain33AccountKey) accountInfo, err := chain33Relayer.db.Get(chain33AccountKey)
if nil != err { if nil != err {
return "", "", err return "", "", err
...@@ -29,7 +29,7 @@ func (chain33Relayer *Chain33Relayer) GetAccount(passphrase string) (privateKey, ...@@ -29,7 +29,7 @@ func (chain33Relayer *Chain33Relayer) GetAccount(passphrase string) (privateKey,
addr = ethAccount.Addr addr = ethAccount.Addr
return return
} }
func (chain33Relayer *Chain33Relayer) GetAccountAddr() (addr string, err error) { func (chain33Relayer *Relayer4Chain33) GetAccountAddr() (addr string, err error) {
accountInfo, err := chain33Relayer.db.Get(chain33AccountKey) accountInfo, err := chain33Relayer.db.Get(chain33AccountKey)
if nil != err { if nil != err {
relayerLog.Info("GetValidatorAddr", "Failed to get account from db due to:", err.Error()) relayerLog.Info("GetValidatorAddr", "Failed to get account from db due to:", err.Error())
...@@ -44,7 +44,7 @@ func (chain33Relayer *Chain33Relayer) GetAccountAddr() (addr string, err error) ...@@ -44,7 +44,7 @@ func (chain33Relayer *Chain33Relayer) GetAccountAddr() (addr string, err error)
return return
} }
func (chain33Relayer *Chain33Relayer) ImportPrivateKey(passphrase, privateKeyStr string) (addr string, err error) { func (chain33Relayer *Relayer4Chain33) ImportPrivateKey(passphrase, privateKeyStr string) (addr string, err error) {
privateKeySlice, err := chain33Common.FromHex(privateKeyStr) privateKeySlice, err := chain33Common.FromHex(privateKeyStr)
if nil != err { if nil != err {
return "", err return "", err
...@@ -71,7 +71,7 @@ func (chain33Relayer *Chain33Relayer) ImportPrivateKey(passphrase, privateKeyStr ...@@ -71,7 +71,7 @@ func (chain33Relayer *Chain33Relayer) ImportPrivateKey(passphrase, privateKeyStr
return return
} }
func (chain33Relayer *Chain33Relayer) StoreAccountWithNewPassphase(newPassphrase, oldPassphrase string) error { func (chain33Relayer *Relayer4Chain33) StoreAccountWithNewPassphase(newPassphrase, oldPassphrase string) error {
accountInfo, err := chain33Relayer.db.Get(chain33AccountKey) accountInfo, err := chain33Relayer.db.Get(chain33AccountKey)
if nil != err { if nil != err {
relayerLog.Info("StoreAccountWithNewPassphase", "pls check account is created already, err", err) relayerLog.Info("StoreAccountWithNewPassphase", "pls check account is created already, err", err)
...@@ -88,10 +88,10 @@ func (chain33Relayer *Chain33Relayer) StoreAccountWithNewPassphase(newPassphrase ...@@ -88,10 +88,10 @@ func (chain33Relayer *Chain33Relayer) StoreAccountWithNewPassphase(newPassphrase
return chain33Relayer.db.SetSync(chain33AccountKey, encodedInfo) return chain33Relayer.db.SetSync(chain33AccountKey, encodedInfo)
} }
func (chain33Relayer *Chain33Relayer) RestorePrivateKeys(passphrase string) error { func (chain33Relayer *Relayer4Chain33) RestorePrivateKeys(passphrase string) error {
accountInfo, err := chain33Relayer.db.Get(chain33AccountKey) accountInfo, err := chain33Relayer.db.Get(chain33AccountKey)
if nil != err { if nil != err {
relayerLog.Info("No private key saved for Chain33Relayer") relayerLog.Info("No private key saved for Relayer4Chain33")
return nil return nil
} }
ethAccount := &x2ethTypes.Account4Relayer{} ethAccount := &x2ethTypes.Account4Relayer{}
...@@ -114,7 +114,7 @@ func (chain33Relayer *Chain33Relayer) RestorePrivateKeys(passphrase string) erro ...@@ -114,7 +114,7 @@ func (chain33Relayer *Chain33Relayer) RestorePrivateKeys(passphrase string) erro
return nil return nil
} }
func (chain33Relayer *Chain33Relayer) UpdatePrivateKey(Passphrase, privateKey string) error { func (chain33Relayer *Relayer4Chain33) UpdatePrivateKey(Passphrase, privateKey string) error {
return nil return nil
} }
...@@ -11,6 +11,9 @@ import ( ...@@ -11,6 +11,9 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/ethclient"
dbm "github.com/33cn/chain33/common/db" dbm "github.com/33cn/chain33/common/db"
log "github.com/33cn/chain33/common/log/log15" log "github.com/33cn/chain33/common/log/log15"
"github.com/33cn/chain33/rpc/jsonclient" "github.com/33cn/chain33/rpc/jsonclient"
...@@ -24,20 +27,16 @@ import ( ...@@ -24,20 +27,16 @@ import (
"github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/utils" "github.com/33cn/plugin/plugin/dapp/x2Ethereum/ebrelayer/utils"
"github.com/33cn/plugin/plugin/dapp/x2Ethereum/types" "github.com/33cn/plugin/plugin/dapp/x2Ethereum/types"
ethCommon "github.com/ethereum/go-ethereum/common" ethCommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
) )
var relayerLog = log.New("module", "chain33_relayer") var relayerLog = log.New("module", "chain33_relayer")
type Chain33Relayer struct { type Relayer4Chain33 struct {
syncTxReceipts *syncTx.SyncTxReceipts syncTxReceipts *syncTx.TxReceipts
client *ethclient.Client ethBackend bind.ContractBackend
rpcLaddr string //用户向指定的blockchain节点进行rpc调用 rpcLaddr string //用户向指定的blockchain节点进行rpc调用
fetchHeightPeriodMs int64 fetchHeightPeriodMs int64
db dbm.DB db dbm.DB
syncTxChan <-chan int64
//height int64 //当前区块高度 +++++++++||++++++++++++||++++++++++||
//heightSync2App int64 //已经同步高度 ^ ^ ^
lastHeight4Tx int64 //等待被处理的具有相应的交易回执的高度 lastHeight4Tx int64 //等待被处理的具有相应的交易回执的高度
matDegree int32 //成熟度 heightSync2App matDegress height matDegree int32 //成熟度 heightSync2App matDegress height
passphase string passphase string
...@@ -48,15 +47,14 @@ type Chain33Relayer struct { ...@@ -48,15 +47,14 @@ type Chain33Relayer struct {
totalTx4Chain33ToEth int64 totalTx4Chain33ToEth int64
statusCheckedIndex int64 statusCheckedIndex int64
ctx context.Context ctx context.Context
wg sync.WaitGroup
rwLock sync.RWMutex rwLock sync.RWMutex
unlock chan int unlock chan int
status int32 status int32
} }
// StartChain33Relayer : initializes a relayer which witnesses events on the chain33 network and relays them to Ethereum // StartChain33Relayer : initializes a relayer which witnesses events on the chain33 network and relays them to Ethereum
func StartChain33Relayer(syncTxConfig *ebTypes.SyncTxConfig, registryAddr, provider string, db dbm.DB, ctx context.Context) *Chain33Relayer { func StartChain33Relayer(ctx context.Context, syncTxConfig *ebTypes.SyncTxConfig, registryAddr, provider string, db dbm.DB) *Relayer4Chain33 {
relayer := &Chain33Relayer{ relayer := &Relayer4Chain33{
rpcLaddr: syncTxConfig.Chain33Host, rpcLaddr: syncTxConfig.Chain33Host,
fetchHeightPeriodMs: syncTxConfig.FetchHeightPeriodMs, fetchHeightPeriodMs: syncTxConfig.FetchHeightPeriodMs,
unlock: make(chan int), unlock: make(chan int),
...@@ -79,7 +77,7 @@ func StartChain33Relayer(syncTxConfig *ebTypes.SyncTxConfig, registryAddr, provi ...@@ -79,7 +77,7 @@ func StartChain33Relayer(syncTxConfig *ebTypes.SyncTxConfig, registryAddr, provi
if err != nil { if err != nil {
panic(err) panic(err)
} }
relayer.client = client relayer.ethBackend = client
relayer.totalTx4Chain33ToEth = relayer.getTotalTxAmount2Eth() relayer.totalTx4Chain33ToEth = relayer.getTotalTxAmount2Eth()
relayer.statusCheckedIndex = relayer.getStatusCheckedIndex() relayer.statusCheckedIndex = relayer.getStatusCheckedIndex()
...@@ -87,18 +85,18 @@ func StartChain33Relayer(syncTxConfig *ebTypes.SyncTxConfig, registryAddr, provi ...@@ -87,18 +85,18 @@ func StartChain33Relayer(syncTxConfig *ebTypes.SyncTxConfig, registryAddr, provi
return relayer return relayer
} }
func (chain33Relayer *Chain33Relayer) SetPassphase(passphase string) { func (chain33Relayer *Relayer4Chain33) SetPassphase(passphase string) {
chain33Relayer.rwLock.Lock() chain33Relayer.rwLock.Lock()
chain33Relayer.passphase = passphase chain33Relayer.passphase = passphase
chain33Relayer.rwLock.Unlock() chain33Relayer.rwLock.Unlock()
} }
func (chain33Relayer *Chain33Relayer) QueryTxhashRelay2Eth() ebTypes.Txhashes { func (chain33Relayer *Relayer4Chain33) QueryTxhashRelay2Eth() ebTypes.Txhashes {
txhashs := utils.QueryTxhashes([]byte(chain33ToEthBurnLockTxHashPrefix), chain33Relayer.db) txhashs := utils.QueryTxhashes([]byte(chain33ToEthBurnLockTxHashPrefix), chain33Relayer.db)
return ebTypes.Txhashes{Txhash: txhashs} return ebTypes.Txhashes{Txhash: txhashs}
} }
func (chain33Relayer *Chain33Relayer) GetRunningStatus() (relayerRunStatus *ebTypes.RelayerRunStatus) { func (chain33Relayer *Relayer4Chain33) GetRunningStatus() (relayerRunStatus *ebTypes.RelayerRunStatus) {
relayerRunStatus = &ebTypes.RelayerRunStatus{} relayerRunStatus = &ebTypes.RelayerRunStatus{}
chain33Relayer.rwLock.RLock() chain33Relayer.rwLock.RLock()
relayerRunStatus.Status = chain33Relayer.status relayerRunStatus.Status = chain33Relayer.status
...@@ -113,7 +111,7 @@ func (chain33Relayer *Chain33Relayer) GetRunningStatus() (relayerRunStatus *ebTy ...@@ -113,7 +111,7 @@ func (chain33Relayer *Chain33Relayer) GetRunningStatus() (relayerRunStatus *ebTy
return return
} }
func (chain33Relayer *Chain33Relayer) syncProc(syncCfg *ebTypes.SyncTxReceiptConfig) { func (chain33Relayer *Relayer4Chain33) syncProc(syncCfg *ebTypes.SyncTxReceiptConfig) {
_, _ = fmt.Fprintln(os.Stdout, "Pls unlock or import private key for Chain33 relayer") _, _ = fmt.Fprintln(os.Stdout, "Pls unlock or import private key for Chain33 relayer")
<-chain33Relayer.unlock <-chain33Relayer.unlock
_, _ = fmt.Fprintln(os.Stdout, "Chain33 relayer starts to run...") _, _ = fmt.Fprintln(os.Stdout, "Chain33 relayer starts to run...")
...@@ -121,7 +119,7 @@ func (chain33Relayer *Chain33Relayer) syncProc(syncCfg *ebTypes.SyncTxReceiptCon ...@@ -121,7 +119,7 @@ func (chain33Relayer *Chain33Relayer) syncProc(syncCfg *ebTypes.SyncTxReceiptCon
chain33Relayer.syncTxReceipts = syncTx.StartSyncTxReceipt(syncCfg, chain33Relayer.db) chain33Relayer.syncTxReceipts = syncTx.StartSyncTxReceipt(syncCfg, chain33Relayer.db)
chain33Relayer.lastHeight4Tx = chain33Relayer.loadLastSyncHeight() chain33Relayer.lastHeight4Tx = chain33Relayer.loadLastSyncHeight()
oracleInstance, err := relayerTx.RecoverOracleInstance(chain33Relayer.client, chain33Relayer.bridgeRegistryAddr, chain33Relayer.bridgeRegistryAddr) oracleInstance, err := relayerTx.RecoverOracleInstance(chain33Relayer.ethBackend, chain33Relayer.bridgeRegistryAddr, chain33Relayer.bridgeRegistryAddr)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }
...@@ -142,7 +140,7 @@ func (chain33Relayer *Chain33Relayer) syncProc(syncCfg *ebTypes.SyncTxReceiptCon ...@@ -142,7 +140,7 @@ func (chain33Relayer *Chain33Relayer) syncProc(syncCfg *ebTypes.SyncTxReceiptCon
} }
} }
func (chain33Relayer *Chain33Relayer) getCurrentHeight() int64 { func (chain33Relayer *Relayer4Chain33) getCurrentHeight() int64 {
var res rpctypes.Header var res rpctypes.Header
ctx := jsonclient.NewRPCCtx(chain33Relayer.rpcLaddr, "Chain33.GetLastHeader", nil, &res) ctx := jsonclient.NewRPCCtx(chain33Relayer.rpcLaddr, "Chain33.GetLastHeader", nil, &res)
_, err := ctx.RunResult() _, err := ctx.RunResult()
...@@ -152,7 +150,7 @@ func (chain33Relayer *Chain33Relayer) getCurrentHeight() int64 { ...@@ -152,7 +150,7 @@ func (chain33Relayer *Chain33Relayer) getCurrentHeight() int64 {
return res.Height return res.Height
} }
func (chain33Relayer *Chain33Relayer) onNewHeightProc(currentHeight int64) { func (chain33Relayer *Relayer4Chain33) onNewHeightProc(currentHeight int64) {
//检查已经提交的交易结果 //检查已经提交的交易结果
for chain33Relayer.statusCheckedIndex < chain33Relayer.totalTx4Chain33ToEth { for chain33Relayer.statusCheckedIndex < chain33Relayer.totalTx4Chain33ToEth {
index := chain33Relayer.statusCheckedIndex + 1 index := chain33Relayer.statusCheckedIndex + 1
...@@ -161,7 +159,7 @@ func (chain33Relayer *Chain33Relayer) onNewHeightProc(currentHeight int64) { ...@@ -161,7 +159,7 @@ func (chain33Relayer *Chain33Relayer) onNewHeightProc(currentHeight int64) {
relayerLog.Error("onNewHeightProc", "getEthTxhash for index ", index, "error", err.Error()) relayerLog.Error("onNewHeightProc", "getEthTxhash for index ", index, "error", err.Error())
break break
} }
status := relayerTx.GetEthTxStatus(chain33Relayer.client, txhash) status := relayerTx.GetEthTxStatus(chain33Relayer.ethBackend.(*ethclient.Client), txhash)
//按照提交交易的先后顺序检查交易,只要出现当前交易还在pending状态,就不再检查后续交易,等到下个区块再从该交易进行检查 //按照提交交易的先后顺序检查交易,只要出现当前交易还在pending状态,就不再检查后续交易,等到下个区块再从该交易进行检查
//TODO:可能会由于网络和打包挖矿的原因,使得交易执行顺序和提交顺序有差别,后续完善该检查逻辑 //TODO:可能会由于网络和打包挖矿的原因,使得交易执行顺序和提交顺序有差别,后续完善该检查逻辑
if status == relayerTx.EthTxPending.String() { if status == relayerTx.EthTxPending.String() {
...@@ -219,9 +217,9 @@ func getOracleClaimType(eventType string) events.Event { ...@@ -219,9 +217,9 @@ func getOracleClaimType(eventType string) events.Event {
switch eventType { switch eventType {
case events.MsgBurn.String(): case events.MsgBurn.String():
claimType = events.Event(events.CLAIM_TYPE_BURN) claimType = events.Event(events.ClaimTypeBurn)
case events.MsgLock.String(): case events.MsgLock.String():
claimType = events.Event(events.CLAIM_TYPE_LOCK) claimType = events.Event(events.ClaimTypeLock)
default: default:
panic(errors.New("eventType invalid")) panic(errors.New("eventType invalid"))
} }
...@@ -230,7 +228,7 @@ func getOracleClaimType(eventType string) events.Event { ...@@ -230,7 +228,7 @@ func getOracleClaimType(eventType string) events.Event {
} }
// handleBurnLockMsg : parse event data as a Chain33Msg, package it into a ProphecyClaim, then relay tx to the Ethereum Network // handleBurnLockMsg : parse event data as a Chain33Msg, package it into a ProphecyClaim, then relay tx to the Ethereum Network
func (chain33Relayer *Chain33Relayer) handleBurnLockMsg(claimEvent events.Event, receipt *chain33Types.ReceiptData, chain33TxHash []byte) error { func (chain33Relayer *Relayer4Chain33) handleBurnLockMsg(claimEvent events.Event, receipt *chain33Types.ReceiptData, chain33TxHash []byte) error {
relayerLog.Info("handleBurnLockMsg", "Received tx with hash", ethCommon.Bytes2Hex(chain33TxHash)) relayerLog.Info("handleBurnLockMsg", "Received tx with hash", ethCommon.Bytes2Hex(chain33TxHash))
// Parse the witnessed event's data into a new Chain33Msg // Parse the witnessed event's data into a new Chain33Msg
...@@ -245,7 +243,7 @@ func (chain33Relayer *Chain33Relayer) handleBurnLockMsg(claimEvent events.Event, ...@@ -245,7 +243,7 @@ func (chain33Relayer *Chain33Relayer) handleBurnLockMsg(claimEvent events.Event,
prophecyClaim := relayerTx.Chain33MsgToProphecyClaim(*chain33Msg) prophecyClaim := relayerTx.Chain33MsgToProphecyClaim(*chain33Msg)
// Relay the Chain33Msg to the Ethereum network // Relay the Chain33Msg to the Ethereum network
txhash, err := relayerTx.RelayOracleClaimToEthereum(chain33Relayer.oracleInstance, chain33Relayer.client, chain33Relayer.ethSender, claimEvent, prophecyClaim, chain33Relayer.privateKey4Ethereum, chain33TxHash) txhash, err := relayerTx.RelayOracleClaimToEthereum(chain33Relayer.oracleInstance, chain33Relayer.ethBackend, chain33Relayer.ethSender, claimEvent, prophecyClaim, chain33Relayer.privateKey4Ethereum, chain33TxHash)
if nil != err { if nil != err {
return err return err
} }
......
...@@ -21,7 +21,7 @@ func calcRelay2EthTxhash(txindex int64) []byte { ...@@ -21,7 +21,7 @@ func calcRelay2EthTxhash(txindex int64) []byte {
return []byte(fmt.Sprintf("%s-%012d", chain33ToEthBurnLockTxHashPrefix, txindex)) return []byte(fmt.Sprintf("%s-%012d", chain33ToEthBurnLockTxHashPrefix, txindex))
} }
func (chain33Relayer *Chain33Relayer) updateTotalTxAmount2Eth(total int64) error { func (chain33Relayer *Relayer4Chain33) updateTotalTxAmount2Eth(total int64) error {
totalTx := &types.Int64{ totalTx := &types.Int64{
Data: atomic.LoadInt64(&chain33Relayer.totalTx4Chain33ToEth), Data: atomic.LoadInt64(&chain33Relayer.totalTx4Chain33ToEth),
} }
...@@ -29,12 +29,12 @@ func (chain33Relayer *Chain33Relayer) updateTotalTxAmount2Eth(total int64) error ...@@ -29,12 +29,12 @@ func (chain33Relayer *Chain33Relayer) updateTotalTxAmount2Eth(total int64) error
return chain33Relayer.db.Set(chain33ToEthBurnLockTxTotalAmount, types.Encode(totalTx)) return chain33Relayer.db.Set(chain33ToEthBurnLockTxTotalAmount, types.Encode(totalTx))
} }
func (chain33Relayer *Chain33Relayer) getTotalTxAmount2Eth() int64 { func (chain33Relayer *Relayer4Chain33) getTotalTxAmount2Eth() int64 {
totalTx, _ := utils.LoadInt64FromDB(chain33ToEthBurnLockTxTotalAmount, chain33Relayer.db) totalTx, _ := utils.LoadInt64FromDB(chain33ToEthBurnLockTxTotalAmount, chain33Relayer.db)
return totalTx return totalTx
} }
func (chain33Relayer *Chain33Relayer) setLastestRelay2EthTxhash(status, txhash string, txIndex int64) error { func (chain33Relayer *Relayer4Chain33) setLastestRelay2EthTxhash(status, txhash string, txIndex int64) error {
key := calcRelay2EthTxhash(txIndex) key := calcRelay2EthTxhash(txIndex)
ethTxStatus := &ebTypes.EthTxStatus{ ethTxStatus := &ebTypes.EthTxStatus{
Status: status, Status: status,
...@@ -44,7 +44,7 @@ func (chain33Relayer *Chain33Relayer) setLastestRelay2EthTxhash(status, txhash s ...@@ -44,7 +44,7 @@ func (chain33Relayer *Chain33Relayer) setLastestRelay2EthTxhash(status, txhash s
return chain33Relayer.db.Set(key, data) return chain33Relayer.db.Set(key, data)
} }
func (chain33Relayer *Chain33Relayer) getEthTxhash(txIndex int64) (common.Hash, error) { func (chain33Relayer *Relayer4Chain33) getEthTxhash(txIndex int64) (common.Hash, error) {
key := calcRelay2EthTxhash(txIndex) key := calcRelay2EthTxhash(txIndex)
ethTxStatus := &ebTypes.EthTxStatus{} ethTxStatus := &ebTypes.EthTxStatus{}
data, err := chain33Relayer.db.Get(key) data, err := chain33Relayer.db.Get(key)
...@@ -58,7 +58,7 @@ func (chain33Relayer *Chain33Relayer) getEthTxhash(txIndex int64) (common.Hash, ...@@ -58,7 +58,7 @@ func (chain33Relayer *Chain33Relayer) getEthTxhash(txIndex int64) (common.Hash,
return common.HexToHash(ethTxStatus.Txhash), nil return common.HexToHash(ethTxStatus.Txhash), nil
} }
func (chain33Relayer *Chain33Relayer) setStatusCheckedIndex(txIndex int64) error { func (chain33Relayer *Relayer4Chain33) setStatusCheckedIndex(txIndex int64) error {
index := &types.Int64{ index := &types.Int64{
Data: txIndex, Data: txIndex,
} }
...@@ -66,13 +66,13 @@ func (chain33Relayer *Chain33Relayer) setStatusCheckedIndex(txIndex int64) error ...@@ -66,13 +66,13 @@ func (chain33Relayer *Chain33Relayer) setStatusCheckedIndex(txIndex int64) error
return chain33Relayer.db.Set(EthTxStatusCheckedIndex, data) return chain33Relayer.db.Set(EthTxStatusCheckedIndex, data)
} }
func (chain33Relayer *Chain33Relayer) getStatusCheckedIndex() int64 { func (chain33Relayer *Relayer4Chain33) getStatusCheckedIndex() int64 {
index, _ := utils.LoadInt64FromDB(EthTxStatusCheckedIndex, chain33Relayer.db) index, _ := utils.LoadInt64FromDB(EthTxStatusCheckedIndex, chain33Relayer.db)
return index return index
} }
//获取上次同步到app的高度 //获取上次同步到app的高度
func (chain33Relayer *Chain33Relayer) loadLastSyncHeight() int64 { func (chain33Relayer *Relayer4Chain33) loadLastSyncHeight() int64 {
height, err := utils.LoadInt64FromDB(lastSyncHeightPrefix, chain33Relayer.db) height, err := utils.LoadInt64FromDB(lastSyncHeightPrefix, chain33Relayer.db)
if nil != err && err != types.ErrHeightNotExist { if nil != err && err != types.ErrHeightNotExist {
relayerLog.Error("loadLastSyncHeight", "err:", err.Error()) relayerLog.Error("loadLastSyncHeight", "err:", err.Error())
...@@ -81,7 +81,7 @@ func (chain33Relayer *Chain33Relayer) loadLastSyncHeight() int64 { ...@@ -81,7 +81,7 @@ func (chain33Relayer *Chain33Relayer) loadLastSyncHeight() int64 {
return height return height
} }
func (chain33Relayer *Chain33Relayer) setLastSyncHeight(syncHeight int64) { func (chain33Relayer *Relayer4Chain33) setLastSyncHeight(syncHeight int64) {
bytes := types.Encode(&types.Int64{Data: syncHeight}) bytes := types.Encode(&types.Int64{Data: syncHeight})
_ = chain33Relayer.db.Set(lastSyncHeightPrefix, bytes) _ = chain33Relayer.db.Set(lastSyncHeightPrefix, bytes)
} }
...@@ -21,7 +21,6 @@ var ( ...@@ -21,7 +21,6 @@ var (
syncLastHeight = []byte("syncLastHeight:") syncLastHeight = []byte("syncLastHeight:")
txReceiptPrefix = []byte("txReceiptPrefix:") txReceiptPrefix = []byte("txReceiptPrefix:")
lastSequences = []byte("lastSequences:") lastSequences = []byte("lastSequences:")
lastSyncHeight = []byte("lastSyncHeight:")
seqOperationType = []string{"SeqTypeAdd", "SeqTypeDel"} seqOperationType = []string{"SeqTypeAdd", "SeqTypeDel"}
) )
...@@ -44,15 +43,15 @@ func pushTxReceipts(txReceipts *types.TxReceipts4Subscribe) error { ...@@ -44,15 +43,15 @@ func pushTxReceipts(txReceipts *types.TxReceipts4Subscribe) error {
return err return err
} }
type SyncTxReceipts struct { type TxReceipts struct {
db dbm.DB db dbm.DB
seqNum int64 //当前同步的序列号 seqNum int64 //当前同步的序列号
height int64 //当前区块高度 height int64 //当前区块高度
quit chan struct{} quit chan struct{}
} }
func NewSyncTxReceipts(db dbm.DB) *SyncTxReceipts { func NewSyncTxReceipts(db dbm.DB) *TxReceipts {
sync := &SyncTxReceipts{ sync := &TxReceipts{
db: db, db: db,
} }
sync.seqNum, _ = sync.loadBlockLastSequence() sync.seqNum, _ = sync.loadBlockLastSequence()
...@@ -64,7 +63,7 @@ func NewSyncTxReceipts(db dbm.DB) *SyncTxReceipts { ...@@ -64,7 +63,7 @@ func NewSyncTxReceipts(db dbm.DB) *SyncTxReceipts {
} }
//此处添加一个高度为0的空块,只是为了查找下一个比较方便,并不需要使用其信息 //此处添加一个高度为0的空块,只是为了查找下一个比较方便,并不需要使用其信息
func (syncTx *SyncTxReceipts) initSyncReceiptDataBase() { func (syncTx *TxReceipts) initSyncReceiptDataBase() {
txblock0, _ := syncTx.GetTxReceipts(0) txblock0, _ := syncTx.GetTxReceipts(0)
if nil != txblock0 { if nil != txblock0 {
return return
...@@ -75,12 +74,12 @@ func (syncTx *SyncTxReceipts) initSyncReceiptDataBase() { ...@@ -75,12 +74,12 @@ func (syncTx *SyncTxReceipts) initSyncReceiptDataBase() {
syncTx.setTxReceiptsPerBlock(txsPerBlock) syncTx.setTxReceiptsPerBlock(txsPerBlock)
} }
func (syncTx *SyncTxReceipts) Stop() { func (syncTx *TxReceipts) Stop() {
close(syncTx.quit) close(syncTx.quit)
} }
// SaveAndSyncTxs2Relayer save block to db // SaveAndSyncTxs2Relayer save block to db
func (syncTx *SyncTxReceipts) SaveAndSyncTxs2Relayer() { func (syncTx *TxReceipts) SaveAndSyncTxs2Relayer() {
for { for {
select { select {
case txReceipts := <-txReceiptCh: case txReceipts := <-txReceiptCh:
...@@ -103,7 +102,7 @@ func (syncTx *SyncTxReceipts) SaveAndSyncTxs2Relayer() { ...@@ -103,7 +102,7 @@ func (syncTx *SyncTxReceipts) SaveAndSyncTxs2Relayer() {
// 所以不需要恢复过程, 读出高度即可 // 所以不需要恢复过程, 读出高度即可
// 处理输入流程 // 处理输入流程
func (syncTx *SyncTxReceipts) dealTxReceipts(txReceipts *types.TxReceipts4Subscribe) { func (syncTx *TxReceipts) dealTxReceipts(txReceipts *types.TxReceipts4Subscribe) {
count, start, txReceiptsParsed, err := parseTxReceipts(txReceipts) count, start, txReceiptsParsed, err := parseTxReceipts(txReceipts)
if err != nil { if err != nil {
resultCh <- err resultCh <- err
...@@ -136,35 +135,34 @@ func (syncTx *SyncTxReceipts) dealTxReceipts(txReceipts *types.TxReceipts4Subscr ...@@ -136,35 +135,34 @@ func (syncTx *SyncTxReceipts) dealTxReceipts(txReceipts *types.TxReceipts4Subscr
//发送回复,确认接收成功 //发送回复,确认接收成功
resultCh <- nil resultCh <- nil
log.Debug("dealTxReceipts", "seqStart", start, "count", count, "maxBlockHeight", height) log.Debug("dealTxReceipts", "seqStart", start, "count", count, "maxBlockHeight", height)
return
} }
func (syncTx *SyncTxReceipts) loadBlockLastSequence() (int64, error) { func (syncTx *TxReceipts) loadBlockLastSequence() (int64, error) {
return utils.LoadInt64FromDB(lastSequences, syncTx.db) return utils.LoadInt64FromDB(lastSequences, syncTx.db)
} }
func (syncTx *SyncTxReceipts) LoadLastBlockHeight() (int64, error) { func (syncTx *TxReceipts) LoadLastBlockHeight() (int64, error) {
return utils.LoadInt64FromDB(syncLastHeight, syncTx.db) return utils.LoadInt64FromDB(syncLastHeight, syncTx.db)
} }
func (syncTx *SyncTxReceipts) setBlockLastSequence(newSequence int64) { func (syncTx *TxReceipts) setBlockLastSequence(newSequence int64) {
Sequencebytes := types.Encode(&types.Int64{Data: newSequence}) Sequencebytes := types.Encode(&types.Int64{Data: newSequence})
syncTx.db.Set(lastSequences, Sequencebytes) syncTx.db.Set(lastSequences, Sequencebytes)
//同时更新内存中的seq //同时更新内存中的seq
syncTx.updateSequence(newSequence) syncTx.updateSequence(newSequence)
} }
func (syncTx *SyncTxReceipts) setBlockHeight(height int64) { func (syncTx *TxReceipts) setBlockHeight(height int64) {
bytes := types.Encode(&types.Int64{Data: height}) bytes := types.Encode(&types.Int64{Data: height})
syncTx.db.Set(syncLastHeight, bytes) syncTx.db.Set(syncLastHeight, bytes)
atomic.StoreInt64(&syncTx.height, height) atomic.StoreInt64(&syncTx.height, height)
} }
func (syncTx *SyncTxReceipts) updateSequence(newSequence int64) { func (syncTx *TxReceipts) updateSequence(newSequence int64) {
atomic.StoreInt64(&syncTx.seqNum, newSequence) atomic.StoreInt64(&syncTx.seqNum, newSequence)
} }
func (syncTx *SyncTxReceipts) setTxReceiptsPerBlock(txReceipts *types.TxReceipts4SubscribePerBlk) { func (syncTx *TxReceipts) setTxReceiptsPerBlock(txReceipts *types.TxReceipts4SubscribePerBlk) {
key := txReceiptsKey4Height(txReceipts.Height) key := txReceiptsKey4Height(txReceipts.Height)
value := types.Encode(txReceipts) value := types.Encode(txReceipts)
if err := syncTx.db.Set(key, value); nil != err { if err := syncTx.db.Set(key, value); nil != err {
...@@ -172,7 +170,7 @@ func (syncTx *SyncTxReceipts) setTxReceiptsPerBlock(txReceipts *types.TxReceipts ...@@ -172,7 +170,7 @@ func (syncTx *SyncTxReceipts) setTxReceiptsPerBlock(txReceipts *types.TxReceipts
} }
} }
func (syncTx *SyncTxReceipts) GetTxReceipts(height int64) (*types.TxReceipts4SubscribePerBlk, error) { func (syncTx *TxReceipts) GetTxReceipts(height int64) (*types.TxReceipts4SubscribePerBlk, error) {
key := txReceiptsKey4Height(height) key := txReceiptsKey4Height(height)
value, err := syncTx.db.Get(key) value, err := syncTx.db.Get(key)
if err != nil { if err != nil {
...@@ -186,7 +184,7 @@ func (syncTx *SyncTxReceipts) GetTxReceipts(height int64) (*types.TxReceipts4Sub ...@@ -186,7 +184,7 @@ func (syncTx *SyncTxReceipts) GetTxReceipts(height int64) (*types.TxReceipts4Sub
return detail, nil return detail, nil
} }
func (syncTx *SyncTxReceipts) GetNextValidTxReceipts(height int64) (*types.TxReceipts4SubscribePerBlk, error) { func (syncTx *TxReceipts) GetNextValidTxReceipts(height int64) (*types.TxReceipts4SubscribePerBlk, error) {
key := txReceiptsKey4Height(height) key := txReceiptsKey4Height(height)
helper := dbm.NewListHelper(syncTx.db) helper := dbm.NewListHelper(syncTx.db)
TxReceipts := helper.List(txReceiptPrefix, key, 1, dbm.ListASC) TxReceipts := helper.List(txReceiptPrefix, key, 1, dbm.ListASC)
...@@ -201,7 +199,7 @@ func (syncTx *SyncTxReceipts) GetNextValidTxReceipts(height int64) (*types.TxRec ...@@ -201,7 +199,7 @@ func (syncTx *SyncTxReceipts) GetNextValidTxReceipts(height int64) (*types.TxRec
return detail, nil return detail, nil
} }
func (syncTx *SyncTxReceipts) delTxReceipts(height int64) { func (syncTx *TxReceipts) delTxReceipts(height int64) {
key := txReceiptsKey4Height(height) key := txReceiptsKey4Height(height)
_ = syncTx.db.Set(key, nil) _ = syncTx.db.Set(key, nil)
} }
......
...@@ -22,12 +22,12 @@ import ( ...@@ -22,12 +22,12 @@ import (
var ( var (
log = l.New("module", "sync.tx_receipts") log = l.New("module", "sync.tx_receipts")
syncTxReceipts *SyncTxReceipts syncTxReceipts *TxReceipts
) )
func StartSyncTxReceipt(cfg *relayerTypes.SyncTxReceiptConfig, db dbm.DB) *SyncTxReceipts { func StartSyncTxReceipt(cfg *relayerTypes.SyncTxReceiptConfig, db dbm.DB) *TxReceipts {
log.Debug("StartSyncTxReceipt, load config", "para:", cfg) log.Debug("StartSyncTxReceipt, load config", "para:", cfg)
log.Debug("SyncTxReceipts started ") log.Debug("TxReceipts started ")
bindOrResumePush(cfg) bindOrResumePush(cfg)
syncTxReceipts = NewSyncTxReceipts(db) syncTxReceipts = NewSyncTxReceipts(db)
......
...@@ -29,7 +29,7 @@ var ( ...@@ -29,7 +29,7 @@ var (
) )
type Key struct { type Key struct {
Id uuid.UUID // Version 4 "random" for unique id not derived from key data ID uuid.UUID // Version 4 "random" for unique id not derived from key data
// to simplify lookups we also store the address // to simplify lookups we also store the address
Address common.Address Address common.Address
// we only store privkey as pubkey/address can be derived from it // we only store privkey as pubkey/address can be derived from it
...@@ -37,7 +37,7 @@ type Key struct { ...@@ -37,7 +37,7 @@ type Key struct {
PrivateKey *ecdsa.PrivateKey PrivateKey *ecdsa.PrivateKey
} }
func (ethRelayer *EthereumRelayer) NewAccount(passphrase string) (privateKeystr, addr string, err error) { func (ethRelayer *Relayer4Ethereum) NewAccount(passphrase string) (privateKeystr, addr string, err error) {
var privateKey *ecdsa.PrivateKey var privateKey *ecdsa.PrivateKey
privateKey, privateKeystr, addr, err = newKeyAndStore(ethRelayer.db, crand.Reader, passphrase) privateKey, privateKeystr, addr, err = newKeyAndStore(ethRelayer.db, crand.Reader, passphrase)
if err != nil { if err != nil {
...@@ -47,7 +47,7 @@ func (ethRelayer *EthereumRelayer) NewAccount(passphrase string) (privateKeystr, ...@@ -47,7 +47,7 @@ func (ethRelayer *EthereumRelayer) NewAccount(passphrase string) (privateKeystr,
return return
} }
func (ethRelayer *EthereumRelayer) GetAccount(passphrase string) (privateKey, addr string, err error) { func (ethRelayer *Relayer4Ethereum) GetAccount(passphrase string) (privateKey, addr string, err error) {
accountInfo, err := ethRelayer.db.Get(ethAccountKey) accountInfo, err := ethRelayer.db.Get(ethAccountKey)
if nil != err { if nil != err {
return "", "", err return "", "", err
...@@ -62,7 +62,7 @@ func (ethRelayer *EthereumRelayer) GetAccount(passphrase string) (privateKey, ad ...@@ -62,7 +62,7 @@ func (ethRelayer *EthereumRelayer) GetAccount(passphrase string) (privateKey, ad
return return
} }
func (ethRelayer *EthereumRelayer) GetValidatorAddr() (validators x2ethTypes.ValidatorAddr4EthRelayer, err error) { func (ethRelayer *Relayer4Ethereum) GetValidatorAddr() (validators x2ethTypes.ValidatorAddr4EthRelayer, err error) {
var ethAccountAddr string var ethAccountAddr string
var chain33AccountAddr string var chain33AccountAddr string
accountInfo, err := ethRelayer.db.Get(ethAccountKey) accountInfo, err := ethRelayer.db.Get(ethAccountKey)
...@@ -92,7 +92,7 @@ func (ethRelayer *EthereumRelayer) GetValidatorAddr() (validators x2ethTypes.Val ...@@ -92,7 +92,7 @@ func (ethRelayer *EthereumRelayer) GetValidatorAddr() (validators x2ethTypes.Val
return return
} }
func (ethRelayer *EthereumRelayer) RestorePrivateKeys(passPhase string) (err error) { func (ethRelayer *Relayer4Ethereum) RestorePrivateKeys(passPhase string) (err error) {
accountInfo, err := ethRelayer.db.Get(ethAccountKey) accountInfo, err := ethRelayer.db.Get(ethAccountKey)
if nil == err { if nil == err {
ethAccount := &x2ethTypes.Account4Relayer{} ethAccount := &x2ethTypes.Account4Relayer{}
...@@ -135,7 +135,7 @@ func (ethRelayer *EthereumRelayer) RestorePrivateKeys(passPhase string) (err err ...@@ -135,7 +135,7 @@ func (ethRelayer *EthereumRelayer) RestorePrivateKeys(passPhase string) (err err
return nil return nil
} }
func (ethRelayer *EthereumRelayer) StoreAccountWithNewPassphase(newPassphrase, oldPassphrase string) error { func (ethRelayer *Relayer4Ethereum) StoreAccountWithNewPassphase(newPassphrase, oldPassphrase string) error {
accountInfo, err := ethRelayer.db.Get(ethAccountKey) accountInfo, err := ethRelayer.db.Get(ethAccountKey)
if nil != err { if nil != err {
relayerLog.Info("StoreAccountWithNewPassphase", "pls check account is created already, err", err) relayerLog.Info("StoreAccountWithNewPassphase", "pls check account is created already, err", err)
...@@ -152,7 +152,7 @@ func (ethRelayer *EthereumRelayer) StoreAccountWithNewPassphase(newPassphrase, o ...@@ -152,7 +152,7 @@ func (ethRelayer *EthereumRelayer) StoreAccountWithNewPassphase(newPassphrase, o
return ethRelayer.db.SetSync(ethAccountKey, encodedInfo) return ethRelayer.db.SetSync(ethAccountKey, encodedInfo)
} }
func (ethRelayer *EthereumRelayer) ImportChain33PrivateKey(passphrase, privateKeyStr string) error { func (ethRelayer *Relayer4Ethereum) ImportChain33PrivateKey(passphrase, privateKeyStr string) error {
var driver secp256k1.Driver var driver secp256k1.Driver
privateKeySli, err := chain33Common.FromHex(privateKeyStr) privateKeySli, err := chain33Common.FromHex(privateKeyStr)
if nil != err { if nil != err {
...@@ -181,7 +181,7 @@ func (ethRelayer *EthereumRelayer) ImportChain33PrivateKey(passphrase, privateKe ...@@ -181,7 +181,7 @@ func (ethRelayer *EthereumRelayer) ImportChain33PrivateKey(passphrase, privateKe
return ethRelayer.db.SetSync(chain33AccountKey, encodedInfo) return ethRelayer.db.SetSync(chain33AccountKey, encodedInfo)
} }
func (ethRelayer *EthereumRelayer) ImportEthValidatorPrivateKey(passphrase, privateKeyStr string) error { func (ethRelayer *Relayer4Ethereum) ImportEthValidatorPrivateKey(passphrase, privateKeyStr string) error {
privateKeySli, err := chain33Common.FromHex(privateKeyStr) privateKeySli, err := chain33Common.FromHex(privateKeyStr)
if nil != err { if nil != err {
return err return err
...@@ -285,7 +285,7 @@ func newKey(rand io.Reader) (*Key, error) { ...@@ -285,7 +285,7 @@ func newKey(rand io.Reader) (*Key, error) {
func newKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key { func newKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
id := uuid.NewRandom() id := uuid.NewRandom()
key := &Key{ key := &Key{
Id: id, ID: id,
Address: crypto.PubkeyToAddress(privateKeyECDSA.PublicKey), Address: crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
PrivateKey: privateKeyECDSA, PrivateKey: privateKeyECDSA,
} }
......
...@@ -26,8 +26,6 @@ var ( ...@@ -26,8 +26,6 @@ var (
ethTxEventPrefix = []byte("ethTxEventPrefix") ethTxEventPrefix = []byte("ethTxEventPrefix")
lastBridgeBankHeightProcPrefix = []byte("lastBridgeBankHeight") lastBridgeBankHeightProcPrefix = []byte("lastBridgeBankHeight")
bridgeBankTxProCnt = []byte("bridgeBankTxProCnt")
) )
func ethTxEventKey4Height(height uint64, index uint32) []byte { func ethTxEventKey4Height(height uint64, index uint32) []byte {
...@@ -42,11 +40,11 @@ func calcRelay2EthTxhash(txindex int64) []byte { ...@@ -42,11 +40,11 @@ func calcRelay2EthTxhash(txindex int64) []byte {
return []byte(fmt.Sprintf("%s-%012d", chain33ToEthTxHashPrefix, txindex)) return []byte(fmt.Sprintf("%s-%012d", chain33ToEthTxHashPrefix, txindex))
} }
func (ethRelayer *EthereumRelayer) setBridgeRegistryAddr(bridgeRegistryAddr string) error { func (ethRelayer *Relayer4Ethereum) setBridgeRegistryAddr(bridgeRegistryAddr string) error {
return ethRelayer.db.Set(bridgeRegistryAddrPrefix, []byte(bridgeRegistryAddr)) return ethRelayer.db.Set(bridgeRegistryAddrPrefix, []byte(bridgeRegistryAddr))
} }
func (ethRelayer *EthereumRelayer) getBridgeRegistryAddr() (string, error) { func (ethRelayer *Relayer4Ethereum) getBridgeRegistryAddr() (string, error) {
addr, err := ethRelayer.db.Get(bridgeRegistryAddrPrefix) addr, err := ethRelayer.db.Get(bridgeRegistryAddrPrefix)
if nil != err { if nil != err {
return "", err return "", err
...@@ -54,7 +52,7 @@ func (ethRelayer *EthereumRelayer) getBridgeRegistryAddr() (string, error) { ...@@ -54,7 +52,7 @@ func (ethRelayer *EthereumRelayer) getBridgeRegistryAddr() (string, error) {
return string(addr), nil return string(addr), nil
} }
func (ethRelayer *EthereumRelayer) updateTotalTxAmount2chain33(total int64) error { func (ethRelayer *Relayer4Ethereum) updateTotalTxAmount2chain33(total int64) error {
totalTx := &chain33Types.Int64{ totalTx := &chain33Types.Int64{
Data: atomic.LoadInt64(&ethRelayer.totalTx4Eth2Chain33), Data: atomic.LoadInt64(&ethRelayer.totalTx4Eth2Chain33),
} }
...@@ -62,12 +60,12 @@ func (ethRelayer *EthereumRelayer) updateTotalTxAmount2chain33(total int64) erro ...@@ -62,12 +60,12 @@ func (ethRelayer *EthereumRelayer) updateTotalTxAmount2chain33(total int64) erro
return ethRelayer.db.Set(eth2chain33TxTotalAmount, chain33Types.Encode(totalTx)) return ethRelayer.db.Set(eth2chain33TxTotalAmount, chain33Types.Encode(totalTx))
} }
func (ethRelayer *EthereumRelayer) setLastestRelay2Chain33Txhash(txhash string, txIndex int64) error { func (ethRelayer *Relayer4Ethereum) setLastestRelay2Chain33Txhash(txhash string, txIndex int64) error {
key := calcRelay2Chain33Txhash(txIndex) key := calcRelay2Chain33Txhash(txIndex)
return ethRelayer.db.Set(key, []byte(txhash)) return ethRelayer.db.Set(key, []byte(txhash))
} }
func (ethRelayer *EthereumRelayer) updateTotalTxAmount2Eth(total int64) error { func (ethRelayer *Relayer4Ethereum) updateTotalTxAmount2Eth(total int64) error {
totalTx := &chain33Types.Int64{ totalTx := &chain33Types.Int64{
Data: atomic.LoadInt64(&ethRelayer.totalTx4Chain33ToEth), Data: atomic.LoadInt64(&ethRelayer.totalTx4Chain33ToEth),
} }
...@@ -75,39 +73,39 @@ func (ethRelayer *EthereumRelayer) updateTotalTxAmount2Eth(total int64) error { ...@@ -75,39 +73,39 @@ func (ethRelayer *EthereumRelayer) updateTotalTxAmount2Eth(total int64) error {
return ethRelayer.db.Set(chain33ToEthTxTotalAmount, chain33Types.Encode(totalTx)) return ethRelayer.db.Set(chain33ToEthTxTotalAmount, chain33Types.Encode(totalTx))
} }
func (ethRelayer *EthereumRelayer) setLastestRelay2EthTxhash(txhash string, txIndex int64) error { func (ethRelayer *Relayer4Ethereum) setLastestRelay2EthTxhash(txhash string, txIndex int64) error {
key := calcRelay2EthTxhash(txIndex) key := calcRelay2EthTxhash(txIndex)
return ethRelayer.db.Set(key, []byte(txhash)) return ethRelayer.db.Set(key, []byte(txhash))
} }
func (ethRelayer *EthereumRelayer) queryTxhashes(prefix []byte) []string { func (ethRelayer *Relayer4Ethereum) queryTxhashes(prefix []byte) []string {
return utils.QueryTxhashes(prefix, ethRelayer.db) return utils.QueryTxhashes(prefix, ethRelayer.db)
} }
func (ethRelayer *EthereumRelayer) setHeight4chain33BridgeLogAt(height uint64) error { func (ethRelayer *Relayer4Ethereum) setHeight4chain33BridgeLogAt(height uint64) error {
return ethRelayer.setLogProcHeight(chain33BridgeLogProcessedAt, height) return ethRelayer.setLogProcHeight(chain33BridgeLogProcessedAt, height)
} }
func (ethRelayer *EthereumRelayer) getHeight4chain33BridgeLogAt() uint64 { func (ethRelayer *Relayer4Ethereum) getHeight4chain33BridgeLogAt() uint64 {
return ethRelayer.getLogProcHeight(chain33BridgeLogProcessedAt) return ethRelayer.getLogProcHeight(chain33BridgeLogProcessedAt)
} }
func (ethRelayer *EthereumRelayer) setHeight4BridgeBankLogAt(height uint64) error { func (ethRelayer *Relayer4Ethereum) setHeight4BridgeBankLogAt(height uint64) error {
return ethRelayer.setLogProcHeight(bridgeBankLogProcessedAt, height) return ethRelayer.setLogProcHeight(bridgeBankLogProcessedAt, height)
} }
func (ethRelayer *EthereumRelayer) getHeight4BridgeBankLogAt() uint64 { func (ethRelayer *Relayer4Ethereum) getHeight4BridgeBankLogAt() uint64 {
return ethRelayer.getLogProcHeight(bridgeBankLogProcessedAt) return ethRelayer.getLogProcHeight(bridgeBankLogProcessedAt)
} }
func (ethRelayer *EthereumRelayer) setLogProcHeight(key []byte, height uint64) error { func (ethRelayer *Relayer4Ethereum) setLogProcHeight(key []byte, height uint64) error {
data := &ebTypes.Uint64{ data := &ebTypes.Uint64{
Data: height, Data: height,
} }
return ethRelayer.db.Set(key, chain33Types.Encode(data)) return ethRelayer.db.Set(key, chain33Types.Encode(data))
} }
func (ethRelayer *EthereumRelayer) getLogProcHeight(key []byte) uint64 { func (ethRelayer *Relayer4Ethereum) getLogProcHeight(key []byte) uint64 {
value, err := ethRelayer.db.Get(key) value, err := ethRelayer.db.Get(key)
if nil != err { if nil != err {
return 0 return 0
...@@ -121,20 +119,17 @@ func (ethRelayer *EthereumRelayer) getLogProcHeight(key []byte) uint64 { ...@@ -121,20 +119,17 @@ func (ethRelayer *EthereumRelayer) getLogProcHeight(key []byte) uint64 {
} }
//保存处理过的交易 //保存处理过的交易
func (ethRelayer *EthereumRelayer) setTxProcessed(txhash []byte) error { func (ethRelayer *Relayer4Ethereum) setTxProcessed(txhash []byte) error {
return ethRelayer.db.Set(txhash, []byte("1")) return ethRelayer.db.Set(txhash, []byte("1"))
} }
//判断是否已经被处理,如果能够在数据库中找到该笔交易,则认为已经被处理 //判断是否已经被处理,如果能够在数据库中找到该笔交易,则认为已经被处理
func (ethRelayer *EthereumRelayer) checkTxProcessed(txhash []byte) bool { func (ethRelayer *Relayer4Ethereum) checkTxProcessed(txhash []byte) bool {
_, err := ethRelayer.db.Get(txhash) _, err := ethRelayer.db.Get(txhash)
if nil != err { return nil == err
return false
}
return true
} }
func (ethRelayer *EthereumRelayer) setEthTxEvent(vLog types.Log) error { func (ethRelayer *Relayer4Ethereum) setEthTxEvent(vLog types.Log) error {
key := ethTxEventKey4Height(vLog.BlockNumber, uint32(vLog.TxIndex)) key := ethTxEventKey4Height(vLog.BlockNumber, uint32(vLog.TxIndex))
value, err := json.Marshal(vLog) value, err := json.Marshal(vLog)
if nil != err { if nil != err {
...@@ -143,7 +138,7 @@ func (ethRelayer *EthereumRelayer) setEthTxEvent(vLog types.Log) error { ...@@ -143,7 +138,7 @@ func (ethRelayer *EthereumRelayer) setEthTxEvent(vLog types.Log) error {
return ethRelayer.db.Set(key, value) return ethRelayer.db.Set(key, value)
} }
func (ethRelayer *EthereumRelayer) getEthTxEvent(blockNumber uint64, txIndex uint32) (*types.Log, error) { func (ethRelayer *Relayer4Ethereum) getEthTxEvent(blockNumber uint64, txIndex uint32) (*types.Log, error) {
key := ethTxEventKey4Height(blockNumber, txIndex) key := ethTxEventKey4Height(blockNumber, txIndex)
data, err := ethRelayer.db.Get(key) data, err := ethRelayer.db.Get(key)
if nil != err { if nil != err {
...@@ -157,7 +152,7 @@ func (ethRelayer *EthereumRelayer) getEthTxEvent(blockNumber uint64, txIndex uin ...@@ -157,7 +152,7 @@ func (ethRelayer *EthereumRelayer) getEthTxEvent(blockNumber uint64, txIndex uin
return &log, nil return &log, nil
} }
func (ethRelayer *EthereumRelayer) getNextValidEthTxEventLogs(height uint64, index uint32, fetchCnt int32) ([]*types.Log, error) { func (ethRelayer *Relayer4Ethereum) getNextValidEthTxEventLogs(height uint64, index uint32, fetchCnt int32) ([]*types.Log, error) {
key := ethTxEventKey4Height(height, index) key := ethTxEventKey4Height(height, index)
helper := dbm.NewListHelper(ethRelayer.db) helper := dbm.NewListHelper(ethRelayer.db)
datas := helper.List(ethTxEventPrefix, key, fetchCnt, dbm.ListASC) datas := helper.List(ethTxEventPrefix, key, fetchCnt, dbm.ListASC)
...@@ -177,14 +172,14 @@ func (ethRelayer *EthereumRelayer) getNextValidEthTxEventLogs(height uint64, ind ...@@ -177,14 +172,14 @@ func (ethRelayer *EthereumRelayer) getNextValidEthTxEventLogs(height uint64, ind
return logs, nil return logs, nil
} }
func (ethRelayer *EthereumRelayer) setBridgeBankProcessedHeight(height uint64, index uint32) { func (ethRelayer *Relayer4Ethereum) setBridgeBankProcessedHeight(height uint64, index uint32) {
bytes := chain33Types.Encode(&ebTypes.EventLogIndex{ bytes := chain33Types.Encode(&ebTypes.EventLogIndex{
Height: height, Height: height,
Index: index}) Index: index})
_ = ethRelayer.db.Set(lastBridgeBankHeightProcPrefix, bytes) _ = ethRelayer.db.Set(lastBridgeBankHeightProcPrefix, bytes)
} }
func (ethRelayer *EthereumRelayer) getLastBridgeBankProcessedHeight() ebTypes.EventLogIndex { func (ethRelayer *Relayer4Ethereum) getLastBridgeBankProcessedHeight() ebTypes.EventLogIndex {
data, err := ethRelayer.db.Get(lastBridgeBankHeightProcPrefix) data, err := ethRelayer.db.Get(lastBridgeBankHeightProcPrefix)
if nil != err { if nil != err {
return ebTypes.EventLogIndex{} return ebTypes.EventLogIndex{}
...@@ -195,7 +190,7 @@ func (ethRelayer *EthereumRelayer) getLastBridgeBankProcessedHeight() ebTypes.Ev ...@@ -195,7 +190,7 @@ func (ethRelayer *EthereumRelayer) getLastBridgeBankProcessedHeight() ebTypes.Ev
} }
//构建一个引导查询使用的bridgeBankTx //构建一个引导查询使用的bridgeBankTx
func (ethRelayer *EthereumRelayer) initBridgeBankTx() { func (ethRelayer *Relayer4Ethereum) initBridgeBankTx() {
log, _ := ethRelayer.getEthTxEvent(0, 0) log, _ := ethRelayer.getEthTxEvent(0, 0)
if nil != log { if nil != log {
return return
......
...@@ -17,15 +17,9 @@ var ( ...@@ -17,15 +17,9 @@ var (
) )
const ( const (
keyAccount = "Account"
keyAddr = "Addr"
keyLabel = "Label"
keyTx = "Tx"
keyEncryptionFlag = "Encryption" keyEncryptionFlag = "Encryption"
keyEncryptionCompFlag = "EncryptionFlag" // 中间有一段时间运行了一个错误的密码版本,导致有部分用户信息发生错误,需要兼容下 keyEncryptionCompFlag = "EncryptionFlag" // 中间有一段时间运行了一个错误的密码版本,导致有部分用户信息发生错误,需要兼容下
keyPasswordHash = "PasswordHash" keyPasswordHash = "PasswordHash"
keyWalletSeed = "walletseed"
keyAirDropIndex = "AirDropIndex" //存储通过seed生成的空投地址信息
) )
// CalcEncryptionFlag 加密标志Key // CalcEncryptionFlag 加密标志Key
......
...@@ -84,7 +84,7 @@ func LoadInt64FromDB(key []byte, db dbm.DB) (int64, error) { ...@@ -84,7 +84,7 @@ func LoadInt64FromDB(key []byte, db dbm.DB) (int64, error) {
func QueryTxhashes(prefix []byte, db dbm.DB) []string { func QueryTxhashes(prefix []byte, db dbm.DB) []string {
kvdb := dbm.NewKVDB(db) kvdb := dbm.NewKVDB(db)
hashes, err := kvdb.List([]byte(prefix), nil, 10, 1) hashes, err := kvdb.List(prefix, nil, 10, 1)
if nil != err { if nil != err {
return nil return nil
} }
......
...@@ -170,14 +170,14 @@ func (x *suiteX2Ethereum) Test_4_Eth2Chain33() { ...@@ -170,14 +170,14 @@ func (x *suiteX2Ethereum) Test_4_Eth2Chain33() {
payload := &types2.Eth2Chain33{ payload := &types2.Eth2Chain33{
EthereumChainID: 0, EthereumChainID: 0,
BridgeContractAddress: bridgeContractAddress, BridgeContractAddress: bridgeContractAddress,
Nonce: 0, Nonce: 0,
IssuerDotSymbol: symbol, IssuerDotSymbol: symbol,
TokenContractAddress: tokenContractAddress, TokenContractAddress: tokenContractAddress,
EthereumSender: ethereumAddr, EthereumSender: ethereumAddr,
Chain33Receiver: chain33Receiver, Chain33Receiver: chain33Receiver,
ValidatorAddress: addValidator1, ValidatorAddress: addValidator1,
Amount: "10", Amount: "10",
ClaimType: int64(types2.LockClaimType), ClaimType: int64(types2.LockClaimType),
} }
receipt, err := x.action.procEth2Chain33_lock(payload) receipt, err := x.action.procEth2Chain33_lock(payload)
......
...@@ -92,18 +92,18 @@ func (a *action) procEth2Chain33_lock(ethBridgeClaim *x2eTy.Eth2Chain33) (*types ...@@ -92,18 +92,18 @@ func (a *action) procEth2Chain33_lock(ethBridgeClaim *x2eTy.Eth2Chain33) (*types
execlog := &types.ReceiptLog{Ty: x2eTy.TyEth2Chain33Log, Log: types.Encode(&x2eTy.ReceiptEth2Chain33{ execlog := &types.ReceiptLog{Ty: x2eTy.TyEth2Chain33Log, Log: types.Encode(&x2eTy.ReceiptEth2Chain33{
EthereumChainID: ethBridgeClaim.EthereumChainID, EthereumChainID: ethBridgeClaim.EthereumChainID,
BridgeContractAddress: ethBridgeClaim.BridgeContractAddress, BridgeContractAddress: ethBridgeClaim.BridgeContractAddress,
Nonce: ethBridgeClaim.Nonce, Nonce: ethBridgeClaim.Nonce,
IssuerDotSymbol: ethBridgeClaim.IssuerDotSymbol, IssuerDotSymbol: ethBridgeClaim.IssuerDotSymbol,
EthereumSender: ethBridgeClaim.EthereumSender, EthereumSender: ethBridgeClaim.EthereumSender,
Chain33Receiver: ethBridgeClaim.Chain33Receiver, Chain33Receiver: ethBridgeClaim.Chain33Receiver,
ValidatorAddress: ethBridgeClaim.ValidatorAddress, ValidatorAddress: ethBridgeClaim.ValidatorAddress,
Amount: ethBridgeClaim.Amount, Amount: ethBridgeClaim.Amount,
ClaimType: ethBridgeClaim.ClaimType, ClaimType: ethBridgeClaim.ClaimType,
XTxHash: a.txhash, XTxHash: a.txhash,
XHeight: uint64(a.height), XHeight: uint64(a.height),
ProphecyID: ID, ProphecyID: ID,
Decimals: ethBridgeClaim.Decimals, Decimals: ethBridgeClaim.Decimals,
TokenAddress: ethBridgeClaim.TokenContractAddress, TokenAddress: ethBridgeClaim.TokenContractAddress,
})} })}
receipt.Logs = append(receipt.Logs, execlog) receipt.Logs = append(receipt.Logs, execlog)
...@@ -251,18 +251,18 @@ func (a *action) procEth2Chain33_burn(withdrawEth *x2eTy.Eth2Chain33) (*types.Re ...@@ -251,18 +251,18 @@ func (a *action) procEth2Chain33_burn(withdrawEth *x2eTy.Eth2Chain33) (*types.Re
execlog := &types.ReceiptLog{Ty: x2eTy.TyWithdrawEthLog, Log: types.Encode(&x2eTy.ReceiptEth2Chain33{ execlog := &types.ReceiptLog{Ty: x2eTy.TyWithdrawEthLog, Log: types.Encode(&x2eTy.ReceiptEth2Chain33{
EthereumChainID: withdrawEth.EthereumChainID, EthereumChainID: withdrawEth.EthereumChainID,
BridgeContractAddress: withdrawEth.BridgeContractAddress, BridgeContractAddress: withdrawEth.BridgeContractAddress,
Nonce: withdrawEth.Nonce, Nonce: withdrawEth.Nonce,
IssuerDotSymbol: withdrawEth.IssuerDotSymbol, IssuerDotSymbol: withdrawEth.IssuerDotSymbol,
EthereumSender: withdrawEth.EthereumSender, EthereumSender: withdrawEth.EthereumSender,
Chain33Receiver: withdrawEth.Chain33Receiver, Chain33Receiver: withdrawEth.Chain33Receiver,
ValidatorAddress: withdrawEth.ValidatorAddress, ValidatorAddress: withdrawEth.ValidatorAddress,
Amount: withdrawEth.Amount, Amount: withdrawEth.Amount,
ClaimType: withdrawEth.ClaimType, ClaimType: withdrawEth.ClaimType,
XTxHash: a.txhash, XTxHash: a.txhash,
XHeight: uint64(a.height), XHeight: uint64(a.height),
ProphecyID: ID, ProphecyID: ID,
Decimals: withdrawEth.Decimals, Decimals: withdrawEth.Decimals,
TokenAddress: withdrawEth.TokenContractAddress, TokenAddress: withdrawEth.TokenContractAddress,
})} })}
receipt.Logs = append(receipt.Logs, execlog) receipt.Logs = append(receipt.Logs, execlog)
......
#!/usr/bin/env bash
set -x
CLI="/opt/src/github.com/33cn/plugin/build/chain33-cli"
EBCLI="/opt/src/github.com/33cn/plugin/plugin/dapp/x2Ethereum/build/ebcli_A"
ETHContractAddr="0x0000000000000000000000000000000000000000"
BTYContractAddr="0x40BFE5eD039A9a2Eb42ece2E2CA431bFa7Cf4c42"
Ethsender="0xcbfddc6ae318970ba3feeb0541624f95822e413a"
BtyReceiever="1BqP2vHkYNjSgdnTqm7pGbnphLhtEhuJFi"
BtyTokenContractAddr="0xbAf2646b8DaD8776fc74Bf4C8d59E6fB3720eddf"
Validator1="14KEKbYtKKQm4wMthSK9J4La4nAiidGozt"
Validator2="12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv"
Validator3="1BqP2vHkYNjSgdnTqm7pGbnphLhtEhuJFi"
# 测试流程
#
# bankAddr = 1BqP2vHkYNjSgdnTqm7pGbnphLhtEhuJFi
#
#
# 1.Exec_EthBridgeClaim, 测试chain33这端
#
#
#
block_wait() {
if [[ $# -lt 1 ]]; then
echo "wrong #block_wait parameter"
exit 1
fi
cur_height=$(${CLI} block last_header | jq ".height")
expect=$((cur_height + ${1}))
local count=0
while true; do
new_height=$(${CLI} block last_header | jq ".height")
if [[ ${new_height} -ge ${expect} ]]; then
break
fi
count=$((count + 1))
sleep 1
done
sleep 1
count=$((count + 1))
echo "wait new block $count s, cur height=$expect,old=$cur_height"
}
# check_tx(ty, hash)
# ty:交易执行结果
# 1:交易打包
# 2:交易执行成功
# hash:交易hash
check_tx() {
if [[ $# -lt 2 ]]; then
echo "wrong check_tx parameters"
exit 1
fi
ty=$(${CLI} tx query -s ${2} | jq .receipt.ty)
if [[ ${ty} != ${1} ]]; then
echo "check tx error, hash is ${2}"
exit 1
fi
}
check_Number() {
if [[ $# -lt 2 ]]; then
echo "wrong check_Number parameters"
exit 1
fi
if [[ ${1} != ${2} ]]; then
echo "error Number, expect ${1}, get ${2}"
exit 1
fi
}
# SetConsensusThreshold
hash=$(${CLI} send x2ethereum setconsensus -p 80 -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv)
#block_wait 2
check_tx 2 ${hash}
# query ConsensusThreshold
nowConsensus=$(${CLI} send x2ethereum query consensus -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .nowConsensusThreshold | sed 's/\"//g')
check_Number 80 ${nowConsensus}
# add a validator
hash=$(${CLI} send x2ethereum add -a ${Validator3} -p 7 -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv)
#block_wait 2
check_tx 2 ${hash}
# query Validators
validators=$(${CLI} send x2ethereum query validators -v ${Validator3} -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .validators | sed 's/\"//g')
totalPower=$(${CLI} send x2ethereum query validators -v ${Validator3} -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .totalPower | sed 's/\"//g')
check_Number 7 ${totalPower}
# add a validator again
hash=$(${CLI} send x2ethereum add -a ${Validator2} -p 6 -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv)
#block_wait 2
check_tx 2 ${hash}
# query Validators
validators=$(${CLI} send x2ethereum query validators -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .validators | sed 's/\"//g')
totalPower=$(${CLI} send x2ethereum query validators -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .totalPower | sed 's/\"//g')
check_Number 13 ${totalPower}
# remove a validator
hash=$(${CLI} send x2ethereum remove -a ${Validator2} -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv)
#block_wait 2
check_tx 2 ${hash}
# query Validators
validators=$(${CLI} send x2ethereum query validators -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .validators | sed 's/\"//g')
totalPower=$(${CLI} send x2ethereum query validators -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .totalPower | sed 's/\"//g')
check_Number 7 ${totalPower}
# add a validator again
hash=$(${CLI} send x2ethereum add -a ${Validator2} -p 6 -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv)
#block_wait 2
check_tx 2 ${hash}
# query Validators
validators=$(${CLI} send x2ethereum query validators -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .validators | sed 's/\"//g')
totalPower=$(${CLI} send x2ethereum query validators -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .totalPower | sed 's/\"//g')
check_Number 13 ${totalPower}
# add a validator
hash=$(${CLI} send x2ethereum add -a ${Validator1} -p 87 -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv)
#block_wait 2
check_tx 2 ${hash}
# query Validators
validators=$(${CLI} send x2ethereum query validators -v 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .validators | sed 's/\"//g')
totalPower=$(${CLI} send x2ethereum query validators -v 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .totalPower | sed 's/\"//g')
check_Number 6 ${totalPower}
totalPower=$(${CLI} send x2ethereum query totalpower -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv | jq .totalPower | sed 's/\"//g')
check_Number 100 ${totalPower}
##############################################################
######################## 测试交易 #############################
##############################################################
# chain33 -> ethereum
# send bty to mavl-x2ethereum-bty-12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv
${CLI} send coins send_exec -e x2ethereum -a 200 -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv
# send a chain33eth tx,在chain33侧lock 5个bty
hash=$(${CLI} send x2ethereum lock --amount 5 -e x2ethereum -t bty -r ${Ethsender} -s 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv -q ${BtyTokenContractAddr} -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv)
#block_wait 4
check_tx 2 ${hash}
#在以太坊侧burn掉1个bty
hash=$(${EBCLI} relayer ethereum burn -m 1 -t ${BtyTokenContractAddr} -r ${BtyReceiever} -k 772db14fc5ae829b155e1eda09431a0b566833f2de3b50b2d35625542b3ae52f | jq .msg | sed 's/\"//g')
# ethereum -> chain33,在以太坊侧lock 0.1 eth
hash=$(${EBCLI} relayer ethereum lock -m 0.1 -r ${BtyReceiever} -k 772db14fc5ae829b155e1eda09431a0b566833f2de3b50b2d35625542b3ae52f)
#在chain33 burn 0.1eth
hash=$(${CLI} send x2ethereum burn --amount 0.1 -e x2ethereum -t eth -r ${Ethsender} -s ${BtyReceiever} -q ${ETHContractAddr} -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv)
#block_wait 4
check_tx 2 ${hash}
# ethereum -> chain33
hash=$(${EBCLI} relayer ethereum lock -m 0.1 -t ${BtyTokenContractAddr} -r ${BtyReceiever} -k 772db14fc5ae829b155e1eda09431a0b566833f2de3b50b2d35625542b3ae52f)
hash=$(${CLI} send x2ethereum burn --amount 0.1 -t ${BtyTokenContractAddr} -e x2ethereum -t eth -r ${Ethsender} -s ${BtyReceiever} -q ${ETHContractAddr} -k 12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv)
#block_wait 4
check_tx 2 ${hash}
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