github.com/theQRL/go-zond@v0.2.1/internal/zondapi/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 zondapi
    18  
    19  import (
    20  	"context"
    21  	"encoding/hex"
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  	"strings"
    26  	"time"
    27  
    28  	"github.com/davecgh/go-spew/spew"
    29  	"github.com/theQRL/go-zond/accounts"
    30  	"github.com/theQRL/go-zond/accounts/abi"
    31  	"github.com/theQRL/go-zond/common"
    32  	"github.com/theQRL/go-zond/common/hexutil"
    33  	"github.com/theQRL/go-zond/common/math"
    34  	"github.com/theQRL/go-zond/consensus"
    35  	"github.com/theQRL/go-zond/consensus/misc/eip1559"
    36  	"github.com/theQRL/go-zond/core"
    37  	"github.com/theQRL/go-zond/core/state"
    38  	"github.com/theQRL/go-zond/core/types"
    39  	"github.com/theQRL/go-zond/core/vm"
    40  	"github.com/theQRL/go-zond/crypto"
    41  	"github.com/theQRL/go-zond/log"
    42  	"github.com/theQRL/go-zond/p2p"
    43  	"github.com/theQRL/go-zond/params"
    44  	"github.com/theQRL/go-zond/rlp"
    45  	"github.com/theQRL/go-zond/rpc"
    46  	"github.com/theQRL/go-zond/trie"
    47  	"github.com/theQRL/go-zond/zond/tracers/logger"
    48  )
    49  
    50  // ZondAPI provides an API to access Zond related information.
    51  type ZondAPI struct {
    52  	b Backend
    53  }
    54  
    55  // NewZondAPI creates a new Zond protocol API.
    56  func NewZondAPI(b Backend) *ZondAPI {
    57  	return &ZondAPI{b}
    58  }
    59  
    60  // GasPrice returns a suggestion for a gas price for legacy transactions.
    61  func (s *ZondAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
    62  	tipcap, err := s.b.SuggestGasTipCap(ctx)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  	if head := s.b.CurrentHeader(); head.BaseFee != nil {
    67  		tipcap.Add(tipcap, head.BaseFee)
    68  	}
    69  	return (*hexutil.Big)(tipcap), err
    70  }
    71  
    72  // MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic fee transactions.
    73  func (s *ZondAPI) MaxPriorityFeePerGas(ctx context.Context) (*hexutil.Big, error) {
    74  	tipcap, err := s.b.SuggestGasTipCap(ctx)
    75  	if err != nil {
    76  		return nil, err
    77  	}
    78  	return (*hexutil.Big)(tipcap), err
    79  }
    80  
    81  type feeHistoryResult struct {
    82  	OldestBlock  *hexutil.Big     `json:"oldestBlock"`
    83  	Reward       [][]*hexutil.Big `json:"reward,omitempty"`
    84  	BaseFee      []*hexutil.Big   `json:"baseFeePerGas,omitempty"`
    85  	GasUsedRatio []float64        `json:"gasUsedRatio"`
    86  }
    87  
    88  // FeeHistory returns the fee market history.
    89  func (s *ZondAPI) FeeHistory(ctx context.Context, blockCount math.HexOrDecimal64, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*feeHistoryResult, error) {
    90  	oldest, reward, baseFee, gasUsed, err := s.b.FeeHistory(ctx, uint64(blockCount), lastBlock, rewardPercentiles)
    91  	if err != nil {
    92  		return nil, err
    93  	}
    94  	results := &feeHistoryResult{
    95  		OldestBlock:  (*hexutil.Big)(oldest),
    96  		GasUsedRatio: gasUsed,
    97  	}
    98  	if reward != nil {
    99  		results.Reward = make([][]*hexutil.Big, len(reward))
   100  		for i, w := range reward {
   101  			results.Reward[i] = make([]*hexutil.Big, len(w))
   102  			for j, v := range w {
   103  				results.Reward[i][j] = (*hexutil.Big)(v)
   104  			}
   105  		}
   106  	}
   107  	if baseFee != nil {
   108  		results.BaseFee = make([]*hexutil.Big, len(baseFee))
   109  		for i, v := range baseFee {
   110  			results.BaseFee[i] = (*hexutil.Big)(v)
   111  		}
   112  	}
   113  	return results, nil
   114  }
   115  
   116  // Syncing returns false in case the node is currently not syncing with the network. It can be up-to-date or has not
   117  // yet received the latest block headers from its pears. In case it is synchronizing:
   118  // - startingBlock: block number this node started to synchronize from
   119  // - currentBlock:  block number this node is currently importing
   120  // - highestBlock:  block number of the highest block header this node has received from peers
   121  // - pulledStates:  number of state entries processed until now
   122  // - knownStates:   number of known state entries that still need to be pulled
   123  func (s *ZondAPI) Syncing() (interface{}, error) {
   124  	progress := s.b.SyncProgress()
   125  
   126  	// Return not syncing if the synchronisation already completed
   127  	if progress.CurrentBlock >= progress.HighestBlock {
   128  		return false, nil
   129  	}
   130  	// Otherwise gather the block sync stats
   131  	return map[string]interface{}{
   132  		"startingBlock":       hexutil.Uint64(progress.StartingBlock),
   133  		"currentBlock":        hexutil.Uint64(progress.CurrentBlock),
   134  		"highestBlock":        hexutil.Uint64(progress.HighestBlock),
   135  		"syncedAccounts":      hexutil.Uint64(progress.SyncedAccounts),
   136  		"syncedAccountBytes":  hexutil.Uint64(progress.SyncedAccountBytes),
   137  		"syncedBytecodes":     hexutil.Uint64(progress.SyncedBytecodes),
   138  		"syncedBytecodeBytes": hexutil.Uint64(progress.SyncedBytecodeBytes),
   139  		"syncedStorage":       hexutil.Uint64(progress.SyncedStorage),
   140  		"syncedStorageBytes":  hexutil.Uint64(progress.SyncedStorageBytes),
   141  		"healedTrienodes":     hexutil.Uint64(progress.HealedTrienodes),
   142  		"healedTrienodeBytes": hexutil.Uint64(progress.HealedTrienodeBytes),
   143  		"healedBytecodes":     hexutil.Uint64(progress.HealedBytecodes),
   144  		"healedBytecodeBytes": hexutil.Uint64(progress.HealedBytecodeBytes),
   145  		"healingTrienodes":    hexutil.Uint64(progress.HealingTrienodes),
   146  		"healingBytecode":     hexutil.Uint64(progress.HealingBytecode),
   147  	}, nil
   148  }
   149  
   150  // TxPoolAPI offers and API for the transaction pool. It only operates on data that is non-confidential.
   151  type TxPoolAPI struct {
   152  	b Backend
   153  }
   154  
   155  // NewTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
   156  func NewTxPoolAPI(b Backend) *TxPoolAPI {
   157  	return &TxPoolAPI{b}
   158  }
   159  
   160  // Content returns the transactions contained within the transaction pool.
   161  func (s *TxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
   162  	content := map[string]map[string]map[string]*RPCTransaction{
   163  		"pending": make(map[string]map[string]*RPCTransaction),
   164  		"queued":  make(map[string]map[string]*RPCTransaction),
   165  	}
   166  	pending, queue := s.b.TxPoolContent()
   167  	curHeader := s.b.CurrentHeader()
   168  	// Flatten the pending transactions
   169  	for account, txs := range pending {
   170  		dump := make(map[string]*RPCTransaction)
   171  		for _, tx := range txs {
   172  			dump[fmt.Sprintf("%d", tx.Nonce())] = NewRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
   173  		}
   174  		content["pending"][account.Hex()] = dump
   175  	}
   176  	// Flatten the queued transactions
   177  	for account, txs := range queue {
   178  		dump := make(map[string]*RPCTransaction)
   179  		for _, tx := range txs {
   180  			dump[fmt.Sprintf("%d", tx.Nonce())] = NewRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
   181  		}
   182  		content["queued"][account.Hex()] = dump
   183  	}
   184  	return content
   185  }
   186  
   187  // ContentFrom returns the transactions contained within the transaction pool.
   188  func (s *TxPoolAPI) ContentFrom(addr common.Address) map[string]map[string]*RPCTransaction {
   189  	content := make(map[string]map[string]*RPCTransaction, 2)
   190  	pending, queue := s.b.TxPoolContentFrom(addr)
   191  	curHeader := s.b.CurrentHeader()
   192  
   193  	// Build the pending transactions
   194  	dump := make(map[string]*RPCTransaction, len(pending))
   195  	for _, tx := range pending {
   196  		dump[fmt.Sprintf("%d", tx.Nonce())] = NewRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
   197  	}
   198  	content["pending"] = dump
   199  
   200  	// Build the queued transactions
   201  	dump = make(map[string]*RPCTransaction, len(queue))
   202  	for _, tx := range queue {
   203  		dump[fmt.Sprintf("%d", tx.Nonce())] = NewRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
   204  	}
   205  	content["queued"] = dump
   206  
   207  	return content
   208  }
   209  
   210  // Status returns the number of pending and queued transaction in the pool.
   211  func (s *TxPoolAPI) Status() map[string]hexutil.Uint {
   212  	pending, queue := s.b.Stats()
   213  	return map[string]hexutil.Uint{
   214  		"pending": hexutil.Uint(pending),
   215  		"queued":  hexutil.Uint(queue),
   216  	}
   217  }
   218  
   219  // Inspect retrieves the content of the transaction pool and flattens it into an
   220  // easily inspectable list.
   221  func (s *TxPoolAPI) Inspect() map[string]map[string]map[string]string {
   222  	content := map[string]map[string]map[string]string{
   223  		"pending": make(map[string]map[string]string),
   224  		"queued":  make(map[string]map[string]string),
   225  	}
   226  	pending, queue := s.b.TxPoolContent()
   227  
   228  	// Define a formatter to flatten a transaction into a string
   229  	var format = func(tx *types.Transaction) string {
   230  		if to := tx.To(); to != nil {
   231  			return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
   232  		}
   233  		return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice())
   234  	}
   235  	// Flatten the pending transactions
   236  	for account, txs := range pending {
   237  		dump := make(map[string]string)
   238  		for _, tx := range txs {
   239  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   240  		}
   241  		content["pending"][account.Hex()] = dump
   242  	}
   243  	// Flatten the queued transactions
   244  	for account, txs := range queue {
   245  		dump := make(map[string]string)
   246  		for _, tx := range txs {
   247  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   248  		}
   249  		content["queued"][account.Hex()] = dump
   250  	}
   251  	return content
   252  }
   253  
   254  // EthereumAccountAPI provides an API to access accounts managed by this node.
   255  // It offers only methods that can retrieve accounts.
   256  type EthereumAccountAPI struct {
   257  	am *accounts.Manager
   258  }
   259  
   260  // NewEthereumAccountAPI creates a new EthereumAccountAPI.
   261  func NewEthereumAccountAPI(am *accounts.Manager) *EthereumAccountAPI {
   262  	return &EthereumAccountAPI{am: am}
   263  }
   264  
   265  // Accounts returns the collection of accounts this node manages.
   266  func (s *EthereumAccountAPI) Accounts() []common.Address {
   267  	return s.am.Accounts()
   268  }
   269  
   270  // BlockChainAPI provides an API to access Zond blockchain data.
   271  type BlockChainAPI struct {
   272  	b Backend
   273  }
   274  
   275  // NewBlockChainAPI creates a new Zond blockchain API.
   276  func NewBlockChainAPI(b Backend) *BlockChainAPI {
   277  	return &BlockChainAPI{b}
   278  }
   279  
   280  // ChainId is the EIP-155 replay-protection chain id for the current Zond chain config.
   281  //
   282  // Note, this method does not conform to EIP-695 because the configured chain ID is always
   283  // returned, regardless of the current head block. We used to return an error when the chain
   284  // wasn't synced up to a block where EIP-155 is enabled, but this behavior caused issues
   285  // in CL clients.
   286  func (api *BlockChainAPI) ChainId() *hexutil.Big {
   287  	return (*hexutil.Big)(api.b.ChainConfig().ChainID)
   288  }
   289  
   290  // BlockNumber returns the block number of the chain head.
   291  func (s *BlockChainAPI) BlockNumber() hexutil.Uint64 {
   292  	header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
   293  	return hexutil.Uint64(header.Number.Uint64())
   294  }
   295  
   296  // GetBalance returns the amount of wei for the given address in the state of the
   297  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   298  // block numbers are also allowed.
   299  func (s *BlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
   300  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   301  	if state == nil || err != nil {
   302  		return nil, err
   303  	}
   304  	return (*hexutil.Big)(state.GetBalance(address)), state.Error()
   305  }
   306  
   307  // Result structs for GetProof
   308  type AccountResult struct {
   309  	Address      common.Address  `json:"address"`
   310  	AccountProof []string        `json:"accountProof"`
   311  	Balance      *hexutil.Big    `json:"balance"`
   312  	CodeHash     common.Hash     `json:"codeHash"`
   313  	Nonce        hexutil.Uint64  `json:"nonce"`
   314  	StorageHash  common.Hash     `json:"storageHash"`
   315  	StorageProof []StorageResult `json:"storageProof"`
   316  }
   317  
   318  type StorageResult struct {
   319  	Key   string       `json:"key"`
   320  	Value *hexutil.Big `json:"value"`
   321  	Proof []string     `json:"proof"`
   322  }
   323  
   324  // proofList implements zonddb.KeyValueWriter and collects the proofs as
   325  // hex-strings for delivery to rpc-caller.
   326  type proofList []string
   327  
   328  func (n *proofList) Put(key []byte, value []byte) error {
   329  	*n = append(*n, hexutil.Encode(value))
   330  	return nil
   331  }
   332  
   333  func (n *proofList) Delete(key []byte) error {
   334  	panic("not supported")
   335  }
   336  
   337  // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
   338  func (s *BlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
   339  	var (
   340  		keys         = make([]common.Hash, len(storageKeys))
   341  		keyLengths   = make([]int, len(storageKeys))
   342  		storageProof = make([]StorageResult, len(storageKeys))
   343  	)
   344  	// Deserialize all keys. This prevents state access on invalid input.
   345  	for i, hexKey := range storageKeys {
   346  		var err error
   347  		keys[i], keyLengths[i], err = decodeHash(hexKey)
   348  		if err != nil {
   349  			return nil, err
   350  		}
   351  	}
   352  	statedb, header, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   353  	if statedb == nil || err != nil {
   354  		return nil, err
   355  	}
   356  	codeHash := statedb.GetCodeHash(address)
   357  	storageRoot := statedb.GetStorageRoot(address)
   358  
   359  	if len(keys) > 0 {
   360  		var storageTrie state.Trie
   361  		if storageRoot != types.EmptyRootHash && storageRoot != (common.Hash{}) {
   362  			id := trie.StorageTrieID(header.Root, crypto.Keccak256Hash(address.Bytes()), storageRoot)
   363  			st, err := trie.NewStateTrie(id, statedb.Database().TrieDB())
   364  			if err != nil {
   365  				return nil, err
   366  			}
   367  			storageTrie = st
   368  		}
   369  		// Create the proofs for the storageKeys.
   370  		for i, key := range keys {
   371  			// Output key encoding is a bit special: if the input was a 32-byte hash, it is
   372  			// returned as such. Otherwise, we apply the QUANTITY encoding mandated by the
   373  			// JSON-RPC spec for getProof. This behavior exists to preserve backwards
   374  			// compatibility with older client versions.
   375  			var outputKey string
   376  			if keyLengths[i] != 32 {
   377  				outputKey = hexutil.EncodeBig(key.Big())
   378  			} else {
   379  				outputKey = hexutil.Encode(key[:])
   380  			}
   381  			if storageTrie == nil {
   382  				storageProof[i] = StorageResult{outputKey, &hexutil.Big{}, []string{}}
   383  				continue
   384  			}
   385  			var proof proofList
   386  			if err := storageTrie.Prove(crypto.Keccak256(key.Bytes()), &proof); err != nil {
   387  				return nil, err
   388  			}
   389  			value := (*hexutil.Big)(statedb.GetState(address, key).Big())
   390  			storageProof[i] = StorageResult{outputKey, value, proof}
   391  		}
   392  	}
   393  
   394  	// Create the accountProof.
   395  	tr, err := trie.NewStateTrie(trie.StateTrieID(header.Root), statedb.Database().TrieDB())
   396  	if err != nil {
   397  		return nil, err
   398  	}
   399  	var accountProof proofList
   400  	if err := tr.Prove(crypto.Keccak256(address.Bytes()), &accountProof); err != nil {
   401  		return nil, err
   402  	}
   403  	return &AccountResult{
   404  		Address:      address,
   405  		AccountProof: accountProof,
   406  		Balance:      (*hexutil.Big)(statedb.GetBalance(address)),
   407  		CodeHash:     codeHash,
   408  		Nonce:        hexutil.Uint64(statedb.GetNonce(address)),
   409  		StorageHash:  storageRoot,
   410  		StorageProof: storageProof,
   411  	}, statedb.Error()
   412  }
   413  
   414  // decodeHash parses a hex-encoded 32-byte hash. The input may optionally
   415  // be prefixed by 0x and can have a byte length up to 32.
   416  func decodeHash(s string) (h common.Hash, inputLength int, err error) {
   417  	if strings.HasPrefix(s, "0x") || strings.HasPrefix(s, "0X") {
   418  		s = s[2:]
   419  	}
   420  	if (len(s) & 1) > 0 {
   421  		s = "0" + s
   422  	}
   423  	b, err := hex.DecodeString(s)
   424  	if err != nil {
   425  		return common.Hash{}, 0, errors.New("hex string invalid")
   426  	}
   427  	if len(b) > 32 {
   428  		return common.Hash{}, len(b), errors.New("hex string too long, want at most 32 bytes")
   429  	}
   430  	return common.BytesToHash(b), len(b), nil
   431  }
   432  
   433  // GetHeaderByNumber returns the requested canonical block header.
   434  //   - When blockNr is -1 the chain pending header is returned.
   435  //   - When blockNr is -2 the chain latest header is returned.
   436  //   - When blockNr is -3 the chain finalized header is returned.
   437  //   - When blockNr is -4 the chain safe header is returned.
   438  func (s *BlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
   439  	header, err := s.b.HeaderByNumber(ctx, number)
   440  	if header != nil && err == nil {
   441  		response := s.rpcMarshalHeader(header)
   442  		if number == rpc.PendingBlockNumber {
   443  			// Pending header need to nil out a few fields
   444  			for _, field := range []string{"hash", "miner"} {
   445  				response[field] = nil
   446  			}
   447  		}
   448  		return response, err
   449  	}
   450  	return nil, err
   451  }
   452  
   453  // GetHeaderByHash returns the requested header by hash.
   454  func (s *BlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
   455  	header, _ := s.b.HeaderByHash(ctx, hash)
   456  	if header != nil {
   457  		return s.rpcMarshalHeader(header)
   458  	}
   459  	return nil
   460  }
   461  
   462  // GetBlockByNumber returns the requested canonical block.
   463  //   - When blockNr is -1 the chain pending block is returned.
   464  //   - When blockNr is -2 the chain latest block is returned.
   465  //   - When blockNr is -3 the chain finalized block is returned.
   466  //   - When blockNr is -4 the chain safe block is returned.
   467  //   - When fullTx is true all transactions in the block are returned, otherwise
   468  //     only the transaction hash is returned.
   469  func (s *BlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
   470  	block, err := s.b.BlockByNumber(ctx, number)
   471  	if block != nil && err == nil {
   472  		response, err := s.rpcMarshalBlock(block, true, fullTx)
   473  		if err == nil && number == rpc.PendingBlockNumber {
   474  			// Pending blocks need to nil out a few fields
   475  			for _, field := range []string{"hash", "miner"} {
   476  				response[field] = nil
   477  			}
   478  		}
   479  		return response, err
   480  	}
   481  	return nil, err
   482  }
   483  
   484  // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
   485  // detail, otherwise only the transaction hash is returned.
   486  func (s *BlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
   487  	block, err := s.b.BlockByHash(ctx, hash)
   488  	if block != nil {
   489  		return s.rpcMarshalBlock(block, true, fullTx)
   490  	}
   491  	return nil, err
   492  }
   493  
   494  // GetCode returns the code stored at the given address in the state for the given block number.
   495  func (s *BlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   496  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   497  	if state == nil || err != nil {
   498  		return nil, err
   499  	}
   500  	code := state.GetCode(address)
   501  	return code, state.Error()
   502  }
   503  
   504  // GetStorageAt returns the storage from the state at the given address, key and
   505  // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
   506  // numbers are also allowed.
   507  func (s *BlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, hexKey string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   508  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   509  	if state == nil || err != nil {
   510  		return nil, err
   511  	}
   512  	key, _, err := decodeHash(hexKey)
   513  	if err != nil {
   514  		return nil, fmt.Errorf("unable to decode storage key: %s", err)
   515  	}
   516  	res := state.GetState(address, key)
   517  	return res[:], state.Error()
   518  }
   519  
   520  // GetBlockReceipts returns the block receipts for the given block hash or number or tag.
   521  func (s *BlockChainAPI) GetBlockReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]map[string]interface{}, error) {
   522  	block, err := s.b.BlockByNumberOrHash(ctx, blockNrOrHash)
   523  	if block == nil || err != nil {
   524  		// When the block doesn't exist, the RPC method should return JSON null
   525  		// as per specification.
   526  		return nil, nil
   527  	}
   528  	receipts, err := s.b.GetReceipts(ctx, block.Hash())
   529  	if err != nil {
   530  		return nil, err
   531  	}
   532  	txs := block.Transactions()
   533  	if len(txs) != len(receipts) {
   534  		return nil, fmt.Errorf("receipts length mismatch: %d vs %d", len(txs), len(receipts))
   535  	}
   536  
   537  	// Derive the sender.
   538  	signer := types.MakeSigner(s.b.ChainConfig())
   539  
   540  	result := make([]map[string]interface{}, len(receipts))
   541  	for i, receipt := range receipts {
   542  		result[i] = marshalReceipt(receipt, block.Hash(), block.NumberU64(), signer, txs[i], i)
   543  	}
   544  
   545  	return result, nil
   546  }
   547  
   548  // OverrideAccount indicates the overriding fields of account during the execution
   549  // of a message call.
   550  // Note, state and stateDiff can't be specified at the same time. If state is
   551  // set, message execution will only use the data in the given state. Otherwise
   552  // if statDiff is set, all diff will be applied first and then execute the call
   553  // message.
   554  type OverrideAccount struct {
   555  	Nonce     *hexutil.Uint64              `json:"nonce"`
   556  	Code      *hexutil.Bytes               `json:"code"`
   557  	Balance   **hexutil.Big                `json:"balance"`
   558  	State     *map[common.Hash]common.Hash `json:"state"`
   559  	StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
   560  }
   561  
   562  // StateOverride is the collection of overridden accounts.
   563  type StateOverride map[common.Address]OverrideAccount
   564  
   565  // Apply overrides the fields of specified accounts into the given state.
   566  func (diff *StateOverride) Apply(state *state.StateDB) error {
   567  	if diff == nil {
   568  		return nil
   569  	}
   570  	for addr, account := range *diff {
   571  		// Override account nonce.
   572  		if account.Nonce != nil {
   573  			state.SetNonce(addr, uint64(*account.Nonce))
   574  		}
   575  		// Override account(contract) code.
   576  		if account.Code != nil {
   577  			state.SetCode(addr, *account.Code)
   578  		}
   579  		// Override account balance.
   580  		if account.Balance != nil {
   581  			state.SetBalance(addr, (*big.Int)(*account.Balance))
   582  		}
   583  		if account.State != nil && account.StateDiff != nil {
   584  			return fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
   585  		}
   586  		// Replace entire state if caller requires.
   587  		if account.State != nil {
   588  			state.SetStorage(addr, *account.State)
   589  		}
   590  		// Apply state diff into specified accounts.
   591  		if account.StateDiff != nil {
   592  			for key, value := range *account.StateDiff {
   593  				state.SetState(addr, key, value)
   594  			}
   595  		}
   596  	}
   597  	// Now finalize the changes. Finalize is normally performed between transactions.
   598  	// By using finalize, the overrides are semantically behaving as
   599  	// if they were created in a transaction just before the tracing occur.
   600  	state.Finalise(false)
   601  	return nil
   602  }
   603  
   604  // BlockOverrides is a set of header fields to override.
   605  type BlockOverrides struct {
   606  	Number   *hexutil.Big
   607  	Time     *hexutil.Uint64
   608  	GasLimit *hexutil.Uint64
   609  	Coinbase *common.Address
   610  	Random   *common.Hash
   611  	BaseFee  *hexutil.Big
   612  }
   613  
   614  // Apply overrides the given header fields into the given block context.
   615  func (diff *BlockOverrides) Apply(blockCtx *vm.BlockContext) {
   616  	if diff == nil {
   617  		return
   618  	}
   619  	if diff.Number != nil {
   620  		blockCtx.BlockNumber = diff.Number.ToInt()
   621  	}
   622  	if diff.Time != nil {
   623  		blockCtx.Time = uint64(*diff.Time)
   624  	}
   625  	if diff.GasLimit != nil {
   626  		blockCtx.GasLimit = uint64(*diff.GasLimit)
   627  	}
   628  	if diff.Coinbase != nil {
   629  		blockCtx.Coinbase = *diff.Coinbase
   630  	}
   631  	if diff.Random != nil {
   632  		blockCtx.Random = diff.Random
   633  	}
   634  	if diff.BaseFee != nil {
   635  		blockCtx.BaseFee = diff.BaseFee.ToInt()
   636  	}
   637  }
   638  
   639  // ChainContextBackend provides methods required to implement ChainContext.
   640  type ChainContextBackend interface {
   641  	Engine() consensus.Engine
   642  	HeaderByNumber(context.Context, rpc.BlockNumber) (*types.Header, error)
   643  }
   644  
   645  // ChainContext is an implementation of core.ChainContext. It's main use-case
   646  // is instantiating a vm.BlockContext without having access to the BlockChain object.
   647  type ChainContext struct {
   648  	b   ChainContextBackend
   649  	ctx context.Context
   650  }
   651  
   652  // NewChainContext creates a new ChainContext object.
   653  func NewChainContext(ctx context.Context, backend ChainContextBackend) *ChainContext {
   654  	return &ChainContext{ctx: ctx, b: backend}
   655  }
   656  
   657  func (context *ChainContext) Engine() consensus.Engine {
   658  	return context.b.Engine()
   659  }
   660  
   661  func (context *ChainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
   662  	// This method is called to get the hash for a block number when executing the BLOCKHASH
   663  	// opcode. Hence no need to search for non-canonical blocks.
   664  	header, err := context.b.HeaderByNumber(context.ctx, rpc.BlockNumber(number))
   665  	if err != nil || header.Hash() != hash {
   666  		return nil
   667  	}
   668  	return header
   669  }
   670  
   671  func doCall(ctx context.Context, b Backend, args TransactionArgs, state *state.StateDB, header *types.Header, overrides *StateOverride, blockOverrides *BlockOverrides, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
   672  	if err := overrides.Apply(state); err != nil {
   673  		return nil, err
   674  	}
   675  	// Setup context so it may be cancelled the call has completed
   676  	// or, in case of unmetered gas, setup a context with a timeout.
   677  	var cancel context.CancelFunc
   678  	if timeout > 0 {
   679  		ctx, cancel = context.WithTimeout(ctx, timeout)
   680  	} else {
   681  		ctx, cancel = context.WithCancel(ctx)
   682  	}
   683  	// Make sure the context is cancelled when the call has completed
   684  	// this makes sure resources are cleaned up.
   685  	defer cancel()
   686  
   687  	// Get a new instance of the ZVM.
   688  	msg, err := args.ToMessage(globalGasCap, header.BaseFee)
   689  	if err != nil {
   690  		return nil, err
   691  	}
   692  	blockCtx := core.NewZVMBlockContext(header, NewChainContext(ctx, b), nil)
   693  	if blockOverrides != nil {
   694  		blockOverrides.Apply(&blockCtx)
   695  	}
   696  	zvm := b.GetZVM(ctx, msg, state, header, &vm.Config{NoBaseFee: true}, &blockCtx)
   697  
   698  	// Wait for the context to be done and cancel the zvm. Even if the
   699  	// ZVM has finished, cancelling may be done (repeatedly)
   700  	go func() {
   701  		<-ctx.Done()
   702  		zvm.Cancel()
   703  	}()
   704  
   705  	// Execute the message.
   706  	gp := new(core.GasPool).AddGas(math.MaxUint64)
   707  	result, err := core.ApplyMessage(zvm, msg, gp)
   708  	if err := state.Error(); err != nil {
   709  		return nil, err
   710  	}
   711  
   712  	// If the timer caused an abort, return an appropriate error message
   713  	if zvm.Cancelled() {
   714  		return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
   715  	}
   716  	if err != nil {
   717  		return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.GasLimit)
   718  	}
   719  	return result, nil
   720  }
   721  
   722  func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, blockOverrides *BlockOverrides, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
   723  	defer func(start time.Time) { log.Debug("Executing ZVM call finished", "runtime", time.Since(start)) }(time.Now())
   724  
   725  	state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   726  	if state == nil || err != nil {
   727  		return nil, err
   728  	}
   729  
   730  	return doCall(ctx, b, args, state, header, overrides, blockOverrides, timeout, globalGasCap)
   731  }
   732  
   733  func newRevertError(result *core.ExecutionResult) *revertError {
   734  	reason, errUnpack := abi.UnpackRevert(result.Revert())
   735  	err := errors.New("execution reverted")
   736  	if errUnpack == nil {
   737  		err = fmt.Errorf("execution reverted: %v", reason)
   738  	}
   739  	return &revertError{
   740  		error:  err,
   741  		reason: hexutil.Encode(result.Revert()),
   742  	}
   743  }
   744  
   745  // revertError is an API error that encompasses an ZVM revertal with JSON error
   746  // code and a binary data blob.
   747  type revertError struct {
   748  	error
   749  	reason string // revert reason hex encoded
   750  }
   751  
   752  // ErrorCode returns the JSON error code for a revertal.
   753  // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
   754  func (e *revertError) ErrorCode() int {
   755  	return 3
   756  }
   757  
   758  // ErrorData returns the hex encoded revert reason.
   759  func (e *revertError) ErrorData() interface{} {
   760  	return e.reason
   761  }
   762  
   763  // Call executes the given transaction on the state for the given block number.
   764  //
   765  // Additionally, the caller can specify a batch of contract for fields overriding.
   766  //
   767  // Note, this function doesn't make and changes in the state/blockchain and is
   768  // useful to execute and retrieve values.
   769  func (s *BlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, blockOverrides *BlockOverrides) (hexutil.Bytes, error) {
   770  	result, err := DoCall(ctx, s.b, args, blockNrOrHash, overrides, blockOverrides, s.b.RPCZVMTimeout(), s.b.RPCGasCap())
   771  	if err != nil {
   772  		return nil, err
   773  	}
   774  	// If the result contains a revert reason, try to unpack and return it.
   775  	if len(result.Revert()) > 0 {
   776  		return nil, newRevertError(result)
   777  	}
   778  	return result.Return(), result.Err
   779  }
   780  
   781  // executeEstimate is a helper that executes the transaction under a given gas limit and returns
   782  // true if the transaction fails for a reason that might be related to not enough gas. A non-nil
   783  // error means execution failed due to reasons unrelated to the gas limit.
   784  func executeEstimate(ctx context.Context, b Backend, args TransactionArgs, state *state.StateDB, header *types.Header, gasCap uint64, gasLimit uint64) (bool, *core.ExecutionResult, error) {
   785  	args.Gas = (*hexutil.Uint64)(&gasLimit)
   786  	result, err := doCall(ctx, b, args, state, header, nil, nil, 0, gasCap)
   787  	if err != nil {
   788  		if errors.Is(err, core.ErrIntrinsicGas) {
   789  			return true, nil, nil // Special case, raise gas limit
   790  		}
   791  		return true, nil, err // Bail out
   792  	}
   793  	return result.Failed(), result, nil
   794  }
   795  
   796  // DoEstimateGas returns the lowest possible gas limit that allows the transaction to run
   797  // successfully at block `blockNrOrHash`. It returns error if the transaction would revert, or if
   798  // there are unexpected failures. The gas limit is capped by both `args.Gas` (if non-nil &
   799  // non-zero) and `gasCap` (if non-zero).
   800  func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, gasCap uint64) (hexutil.Uint64, error) {
   801  	// Binary search the gas limit, as it may need to be higher than the amount used
   802  	var (
   803  		lo uint64 // lowest-known gas limit where tx execution fails
   804  		hi uint64 // lowest-known gas limit where tx execution succeeds
   805  	)
   806  	// Use zero address if sender unspecified.
   807  	if args.From == nil {
   808  		args.From = new(common.Address)
   809  	}
   810  	// Determine the highest gas limit can be used during the estimation.
   811  	if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
   812  		hi = uint64(*args.Gas)
   813  	} else {
   814  		// Retrieve the block to act as the gas ceiling
   815  		block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
   816  		if err != nil {
   817  			return 0, err
   818  		}
   819  		if block == nil {
   820  			return 0, errors.New("block not found")
   821  		}
   822  		hi = block.GasLimit()
   823  	}
   824  	// Normalize the max fee per gas the call is willing to spend.
   825  	var feeCap *big.Int
   826  	if args.MaxFeePerGas != nil {
   827  		feeCap = args.MaxFeePerGas.ToInt()
   828  	} else {
   829  		feeCap = common.Big0
   830  	}
   831  
   832  	state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   833  	if state == nil || err != nil {
   834  		return 0, err
   835  	}
   836  	if err := overrides.Apply(state); err != nil {
   837  		return 0, err
   838  	}
   839  
   840  	// Recap the highest gas limit with account's available balance.
   841  	if feeCap.BitLen() != 0 {
   842  		balance := state.GetBalance(*args.From) // from can't be nil
   843  		available := new(big.Int).Set(balance)
   844  		if args.Value != nil {
   845  			if args.Value.ToInt().Cmp(available) >= 0 {
   846  				return 0, core.ErrInsufficientFundsForTransfer
   847  			}
   848  			available.Sub(available, args.Value.ToInt())
   849  		}
   850  		allowance := new(big.Int).Div(available, feeCap)
   851  
   852  		// If the allowance is larger than maximum uint64, skip checking
   853  		if allowance.IsUint64() && hi > allowance.Uint64() {
   854  			transfer := args.Value
   855  			if transfer == nil {
   856  				transfer = new(hexutil.Big)
   857  			}
   858  			log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
   859  				"sent", transfer.ToInt(), "maxFeePerGas", feeCap, "fundable", allowance)
   860  			hi = allowance.Uint64()
   861  		}
   862  	}
   863  	// Recap the highest gas allowance with specified gascap.
   864  	if gasCap != 0 && hi > gasCap {
   865  		log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
   866  		hi = gasCap
   867  	}
   868  
   869  	// We first execute the transaction at the highest allowable gas limit, since if this fails we
   870  	// can return error immediately.
   871  	failed, result, err := executeEstimate(ctx, b, args, state.Copy(), header, gasCap, hi)
   872  	if err != nil {
   873  		return 0, err
   874  	}
   875  	if failed {
   876  		if result != nil && result.Err != vm.ErrOutOfGas {
   877  			if len(result.Revert()) > 0 {
   878  				return 0, newRevertError(result)
   879  			}
   880  			return 0, result.Err
   881  		}
   882  		return 0, fmt.Errorf("gas required exceeds allowance (%d)", hi)
   883  	}
   884  	// For almost any transaction, the gas consumed by the unconstrained execution above
   885  	// lower-bounds the gas limit required for it to succeed. One exception is those txs that
   886  	// explicitly check gas remaining in order to successfully execute within a given limit, but we
   887  	// probably don't want to return a lowest possible gas limit for these cases anyway.
   888  	lo = result.UsedGas - 1
   889  
   890  	// Binary search for the smallest gas limit that allows the tx to execute successfully.
   891  	for lo+1 < hi {
   892  		mid := (hi + lo) / 2
   893  		if mid > lo*2 {
   894  			// Most txs don't need much higher gas limit than their gas used, and most txs don't
   895  			// require near the full block limit of gas, so the selection of where to bisect the
   896  			// range here is skewed to favor the low side.
   897  			mid = lo * 2
   898  		}
   899  		failed, _, err = executeEstimate(ctx, b, args, state.Copy(), header, gasCap, mid)
   900  		if err != nil {
   901  			// This should not happen under normal conditions since if we make it this far the
   902  			// transaction had run without error at least once before.
   903  			log.Error("execution error in estimate gas", "err", err)
   904  			return 0, err
   905  		}
   906  		if failed {
   907  			lo = mid
   908  		} else {
   909  			hi = mid
   910  		}
   911  	}
   912  	return hexutil.Uint64(hi), nil
   913  }
   914  
   915  // EstimateGas returns the lowest possible gas limit that allows the transaction to run
   916  // successfully at block `blockNrOrHash`, or the latest block if `blockNrOrHash` is unspecified. It
   917  // returns error if the transaction would revert or if there are unexpected failures. The returned
   918  // value is capped by both `args.Gas` (if non-nil & non-zero) and the backend's RPCGasCap
   919  // configuration (if non-zero).
   920  func (s *BlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Uint64, error) {
   921  	bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
   922  	if blockNrOrHash != nil {
   923  		bNrOrHash = *blockNrOrHash
   924  	}
   925  	return DoEstimateGas(ctx, s.b, args, bNrOrHash, overrides, s.b.RPCGasCap())
   926  }
   927  
   928  // RPCMarshalHeader converts the given header to the RPC output .
   929  func RPCMarshalHeader(head *types.Header) map[string]interface{} {
   930  	result := map[string]interface{}{
   931  		"number":           (*hexutil.Big)(head.Number),
   932  		"hash":             head.Hash(),
   933  		"parentHash":       head.ParentHash,
   934  		"prevRandao":       head.Random,
   935  		"logsBloom":        head.Bloom,
   936  		"stateRoot":        head.Root,
   937  		"miner":            head.Coinbase,
   938  		"extraData":        hexutil.Bytes(head.Extra),
   939  		"gasLimit":         hexutil.Uint64(head.GasLimit),
   940  		"gasUsed":          hexutil.Uint64(head.GasUsed),
   941  		"timestamp":        hexutil.Uint64(head.Time),
   942  		"transactionsRoot": head.TxHash,
   943  		"receiptsRoot":     head.ReceiptHash,
   944  	}
   945  	if head.BaseFee != nil {
   946  		result["baseFeePerGas"] = (*hexutil.Big)(head.BaseFee)
   947  	}
   948  	if head.WithdrawalsHash != nil {
   949  		result["withdrawalsRoot"] = head.WithdrawalsHash
   950  	}
   951  	return result
   952  }
   953  
   954  // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
   955  // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
   956  // transaction hashes.
   957  func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool, config *params.ChainConfig) map[string]interface{} {
   958  	fields := RPCMarshalHeader(block.Header())
   959  	fields["size"] = hexutil.Uint64(block.Size())
   960  
   961  	if inclTx {
   962  		formatTx := func(idx int, tx *types.Transaction) interface{} {
   963  			return tx.Hash()
   964  		}
   965  		if fullTx {
   966  			formatTx = func(idx int, _ *types.Transaction) interface{} {
   967  				return newRPCTransactionFromBlockIndex(block, uint64(idx), config)
   968  			}
   969  		}
   970  		txs := block.Transactions()
   971  		transactions := make([]interface{}, len(txs))
   972  		for i, tx := range txs {
   973  			transactions[i] = formatTx(i, tx)
   974  		}
   975  		fields["transactions"] = transactions
   976  	}
   977  	if block.Header().WithdrawalsHash != nil {
   978  		fields["withdrawals"] = block.Withdrawals()
   979  	}
   980  	return fields
   981  }
   982  
   983  // rpcMarshalHeader uses the generalized output filler.
   984  func (s *BlockChainAPI) rpcMarshalHeader(header *types.Header) map[string]interface{} {
   985  	fields := RPCMarshalHeader(header)
   986  	return fields
   987  }
   988  
   989  // rpcMarshalBlock uses the generalized output filler.
   990  func (s *BlockChainAPI) rpcMarshalBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
   991  	fields := RPCMarshalBlock(b, inclTx, fullTx, s.b.ChainConfig())
   992  	return fields, nil
   993  }
   994  
   995  // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
   996  type RPCTransaction struct {
   997  	BlockHash   *common.Hash   `json:"blockHash"`
   998  	BlockNumber *hexutil.Big   `json:"blockNumber"`
   999  	From        common.Address `json:"from"`
  1000  	Gas         hexutil.Uint64 `json:"gas"`
  1001  	// NOTE(rgeraldes24): keeping GasPrice for now because it provides
  1002  	// the effective gas price if the transaction has been included
  1003  	GasPrice         *hexutil.Big      `json:"gasPrice"`
  1004  	GasFeeCap        *hexutil.Big      `json:"maxFeePerGas,omitempty"`
  1005  	GasTipCap        *hexutil.Big      `json:"maxPriorityFeePerGas,omitempty"`
  1006  	Hash             common.Hash       `json:"hash"`
  1007  	Input            hexutil.Bytes     `json:"input"`
  1008  	Nonce            hexutil.Uint64    `json:"nonce"`
  1009  	To               *common.Address   `json:"to"`
  1010  	TransactionIndex *hexutil.Uint64   `json:"transactionIndex"`
  1011  	Value            *hexutil.Big      `json:"value"`
  1012  	Type             hexutil.Uint64    `json:"type"`
  1013  	Accesses         *types.AccessList `json:"accessList,omitempty"`
  1014  	ChainID          *hexutil.Big      `json:"chainId,omitempty"`
  1015  	PublicKey        hexutil.Bytes     `json:"publicKey"`
  1016  	Signature        hexutil.Bytes     `json:"signature"`
  1017  }
  1018  
  1019  // newRPCTransaction returns a transaction that will serialize to the RPC
  1020  // representation, with the given location metadata set (if available).
  1021  func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64, baseFee *big.Int, config *params.ChainConfig) *RPCTransaction {
  1022  	signer := types.MakeSigner(config)
  1023  	from, _ := types.Sender(signer, tx)
  1024  	publicKey := tx.RawPublicKeyValue()
  1025  	signature := tx.RawSignatureValue()
  1026  	result := &RPCTransaction{
  1027  		Type:      hexutil.Uint64(tx.Type()),
  1028  		From:      from,
  1029  		Gas:       hexutil.Uint64(tx.Gas()),
  1030  		GasPrice:  (*hexutil.Big)(tx.GasPrice()),
  1031  		Hash:      tx.Hash(),
  1032  		Input:     hexutil.Bytes(tx.Data()),
  1033  		Nonce:     hexutil.Uint64(tx.Nonce()),
  1034  		To:        tx.To(),
  1035  		Value:     (*hexutil.Big)(tx.Value()),
  1036  		PublicKey: hexutil.Bytes(publicKey),
  1037  		Signature: hexutil.Bytes(signature),
  1038  	}
  1039  	if blockHash != (common.Hash{}) {
  1040  		result.BlockHash = &blockHash
  1041  		result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1042  		result.TransactionIndex = (*hexutil.Uint64)(&index)
  1043  	}
  1044  
  1045  	switch tx.Type() {
  1046  	case types.DynamicFeeTxType:
  1047  		al := tx.AccessList()
  1048  		result.Accesses = &al
  1049  		result.ChainID = (*hexutil.Big)(tx.ChainId())
  1050  		result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap())
  1051  		result.GasTipCap = (*hexutil.Big)(tx.GasTipCap())
  1052  		// if the transaction has been mined, compute the effective gas price
  1053  		if baseFee != nil && blockHash != (common.Hash{}) {
  1054  			// price = min(gasTipCap + baseFee, gasFeeCap)
  1055  			result.GasPrice = (*hexutil.Big)(effectiveGasPrice(tx, baseFee))
  1056  		} else {
  1057  			result.GasPrice = (*hexutil.Big)(tx.GasFeeCap())
  1058  		}
  1059  	}
  1060  	return result
  1061  }
  1062  
  1063  // effectiveGasPrice computes the transaction gas fee, based on the given basefee value.
  1064  //
  1065  //	price = min(gasTipCap + baseFee, gasFeeCap)
  1066  func effectiveGasPrice(tx *types.Transaction, baseFee *big.Int) *big.Int {
  1067  	fee := tx.GasTipCap()
  1068  	fee = fee.Add(fee, baseFee)
  1069  	if tx.GasFeeCapIntCmp(fee) < 0 {
  1070  		return tx.GasFeeCap()
  1071  	}
  1072  	return fee
  1073  }
  1074  
  1075  // NewRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1076  func NewRPCPendingTransaction(tx *types.Transaction, current *types.Header, config *params.ChainConfig) *RPCTransaction {
  1077  	var (
  1078  		baseFee     *big.Int
  1079  		blockNumber = uint64(0)
  1080  	)
  1081  	if current != nil {
  1082  		baseFee = eip1559.CalcBaseFee(config, current)
  1083  		blockNumber = current.Number.Uint64()
  1084  	}
  1085  	return newRPCTransaction(tx, common.Hash{}, blockNumber, 0, baseFee, config)
  1086  }
  1087  
  1088  // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1089  func newRPCTransactionFromBlockIndex(b *types.Block, index uint64, config *params.ChainConfig) *RPCTransaction {
  1090  	txs := b.Transactions()
  1091  	if index >= uint64(len(txs)) {
  1092  		return nil
  1093  	}
  1094  	return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index, b.BaseFee(), config)
  1095  }
  1096  
  1097  // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1098  func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1099  	txs := b.Transactions()
  1100  	if index >= uint64(len(txs)) {
  1101  		return nil
  1102  	}
  1103  	blob, _ := txs[index].MarshalBinary()
  1104  	return blob
  1105  }
  1106  
  1107  // accessListResult returns an optional accesslist
  1108  // It's the result of the `debug_createAccessList` RPC call.
  1109  // It contains an error if the transaction itself failed.
  1110  type accessListResult struct {
  1111  	Accesslist *types.AccessList `json:"accessList"`
  1112  	Error      string            `json:"error,omitempty"`
  1113  	GasUsed    hexutil.Uint64    `json:"gasUsed"`
  1114  }
  1115  
  1116  // CreateAccessList creates an EIP-2930 type AccessList for the given transaction.
  1117  // Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
  1118  func (s *BlockChainAPI) CreateAccessList(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*accessListResult, error) {
  1119  	bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1120  	if blockNrOrHash != nil {
  1121  		bNrOrHash = *blockNrOrHash
  1122  	}
  1123  	acl, gasUsed, vmerr, err := AccessList(ctx, s.b, bNrOrHash, args)
  1124  	if err != nil {
  1125  		return nil, err
  1126  	}
  1127  	result := &accessListResult{Accesslist: &acl, GasUsed: hexutil.Uint64(gasUsed)}
  1128  	if vmerr != nil {
  1129  		result.Error = vmerr.Error()
  1130  	}
  1131  	return result, nil
  1132  }
  1133  
  1134  // AccessList creates an access list for the given transaction.
  1135  // If the accesslist creation fails an error is returned.
  1136  // If the transaction itself fails, an vmErr is returned.
  1137  func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrHash, args TransactionArgs) (acl types.AccessList, gasUsed uint64, vmErr error, err error) {
  1138  	// Retrieve the execution context
  1139  	db, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1140  	if db == nil || err != nil {
  1141  		return nil, 0, nil, err
  1142  	}
  1143  	// If the gas amount is not set, default to RPC gas cap.
  1144  	if args.Gas == nil {
  1145  		tmp := hexutil.Uint64(b.RPCGasCap())
  1146  		args.Gas = &tmp
  1147  	}
  1148  
  1149  	// Ensure any missing fields are filled, extract the recipient and input data
  1150  	if err := args.setDefaults(ctx, b); err != nil {
  1151  		return nil, 0, nil, err
  1152  	}
  1153  	var to common.Address
  1154  	if args.To != nil {
  1155  		to = *args.To
  1156  	} else {
  1157  		to = crypto.CreateAddress(args.from(), uint64(*args.Nonce))
  1158  	}
  1159  	// Retrieve the precompiles since they don't need to be added to the access list
  1160  	precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number, header.Time))
  1161  
  1162  	// Create an initial tracer
  1163  	prevTracer := logger.NewAccessListTracer(nil, args.from(), to, precompiles)
  1164  	if args.AccessList != nil {
  1165  		prevTracer = logger.NewAccessListTracer(*args.AccessList, args.from(), to, precompiles)
  1166  	}
  1167  	for {
  1168  		// Retrieve the current access list to expand
  1169  		accessList := prevTracer.AccessList()
  1170  		log.Trace("Creating access list", "input", accessList)
  1171  
  1172  		// Copy the original db so we don't modify it
  1173  		statedb := db.Copy()
  1174  		// Set the accesslist to the last al
  1175  		args.AccessList = &accessList
  1176  		msg, err := args.ToMessage(b.RPCGasCap(), header.BaseFee)
  1177  		if err != nil {
  1178  			return nil, 0, nil, err
  1179  		}
  1180  
  1181  		// Apply the transaction with the access list tracer
  1182  		tracer := logger.NewAccessListTracer(accessList, args.from(), to, precompiles)
  1183  		config := vm.Config{Tracer: tracer, NoBaseFee: true}
  1184  		vmenv := b.GetZVM(ctx, msg, statedb, header, &config, nil)
  1185  		res, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.GasLimit))
  1186  		if err != nil {
  1187  			return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.toTransaction().Hash(), err)
  1188  		}
  1189  		if tracer.Equal(prevTracer) {
  1190  			return accessList, res.UsedGas, res.Err, nil
  1191  		}
  1192  		prevTracer = tracer
  1193  	}
  1194  }
  1195  
  1196  // TransactionAPI exposes methods for reading and creating transaction data.
  1197  type TransactionAPI struct {
  1198  	b         Backend
  1199  	nonceLock *AddrLocker
  1200  	signer    types.Signer
  1201  }
  1202  
  1203  // NewTransactionAPI creates a new RPC service with methods for interacting with transactions.
  1204  func NewTransactionAPI(b Backend, nonceLock *AddrLocker) *TransactionAPI {
  1205  	// The signer used by the API should always be the 'latest' known one because we expect
  1206  	// signers to be backwards-compatible with old transactions.
  1207  	signer := types.LatestSigner(b.ChainConfig())
  1208  	return &TransactionAPI{b, nonceLock, signer}
  1209  }
  1210  
  1211  // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1212  func (s *TransactionAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1213  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1214  		n := hexutil.Uint(len(block.Transactions()))
  1215  		return &n
  1216  	}
  1217  	return nil
  1218  }
  1219  
  1220  // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1221  func (s *TransactionAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1222  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1223  		n := hexutil.Uint(len(block.Transactions()))
  1224  		return &n
  1225  	}
  1226  	return nil
  1227  }
  1228  
  1229  // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1230  func (s *TransactionAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1231  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1232  		return newRPCTransactionFromBlockIndex(block, uint64(index), s.b.ChainConfig())
  1233  	}
  1234  	return nil
  1235  }
  1236  
  1237  // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1238  func (s *TransactionAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1239  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1240  		return newRPCTransactionFromBlockIndex(block, uint64(index), s.b.ChainConfig())
  1241  	}
  1242  	return nil
  1243  }
  1244  
  1245  // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1246  func (s *TransactionAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1247  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1248  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1249  	}
  1250  	return nil
  1251  }
  1252  
  1253  // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1254  func (s *TransactionAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1255  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1256  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1257  	}
  1258  	return nil
  1259  }
  1260  
  1261  // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1262  func (s *TransactionAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1263  	// Ask transaction pool for the nonce which includes pending transactions
  1264  	if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1265  		nonce, err := s.b.GetPoolNonce(ctx, address)
  1266  		if err != nil {
  1267  			return nil, err
  1268  		}
  1269  		return (*hexutil.Uint64)(&nonce), nil
  1270  	}
  1271  	// Resolve block number and use its state to ask for the nonce
  1272  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1273  	if state == nil || err != nil {
  1274  		return nil, err
  1275  	}
  1276  	nonce := state.GetNonce(address)
  1277  	return (*hexutil.Uint64)(&nonce), state.Error()
  1278  }
  1279  
  1280  // GetTransactionByHash returns the transaction for the given hash
  1281  func (s *TransactionAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1282  	// Try to return an already finalized transaction
  1283  	tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1284  	if err != nil {
  1285  		return nil, err
  1286  	}
  1287  	if tx != nil {
  1288  		header, err := s.b.HeaderByHash(ctx, blockHash)
  1289  		if err != nil {
  1290  			return nil, err
  1291  		}
  1292  		return newRPCTransaction(tx, blockHash, blockNumber, index, header.BaseFee, s.b.ChainConfig()), nil
  1293  	}
  1294  	// No finalized transaction, try to retrieve it from the pool
  1295  	if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1296  		return NewRPCPendingTransaction(tx, s.b.CurrentHeader(), s.b.ChainConfig()), nil
  1297  	}
  1298  
  1299  	// Transaction unknown, return as such
  1300  	return nil, nil
  1301  }
  1302  
  1303  // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1304  func (s *TransactionAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1305  	// Retrieve a finalized transaction, or a pooled otherwise
  1306  	tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1307  	if err != nil {
  1308  		return nil, err
  1309  	}
  1310  	if tx == nil {
  1311  		if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1312  			// Transaction not found anywhere, abort
  1313  			return nil, nil
  1314  		}
  1315  	}
  1316  	// Serialize to RLP and return
  1317  	return tx.MarshalBinary()
  1318  }
  1319  
  1320  // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1321  func (s *TransactionAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1322  	tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1323  	if tx == nil || err != nil {
  1324  		// When the transaction doesn't exist, the RPC method should return JSON null
  1325  		// as per specification.
  1326  		return nil, nil
  1327  	}
  1328  	receipts, err := s.b.GetReceipts(ctx, blockHash)
  1329  	if err != nil {
  1330  		return nil, err
  1331  	}
  1332  	if uint64(len(receipts)) <= index {
  1333  		return nil, nil
  1334  	}
  1335  	receipt := receipts[index]
  1336  
  1337  	// Derive the sender.
  1338  	signer := types.MakeSigner(s.b.ChainConfig())
  1339  	return marshalReceipt(receipt, blockHash, blockNumber, signer, tx, int(index)), nil
  1340  }
  1341  
  1342  // marshalReceipt marshals a transaction receipt into a JSON object.
  1343  func marshalReceipt(receipt *types.Receipt, blockHash common.Hash, blockNumber uint64, signer types.Signer, tx *types.Transaction, txIndex int) map[string]interface{} {
  1344  	from, _ := types.Sender(signer, tx)
  1345  
  1346  	fields := map[string]interface{}{
  1347  		"blockHash":         blockHash,
  1348  		"blockNumber":       hexutil.Uint64(blockNumber),
  1349  		"transactionHash":   tx.Hash(),
  1350  		"transactionIndex":  hexutil.Uint64(txIndex),
  1351  		"from":              from,
  1352  		"to":                tx.To(),
  1353  		"gasUsed":           hexutil.Uint64(receipt.GasUsed),
  1354  		"cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1355  		"contractAddress":   nil,
  1356  		"logs":              receipt.Logs,
  1357  		"logsBloom":         receipt.Bloom,
  1358  		"type":              hexutil.Uint(tx.Type()),
  1359  		"effectiveGasPrice": (*hexutil.Big)(receipt.EffectiveGasPrice),
  1360  	}
  1361  
  1362  	// Assign receipt status or post state.
  1363  	if len(receipt.PostState) > 0 {
  1364  		fields["root"] = hexutil.Bytes(receipt.PostState)
  1365  	} else {
  1366  		fields["status"] = hexutil.Uint(receipt.Status)
  1367  	}
  1368  	if receipt.Logs == nil {
  1369  		fields["logs"] = []*types.Log{}
  1370  	}
  1371  
  1372  	// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1373  	if receipt.ContractAddress != (common.Address{}) {
  1374  		fields["contractAddress"] = receipt.ContractAddress
  1375  	}
  1376  	return fields
  1377  }
  1378  
  1379  // sign is a helper function that signs a transaction with the private key of the given address.
  1380  func (s *TransactionAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1381  	// Look up the wallet containing the requested signer
  1382  	account := accounts.Account{Address: addr}
  1383  
  1384  	wallet, err := s.b.AccountManager().Find(account)
  1385  	if err != nil {
  1386  		return nil, err
  1387  	}
  1388  	// Request the wallet to sign the transaction
  1389  	return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1390  }
  1391  
  1392  // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1393  func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1394  	// If the transaction fee cap is already specified, ensure the
  1395  	// fee of the given transaction is _reasonable_.
  1396  	if err := checkTxFee(tx.GasPrice(), tx.Gas(), b.RPCTxFeeCap()); err != nil {
  1397  		return common.Hash{}, err
  1398  	}
  1399  	if err := b.SendTx(ctx, tx); err != nil {
  1400  		return common.Hash{}, err
  1401  	}
  1402  	// Print a log with full tx details for manual investigations and interventions
  1403  	signer := types.MakeSigner(b.ChainConfig())
  1404  	from, err := types.Sender(signer, tx)
  1405  	if err != nil {
  1406  		return common.Hash{}, err
  1407  	}
  1408  
  1409  	if tx.To() == nil {
  1410  		addr := crypto.CreateAddress(from, tx.Nonce())
  1411  		log.Info("Submitted contract creation", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "contract", addr.Hex(), "value", tx.Value())
  1412  	} else {
  1413  		log.Info("Submitted transaction", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "recipient", tx.To(), "value", tx.Value())
  1414  	}
  1415  	return tx.Hash(), nil
  1416  }
  1417  
  1418  // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1419  // transaction pool.
  1420  func (s *TransactionAPI) SendTransaction(ctx context.Context, args TransactionArgs) (common.Hash, error) {
  1421  	// Look up the wallet containing the requested signer
  1422  	account := accounts.Account{Address: args.from()}
  1423  
  1424  	wallet, err := s.b.AccountManager().Find(account)
  1425  	if err != nil {
  1426  		return common.Hash{}, err
  1427  	}
  1428  
  1429  	if args.Nonce == nil {
  1430  		// Hold the mutex around signing to prevent concurrent assignment of
  1431  		// the same nonce to multiple accounts.
  1432  		s.nonceLock.LockAddr(args.from())
  1433  		defer s.nonceLock.UnlockAddr(args.from())
  1434  	}
  1435  
  1436  	// Set some sanity defaults and terminate on failure
  1437  	if err := args.setDefaults(ctx, s.b); err != nil {
  1438  		return common.Hash{}, err
  1439  	}
  1440  	// Assemble the transaction and sign with the wallet
  1441  	tx := args.toTransaction()
  1442  
  1443  	signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1444  	if err != nil {
  1445  		return common.Hash{}, err
  1446  	}
  1447  	return SubmitTransaction(ctx, s.b, signed)
  1448  }
  1449  
  1450  // FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields)
  1451  // on a given unsigned transaction, and returns it to the caller for further
  1452  // processing (signing + broadcast).
  1453  func (s *TransactionAPI) FillTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
  1454  	// Set some sanity defaults and terminate on failure
  1455  	if err := args.setDefaults(ctx, s.b); err != nil {
  1456  		return nil, err
  1457  	}
  1458  	// Assemble the transaction and obtain rlp
  1459  	tx := args.toTransaction()
  1460  	data, err := tx.MarshalBinary()
  1461  	if err != nil {
  1462  		return nil, err
  1463  	}
  1464  	return &SignTransactionResult{data, tx}, nil
  1465  }
  1466  
  1467  // SendRawTransaction will add the signed transaction to the transaction pool.
  1468  // The sender is responsible for signing the transaction and using the correct nonce.
  1469  func (s *TransactionAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (common.Hash, error) {
  1470  	tx := new(types.Transaction)
  1471  	if err := tx.UnmarshalBinary(input); err != nil {
  1472  		return common.Hash{}, err
  1473  	}
  1474  	return SubmitTransaction(ctx, s.b, tx)
  1475  }
  1476  
  1477  // Sign calculates an ECDSA signature for:
  1478  // keccak256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1479  //
  1480  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1481  // where the V value will be 27 or 28 for legacy reasons.
  1482  //
  1483  // The account associated with addr must be unlocked.
  1484  //
  1485  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1486  func (s *TransactionAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1487  	// Look up the wallet containing the requested signer
  1488  	account := accounts.Account{Address: addr}
  1489  
  1490  	wallet, err := s.b.AccountManager().Find(account)
  1491  	if err != nil {
  1492  		return nil, err
  1493  	}
  1494  	// Sign the requested hash with the wallet
  1495  	signature, err := wallet.SignText(account, data)
  1496  	if err == nil {
  1497  		signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1498  	}
  1499  	return signature, err
  1500  }
  1501  
  1502  // SignTransactionResult represents a RLP encoded signed transaction.
  1503  type SignTransactionResult struct {
  1504  	Raw hexutil.Bytes      `json:"raw"`
  1505  	Tx  *types.Transaction `json:"tx"`
  1506  }
  1507  
  1508  // SignTransaction will sign the given transaction with the from account.
  1509  // The node needs to have the private key of the account corresponding with
  1510  // the given from address and it needs to be unlocked.
  1511  func (s *TransactionAPI) SignTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
  1512  	if args.Gas == nil {
  1513  		return nil, errors.New("gas not specified")
  1514  	}
  1515  	if args.MaxPriorityFeePerGas == nil || args.MaxFeePerGas == nil {
  1516  		return nil, errors.New("missing maxFeePerGas/maxPriorityFeePerGas")
  1517  	}
  1518  	if args.Nonce == nil {
  1519  		return nil, errors.New("nonce not specified")
  1520  	}
  1521  	if err := args.setDefaults(ctx, s.b); err != nil {
  1522  		return nil, err
  1523  	}
  1524  	// Before actually sign the transaction, ensure the transaction fee is reasonable.
  1525  	tx := args.toTransaction()
  1526  	if err := checkTxFee(tx.GasPrice(), tx.Gas(), s.b.RPCTxFeeCap()); err != nil {
  1527  		return nil, err
  1528  	}
  1529  	signed, err := s.sign(args.from(), tx)
  1530  	if err != nil {
  1531  		return nil, err
  1532  	}
  1533  	data, err := signed.MarshalBinary()
  1534  	if err != nil {
  1535  		return nil, err
  1536  	}
  1537  	return &SignTransactionResult{data, signed}, nil
  1538  }
  1539  
  1540  // PendingTransactions returns the transactions that are in the transaction pool
  1541  // and have a from address that is one of the accounts this node manages.
  1542  func (s *TransactionAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1543  	pending, err := s.b.GetPoolTransactions()
  1544  	if err != nil {
  1545  		return nil, err
  1546  	}
  1547  	accounts := make(map[common.Address]struct{})
  1548  	for _, wallet := range s.b.AccountManager().Wallets() {
  1549  		for _, account := range wallet.Accounts() {
  1550  			accounts[account.Address] = struct{}{}
  1551  		}
  1552  	}
  1553  	curHeader := s.b.CurrentHeader()
  1554  	transactions := make([]*RPCTransaction, 0, len(pending))
  1555  	for _, tx := range pending {
  1556  		from, _ := types.Sender(s.signer, tx)
  1557  		if _, exists := accounts[from]; exists {
  1558  			transactions = append(transactions, NewRPCPendingTransaction(tx, curHeader, s.b.ChainConfig()))
  1559  		}
  1560  	}
  1561  	return transactions, nil
  1562  }
  1563  
  1564  // TODO(now.youtrack.cloud/issue/TGZ-11)
  1565  /*
  1566  // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1567  // the given transaction from the pool and reinsert it with the new gas price and limit.
  1568  func (s *TransactionAPI) Resend(ctx context.Context, sendArgs TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1569  	if sendArgs.Nonce == nil {
  1570  		return common.Hash{}, errors.New("missing transaction nonce in transaction spec")
  1571  	}
  1572  	if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1573  		return common.Hash{}, err
  1574  	}
  1575  	matchTx := sendArgs.toTransaction()
  1576  
  1577  	// Before replacing the old transaction, ensure the _new_ transaction fee is reasonable.
  1578  	var price = matchTx.GasPrice()
  1579  	if gasPrice != nil {
  1580  		price = gasPrice.ToInt()
  1581  	}
  1582  	var gas = matchTx.Gas()
  1583  	if gasLimit != nil {
  1584  		gas = uint64(*gasLimit)
  1585  	}
  1586  	if err := checkTxFee(price, gas, s.b.RPCTxFeeCap()); err != nil {
  1587  		return common.Hash{}, err
  1588  	}
  1589  	// Iterate the pending list for replacement
  1590  	pending, err := s.b.GetPoolTransactions()
  1591  	if err != nil {
  1592  		return common.Hash{}, err
  1593  	}
  1594  	for _, p := range pending {
  1595  		wantSigHash := s.signer.Hash(matchTx)
  1596  		pFrom, err := types.Sender(s.signer, p)
  1597  		if err == nil && pFrom == sendArgs.from() && s.signer.Hash(p) == wantSigHash {
  1598  			// Match. Re-sign and send the transaction.
  1599  			if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1600  				sendArgs.GasPrice = gasPrice
  1601  			}
  1602  			if gasLimit != nil && *gasLimit != 0 {
  1603  				sendArgs.Gas = gasLimit
  1604  			}
  1605  			signedTx, err := s.sign(sendArgs.from(), sendArgs.toTransaction())
  1606  			if err != nil {
  1607  				return common.Hash{}, err
  1608  			}
  1609  			if err = s.b.SendTx(ctx, signedTx); err != nil {
  1610  				return common.Hash{}, err
  1611  			}
  1612  			return signedTx.Hash(), nil
  1613  		}
  1614  	}
  1615  	return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  1616  }
  1617  */
  1618  
  1619  // DebugAPI is the collection of Zond APIs exposed over the debugging
  1620  // namespace.
  1621  type DebugAPI struct {
  1622  	b Backend
  1623  }
  1624  
  1625  // NewDebugAPI creates a new instance of DebugAPI.
  1626  func NewDebugAPI(b Backend) *DebugAPI {
  1627  	return &DebugAPI{b: b}
  1628  }
  1629  
  1630  // GetRawHeader retrieves the RLP encoding for a single header.
  1631  func (api *DebugAPI) GetRawHeader(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  1632  	var hash common.Hash
  1633  	if h, ok := blockNrOrHash.Hash(); ok {
  1634  		hash = h
  1635  	} else {
  1636  		block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash)
  1637  		if err != nil {
  1638  			return nil, err
  1639  		}
  1640  		hash = block.Hash()
  1641  	}
  1642  	header, _ := api.b.HeaderByHash(ctx, hash)
  1643  	if header == nil {
  1644  		return nil, fmt.Errorf("header #%d not found", hash)
  1645  	}
  1646  	return rlp.EncodeToBytes(header)
  1647  }
  1648  
  1649  // GetRawBlock retrieves the RLP encoded for a single block.
  1650  func (api *DebugAPI) GetRawBlock(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  1651  	var hash common.Hash
  1652  	if h, ok := blockNrOrHash.Hash(); ok {
  1653  		hash = h
  1654  	} else {
  1655  		block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash)
  1656  		if err != nil {
  1657  			return nil, err
  1658  		}
  1659  		hash = block.Hash()
  1660  	}
  1661  	block, _ := api.b.BlockByHash(ctx, hash)
  1662  	if block == nil {
  1663  		return nil, fmt.Errorf("block #%d not found", hash)
  1664  	}
  1665  	return rlp.EncodeToBytes(block)
  1666  }
  1667  
  1668  // GetRawReceipts retrieves the binary-encoded receipts of a single block.
  1669  func (api *DebugAPI) GetRawReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]hexutil.Bytes, error) {
  1670  	var hash common.Hash
  1671  	if h, ok := blockNrOrHash.Hash(); ok {
  1672  		hash = h
  1673  	} else {
  1674  		block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash)
  1675  		if err != nil {
  1676  			return nil, err
  1677  		}
  1678  		hash = block.Hash()
  1679  	}
  1680  	receipts, err := api.b.GetReceipts(ctx, hash)
  1681  	if err != nil {
  1682  		return nil, err
  1683  	}
  1684  	result := make([]hexutil.Bytes, len(receipts))
  1685  	for i, receipt := range receipts {
  1686  		b, err := receipt.MarshalBinary()
  1687  		if err != nil {
  1688  			return nil, err
  1689  		}
  1690  		result[i] = b
  1691  	}
  1692  	return result, nil
  1693  }
  1694  
  1695  // GetRawTransaction returns the bytes of the transaction for the given hash.
  1696  func (s *DebugAPI) GetRawTransaction(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1697  	// Retrieve a finalized transaction, or a pooled otherwise
  1698  	tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1699  	if err != nil {
  1700  		return nil, err
  1701  	}
  1702  	if tx == nil {
  1703  		if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1704  			// Transaction not found anywhere, abort
  1705  			return nil, nil
  1706  		}
  1707  	}
  1708  	return tx.MarshalBinary()
  1709  }
  1710  
  1711  // PrintBlock retrieves a block and returns its pretty printed form.
  1712  func (api *DebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1713  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1714  	if block == nil {
  1715  		return "", fmt.Errorf("block #%d not found", number)
  1716  	}
  1717  	return spew.Sdump(block), nil
  1718  }
  1719  
  1720  // ChaindbProperty returns leveldb properties of the key-value database.
  1721  func (api *DebugAPI) ChaindbProperty(property string) (string, error) {
  1722  	if property == "" {
  1723  		property = "leveldb.stats"
  1724  	} else if !strings.HasPrefix(property, "leveldb.") {
  1725  		property = "leveldb." + property
  1726  	}
  1727  	return api.b.ChainDb().Stat(property)
  1728  }
  1729  
  1730  // ChaindbCompact flattens the entire key-value database into a single level,
  1731  // removing all unused slots and merging all keys.
  1732  func (api *DebugAPI) ChaindbCompact() error {
  1733  	for b := byte(0); b < 255; b++ {
  1734  		log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1735  		if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  1736  			log.Error("Database compaction failed", "err", err)
  1737  			return err
  1738  		}
  1739  	}
  1740  	return nil
  1741  }
  1742  
  1743  // SetHead rewinds the head of the blockchain to a previous block.
  1744  func (api *DebugAPI) SetHead(number hexutil.Uint64) {
  1745  	api.b.SetHead(uint64(number))
  1746  }
  1747  
  1748  // NetAPI offers network related RPC methods
  1749  type NetAPI struct {
  1750  	net            *p2p.Server
  1751  	networkVersion uint64
  1752  }
  1753  
  1754  // NewNetAPI creates a new net API instance.
  1755  func NewNetAPI(net *p2p.Server, networkVersion uint64) *NetAPI {
  1756  	return &NetAPI{net, networkVersion}
  1757  }
  1758  
  1759  // Listening returns an indication if the node is listening for network connections.
  1760  func (s *NetAPI) Listening() bool {
  1761  	return true // always listening
  1762  }
  1763  
  1764  // PeerCount returns the number of connected peers
  1765  func (s *NetAPI) PeerCount() hexutil.Uint {
  1766  	return hexutil.Uint(s.net.PeerCount())
  1767  }
  1768  
  1769  // Version returns the current zond protocol version.
  1770  func (s *NetAPI) Version() string {
  1771  	return fmt.Sprintf("%d", s.networkVersion)
  1772  }
  1773  
  1774  // checkTxFee is an internal function used to check whether the fee of
  1775  // the given transaction is _reasonable_(under the cap).
  1776  func checkTxFee(gasPrice *big.Int, gas uint64, cap float64) error {
  1777  	// Short circuit if there is no cap for transaction fee at all.
  1778  	if cap == 0 {
  1779  		return nil
  1780  	}
  1781  	feeEth := new(big.Float).Quo(new(big.Float).SetInt(new(big.Int).Mul(gasPrice, new(big.Int).SetUint64(gas))), new(big.Float).SetInt(big.NewInt(params.Ether)))
  1782  	feeFloat, _ := feeEth.Float64()
  1783  	if feeFloat > cap {
  1784  		return fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, cap)
  1785  	}
  1786  	return nil
  1787  }