You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

297 lines
9.4 KiB

Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
3 years ago
  1. package api
  2. import (
  3. "fmt"
  4. "strconv"
  5. "testing"
  6. "time"
  7. ethCommon "github.com/ethereum/go-ethereum/common"
  8. "github.com/hermeznetwork/hermez-node/api/apitypes"
  9. "github.com/hermeznetwork/hermez-node/common"
  10. "github.com/hermeznetwork/hermez-node/db/historydb"
  11. "github.com/mitchellh/copystructure"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. )
  15. type testBatch struct {
  16. ItemID uint64 `json:"itemId"`
  17. BatchNum common.BatchNum `json:"batchNum"`
  18. EthBlockNum int64 `json:"ethereumBlockNum"`
  19. EthBlockHash ethCommon.Hash `json:"ethereumBlockHash"`
  20. Timestamp time.Time `json:"timestamp"`
  21. ForgerAddr ethCommon.Address `json:"forgerAddr"`
  22. CollectedFees apitypes.CollectedFeesAPI `json:"collectedFees"`
  23. TotalFeesUSD *float64 `json:"historicTotalCollectedFeesUSD"`
  24. StateRoot string `json:"stateRoot"`
  25. NumAccounts int `json:"numAccounts"`
  26. ExitRoot string `json:"exitRoot"`
  27. ForgeL1TxsNum *int64 `json:"forgeL1TransactionsNum"`
  28. SlotNum int64 `json:"slotNum"`
  29. ForgedTxs int `json:"forgedTransactions"`
  30. }
  31. type testBatchesResponse struct {
  32. Batches []testBatch `json:"batches"`
  33. PendingItems uint64 `json:"pendingItems"`
  34. }
  35. func (t testBatchesResponse) GetPending() (pendingItems, lastItemID uint64) {
  36. if len(t.Batches) == 0 {
  37. return 0, 0
  38. }
  39. pendingItems = t.PendingItems
  40. lastItemID = t.Batches[len(t.Batches)-1].ItemID
  41. return pendingItems, lastItemID
  42. }
  43. func (t testBatchesResponse) Len() int {
  44. return len(t.Batches)
  45. }
  46. func (t testBatchesResponse) New() Pendinger { return &testBatchesResponse{} }
  47. type testFullBatch struct {
  48. Batch testBatch `json:"batch"`
  49. Txs []testTx `json:"transactions"`
  50. }
  51. func genTestBatches(
  52. blocks []common.Block,
  53. cBatches []common.Batch,
  54. txs []testTx,
  55. ) ([]testBatch, []testFullBatch) {
  56. tBatches := []testBatch{}
  57. for i := 0; i < len(cBatches); i++ {
  58. block := common.Block{}
  59. found := false
  60. for _, b := range blocks {
  61. if b.Num == cBatches[i].EthBlockNum {
  62. block = b
  63. found = true
  64. break
  65. }
  66. }
  67. if !found {
  68. panic("block not found")
  69. }
  70. collectedFees := apitypes.CollectedFeesAPI(make(map[common.TokenID]apitypes.BigIntStr))
  71. for k, v := range cBatches[i].CollectedFees {
  72. collectedFees[k] = *apitypes.NewBigIntStr(v)
  73. }
  74. forgedTxs := 0
  75. for _, tx := range txs {
  76. if tx.BatchNum != nil && *tx.BatchNum == cBatches[i].BatchNum {
  77. forgedTxs++
  78. }
  79. }
  80. tBatch := testBatch{
  81. BatchNum: cBatches[i].BatchNum,
  82. EthBlockNum: cBatches[i].EthBlockNum,
  83. EthBlockHash: block.Hash,
  84. Timestamp: block.Timestamp,
  85. ForgerAddr: cBatches[i].ForgerAddr,
  86. CollectedFees: collectedFees,
  87. TotalFeesUSD: cBatches[i].TotalFeesUSD,
  88. StateRoot: cBatches[i].StateRoot.String(),
  89. NumAccounts: cBatches[i].NumAccounts,
  90. ExitRoot: cBatches[i].ExitRoot.String(),
  91. ForgeL1TxsNum: cBatches[i].ForgeL1TxsNum,
  92. SlotNum: cBatches[i].SlotNum,
  93. ForgedTxs: forgedTxs,
  94. }
  95. tBatches = append(tBatches, tBatch)
  96. }
  97. fullBatches := []testFullBatch{}
  98. for i := 0; i < len(tBatches); i++ {
  99. forgedTxs := []testTx{}
  100. for j := 0; j < len(txs); j++ {
  101. if txs[j].BatchNum != nil && *txs[j].BatchNum == tBatches[i].BatchNum {
  102. forgedTxs = append(forgedTxs, txs[j])
  103. }
  104. }
  105. fullBatches = append(fullBatches, testFullBatch{
  106. Batch: tBatches[i],
  107. Txs: forgedTxs,
  108. })
  109. }
  110. return tBatches, fullBatches
  111. }
  112. func TestGetBatches(t *testing.T) {
  113. endpoint := apiURL + "batches"
  114. fetchedBatches := []testBatch{}
  115. appendIter := func(intr interface{}) {
  116. for i := 0; i < len(intr.(*testBatchesResponse).Batches); i++ {
  117. tmp, err := copystructure.Copy(intr.(*testBatchesResponse).Batches[i])
  118. if err != nil {
  119. panic(err)
  120. }
  121. fetchedBatches = append(fetchedBatches, tmp.(testBatch))
  122. }
  123. }
  124. // Get all (no filters)
  125. limit := 3
  126. path := fmt.Sprintf("%s?limit=%d", endpoint, limit)
  127. err := doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  128. require.NoError(t, err)
  129. assertBatches(t, tc.batches, fetchedBatches)
  130. // minBatchNum
  131. fetchedBatches = []testBatch{}
  132. limit = 2
  133. minBatchNum := tc.batches[len(tc.batches)/2].BatchNum
  134. path = fmt.Sprintf("%s?minBatchNum=%d&limit=%d", endpoint, minBatchNum, limit)
  135. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  136. require.NoError(t, err)
  137. minBatchNumBatches := []testBatch{}
  138. for i := 0; i < len(tc.batches); i++ {
  139. if tc.batches[i].BatchNum > minBatchNum {
  140. minBatchNumBatches = append(minBatchNumBatches, tc.batches[i])
  141. }
  142. }
  143. assertBatches(t, minBatchNumBatches, fetchedBatches)
  144. // maxBatchNum
  145. fetchedBatches = []testBatch{}
  146. limit = 1
  147. maxBatchNum := tc.batches[len(tc.batches)/2].BatchNum
  148. path = fmt.Sprintf("%s?maxBatchNum=%d&limit=%d", endpoint, maxBatchNum, limit)
  149. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  150. require.NoError(t, err)
  151. maxBatchNumBatches := []testBatch{}
  152. for i := 0; i < len(tc.batches); i++ {
  153. if tc.batches[i].BatchNum < maxBatchNum {
  154. maxBatchNumBatches = append(maxBatchNumBatches, tc.batches[i])
  155. }
  156. }
  157. assertBatches(t, maxBatchNumBatches, fetchedBatches)
  158. // slotNum
  159. fetchedBatches = []testBatch{}
  160. limit = 5
  161. slotNum := tc.batches[len(tc.batches)/2].SlotNum
  162. path = fmt.Sprintf("%s?slotNum=%d&limit=%d", endpoint, slotNum, limit)
  163. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  164. require.NoError(t, err)
  165. slotNumBatches := []testBatch{}
  166. for i := 0; i < len(tc.batches); i++ {
  167. if tc.batches[i].SlotNum == slotNum {
  168. slotNumBatches = append(slotNumBatches, tc.batches[i])
  169. }
  170. }
  171. assertBatches(t, slotNumBatches, fetchedBatches)
  172. // forgerAddr
  173. fetchedBatches = []testBatch{}
  174. limit = 10
  175. forgerAddr := tc.batches[len(tc.batches)/2].ForgerAddr
  176. path = fmt.Sprintf("%s?forgerAddr=%s&limit=%d", endpoint, forgerAddr.String(), limit)
  177. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  178. require.NoError(t, err)
  179. forgerAddrBatches := []testBatch{}
  180. for i := 0; i < len(tc.batches); i++ {
  181. if tc.batches[i].ForgerAddr == forgerAddr {
  182. forgerAddrBatches = append(forgerAddrBatches, tc.batches[i])
  183. }
  184. }
  185. assertBatches(t, forgerAddrBatches, fetchedBatches)
  186. // All, in reverse order
  187. fetchedBatches = []testBatch{}
  188. limit = 6
  189. path = fmt.Sprintf("%s?limit=%d", endpoint, limit)
  190. err = doGoodReqPaginated(path, historydb.OrderDesc, &testBatchesResponse{}, appendIter)
  191. require.NoError(t, err)
  192. flippedBatches := []testBatch{}
  193. for i := len(tc.batches) - 1; i >= 0; i-- {
  194. flippedBatches = append(flippedBatches, tc.batches[i])
  195. }
  196. assertBatches(t, flippedBatches, fetchedBatches)
  197. // Mixed filters
  198. fetchedBatches = []testBatch{}
  199. limit = 1
  200. maxBatchNum = tc.batches[len(tc.batches)-len(tc.batches)/4].BatchNum
  201. minBatchNum = tc.batches[len(tc.batches)/4].BatchNum
  202. path = fmt.Sprintf("%s?minBatchNum=%d&maxBatchNum=%d&limit=%d", endpoint, minBatchNum, maxBatchNum, limit)
  203. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  204. require.NoError(t, err)
  205. minMaxBatchNumBatches := []testBatch{}
  206. for i := 0; i < len(tc.batches); i++ {
  207. if tc.batches[i].BatchNum < maxBatchNum && tc.batches[i].BatchNum > minBatchNum {
  208. minMaxBatchNumBatches = append(minMaxBatchNumBatches, tc.batches[i])
  209. }
  210. }
  211. assertBatches(t, minMaxBatchNumBatches, fetchedBatches)
  212. // Empty array
  213. fetchedBatches = []testBatch{}
  214. path = fmt.Sprintf("%s?slotNum=%d&minBatchNum=%d", endpoint, 1, 25)
  215. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  216. require.NoError(t, err)
  217. assertBatches(t, []testBatch{}, fetchedBatches)
  218. // 400
  219. // Invalid minBatchNum
  220. path = fmt.Sprintf("%s?minBatchNum=%d", endpoint, -2)
  221. err = doBadReq("GET", path, nil, 400)
  222. require.NoError(t, err)
  223. // Invalid forgerAddr
  224. path = fmt.Sprintf("%s?forgerAddr=%s", endpoint, "0xG0000001")
  225. err = doBadReq("GET", path, nil, 400)
  226. require.NoError(t, err)
  227. }
  228. func TestGetBatch(t *testing.T) {
  229. endpoint := apiURL + "batches/"
  230. for _, batch := range tc.batches {
  231. fetchedBatch := testBatch{}
  232. require.NoError(
  233. t, doGoodReq(
  234. "GET",
  235. endpoint+strconv.Itoa(int(batch.BatchNum)),
  236. nil, &fetchedBatch,
  237. ),
  238. )
  239. assertBatch(t, batch, fetchedBatch)
  240. }
  241. // 400
  242. require.NoError(t, doBadReq("GET", endpoint+"foo", nil, 400))
  243. // 404
  244. require.NoError(t, doBadReq("GET", endpoint+"99999", nil, 404))
  245. }
  246. func TestGetFullBatch(t *testing.T) {
  247. endpoint := apiURL + "full-batches/"
  248. for _, fullBatch := range tc.fullBatches {
  249. fetchedFullBatch := testFullBatch{}
  250. require.NoError(
  251. t, doGoodReq(
  252. "GET",
  253. endpoint+strconv.Itoa(int(fullBatch.Batch.BatchNum)),
  254. nil, &fetchedFullBatch,
  255. ),
  256. )
  257. assertBatch(t, fullBatch.Batch, fetchedFullBatch.Batch)
  258. assertTxs(t, fullBatch.Txs, fetchedFullBatch.Txs)
  259. }
  260. // 400
  261. require.NoError(t, doBadReq("GET", endpoint+"foo", nil, 400))
  262. // 404
  263. require.NoError(t, doBadReq("GET", endpoint+"99999", nil, 404))
  264. }
  265. func assertBatches(t *testing.T, expected, actual []testBatch) {
  266. assert.Equal(t, len(expected), len(actual))
  267. for i := 0; i < len(expected); i++ {
  268. assertBatch(t, expected[i], actual[i])
  269. }
  270. }
  271. func assertBatch(t *testing.T, expected, actual testBatch) {
  272. assert.Equal(t, expected.Timestamp.Unix(), actual.Timestamp.Unix())
  273. expected.Timestamp = actual.Timestamp
  274. actual.ItemID = expected.ItemID
  275. assert.Equal(t, expected, actual)
  276. }