github.com/hyperion-hyn/go-ethereum@v2.4.0+incompatible/accounts/abi/bind/base.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 bind 18 19 import ( 20 "context" 21 "errors" 22 "fmt" 23 "math/big" 24 25 "github.com/ethereum/go-ethereum" 26 "github.com/ethereum/go-ethereum/accounts/abi" 27 "github.com/ethereum/go-ethereum/common" 28 "github.com/ethereum/go-ethereum/core/types" 29 "github.com/ethereum/go-ethereum/crypto" 30 "github.com/ethereum/go-ethereum/event" 31 ) 32 33 // SignerFn is a signer function callback when a contract requires a method to 34 // sign the transaction before submission. 35 type SignerFn func(types.Signer, common.Address, *types.Transaction) (*types.Transaction, error) 36 37 // Quorum 38 // 39 // Additional arguments in order to support transaction privacy 40 type PrivateTxArgs struct { 41 PrivateFor []string `json:"privateFor"` 42 } 43 44 // CallOpts is the collection of options to fine tune a contract call request. 45 type CallOpts struct { 46 Pending bool // Whether to operate on the pending state or the last known one 47 From common.Address // Optional the sender address, otherwise the first account is used 48 49 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 50 } 51 52 // TransactOpts is the collection of authorization data required to create a 53 // valid Ethereum transaction. 54 type TransactOpts struct { 55 From common.Address // Ethereum account to send the transaction from 56 Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state) 57 Signer SignerFn // Method to use for signing the transaction (mandatory) 58 59 Value *big.Int // Funds to transfer along along the transaction (nil = 0 = no funds) 60 GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle) 61 GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate) 62 63 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 64 65 // Quorum 66 PrivateFrom string // The public key of the Tessera/Constellation identity to send this tx from. 67 PrivateFor []string // The public keys of the Tessera/Constellation identities this tx is intended for. 68 } 69 70 // FilterOpts is the collection of options to fine tune filtering for events 71 // within a bound contract. 72 type FilterOpts struct { 73 Start uint64 // Start of the queried range 74 End *uint64 // End of the range (nil = latest) 75 76 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 77 } 78 79 // WatchOpts is the collection of options to fine tune subscribing for events 80 // within a bound contract. 81 type WatchOpts struct { 82 Start *uint64 // Start of the queried range (nil = latest) 83 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 84 } 85 86 // BoundContract is the base wrapper object that reflects a contract on the 87 // Ethereum network. It contains a collection of methods that are used by the 88 // higher level contract bindings to operate. 89 type BoundContract struct { 90 address common.Address // Deployment address of the contract on the Ethereum blockchain 91 abi abi.ABI // Reflect based ABI to access the correct Ethereum methods 92 caller ContractCaller // Read interface to interact with the blockchain 93 transactor ContractTransactor // Write interface to interact with the blockchain 94 filterer ContractFilterer // Event filtering to interact with the blockchain 95 } 96 97 // NewBoundContract creates a low level contract interface through which calls 98 // and transactions may be made through. 99 func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract { 100 return &BoundContract{ 101 address: address, 102 abi: abi, 103 caller: caller, 104 transactor: transactor, 105 filterer: filterer, 106 } 107 } 108 109 // DeployContract deploys a contract onto the Ethereum blockchain and binds the 110 // deployment address with a Go wrapper. 111 func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) { 112 // Otherwise try to deploy the contract 113 c := NewBoundContract(common.Address{}, abi, backend, backend, backend) 114 115 input, err := c.abi.Pack("", params...) 116 if err != nil { 117 return common.Address{}, nil, nil, err 118 } 119 tx, err := c.transact(opts, nil, append(bytecode, input...)) 120 if err != nil { 121 return common.Address{}, nil, nil, err 122 } 123 c.address = crypto.CreateAddress(opts.From, tx.Nonce()) 124 return c.address, tx, c, nil 125 } 126 127 // Call invokes the (constant) contract method with params as input values and 128 // sets the output to result. The result type might be a single field for simple 129 // returns, a slice of interfaces for anonymous returns and a struct for named 130 // returns. 131 func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, params ...interface{}) error { 132 // Don't crash on a lazy user 133 if opts == nil { 134 opts = new(CallOpts) 135 } 136 // Pack the input, call and unpack the results 137 input, err := c.abi.Pack(method, params...) 138 if err != nil { 139 return err 140 } 141 var ( 142 msg = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input} 143 ctx = ensureContext(opts.Context) 144 code []byte 145 output []byte 146 ) 147 if opts.Pending { 148 pb, ok := c.caller.(PendingContractCaller) 149 if !ok { 150 return ErrNoPendingState 151 } 152 output, err = pb.PendingCallContract(ctx, msg) 153 if err == nil && len(output) == 0 { 154 // Make sure we have a contract to operate on, and bail out otherwise. 155 if code, err = pb.PendingCodeAt(ctx, c.address); err != nil { 156 return err 157 } else if len(code) == 0 { 158 return ErrNoCode 159 } 160 } 161 } else { 162 output, err = c.caller.CallContract(ctx, msg, nil) 163 if err == nil && len(output) == 0 { 164 // Make sure we have a contract to operate on, and bail out otherwise. 165 if code, err = c.caller.CodeAt(ctx, c.address, nil); err != nil { 166 return err 167 } else if len(code) == 0 { 168 return ErrNoCode 169 } 170 } 171 } 172 if err != nil { 173 return err 174 } 175 return c.abi.Unpack(result, method, output) 176 } 177 178 // Transact invokes the (paid) contract method with params as input values. 179 func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { 180 // Otherwise pack up the parameters and invoke the contract 181 input, err := c.abi.Pack(method, params...) 182 if err != nil { 183 return nil, err 184 } 185 return c.transact(opts, &c.address, input) 186 } 187 188 // Transfer initiates a plain transaction to move funds to the contract, calling 189 // its default method if one is available. 190 func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) { 191 return c.transact(opts, &c.address, nil) 192 } 193 194 // transact executes an actual transaction invocation, first deriving any missing 195 // authorization fields, and then scheduling the transaction for execution. 196 func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) { 197 var err error 198 199 // Ensure a valid value field and resolve the account nonce 200 value := opts.Value 201 if value == nil { 202 value = new(big.Int) 203 } 204 var nonce uint64 205 if opts.Nonce == nil { 206 nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From) 207 if err != nil { 208 return nil, fmt.Errorf("failed to retrieve account nonce: %v", err) 209 } 210 } else { 211 nonce = opts.Nonce.Uint64() 212 } 213 // Figure out the gas allowance and gas price values 214 gasPrice := opts.GasPrice 215 if gasPrice == nil { 216 gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context)) 217 if err != nil { 218 return nil, fmt.Errorf("failed to suggest gas price: %v", err) 219 } 220 } 221 gasLimit := opts.GasLimit 222 if gasLimit == 0 { 223 // Gas estimation cannot succeed without code for method invocations 224 if contract != nil { 225 if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil { 226 return nil, err 227 } else if len(code) == 0 { 228 return nil, ErrNoCode 229 } 230 } 231 // If the contract surely has code (or code is not needed), estimate the transaction 232 msg := ethereum.CallMsg{From: opts.From, To: contract, Value: value, Data: input} 233 gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg) 234 if err != nil { 235 return nil, fmt.Errorf("failed to estimate gas needed: %v", err) 236 } 237 } 238 // Create the transaction, sign it and schedule it for execution 239 var rawTx *types.Transaction 240 if contract == nil { 241 rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input) 242 } else { 243 rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input) 244 } 245 246 // If this transaction is private, we need to substitute the data payload 247 // with the hash of the transaction from tessera/constellation. 248 if opts.PrivateFor != nil { 249 var payload []byte 250 payload, err = c.transactor.PreparePrivateTransaction(rawTx.Data(), opts.PrivateFrom) 251 if err != nil { 252 return nil, err 253 } 254 rawTx = c.createPrivateTransaction(rawTx, payload) 255 } 256 257 // Choose signer to sign transaction 258 if opts.Signer == nil { 259 return nil, errors.New("no signer to authorize the transaction with") 260 } 261 var signedTx *types.Transaction 262 if rawTx.IsPrivate() { 263 signedTx, err = opts.Signer(types.QuorumPrivateTxSigner{}, opts.From, rawTx) 264 } else { 265 signedTx, err = opts.Signer(types.HomesteadSigner{}, opts.From, rawTx) 266 } 267 if err != nil { 268 return nil, err 269 } 270 271 if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx, PrivateTxArgs{PrivateFor: opts.PrivateFor}); err != nil { 272 return nil, err 273 } 274 275 return signedTx, nil 276 } 277 278 // FilterLogs filters contract logs for past blocks, returning the necessary 279 // channels to construct a strongly typed bound iterator on top of them. 280 func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { 281 // Don't crash on a lazy user 282 if opts == nil { 283 opts = new(FilterOpts) 284 } 285 // Append the event selector to the query parameters and construct the topic set 286 query = append([][]interface{}{{c.abi.Events[name].Id()}}, query...) 287 288 topics, err := makeTopics(query...) 289 if err != nil { 290 return nil, nil, err 291 } 292 // Start the background filtering 293 logs := make(chan types.Log, 128) 294 295 config := ethereum.FilterQuery{ 296 Addresses: []common.Address{c.address}, 297 Topics: topics, 298 FromBlock: new(big.Int).SetUint64(opts.Start), 299 } 300 if opts.End != nil { 301 config.ToBlock = new(big.Int).SetUint64(*opts.End) 302 } 303 /* TODO(karalabe): Replace the rest of the method below with this when supported 304 sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) 305 */ 306 buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config) 307 if err != nil { 308 return nil, nil, err 309 } 310 sub, err := event.NewSubscription(func(quit <-chan struct{}) error { 311 for _, log := range buff { 312 select { 313 case logs <- log: 314 case <-quit: 315 return nil 316 } 317 } 318 return nil 319 }), nil 320 321 if err != nil { 322 return nil, nil, err 323 } 324 return logs, sub, nil 325 } 326 327 // WatchLogs filters subscribes to contract logs for future blocks, returning a 328 // subscription object that can be used to tear down the watcher. 329 func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { 330 // Don't crash on a lazy user 331 if opts == nil { 332 opts = new(WatchOpts) 333 } 334 // Append the event selector to the query parameters and construct the topic set 335 query = append([][]interface{}{{c.abi.Events[name].Id()}}, query...) 336 337 topics, err := makeTopics(query...) 338 if err != nil { 339 return nil, nil, err 340 } 341 // Start the background filtering 342 logs := make(chan types.Log, 128) 343 344 config := ethereum.FilterQuery{ 345 Addresses: []common.Address{c.address}, 346 Topics: topics, 347 } 348 if opts.Start != nil { 349 config.FromBlock = new(big.Int).SetUint64(*opts.Start) 350 } 351 sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) 352 if err != nil { 353 return nil, nil, err 354 } 355 return logs, sub, nil 356 } 357 358 // UnpackLog unpacks a retrieved log into the provided output structure. 359 func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error { 360 if len(log.Data) > 0 { 361 if err := c.abi.Unpack(out, event, log.Data); err != nil { 362 return err 363 } 364 } 365 var indexed abi.Arguments 366 for _, arg := range c.abi.Events[event].Inputs { 367 if arg.Indexed { 368 indexed = append(indexed, arg) 369 } 370 } 371 return parseTopics(out, indexed, log.Topics[1:]) 372 } 373 374 // createPrivateTransaction replaces the payload of private transaction to the hash from Tessera/Constellation 375 func (c *BoundContract) createPrivateTransaction(tx *types.Transaction, payload []byte) *types.Transaction { 376 var privateTx *types.Transaction 377 if tx.To() == nil { 378 privateTx = types.NewContractCreation(tx.Nonce(), tx.Value(), tx.Gas(), tx.GasPrice(), payload) 379 } else { 380 privateTx = types.NewTransaction(tx.Nonce(), c.address, tx.Value(), tx.Gas(), tx.GasPrice(), payload) 381 } 382 privateTx.SetPrivate() 383 return privateTx 384 } 385 386 // ensureContext is a helper method to ensure a context is not nil, even if the 387 // user specified it as such. 388 func ensureContext(ctx context.Context) context.Context { 389 if ctx == nil { 390 return context.TODO() 391 } 392 return ctx 393 }