base.go 16 KB

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