github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/x/evm/watcher/types.go (about)

     1  package watcher
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/binary"
     6  	"encoding/json"
     7  	"fmt"
     8  	"math/big"
     9  	"strconv"
    10  	"time"
    11  
    12  	"github.com/ethereum/go-ethereum/common"
    13  	"github.com/ethereum/go-ethereum/common/hexutil"
    14  	ethtypes "github.com/ethereum/go-ethereum/core/types"
    15  	app "github.com/fibonacci-chain/fbc/app/types"
    16  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/codec"
    17  	sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types"
    18  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/auth"
    19  	abci "github.com/fibonacci-chain/fbc/libs/tendermint/abci/types"
    20  	ctypes "github.com/fibonacci-chain/fbc/libs/tendermint/rpc/core/types"
    21  	"github.com/fibonacci-chain/fbc/x/evm/types"
    22  	"github.com/gogo/protobuf/proto"
    23  	"github.com/pkg/errors"
    24  	"github.com/status-im/keycard-go/hexutils"
    25  	"github.com/tendermint/go-amino"
    26  )
    27  
    28  var (
    29  	prefixTx           = []byte{0x01}
    30  	prefixBlock        = []byte{0x02}
    31  	prefixReceipt      = []byte{0x03}
    32  	prefixCode         = []byte{0x04}
    33  	prefixBlockInfo    = []byte{0x05}
    34  	prefixLatestHeight = []byte{0x06}
    35  	prefixAccount      = []byte{0x07}
    36  	PrefixState        = []byte{0x08}
    37  	prefixCodeHash     = []byte{0x09}
    38  	prefixParams       = []byte{0x10}
    39  	prefixWhiteList    = []byte{0x11}
    40  	prefixBlackList    = []byte{0x12}
    41  	prefixRpcDb        = []byte{0x13}
    42  	prefixTxResponse   = []byte{0x14}
    43  	prefixStdTxHash    = []byte{0x15}
    44  
    45  	KeyLatestHeight = "LatestHeight"
    46  
    47  	TransactionSuccess = uint32(1)
    48  	TransactionFailed  = uint32(0)
    49  
    50  	keyLatestBlockHeight = append(prefixLatestHeight, KeyLatestHeight...)
    51  )
    52  
    53  const (
    54  	TypeOthers    = uint32(1)
    55  	TypeState     = uint32(2)
    56  	TypeDelete    = uint32(3)
    57  	TypeEvmParams = uint32(4)
    58  
    59  	EthReceipt  = uint64(0)
    60  	StdResponse = uint64(1)
    61  )
    62  
    63  type WatchMessage = sdk.WatchMessage
    64  
    65  type Batch struct {
    66  	Key       []byte `json:"key"`
    67  	Value     []byte `json:"value"`
    68  	TypeValue uint32 `json:"type_value"`
    69  }
    70  
    71  // MarshalToAmino marshal batch data to amino bytes
    72  func (b *Batch) MarshalToAmino(cdc *amino.Codec) ([]byte, error) {
    73  	var buf bytes.Buffer
    74  	var err error
    75  	fieldKeysType := [3]byte{1<<3 | 2, 2<<3 | 2, 3 << 3}
    76  	for pos := 1; pos <= 3; pos++ {
    77  		switch pos {
    78  		case 1:
    79  			if len(b.Key) == 0 {
    80  				break
    81  			}
    82  			err = buf.WriteByte(fieldKeysType[pos-1])
    83  			if err != nil {
    84  				return nil, err
    85  			}
    86  			err = amino.EncodeByteSliceToBuffer(&buf, b.Key)
    87  			if err != nil {
    88  				return nil, err
    89  			}
    90  
    91  		case 2:
    92  			if len(b.Value) == 0 {
    93  				break
    94  			}
    95  			err = buf.WriteByte(fieldKeysType[pos-1])
    96  			if err != nil {
    97  				return nil, err
    98  			}
    99  			err = amino.EncodeByteSliceToBuffer(&buf, b.Value)
   100  			if err != nil {
   101  				return nil, err
   102  			}
   103  		case 3:
   104  			if b.TypeValue == 0 {
   105  				break
   106  			}
   107  			err := buf.WriteByte(fieldKeysType[pos-1])
   108  			if err != nil {
   109  				return nil, err
   110  			}
   111  			err = amino.EncodeUvarintToBuffer(&buf, uint64(b.TypeValue))
   112  			if err != nil {
   113  				return nil, err
   114  			}
   115  
   116  		default:
   117  			panic("unreachable")
   118  		}
   119  	}
   120  	return buf.Bytes(), nil
   121  }
   122  
   123  // UnmarshalFromAmino unmarshal amino bytes to this object
   124  func (b *Batch) UnmarshalFromAmino(cdc *amino.Codec, data []byte) error {
   125  	var dataLen uint64 = 0
   126  	var subData []byte
   127  
   128  	for {
   129  		data = data[dataLen:]
   130  		if len(data) == 0 {
   131  			break
   132  		}
   133  		// decode field key type and data position
   134  		pos, pbType, err := amino.ParseProtoPosAndTypeMustOneByte(data[0])
   135  		if err != nil {
   136  			return err
   137  		}
   138  		data = data[1:]
   139  
   140  		// choose sub-data to parse data
   141  		if pbType == amino.Typ3_ByteLength {
   142  			var n int
   143  			dataLen, n, _ = amino.DecodeUvarint(data)
   144  
   145  			data = data[n:]
   146  			if len(data) < int(dataLen) {
   147  				return errors.New("not enough data")
   148  			}
   149  			subData = data[:dataLen]
   150  		}
   151  
   152  		switch pos {
   153  		case 1:
   154  			b.Key = make([]byte, len(subData))
   155  			copy(b.Key, subData)
   156  
   157  		case 2:
   158  			b.Value = make([]byte, len(subData))
   159  			copy(b.Value, subData)
   160  
   161  		case 3:
   162  			tv, n, err := amino.DecodeUvarint(data)
   163  			if err != nil {
   164  				return err
   165  			}
   166  			b.TypeValue = uint32(tv)
   167  			dataLen = uint64(n)
   168  
   169  		default:
   170  			return fmt.Errorf("unexpect feild num %d", pos)
   171  		}
   172  	}
   173  	return nil
   174  }
   175  
   176  type WatchData struct {
   177  	DirtyAccount  []*sdk.AccAddress `json:"dirty_account"`
   178  	Batches       []*Batch          `json:"batches"`
   179  	DelayEraseKey [][]byte          `json:"delay_erase_key"`
   180  	BloomData     []*types.KV       `json:"bloom_data"`
   181  	DirtyList     [][]byte          `json:"dirty_list"`
   182  }
   183  
   184  func (w *WatchData) Size() int {
   185  	return len(w.DirtyAccount) + len(w.Batches) + len(w.DelayEraseKey) + len(w.BloomData) + len(w.DirtyList)
   186  }
   187  
   188  // MarshalToAmino marshal to amino bytes
   189  func (w *WatchData) MarshalToAmino(cdc *amino.Codec) ([]byte, error) {
   190  	var buf bytes.Buffer
   191  	var err error
   192  	fieldKeysType := [5]byte{1<<3 | 2, 2<<3 | 2, 3<<3 | 2, 4<<3 | 2, 5<<3 | 2}
   193  	for pos := 1; pos <= 5; pos++ {
   194  		switch pos {
   195  		case 1:
   196  			if len(w.DirtyAccount) == 0 {
   197  				break
   198  			}
   199  			for i := 0; i < len(w.DirtyAccount); i++ {
   200  				err := buf.WriteByte(fieldKeysType[pos-1])
   201  				if err != nil {
   202  					return nil, err
   203  				}
   204  				var data []byte
   205  				if w.DirtyAccount[i] != nil {
   206  					data = w.DirtyAccount[i].Bytes()
   207  				}
   208  				err = amino.EncodeByteSliceToBuffer(&buf, data)
   209  				if err != nil {
   210  					return nil, err
   211  				}
   212  
   213  			}
   214  		case 2:
   215  			if len(w.Batches) == 0 {
   216  				break
   217  			}
   218  			for i := 0; i < len(w.Batches); i++ {
   219  				err = buf.WriteByte(fieldKeysType[pos-1])
   220  				if err != nil {
   221  					return nil, err
   222  				}
   223  
   224  				var data []byte
   225  				if w.Batches[i] != nil {
   226  					data, err = w.Batches[i].MarshalToAmino(cdc)
   227  					if err != nil {
   228  						return nil, err
   229  					}
   230  				}
   231  				err = amino.EncodeByteSliceToBuffer(&buf, data)
   232  				if err != nil {
   233  					return nil, err
   234  				}
   235  			}
   236  		case 3:
   237  			if len(w.DelayEraseKey) == 0 {
   238  				break
   239  			}
   240  			// encode a slice one by one
   241  			for i := 0; i < len(w.DelayEraseKey); i++ {
   242  				err = buf.WriteByte(fieldKeysType[pos-1])
   243  				if err != nil {
   244  					return nil, err
   245  				}
   246  				err = amino.EncodeByteSliceToBuffer(&buf, w.DelayEraseKey[i])
   247  				if err != nil {
   248  					return nil, err
   249  				}
   250  			}
   251  		case 4:
   252  			if len(w.BloomData) == 0 {
   253  				break
   254  			}
   255  			for i := 0; i < len(w.BloomData); i++ {
   256  				err = buf.WriteByte(fieldKeysType[pos-1])
   257  				if err != nil {
   258  					return nil, err
   259  				}
   260  				var data []byte
   261  				if w.BloomData[i] != nil {
   262  					data, err = w.BloomData[i].MarshalToAmino(cdc)
   263  					if err != nil {
   264  						return nil, err
   265  					}
   266  				}
   267  				err = amino.EncodeByteSliceToBuffer(&buf, data)
   268  				if err != nil {
   269  					return nil, err
   270  				}
   271  			}
   272  		case 5:
   273  			if len(w.DirtyList) == 0 {
   274  				break
   275  			}
   276  			// encode a slice one by one
   277  			for i := 0; i < len(w.DirtyList); i++ {
   278  				err = buf.WriteByte(fieldKeysType[pos-1])
   279  				if err != nil {
   280  					return nil, err
   281  				}
   282  				err = amino.EncodeByteSliceToBuffer(&buf, w.DirtyList[i])
   283  				if err != nil {
   284  					return nil, err
   285  				}
   286  			}
   287  		default:
   288  			panic("unreachable")
   289  		}
   290  	}
   291  	return buf.Bytes(), nil
   292  }
   293  
   294  // UnmarshalFromAmino unmarshal from amino bytes
   295  func (w *WatchData) UnmarshalFromAmino(cdc *amino.Codec, data []byte) error {
   296  	var dataLen uint64 = 0
   297  	var subData []byte
   298  
   299  	for {
   300  		data = data[dataLen:]
   301  		if len(data) == 0 {
   302  			break
   303  		}
   304  		pos, pbType, err := amino.ParseProtoPosAndTypeMustOneByte(data[0])
   305  		if err != nil {
   306  			return err
   307  		}
   308  		data = data[1:]
   309  
   310  		if pbType == amino.Typ3_ByteLength {
   311  			var n int
   312  			dataLen, n, _ = amino.DecodeUvarint(data)
   313  
   314  			data = data[n:]
   315  			if len(data) < int(dataLen) {
   316  				return errors.New("not enough data")
   317  			}
   318  			subData = data[:dataLen]
   319  		}
   320  
   321  		switch pos {
   322  		case 1:
   323  			// copy subData to new memory and use it as sdk.AccAddress type
   324  			var acc *sdk.AccAddress = nil
   325  			if len(subData) != 0 {
   326  				accAddr := make([]byte, len(subData))
   327  				copy(accAddr, subData)
   328  				accByte := sdk.AccAddress(accAddr)
   329  				acc = &accByte
   330  			}
   331  			w.DirtyAccount = append(w.DirtyAccount, acc)
   332  
   333  		case 2:
   334  			var bat *Batch = nil
   335  			if len(subData) != 0 {
   336  				bat = &Batch{}
   337  				err := bat.UnmarshalFromAmino(cdc, subData)
   338  				if err != nil {
   339  					return err
   340  				}
   341  			}
   342  			w.Batches = append(w.Batches, bat)
   343  
   344  		case 3:
   345  			var delayEraseKey []byte
   346  			if len(subData) != 0 {
   347  				delayEraseKey = make([]byte, len(subData))
   348  				copy(delayEraseKey, subData)
   349  			}
   350  			w.DelayEraseKey = append(w.DelayEraseKey, delayEraseKey)
   351  
   352  		case 4:
   353  			var kv *types.KV = nil
   354  			if len(subData) != 0 {
   355  				kv = &types.KV{}
   356  				err := kv.UnmarshalFromAmino(nil, subData)
   357  				if err != nil {
   358  					return err
   359  				}
   360  			}
   361  			w.BloomData = append(w.BloomData, kv)
   362  
   363  		case 5:
   364  			var dirtyList []byte
   365  			if len(subData) != 0 {
   366  				dirtyList = make([]byte, len(subData))
   367  				copy(dirtyList, subData)
   368  			}
   369  			w.DirtyList = append(w.DirtyList, dirtyList)
   370  
   371  		default:
   372  			return fmt.Errorf("unexpect feild num %d", pos)
   373  		}
   374  	}
   375  	return nil
   376  }
   377  
   378  type MsgCode struct {
   379  	Key  []byte
   380  	Code string
   381  }
   382  
   383  func (m MsgCode) GetType() uint32 {
   384  	return TypeOthers
   385  }
   386  
   387  type CodeInfo struct {
   388  	Height uint64 `json:"height"`
   389  	Code   string `json:"code"`
   390  }
   391  
   392  func NewMsgCode(contractAddr common.Address, code []byte, height uint64) *MsgCode {
   393  	codeInfo := CodeInfo{
   394  		Height: height,
   395  		Code:   hexutils.BytesToHex(code),
   396  	}
   397  	jsCode, e := json.Marshal(codeInfo)
   398  	if e != nil {
   399  		return nil
   400  	}
   401  	return &MsgCode{
   402  		Key:  contractAddr.Bytes(),
   403  		Code: string(jsCode),
   404  	}
   405  }
   406  
   407  func (m MsgCode) GetKey() []byte {
   408  	return append(prefixCode, m.Key...)
   409  }
   410  
   411  func (m MsgCode) GetValue() string {
   412  	return m.Code
   413  }
   414  
   415  type MsgCodeByHash struct {
   416  	Key  []byte
   417  	Code string
   418  }
   419  
   420  func (m MsgCodeByHash) GetType() uint32 {
   421  	return TypeOthers
   422  }
   423  
   424  func NewMsgCodeByHash(hash []byte, code []byte) *MsgCodeByHash {
   425  	return &MsgCodeByHash{
   426  		Key:  hash,
   427  		Code: string(code),
   428  	}
   429  }
   430  
   431  func (m MsgCodeByHash) GetKey() []byte {
   432  	return append(prefixCodeHash, m.Key...)
   433  }
   434  
   435  func (m MsgCodeByHash) GetValue() string {
   436  	return m.Code
   437  }
   438  
   439  type MsgTransactionReceipt struct {
   440  	*TransactionReceipt
   441  	txHash []byte
   442  }
   443  
   444  func (m MsgTransactionReceipt) GetType() uint32 {
   445  	return TypeOthers
   446  }
   447  
   448  // type WrappedResponseWithCodec
   449  type WrappedResponseWithCodec struct {
   450  	Response sdk.TxResponse
   451  	Codec    *codec.Codec `json:"-"`
   452  }
   453  
   454  type TransactionResult struct {
   455  	TxType   hexutil.Uint64            `json:"type"`
   456  	EthTx    *Transaction              `json:"ethTx"`
   457  	EthTxLog string                    `json:"ethTxLog"`
   458  	Receipt  *TransactionReceipt       `json:"receipt"`
   459  	Response *WrappedResponseWithCodec `json:"response"`
   460  }
   461  
   462  func (wr *WrappedResponseWithCodec) MarshalJSON() ([]byte, error) {
   463  	if wr.Codec != nil {
   464  		return wr.Codec.MarshalJSON(wr.Response)
   465  	}
   466  
   467  	return json.Marshal(wr.Response)
   468  }
   469  
   470  type TransactionReceipt struct {
   471  	Status                hexutil.Uint64  `json:"status"`
   472  	CumulativeGasUsed     hexutil.Uint64  `json:"cumulativeGasUsed"`
   473  	LogsBloom             ethtypes.Bloom  `json:"logsBloom"`
   474  	Logs                  []*ethtypes.Log `json:"logs"`
   475  	originTransactionHash common.Hash
   476  	TransactionHash       string          `json:"transactionHash"`
   477  	ContractAddress       *common.Address `json:"contractAddress"`
   478  	GasUsed               hexutil.Uint64  `json:"gasUsed"`
   479  	originBlockHash       common.Hash
   480  	BlockHash             string         `json:"blockHash"`
   481  	BlockNumber           hexutil.Uint64 `json:"blockNumber"`
   482  	TransactionIndex      hexutil.Uint64 `json:"transactionIndex"`
   483  	tx                    *types.MsgEthereumTx
   484  	From                  string          `json:"from"`
   485  	To                    *common.Address `json:"to"`
   486  }
   487  
   488  func (tr *TransactionReceipt) GetValue() string {
   489  	tr.TransactionHash = tr.GetHash()
   490  	tr.BlockHash = tr.GetBlockHash()
   491  	tr.From = tr.GetFrom()
   492  	tr.To = tr.tx.To()
   493  	//contract address will be set to 0x0000000000000000000000000000000000000000 if contract deploy failed
   494  	if tr.ContractAddress != nil && types.EthAddressStringer(*tr.ContractAddress).String() == "0x0000000000000000000000000000000000000000" {
   495  		//set to nil to keep sync with ethereum rpc
   496  		tr.ContractAddress = nil
   497  	}
   498  	protoReceipt := receiptToProto(tr)
   499  	buf, err := proto.Marshal(protoReceipt)
   500  	if err != nil {
   501  		panic("cant happen")
   502  	}
   503  
   504  	return string(buf)
   505  }
   506  
   507  func (tr *TransactionReceipt) GetHash() string {
   508  	return types.EthHashStringer(tr.originTransactionHash).String()
   509  }
   510  
   511  func (tr *TransactionReceipt) GetBlockHash() string {
   512  	return types.EthHashStringer(tr.originBlockHash).String()
   513  }
   514  
   515  func (tr *TransactionReceipt) GetFrom() string {
   516  	return types.EthAddressStringer(common.BytesToAddress(tr.tx.AccountAddress().Bytes())).String()
   517  }
   518  
   519  func (tr *TransactionReceipt) GetTo() *common.Address {
   520  	return tr.tx.To()
   521  }
   522  
   523  func newTransactionReceipt(status uint32, tx *types.MsgEthereumTx, txHash, blockHash common.Hash, txIndex, height uint64, data *types.ResultData, cumulativeGas, GasUsed uint64) TransactionReceipt {
   524  	tr := TransactionReceipt{
   525  		Status:                hexutil.Uint64(status),
   526  		CumulativeGasUsed:     hexutil.Uint64(cumulativeGas),
   527  		LogsBloom:             data.Bloom,
   528  		Logs:                  data.Logs,
   529  		originTransactionHash: txHash,
   530  		ContractAddress:       &data.ContractAddress,
   531  		GasUsed:               hexutil.Uint64(GasUsed),
   532  		originBlockHash:       blockHash,
   533  		BlockNumber:           hexutil.Uint64(height),
   534  		TransactionIndex:      hexutil.Uint64(txIndex),
   535  		tx:                    tx,
   536  	}
   537  	return tr
   538  }
   539  
   540  func NewMsgTransactionReceipt(tr TransactionReceipt, txHash common.Hash) *MsgTransactionReceipt {
   541  	return &MsgTransactionReceipt{txHash: txHash.Bytes(), TransactionReceipt: &tr}
   542  }
   543  
   544  func (m MsgTransactionReceipt) GetKey() []byte {
   545  	return append(prefixReceipt, m.txHash...)
   546  }
   547  
   548  type MsgBlock struct {
   549  	blockHash []byte
   550  	block     string
   551  }
   552  
   553  func (m MsgBlock) GetType() uint32 {
   554  	return TypeOthers
   555  }
   556  
   557  // A BlockNonce is a 64-bit hash which proves (combined with the
   558  // mix-hash) that a sufficient amount of computation has been carried
   559  // out on a block.
   560  type BlockNonce [8]byte
   561  
   562  // EncodeNonce converts the given integer to a block nonce.
   563  func EncodeNonce(i uint64) BlockNonce {
   564  	var n BlockNonce
   565  	binary.BigEndian.PutUint64(n[:], i)
   566  	return n
   567  }
   568  
   569  // Uint64 returns the integer value of a block nonce.
   570  func (n BlockNonce) Uint64() uint64 {
   571  	return binary.BigEndian.Uint64(n[:])
   572  }
   573  
   574  // MarshalText encodes n as a hex string with 0x prefix.
   575  func (n BlockNonce) MarshalText() ([]byte, error) {
   576  	return hexutil.Bytes(n[:]).MarshalText()
   577  }
   578  
   579  // UnmarshalText implements encoding.TextUnmarshaler.
   580  func (n *BlockNonce) UnmarshalText(input []byte) error {
   581  	return hexutil.UnmarshalFixedText("BlockNonce", input, n[:])
   582  }
   583  
   584  // Block represents a transaction returned to RPC clients.
   585  type Block struct {
   586  	Number           hexutil.Uint64 `json:"number"`
   587  	Hash             common.Hash    `json:"hash"`
   588  	ParentHash       common.Hash    `json:"parentHash"`
   589  	Nonce            BlockNonce     `json:"nonce"`
   590  	UncleHash        common.Hash    `json:"sha3Uncles"`
   591  	LogsBloom        ethtypes.Bloom `json:"logsBloom"`
   592  	TransactionsRoot common.Hash    `json:"transactionsRoot"`
   593  	StateRoot        common.Hash    `json:"stateRoot"`
   594  	Miner            common.Address `json:"miner"`
   595  	MixHash          common.Hash    `json:"mixHash"`
   596  	Difficulty       hexutil.Uint64 `json:"difficulty"`
   597  	TotalDifficulty  hexutil.Uint64 `json:"totalDifficulty"`
   598  	ExtraData        hexutil.Bytes  `json:"extraData"`
   599  	Size             hexutil.Uint64 `json:"size"`
   600  	GasLimit         hexutil.Uint64 `json:"gasLimit"`
   601  	GasUsed          *hexutil.Big   `json:"gasUsed"`
   602  	Timestamp        hexutil.Uint64 `json:"timestamp"`
   603  	Uncles           []common.Hash  `json:"uncles"`
   604  	ReceiptsRoot     common.Hash    `json:"receiptsRoot"`
   605  	Transactions     interface{}    `json:"transactions"`
   606  }
   607  
   608  // Transaction represents a transaction returned to RPC clients.
   609  type Transaction struct {
   610  	BlockHash         *common.Hash    `json:"blockHash"`
   611  	BlockNumber       *hexutil.Big    `json:"blockNumber"`
   612  	From              common.Address  `json:"from"`
   613  	Gas               hexutil.Uint64  `json:"gas"`
   614  	GasPrice          *hexutil.Big    `json:"gasPrice"`
   615  	Hash              common.Hash     `json:"hash"`
   616  	Input             hexutil.Bytes   `json:"input"`
   617  	Nonce             hexutil.Uint64  `json:"nonce"`
   618  	To                *common.Address `json:"to"`
   619  	TransactionIndex  *hexutil.Uint64 `json:"transactionIndex"`
   620  	Value             *hexutil.Big    `json:"value"`
   621  	V                 *hexutil.Big    `json:"v"`
   622  	R                 *hexutil.Big    `json:"r"`
   623  	S                 *hexutil.Big    `json:"s"`
   624  	tx                *types.MsgEthereumTx
   625  	originBlockHash   *common.Hash
   626  	originBlockNumber uint64
   627  	originIndex       uint64
   628  }
   629  
   630  func (tr *Transaction) GetValue() string {
   631  	// Verify signature and retrieve sender address
   632  	err := tr.tx.VerifySig(tr.tx.ChainID(), int64(tr.originBlockNumber))
   633  	if err != nil {
   634  		return ""
   635  	}
   636  
   637  	tr.From = common.HexToAddress(tr.tx.GetFrom())
   638  	tr.Gas = hexutil.Uint64(tr.tx.Data.GasLimit)
   639  	tr.GasPrice = (*hexutil.Big)(tr.tx.Data.Price)
   640  	tr.Input = tr.tx.Data.Payload
   641  	tr.Nonce = hexutil.Uint64(tr.tx.Data.AccountNonce)
   642  	tr.To = tr.tx.To()
   643  	tr.Value = (*hexutil.Big)(tr.tx.Data.Amount)
   644  	tr.V = (*hexutil.Big)(tr.tx.Data.V)
   645  	tr.R = (*hexutil.Big)(tr.tx.Data.R)
   646  	tr.S = (*hexutil.Big)(tr.tx.Data.S)
   647  
   648  	if *tr.originBlockHash != (common.Hash{}) {
   649  		tr.BlockHash = tr.originBlockHash
   650  		tr.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(tr.originBlockNumber))
   651  		tr.TransactionIndex = (*hexutil.Uint64)(&tr.originIndex)
   652  	}
   653  	protoTransaction := transactionToProto(tr)
   654  	buf, err := proto.Marshal(protoTransaction)
   655  	if err != nil {
   656  		panic("cant happen")
   657  	}
   658  
   659  	return string(buf)
   660  }
   661  
   662  func newBlock(height uint64, blockBloom ethtypes.Bloom, blockHash common.Hash, header abci.Header, gasLimit uint64, gasUsed *big.Int, txs interface{}) Block {
   663  	timestamp := header.Time.Unix()
   664  	if timestamp < 0 {
   665  		timestamp = time.Now().Unix()
   666  	}
   667  	transactionsRoot := ethtypes.EmptyRootHash
   668  	if len(header.DataHash) > 0 {
   669  		transactionsRoot = common.BytesToHash(header.DataHash)
   670  	}
   671  	return Block{
   672  		Number:           hexutil.Uint64(height),
   673  		Hash:             blockHash,
   674  		ParentHash:       common.BytesToHash(header.LastBlockId.Hash),
   675  		Nonce:            BlockNonce{},
   676  		UncleHash:        common.Hash{},
   677  		LogsBloom:        blockBloom,
   678  		TransactionsRoot: transactionsRoot,
   679  		StateRoot:        common.BytesToHash(header.AppHash),
   680  		Miner:            common.BytesToAddress(header.ProposerAddress),
   681  		MixHash:          common.Hash{},
   682  		Difficulty:       0,
   683  		TotalDifficulty:  0,
   684  		ExtraData:        nil,
   685  		Size:             hexutil.Uint64(header.Size()),
   686  		GasLimit:         hexutil.Uint64(gasLimit),
   687  		GasUsed:          (*hexutil.Big)(gasUsed),
   688  		Timestamp:        hexutil.Uint64(timestamp),
   689  		Uncles:           []common.Hash{},
   690  		ReceiptsRoot:     common.Hash{},
   691  		Transactions:     txs,
   692  	}
   693  }
   694  
   695  func NewMsgBlock(b Block) *MsgBlock {
   696  	jsBlock, e := json.Marshal(b)
   697  	if e != nil {
   698  		return nil
   699  	}
   700  	return &MsgBlock{blockHash: b.Hash.Bytes(), block: string(jsBlock)}
   701  }
   702  
   703  func (m MsgBlock) GetKey() []byte {
   704  	return append(prefixBlock, m.blockHash...)
   705  }
   706  
   707  func (m MsgBlock) GetValue() string {
   708  	return m.block
   709  }
   710  
   711  type MsgBlockInfo struct {
   712  	height []byte
   713  	hash   string
   714  }
   715  
   716  func (b MsgBlockInfo) GetType() uint32 {
   717  	return TypeOthers
   718  }
   719  
   720  func NewMsgBlockInfo(height uint64, blockHash common.Hash) *MsgBlockInfo {
   721  	return &MsgBlockInfo{
   722  		height: []byte(strconv.Itoa(int(height))),
   723  		hash:   blockHash.String(),
   724  	}
   725  }
   726  
   727  func (b MsgBlockInfo) GetKey() []byte {
   728  	return append(prefixBlockInfo, b.height...)
   729  }
   730  
   731  func (b MsgBlockInfo) GetValue() string {
   732  	return b.hash
   733  }
   734  
   735  type MsgLatestHeight struct {
   736  	height string
   737  }
   738  
   739  func (b MsgLatestHeight) GetType() uint32 {
   740  	return TypeOthers
   741  }
   742  
   743  func NewMsgLatestHeight(height uint64) *MsgLatestHeight {
   744  	return &MsgLatestHeight{
   745  		height: strconv.Itoa(int(height)),
   746  	}
   747  }
   748  
   749  func (b MsgLatestHeight) GetKey() []byte {
   750  	return append(prefixLatestHeight, KeyLatestHeight...)
   751  }
   752  
   753  func (b MsgLatestHeight) GetValue() string {
   754  	return b.height
   755  }
   756  
   757  type MsgAccount struct {
   758  	account *app.EthAccount
   759  }
   760  
   761  func (msgAccount *MsgAccount) GetType() uint32 {
   762  	return TypeOthers
   763  }
   764  
   765  func NewMsgAccount(acc auth.Account) *MsgAccount {
   766  	var msg *MsgAccount
   767  	switch v := acc.(type) {
   768  	case app.EthAccount:
   769  		msg = &MsgAccount{account: &v}
   770  	case *app.EthAccount:
   771  		msg = &MsgAccount{account: v}
   772  	default:
   773  		msg = nil
   774  	}
   775  	return msg
   776  }
   777  
   778  func GetMsgAccountKey(addr []byte) []byte {
   779  	return append(prefixAccount, addr...)
   780  }
   781  
   782  func (msgAccount *MsgAccount) GetKey() []byte {
   783  	return GetMsgAccountKey(msgAccount.account.Address.Bytes())
   784  }
   785  
   786  func (msgAccount *MsgAccount) GetValue() string {
   787  	data, err := EncodeAccount(msgAccount.account)
   788  	if err != nil {
   789  		panic(err)
   790  	}
   791  	return string(data)
   792  }
   793  
   794  type DelAccMsg struct {
   795  	addr []byte
   796  }
   797  
   798  func NewDelAccMsg(acc auth.Account) *DelAccMsg {
   799  	return &DelAccMsg{
   800  		addr: acc.GetAddress().Bytes(),
   801  	}
   802  }
   803  
   804  func (delAcc *DelAccMsg) GetType() uint32 {
   805  	return TypeDelete
   806  }
   807  
   808  func (delAcc *DelAccMsg) GetKey() []byte {
   809  	return GetMsgAccountKey(delAcc.addr)
   810  }
   811  
   812  func (delAcc *DelAccMsg) GetValue() string {
   813  	return ""
   814  }
   815  
   816  type MsgState struct {
   817  	addr  common.Address
   818  	key   []byte
   819  	value []byte
   820  }
   821  
   822  func (msgState *MsgState) GetType() uint32 {
   823  	return TypeState
   824  }
   825  
   826  func NewMsgState(addr common.Address, key, value []byte) *MsgState {
   827  	return &MsgState{
   828  		addr:  addr,
   829  		key:   key,
   830  		value: value,
   831  	}
   832  }
   833  
   834  func GetMsgStateKey(addr common.Address, key []byte) []byte {
   835  	prefix := addr.Bytes()
   836  	compositeKey := make([]byte, len(prefix)+len(key))
   837  
   838  	copy(compositeKey, prefix)
   839  	copy(compositeKey[len(prefix):], key)
   840  
   841  	return append(PrefixState, compositeKey...)
   842  }
   843  
   844  func (msgState *MsgState) GetKey() []byte {
   845  	return GetMsgStateKey(msgState.addr, msgState.key)
   846  }
   847  
   848  func (msgState *MsgState) GetValue() string {
   849  	return string(msgState.value)
   850  }
   851  
   852  type MsgParams struct {
   853  	types.Params
   854  }
   855  
   856  func (msgParams *MsgParams) GetType() uint32 {
   857  	return TypeEvmParams
   858  }
   859  
   860  func NewMsgParams(params types.Params) *MsgParams {
   861  	return &MsgParams{
   862  		params,
   863  	}
   864  }
   865  
   866  func (msgParams *MsgParams) GetKey() []byte {
   867  	return prefixParams
   868  }
   869  
   870  func (msgParams *MsgParams) GetValue() string {
   871  	jsonValue, err := json.Marshal(msgParams)
   872  	if err != nil {
   873  		panic(err)
   874  	}
   875  	return string(jsonValue)
   876  }
   877  
   878  type MsgContractBlockedListItem struct {
   879  	addr sdk.AccAddress
   880  }
   881  
   882  func (msgItem *MsgContractBlockedListItem) GetType() uint32 {
   883  	return TypeOthers
   884  }
   885  
   886  func NewMsgContractBlockedListItem(addr sdk.AccAddress) *MsgContractBlockedListItem {
   887  	return &MsgContractBlockedListItem{
   888  		addr: addr,
   889  	}
   890  }
   891  
   892  func (msgItem *MsgContractBlockedListItem) GetKey() []byte {
   893  	return append(prefixBlackList, msgItem.addr.Bytes()...)
   894  }
   895  
   896  func (msgItem *MsgContractBlockedListItem) GetValue() string {
   897  	return ""
   898  }
   899  
   900  type MsgDelContractBlockedListItem struct {
   901  	addr sdk.AccAddress
   902  }
   903  
   904  func (msgItem *MsgDelContractBlockedListItem) GetType() uint32 {
   905  	return TypeDelete
   906  }
   907  
   908  func NewMsgDelContractBlockedListItem(addr sdk.AccAddress) *MsgDelContractBlockedListItem {
   909  	return &MsgDelContractBlockedListItem{
   910  		addr: addr,
   911  	}
   912  }
   913  
   914  func (msgItem *MsgDelContractBlockedListItem) GetKey() []byte {
   915  	return append(prefixBlackList, msgItem.addr.Bytes()...)
   916  }
   917  
   918  func (msgItem *MsgDelContractBlockedListItem) GetValue() string {
   919  	return ""
   920  }
   921  
   922  type MsgContractDeploymentWhitelistItem struct {
   923  	addr sdk.AccAddress
   924  }
   925  
   926  func (msgItem *MsgContractDeploymentWhitelistItem) GetType() uint32 {
   927  	return TypeOthers
   928  }
   929  
   930  func NewMsgContractDeploymentWhitelistItem(addr sdk.AccAddress) *MsgContractDeploymentWhitelistItem {
   931  	return &MsgContractDeploymentWhitelistItem{
   932  		addr: addr,
   933  	}
   934  }
   935  
   936  func (msgItem *MsgContractDeploymentWhitelistItem) GetKey() []byte {
   937  	return append(prefixWhiteList, msgItem.addr.Bytes()...)
   938  }
   939  
   940  func (msgItem *MsgContractDeploymentWhitelistItem) GetValue() string {
   941  	return ""
   942  }
   943  
   944  type MsgDelContractDeploymentWhitelistItem struct {
   945  	addr sdk.AccAddress
   946  }
   947  
   948  func (msgItem *MsgDelContractDeploymentWhitelistItem) GetType() uint32 {
   949  	return TypeDelete
   950  }
   951  
   952  func NewMsgDelContractDeploymentWhitelistItem(addr sdk.AccAddress) *MsgDelContractDeploymentWhitelistItem {
   953  	return &MsgDelContractDeploymentWhitelistItem{
   954  		addr: addr,
   955  	}
   956  }
   957  
   958  func (msgItem *MsgDelContractDeploymentWhitelistItem) GetKey() []byte {
   959  	return append(prefixWhiteList, msgItem.addr.Bytes()...)
   960  }
   961  
   962  func (msgItem *MsgDelContractDeploymentWhitelistItem) GetValue() string {
   963  	return ""
   964  }
   965  
   966  type MsgContractMethodBlockedListItem struct {
   967  	addr    sdk.AccAddress
   968  	methods []byte
   969  }
   970  
   971  func (msgItem *MsgContractMethodBlockedListItem) GetType() uint32 {
   972  	return TypeOthers
   973  }
   974  
   975  func NewMsgContractMethodBlockedListItem(addr sdk.AccAddress, methods []byte) *MsgContractMethodBlockedListItem {
   976  	return &MsgContractMethodBlockedListItem{
   977  		addr:    addr,
   978  		methods: methods,
   979  	}
   980  }
   981  
   982  func (msgItem *MsgContractMethodBlockedListItem) GetKey() []byte {
   983  	return append(prefixBlackList, msgItem.addr.Bytes()...)
   984  }
   985  
   986  func (msgItem *MsgContractMethodBlockedListItem) GetValue() string {
   987  	return string(msgItem.methods)
   988  }
   989  
   990  type MsgStdTransactionResponse struct {
   991  	txResponse string
   992  	txHash     []byte
   993  }
   994  
   995  func (tr *MsgStdTransactionResponse) GetType() uint32 {
   996  	return TypeOthers
   997  }
   998  
   999  func (tr *MsgStdTransactionResponse) GetValue() string {
  1000  	return tr.txResponse
  1001  }
  1002  
  1003  func (tr *MsgStdTransactionResponse) GetKey() []byte {
  1004  	return append(prefixTxResponse, tr.txHash...)
  1005  }
  1006  
  1007  type TransactionResponse struct {
  1008  	*ctypes.ResultTx
  1009  	Timestamp time.Time
  1010  }
  1011  
  1012  func NewStdTransactionResponse(tr *ctypes.ResultTx, timestamp time.Time, txHash common.Hash) *MsgStdTransactionResponse {
  1013  	tResponse := TransactionResponse{
  1014  		ResultTx:  tr,
  1015  		Timestamp: timestamp,
  1016  	}
  1017  	jsResponse, err := json.Marshal(tResponse)
  1018  
  1019  	if err != nil {
  1020  		return nil
  1021  	}
  1022  	return &MsgStdTransactionResponse{txResponse: string(jsResponse), txHash: txHash.Bytes()}
  1023  }
  1024  
  1025  type MsgBlockStdTxHash struct {
  1026  	blockHash []byte
  1027  	stdTxHash string
  1028  }
  1029  
  1030  func (m *MsgBlockStdTxHash) GetType() uint32 {
  1031  	return TypeOthers
  1032  }
  1033  
  1034  func (m *MsgBlockStdTxHash) GetValue() string {
  1035  	return m.stdTxHash
  1036  }
  1037  
  1038  func (m *MsgBlockStdTxHash) GetKey() []byte {
  1039  	return append(prefixStdTxHash, m.blockHash...)
  1040  }
  1041  
  1042  func NewMsgBlockStdTxHash(stdTxHash []common.Hash, blockHash common.Hash) *MsgBlockStdTxHash {
  1043  	jsonValue, err := json.Marshal(stdTxHash)
  1044  	if err != nil {
  1045  		panic(err)
  1046  	}
  1047  
  1048  	return &MsgBlockStdTxHash{
  1049  		stdTxHash: string(jsonValue),
  1050  		blockHash: blockHash.Bytes(),
  1051  	}
  1052  }