github.com/ConsenSys/Quorum@v20.10.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  	BlockNumber *big.Int        // Optional the block number on which the call should be performed
    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, opts.BlockNumber)
   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, opts.BlockNumber); 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, GasPrice: gasPrice, 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  	// Quorum
   247  	// If this transaction is private, we need to substitute the data payload
   248  	// with the hash of the transaction from tessera/constellation.
   249  	if opts.PrivateFor != nil {
   250  		var payload []byte
   251  		hash, err := c.transactor.PreparePrivateTransaction(rawTx.Data(), opts.PrivateFrom)
   252  		if err != nil {
   253  			return nil, err
   254  		}
   255  		payload = hash.Bytes()
   256  		rawTx = c.createPrivateTransaction(rawTx, payload)
   257  	}
   258  
   259  	// Choose signer to sign transaction
   260  	if opts.Signer == nil {
   261  		return nil, errors.New("no signer to authorize the transaction with")
   262  	}
   263  	var signedTx *types.Transaction
   264  	if rawTx.IsPrivate() {
   265  		signedTx, err = opts.Signer(types.QuorumPrivateTxSigner{}, opts.From, rawTx)
   266  	} else {
   267  		signedTx, err = opts.Signer(types.HomesteadSigner{}, opts.From, rawTx)
   268  	}
   269  	if err != nil {
   270  		return nil, err
   271  	}
   272  
   273  	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx, PrivateTxArgs{PrivateFor: opts.PrivateFor}); err != nil {
   274  		return nil, err
   275  	}
   276  
   277  	return signedTx, nil
   278  }
   279  
   280  // FilterLogs filters contract logs for past blocks, returning the necessary
   281  // channels to construct a strongly typed bound iterator on top of them.
   282  func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   283  	// Don't crash on a lazy user
   284  	if opts == nil {
   285  		opts = new(FilterOpts)
   286  	}
   287  	// Append the event selector to the query parameters and construct the topic set
   288  	query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
   289  
   290  	topics, err := makeTopics(query...)
   291  	if err != nil {
   292  		return nil, nil, err
   293  	}
   294  	// Start the background filtering
   295  	logs := make(chan types.Log, 128)
   296  
   297  	config := ethereum.FilterQuery{
   298  		Addresses: []common.Address{c.address},
   299  		Topics:    topics,
   300  		FromBlock: new(big.Int).SetUint64(opts.Start),
   301  	}
   302  	if opts.End != nil {
   303  		config.ToBlock = new(big.Int).SetUint64(*opts.End)
   304  	}
   305  	/* TODO(karalabe): Replace the rest of the method below with this when supported
   306  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   307  	*/
   308  	buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
   309  	if err != nil {
   310  		return nil, nil, err
   311  	}
   312  	sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
   313  		for _, log := range buff {
   314  			select {
   315  			case logs <- log:
   316  			case <-quit:
   317  				return nil
   318  			}
   319  		}
   320  		return nil
   321  	}), nil
   322  
   323  	if err != nil {
   324  		return nil, nil, err
   325  	}
   326  	return logs, sub, nil
   327  }
   328  
   329  // WatchLogs filters subscribes to contract logs for future blocks, returning a
   330  // subscription object that can be used to tear down the watcher.
   331  func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   332  	// Don't crash on a lazy user
   333  	if opts == nil {
   334  		opts = new(WatchOpts)
   335  	}
   336  	// Append the event selector to the query parameters and construct the topic set
   337  	query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
   338  
   339  	topics, err := makeTopics(query...)
   340  	if err != nil {
   341  		return nil, nil, err
   342  	}
   343  	// Start the background filtering
   344  	logs := make(chan types.Log, 128)
   345  
   346  	config := ethereum.FilterQuery{
   347  		Addresses: []common.Address{c.address},
   348  		Topics:    topics,
   349  	}
   350  	if opts.Start != nil {
   351  		config.FromBlock = new(big.Int).SetUint64(*opts.Start)
   352  	}
   353  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   354  	if err != nil {
   355  		return nil, nil, err
   356  	}
   357  	return logs, sub, nil
   358  }
   359  
   360  // UnpackLog unpacks a retrieved log into the provided output structure.
   361  func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
   362  	if len(log.Data) > 0 {
   363  		if err := c.abi.Unpack(out, event, log.Data); err != nil {
   364  			return err
   365  		}
   366  	}
   367  	var indexed abi.Arguments
   368  	for _, arg := range c.abi.Events[event].Inputs {
   369  		if arg.Indexed {
   370  			indexed = append(indexed, arg)
   371  		}
   372  	}
   373  	return parseTopics(out, indexed, log.Topics[1:])
   374  }
   375  
   376  // UnpackLogIntoMap unpacks a retrieved log into the provided map.
   377  func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
   378  	if len(log.Data) > 0 {
   379  		if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
   380  			return err
   381  		}
   382  	}
   383  	var indexed abi.Arguments
   384  	for _, arg := range c.abi.Events[event].Inputs {
   385  		if arg.Indexed {
   386  			indexed = append(indexed, arg)
   387  		}
   388  	}
   389  	return parseTopicsIntoMap(out, indexed, log.Topics[1:])
   390  }
   391  
   392  // Quorum
   393  // createPrivateTransaction replaces the payload of private transaction to the hash from Tessera/Constellation
   394  func (c *BoundContract) createPrivateTransaction(tx *types.Transaction, payload []byte) *types.Transaction {
   395  	var privateTx *types.Transaction
   396  	if tx.To() == nil {
   397  		privateTx = types.NewContractCreation(tx.Nonce(), tx.Value(), tx.Gas(), tx.GasPrice(), payload)
   398  	} else {
   399  		privateTx = types.NewTransaction(tx.Nonce(), c.address, tx.Value(), tx.Gas(), tx.GasPrice(), payload)
   400  	}
   401  	privateTx.SetPrivate()
   402  	return privateTx
   403  }
   404  
   405  // ensureContext is a helper method to ensure a context is not nil, even if the
   406  // user specified it as such.
   407  func ensureContext(ctx context.Context) context.Context {
   408  	if ctx == nil {
   409  		return context.TODO()
   410  	}
   411  	return ctx
   412  }