github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/internal/intapi/api.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package intapi
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"github.com/intfoundation/intchain/accounts/abi"
    25  	"github.com/intfoundation/intchain/consensus"
    26  	"github.com/intfoundation/intchain/consensus/ipbft/epoch"
    27  	"github.com/intfoundation/intchain/core/state"
    28  	"math/big"
    29  	"strings"
    30  	"time"
    31  
    32  	goCrypto "github.com/intfoundation/go-crypto"
    33  	"github.com/intfoundation/intchain/accounts"
    34  	"github.com/intfoundation/intchain/accounts/keystore"
    35  	"github.com/intfoundation/intchain/common"
    36  	"github.com/intfoundation/intchain/common/hexutil"
    37  	"github.com/intfoundation/intchain/common/math"
    38  	"github.com/intfoundation/intchain/core"
    39  	"github.com/intfoundation/intchain/core/rawdb"
    40  	"github.com/intfoundation/intchain/core/types"
    41  	"github.com/intfoundation/intchain/core/vm"
    42  	"github.com/intfoundation/intchain/crypto"
    43  	intAbi "github.com/intfoundation/intchain/intabi/abi"
    44  	"github.com/intfoundation/intchain/log"
    45  	"github.com/intfoundation/intchain/p2p"
    46  	"github.com/intfoundation/intchain/params"
    47  	"github.com/intfoundation/intchain/rlp"
    48  	"github.com/intfoundation/intchain/rpc"
    49  	"github.com/syndtr/goleveldb/leveldb"
    50  )
    51  
    52  const (
    53  	defaultGasPrice          = 5000 * params.GWei
    54  	updateValidatorThreshold = 25
    55  )
    56  
    57  var (
    58  	minimumRegisterAmount = math.MustParseBig256("1000000000000000000000000") //  1000000 * e18
    59  
    60  	//maxCandidateNumber = 1000
    61  
    62  	maxDelegationAddresses = 1000
    63  
    64  	maxEditValidatorLength = 100
    65  )
    66  
    67  // PublicINTChainAPI provides an API to access intchain related information.
    68  // It offers only methods that operate on public data that is freely available to anyone.
    69  type PublicINTChainAPI struct {
    70  	b Backend
    71  }
    72  
    73  // NewPublicINTChainAPI creates a new intchain protocol API.
    74  func NewPublicINTChainAPI(b Backend) *PublicINTChainAPI {
    75  	return &PublicINTChainAPI{b}
    76  }
    77  
    78  // GasPrice returns a suggestion for a gas price.
    79  func (s *PublicINTChainAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
    80  	price, err := s.b.SuggestPrice(ctx)
    81  	return (*hexutil.Big)(price), err
    82  }
    83  
    84  // ProtocolVersion returns the current intchain protocol version this node supports
    85  func (s *PublicINTChainAPI) ProtocolVersion() hexutil.Uint {
    86  	return hexutil.Uint(s.b.ProtocolVersion())
    87  }
    88  
    89  // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
    90  // yet received the latest block headers from its pears. In case it is synchronizing:
    91  // - startingBlock: block number this node started to synchronise from
    92  // - currentBlock:  block number this node is currently importing
    93  // - highestBlock:  block number of the highest block header this node has received from peers
    94  // - pulledStates:  number of state entries processed until now
    95  // - knownStates:   number of known state entries that still need to be pulled
    96  func (s *PublicINTChainAPI) Syncing() (interface{}, error) {
    97  	progress := s.b.Downloader().Progress()
    98  
    99  	// Return not syncing if the synchronisation already completed
   100  	if progress.CurrentBlock >= progress.HighestBlock {
   101  		return false, nil
   102  	}
   103  	// Otherwise gather the block sync stats
   104  	return map[string]interface{}{
   105  		"startingBlock": hexutil.Uint64(progress.StartingBlock),
   106  		"currentBlock":  hexutil.Uint64(progress.CurrentBlock),
   107  		"highestBlock":  hexutil.Uint64(progress.HighestBlock),
   108  		"pulledStates":  hexutil.Uint64(progress.PulledStates),
   109  		"knownStates":   hexutil.Uint64(progress.KnownStates),
   110  	}, nil
   111  }
   112  
   113  // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
   114  type PublicTxPoolAPI struct {
   115  	b Backend
   116  }
   117  
   118  // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
   119  func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI {
   120  	return &PublicTxPoolAPI{b}
   121  }
   122  
   123  // Content returns the transactions contained within the transaction pool.
   124  func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
   125  	content := map[string]map[string]map[string]*RPCTransaction{
   126  		"pending": make(map[string]map[string]*RPCTransaction),
   127  		"queued":  make(map[string]map[string]*RPCTransaction),
   128  	}
   129  	pending, queue := s.b.TxPoolContent()
   130  
   131  	// Flatten the pending transactions
   132  	for account, txs := range pending {
   133  		dump := make(map[string]*RPCTransaction)
   134  		for _, tx := range txs {
   135  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
   136  		}
   137  		content["pending"][account.Hex()] = dump
   138  	}
   139  	// Flatten the queued transactions
   140  	for account, txs := range queue {
   141  		dump := make(map[string]*RPCTransaction)
   142  		for _, tx := range txs {
   143  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
   144  		}
   145  		content["queued"][account.Hex()] = dump
   146  	}
   147  	return content
   148  }
   149  
   150  // Status returns the number of pending and queued transaction in the pool.
   151  func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint {
   152  	pending, queue := s.b.Stats()
   153  	return map[string]hexutil.Uint{
   154  		"pending": hexutil.Uint(pending),
   155  		"queued":  hexutil.Uint(queue),
   156  	}
   157  }
   158  
   159  // Inspect retrieves the content of the transaction pool and flattens it into an
   160  // easily inspectable list.
   161  func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string {
   162  	content := map[string]map[string]map[string]string{
   163  		"pending": make(map[string]map[string]string),
   164  		"queued":  make(map[string]map[string]string),
   165  	}
   166  	pending, queue := s.b.TxPoolContent()
   167  
   168  	// Define a formatter to flatten a transaction into a string
   169  	var format = func(tx *types.Transaction) string {
   170  		if to := tx.To(); to != nil {
   171  			return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
   172  		}
   173  		return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice())
   174  	}
   175  	// Flatten the pending transactions
   176  	for account, txs := range pending {
   177  		dump := make(map[string]string)
   178  		for _, tx := range txs {
   179  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   180  		}
   181  		content["pending"][account.Hex()] = dump
   182  	}
   183  	// Flatten the queued transactions
   184  	for account, txs := range queue {
   185  		dump := make(map[string]string)
   186  		for _, tx := range txs {
   187  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   188  		}
   189  		content["queued"][account.Hex()] = dump
   190  	}
   191  	return content
   192  }
   193  
   194  // PublicAccountAPI provides an API to access accounts managed by this node.
   195  // It offers only methods that can retrieve accounts.
   196  type PublicAccountAPI struct {
   197  	am *accounts.Manager
   198  }
   199  
   200  // NewPublicAccountAPI creates a new PublicAccountAPI.
   201  func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI {
   202  	return &PublicAccountAPI{am: am}
   203  }
   204  
   205  // Accounts returns the collection of accounts this node manages
   206  func (s *PublicAccountAPI) Accounts() []common.Address {
   207  	addresses := make([]common.Address, 0) // return [] instead of nil if empty
   208  	for _, wallet := range s.am.Wallets() {
   209  		for _, account := range wallet.Accounts() {
   210  			addresses = append(addresses, account.Address)
   211  		}
   212  	}
   213  	return addresses
   214  }
   215  
   216  // PrivateAccountAPI provides an API to access accounts managed by this node.
   217  // It offers methods to create, (un)lock en list accounts. Some methods accept
   218  // passwords and are therefore considered private by default.
   219  type PrivateAccountAPI struct {
   220  	am        *accounts.Manager
   221  	nonceLock *AddrLocker
   222  	b         Backend
   223  }
   224  
   225  // NewPrivateAccountAPI create a new PrivateAccountAPI.
   226  func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI {
   227  	return &PrivateAccountAPI{
   228  		am:        b.AccountManager(),
   229  		nonceLock: nonceLock,
   230  		b:         b,
   231  	}
   232  }
   233  
   234  // ListAccounts will return a list of addresses for accounts this node manages.
   235  func (s *PrivateAccountAPI) ListAccounts() []common.Address {
   236  	addresses := make([]common.Address, 0) // return [] instead of nil if empty
   237  	for _, wallet := range s.am.Wallets() {
   238  		for _, account := range wallet.Accounts() {
   239  			addresses = append(addresses, account.Address)
   240  		}
   241  	}
   242  	return addresses
   243  }
   244  
   245  // rawWallet is a JSON representation of an accounts.Wallet interface, with its
   246  // data contents extracted into plain fields.
   247  type rawWallet struct {
   248  	URL      string             `json:"url"`
   249  	Status   string             `json:"status"`
   250  	Failure  string             `json:"failure,omitempty"`
   251  	Accounts []accounts.Account `json:"accounts,omitempty"`
   252  }
   253  
   254  // ListWallets will return a list of wallets this node manages.
   255  func (s *PrivateAccountAPI) ListWallets() []rawWallet {
   256  	wallets := make([]rawWallet, 0) // return [] instead of nil if empty
   257  	for _, wallet := range s.am.Wallets() {
   258  		status, failure := wallet.Status()
   259  
   260  		raw := rawWallet{
   261  			URL:      wallet.URL().String(),
   262  			Status:   status,
   263  			Accounts: wallet.Accounts(),
   264  		}
   265  		if failure != nil {
   266  			raw.Failure = failure.Error()
   267  		}
   268  		wallets = append(wallets, raw)
   269  	}
   270  	return wallets
   271  }
   272  
   273  // OpenWallet initiates a hardware wallet opening procedure, establishing a USB
   274  // connection and attempting to authenticate via the provided passphrase. Note,
   275  // the method may return an extra challenge requiring a second open (e.g. the
   276  // Trezor PIN matrix challenge).
   277  func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error {
   278  	wallet, err := s.am.Wallet(url)
   279  	if err != nil {
   280  		return err
   281  	}
   282  	pass := ""
   283  	if passphrase != nil {
   284  		pass = *passphrase
   285  	}
   286  	return wallet.Open(pass)
   287  }
   288  
   289  // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
   290  // it for later reuse.
   291  func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
   292  	wallet, err := s.am.Wallet(url)
   293  	if err != nil {
   294  		return accounts.Account{}, err
   295  	}
   296  	derivPath, err := accounts.ParseDerivationPath(path)
   297  	if err != nil {
   298  		return accounts.Account{}, err
   299  	}
   300  	if pin == nil {
   301  		pin = new(bool)
   302  	}
   303  	return wallet.Derive(derivPath, *pin)
   304  }
   305  
   306  // NewAccount will create a new account and returns the address for the new account.
   307  func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
   308  	acc, err := fetchKeystore(s.am).NewAccount(password)
   309  	if err == nil {
   310  		return acc.Address, nil
   311  	}
   312  	return common.Address{}, err
   313  }
   314  
   315  // fetchKeystore retrives the encrypted keystore from the account manager.
   316  func fetchKeystore(am *accounts.Manager) *keystore.KeyStore {
   317  	return am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   318  }
   319  
   320  // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
   321  // encrypting it with the passphrase.
   322  func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
   323  	key, err := crypto.HexToECDSA(privkey)
   324  	if err != nil {
   325  		return common.Address{}, err
   326  	}
   327  	acc, err := fetchKeystore(s.am).ImportECDSA(key, password)
   328  	return acc.Address, err
   329  }
   330  
   331  // UnlockAccount will unlock the account associated with the given address with
   332  // the given password for duration seconds. If duration is nil it will use a
   333  // default of 300 seconds. It returns an indication if the account was unlocked.
   334  func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration *uint64) (bool, error) {
   335  	const max = uint64(time.Duration(math.MaxInt64) / time.Second)
   336  	var d time.Duration
   337  	if duration == nil {
   338  		d = 300 * time.Second
   339  	} else if *duration > max {
   340  		return false, errors.New("unlock duration too large")
   341  	} else {
   342  		d = time.Duration(*duration) * time.Second
   343  	}
   344  	err := fetchKeystore(s.am).TimedUnlock(accounts.Account{Address: addr}, password, d)
   345  	return err == nil, err
   346  }
   347  
   348  // LockAccount will lock the account associated with the given address when it's unlocked.
   349  func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
   350  	return fetchKeystore(s.am).Lock(addr) == nil
   351  }
   352  
   353  // signTransactions sets defaults and signs the given transaction
   354  // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
   355  // and release it after the transaction has been submitted to the tx pool
   356  func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args SendTxArgs, passwd string) (*types.Transaction, error) {
   357  	// Look up the wallet containing the requested signer
   358  	account := accounts.Account{Address: args.From}
   359  	wallet, err := s.am.Find(account)
   360  	if err != nil {
   361  		return nil, err
   362  	}
   363  	// Set some sanity defaults and terminate on failure
   364  	if err := args.setDefaults(ctx, s.b); err != nil {
   365  		return nil, err
   366  	}
   367  	// Assemble the transaction and sign with the wallet
   368  	tx := args.toTransaction()
   369  
   370  	var chainID *big.Int
   371  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
   372  		chainID = config.ChainId
   373  	}
   374  	return wallet.SignTxWithPassphrase(account, passwd, tx, chainID)
   375  }
   376  
   377  // SendTransaction will create a transaction from the given arguments and
   378  // tries to sign it with the key associated with args.To. If the given passwd isn't
   379  // able to decrypt the key it fails.
   380  func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   381  	fmt.Printf("transaction args PrivateAccountAPI args %v\n", args)
   382  	if args.Nonce == nil {
   383  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
   384  		// the same nonce to multiple accounts.
   385  		s.nonceLock.LockAddr(args.From)
   386  		defer s.nonceLock.UnlockAddr(args.From)
   387  	}
   388  	signed, err := s.signTransaction(ctx, args, passwd)
   389  	if err != nil {
   390  		return common.Hash{}, err
   391  	}
   392  	return submitTransaction(ctx, s.b, signed)
   393  }
   394  
   395  // SignTransaction will create a transaction from the given arguments and
   396  // tries to sign it with the key associated with args.To. If the given passwd isn't
   397  // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
   398  // to other nodes
   399  func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) {
   400  	// No need to obtain the noncelock mutex, since we won't be sending this
   401  	// tx into the transaction pool, but right back to the user
   402  	if args.Gas == nil {
   403  		return nil, fmt.Errorf("gas not specified")
   404  	}
   405  	if args.GasPrice == nil {
   406  		return nil, fmt.Errorf("gasPrice not specified")
   407  	}
   408  	if args.Nonce == nil {
   409  		return nil, fmt.Errorf("nonce not specified")
   410  	}
   411  	signed, err := s.signTransaction(ctx, args, passwd)
   412  	if err != nil {
   413  		return nil, err
   414  	}
   415  	data, err := rlp.EncodeToBytes(signed)
   416  	if err != nil {
   417  		return nil, err
   418  	}
   419  	return &SignTransactionResult{data, signed}, nil
   420  }
   421  
   422  // signHash is a helper function that calculates a hash for the given message that can be
   423  // safely used to calculate a signature from.
   424  //
   425  // The hash is calulcated as
   426  //   keccak256("\x19INT Chain Signed Message:\n"${message length}${message}).
   427  //
   428  // This gives context to the signed message and prevents signing of transactions.
   429  func signHash(data []byte) []byte {
   430  	msg := fmt.Sprintf("\x19INT Chain Signed Message:\n%d%s", len(data), data)
   431  	return crypto.Keccak256([]byte(msg))
   432  }
   433  
   434  // Sign calculates an INT Chain ECDSA signature for:
   435  // keccack256("\x19INT Chain Signed Message:\n" + len(message) + message))
   436  //
   437  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
   438  // where the V value will be 27 or 28 for legacy reasons.
   439  //
   440  // The key used to calculate the signature is decrypted with the given password.
   441  //
   442  // https://github.com/intfoundation/intchain/wiki/Management-APIs#personal_sign
   443  func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
   444  	// Look up the wallet containing the requested signer
   445  	account := accounts.Account{Address: addr}
   446  
   447  	wallet, err := s.b.AccountManager().Find(account)
   448  	if err != nil {
   449  		return nil, err
   450  	}
   451  	// Assemble sign the data with the wallet
   452  	signature, err := wallet.SignHashWithPassphrase(account, passwd, signHash(data))
   453  	if err != nil {
   454  		return nil, err
   455  	}
   456  	signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
   457  	return signature, nil
   458  }
   459  
   460  // EcRecover returns the address for the account that was used to create the signature.
   461  // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
   462  // the address of:
   463  // hash = keccak256("\x19INT Chain Signed Message:\n"${message length}${message})
   464  // addr = ecrecover(hash, signature)
   465  //
   466  // Note, the signature must conform to the secp256k1 curve R, S and V values, where
   467  // the V value must be 27 or 28 for legacy reasons.
   468  //
   469  // https://github.com/intfoundation/intchain/wiki/Management-APIs#personal_ecRecover
   470  func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
   471  	if len(sig) != 65 {
   472  		return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
   473  	}
   474  	if sig[64] != 27 && sig[64] != 28 {
   475  		return common.Address{}, fmt.Errorf("invalid INT Chain signature (V is not 27 or 28)")
   476  	}
   477  	sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
   478  
   479  	rpk, err := crypto.SigToPub(signHash(data), sig)
   480  	if err != nil {
   481  		return common.Address{}, err
   482  	}
   483  	return crypto.PubkeyToAddress(*rpk), nil
   484  }
   485  
   486  // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
   487  // and will be removed in the future. It primary goal is to give clients time to update.
   488  func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   489  	return s.SendTransaction(ctx, args, passwd)
   490  }
   491  
   492  // PublicBlockChainAPI provides an API to access the INT blockchain.
   493  // It offers only methods that operate on public data that is freely available to anyone.
   494  type PublicBlockChainAPI struct {
   495  	b Backend
   496  }
   497  
   498  // NewPublicBlockChainAPI creates a new INT blockchain API.
   499  func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
   500  	return &PublicBlockChainAPI{b}
   501  }
   502  
   503  // ChainId returns the chainID value for transaction replay protection.
   504  func (s *PublicBlockChainAPI) ChainId() *hexutil.Big {
   505  	return (*hexutil.Big)(s.b.ChainConfig().ChainId)
   506  }
   507  
   508  // BlockNumber returns the block number of the chain head.
   509  func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
   510  	header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
   511  	return hexutil.Uint64(header.Number.Uint64())
   512  }
   513  
   514  // GetBalance returns the amount of wei for the given address in the state of the
   515  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   516  // block numbers are also allowed.
   517  func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Big, error) {
   518  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   519  	if state == nil || err != nil {
   520  		return nil, err
   521  	}
   522  	return (*hexutil.Big)(state.GetBalance(address)), state.Error()
   523  }
   524  
   525  //func (s *PublicBlockChainAPI) GetCandidateSetByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) ([]common.Address, error) {
   526  //	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   527  //	if state == nil || err != nil {
   528  //		return nil, err
   529  //	}
   530  //
   531  //	var candidateList = make([]common.Address, 0)
   532  //
   533  //	for addr := range state.GetCandidateSet() {
   534  //		candidateList = append(candidateList, addr)
   535  //	}
   536  //
   537  //	return candidateList, nil
   538  //}
   539  
   540  type ProxiedDetail struct {
   541  	ProxiedBalance        *hexutil.Big `json:"proxiedBalance"`
   542  	DepositProxiedBalance *hexutil.Big `json:"depositProxiedBalance"`
   543  	PendingRefundBalance  *hexutil.Big `json:"pendingRefundBalance"`
   544  }
   545  
   546  // GetBalanceDetail returns the amount of wei for the given address in the state of the
   547  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   548  // block numbers are also allowed.
   549  func (s *PublicBlockChainAPI) GetBalanceDetail(ctx context.Context, address common.Address, blockNr rpc.BlockNumber, fullDetail bool) (map[string]interface{}, error) {
   550  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   551  	if state == nil || err != nil {
   552  		return nil, err
   553  	}
   554  
   555  	fields := map[string]interface{}{
   556  		"balance":               (*hexutil.Big)(state.GetBalance(address)),
   557  		"depositBalance":        (*hexutil.Big)(state.GetDepositBalance(address)),
   558  		"delegateBalance":       (*hexutil.Big)(state.GetDelegateBalance(address)),
   559  		"proxiedBalance":        (*hexutil.Big)(state.GetTotalProxiedBalance(address)),
   560  		"depositProxiedBalance": (*hexutil.Big)(state.GetTotalDepositProxiedBalance(address)),
   561  		"pendingRefundBalance":  (*hexutil.Big)(state.GetTotalPendingRefundBalance(address)),
   562  		"rewardBalance":         (*hexutil.Big)(state.GetTotalRewardBalance(address)),
   563  	}
   564  
   565  	if fullDetail {
   566  		proxiedDetail := make(map[common.Address]ProxiedDetail)
   567  		state.ForEachProxied(address, func(key common.Address, proxiedBalance, depositProxiedBalance, pendingRefundBalance *big.Int) bool {
   568  			proxiedDetail[key] = ProxiedDetail{
   569  				ProxiedBalance:        (*hexutil.Big)(proxiedBalance),
   570  				DepositProxiedBalance: (*hexutil.Big)(depositProxiedBalance),
   571  				PendingRefundBalance:  (*hexutil.Big)(pendingRefundBalance),
   572  			}
   573  			return true
   574  		})
   575  
   576  		fields["proxiedDetail"] = proxiedDetail
   577  
   578  		rewardDetail := make(map[common.Address]*hexutil.Big)
   579  		state.ForEachReward(address, func(key common.Address, rewardBalance *big.Int) bool {
   580  			rewardDetail[key] = (*hexutil.Big)(rewardBalance)
   581  			return true
   582  		})
   583  
   584  		fields["rewardDetail"] = rewardDetail
   585  	}
   586  	return fields, state.Error()
   587  }
   588  
   589  type EpochLabel uint64
   590  
   591  func (e EpochLabel) MarshalText() ([]byte, error) {
   592  	output := fmt.Sprintf("epoch_%d", e)
   593  	return []byte(output), nil
   594  }
   595  
   596  // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
   597  // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   598  func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
   599  	block, err := s.b.BlockByNumber(ctx, blockNr)
   600  	if block != nil {
   601  		response, err := s.rpcOutputBlock(block, true, fullTx)
   602  		if err == nil && blockNr == rpc.PendingBlockNumber {
   603  			// Pending blocks need to nil out a few fields
   604  			for _, field := range []string{"hash", "nonce", "miner"} {
   605  				response[field] = nil
   606  			}
   607  		}
   608  		return response, err
   609  	}
   610  	return nil, err
   611  }
   612  
   613  // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
   614  // detail, otherwise only the transaction hash is returned.
   615  func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
   616  	block, err := s.b.GetBlock(ctx, blockHash)
   617  	if block != nil {
   618  		return s.rpcOutputBlock(block, true, fullTx)
   619  	}
   620  	return nil, err
   621  }
   622  
   623  // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   624  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   625  func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
   626  	block, err := s.b.BlockByNumber(ctx, blockNr)
   627  	if block != nil {
   628  		uncles := block.Uncles()
   629  		if index >= hexutil.Uint(len(uncles)) {
   630  			log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
   631  			return nil, nil
   632  		}
   633  		block = types.NewBlockWithHeader(uncles[index])
   634  		return s.rpcOutputBlock(block, false, false)
   635  	}
   636  	return nil, err
   637  }
   638  
   639  // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   640  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   641  func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
   642  	block, err := s.b.GetBlock(ctx, blockHash)
   643  	if block != nil {
   644  		uncles := block.Uncles()
   645  		if index >= hexutil.Uint(len(uncles)) {
   646  			log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
   647  			return nil, nil
   648  		}
   649  		block = types.NewBlockWithHeader(uncles[index])
   650  		return s.rpcOutputBlock(block, false, false)
   651  	}
   652  	return nil, err
   653  }
   654  
   655  // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
   656  func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
   657  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
   658  		n := hexutil.Uint(len(block.Uncles()))
   659  		return &n
   660  	}
   661  	return nil
   662  }
   663  
   664  // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
   665  func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
   666  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
   667  		n := hexutil.Uint(len(block.Uncles()))
   668  		return &n
   669  	}
   670  	return nil
   671  }
   672  
   673  // GetCode returns the code stored at the given address in the state for the given block number.
   674  func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
   675  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   676  	if state == nil || err != nil {
   677  		return nil, err
   678  	}
   679  	code := state.GetCode(address)
   680  	return code, state.Error()
   681  }
   682  
   683  // GetStorageAt returns the storage from the state at the given address, key and
   684  // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
   685  // numbers are also allowed.
   686  func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
   687  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   688  	if state == nil || err != nil {
   689  		return nil, err
   690  	}
   691  	res := state.GetState(address, common.HexToHash(key))
   692  	return res[:], state.Error()
   693  }
   694  
   695  // CallArgs represents the arguments for a call.
   696  type CallArgs struct {
   697  	From     common.Address  `json:"from"`
   698  	To       *common.Address `json:"to"`
   699  	Gas      hexutil.Uint64  `json:"gas"`
   700  	GasPrice hexutil.Big     `json:"gasPrice"`
   701  	Value    hexutil.Big     `json:"value"`
   702  	Data     hexutil.Bytes   `json:"data"`
   703  }
   704  
   705  func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber, vmCfg vm.Config, timeout time.Duration) (*core.ExecutionResult, error) {
   706  	defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
   707  
   708  	state, header, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   709  	if state == nil || err != nil {
   710  		return nil, err
   711  	}
   712  	// Set sender address or use a default if none specified
   713  	addr := args.From
   714  	if addr == (common.Address{}) {
   715  		if wallets := s.b.AccountManager().Wallets(); len(wallets) > 0 {
   716  			if accounts := wallets[0].Accounts(); len(accounts) > 0 {
   717  				addr = accounts[0].Address
   718  			}
   719  		}
   720  	}
   721  	// Set default gas & gas price if none were set
   722  	gas, gasPrice := uint64(args.Gas), args.GasPrice.ToInt()
   723  	if gas == 0 {
   724  		gas = math.MaxUint64 / 2
   725  	}
   726  	if gasPrice.Sign() == 0 {
   727  		gasPrice = new(big.Int).SetUint64(defaultGasPrice)
   728  	}
   729  
   730  	// Create new call message
   731  	msg := types.NewMessage(addr, args.To, 0, args.Value.ToInt(), gas, gasPrice, args.Data, false)
   732  
   733  	// Setup context so it may be cancelled the call has completed
   734  	// or, in case of unmetered gas, setup a context with a timeout.
   735  	var cancel context.CancelFunc
   736  	if timeout > 0 {
   737  		ctx, cancel = context.WithTimeout(ctx, timeout)
   738  	} else {
   739  		ctx, cancel = context.WithCancel(ctx)
   740  	}
   741  	// Make sure the context is cancelled when the call has completed
   742  	// this makes sure resources are cleaned up.
   743  	defer cancel()
   744  
   745  	// Get a new instance of the EVM.
   746  	evm, vmError, err := s.b.GetEVM(ctx, msg, state, header, vmCfg)
   747  	if err != nil {
   748  		return nil, err
   749  	}
   750  	// Wait for the context to be done and cancel the evm. Even if the
   751  	// EVM has finished, cancelling may be done (repeatedly)
   752  	go func() {
   753  		<-ctx.Done()
   754  		evm.Cancel()
   755  	}()
   756  
   757  	// Setup the gas pool (also for unmetered requests)
   758  	// and apply the message.
   759  	gp := new(core.GasPool).AddGas(math.MaxUint64)
   760  	result, _, err := core.ApplyMessageEx(evm, msg, gp)
   761  	if err := vmError(); err != nil {
   762  		return nil, err
   763  	}
   764  	// If the timer caused an abort, return an appropriate error message
   765  	//if evm.Cancelled() {
   766  	//	return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
   767  	//}
   768  	if err != nil {
   769  		return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.Gas())
   770  	}
   771  
   772  	return result, err
   773  }
   774  
   775  func newRevertError(result *core.ExecutionResult) *revertError {
   776  	reason, errUnpack := abi.UnpackRevert(result.Revert())
   777  	err := errors.New("execution reverted")
   778  	if errUnpack == nil {
   779  		err = fmt.Errorf("execution reverted: %v", reason)
   780  	}
   781  	return &revertError{
   782  		error:  err,
   783  		reason: hexutil.Encode(result.Revert()),
   784  	}
   785  }
   786  
   787  // revertError is an API error that encompassas an EVM revertal with JSON error
   788  // code and a binary data blob.
   789  type revertError struct {
   790  	error
   791  	reason string // revert reason hex encoded
   792  }
   793  
   794  // ErrorCode returns the JSON error code for a revertal.
   795  // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
   796  func (e *revertError) ErrorCode() int {
   797  	return 3
   798  }
   799  
   800  // ErrorData returns the hex encoded revert reason.
   801  func (e *revertError) ErrorData() interface{} {
   802  	return e.reason
   803  }
   804  
   805  // Call executes the given transaction on the state for the given block number.
   806  // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.
   807  func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
   808  	result, err := s.doCall(ctx, args, blockNr, vm.Config{}, 5*time.Second)
   809  	//return (hexutil.Bytes)(result), err
   810  
   811  	if err != nil {
   812  		return nil, err
   813  	}
   814  	// If the result contains a revert reason, try to unpack and return it.
   815  	if len(result.Revert()) > 0 {
   816  		return nil, newRevertError(result)
   817  	}
   818  	return result.Return(), result.Err
   819  }
   820  
   821  // EstimateGas returns an estimate of the amount of gas needed to execute the
   822  // given transaction against the current pending block.
   823  func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error) {
   824  	// Binary search the gas requirement, as it may be higher than the amount used
   825  	var (
   826  		lo  uint64 = params.TxGas - 1
   827  		hi  uint64
   828  		cap uint64
   829  	)
   830  
   831  	functionType, e := intAbi.FunctionTypeFromId(args.Data[:4])
   832  	if e == nil && functionType != intAbi.Unknown {
   833  		fmt.Printf("intchain inner contract tx, address: %v, functionType: %v\n", args.To.Hex(), functionType)
   834  		return hexutil.Uint64(functionType.RequiredGas()), nil
   835  	}
   836  
   837  	if uint64(args.Gas) >= params.TxGas {
   838  		hi = uint64(args.Gas)
   839  	} else {
   840  		// Retrieve the current pending block to act as the gas ceiling
   841  		block, err := s.b.BlockByNumber(ctx, rpc.PendingBlockNumber)
   842  		if err != nil {
   843  			return 0, err
   844  		}
   845  		hi = block.GasLimit()
   846  	}
   847  	cap = hi
   848  
   849  	// Create a helper to check if a gas allowance results in an executable transaction
   850  	executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
   851  		args.Gas = hexutil.Uint64(gas)
   852  
   853  		result, err := s.doCall(ctx, args, rpc.PendingBlockNumber, vm.Config{}, 0)
   854  		//if err != nil || failed {
   855  		//	return false
   856  		//}
   857  		//return true
   858  		if err != nil {
   859  			if errors.Is(err, core.ErrIntrinsicGas) {
   860  				return true, nil, nil // Special case, raise gas limit
   861  			}
   862  			return true, nil, err // Bail out
   863  		}
   864  		return result.Failed(), result, nil
   865  	}
   866  	// Execute the binary search and hone in on an executable gas limit
   867  	for lo+1 < hi {
   868  		//mid := (hi + lo) / 2
   869  		//if !executable(mid) {
   870  		//	lo = mid
   871  		//} else {
   872  		//	hi = mid
   873  		//}
   874  		mid := (hi + lo) / 2
   875  		failed, _, err := executable(mid)
   876  
   877  		// If the error is not nil(consensus error), it means the provided message
   878  		// call or transaction will never be accepted no matter how much gas it is
   879  		// assigned. Return the error directly, don't struggle any more.
   880  		if err != nil {
   881  			return 0, err
   882  		}
   883  		if failed {
   884  			lo = mid
   885  		} else {
   886  			hi = mid
   887  		}
   888  	}
   889  	// Reject the transaction as invalid if it still fails at the highest allowance
   890  	if hi == cap {
   891  		//if !executable(hi) {
   892  		//	return 0, fmt.Errorf("gas required exceeds allowance or always failing transaction")
   893  		//}
   894  		failed, result, err := executable(hi)
   895  		if err != nil {
   896  			return 0, err
   897  		}
   898  		if failed {
   899  			if result != nil && result.Err != vm.ErrOutOfGas {
   900  				if len(result.Revert()) > 0 {
   901  					return 0, newRevertError(result)
   902  				}
   903  				return 0, result.Err
   904  			}
   905  			// Otherwise, the specified gas cap is too low
   906  			return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
   907  		}
   908  	}
   909  	return hexutil.Uint64(hi), nil
   910  }
   911  
   912  // ExecutionResult groups all structured logs emitted by the EVM
   913  // while replaying a transaction in debug mode as well as transaction
   914  // execution status, the amount of gas used and the return value
   915  type ExecutionResult struct {
   916  	Gas         uint64         `json:"gas"`
   917  	Failed      bool           `json:"failed"`
   918  	ReturnValue string         `json:"returnValue"`
   919  	StructLogs  []StructLogRes `json:"structLogs"`
   920  }
   921  
   922  // StructLogRes stores a structured log emitted by the EVM while replaying a
   923  // transaction in debug mode
   924  type StructLogRes struct {
   925  	Pc      uint64             `json:"pc"`
   926  	Op      string             `json:"op"`
   927  	Gas     uint64             `json:"gas"`
   928  	GasCost uint64             `json:"gasCost"`
   929  	Depth   int                `json:"depth"`
   930  	Error   error              `json:"error,omitempty"`
   931  	Stack   *[]string          `json:"stack,omitempty"`
   932  	Memory  *[]string          `json:"memory,omitempty"`
   933  	Storage *map[string]string `json:"storage,omitempty"`
   934  }
   935  
   936  // formatLogs formats EVM returned structured logs for json output
   937  func FormatLogs(logs []vm.StructLog) []StructLogRes {
   938  	formatted := make([]StructLogRes, len(logs))
   939  	for index, trace := range logs {
   940  		formatted[index] = StructLogRes{
   941  			Pc:      trace.Pc,
   942  			Op:      trace.Op.String(),
   943  			Gas:     trace.Gas,
   944  			GasCost: trace.GasCost,
   945  			Depth:   trace.Depth,
   946  			Error:   trace.Err,
   947  		}
   948  		if trace.Stack != nil {
   949  			stack := make([]string, len(trace.Stack))
   950  			for i, stackValue := range trace.Stack {
   951  				stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
   952  			}
   953  			formatted[index].Stack = &stack
   954  		}
   955  		if trace.Memory != nil {
   956  			memory := make([]string, 0, (len(trace.Memory)+31)/32)
   957  			for i := 0; i+32 <= len(trace.Memory); i += 32 {
   958  				memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
   959  			}
   960  			formatted[index].Memory = &memory
   961  		}
   962  		if trace.Storage != nil {
   963  			storage := make(map[string]string)
   964  			for i, storageValue := range trace.Storage {
   965  				storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
   966  			}
   967  			formatted[index].Storage = &storage
   968  		}
   969  	}
   970  	return formatted
   971  }
   972  
   973  // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
   974  // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
   975  // transaction hashes.
   976  func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
   977  	head := b.Header() // copies the header once
   978  	fields := map[string]interface{}{
   979  		"number": (*hexutil.Big)(head.Number),
   980  		//"mainchainNumber":  (*hexutil.Big)(head.MainChainNumber),
   981  		"hash":             b.Hash(),
   982  		"parentHash":       head.ParentHash,
   983  		"nonce":            head.Nonce,
   984  		"mixHash":          head.MixDigest,
   985  		"sha3Uncles":       head.UncleHash,
   986  		"logsBloom":        head.Bloom,
   987  		"stateRoot":        head.Root,
   988  		"miner":            head.Coinbase,
   989  		"difficulty":       (*hexutil.Big)(head.Difficulty),
   990  		"totalDifficulty":  (*hexutil.Big)(s.b.GetTd(b.Hash())),
   991  		"extraData":        hexutil.Bytes(head.Extra),
   992  		"size":             hexutil.Uint64(b.Size()),
   993  		"gasLimit":         hexutil.Uint64(head.GasLimit),
   994  		"gasUsed":          hexutil.Uint64(head.GasUsed),
   995  		"timestamp":        (*hexutil.Big)(head.Time),
   996  		"transactionsRoot": head.TxHash,
   997  		"receiptsRoot":     head.ReceiptHash,
   998  	}
   999  
  1000  	if inclTx {
  1001  		formatTx := func(tx *types.Transaction) (interface{}, error) {
  1002  			return tx.Hash(), nil
  1003  		}
  1004  
  1005  		if fullTx {
  1006  			formatTx = func(tx *types.Transaction) (interface{}, error) {
  1007  				return newRPCTransactionFromBlockHash(b, tx.Hash()), nil
  1008  			}
  1009  		}
  1010  
  1011  		txs := b.Transactions()
  1012  		transactions := make([]interface{}, len(txs))
  1013  		var err error
  1014  		for i, tx := range b.Transactions() {
  1015  			if transactions[i], err = formatTx(tx); err != nil {
  1016  				return nil, err
  1017  			}
  1018  		}
  1019  		fields["transactions"] = transactions
  1020  	}
  1021  
  1022  	uncles := b.Uncles()
  1023  	uncleHashes := make([]common.Hash, len(uncles))
  1024  	for i, uncle := range uncles {
  1025  		uncleHashes[i] = uncle.Hash()
  1026  	}
  1027  	fields["uncles"] = uncleHashes
  1028  
  1029  	return fields, nil
  1030  }
  1031  
  1032  // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1033  type RPCTransaction struct {
  1034  	BlockHash        common.Hash     `json:"blockHash"`
  1035  	BlockNumber      *hexutil.Big    `json:"blockNumber"`
  1036  	From             common.Address  `json:"from"`
  1037  	Gas              hexutil.Uint64  `json:"gas"`
  1038  	GasPrice         *hexutil.Big    `json:"gasPrice"`
  1039  	Hash             common.Hash     `json:"hash"`
  1040  	Input            hexutil.Bytes   `json:"input"`
  1041  	Nonce            hexutil.Uint64  `json:"nonce"`
  1042  	To               *common.Address `json:"to"`
  1043  	TransactionIndex hexutil.Uint    `json:"transactionIndex"`
  1044  	Value            *hexutil.Big    `json:"value"`
  1045  	V                *hexutil.Big    `json:"v"`
  1046  	R                *hexutil.Big    `json:"r"`
  1047  	S                *hexutil.Big    `json:"s"`
  1048  }
  1049  
  1050  // newRPCTransaction returns a transaction that will serialize to the RPC
  1051  // representation, with the given location metadata set (if available).
  1052  func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  1053  	var signer types.Signer = types.FrontierSigner{}
  1054  	if tx.Protected() {
  1055  		signer = types.NewEIP155Signer(tx.ChainId())
  1056  	}
  1057  	from, _ := types.Sender(signer, tx)
  1058  	v, r, s := tx.RawSignatureValues()
  1059  
  1060  	result := &RPCTransaction{
  1061  		From:     from,
  1062  		Gas:      hexutil.Uint64(tx.Gas()),
  1063  		GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1064  		Hash:     tx.Hash(),
  1065  		Input:    hexutil.Bytes(tx.Data()),
  1066  		Nonce:    hexutil.Uint64(tx.Nonce()),
  1067  		To:       tx.To(),
  1068  		Value:    (*hexutil.Big)(tx.Value()),
  1069  		V:        (*hexutil.Big)(v),
  1070  		R:        (*hexutil.Big)(r),
  1071  		S:        (*hexutil.Big)(s),
  1072  	}
  1073  	if blockHash != (common.Hash{}) {
  1074  		result.BlockHash = blockHash
  1075  		result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1076  		result.TransactionIndex = hexutil.Uint(index)
  1077  	}
  1078  	return result
  1079  }
  1080  
  1081  // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1082  func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  1083  	return newRPCTransaction(tx, common.Hash{}, 0, 0)
  1084  }
  1085  
  1086  // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1087  func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1088  	txs := b.Transactions()
  1089  	if index >= uint64(len(txs)) {
  1090  		return nil
  1091  	}
  1092  	return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  1093  }
  1094  
  1095  // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1096  func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1097  	txs := b.Transactions()
  1098  	if index >= uint64(len(txs)) {
  1099  		return nil
  1100  	}
  1101  	blob, _ := rlp.EncodeToBytes(txs[index])
  1102  	return blob
  1103  }
  1104  
  1105  // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1106  func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1107  	for idx, tx := range b.Transactions() {
  1108  		if tx.Hash() == hash {
  1109  			return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1110  		}
  1111  	}
  1112  	return nil
  1113  }
  1114  
  1115  // PublicTransactionPoolAPI exposes methods for the RPC interface
  1116  type PublicTransactionPoolAPI struct {
  1117  	b         Backend
  1118  	nonceLock *AddrLocker
  1119  }
  1120  
  1121  // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1122  func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1123  	return &PublicTransactionPoolAPI{b, nonceLock}
  1124  }
  1125  
  1126  // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1127  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1128  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1129  		n := hexutil.Uint(len(block.Transactions()))
  1130  		return &n
  1131  	}
  1132  	return nil
  1133  }
  1134  
  1135  // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1136  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1137  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1138  		n := hexutil.Uint(len(block.Transactions()))
  1139  		return &n
  1140  	}
  1141  	return nil
  1142  }
  1143  
  1144  // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1145  func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1146  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1147  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1148  	}
  1149  	return nil
  1150  }
  1151  
  1152  // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1153  func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1154  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1155  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1156  	}
  1157  	return nil
  1158  }
  1159  
  1160  // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1161  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1162  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1163  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1164  	}
  1165  	return nil
  1166  }
  1167  
  1168  // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1169  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1170  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1171  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1172  	}
  1173  	return nil
  1174  }
  1175  
  1176  // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1177  func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {
  1178  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  1179  	if state == nil || err != nil {
  1180  		return nil, err
  1181  	}
  1182  	nonce := state.GetNonce(address)
  1183  	return (*hexutil.Uint64)(&nonce), state.Error()
  1184  }
  1185  
  1186  // GetTransactionByHash returns the transaction for the given hash
  1187  func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) *RPCTransaction {
  1188  	// Try to return an already finalized transaction
  1189  	if tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash); tx != nil {
  1190  		return newRPCTransaction(tx, blockHash, blockNumber, index)
  1191  	}
  1192  	// No finalized transaction, try to retrieve it from the pool
  1193  	if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1194  		return newRPCPendingTransaction(tx)
  1195  	}
  1196  	// Transaction unknown, return as such
  1197  	return nil
  1198  }
  1199  
  1200  // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1201  func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1202  	var tx *types.Transaction
  1203  
  1204  	// Retrieve a finalized transaction, or a pooled otherwise
  1205  	if tx, _, _, _ = rawdb.ReadTransaction(s.b.ChainDb(), hash); tx == nil {
  1206  		if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1207  			// Transaction not found anywhere, abort
  1208  			return nil, nil
  1209  		}
  1210  	}
  1211  	// Serialize to RLP and return
  1212  	return rlp.EncodeToBytes(tx)
  1213  }
  1214  
  1215  type Log struct {
  1216  	// Consensus fields:
  1217  	// address of the contract that generated the event
  1218  	Address string `json:"address" gencodec:"required"`
  1219  	// list of topics provided by the contract.
  1220  	Topics []common.Hash `json:"topics" gencodec:"required"`
  1221  	// supplied by the contract, usually ABI-encoded
  1222  	Data string `json:"data" gencodec:"required"`
  1223  
  1224  	// Derived fields. These fields are filled in by the node
  1225  	// but not secured by consensus.
  1226  	// block in which the transaction was included
  1227  	BlockNumber uint64 `json:"blockNumber"`
  1228  	// hash of the transaction
  1229  	TxHash common.Hash `json:"transactionHash" gencodec:"required"`
  1230  	// index of the transaction in the block
  1231  	TxIndex uint `json:"transactionIndex" gencodec:"required"`
  1232  	// hash of the block in which the transaction was included
  1233  	BlockHash common.Hash `json:"blockHash"`
  1234  	// index of the log in the receipt
  1235  	Index uint `json:"logIndex" gencodec:"required"`
  1236  
  1237  	// The Removed field is true if this log was reverted due to a chain reorganisation.
  1238  	// You must pay attention to this field if you receive logs through a filter query.
  1239  	Removed bool `json:"removed"`
  1240  }
  1241  
  1242  // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1243  func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1244  	tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
  1245  	if tx == nil {
  1246  		return nil, nil
  1247  	}
  1248  	receipts, err := s.b.GetReceipts(ctx, blockHash)
  1249  	if err != nil {
  1250  		return nil, err
  1251  	}
  1252  	if len(receipts) <= int(index) {
  1253  		return nil, nil
  1254  	}
  1255  	receipt := receipts[index]
  1256  
  1257  	var signer types.Signer = types.FrontierSigner{}
  1258  	if tx.Protected() {
  1259  		signer = types.NewEIP155Signer(tx.ChainId())
  1260  	}
  1261  	from, _ := types.Sender(signer, tx)
  1262  
  1263  	fields := map[string]interface{}{
  1264  		"blockHash":         blockHash,
  1265  		"blockNumber":       hexutil.Uint64(blockNumber),
  1266  		"transactionHash":   hash,
  1267  		"transactionIndex":  hexutil.Uint64(index),
  1268  		"from":              from,
  1269  		"to":                tx.To(),
  1270  		"gasUsed":           hexutil.Uint64(receipt.GasUsed),
  1271  		"cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1272  		"contractAddress":   nil,
  1273  		"logs":              receipt.Logs,
  1274  		"logsBloom":         receipt.Bloom,
  1275  	}
  1276  
  1277  	// Assign receipt status or post state.
  1278  	if len(receipt.PostState) > 0 {
  1279  		fields["root"] = hexutil.Bytes(receipt.PostState)
  1280  	} else {
  1281  		fields["status"] = hexutil.Uint(receipt.Status)
  1282  	}
  1283  	if receipt.Logs == nil {
  1284  		fields["logs"] = [][]*types.Log{}
  1285  	}
  1286  
  1287  	// If the ContractAddress is 32 0x0 bytes, assume it is not a contract creation
  1288  	if receipt.ContractAddress != (common.Address{}) {
  1289  		fields["contractAddress"] = receipt.ContractAddress
  1290  	}
  1291  	return fields, nil
  1292  }
  1293  
  1294  // sign is a helper function that signs a transaction with the private key of the given address.
  1295  func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1296  	// Look up the wallet containing the requested signer
  1297  	account := accounts.Account{Address: addr}
  1298  
  1299  	wallet, err := s.b.AccountManager().Find(account)
  1300  	if err != nil {
  1301  		return nil, err
  1302  	}
  1303  	// Request the wallet to sign the transaction
  1304  	var chainID *big.Int
  1305  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  1306  		chainID = config.ChainId
  1307  	}
  1308  	return wallet.SignTxWithAddress(account, tx, chainID)
  1309  }
  1310  
  1311  // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1312  type SendTxArgs struct {
  1313  	From     common.Address  `json:"from"`
  1314  	To       *common.Address `json:"to"`
  1315  	Gas      *hexutil.Uint64 `json:"gas"`
  1316  	GasPrice *hexutil.Big    `json:"gasPrice"`
  1317  	Value    *hexutil.Big    `json:"value"`
  1318  	Nonce    *hexutil.Uint64 `json:"nonce"`
  1319  	// We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1320  	// newer name and should be preferred by clients.
  1321  	Data  *hexutil.Bytes `json:"data"`
  1322  	Input *hexutil.Bytes `json:"input"`
  1323  }
  1324  
  1325  // setDefaults is a helper function that fills in default values for unspecified tx fields.
  1326  func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1327  
  1328  	var function = intAbi.Unknown
  1329  	if intAbi.IsIntChainContractAddr(args.To) {
  1330  		var input []byte
  1331  		if args.Data != nil {
  1332  			input = *args.Data
  1333  		} else if args.Input != nil {
  1334  			input = *args.Input
  1335  		}
  1336  		if len(input) == 0 {
  1337  			return errors.New(`intchain contract without any data provided`)
  1338  		}
  1339  
  1340  		var err error
  1341  		function, err = intAbi.FunctionTypeFromId(input[:4])
  1342  		if err != nil {
  1343  			return err
  1344  		}
  1345  	}
  1346  
  1347  	// force GasLimit to 0 for DepositInChildChain/WithdrawFromMainChain/SaveDataToMainChain in order to avoid being dropped by TxPool.
  1348  	if function == intAbi.DepositInChildChain || function == intAbi.WithdrawFromMainChain || function == intAbi.SaveDataToMainChain {
  1349  		args.Gas = new(hexutil.Uint64)
  1350  		*(*uint64)(args.Gas) = 0
  1351  	} else {
  1352  		if args.Gas == nil {
  1353  			args.Gas = new(hexutil.Uint64)
  1354  			*(*uint64)(args.Gas) = 90000
  1355  		}
  1356  	}
  1357  
  1358  	if args.GasPrice == nil {
  1359  		price, err := b.SuggestPrice(ctx)
  1360  		if err != nil {
  1361  			return err
  1362  		}
  1363  		args.GasPrice = (*hexutil.Big)(price)
  1364  	}
  1365  	if args.Value == nil {
  1366  		args.Value = new(hexutil.Big)
  1367  	}
  1368  	if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1369  		return errors.New(`Both "data" and "input" are set and not equal. Please use "input" to pass transaction call data.`)
  1370  	}
  1371  	if args.To == nil {
  1372  		// Contract creation
  1373  		var input []byte
  1374  		if args.Data != nil {
  1375  			input = *args.Data
  1376  		} else if args.Input != nil {
  1377  			input = *args.Input
  1378  		}
  1379  		if len(input) == 0 {
  1380  			return errors.New(`contract creation without any data provided`)
  1381  		}
  1382  	}
  1383  
  1384  	if args.Nonce == nil {
  1385  		nonce, err := b.GetPoolNonce(ctx, args.From)
  1386  		if err != nil {
  1387  			return err
  1388  		}
  1389  		args.Nonce = (*hexutil.Uint64)(&nonce)
  1390  	}
  1391  
  1392  	return nil
  1393  }
  1394  
  1395  func (args *SendTxArgs) toTransaction() *types.Transaction {
  1396  	var input []byte
  1397  	if args.Data != nil {
  1398  		input = *args.Data
  1399  	} else if args.Input != nil {
  1400  		input = *args.Input
  1401  	}
  1402  	if args.To == nil {
  1403  		return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1404  	}
  1405  	return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1406  }
  1407  
  1408  // submitTransaction is a helper function that submits tx to txPool and logs a message.
  1409  func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1410  	if err := b.SendTx(ctx, tx); err != nil {
  1411  		return common.Hash{}, err
  1412  	}
  1413  	if tx.To() == nil {
  1414  		signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1415  		from, err := types.Sender(signer, tx)
  1416  		if err != nil {
  1417  			return common.Hash{}, err
  1418  		}
  1419  		addr := crypto.CreateAddress(from, tx.Nonce())
  1420  		log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
  1421  	} else {
  1422  		log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1423  	}
  1424  	return tx.Hash(), nil
  1425  }
  1426  
  1427  // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1428  // transaction pool.
  1429  func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1430  	fmt.Printf("transaction args PublicTransactionPoolAPI args %v\n", args)
  1431  	// Look up the wallet containing the requested signer
  1432  	account := accounts.Account{Address: args.From}
  1433  
  1434  	wallet, err := s.b.AccountManager().Find(account)
  1435  	if err != nil {
  1436  		return common.Hash{}, err
  1437  	}
  1438  
  1439  	if args.Nonce == nil {
  1440  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  1441  		// the same nonce to multiple accounts.
  1442  		s.nonceLock.LockAddr(args.From)
  1443  		defer s.nonceLock.UnlockAddr(args.From)
  1444  	}
  1445  
  1446  	// Set some sanity defaults and terminate on failure
  1447  	if err := args.setDefaults(ctx, s.b); err != nil {
  1448  		return common.Hash{}, err
  1449  	}
  1450  	// Assemble the transaction and sign with the wallet
  1451  	tx := args.toTransaction()
  1452  
  1453  	var chainID *big.Int
  1454  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  1455  		chainID = config.ChainId
  1456  	}
  1457  	signed, err := wallet.SignTxWithAddress(account, tx, chainID)
  1458  	if err != nil {
  1459  		return common.Hash{}, err
  1460  	}
  1461  	return submitTransaction(ctx, s.b, signed)
  1462  }
  1463  
  1464  func SendTransaction(ctx context.Context, args SendTxArgs, am *accounts.Manager, b Backend, nonceLock *AddrLocker) (common.Hash, error) {
  1465  	fmt.Printf("transaction args PublicTransactionPoolAPI args %v\n", args)
  1466  	// Look up the wallet containing the requested signer
  1467  	account := accounts.Account{Address: args.From}
  1468  
  1469  	wallet, err := am.Find(account)
  1470  	if err != nil {
  1471  		return common.Hash{}, err
  1472  	}
  1473  
  1474  	if args.Nonce == nil {
  1475  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  1476  		// the same nonce to multiple accounts.
  1477  		nonceLock.LockAddr(args.From)
  1478  		defer nonceLock.UnlockAddr(args.From)
  1479  	}
  1480  
  1481  	// Set some sanity defaults and terminate on failure
  1482  	if err := args.setDefaults(ctx, b); err != nil {
  1483  		return common.Hash{}, err
  1484  	}
  1485  	// Assemble the transaction and sign with the wallet
  1486  	tx := args.toTransaction()
  1487  
  1488  	var chainID *big.Int
  1489  	if config := b.ChainConfig(); config.IsEIP155(b.CurrentBlock().Number()) {
  1490  		chainID = config.ChainId
  1491  	}
  1492  	signed, err := wallet.SignTxWithAddress(account, tx, chainID)
  1493  	if err != nil {
  1494  		return common.Hash{}, err
  1495  	}
  1496  	return submitTransaction(ctx, b, signed)
  1497  }
  1498  
  1499  // SendRawTransaction will add the signed transaction to the transaction pool.
  1500  // The sender is responsible for signing the transaction and using the correct nonce.
  1501  func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
  1502  	tx := new(types.Transaction)
  1503  	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1504  		return common.Hash{}, err
  1505  	}
  1506  	return submitTransaction(ctx, s.b, tx)
  1507  }
  1508  
  1509  // Sign calculates an ECDSA signature for:
  1510  // keccack256("\x19INT Chain Signed Message:\n" + len(message) + message).
  1511  //
  1512  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1513  // where the V value will be 27 or 28 for legacy reasons.
  1514  //
  1515  // The account associated with addr must be unlocked.
  1516  //
  1517  func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1518  	// Look up the wallet containing the requested signer
  1519  	account := accounts.Account{Address: addr}
  1520  
  1521  	wallet, err := s.b.AccountManager().Find(account)
  1522  	if err != nil {
  1523  		return nil, err
  1524  	}
  1525  	// Sign the requested hash with the wallet
  1526  	signature, err := wallet.SignHash(account, signHash(data))
  1527  	if err == nil {
  1528  		signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1529  	}
  1530  	return signature, err
  1531  }
  1532  
  1533  // SignTransactionResult represents a RLP encoded signed transaction.
  1534  type SignTransactionResult struct {
  1535  	Raw hexutil.Bytes      `json:"raw"`
  1536  	Tx  *types.Transaction `json:"tx"`
  1537  }
  1538  
  1539  // SignTransaction will sign the given transaction with the from account.
  1540  // The node needs to have the private key of the account corresponding with
  1541  // the given from address and it needs to be unlocked.
  1542  func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1543  	if args.Gas == nil {
  1544  		return nil, fmt.Errorf("gas not specified")
  1545  	}
  1546  	if args.GasPrice == nil {
  1547  		return nil, fmt.Errorf("gasPrice not specified")
  1548  	}
  1549  	if args.Nonce == nil {
  1550  		return nil, fmt.Errorf("nonce not specified")
  1551  	}
  1552  	if err := args.setDefaults(ctx, s.b); err != nil {
  1553  		return nil, err
  1554  	}
  1555  	tx, err := s.sign(args.From, args.toTransaction())
  1556  	if err != nil {
  1557  		return nil, err
  1558  	}
  1559  	data, err := rlp.EncodeToBytes(tx)
  1560  	if err != nil {
  1561  		return nil, err
  1562  	}
  1563  	return &SignTransactionResult{data, tx}, nil
  1564  }
  1565  
  1566  // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of
  1567  // the accounts this node manages.
  1568  func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1569  	pending, err := s.b.GetPoolTransactions()
  1570  	if err != nil {
  1571  		return nil, err
  1572  	}
  1573  
  1574  	transactions := make([]*RPCTransaction, 0, len(pending))
  1575  	for _, tx := range pending {
  1576  		var signer types.Signer = types.HomesteadSigner{}
  1577  		if tx.Protected() {
  1578  			signer = types.NewEIP155Signer(tx.ChainId())
  1579  		}
  1580  		from, _ := types.Sender(signer, tx)
  1581  		if _, err := s.b.AccountManager().Find(accounts.Account{Address: from}); err == nil {
  1582  			transactions = append(transactions, newRPCPendingTransaction(tx))
  1583  		}
  1584  	}
  1585  	return transactions, nil
  1586  }
  1587  
  1588  // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1589  // the given transaction from the pool and reinsert it with the new gas price and limit.
  1590  func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1591  	if sendArgs.Nonce == nil {
  1592  		return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1593  	}
  1594  	if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1595  		return common.Hash{}, err
  1596  	}
  1597  	matchTx := sendArgs.toTransaction()
  1598  	pending, err := s.b.GetPoolTransactions()
  1599  	if err != nil {
  1600  		return common.Hash{}, err
  1601  	}
  1602  
  1603  	for _, p := range pending {
  1604  		var signer types.Signer = types.HomesteadSigner{}
  1605  		if p.Protected() {
  1606  			signer = types.NewEIP155Signer(p.ChainId())
  1607  		}
  1608  		wantSigHash := signer.Hash(matchTx)
  1609  
  1610  		if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  1611  			// Match. Re-sign and send the transaction.
  1612  			if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1613  				sendArgs.GasPrice = gasPrice
  1614  			}
  1615  			if gasLimit != nil && *gasLimit != 0 {
  1616  				sendArgs.Gas = gasLimit
  1617  			}
  1618  			signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction())
  1619  			if err != nil {
  1620  				return common.Hash{}, err
  1621  			}
  1622  			if err = s.b.SendTx(ctx, signedTx); err != nil {
  1623  				return common.Hash{}, err
  1624  			}
  1625  			return signedTx.Hash(), nil
  1626  		}
  1627  	}
  1628  
  1629  	return common.Hash{}, fmt.Errorf("Transaction %#x not found", matchTx.Hash())
  1630  }
  1631  
  1632  // PublicDebugAPI is the collection of INT Chain APIs exposed over the public
  1633  // debugging endpoint.
  1634  type PublicDebugAPI struct {
  1635  	b Backend
  1636  }
  1637  
  1638  // NewPublicDebugAPI creates a new API definition for the public debug methods
  1639  // of the INT Chain service.
  1640  func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1641  	return &PublicDebugAPI{b: b}
  1642  }
  1643  
  1644  // GetBlockRlp retrieves the RLP encoded for of a single block.
  1645  func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1646  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1647  	if block == nil {
  1648  		return "", fmt.Errorf("block #%d not found", number)
  1649  	}
  1650  	encoded, err := rlp.EncodeToBytes(block)
  1651  	if err != nil {
  1652  		return "", err
  1653  	}
  1654  	return fmt.Sprintf("%x", encoded), nil
  1655  }
  1656  
  1657  // PrintBlock retrieves a block and returns its pretty printed form.
  1658  func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1659  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1660  	if block == nil {
  1661  		return "", fmt.Errorf("block #%d not found", number)
  1662  	}
  1663  	return block.String(), nil
  1664  }
  1665  
  1666  // PrivateDebugAPI is the collection of INT Chain APIs exposed over the private
  1667  // debugging endpoint.
  1668  type PrivateDebugAPI struct {
  1669  	b Backend
  1670  }
  1671  
  1672  // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1673  // of the INT Chain service.
  1674  func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1675  	return &PrivateDebugAPI{b: b}
  1676  }
  1677  
  1678  // ChaindbProperty returns leveldb properties of the chain database.
  1679  func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1680  	ldb, ok := api.b.ChainDb().(interface {
  1681  		LDB() *leveldb.DB
  1682  	})
  1683  	if !ok {
  1684  		return "", fmt.Errorf("chaindbProperty does not work for memory databases")
  1685  	}
  1686  	if property == "" {
  1687  		property = "leveldb.stats"
  1688  	} else if !strings.HasPrefix(property, "leveldb.") {
  1689  		property = "leveldb." + property
  1690  	}
  1691  	return ldb.LDB().GetProperty(property)
  1692  }
  1693  
  1694  func (api *PrivateDebugAPI) ChaindbCompact() error {
  1695  	for b := byte(0); b < 255; b++ {
  1696  		log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1697  		if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  1698  			log.Error("Database compaction failed", "err", err)
  1699  			return err
  1700  		}
  1701  	}
  1702  	return nil
  1703  }
  1704  
  1705  // SetHead rewinds the head of the blockchain to a previous block.
  1706  func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  1707  	api.b.SetHead(uint64(number))
  1708  }
  1709  
  1710  // PublicNetAPI offers network related RPC methods
  1711  type PublicNetAPI struct {
  1712  	net            *p2p.Server
  1713  	networkVersion uint64
  1714  }
  1715  
  1716  // NewPublicNetAPI creates a new net API instance.
  1717  func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  1718  	return &PublicNetAPI{net, networkVersion}
  1719  }
  1720  
  1721  // Listening returns an indication if the node is listening for network connections.
  1722  func (s *PublicNetAPI) Listening() bool {
  1723  	return true // always listening
  1724  }
  1725  
  1726  // PeerCount returns the number of connected peers
  1727  func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  1728  	return hexutil.Uint(s.net.PeerCount())
  1729  }
  1730  
  1731  // Version returns the current intchain protocol version.
  1732  func (s *PublicNetAPI) Version() string {
  1733  	return fmt.Sprintf("%d", s.networkVersion)
  1734  }
  1735  
  1736  type PublicINTAPI struct {
  1737  	am        *accounts.Manager
  1738  	b         Backend
  1739  	nonceLock *AddrLocker
  1740  }
  1741  
  1742  // NewPublicINTAPI creates a new INT API instance.
  1743  func NewPublicINTAPI(b Backend, nonceLock *AddrLocker) *PublicINTAPI {
  1744  	return &PublicINTAPI{b.AccountManager(), b, nonceLock}
  1745  }
  1746  
  1747  func (s *PublicINTAPI) SignAddress(from common.Address, consensusPrivateKey hexutil.Bytes) (goCrypto.Signature, error) {
  1748  	if len(consensusPrivateKey) != 32 {
  1749  		return nil, errors.New("invalid consensus private key")
  1750  	}
  1751  
  1752  	var blsPriv goCrypto.BLSPrivKey
  1753  	copy(blsPriv[:], consensusPrivateKey)
  1754  
  1755  	blsSign := blsPriv.Sign(from.Bytes())
  1756  
  1757  	return blsSign, nil
  1758  }
  1759  
  1760  func (api *PublicINTAPI) WithdrawReward(ctx context.Context, from common.Address, delegateAddress common.Address, amount *hexutil.Big, gasPrice *hexutil.Big) (common.Hash, error) {
  1761  	input, err := intAbi.ChainABI.Pack(intAbi.WithdrawReward.String(), delegateAddress, (*big.Int)(amount))
  1762  	if err != nil {
  1763  		return common.Hash{}, err
  1764  	}
  1765  
  1766  	defaultGas := intAbi.WithdrawReward.RequiredGas()
  1767  
  1768  	args := SendTxArgs{
  1769  		From:     from,
  1770  		To:       &intAbi.ChainContractMagicAddr,
  1771  		Gas:      (*hexutil.Uint64)(&defaultGas),
  1772  		GasPrice: gasPrice,
  1773  		Value:    nil,
  1774  		Input:    (*hexutil.Bytes)(&input),
  1775  		Nonce:    nil,
  1776  	}
  1777  
  1778  	return SendTransaction(ctx, args, api.am, api.b, api.nonceLock)
  1779  }
  1780  
  1781  func (api *PublicINTAPI) Delegate(ctx context.Context, from, candidate common.Address, amount *hexutil.Big, gasPrice *hexutil.Big) (common.Hash, error) {
  1782  
  1783  	input, err := intAbi.ChainABI.Pack(intAbi.Delegate.String(), candidate)
  1784  	if err != nil {
  1785  		return common.Hash{}, err
  1786  	}
  1787  
  1788  	defaultGas := intAbi.Delegate.RequiredGas()
  1789  
  1790  	args := SendTxArgs{
  1791  		From:     from,
  1792  		To:       &intAbi.ChainContractMagicAddr,
  1793  		Gas:      (*hexutil.Uint64)(&defaultGas),
  1794  		GasPrice: gasPrice,
  1795  		Value:    amount,
  1796  		Input:    (*hexutil.Bytes)(&input),
  1797  		Nonce:    nil,
  1798  	}
  1799  	return SendTransaction(ctx, args, api.am, api.b, api.nonceLock)
  1800  }
  1801  
  1802  func (api *PublicINTAPI) UnDelegate(ctx context.Context, from, candidate common.Address, amount *hexutil.Big, gasPrice *hexutil.Big) (common.Hash, error) {
  1803  
  1804  	input, err := intAbi.ChainABI.Pack(intAbi.UnDelegate.String(), candidate, (*big.Int)(amount))
  1805  	if err != nil {
  1806  		return common.Hash{}, err
  1807  	}
  1808  
  1809  	defaultGas := intAbi.UnDelegate.RequiredGas()
  1810  
  1811  	args := SendTxArgs{
  1812  		From:     from,
  1813  		To:       &intAbi.ChainContractMagicAddr,
  1814  		Gas:      (*hexutil.Uint64)(&defaultGas),
  1815  		GasPrice: gasPrice,
  1816  		Value:    nil,
  1817  		Input:    (*hexutil.Bytes)(&input),
  1818  		Nonce:    nil,
  1819  	}
  1820  
  1821  	return SendTransaction(ctx, args, api.am, api.b, api.nonceLock)
  1822  }
  1823  
  1824  func (api *PublicINTAPI) Register(ctx context.Context, from common.Address, registerAmount *hexutil.Big, pubkey goCrypto.BLSPubKey, signature hexutil.Bytes, commission uint8, gasPrice *hexutil.Big) (common.Hash, error) {
  1825  
  1826  	input, err := intAbi.ChainABI.Pack(intAbi.Register.String(), pubkey.Bytes(), signature, commission)
  1827  	if err != nil {
  1828  		return common.Hash{}, err
  1829  	}
  1830  
  1831  	defaultGas := intAbi.Register.RequiredGas()
  1832  
  1833  	args := SendTxArgs{
  1834  		From:     from,
  1835  		To:       &intAbi.ChainContractMagicAddr,
  1836  		Gas:      (*hexutil.Uint64)(&defaultGas),
  1837  		GasPrice: gasPrice,
  1838  		Value:    registerAmount,
  1839  		Input:    (*hexutil.Bytes)(&input),
  1840  		Nonce:    nil,
  1841  	}
  1842  	return SendTransaction(ctx, args, api.am, api.b, api.nonceLock)
  1843  }
  1844  
  1845  func (api *PublicINTAPI) UnRegister(ctx context.Context, from common.Address, gasPrice *hexutil.Big) (common.Hash, error) {
  1846  
  1847  	input, err := intAbi.ChainABI.Pack(intAbi.UnRegister.String())
  1848  	if err != nil {
  1849  		return common.Hash{}, err
  1850  	}
  1851  
  1852  	defaultGas := intAbi.UnRegister.RequiredGas()
  1853  
  1854  	args := SendTxArgs{
  1855  		From:     from,
  1856  		To:       &intAbi.ChainContractMagicAddr,
  1857  		Gas:      (*hexutil.Uint64)(&defaultGas),
  1858  		GasPrice: gasPrice,
  1859  		Value:    nil,
  1860  		Input:    (*hexutil.Bytes)(&input),
  1861  		Nonce:    nil,
  1862  	}
  1863  	return SendTransaction(ctx, args, api.am, api.b, api.nonceLock)
  1864  }
  1865  
  1866  func (api *PublicINTAPI) CheckCandidate(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (map[string]interface{}, error) {
  1867  	state, _, err := api.b.StateAndHeaderByNumber(ctx, blockNr)
  1868  	if state == nil || err != nil {
  1869  		return nil, err
  1870  	}
  1871  
  1872  	fields := map[string]interface{}{
  1873  		"candidate":  state.IsCandidate(address),
  1874  		"commission": state.GetCommission(address),
  1875  	}
  1876  	return fields, state.Error()
  1877  }
  1878  
  1879  func (api *PublicINTAPI) SetCommission(ctx context.Context, from common.Address, commission uint8, gasPrice *hexutil.Big) (common.Hash, error) {
  1880  	input, err := intAbi.ChainABI.Pack(intAbi.SetCommission.String(), commission)
  1881  	if err != nil {
  1882  		return common.Hash{}, err
  1883  	}
  1884  
  1885  	defaultGas := intAbi.SetCommission.RequiredGas()
  1886  
  1887  	args := SendTxArgs{
  1888  		From:     from,
  1889  		To:       &intAbi.ChainContractMagicAddr,
  1890  		Gas:      (*hexutil.Uint64)(&defaultGas),
  1891  		GasPrice: gasPrice,
  1892  		Value:    nil,
  1893  		Input:    (*hexutil.Bytes)(&input),
  1894  		Nonce:    nil,
  1895  	}
  1896  
  1897  	return SendTransaction(ctx, args, api.am, api.b, api.nonceLock)
  1898  }
  1899  
  1900  func (api *PublicINTAPI) EditValidator(ctx context.Context, from common.Address, moniker, website string, identity string, details string, gasPrice *hexutil.Big) (common.Hash, error) {
  1901  	input, err := intAbi.ChainABI.Pack(intAbi.EditValidator.String(), moniker, website, identity, details)
  1902  	if err != nil {
  1903  		return common.Hash{}, err
  1904  	}
  1905  
  1906  	defaultGas := intAbi.EditValidator.RequiredGas()
  1907  
  1908  	args := SendTxArgs{
  1909  		From:     from,
  1910  		To:       &intAbi.ChainContractMagicAddr,
  1911  		Gas:      (*hexutil.Uint64)(&defaultGas),
  1912  		GasPrice: gasPrice,
  1913  		Value:    nil,
  1914  		Input:    (*hexutil.Bytes)(&input),
  1915  		Nonce:    nil,
  1916  	}
  1917  
  1918  	return SendTransaction(ctx, args, api.am, api.b, api.nonceLock)
  1919  }
  1920  
  1921  func (api *PublicINTAPI) SetAddress(ctx context.Context, from, fAddress common.Address, gasPrice *hexutil.Big) (common.Hash, error) {
  1922  	input, err := intAbi.ChainABI.Pack(intAbi.SetAddress.String(), fAddress)
  1923  	if err != nil {
  1924  		return common.Hash{}, err
  1925  	}
  1926  
  1927  	defaultGas := intAbi.SetAddress.RequiredGas()
  1928  
  1929  	args := SendTxArgs{
  1930  		From:     from,
  1931  		To:       &intAbi.ChainContractMagicAddr,
  1932  		Gas:      (*hexutil.Uint64)(&defaultGas),
  1933  		GasPrice: gasPrice,
  1934  		Value:    nil,
  1935  		Input:    (*hexutil.Bytes)(&input),
  1936  		Nonce:    nil,
  1937  	}
  1938  
  1939  	return SendTransaction(ctx, args, api.am, api.b, api.nonceLock)
  1940  }
  1941  
  1942  func init() {
  1943  	// Withdraw reward
  1944  	core.RegisterValidateCb(intAbi.WithdrawReward, withdrawRewardValidateCb)
  1945  	core.RegisterApplyCb(intAbi.WithdrawReward, withdrawRewardApplyCb)
  1946  
  1947  	// Delegate
  1948  	core.RegisterValidateCb(intAbi.Delegate, delegateValidateCb)
  1949  	core.RegisterApplyCb(intAbi.Delegate, delegateApplyCb)
  1950  
  1951  	// Cancel Delegate
  1952  	core.RegisterValidateCb(intAbi.UnDelegate, unDelegateValidateCb)
  1953  	core.RegisterApplyCb(intAbi.UnDelegate, unDelegateApplyCb)
  1954  
  1955  	// Register
  1956  	core.RegisterValidateCb(intAbi.Register, registerValidateCb)
  1957  	core.RegisterApplyCb(intAbi.Register, registerApplyCb)
  1958  
  1959  	// Cancel Register
  1960  	core.RegisterValidateCb(intAbi.UnRegister, unRegisterValidateCb)
  1961  	core.RegisterApplyCb(intAbi.UnRegister, unRegisterApplyCb)
  1962  
  1963  	// Set Commission
  1964  	core.RegisterValidateCb(intAbi.SetCommission, setCommisstionValidateCb)
  1965  	core.RegisterApplyCb(intAbi.SetCommission, setCommisstionApplyCb)
  1966  
  1967  	// Edit Validator
  1968  	core.RegisterValidateCb(intAbi.EditValidator, editValidatorValidateCb)
  1969  
  1970  	// UnForbidden
  1971  	//core.RegisterValidateCb(intAbi.UnForbidden, unForbiddenValidateCb)
  1972  	//core.RegisterApplyCb(intAbi.UnForbidden, unForbiddenApplyCb)
  1973  
  1974  	// Set Address
  1975  	core.RegisterValidateCb(intAbi.SetAddress, setAddressValidateCb)
  1976  	core.RegisterApplyCb(intAbi.SetAddress, setAddressApplyCb)
  1977  }
  1978  
  1979  func withdrawRewardValidateCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) error {
  1980  	from := derivedAddressFromTx(tx)
  1981  	_, err := withDrawRewardValidation(from, tx, state, bc)
  1982  	if err != nil {
  1983  		return err
  1984  	}
  1985  
  1986  	return nil
  1987  }
  1988  
  1989  func withdrawRewardApplyCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain, ops *types.PendingOps) error {
  1990  	from := derivedAddressFromTx(tx)
  1991  
  1992  	args, err := withDrawRewardValidation(from, tx, state, bc)
  1993  	if err != nil {
  1994  		return err
  1995  	}
  1996  
  1997  	//reward := state.GetRewardBalanceByDelegateAddress(from, args.DelegateAddress)
  1998  	state.SubRewardBalanceByDelegateAddress(from, args.DelegateAddress, args.Amount)
  1999  	state.AddBalance(from, args.Amount)
  2000  
  2001  	return nil
  2002  }
  2003  
  2004  func withDrawRewardValidation(from common.Address, tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) (*intAbi.WithdrawRewardArgs, error) {
  2005  
  2006  	var args intAbi.WithdrawRewardArgs
  2007  	data := tx.Data()
  2008  	if err := intAbi.ChainABI.UnpackMethodInputs(&args, intAbi.WithdrawReward.String(), data[4:]); err != nil {
  2009  		return nil, err
  2010  	}
  2011  
  2012  	reward := state.GetRewardBalanceByDelegateAddress(from, args.DelegateAddress)
  2013  
  2014  	if reward.Sign() < 1 {
  2015  		return nil, fmt.Errorf("have no reward to withdraw")
  2016  	}
  2017  
  2018  	if args.Amount.Sign() == -1 {
  2019  		return nil, fmt.Errorf("widthdraw amount can not be negative")
  2020  	}
  2021  
  2022  	if args.Amount.Cmp(reward) == 1 {
  2023  		return nil, fmt.Errorf("reward balance not enough, withdraw amount %v, but balance %v, delegate address %v", args.Amount, reward, args.DelegateAddress)
  2024  	}
  2025  	return &args, nil
  2026  }
  2027  
  2028  // register and unregister
  2029  func registerValidateCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) error {
  2030  	from := derivedAddressFromTx(tx)
  2031  	_, verror := registerValidation(from, tx, state, bc)
  2032  	if verror != nil {
  2033  		return verror
  2034  	}
  2035  	return nil
  2036  }
  2037  
  2038  func registerApplyCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain, ops *types.PendingOps) error {
  2039  	// Validate first
  2040  	from := derivedAddressFromTx(tx)
  2041  	args, verror := registerValidation(from, tx, state, bc)
  2042  	if verror != nil {
  2043  		return verror
  2044  	}
  2045  
  2046  	// block height validation
  2047  	verror = updateValidation(bc)
  2048  	if verror != nil {
  2049  		return verror
  2050  	}
  2051  
  2052  	amount := tx.Value()
  2053  	// Add minimum register amount to self
  2054  	state.SubBalance(from, amount)
  2055  	state.AddDelegateBalance(from, amount)
  2056  	state.AddProxiedBalanceByUser(from, from, amount)
  2057  	// Become a Candidate
  2058  
  2059  	var blsPK goCrypto.BLSPubKey
  2060  	copy(blsPK[:], args.Pubkey)
  2061  	if verror != nil {
  2062  		return verror
  2063  	}
  2064  	state.ApplyForCandidate(from, blsPK.KeyString(), args.Commission)
  2065  
  2066  	// mark address candidate
  2067  	//state.MarkAddressCandidate(from)
  2068  
  2069  	verror = updateNextEpochValidatorVoteSet(tx, state, bc, from, ops)
  2070  	if verror != nil {
  2071  		return verror
  2072  	}
  2073  
  2074  	return nil
  2075  }
  2076  
  2077  func registerValidation(from common.Address, tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) (*intAbi.RegisterArgs, error) {
  2078  	//candidateSet := state.GetCandidateSet()
  2079  	//if len(candidateSet) > maxCandidateNumber {
  2080  	//	return nil, core.ErrMaxCandidate
  2081  	//}
  2082  
  2083  	// Check cleaned Candidate
  2084  	if !state.IsCleanAddress(from) {
  2085  		return nil, core.ErrAlreadyCandidate
  2086  	}
  2087  
  2088  	// Check minimum register amount
  2089  	if tx.Value().Cmp(minimumRegisterAmount) == -1 {
  2090  		return nil, core.ErrMinimumRegisterAmount
  2091  	}
  2092  
  2093  	var args intAbi.RegisterArgs
  2094  	data := tx.Data()
  2095  	if err := intAbi.ChainABI.UnpackMethodInputs(&args, intAbi.Register.String(), data[4:]); err != nil {
  2096  		return nil, err
  2097  	}
  2098  
  2099  	if err := goCrypto.CheckConsensusPubKey(from, args.Pubkey, args.Signature); err != nil {
  2100  		return nil, err
  2101  	}
  2102  
  2103  	// Check Commission Range
  2104  	if args.Commission > 100 {
  2105  		return nil, core.ErrCommission
  2106  	}
  2107  
  2108  	// Annual/SemiAnnual supernode can not become candidate
  2109  	var ep *epoch.Epoch
  2110  	if tdm, ok := bc.Engine().(consensus.IPBFT); ok {
  2111  		ep = tdm.GetEpoch().GetEpochByBlockNumber(bc.CurrentBlock().NumberU64())
  2112  	}
  2113  	if _, supernode := ep.Validators.GetByAddress(from.Bytes()); supernode != nil && supernode.RemainingEpoch > 0 {
  2114  		return nil, core.ErrCannotCandidate
  2115  	}
  2116  
  2117  	return &args, nil
  2118  }
  2119  
  2120  func unRegisterValidateCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) error {
  2121  	from := derivedAddressFromTx(tx)
  2122  	verror := unRegisterValidation(from, tx, state, bc)
  2123  	if verror != nil {
  2124  		return verror
  2125  	}
  2126  	return nil
  2127  }
  2128  
  2129  func unRegisterApplyCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain, ops *types.PendingOps) error {
  2130  	// Validate first
  2131  	from := derivedAddressFromTx(tx)
  2132  	verror := unRegisterValidation(from, tx, state, bc)
  2133  	if verror != nil {
  2134  		return verror
  2135  	}
  2136  
  2137  	// Do job
  2138  	allRefund := true
  2139  	// Refund all the amount back to users
  2140  	state.ForEachProxied(from, func(key common.Address, proxiedBalance, depositProxiedBalance, pendingRefundBalance *big.Int) bool {
  2141  		// Refund Proxied Amount
  2142  		state.SubProxiedBalanceByUser(from, key, proxiedBalance)
  2143  		state.SubDelegateBalance(key, proxiedBalance)
  2144  		state.AddBalance(key, proxiedBalance)
  2145  
  2146  		// Refund Deposit to PendingRefund if deposit > 0
  2147  		if depositProxiedBalance.Sign() > 0 {
  2148  			allRefund = false
  2149  			//Calculate the refunding amount user canceled by oneself before
  2150  			refunded := state.GetPendingRefundBalanceByUser(from, key)
  2151  			//Add the rest to refunding balance
  2152  			state.AddPendingRefundBalanceByUser(from, key, new(big.Int).Sub(depositProxiedBalance, refunded))
  2153  			// TODO Add Pending Refund Set, Commit the Refund Set
  2154  			state.MarkDelegateAddressRefund(from)
  2155  		}
  2156  		return true
  2157  	})
  2158  
  2159  	state.CancelCandidate(from, allRefund)
  2160  
  2161  	return nil
  2162  }
  2163  
  2164  func unRegisterValidation(from common.Address, tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) error {
  2165  	// Check already Candidate
  2166  	if !state.IsCandidate(from) {
  2167  		return core.ErrNotCandidate
  2168  	}
  2169  
  2170  	// Forbidden candidate can't unregister
  2171  	//if state.GetForbidden(from) {
  2172  	//	return core.ErrForbiddenUnRegister
  2173  	//}
  2174  
  2175  	// Super node can't unregister
  2176  	var ep *epoch.Epoch
  2177  	if tdm, ok := bc.Engine().(consensus.IPBFT); ok {
  2178  		ep = tdm.GetEpoch().GetEpochByBlockNumber(bc.CurrentBlock().NumberU64())
  2179  	}
  2180  	if _, supernode := ep.Validators.GetByAddress(from.Bytes()); supernode != nil && supernode.RemainingEpoch > 0 {
  2181  		return core.ErrCannotUnRegister
  2182  	}
  2183  
  2184  	// Check Epoch Height
  2185  	if _, err := getEpoch(bc); err != nil {
  2186  		return err
  2187  	}
  2188  
  2189  	return nil
  2190  }
  2191  
  2192  // delegate and unDelegate
  2193  func delegateValidateCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) error {
  2194  	from := derivedAddressFromTx(tx)
  2195  	_, verror := delegateValidation(from, tx, state, bc)
  2196  	if verror != nil {
  2197  		return verror
  2198  	}
  2199  	return nil
  2200  }
  2201  
  2202  func delegateApplyCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain, ops *types.PendingOps) error {
  2203  	// Validate first
  2204  	from := derivedAddressFromTx(tx)
  2205  	args, verror := delegateValidation(from, tx, state, bc)
  2206  	if verror != nil {
  2207  		return verror
  2208  	}
  2209  
  2210  	// block height validation
  2211  	verror = updateValidation(bc)
  2212  	if verror != nil {
  2213  		return verror
  2214  	}
  2215  
  2216  	// Do job
  2217  	amount := tx.Value()
  2218  	// Move Balance to delegate balance
  2219  	state.SubBalance(from, amount)
  2220  	state.AddDelegateBalance(from, amount)
  2221  	// Add Balance to Candidate's Proxied Balance
  2222  	state.AddProxiedBalanceByUser(args.Candidate, from, amount)
  2223  
  2224  	verror = updateNextEpochValidatorVoteSet(tx, state, bc, args.Candidate, ops)
  2225  	if verror != nil {
  2226  		return verror
  2227  	}
  2228  
  2229  	return nil
  2230  }
  2231  
  2232  func delegateValidation(from common.Address, tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) (*intAbi.DelegateArgs, error) {
  2233  	// Check minimum delegate amount
  2234  	if tx.Value().Sign() == -1 {
  2235  		return nil, core.ErrDelegateAmount
  2236  	}
  2237  
  2238  	var args intAbi.DelegateArgs
  2239  	data := tx.Data()
  2240  	if err := intAbi.ChainABI.UnpackMethodInputs(&args, intAbi.Delegate.String(), data[4:]); err != nil {
  2241  		return nil, err
  2242  	}
  2243  
  2244  	// Check Candidate
  2245  	if !state.IsCandidate(args.Candidate) {
  2246  		return nil, core.ErrNotCandidate
  2247  	}
  2248  
  2249  	depositBalance := state.GetDepositProxiedBalanceByUser(args.Candidate, from)
  2250  	if depositBalance.Sign() == 0 {
  2251  		// Check if exceed the limit of delegated addresses
  2252  		// if exceed the limit of delegation address number, return error
  2253  		delegatedAddressNumber := state.GetProxiedAddressNumber(args.Candidate)
  2254  		if delegatedAddressNumber >= maxDelegationAddresses {
  2255  			return nil, core.ErrExceedDelegationAddressLimit
  2256  		}
  2257  	}
  2258  
  2259  	// If Candidate is supernode, only allow to increase the stack(whitelist proxied list), not allow to create the new stack
  2260  	var ep *epoch.Epoch
  2261  	if tdm, ok := bc.Engine().(consensus.IPBFT); ok {
  2262  		ep = tdm.GetEpoch().GetEpochByBlockNumber(bc.CurrentBlock().NumberU64())
  2263  	}
  2264  	if _, supernode := ep.Validators.GetByAddress(args.Candidate.Bytes()); supernode != nil && supernode.RemainingEpoch > 0 {
  2265  		if depositBalance.Sign() == 0 {
  2266  			return nil, core.ErrCannotDelegate
  2267  		}
  2268  	}
  2269  
  2270  	// Check Epoch Height
  2271  	//if _, err := getEpoch(bc); err != nil {
  2272  	//	return nil, err
  2273  	//}
  2274  	return &args, nil
  2275  }
  2276  
  2277  func unDelegateValidateCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) error {
  2278  	from := derivedAddressFromTx(tx)
  2279  	_, verror := unDelegateValidation(from, tx, state, bc)
  2280  	if verror != nil {
  2281  		return verror
  2282  	}
  2283  	return nil
  2284  }
  2285  
  2286  func unDelegateApplyCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain, ops *types.PendingOps) error {
  2287  	// Validate first
  2288  	from := derivedAddressFromTx(tx)
  2289  	args, verror := unDelegateValidation(from, tx, state, bc)
  2290  	if verror != nil {
  2291  		return verror
  2292  	}
  2293  
  2294  	// block height validation
  2295  	verror = updateValidation(bc)
  2296  	if verror != nil {
  2297  		return verror
  2298  	}
  2299  
  2300  	// Apply Logic
  2301  	// if request amount < proxied amount, refund it immediately
  2302  	// otherwise, refund the proxied amount, and put the rest to pending refund balance
  2303  	proxiedBalance := state.GetProxiedBalanceByUser(args.Candidate, from)
  2304  	var immediatelyRefund *big.Int
  2305  	if args.Amount.Cmp(proxiedBalance) <= 0 {
  2306  		immediatelyRefund = args.Amount
  2307  	} else {
  2308  		immediatelyRefund = proxiedBalance
  2309  		restRefund := new(big.Int).Sub(args.Amount, proxiedBalance)
  2310  		state.AddPendingRefundBalanceByUser(args.Candidate, from, restRefund)
  2311  		// TODO Add Pending Refund Set, Commit the Refund Set
  2312  		state.MarkDelegateAddressRefund(args.Candidate)
  2313  	}
  2314  
  2315  	state.SubProxiedBalanceByUser(args.Candidate, from, immediatelyRefund)
  2316  	state.SubDelegateBalance(from, immediatelyRefund)
  2317  	state.AddBalance(from, immediatelyRefund)
  2318  
  2319  	verror = updateNextEpochValidatorVoteSet(tx, state, bc, args.Candidate, ops)
  2320  	if verror != nil {
  2321  		return verror
  2322  	}
  2323  
  2324  	return nil
  2325  }
  2326  
  2327  func unDelegateValidation(from common.Address, tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) (*intAbi.UnDelegateArgs, error) {
  2328  
  2329  	var args intAbi.UnDelegateArgs
  2330  	data := tx.Data()
  2331  	if err := intAbi.ChainABI.UnpackMethodInputs(&args, intAbi.UnDelegate.String(), data[4:]); err != nil {
  2332  		return nil, err
  2333  	}
  2334  
  2335  	if args.Amount.Sign() == -1 {
  2336  		return nil, fmt.Errorf("undelegate amount can not be negative")
  2337  	}
  2338  
  2339  	// Check Self Address
  2340  	if from == args.Candidate {
  2341  		return nil, core.ErrCancelSelfDelegate
  2342  	}
  2343  
  2344  	// Super node Candidate can't decrease balance
  2345  	var ep *epoch.Epoch
  2346  	if tdm, ok := bc.Engine().(consensus.IPBFT); ok {
  2347  		ep = tdm.GetEpoch().GetEpochByBlockNumber(bc.CurrentBlock().NumberU64())
  2348  	}
  2349  	if _, supernode := ep.Validators.GetByAddress(args.Candidate.Bytes()); supernode != nil && supernode.RemainingEpoch > 0 {
  2350  		return nil, core.ErrCannotUnBond
  2351  	}
  2352  
  2353  	// Check Proxied Amount in Candidate Balance
  2354  	proxiedBalance := state.GetProxiedBalanceByUser(args.Candidate, from)
  2355  	depositProxiedBalance := state.GetDepositProxiedBalanceByUser(args.Candidate, from)
  2356  	pendingRefundBalance := state.GetPendingRefundBalanceByUser(args.Candidate, from)
  2357  	// net = deposit - pending refund
  2358  	netDeposit := new(big.Int).Sub(depositProxiedBalance, pendingRefundBalance)
  2359  	// available = proxied + net
  2360  	availableRefundBalance := new(big.Int).Add(proxiedBalance, netDeposit)
  2361  	if args.Amount.Cmp(availableRefundBalance) == 1 {
  2362  		return nil, core.ErrInsufficientProxiedBalance
  2363  	}
  2364  
  2365  	// if left, the left must be greater than the min delegate amount
  2366  	//remainingBalance := new(big.Int).Sub(availableRefundBalance, args.Amount)
  2367  	//if remainingBalance.Sign() == 1 && remainingBalance.Cmp(minimumDelegationAmount) == -1 {
  2368  	//	return nil, core.ErrDelegateAmount
  2369  	//}
  2370  
  2371  	// Check Epoch Height
  2372  	if _, err := getEpoch(bc); err != nil {
  2373  		return nil, err
  2374  	}
  2375  
  2376  	return &args, nil
  2377  }
  2378  
  2379  // set commission
  2380  func setCommisstionValidateCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) error {
  2381  	from := derivedAddressFromTx(tx)
  2382  	_, err := setCommissionValidation(from, tx, state, bc)
  2383  	if err != nil {
  2384  		return err
  2385  	}
  2386  
  2387  	return nil
  2388  }
  2389  
  2390  func setCommisstionApplyCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain, ops *types.PendingOps) error {
  2391  	from := derivedAddressFromTx(tx)
  2392  	args, err := setCommissionValidation(from, tx, state, bc)
  2393  	if err != nil {
  2394  		return err
  2395  	}
  2396  
  2397  	state.SetCommission(from, args.Commission)
  2398  
  2399  	return nil
  2400  }
  2401  
  2402  func setCommissionValidation(from common.Address, tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) (*intAbi.SetCommissionArgs, error) {
  2403  	if !state.IsCandidate(from) {
  2404  		return nil, core.ErrNotCandidate
  2405  	}
  2406  
  2407  	var args intAbi.SetCommissionArgs
  2408  	data := tx.Data()
  2409  	if err := intAbi.ChainABI.UnpackMethodInputs(&args, intAbi.SetCommission.String(), data[4:]); err != nil {
  2410  		return nil, err
  2411  	}
  2412  
  2413  	if args.Commission > 100 {
  2414  		return nil, core.ErrCommission
  2415  	}
  2416  
  2417  	return &args, nil
  2418  }
  2419  
  2420  func setAddressValidateCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) error {
  2421  	from := derivedAddressFromTx(tx)
  2422  	_, err := setAddressValidation(from, tx, state, bc)
  2423  	if err != nil {
  2424  		return err
  2425  	}
  2426  
  2427  	return nil
  2428  }
  2429  
  2430  func setAddressApplyCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain, ops *types.PendingOps) error {
  2431  	from := derivedAddressFromTx(tx)
  2432  	args, err := setAddressValidation(from, tx, state, bc)
  2433  	if err != nil {
  2434  		return err
  2435  	}
  2436  
  2437  	state.SetAddress(from, args.FAddress)
  2438  
  2439  	return nil
  2440  }
  2441  
  2442  func setAddressValidation(from common.Address, tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) (*intAbi.SetAddressArgs, error) {
  2443  	var args intAbi.SetAddressArgs
  2444  	data := tx.Data()
  2445  	if err := intAbi.ChainABI.UnpackMethodInputs(&args, intAbi.SetAddress.String(), data[4:]); err != nil {
  2446  		return nil, err
  2447  	}
  2448  
  2449  	return &args, nil
  2450  }
  2451  
  2452  func editValidatorValidateCb(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain) error {
  2453  	from := derivedAddressFromTx(tx)
  2454  	if !state.IsCandidate(from) {
  2455  		return errors.New("you are not a validator or candidate")
  2456  	}
  2457  
  2458  	var args intAbi.EditValidatorArgs
  2459  	data := tx.Data()
  2460  	if err := intAbi.ChainABI.UnpackMethodInputs(&args, intAbi.EditValidator.String(), data[4:]); err != nil {
  2461  		return err
  2462  	}
  2463  
  2464  	if len([]byte(args.Details)) > maxEditValidatorLength ||
  2465  		len([]byte(args.Identity)) > maxEditValidatorLength ||
  2466  		len([]byte(args.Moniker)) > maxEditValidatorLength ||
  2467  		len([]byte(args.Website)) > maxEditValidatorLength {
  2468  		//fmt.Printf("args details length %v, identity length %v, moniker lenth %v, website length %v\n", len([]byte(args.Details)),len([]byte(args.Identity)),len([]byte(args.Moniker)),len([]byte(args.Website)))
  2469  		return fmt.Errorf("args length too long, more than %v", maxEditValidatorLength)
  2470  	}
  2471  
  2472  	return nil
  2473  }
  2474  
  2475  func concatCopyPreAllocate(slices [][]byte) []byte {
  2476  	var totalLen int
  2477  	for _, s := range slices {
  2478  		totalLen += len(s)
  2479  	}
  2480  	tmp := make([]byte, totalLen)
  2481  	var i int
  2482  	for _, s := range slices {
  2483  		i += copy(tmp[i:], s)
  2484  	}
  2485  	return tmp
  2486  }
  2487  
  2488  func getEpoch(bc *core.BlockChain) (*epoch.Epoch, error) {
  2489  	var ep *epoch.Epoch
  2490  	if tdm, ok := bc.Engine().(consensus.IPBFT); ok {
  2491  		ep = tdm.GetEpoch().GetEpochByBlockNumber(bc.CurrentBlock().NumberU64())
  2492  	}
  2493  
  2494  	if ep == nil {
  2495  		return nil, errors.New("epoch is nil, are you running on IPBFT Consensus Engine")
  2496  	}
  2497  
  2498  	return ep, nil
  2499  }
  2500  
  2501  func derivedAddressFromTx(tx *types.Transaction) (from common.Address) {
  2502  	signer := types.NewEIP155Signer(tx.ChainId())
  2503  	from, _ = types.Sender(signer, tx)
  2504  	return
  2505  }
  2506  
  2507  func updateValidation(bc *core.BlockChain) error {
  2508  	ep, err := getEpoch(bc)
  2509  	if err != nil {
  2510  		return err
  2511  	}
  2512  
  2513  	currHeight := bc.CurrentBlock().NumberU64()
  2514  
  2515  	if currHeight <= ep.StartBlock+2 || currHeight == ep.EndBlock {
  2516  		return errors.New("incorrect block height, please retry later")
  2517  	}
  2518  
  2519  	return nil
  2520  }
  2521  
  2522  func updateNextEpochValidatorVoteSet(tx *types.Transaction, state *state.StateDB, bc *core.BlockChain, candidate common.Address, ops *types.PendingOps) error {
  2523  	var update bool
  2524  	ep, err := getEpoch(bc)
  2525  	if err != nil {
  2526  		return err
  2527  	}
  2528  
  2529  	// calculate the net proxied balance of this candidate
  2530  	proxiedBalance := state.GetTotalProxiedBalance(candidate)
  2531  	depositProxiedBalance := state.GetTotalDepositProxiedBalance(candidate)
  2532  	pendingRefundBalance := state.GetTotalPendingRefundBalance(candidate)
  2533  	netProxied := new(big.Int).Sub(new(big.Int).Add(proxiedBalance, depositProxiedBalance), pendingRefundBalance)
  2534  
  2535  	if netProxied.Sign() == -1 {
  2536  		return errors.New("validator voting power can not be negative")
  2537  	}
  2538  
  2539  	//fmt.Printf("update next epoch voteset %v\n", ep.GetEpochValidatorVoteSet())
  2540  	currentEpochVoteSet := ep.GetEpochValidatorVoteSet()
  2541  	//fmt.Printf("update next epoch current epoch voteset %v\n", ep.GetEpochValidatorVoteSet())
  2542  
  2543  	// whether update next epoch vote set
  2544  	if currentEpochVoteSet == nil {
  2545  		update = true
  2546  	} else {
  2547  		// if current validator size bigger than updateValidatorThreshold and the netProxied is bigger then one of the current validator voting power
  2548  		if len(currentEpochVoteSet.Votes) >= updateValidatorThreshold {
  2549  			for _, val := range currentEpochVoteSet.Votes {
  2550  				// TODO whether need compare
  2551  				if val.Amount.Cmp(netProxied) == -1 {
  2552  					update = true
  2553  					break
  2554  				}
  2555  			}
  2556  		} else {
  2557  			update = true
  2558  		}
  2559  	}
  2560  
  2561  	// update is true and the address is candidate, then update next epoch validator vote set
  2562  	if update && state.IsCandidate(candidate) {
  2563  		// no need move
  2564  		// Move delegate amount first if Candidate
  2565  		//state.ForEachProxied(candidate, func(key common.Address, proxiedBalance, depositProxiedBalance, pendingRefundBalance *big.Int) bool {
  2566  		//	// Move Proxied Amount to Deposit Proxied Amount
  2567  		//	state.SubProxiedBalanceByUser(candidate, key, proxiedBalance)
  2568  		//	state.AddDepositProxiedBalanceByUser(candidate, key, proxiedBalance)
  2569  		//	return true
  2570  		//})
  2571  
  2572  		var pubkey string
  2573  		pubkey = state.GetPubkey(candidate)
  2574  		pubkeyBytes := common.FromHex(pubkey)
  2575  		if pubkey == "" || len(pubkeyBytes) != 128 {
  2576  			return errors.New("wrong format of required field 'pub_key'")
  2577  		}
  2578  		var blsPK goCrypto.BLSPubKey
  2579  		copy(blsPK[:], pubkeyBytes)
  2580  
  2581  		op := types.UpdateNextEpochOp{
  2582  			From:   candidate,
  2583  			PubKey: blsPK,
  2584  			Amount: netProxied,
  2585  			Salt:   "intchain",
  2586  			TxHash: tx.Hash(),
  2587  		}
  2588  
  2589  		if ok := ops.Append(&op); !ok {
  2590  			return fmt.Errorf("pending ops conflict: %v", op)
  2591  		}
  2592  	}
  2593  
  2594  	return nil
  2595  }