func(s*BlockChainAPI)BlockNumber()hexutil.Uint64{header,_:=s.b.HeaderByNumber(context.Background(),rpc.LatestBlockNumber)returnhexutil.Uint64(header.Number.Uint64())}// BlockNumber returns the block number of the chain head.
func(s*BlockChainAPI)Call(ctxcontext.Context,argsTransactionArgs,blockNrOrHashrpc.BlockNumberOrHash,overrides*StateOverride)(hexutil.Bytes,error){result,err:=DoCall(ctx,s.b,args,blockNrOrHash,overrides,s.b.RPCEVMTimeout(),s.b.RPCGasCap())iferr!=nil{returnnil,err}iflen(result.Revert())>0{returnnil,newRevertError(result)}returnresult.Return(),result.Err}// Call executes the given transaction on the state for the given block number.//// Additionally, the caller can specify a batch of contract for fields overriding.//// Note, this function doesn't make and changes in the state/blockchain and is// useful to execute and retrieve values.
ChainId is the EIP-155 replay-protection chain id for the current Ethereum chain config.
Note, this method does not conform to EIP-695 because the configured chain ID is always returned, regardless of the current head block. We used to return an error when the chain wasn’t synced up to a block where EIP-155 is enabled, but this behavior caused issues in CL clients.
func(api*BlockChainAPI)ChainId()*hexutil.Big{return(*hexutil.Big)(api.b.ChainConfig().GetChainID())}// ChainId is the EIP-155 replay-protection chain id for the current Ethereum chain config.//// Note, this method does not conform to EIP-695 because the configured chain ID is always// returned, regardless of the current head block. We used to return an error when the chain// wasn't synced up to a block where EIP-155 is enabled, but this behavior caused issues// in CL clients.
func(api*EthereumAPI)Coinbase()(common.Address,error){returnapi.Etherbase()}// Coinbase is the address that mining rewards will be send to (alias for Etherbase).
CreateAccessList creates a EIP-2930 type AccessList for the given transaction. Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
func(s*BlockChainAPI)CreateAccessList(ctxcontext.Context,argsTransactionArgs,blockNrOrHash*rpc.BlockNumberOrHash)(*accessListResult,error){bNrOrHash:=rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)ifblockNrOrHash!=nil{bNrOrHash=*blockNrOrHash}acl,gasUsed,vmerr,err:=AccessList(ctx,s.b,bNrOrHash,args)iferr!=nil{returnnil,err}result:=&accessListResult{Accesslist:&acl,GasUsed:hexutil.Uint64(gasUsed)}ifvmerr!=nil{result.Error=vmerr.Error()}returnresult,nil}// CreateAccessList creates a EIP-2930 type AccessList for the given transaction.// Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
func(s*BlockChainAPI)EstimateGas(ctxcontext.Context,argsTransactionArgs,blockNrOrHash*rpc.BlockNumberOrHash)(hexutil.Uint64,error){bNrOrHash:=rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)ifblockNrOrHash!=nil{bNrOrHash=*blockNrOrHash}returnDoEstimateGas(ctx,s.b,args,bNrOrHash,s.b.RPCGasCap())}// EstimateGas returns an estimate of the amount of gas needed to execute the// given transaction against the current pending block.
FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields) on a given unsigned transaction, and returns it to the caller for further processing (signing + broadcast).
func(s*TransactionAPI)FillTransaction(ctxcontext.Context,argsTransactionArgs)(*SignTransactionResult,error){iferr:=args.setDefaults(ctx,s.b);err!=nil{returnnil,err}tx:=args.toTransaction()data,err:=tx.MarshalBinary()iferr!=nil{returnnil,err}return&SignTransactionResult{data,tx},nil}// FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields)// on a given unsigned transaction, and returns it to the caller for further// processing (signing + broadcast).
func(s*EthereumAPI)GasPrice(ctxcontext.Context)(*hexutil.Big,error){tipcap,err:=s.b.SuggestGasTipCap(ctx)iferr!=nil{returnnil,err}ifhead:=s.b.CurrentHeader();head.BaseFee!=nil{tipcap.Add(tipcap,head.BaseFee)}return(*hexutil.Big)(tipcap),err}// GasPrice returns a suggestion for a gas price for legacy transactions.
GetBalance returns the amount of wei for the given address in the state of the given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block numbers are also allowed.
func(s*BlockChainAPI)GetBalance(ctxcontext.Context,addresscommon.Address,blockNrOrHashrpc.BlockNumberOrHash)(*hexutil.Big,error){state,_,err:=s.b.StateAndHeaderByNumberOrHash(ctx,blockNrOrHash)ifstate==nil||err!=nil{returnnil,err}return(*hexutil.Big)(state.GetBalance(address)),state.Error()}// GetBalance returns the amount of wei for the given address in the state of the// given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta// block numbers are also allowed.
GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
func(s*BlockChainAPI)GetBlockByHash(ctxcontext.Context,hashcommon.Hash,fullTxbool)(*RPCMarshalBlockT,error){block,err:=s.b.BlockByHash(ctx,hash)ifblock!=nil{returns.rpcMarshalBlock(ctx,block,true,fullTx)}returnnil,err}// GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full// detail, otherwise only the transaction hash is returned.
GetBlockByNumber returns the requested canonical block. * When blockNr is -1 the chain head is returned. * When blockNr is -2 the pending chain head is returned. * When fullTx is true all transactions in the block are returned, otherwise only the transaction hash is returned.
func(s*BlockChainAPI)GetBlockByNumber(ctxcontext.Context,numberrpc.BlockNumber,fullTxbool)(*RPCMarshalBlockT,error){block,err:=s.b.BlockByNumber(ctx,number)ifblock!=nil&&err==nil{response,err:=s.rpcMarshalBlock(ctx,block,true,fullTx)iferr==nil&&number==rpc.PendingBlockNumber{response.setAsPending()}returnresponse,err}returnnil,err}// GetBlockByNumber returns the requested canonical block.// * When blockNr is -1 the chain head is returned.// * When blockNr is -2 the pending chain head is returned.// * When fullTx is true all transactions in the block are returned, otherwise// only the transaction hash is returned.
func(s*TransactionAPI)GetBlockTransactionCountByHash(ctxcontext.Context,blockHashcommon.Hash)*hexutil.Uint{ifblock,_:=s.b.BlockByHash(ctx,blockHash);block!=nil{n:=hexutil.Uint(len(block.Transactions()))return&n}returnnil}// GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
func(s*TransactionAPI)GetBlockTransactionCountByNumber(ctxcontext.Context,blockNrrpc.BlockNumber)*hexutil.Uint{ifblock,_:=s.b.BlockByNumber(ctx,blockNr);block!=nil{n:=hexutil.Uint(len(block.Transactions()))return&n}returnnil}// GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
func(s*BlockChainAPI)GetCode(ctxcontext.Context,addresscommon.Address,blockNrOrHashrpc.BlockNumberOrHash)(hexutil.Bytes,error){state,_,err:=s.b.StateAndHeaderByNumberOrHash(ctx,blockNrOrHash)ifstate==nil||err!=nil{returnnil,err}code:=state.GetCode(address)returncode,state.Error()}// GetCode returns the code stored at the given address in the state for the given block number.
func(api*FilterAPI)GetFilterChanges(idrpc.ID)(interface{},error){api.filtersMu.Lock()deferapi.filtersMu.Unlock()iff,found:=api.filters[id];found{if!f.deadline.Stop(){<-f.deadline.C}f.deadline.Reset(api.timeout)switchf.typ{casePendingTransactionsSubscription,BlocksSubscription,SideBlocksSubscription:hashes:=f.hashesf.hashes=nilreturnreturnHashes(hashes),nilcaseLogsSubscription,MinedAndPendingLogsSubscription:logs:=f.logsf.logs=nilreturnreturnLogs(logs),nil}}return[// GetFilterChanges returns the logs for the filter with the given id since// last time it was called. This can be used for polling.//// For pending transaction and block filters the result is []common.Hash.// (pending)Log filters return []Log.]interface{}{},fmt.Errorf("filter not found")}
func(api*FilterAPI)GetFilterLogs(ctxcontext.Context,idrpc.ID)([// GetFilterLogs returns the logs for the filter with the given id.// If the filter could not be found an empty array of logs is returned.]*types.Log,error){api.filtersMu.Lock()f,found:=api.filters[id]api.filtersMu.Unlock()if!found||f.typ!=LogsSubscription{returnnil,fmt.Errorf("filter not found")}varfilter*Filteriff.crit.BlockHash!=nil{filter=NewBlockFilter(api.backend,*f.crit.BlockHash,f.crit.Addresses,f.crit.Topics)}else{begin:=rpc.LatestBlockNumber.Int64()iff.crit.FromBlock!=nil{begin=f.crit.FromBlock.Int64()}end:=rpc.LatestBlockNumber.Int64()iff.crit.ToBlock!=nil{end=f.crit.ToBlock.Int64()}filter=NewRangeFilter(api.backend,begin,end,f.crit.Addresses,f.crit.Topics)}logs,err:=filter.Logs(ctx)iferr!=nil{returnnil,err}returnreturnLogs(logs),nil}
func(s*BlockChainAPI)GetHeaderByHash(ctxcontext.Context,hashcommon.Hash)*RPCMarshalHeaderT{header,_:=s.b.HeaderByHash(ctx,hash)ifheader!=nil{returns.rpcMarshalHeader(ctx,header)}returnnil}// GetHeaderByHash returns the requested header by hash.
GetHeaderByNumber returns the requested canonical block header. * When blockNr is -1 the chain head is returned. * When blockNr is -2 the pending chain head is returned.
func(s*BlockChainAPI)GetHeaderByNumber(ctxcontext.Context,numberrpc.BlockNumber)(*RPCMarshalHeaderT,error){header,err:=s.b.HeaderByNumber(ctx,number)ifheader!=nil&&err==nil{response:=s.rpcMarshalHeader(ctx,header)ifnumber==rpc.PendingBlockNumber{response.setAsPending()}returnresponse,err}returnnil,err}// GetHeaderByNumber returns the requested canonical block header.// * When blockNr is -1 the chain head is returned.// * When blockNr is -2 the pending chain head is returned.
func(api*FilterAPI)GetLogs(ctxcontext.Context,critFilterCriteria)([// GetLogs returns logs matching the given argument that are stored within the state.]*types.Log,error){varfilter*Filterifcrit.BlockHash!=nil{filter=NewBlockFilter(api.backend,*crit.BlockHash,crit.Addresses,crit.Topics)}else{begin:=rpc.LatestBlockNumber.Int64()ifcrit.FromBlock!=nil{begin=crit.FromBlock.Int64()}end:=rpc.LatestBlockNumber.Int64()ifcrit.ToBlock!=nil{end=crit.ToBlock.Int64()}filter=NewRangeFilter(api.backend,begin,end,crit.Addresses,crit.Topics)}logs,err:=filter.Logs(ctx)iferr!=nil{returnnil,err}returnreturnLogs(logs),err}
func(s*BlockChainAPI)GetProof(ctxcontext.Context,addresscommon.Address,storageKeys[// GetProof returns the Merkle-proof for a given account and optionally some storage keys.]string,blockNrOrHashrpc.BlockNumberOrHash)(*AccountResult,error){state,_,err:=s.b.StateAndHeaderByNumberOrHash(ctx,blockNrOrHash)ifstate==nil||err!=nil{returnnil,err}storageTrie:=state.StorageTrie(address)storageHash:=types.EmptyRootHashcodeHash:=state.GetCodeHash(address)storageProof:=make([]StorageResult,len(storageKeys))ifstorageTrie!=nil{storageHash=storageTrie.Hash()}else{codeHash=crypto.Keccak256Hash(nil)}fori,key:=rangestorageKeys{ifstorageTrie!=nil{proof,storageError:=state.GetStorageProof(address,common.HexToHash(key))ifstorageError!=nil{returnnil,storageError}storageProof[i]=StorageResult{key,(*hexutil.Big)(state.GetState(address,common.HexToHash(key)).Big()),toHexSlice(proof)}}else{storageProof[i]=StorageResult{key,&hexutil.Big{},[]string{}}}}accountProof,proofErr:=state.GetProof(address)ifproofErr!=nil{returnnil,proofErr}return&AccountResult{Address:address,AccountProof:toHexSlice(accountProof),Balance:(*hexutil.Big)(state.GetBalance(address)),CodeHash:codeHash,Nonce:hexutil.Uint64(state.GetNonce(address)),StorageHash:storageHash,StorageProof:storageProof},state.Error()}
func(s*TransactionAPI)GetRawTransactionByBlockHashAndIndex(ctxcontext.Context,blockHashcommon.Hash,indexhexutil.Uint)hexutil.Bytes{ifblock,_:=s.b.BlockByHash(ctx,blockHash);block!=nil{returnnewRPCRawTransactionFromBlockIndex(block,uint64(index))}returnnil}// GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
func(s*TransactionAPI)GetRawTransactionByBlockNumberAndIndex(ctxcontext.Context,blockNrrpc.BlockNumber,indexhexutil.Uint)hexutil.Bytes{ifblock,_:=s.b.BlockByNumber(ctx,blockNr);block!=nil{returnnewRPCRawTransactionFromBlockIndex(block,uint64(index))}returnnil}// GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
func(s*TransactionAPI)GetRawTransactionByHash(ctxcontext.Context,hashcommon.Hash)(hexutil.Bytes,error){tx,_,_,_,err:=s.b.GetTransaction(ctx,hash)iferr!=nil{returnnil,err}iftx==nil{iftx=s.b.GetPoolTransaction(hash);tx==nil{returnnil,nil}}returntx.MarshalBinary()}// GetRawTransactionByHash returns the bytes of the transaction for the given hash.
GetStorageAt returns the storage from the state at the given address, key and block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block numbers are also allowed.
func(s*BlockChainAPI)GetStorageAt(ctxcontext.Context,addresscommon.Address,keystring,blockNrOrHashrpc.BlockNumberOrHash)(hexutil.Bytes,error){state,_,err:=s.b.StateAndHeaderByNumberOrHash(ctx,blockNrOrHash)ifstate==nil||err!=nil{returnnil,err}res:=state.GetState(address,common.HexToHash(key))returnres[// GetStorageAt returns the storage from the state at the given address, key and// block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block// numbers are also allowed.:],state.Error()}
func(s*TransactionAPI)GetTransactionByBlockHashAndIndex(ctxcontext.Context,blockHashcommon.Hash,indexhexutil.Uint)*RPCTransaction{ifblock,_:=s.b.BlockByHash(ctx,blockHash);block!=nil{returnnewRPCTransactionFromBlockIndex(block,uint64(index),s.b.ChainConfig())}returnnil}// GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
func(s*TransactionAPI)GetTransactionByBlockNumberAndIndex(ctxcontext.Context,blockNrrpc.BlockNumber,indexhexutil.Uint)*RPCTransaction{ifblock,_:=s.b.BlockByNumber(ctx,blockNr);block!=nil{returnnewRPCTransactionFromBlockIndex(block,uint64(index),s.b.ChainConfig())}returnnil}// GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
func(s*TransactionAPI)GetTransactionByHash(ctxcontext.Context,hashcommon.Hash)(*RPCTransaction,error){tx,blockHash,blockNumber,index,err:=s.b.GetTransaction(ctx,hash)iferr!=nil{returnnil,err}iftx!=nil{header,err:=s.b.HeaderByHash(ctx,blockHash)iferr!=nil{returnnil,err}returnnewRPCTransaction(tx,blockHash,blockNumber,index,header.BaseFee,s.b.ChainConfig()),nil}iftx:=s.b.GetPoolTransaction(hash);tx!=nil{returnnewRPCPendingTransaction(tx,s.b.CurrentHeader(),s.b.ChainConfig()),nil}returnnil,nil}// GetTransactionByHash returns the transaction for the given hash
func(s*TransactionAPI)GetTransactionCount(ctxcontext.Context,addresscommon.Address,blockNrOrHashrpc.BlockNumberOrHash)(*hexutil.Uint64,error){ifblockNr,ok:=blockNrOrHash.Number();ok&&blockNr==rpc.PendingBlockNumber{nonce,err:=s.b.GetPoolNonce(ctx,address)iferr!=nil{returnnil,err}return(*hexutil.Uint64)(&nonce),nil}state,_,err:=s.b.StateAndHeaderByNumberOrHash(ctx,blockNrOrHash)ifstate==nil||err!=nil{returnnil,err}nonce:=state.GetNonce(address)return(*hexutil.Uint64)(&nonce),state.Error()}// GetTransactionCount returns the number of transactions the given address has sent for the given block number
func(s*TransactionAPI)GetTransactionReceipt(ctxcontext.Context,hashcommon.Hash)(map// GetTransactionReceipt returns the transaction receipt for the given transaction hash.[string]interface{},error){tx,blockHash,blockNumber,index,err:=s.b.GetTransaction(ctx,hash)iferr!=nil{returnnil,nil}receipts,err:=s.b.GetReceipts(ctx,blockHash)iferr!=nil{returnnil,err}iflen(receipts)<=int(index){returnnil,nil}receipt:=receipts[index]bigblock:=new(big.Int).SetUint64(blockNumber)signer:=types.MakeSigner(s.b.ChainConfig(),bigblock)from,_:=types.Sender(signer,tx)fields:=map[string]interface{}{"blockHash":blockHash,"blockNumber":hexutil.Uint64(blockNumber),"transactionHash":hash,"transactionIndex":hexutil.Uint64(index),"from":from,"to":tx.To(),"gasUsed":hexutil.Uint64(receipt.GasUsed),"cumulativeGasUsed":hexutil.Uint64(receipt.CumulativeGasUsed),"contractAddress":nil,"logs":receipt.Logs,"logsBloom":receipt.Bloom,"type":hexutil.Uint(tx.Type())}if!s.b.ChainConfig().IsEnabled(s.b.ChainConfig().GetEIP1559Transition,bigblock){fields["effectiveGasPrice"]=hexutil.Uint64(tx.GasPrice().Uint64())}else{header,err:=s.b.HeaderByHash(ctx,blockHash)iferr!=nil{returnnil,err}gasPrice:=new(big.Int).Add(header.BaseFee,tx.EffectiveGasTipValue(header.BaseFee))fields["effectiveGasPrice"]=hexutil.Uint64(gasPrice.Uint64())}iflen(receipt.PostState)>0{fields["root"]=hexutil.Bytes(receipt.PostState)}else{fields["status"]=hexutil.Uint(receipt.Status)}ifreceipt.Logs==nil{fields["logs"]=[]*types.Log{}}ifreceipt.ContractAddress!=(common.Address{}){fields["contractAddress"]=receipt.ContractAddress}returnfields,nil}
GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
func(s*BlockChainAPI)GetUncleByBlockHashAndIndex(ctxcontext.Context,blockHashcommon.Hash,indexhexutil.Uint)(*RPCMarshalBlockT,error){block,err:=s.b.BlockByHash(ctx,blockHash)ifblock!=nil{uncles:=block.Uncles()ifindex>=hexutil.Uint(len(uncles)){log.Debug("Requested uncle not found","number",block.Number(),"hash",blockHash,"index",index)returnnil,nil}block=types.NewBlockWithHeader(uncles[index])returns.rpcMarshalBlock(ctx,block,false,false)}returnnil,err}// GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true// all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
func(s*BlockChainAPI)GetUncleByBlockNumberAndIndex(ctxcontext.Context,blockNrrpc.BlockNumber,indexhexutil.Uint)(*RPCMarshalBlockT,error){block,err:=s.b.BlockByNumber(ctx,blockNr)ifblock!=nil{uncles:=block.Uncles()ifindex>=hexutil.Uint(len(uncles)){log.Debug("Requested uncle not found","number",blockNr,"hash",block.Hash(),"index",index)returnnil,nil}block=types.NewBlockWithHeader(uncles[index])returns.rpcMarshalBlock(ctx,block,false,false)}returnnil,err}// GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true// all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
func(s*BlockChainAPI)GetUncleCountByBlockHash(ctxcontext.Context,blockHashcommon.Hash)*hexutil.Uint{ifblock,_:=s.b.BlockByHash(ctx,blockHash);block!=nil{n:=hexutil.Uint(len(block.Uncles()))return&n}returnnil}// GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
func(s*BlockChainAPI)GetUncleCountByBlockNumber(ctxcontext.Context,blockNrrpc.BlockNumber)*hexutil.Uint{ifblock,_:=s.b.BlockByNumber(ctx,blockNr);block!=nil{n:=hexutil.Uint(len(block.Uncles()))return&n}returnnil}// GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
func(api*FilterAPI)Logs(ctxcontext.Context,critFilterCriteria)(*rpc.Subscription,error){notifier,supported:=rpc.NotifierFromContext(ctx)if!supported{return&rpc.Subscription{},rpc.ErrNotificationsUnsupported}var(rpcSub=notifier.CreateSubscription()matchedLogs=make(chan[// Logs creates a subscription that fires for all new log that match the given filter criteria.]*types.Log))logsSub,err:=api.events.SubscribeLogs(ethereum.FilterQuery(crit),matchedLogs)iferr!=nil{returnnil,err}gofunc(){for{select{caselogs:=<-matchedLogs:for_,log:=rangelogs{log:=lognotifier.Notify(rpcSub.ID,&log)}case<-rpcSub.Err():logsSub.Unsubscribe()returncase<-notifier.Closed():logsSub.Unsubscribe()return}}}()returnrpcSub,nil}
func(s*EthereumAPI)MaxPriorityFeePerGas(ctxcontext.Context)(*hexutil.Big,error){tipcap,err:=s.b.SuggestGasTipCap(ctx)iferr!=nil{returnnil,err}return(*hexutil.Big)(tipcap),err}// MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic fee transactions.
NewBlockFilter creates a filter that fetches blocks that are imported into the chain. It is part of the filter package since polling goes with eth_getFilterChanges.
func(api*FilterAPI)NewBlockFilter()rpc.ID{var(headers=make(chan*types.Header)headerSub=api.events.SubscribeNewHeads(headers))api.filtersMu.Lock()api.filters[headerSub.ID]=&filter{typ:BlocksSubscription,deadline:time.NewTimer(api.timeout),hashes:make([// NewBlockFilter creates a filter that fetches blocks that are imported into the chain.// It is part of the filter package since polling goes with eth_getFilterChanges.]common.Hash,0),s:headerSub}api.filtersMu.Unlock()gofunc(){for{select{caseh:=<-headers:api.filtersMu.Lock()iff,found:=api.filters[headerSub.ID];found{f.hashes=append(f.hashes,h.Hash())}api.filtersMu.Unlock()case<-headerSub.Err():api.filtersMu.Lock()delete(api.filters,headerSub.ID)api.filtersMu.Unlock()return}}}()returnheaderSub.ID}
NewFilter creates a new filter and returns the filter id. It can be used to retrieve logs when the state changes. This method cannot be used to fetch logs that are already stored in the state.
Default criteria for the from and to block are “latest”. Using “latest” as block number will return logs for mined blocks. Using “pending” as block number returns logs for not yet mined (pending) blocks. In case logs are removed (chain reorg) previously returned logs are returned again but with the removed property set to true.
In case “fromBlock” > “toBlock” an error is returned.
func(api*FilterAPI)NewFilter(critFilterCriteria)(rpc.ID,error){logs:=make(chan[// NewFilter creates a new filter and returns the filter id. It can be// used to retrieve logs when the state changes. This method cannot be// used to fetch logs that are already stored in the state.//// Default criteria for the from and to block are "latest".// Using "latest" as block number will return logs for mined blocks.// Using "pending" as block number returns logs for not yet mined (pending) blocks.// In case logs are removed (chain reorg) previously returned logs are returned// again but with the removed property set to true.//// In case "fromBlock" > "toBlock" an error is returned.]*types.Log)logsSub,err:=api.events.SubscribeLogs(ethereum.FilterQuery(crit),logs)iferr!=nil{return"",err}api.filtersMu.Lock()api.filters[logsSub.ID]=&filter{typ:LogsSubscription,crit:crit,deadline:time.NewTimer(api.timeout),logs:make([]*types.Log,0),s:logsSub}api.filtersMu.Unlock()gofunc(){for{select{casel:=<-logs:api.filtersMu.Lock()iff,found:=api.filters[logsSub.ID];found{f.logs=append(f.logs,l...)}api.filtersMu.Unlock()case<-logsSub.Err():api.filtersMu.Lock()delete(api.filters,logsSub.ID)api.filtersMu.Unlock()return}}}()returnlogsSub.ID,nil}
func(api*FilterAPI)NewHeads(ctxcontext.Context)(*rpc.Subscription,error){notifier,supported:=rpc.NotifierFromContext(ctx)if!supported{return&rpc.Subscription{},rpc.ErrNotificationsUnsupported}rpcSub:=notifier.CreateSubscription()gofunc(){headers:=make(chan*types.Header)headersSub:=api.events.SubscribeNewHeads(headers)for{select{caseh:=<-headers:notifier.Notify(rpcSub.ID,h)case<-rpcSub.Err():headersSub.Unsubscribe()returncase<-notifier.Closed():headersSub.Unsubscribe()return}}}()returnrpcSub,nil}// NewHeads send a notification each time a new (header) block is appended to the chain.
func(api*FilterAPI)NewPendingTransactionFilter()rpc.ID{var(pendingTxs=make(chan[// NewPendingTransactionFilter creates a filter that fetches pending transaction hashes// as transactions enter the pending state.//// It is part of the filter package because this filter can be used through the// `eth_getFilterChanges` polling method that is also used for log filters.]common.Hash)pendingTxSub=api.events.SubscribePendingTxs(pendingTxs))api.filtersMu.Lock()api.filters[pendingTxSub.ID]=&filter{typ:PendingTransactionsSubscription,deadline:time.NewTimer(api.timeout),hashes:make([]common.Hash,0),s:pendingTxSub}api.filtersMu.Unlock()gofunc(){for{select{caseph:=<-pendingTxs:api.filtersMu.Lock()iff,found:=api.filters[pendingTxSub.ID];found{f.hashes=append(f.hashes,ph...)}api.filtersMu.Unlock()case<-pendingTxSub.Err():api.filtersMu.Lock()delete(api.filters,pendingTxSub.ID)api.filtersMu.Unlock()return}}}()returnpendingTxSub.ID}
NewPendingTransactions creates a subscription that is triggered each time a transaction enters the transaction pool and was signed from one of the transactions this nodes manages.
func(api*FilterAPI)NewPendingTransactions(ctxcontext.Context)(*rpc.Subscription,error){notifier,supported:=rpc.NotifierFromContext(ctx)if!supported{return&rpc.Subscription{},rpc.ErrNotificationsUnsupported}rpcSub:=notifier.CreateSubscription()gofunc(){txHashes:=make(chan[// NewPendingTransactions creates a subscription that is triggered each time a transaction// enters the transaction pool and was signed from one of the transactions this nodes manages.]common.Hash,128)pendingTxSub:=api.events.SubscribePendingTxs(txHashes)for{select{casehashes:=<-txHashes:for_,h:=rangehashes{notifier.Notify(rpcSub.ID,h)}case<-rpcSub.Err():pendingTxSub.Unsubscribe()returncase<-notifier.Closed():pendingTxSub.Unsubscribe()return}}}()returnrpcSub,nil}
NewSideBlockFilter creates a filter that fetches blocks that are imported into the chain with a non-canonical status. It is part of the filter package since polling goes with eth_getFilterChanges.
func(api*FilterAPI)NewSideBlockFilter()rpc.ID{var(headers=make(chan*types.Header)headerSub=api.events.SubscribeNewSideHeads(headers))api.filtersMu.Lock()api.filters[headerSub.ID]=&filter{typ:SideBlocksSubscription,deadline:time.NewTimer(api.timeout),hashes:make([// NewSideBlockFilter creates a filter that fetches blocks that are imported into the chain with a non-canonical status.// It is part of the filter package since polling goes with eth_getFilterChanges.]common.Hash,0),s:headerSub}api.filtersMu.Unlock()gofunc(){for{select{caseh:=<-headers:api.filtersMu.Lock()iff,found:=api.filters[headerSub.ID];found{f.hashes=append(f.hashes,h.Hash())}api.filtersMu.Unlock()case<-headerSub.Err():api.filtersMu.Lock()delete(api.filters,headerSub.ID)api.filtersMu.Unlock()return}}}()returnheaderSub.ID}
func(api*FilterAPI)NewSideHeads(ctxcontext.Context)(*rpc.Subscription,error){notifier,supported:=rpc.NotifierFromContext(ctx)if!supported{return&rpc.Subscription{},rpc.ErrNotificationsUnsupported}rpcSub:=notifier.CreateSubscription()gofunc(){headers:=make(chan*types.Header)headersSub:=api.events.SubscribeNewSideHeads(headers)for{select{caseh:=<-headers:notifier.Notify(rpcSub.ID,h)case<-rpcSub.Err():headersSub.Unsubscribe()returncase<-notifier.Closed():headersSub.Unsubscribe()return}}}()returnrpcSub,nil}// NewSideHeads send a notification each time a new non-canonical (header) block is written to the database.
func(s*TransactionAPI)PendingTransactions()([// PendingTransactions returns the transactions that are in the transaction pool// and have a from address that is one of the accounts this node manages.]*RPCTransaction,error){pending,err:=s.b.GetPoolTransactions()iferr!=nil{returnnil,err}accounts:=make(map[common.Address]struct{})for_,wallet:=ranges.b.AccountManager().Wallets(){for_,account:=rangewallet.Accounts(){accounts[account.Address]=struct{}{}}}curHeader:=s.b.CurrentHeader()transactions:=make([]*RPCTransaction,0,len(pending))for_,tx:=rangepending{from,_:=types.Sender(s.signer,tx)if_,exists:=accounts[from];exists{transactions=append(transactions,newRPCPendingTransaction(tx,curHeader,s.b.ChainConfig()))}}returntransactions,nil}
Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the pool and reinsert it with the new gas price and limit.
func(s*TransactionAPI)Resend(ctxcontext.Context,sendArgsTransactionArgs,gasPrice*hexutil.Big,gasLimit*hexutil.Uint64)(common.Hash,error){ifsendArgs.Nonce==nil{returncommon.Hash{},fmt.Errorf("missing transaction nonce in transaction spec")}iferr:=sendArgs.setDefaults(ctx,s.b);err!=nil{returncommon.Hash{},err}matchTx:=sendArgs.toTransaction()varprice=matchTx.GasPrice()ifgasPrice!=nil{price=gasPrice.ToInt()}vargas=matchTx.Gas()ifgasLimit!=nil{gas=uint64(*gasLimit)}iferr:=checkTxFee(price,gas,s.b.RPCTxFeeCap());err!=nil{returncommon.Hash{},err}pending,err:=s.b.GetPoolTransactions()iferr!=nil{returncommon.Hash{},err}for_,p:=// Resend accepts an existing transaction and a new gas price and limit. It will remove// the given transaction from the pool and reinsert it with the new gas price and limit.// Before replacing the old transaction, ensure the _new_ transaction fee is reasonable.rangepending{wantSigHash:=s.signer.Hash(matchTx)pFrom,err:=types.Sender(s.signer,p)iferr==nil&&pFrom==sendArgs.from()&&s.signer.Hash(p)==wantSigHash{ifgasPrice!=nil&&(*big.Int)(gasPrice).Sign()!=0{sendArgs.GasPrice=gasPrice}ifgasLimit!=nil&&*gasLimit!=0{sendArgs.Gas=gasLimit}signedTx,err:=s.sign(sendArgs.from(),sendArgs.toTransaction())iferr!=nil{returncommon.Hash{},err}iferr=s.b.SendTx(ctx,signedTx);err!=nil{returncommon.Hash{},err}returnsignedTx.Hash(),nil}}returncommon.Hash{},fmt.Errorf("transaction %#x not found",matchTx.Hash())}
SendRawTransaction will add the signed transaction to the transaction pool. The sender is responsible for signing the transaction and using the correct nonce.
func(s*TransactionAPI)SendRawTransaction(ctxcontext.Context,inputhexutil.Bytes)(common.Hash,error){tx:=new(types.Transaction)iferr:=tx.UnmarshalBinary(input);err!=nil{returncommon.Hash{},err}returnSubmitTransaction(ctx,s.b,tx)}// SendRawTransaction will add the signed transaction to the transaction pool.// The sender is responsible for signing the transaction and using the correct nonce.
func(s*TransactionAPI)SendTransaction(ctxcontext.Context,argsTransactionArgs)(common.Hash,error){account:=accounts.Account{Address:args.from()}wallet,err:=s.b.AccountManager().Find(account)iferr!=nil{returncommon.Hash{},err}ifargs.Nonce==nil{s.nonceLock.LockAddr(args.from())defers.nonceLock.UnlockAddr(args.from())}iferr:=args.setDefaults(ctx,s.b);err!=nil{returncommon.Hash{},err}tx:=args.toTransaction()signed,err:=wallet.SignTx(account,tx,s.b.ChainConfig().GetChainID())iferr!=nil{returncommon.Hash{},err}returnSubmitTransaction(ctx,s.b,signed)}// SendTransaction creates a transaction for the given argument, sign it and submit it to the// transaction pool.
func(s*TransactionAPI)Sign(addrcommon.Address,datahexutil.Bytes)(hexutil.Bytes,error){account:=accounts.Account{Address:addr}wallet,err:=s.b.AccountManager().Find(account)iferr!=nil{returnnil,err}signature,err:=wallet.SignText(account,data)iferr==nil{signature[64]+=27}returnsignature,err}// Sign calculates an ECDSA signature for:// keccak256("\x19Ethereum Signed Message:\n" + len(message) + message).//// Note, the produced signature conforms to the secp256k1 curve R, S and V values,// where the V value will be 27 or 28 for legacy reasons.//// The account associated with addr must be unlocked.//// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
SignTransaction will sign the given transaction with the from account. The node needs to have the private key of the account corresponding with the given from address and it needs to be unlocked.
func(s*TransactionAPI)SignTransaction(ctxcontext.Context,argsTransactionArgs)(*SignTransactionResult,error){ifargs.Gas==nil{returnnil,fmt.Errorf("gas not specified")}ifargs.GasPrice==nil&&(args.MaxPriorityFeePerGas==nil||args.MaxFeePerGas==nil){returnnil,fmt.Errorf("missing gasPrice or maxFeePerGas/maxPriorityFeePerGas")}ifargs.Nonce==nil{returnnil,fmt.Errorf("nonce not specified")}iferr:=args.setDefaults(ctx,s.b);err!=nil{returnnil,err}tx:=args.toTransaction()iferr:=checkTxFee(tx.GasPrice(),tx.Gas(),s.b.RPCTxFeeCap());err!=nil{returnnil,err}signed,err:=s.sign(args.from(),tx)iferr!=nil{returnnil,err}data,err:=signed.MarshalBinary()iferr!=nil{returnnil,err}return&SignTransactionResult{data,signed},nil}// SignTransaction will sign the given transaction with the from account.// The node needs to have the private key of the account corresponding with// the given from address and it needs to be unlocked.
SubmitHashrate can be used for remote miners to submit their hash rate. This enables the node to report the combined hash rate of all miners which submit work through this node.
It accepts the miner hash rate and an identifier which must be unique between nodes.
func(api*API)SubmitHashrate(ratehexutil.Uint64,idcommon.Hash)bool{ifapi.ethash.remote==nil{returnfalse}vardone=make(chanstruct{},1)select{caseapi.ethash.remote.submitRateCh<-&hashrate{done:done,rate:uint64(rate),id:id}:case<-api.ethash.remote.exitCh:returnfalse}<-donereturntrue}// SubmitHashrate can be used for remote miners to submit their hash rate.// This enables the node to report the combined hash rate of all miners// which submit work through this node.//// It accepts the miner hash rate and an identifier which must be unique// between nodes.
SubmitWork can be used by external miner to submit their POW solution. It returns an indication if the work was accepted. Note either an invalid solution, a stale work a non-existent work will return false.
func(api*API)SubmitWork(noncetypes.BlockNonce,hash,digestcommon.Hash)bool{ifapi.ethash.remote==nil{returnfalse}varerrc=make(chanerror,1)select{caseapi.ethash.remote.submitWorkCh<-&mineResult{nonce:nonce,mixDigest:digest,hash:hash,errc:errc}:case<-api.ethash.remote.exitCh:returnfalse}err:=<-errcreturnerr==nil}// SubmitWork can be used by external miner to submit their POW solution.// It returns an indication if the work was accepted.// Note either an invalid solution, a stale work a non-existent work will return false.
Subscribe creates a subscription to an event channel. Subscriptions are not available over HTTP; they are only available over WS, IPC, and Process connections.
- oneOf:
- description: `Fires a notification each time a new header is appended to the chain, including chain reorganizations.`
- enum: newHeads
- type: string
- description: `Fires a notification each time a new header is appended to the non-canonical (side) chain, including chain reorganizations.`
- enum: newSideHeads
- type: string
- description: `Returns logs that are included in new imported blocks and match the given filter criteria.`
- enum: logs
- type: string
- description: `Returns the hash for all transactions that are added to the pending state and are signed with a key that is available in the node.`
- enum: newPendingTransactions
- type: string
- description: `Indicates when the node starts or stops synchronizing. The result can either be a boolean indicating that the synchronization has started (true), finished (false) or an object with various progress indicators.`
- enum: syncing
- type: string
- title: `subscriptionName`
{
"oneOf": [
{
"description": "Fires a notification each time a new header is appended to the chain, including chain reorganizations.",
"enum": [
"newHeads"
],
"type": [
"string"
]
},
{
"description": "Fires a notification each time a new header is appended to the non-canonical (side) chain, including chain reorganizations.",
"enum": [
"newSideHeads"
],
"type": [
"string"
]
},
{
"description": "Returns logs that are included in new imported blocks and match the given filter criteria.",
"enum": [
"logs"
],
"type": [
"string"
]
},
{
"description": "Returns the hash for all transactions that are added to the pending state and are signed with a key that is available in the node.",
"enum": [
"newPendingTransactions"
],
"type": [
"string"
]
},
{
"description": "Indicates when the node starts or stops synchronizing. The result can either be a boolean indicating that the synchronization has started (true), finished (false) or an object with various progress indicators.",
"enum": [
"syncing"
],
"type": [
"string"
]
}
],
"title": "subscriptionName"
}
func(sub*RPCEthSubscription)Subscribe(subscriptionNameRPCEthSubscriptionParamsName,subscriptionOptionsinterface{})(subscriptionIDrpc.ID,errerror){return}// Subscribe creates a subscription to an event channel.// Subscriptions are not available over HTTP; they are only available over WS, IPC, and Process connections.
Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not yet received the latest block headers from its pears. In case it is synchronizing: - startingBlock: block number this node started to synchronise from - currentBlock: block number this node is currently importing - highestBlock: block number of the highest block header this node has received from peers - pulledStates: number of state entries processed until now - knownStates: number of known state entries that still need to be pulled
func(s*EthereumAPI)Syncing()(interface{},error){progress:=s.b.SyncProgress()ifprogress.CurrentBlock>=progress.HighestBlock{returnfalse,nil}returnmap// Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not// yet received the latest block headers from its pears. In case it is synchronizing:// - startingBlock: block number this node started to synchronise from// - currentBlock: block number this node is currently importing// - highestBlock: block number of the highest block header this node has received from peers// - pulledStates: number of state entries processed until now// - knownStates: number of known state entries that still need to be pulled[string]interface{}{"startingBlock":hexutil.Uint64(progress.StartingBlock),"currentBlock":hexutil.Uint64(progress.CurrentBlock),"highestBlock":hexutil.Uint64(progress.HighestBlock),"syncedAccounts":hexutil.Uint64(progress.SyncedAccounts),"syncedAccountBytes":hexutil.Uint64(progress.SyncedAccountBytes),"syncedBytecodes":hexutil.Uint64(progress.SyncedBytecodes),"syncedBytecodeBytes":hexutil.Uint64(progress.SyncedBytecodeBytes),"syncedStorage":hexutil.Uint64(progress.SyncedStorage),"syncedStorageBytes":hexutil.Uint64(progress.SyncedStorageBytes),"healedTrienodes":hexutil.Uint64(progress.HealedTrienodes),"healedTrienodeBytes":hexutil.Uint64(progress.HealedTrienodeBytes),"healedBytecodes":hexutil.Uint64(progress.HealedBytecodes),"healedBytecodeBytes":hexutil.Uint64(progress.HealedBytecodeBytes),"healingTrienodes":hexutil.Uint64(progress.HealingTrienodes),"healingBytecode":hexutil.Uint64(progress.HealingBytecode)},nil}
func(api*DownloaderAPI)Syncing(ctxcontext.Context)(*rpc.Subscription,error){notifier,supported:=rpc.NotifierFromContext(ctx)if!supported{return&rpc.Subscription{},rpc.ErrNotificationsUnsupported}rpcSub:=notifier.CreateSubscription()gofunc(){statuses:=make(chaninterface{})sub:=api.SubscribeSyncStatus(statuses)for{select{casestatus:=<-statuses:notifier.Notify(rpcSub.ID,status)case<-rpcSub.Err():sub.Unsubscribe()returncase<-notifier.Closed():sub.Unsubscribe()return}}}()returnrpcSub,nil}// Syncing provides information when this nodes starts synchronising with the Ethereum network and when it's finished.
func(api*FilterAPI)UninstallFilter(idrpc.ID)bool{api.filtersMu.Lock()f,found:=api.filters[id]iffound{delete(api.filters,id)}api.filtersMu.Unlock()iffound{f.s.Unsubscribe()}returnfound}// UninstallFilter removes the filter with the given filter id.