base_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. // Copyright 2019 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_test
  17. import (
  18. "context"
  19. "errors"
  20. "math/big"
  21. "reflect"
  22. "strings"
  23. "testing"
  24. "github.com/ethereum/go-ethereum"
  25. "github.com/ethereum/go-ethereum/accounts/abi"
  26. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/hexutil"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. "github.com/stretchr/testify/assert"
  33. )
  34. func mockSign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) { return tx, nil }
  35. type mockTransactor struct {
  36. baseFee *big.Int
  37. gasTipCap *big.Int
  38. gasPrice *big.Int
  39. suggestGasTipCapCalled bool
  40. suggestGasPriceCalled bool
  41. }
  42. func (mt *mockTransactor) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  43. return &types.Header{BaseFee: mt.baseFee}, nil
  44. }
  45. func (mt *mockTransactor) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) {
  46. return []byte{1}, nil
  47. }
  48. func (mt *mockTransactor) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  49. return 0, nil
  50. }
  51. func (mt *mockTransactor) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  52. mt.suggestGasPriceCalled = true
  53. return mt.gasPrice, nil
  54. }
  55. func (mt *mockTransactor) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
  56. mt.suggestGasTipCapCalled = true
  57. return mt.gasTipCap, nil
  58. }
  59. func (mt *mockTransactor) EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error) {
  60. return 0, nil
  61. }
  62. func (mt *mockTransactor) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  63. return nil
  64. }
  65. type mockCaller struct {
  66. codeAtBlockNumber *big.Int
  67. callContractBlockNumber *big.Int
  68. callContractBytes []byte
  69. callContractErr error
  70. codeAtBytes []byte
  71. codeAtErr error
  72. }
  73. func (mc *mockCaller) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
  74. mc.codeAtBlockNumber = blockNumber
  75. return mc.codeAtBytes, mc.codeAtErr
  76. }
  77. func (mc *mockCaller) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  78. mc.callContractBlockNumber = blockNumber
  79. return mc.callContractBytes, mc.callContractErr
  80. }
  81. type mockPendingCaller struct {
  82. *mockCaller
  83. pendingCodeAtBytes []byte
  84. pendingCodeAtErr error
  85. pendingCodeAtCalled bool
  86. pendingCallContractCalled bool
  87. pendingCallContractBytes []byte
  88. pendingCallContractErr error
  89. }
  90. func (mc *mockPendingCaller) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
  91. mc.pendingCodeAtCalled = true
  92. return mc.pendingCodeAtBytes, mc.pendingCodeAtErr
  93. }
  94. func (mc *mockPendingCaller) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
  95. mc.pendingCallContractCalled = true
  96. return mc.pendingCallContractBytes, mc.pendingCallContractErr
  97. }
  98. func TestPassingBlockNumber(t *testing.T) {
  99. mc := &mockPendingCaller{
  100. mockCaller: &mockCaller{
  101. codeAtBytes: []byte{1, 2, 3},
  102. },
  103. }
  104. bc := bind.NewBoundContract(common.HexToAddress("0x0"), abi.ABI{
  105. Methods: map[string]abi.Method{
  106. "something": {
  107. Name: "something",
  108. Outputs: abi.Arguments{},
  109. },
  110. },
  111. }, mc, nil, nil)
  112. blockNumber := big.NewInt(42)
  113. bc.Call(&bind.CallOpts{BlockNumber: blockNumber}, nil, "something")
  114. if mc.callContractBlockNumber != blockNumber {
  115. t.Fatalf("CallContract() was not passed the block number")
  116. }
  117. if mc.codeAtBlockNumber != blockNumber {
  118. t.Fatalf("CodeAt() was not passed the block number")
  119. }
  120. bc.Call(&bind.CallOpts{}, nil, "something")
  121. if mc.callContractBlockNumber != nil {
  122. t.Fatalf("CallContract() was passed a block number when it should not have been")
  123. }
  124. if mc.codeAtBlockNumber != nil {
  125. t.Fatalf("CodeAt() was passed a block number when it should not have been")
  126. }
  127. bc.Call(&bind.CallOpts{BlockNumber: blockNumber, Pending: true}, nil, "something")
  128. if !mc.pendingCallContractCalled {
  129. t.Fatalf("CallContract() was not passed the block number")
  130. }
  131. if !mc.pendingCodeAtCalled {
  132. t.Fatalf("CodeAt() was not passed the block number")
  133. }
  134. }
  135. const hexData = "0x000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158"
  136. func TestUnpackIndexedStringTyLogIntoMap(t *testing.T) {
  137. hash := crypto.Keccak256Hash([]byte("testName"))
  138. topics := []common.Hash{
  139. crypto.Keccak256Hash([]byte("received(string,address,uint256,bytes)")),
  140. hash,
  141. }
  142. mockLog := newMockLog(topics, common.HexToHash("0x0"))
  143. abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"string"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
  144. parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
  145. bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
  146. expectedReceivedMap := map[string]interface{}{
  147. "name": hash,
  148. "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
  149. "amount": big.NewInt(1),
  150. "memo": []byte{88},
  151. }
  152. unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
  153. }
  154. func TestUnpackIndexedSliceTyLogIntoMap(t *testing.T) {
  155. sliceBytes, err := rlp.EncodeToBytes([]string{"name1", "name2", "name3", "name4"})
  156. if err != nil {
  157. t.Fatal(err)
  158. }
  159. hash := crypto.Keccak256Hash(sliceBytes)
  160. topics := []common.Hash{
  161. crypto.Keccak256Hash([]byte("received(string[],address,uint256,bytes)")),
  162. hash,
  163. }
  164. mockLog := newMockLog(topics, common.HexToHash("0x0"))
  165. abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"names","type":"string[]"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
  166. parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
  167. bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
  168. expectedReceivedMap := map[string]interface{}{
  169. "names": hash,
  170. "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
  171. "amount": big.NewInt(1),
  172. "memo": []byte{88},
  173. }
  174. unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
  175. }
  176. func TestUnpackIndexedArrayTyLogIntoMap(t *testing.T) {
  177. arrBytes, err := rlp.EncodeToBytes([2]common.Address{common.HexToAddress("0x0"), common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2")})
  178. if err != nil {
  179. t.Fatal(err)
  180. }
  181. hash := crypto.Keccak256Hash(arrBytes)
  182. topics := []common.Hash{
  183. crypto.Keccak256Hash([]byte("received(address[2],address,uint256,bytes)")),
  184. hash,
  185. }
  186. mockLog := newMockLog(topics, common.HexToHash("0x0"))
  187. abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"addresses","type":"address[2]"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
  188. parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
  189. bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
  190. expectedReceivedMap := map[string]interface{}{
  191. "addresses": hash,
  192. "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
  193. "amount": big.NewInt(1),
  194. "memo": []byte{88},
  195. }
  196. unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
  197. }
  198. func TestUnpackIndexedFuncTyLogIntoMap(t *testing.T) {
  199. mockAddress := common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2")
  200. addrBytes := mockAddress.Bytes()
  201. hash := crypto.Keccak256Hash([]byte("mockFunction(address,uint)"))
  202. functionSelector := hash[:4]
  203. functionTyBytes := append(addrBytes, functionSelector...)
  204. var functionTy [24]byte
  205. copy(functionTy[:], functionTyBytes[0:24])
  206. topics := []common.Hash{
  207. crypto.Keccak256Hash([]byte("received(function,address,uint256,bytes)")),
  208. common.BytesToHash(functionTyBytes),
  209. }
  210. mockLog := newMockLog(topics, common.HexToHash("0x5c698f13940a2153440c6d19660878bc90219d9298fdcf37365aa8d88d40fc42"))
  211. abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"function","type":"function"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
  212. parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
  213. bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
  214. expectedReceivedMap := map[string]interface{}{
  215. "function": functionTy,
  216. "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
  217. "amount": big.NewInt(1),
  218. "memo": []byte{88},
  219. }
  220. unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
  221. }
  222. func TestUnpackIndexedBytesTyLogIntoMap(t *testing.T) {
  223. bytes := []byte{1, 2, 3, 4, 5}
  224. hash := crypto.Keccak256Hash(bytes)
  225. topics := []common.Hash{
  226. crypto.Keccak256Hash([]byte("received(bytes,address,uint256,bytes)")),
  227. hash,
  228. }
  229. mockLog := newMockLog(topics, common.HexToHash("0x5c698f13940a2153440c6d19660878bc90219d9298fdcf37365aa8d88d40fc42"))
  230. abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"content","type":"bytes"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
  231. parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
  232. bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
  233. expectedReceivedMap := map[string]interface{}{
  234. "content": hash,
  235. "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
  236. "amount": big.NewInt(1),
  237. "memo": []byte{88},
  238. }
  239. unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
  240. }
  241. func TestTransactGasFee(t *testing.T) {
  242. assert := assert.New(t)
  243. // GasTipCap and GasFeeCap
  244. // When opts.GasTipCap and opts.GasFeeCap are nil
  245. mt := &mockTransactor{baseFee: big.NewInt(100), gasTipCap: big.NewInt(5)}
  246. bc := bind.NewBoundContract(common.Address{}, abi.ABI{}, nil, mt, nil)
  247. opts := &bind.TransactOpts{Signer: mockSign}
  248. tx, err := bc.Transact(opts, "")
  249. assert.Nil(err)
  250. assert.Equal(big.NewInt(5), tx.GasTipCap())
  251. assert.Equal(big.NewInt(205), tx.GasFeeCap())
  252. assert.Nil(opts.GasTipCap)
  253. assert.Nil(opts.GasFeeCap)
  254. assert.True(mt.suggestGasTipCapCalled)
  255. // Second call to Transact should use latest suggested GasTipCap
  256. mt.gasTipCap = big.NewInt(6)
  257. mt.suggestGasTipCapCalled = false
  258. tx, err = bc.Transact(opts, "")
  259. assert.Nil(err)
  260. assert.Equal(big.NewInt(6), tx.GasTipCap())
  261. assert.Equal(big.NewInt(206), tx.GasFeeCap())
  262. assert.True(mt.suggestGasTipCapCalled)
  263. // GasPrice
  264. // When opts.GasPrice is nil
  265. mt = &mockTransactor{gasPrice: big.NewInt(5)}
  266. bc = bind.NewBoundContract(common.Address{}, abi.ABI{}, nil, mt, nil)
  267. opts = &bind.TransactOpts{Signer: mockSign}
  268. tx, err = bc.Transact(opts, "")
  269. assert.Nil(err)
  270. assert.Equal(big.NewInt(5), tx.GasPrice())
  271. assert.Nil(opts.GasPrice)
  272. assert.True(mt.suggestGasPriceCalled)
  273. // Second call to Transact should use latest suggested GasPrice
  274. mt.gasPrice = big.NewInt(6)
  275. mt.suggestGasPriceCalled = false
  276. tx, err = bc.Transact(opts, "")
  277. assert.Nil(err)
  278. assert.Equal(big.NewInt(6), tx.GasPrice())
  279. assert.True(mt.suggestGasPriceCalled)
  280. }
  281. func unpackAndCheck(t *testing.T, bc *bind.BoundContract, expected map[string]interface{}, mockLog types.Log) {
  282. received := make(map[string]interface{})
  283. if err := bc.UnpackLogIntoMap(received, "received", mockLog); err != nil {
  284. t.Error(err)
  285. }
  286. if len(received) != len(expected) {
  287. t.Fatalf("unpacked map length %v not equal expected length of %v", len(received), len(expected))
  288. }
  289. for name, elem := range expected {
  290. if !reflect.DeepEqual(elem, received[name]) {
  291. t.Errorf("field %v does not match expected, want %v, got %v", name, elem, received[name])
  292. }
  293. }
  294. }
  295. func newMockLog(topics []common.Hash, txHash common.Hash) types.Log {
  296. return types.Log{
  297. Address: common.HexToAddress("0x0"),
  298. Topics: topics,
  299. Data: hexutil.MustDecode(hexData),
  300. BlockNumber: uint64(26),
  301. TxHash: txHash,
  302. TxIndex: 111,
  303. BlockHash: common.BytesToHash([]byte{1, 2, 3, 4, 5}),
  304. Index: 7,
  305. Removed: false,
  306. }
  307. }
  308. func TestCall(t *testing.T) {
  309. var method, methodWithArg = "something", "somethingArrrrg"
  310. tests := []struct {
  311. name, method string
  312. opts *bind.CallOpts
  313. mc bind.ContractCaller
  314. results *[]interface{}
  315. wantErr bool
  316. wantErrExact error
  317. }{{
  318. name: "ok not pending",
  319. mc: &mockCaller{
  320. codeAtBytes: []byte{0},
  321. },
  322. method: method,
  323. }, {
  324. name: "ok pending",
  325. mc: &mockPendingCaller{
  326. pendingCodeAtBytes: []byte{0},
  327. },
  328. opts: &bind.CallOpts{
  329. Pending: true,
  330. },
  331. method: method,
  332. }, {
  333. name: "pack error, no method",
  334. mc: new(mockCaller),
  335. method: "else",
  336. wantErr: true,
  337. }, {
  338. name: "interface error, pending but not a PendingContractCaller",
  339. mc: new(mockCaller),
  340. opts: &bind.CallOpts{
  341. Pending: true,
  342. },
  343. method: method,
  344. wantErrExact: bind.ErrNoPendingState,
  345. }, {
  346. name: "pending call canceled",
  347. mc: &mockPendingCaller{
  348. pendingCallContractErr: context.DeadlineExceeded,
  349. },
  350. opts: &bind.CallOpts{
  351. Pending: true,
  352. },
  353. method: method,
  354. wantErrExact: context.DeadlineExceeded,
  355. }, {
  356. name: "pending code at error",
  357. mc: &mockPendingCaller{
  358. pendingCodeAtErr: errors.New(""),
  359. },
  360. opts: &bind.CallOpts{
  361. Pending: true,
  362. },
  363. method: method,
  364. wantErr: true,
  365. }, {
  366. name: "no pending code at",
  367. mc: new(mockPendingCaller),
  368. opts: &bind.CallOpts{
  369. Pending: true,
  370. },
  371. method: method,
  372. wantErrExact: bind.ErrNoCode,
  373. }, {
  374. name: "call contract error",
  375. mc: &mockCaller{
  376. callContractErr: context.DeadlineExceeded,
  377. },
  378. method: method,
  379. wantErrExact: context.DeadlineExceeded,
  380. }, {
  381. name: "code at error",
  382. mc: &mockCaller{
  383. codeAtErr: errors.New(""),
  384. },
  385. method: method,
  386. wantErr: true,
  387. }, {
  388. name: "no code at",
  389. mc: new(mockCaller),
  390. method: method,
  391. wantErrExact: bind.ErrNoCode,
  392. }, {
  393. name: "unpack error missing arg",
  394. mc: &mockCaller{
  395. codeAtBytes: []byte{0},
  396. },
  397. method: methodWithArg,
  398. wantErr: true,
  399. }, {
  400. name: "interface unpack error",
  401. mc: &mockCaller{
  402. codeAtBytes: []byte{0},
  403. },
  404. method: method,
  405. results: &[]interface{}{0},
  406. wantErr: true,
  407. }}
  408. for _, test := range tests {
  409. bc := bind.NewBoundContract(common.HexToAddress("0x0"), abi.ABI{
  410. Methods: map[string]abi.Method{
  411. method: {
  412. Name: method,
  413. Outputs: abi.Arguments{},
  414. },
  415. methodWithArg: {
  416. Name: methodWithArg,
  417. Outputs: abi.Arguments{abi.Argument{}},
  418. },
  419. },
  420. }, test.mc, nil, nil)
  421. err := bc.Call(test.opts, test.results, test.method)
  422. if test.wantErr || test.wantErrExact != nil {
  423. if err == nil {
  424. t.Fatalf("%q expected error", test.name)
  425. }
  426. if test.wantErrExact != nil && !errors.Is(err, test.wantErrExact) {
  427. t.Fatalf("%q expected error %q but got %q", test.name, test.wantErrExact, err)
  428. }
  429. continue
  430. }
  431. if err != nil {
  432. t.Fatalf("%q unexpected error: %v", test.name, err)
  433. }
  434. }
  435. }
  436. // TestCrashers contains some strings which previously caused the abi codec to crash.
  437. func TestCrashers(t *testing.T) {
  438. abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"_1"}]}]}]`))
  439. abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"&"}]}]}]`))
  440. abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"----"}]}]}]`))
  441. abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"foo.Bar"}]}]}]`))
  442. }