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