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.

295 lines
9.2 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/common"
  9. "github.com/hermeznetwork/hermez-node/db/historydb"
  10. "github.com/mitchellh/copystructure"
  11. "github.com/stretchr/testify/assert"
  12. )
  13. type testBatch struct {
  14. ItemID uint64 `json:"itemId"`
  15. BatchNum common.BatchNum `json:"batchNum"`
  16. EthBlockNum int64 `json:"ethereumBlockNum"`
  17. EthBlockHash ethCommon.Hash `json:"ethereumBlockHash"`
  18. Timestamp time.Time `json:"timestamp"`
  19. ForgerAddr ethCommon.Address `json:"forgerAddr"`
  20. CollectedFees map[common.TokenID]string `json:"collectedFees"`
  21. TotalFeesUSD *float64 `json:"historicTotalCollectedFeesUSD"`
  22. StateRoot string `json:"stateRoot"`
  23. NumAccounts int `json:"numAccounts"`
  24. ExitRoot string `json:"exitRoot"`
  25. ForgeL1TxsNum *int64 `json:"forgeL1TransactionsNum"`
  26. SlotNum int64 `json:"slotNum"`
  27. ForgedTxs int `json:"forgedTransactions"`
  28. }
  29. type testBatchesResponse struct {
  30. Batches []testBatch `json:"batches"`
  31. PendingItems uint64 `json:"pendingItems"`
  32. }
  33. func (t testBatchesResponse) GetPending() (pendingItems, lastItemID uint64) {
  34. if len(t.Batches) == 0 {
  35. return 0, 0
  36. }
  37. pendingItems = t.PendingItems
  38. lastItemID = t.Batches[len(t.Batches)-1].ItemID
  39. return pendingItems, lastItemID
  40. }
  41. func (t testBatchesResponse) Len() int {
  42. return len(t.Batches)
  43. }
  44. func (t testBatchesResponse) New() Pendinger { return &testBatchesResponse{} }
  45. type testFullBatch struct {
  46. Batch testBatch `json:"batch"`
  47. Txs []testTx `json:"transactions"`
  48. }
  49. func genTestBatches(
  50. blocks []common.Block,
  51. cBatches []common.Batch,
  52. txs []testTx,
  53. ) ([]testBatch, []testFullBatch) {
  54. tBatches := []testBatch{}
  55. for i := 0; i < len(cBatches); i++ {
  56. block := common.Block{}
  57. found := false
  58. for _, b := range blocks {
  59. if b.Num == cBatches[i].EthBlockNum {
  60. block = b
  61. found = true
  62. break
  63. }
  64. }
  65. if !found {
  66. panic("block not found")
  67. }
  68. collectedFees := make(map[common.TokenID]string)
  69. for k, v := range cBatches[i].CollectedFees {
  70. collectedFees[k] = v.String()
  71. }
  72. forgedTxs := 0
  73. for _, tx := range txs {
  74. if tx.BatchNum != nil && *tx.BatchNum == cBatches[i].BatchNum {
  75. forgedTxs++
  76. }
  77. }
  78. tBatch := testBatch{
  79. BatchNum: cBatches[i].BatchNum,
  80. EthBlockNum: cBatches[i].EthBlockNum,
  81. EthBlockHash: block.Hash,
  82. Timestamp: block.Timestamp,
  83. ForgerAddr: cBatches[i].ForgerAddr,
  84. CollectedFees: collectedFees,
  85. TotalFeesUSD: cBatches[i].TotalFeesUSD,
  86. StateRoot: cBatches[i].StateRoot.String(),
  87. NumAccounts: cBatches[i].NumAccounts,
  88. ExitRoot: cBatches[i].ExitRoot.String(),
  89. ForgeL1TxsNum: cBatches[i].ForgeL1TxsNum,
  90. SlotNum: cBatches[i].SlotNum,
  91. ForgedTxs: forgedTxs,
  92. }
  93. tBatches = append(tBatches, tBatch)
  94. }
  95. fullBatches := []testFullBatch{}
  96. for i := 0; i < len(tBatches); i++ {
  97. forgedTxs := []testTx{}
  98. for j := 0; j < len(txs); j++ {
  99. if txs[j].BatchNum != nil && *txs[j].BatchNum == tBatches[i].BatchNum {
  100. forgedTxs = append(forgedTxs, txs[j])
  101. }
  102. }
  103. fullBatches = append(fullBatches, testFullBatch{
  104. Batch: tBatches[i],
  105. Txs: forgedTxs,
  106. })
  107. }
  108. return tBatches, fullBatches
  109. }
  110. func TestGetBatches(t *testing.T) {
  111. endpoint := apiURL + "batches"
  112. fetchedBatches := []testBatch{}
  113. appendIter := func(intr interface{}) {
  114. for i := 0; i < len(intr.(*testBatchesResponse).Batches); i++ {
  115. tmp, err := copystructure.Copy(intr.(*testBatchesResponse).Batches[i])
  116. if err != nil {
  117. panic(err)
  118. }
  119. fetchedBatches = append(fetchedBatches, tmp.(testBatch))
  120. }
  121. }
  122. // Get all (no filters)
  123. limit := 3
  124. path := fmt.Sprintf("%s?limit=%d", endpoint, limit)
  125. err := doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  126. assert.NoError(t, err)
  127. assertBatches(t, tc.batches, fetchedBatches)
  128. // minBatchNum
  129. fetchedBatches = []testBatch{}
  130. limit = 2
  131. minBatchNum := tc.batches[len(tc.batches)/2].BatchNum
  132. path = fmt.Sprintf("%s?minBatchNum=%d&limit=%d", endpoint, minBatchNum, limit)
  133. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  134. assert.NoError(t, err)
  135. minBatchNumBatches := []testBatch{}
  136. for i := 0; i < len(tc.batches); i++ {
  137. if tc.batches[i].BatchNum > minBatchNum {
  138. minBatchNumBatches = append(minBatchNumBatches, tc.batches[i])
  139. }
  140. }
  141. assertBatches(t, minBatchNumBatches, fetchedBatches)
  142. // maxBatchNum
  143. fetchedBatches = []testBatch{}
  144. limit = 1
  145. maxBatchNum := tc.batches[len(tc.batches)/2].BatchNum
  146. path = fmt.Sprintf("%s?maxBatchNum=%d&limit=%d", endpoint, maxBatchNum, limit)
  147. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  148. assert.NoError(t, err)
  149. maxBatchNumBatches := []testBatch{}
  150. for i := 0; i < len(tc.batches); i++ {
  151. if tc.batches[i].BatchNum < maxBatchNum {
  152. maxBatchNumBatches = append(maxBatchNumBatches, tc.batches[i])
  153. }
  154. }
  155. assertBatches(t, maxBatchNumBatches, fetchedBatches)
  156. // slotNum
  157. fetchedBatches = []testBatch{}
  158. limit = 5
  159. slotNum := tc.batches[len(tc.batches)/2].SlotNum
  160. path = fmt.Sprintf("%s?slotNum=%d&limit=%d", endpoint, slotNum, limit)
  161. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  162. assert.NoError(t, err)
  163. slotNumBatches := []testBatch{}
  164. for i := 0; i < len(tc.batches); i++ {
  165. if tc.batches[i].SlotNum == slotNum {
  166. slotNumBatches = append(slotNumBatches, tc.batches[i])
  167. }
  168. }
  169. assertBatches(t, slotNumBatches, fetchedBatches)
  170. // forgerAddr
  171. fetchedBatches = []testBatch{}
  172. limit = 10
  173. forgerAddr := tc.batches[len(tc.batches)/2].ForgerAddr
  174. path = fmt.Sprintf("%s?forgerAddr=%s&limit=%d", endpoint, forgerAddr.String(), limit)
  175. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  176. assert.NoError(t, err)
  177. forgerAddrBatches := []testBatch{}
  178. for i := 0; i < len(tc.batches); i++ {
  179. if tc.batches[i].ForgerAddr == forgerAddr {
  180. forgerAddrBatches = append(forgerAddrBatches, tc.batches[i])
  181. }
  182. }
  183. assertBatches(t, forgerAddrBatches, fetchedBatches)
  184. // All, in reverse order
  185. fetchedBatches = []testBatch{}
  186. limit = 6
  187. path = fmt.Sprintf("%s?limit=%d", endpoint, limit)
  188. err = doGoodReqPaginated(path, historydb.OrderDesc, &testBatchesResponse{}, appendIter)
  189. assert.NoError(t, err)
  190. flippedBatches := []testBatch{}
  191. for i := len(tc.batches) - 1; i >= 0; i-- {
  192. flippedBatches = append(flippedBatches, tc.batches[i])
  193. }
  194. assertBatches(t, flippedBatches, fetchedBatches)
  195. // Mixed filters
  196. fetchedBatches = []testBatch{}
  197. limit = 1
  198. maxBatchNum = tc.batches[len(tc.batches)-len(tc.batches)/4].BatchNum
  199. minBatchNum = tc.batches[len(tc.batches)/4].BatchNum
  200. path = fmt.Sprintf("%s?minBatchNum=%d&maxBatchNum=%d&limit=%d", endpoint, minBatchNum, maxBatchNum, limit)
  201. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  202. assert.NoError(t, err)
  203. minMaxBatchNumBatches := []testBatch{}
  204. for i := 0; i < len(tc.batches); i++ {
  205. if tc.batches[i].BatchNum < maxBatchNum && tc.batches[i].BatchNum > minBatchNum {
  206. minMaxBatchNumBatches = append(minMaxBatchNumBatches, tc.batches[i])
  207. }
  208. }
  209. assertBatches(t, minMaxBatchNumBatches, fetchedBatches)
  210. // Empty array
  211. fetchedBatches = []testBatch{}
  212. path = fmt.Sprintf("%s?slotNum=%d&minBatchNum=%d", endpoint, 1, 25)
  213. err = doGoodReqPaginated(path, historydb.OrderAsc, &testBatchesResponse{}, appendIter)
  214. assert.NoError(t, err)
  215. assertBatches(t, []testBatch{}, fetchedBatches)
  216. // 400
  217. // Invalid minBatchNum
  218. path = fmt.Sprintf("%s?minBatchNum=%d", endpoint, -2)
  219. err = doBadReq("GET", path, nil, 400)
  220. assert.NoError(t, err)
  221. // Invalid forgerAddr
  222. path = fmt.Sprintf("%s?forgerAddr=%s", endpoint, "0xG0000001")
  223. err = doBadReq("GET", path, nil, 400)
  224. assert.NoError(t, err)
  225. }
  226. func TestGetBatch(t *testing.T) {
  227. endpoint := apiURL + "batches/"
  228. for _, batch := range tc.batches {
  229. fetchedBatch := testBatch{}
  230. assert.NoError(
  231. t, doGoodReq(
  232. "GET",
  233. endpoint+strconv.Itoa(int(batch.BatchNum)),
  234. nil, &fetchedBatch,
  235. ),
  236. )
  237. assertBatch(t, batch, fetchedBatch)
  238. }
  239. // 400
  240. assert.NoError(t, doBadReq("GET", endpoint+"foo", nil, 400))
  241. // 404
  242. assert.NoError(t, doBadReq("GET", endpoint+"99999", nil, 404))
  243. }
  244. func TestGetFullBatch(t *testing.T) {
  245. endpoint := apiURL + "full-batches/"
  246. for _, fullBatch := range tc.fullBatches {
  247. fetchedFullBatch := testFullBatch{}
  248. assert.NoError(
  249. t, doGoodReq(
  250. "GET",
  251. endpoint+strconv.Itoa(int(fullBatch.Batch.BatchNum)),
  252. nil, &fetchedFullBatch,
  253. ),
  254. )
  255. assertBatch(t, fullBatch.Batch, fetchedFullBatch.Batch)
  256. assertTxs(t, fullBatch.Txs, fetchedFullBatch.Txs)
  257. }
  258. // 400
  259. assert.NoError(t, doBadReq("GET", endpoint+"foo", nil, 400))
  260. // 404
  261. assert.NoError(t, doBadReq("GET", endpoint+"99999", nil, 404))
  262. }
  263. func assertBatches(t *testing.T, expected, actual []testBatch) {
  264. assert.Equal(t, len(expected), len(actual))
  265. for i := 0; i < len(expected); i++ {
  266. assertBatch(t, expected[i], actual[i])
  267. }
  268. }
  269. func assertBatch(t *testing.T, expected, actual testBatch) {
  270. assert.Equal(t, expected.Timestamp.Unix(), actual.Timestamp.Unix())
  271. expected.Timestamp = actual.Timestamp
  272. actual.ItemID = expected.ItemID
  273. assert.Equal(t, expected, actual)
  274. }