base.go 12 KB

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