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