github.com/ethereum/go-ethereum@v1.16.1/ethclient/gethclient/gethclient.go (about) 1 // Copyright 2021 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 gethclient provides an RPC client for geth-specific APIs. 18 package gethclient 19 20 import ( 21 "context" 22 "encoding/json" 23 "fmt" 24 "math/big" 25 "runtime" 26 "runtime/debug" 27 28 "github.com/ethereum/go-ethereum" 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/common/hexutil" 31 "github.com/ethereum/go-ethereum/core/types" 32 "github.com/ethereum/go-ethereum/eth/tracers" 33 "github.com/ethereum/go-ethereum/p2p" 34 "github.com/ethereum/go-ethereum/rpc" 35 ) 36 37 // Client is a wrapper around rpc.Client that implements geth-specific functionality. 38 // 39 // If you want to use the standardized Ethereum RPC functionality, use ethclient.Client instead. 40 type Client struct { 41 c *rpc.Client 42 } 43 44 // New creates a client that uses the given RPC client. 45 func New(c *rpc.Client) *Client { 46 return &Client{c} 47 } 48 49 // CreateAccessList tries to create an access list for a specific transaction based on the 50 // current pending state of the blockchain. 51 func (ec *Client) CreateAccessList(ctx context.Context, msg ethereum.CallMsg) (*types.AccessList, uint64, string, error) { 52 type accessListResult struct { 53 Accesslist *types.AccessList `json:"accessList"` 54 Error string `json:"error,omitempty"` 55 GasUsed hexutil.Uint64 `json:"gasUsed"` 56 } 57 var result accessListResult 58 if err := ec.c.CallContext(ctx, &result, "eth_createAccessList", toCallArg(msg)); err != nil { 59 return nil, 0, "", err 60 } 61 return result.Accesslist, uint64(result.GasUsed), result.Error, nil 62 } 63 64 // AccountResult is the result of a GetProof operation. 65 type AccountResult struct { 66 Address common.Address `json:"address"` 67 AccountProof []string `json:"accountProof"` 68 Balance *big.Int `json:"balance"` 69 CodeHash common.Hash `json:"codeHash"` 70 Nonce uint64 `json:"nonce"` 71 StorageHash common.Hash `json:"storageHash"` 72 StorageProof []StorageResult `json:"storageProof"` 73 } 74 75 // StorageResult provides a proof for a key-value pair. 76 type StorageResult struct { 77 Key string `json:"key"` 78 Value *big.Int `json:"value"` 79 Proof []string `json:"proof"` 80 } 81 82 // GetProof returns the account and storage values of the specified account including the Merkle-proof. 83 // The block number can be nil, in which case the value is taken from the latest known block. 84 func (ec *Client) GetProof(ctx context.Context, account common.Address, keys []string, blockNumber *big.Int) (*AccountResult, error) { 85 type storageResult struct { 86 Key string `json:"key"` 87 Value *hexutil.Big `json:"value"` 88 Proof []string `json:"proof"` 89 } 90 91 type accountResult struct { 92 Address common.Address `json:"address"` 93 AccountProof []string `json:"accountProof"` 94 Balance *hexutil.Big `json:"balance"` 95 CodeHash common.Hash `json:"codeHash"` 96 Nonce hexutil.Uint64 `json:"nonce"` 97 StorageHash common.Hash `json:"storageHash"` 98 StorageProof []storageResult `json:"storageProof"` 99 } 100 101 // Avoid keys being 'null'. 102 if keys == nil { 103 keys = []string{} 104 } 105 106 var res accountResult 107 err := ec.c.CallContext(ctx, &res, "eth_getProof", account, keys, toBlockNumArg(blockNumber)) 108 // Turn hexutils back to normal datatypes 109 storageResults := make([]StorageResult, 0, len(res.StorageProof)) 110 for _, st := range res.StorageProof { 111 storageResults = append(storageResults, StorageResult{ 112 Key: st.Key, 113 Value: st.Value.ToInt(), 114 Proof: st.Proof, 115 }) 116 } 117 result := AccountResult{ 118 Address: res.Address, 119 AccountProof: res.AccountProof, 120 Balance: res.Balance.ToInt(), 121 Nonce: uint64(res.Nonce), 122 CodeHash: res.CodeHash, 123 StorageHash: res.StorageHash, 124 StorageProof: storageResults, 125 } 126 return &result, err 127 } 128 129 // CallContract executes a message call transaction, which is directly executed in the VM 130 // of the node, but never mined into the blockchain. 131 // 132 // blockNumber selects the block height at which the call runs. It can be nil, in which 133 // case the code is taken from the latest known block. Note that state from very old 134 // blocks might not be available. 135 // 136 // overrides specifies a map of contract states that should be overwritten before executing 137 // the message call. 138 // Please use ethclient.CallContract instead if you don't need the override functionality. 139 func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int, overrides *map[common.Address]OverrideAccount) ([]byte, error) { 140 var hex hexutil.Bytes 141 err := ec.c.CallContext( 142 ctx, &hex, "eth_call", toCallArg(msg), 143 toBlockNumArg(blockNumber), overrides, 144 ) 145 return hex, err 146 } 147 148 // CallContractWithBlockOverrides executes a message call transaction, which is directly executed 149 // in the VM of the node, but never mined into the blockchain. 150 // 151 // blockNumber selects the block height at which the call runs. It can be nil, in which 152 // case the code is taken from the latest known block. Note that state from very old 153 // blocks might not be available. 154 // 155 // overrides specifies a map of contract states that should be overwritten before executing 156 // the message call. 157 // 158 // blockOverrides specifies block fields exposed to the EVM that can be overridden for the call. 159 // 160 // Please use ethclient.CallContract instead if you don't need the override functionality. 161 func (ec *Client) CallContractWithBlockOverrides(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int, overrides *map[common.Address]OverrideAccount, blockOverrides BlockOverrides) ([]byte, error) { 162 var hex hexutil.Bytes 163 err := ec.c.CallContext( 164 ctx, &hex, "eth_call", toCallArg(msg), 165 toBlockNumArg(blockNumber), overrides, blockOverrides, 166 ) 167 return hex, err 168 } 169 170 // GCStats retrieves the current garbage collection stats from a geth node. 171 func (ec *Client) GCStats(ctx context.Context) (*debug.GCStats, error) { 172 var result debug.GCStats 173 err := ec.c.CallContext(ctx, &result, "debug_gcStats") 174 return &result, err 175 } 176 177 // MemStats retrieves the current memory stats from a geth node. 178 func (ec *Client) MemStats(ctx context.Context) (*runtime.MemStats, error) { 179 var result runtime.MemStats 180 err := ec.c.CallContext(ctx, &result, "debug_memStats") 181 return &result, err 182 } 183 184 // SetHead sets the current head of the local chain by block number. 185 // Note, this is a destructive action and may severely damage your chain. 186 // Use with extreme caution. 187 func (ec *Client) SetHead(ctx context.Context, number *big.Int) error { 188 return ec.c.CallContext(ctx, nil, "debug_setHead", toBlockNumArg(number)) 189 } 190 191 // GetNodeInfo retrieves the node info of a geth node. 192 func (ec *Client) GetNodeInfo(ctx context.Context) (*p2p.NodeInfo, error) { 193 var result p2p.NodeInfo 194 err := ec.c.CallContext(ctx, &result, "admin_nodeInfo") 195 return &result, err 196 } 197 198 // SubscribeFullPendingTransactions subscribes to new pending transactions. 199 func (ec *Client) SubscribeFullPendingTransactions(ctx context.Context, ch chan<- *types.Transaction) (*rpc.ClientSubscription, error) { 200 return ec.c.EthSubscribe(ctx, ch, "newPendingTransactions", true) 201 } 202 203 // SubscribePendingTransactions subscribes to new pending transaction hashes. 204 func (ec *Client) SubscribePendingTransactions(ctx context.Context, ch chan<- common.Hash) (*rpc.ClientSubscription, error) { 205 return ec.c.EthSubscribe(ctx, ch, "newPendingTransactions") 206 } 207 208 // TraceTransaction returns the structured logs created during the execution of EVM 209 // and returns them as a JSON object. 210 func (ec *Client) TraceTransaction(ctx context.Context, hash common.Hash, config *tracers.TraceConfig) (any, error) { 211 var result any 212 err := ec.c.CallContext(ctx, &result, "debug_traceTransaction", hash.Hex(), config) 213 if err != nil { 214 return nil, err 215 } 216 return result, nil 217 } 218 219 func toBlockNumArg(number *big.Int) string { 220 if number == nil { 221 return "latest" 222 } 223 if number.Sign() >= 0 { 224 return hexutil.EncodeBig(number) 225 } 226 // It's negative. 227 if number.IsInt64() { 228 return rpc.BlockNumber(number.Int64()).String() 229 } 230 // It's negative and large, which is invalid. 231 return fmt.Sprintf("<invalid %d>", number) 232 } 233 234 func toCallArg(msg ethereum.CallMsg) interface{} { 235 arg := map[string]interface{}{ 236 "from": msg.From, 237 "to": msg.To, 238 } 239 if len(msg.Data) > 0 { 240 arg["input"] = hexutil.Bytes(msg.Data) 241 } 242 if msg.Value != nil { 243 arg["value"] = (*hexutil.Big)(msg.Value) 244 } 245 if msg.Gas != 0 { 246 arg["gas"] = hexutil.Uint64(msg.Gas) 247 } 248 if msg.GasPrice != nil { 249 arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice) 250 } 251 if msg.GasFeeCap != nil { 252 arg["maxFeePerGas"] = (*hexutil.Big)(msg.GasFeeCap) 253 } 254 if msg.GasTipCap != nil { 255 arg["maxPriorityFeePerGas"] = (*hexutil.Big)(msg.GasTipCap) 256 } 257 if msg.AccessList != nil { 258 arg["accessList"] = msg.AccessList 259 } 260 if msg.BlobGasFeeCap != nil { 261 arg["maxFeePerBlobGas"] = (*hexutil.Big)(msg.BlobGasFeeCap) 262 } 263 if msg.BlobHashes != nil { 264 arg["blobVersionedHashes"] = msg.BlobHashes 265 } 266 if msg.AuthorizationList != nil { 267 arg["authorizationList"] = msg.AuthorizationList 268 } 269 return arg 270 } 271 272 // OverrideAccount specifies the state of an account to be overridden. 273 type OverrideAccount struct { 274 // Nonce sets nonce of the account. Note: the nonce override will only 275 // be applied when it is set to a non-zero value. 276 Nonce uint64 277 278 // Code sets the contract code. The override will be applied 279 // when the code is non-nil, i.e. setting empty code is possible 280 // using an empty slice. 281 Code []byte 282 283 // Balance sets the account balance. 284 Balance *big.Int 285 286 // State sets the complete storage. The override will be applied 287 // when the given map is non-nil. Using an empty map wipes the 288 // entire contract storage during the call. 289 State map[common.Hash]common.Hash 290 291 // StateDiff allows overriding individual storage slots. 292 StateDiff map[common.Hash]common.Hash 293 } 294 295 func (a OverrideAccount) MarshalJSON() ([]byte, error) { 296 type acc struct { 297 Nonce hexutil.Uint64 `json:"nonce,omitempty"` 298 Code string `json:"code,omitempty"` 299 Balance *hexutil.Big `json:"balance,omitempty"` 300 State interface{} `json:"state,omitempty"` 301 StateDiff map[common.Hash]common.Hash `json:"stateDiff,omitempty"` 302 } 303 304 output := acc{ 305 Nonce: hexutil.Uint64(a.Nonce), 306 Balance: (*hexutil.Big)(a.Balance), 307 StateDiff: a.StateDiff, 308 } 309 if a.Code != nil { 310 output.Code = hexutil.Encode(a.Code) 311 } 312 if a.State != nil { 313 output.State = a.State 314 } 315 return json.Marshal(output) 316 } 317 318 // BlockOverrides specifies the set of header fields to override. 319 type BlockOverrides struct { 320 // Number overrides the block number. 321 Number *big.Int 322 // Difficulty overrides the block difficulty. 323 Difficulty *big.Int 324 // Time overrides the block timestamp. Time is applied only when 325 // it is non-zero. 326 Time uint64 327 // GasLimit overrides the block gas limit. GasLimit is applied only when 328 // it is non-zero. 329 GasLimit uint64 330 // Coinbase overrides the block coinbase. Coinbase is applied only when 331 // it is different from the zero address. 332 Coinbase common.Address 333 // Random overrides the block extra data which feeds into the RANDOM opcode. 334 // Random is applied only when it is a non-zero hash. 335 Random common.Hash 336 // BaseFee overrides the block base fee. 337 BaseFee *big.Int 338 } 339 340 func (o BlockOverrides) MarshalJSON() ([]byte, error) { 341 type override struct { 342 Number *hexutil.Big `json:"number,omitempty"` 343 Difficulty *hexutil.Big `json:"difficulty,omitempty"` 344 Time hexutil.Uint64 `json:"time,omitempty"` 345 GasLimit hexutil.Uint64 `json:"gasLimit,omitempty"` 346 Coinbase *common.Address `json:"feeRecipient,omitempty"` 347 Random *common.Hash `json:"prevRandao,omitempty"` 348 BaseFee *hexutil.Big `json:"baseFeePerGas,omitempty"` 349 } 350 351 output := override{ 352 Number: (*hexutil.Big)(o.Number), 353 Difficulty: (*hexutil.Big)(o.Difficulty), 354 Time: hexutil.Uint64(o.Time), 355 GasLimit: hexutil.Uint64(o.GasLimit), 356 BaseFee: (*hexutil.Big)(o.BaseFee), 357 } 358 if o.Coinbase != (common.Address{}) { 359 output.Coinbase = &o.Coinbase 360 } 361 if o.Random != (common.Hash{}) { 362 output.Random = &o.Random 363 } 364 return json.Marshal(output) 365 }