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.

234 lines
9.6 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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.
4 years ago
3 years ago
3 years ago
  1. package api
  2. import (
  3. "math/big"
  4. "testing"
  5. "github.com/hermeznetwork/hermez-node/apitypes"
  6. "github.com/hermeznetwork/hermez-node/common"
  7. "github.com/hermeznetwork/hermez-node/db/historydb"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/stretchr/testify/require"
  10. )
  11. type testStatus struct {
  12. Network testNetwork `json:"network"`
  13. Metrics historydb.MetricsAPI `json:"metrics"`
  14. Rollup historydb.RollupVariablesAPI `json:"rollup"`
  15. Auction historydb.AuctionVariablesAPI `json:"auction"`
  16. WithdrawalDelayer common.WDelayerVariables `json:"withdrawalDelayer"`
  17. RecommendedFee common.RecommendedFee `json:"recommendedFee"`
  18. }
  19. type testNetwork struct {
  20. LastEthBlock int64 `json:"lastEthereumBlock"`
  21. LastSyncBlock int64 `json:"lastSynchedBlock"`
  22. LastBatch testBatch `json:"lastBatch"`
  23. CurrentSlot int64 `json:"currentSlot"`
  24. NextForgers []historydb.NextForgerAPI `json:"nextForgers"`
  25. }
  26. func TestSetRollupVariables(t *testing.T) {
  27. stateAPIUpdater.SetSCVars(&common.SCVariablesPtr{Rollup: &tc.rollupVars})
  28. require.NoError(t, stateAPIUpdater.Store())
  29. ni, err := api.h.GetNodeInfoAPI()
  30. require.NoError(t, err)
  31. assertEqualRollupVariables(t, tc.rollupVars, ni.StateAPI.Rollup, true)
  32. }
  33. func assertEqualRollupVariables(t *testing.T, rollupVariables common.RollupVariables, apiVariables historydb.RollupVariablesAPI, checkBuckets bool) {
  34. assert.Equal(t, apitypes.NewBigIntStr(rollupVariables.FeeAddToken), apiVariables.FeeAddToken)
  35. assert.Equal(t, rollupVariables.ForgeL1L2BatchTimeout, apiVariables.ForgeL1L2BatchTimeout)
  36. assert.Equal(t, rollupVariables.WithdrawalDelay, apiVariables.WithdrawalDelay)
  37. assert.Equal(t, rollupVariables.SafeMode, apiVariables.SafeMode)
  38. if checkBuckets {
  39. for i, bucket := range rollupVariables.Buckets {
  40. assert.Equal(t, apitypes.NewBigIntStr(bucket.BlockWithdrawalRate), apiVariables.Buckets[i].BlockWithdrawalRate)
  41. assert.Equal(t, apitypes.NewBigIntStr(bucket.CeilUSD), apiVariables.Buckets[i].CeilUSD)
  42. assert.Equal(t, apitypes.NewBigIntStr(bucket.MaxWithdrawals), apiVariables.Buckets[i].MaxWithdrawals)
  43. assert.Equal(t, apitypes.NewBigIntStr(bucket.Withdrawals), apiVariables.Buckets[i].Withdrawals)
  44. }
  45. }
  46. }
  47. func TestSetWDelayerVariables(t *testing.T) {
  48. stateAPIUpdater.SetSCVars(&common.SCVariablesPtr{WDelayer: &tc.wdelayerVars})
  49. require.NoError(t, stateAPIUpdater.Store())
  50. ni, err := api.h.GetNodeInfoAPI()
  51. require.NoError(t, err)
  52. assert.Equal(t, tc.wdelayerVars, ni.StateAPI.WithdrawalDelayer)
  53. }
  54. func TestSetAuctionVariables(t *testing.T) {
  55. stateAPIUpdater.SetSCVars(&common.SCVariablesPtr{Auction: &tc.auctionVars})
  56. require.NoError(t, stateAPIUpdater.Store())
  57. ni, err := api.h.GetNodeInfoAPI()
  58. require.NoError(t, err)
  59. assertEqualAuctionVariables(t, tc.auctionVars, ni.StateAPI.Auction)
  60. }
  61. func assertEqualAuctionVariables(t *testing.T, auctionVariables common.AuctionVariables, apiVariables historydb.AuctionVariablesAPI) {
  62. assert.Equal(t, auctionVariables.EthBlockNum, apiVariables.EthBlockNum)
  63. assert.Equal(t, auctionVariables.DonationAddress, apiVariables.DonationAddress)
  64. assert.Equal(t, auctionVariables.BootCoordinator, apiVariables.BootCoordinator)
  65. assert.Equal(t, auctionVariables.BootCoordinatorURL, apiVariables.BootCoordinatorURL)
  66. assert.Equal(t, auctionVariables.DefaultSlotSetBidSlotNum, apiVariables.DefaultSlotSetBidSlotNum)
  67. assert.Equal(t, auctionVariables.ClosedAuctionSlots, apiVariables.ClosedAuctionSlots)
  68. assert.Equal(t, auctionVariables.OpenAuctionSlots, apiVariables.OpenAuctionSlots)
  69. assert.Equal(t, auctionVariables.Outbidding, apiVariables.Outbidding)
  70. assert.Equal(t, auctionVariables.SlotDeadline, apiVariables.SlotDeadline)
  71. for i, slot := range auctionVariables.DefaultSlotSetBid {
  72. assert.Equal(t, apitypes.NewBigIntStr(slot), apiVariables.DefaultSlotSetBid[i])
  73. }
  74. for i, ratio := range auctionVariables.AllocationRatio {
  75. assert.Equal(t, ratio, apiVariables.AllocationRatio[i])
  76. }
  77. }
  78. func TestUpdateNetworkInfo(t *testing.T) {
  79. lastBlock := tc.blocks[3]
  80. lastBatchNum := common.BatchNum(3)
  81. currentSlotNum := int64(1)
  82. // Generate some bucket_update data
  83. bucketUpdates := []common.BucketUpdate{
  84. {
  85. EthBlockNum: 4,
  86. NumBucket: 0,
  87. BlockStamp: 4,
  88. Withdrawals: big.NewInt(123),
  89. },
  90. {
  91. EthBlockNum: 5,
  92. NumBucket: 2,
  93. BlockStamp: 5,
  94. Withdrawals: big.NewInt(42),
  95. },
  96. {
  97. EthBlockNum: 5,
  98. NumBucket: 2, // Repeated bucket
  99. BlockStamp: 5,
  100. Withdrawals: big.NewInt(43),
  101. },
  102. }
  103. err := api.h.AddBucketUpdatesTest(api.h.DB(), bucketUpdates)
  104. require.NoError(t, err)
  105. // stateAPIUpdater := NewStateAPIUpdater(hdb)
  106. err = stateAPIUpdater.UpdateNetworkInfo(lastBlock, lastBlock, lastBatchNum, currentSlotNum)
  107. require.NoError(t, err)
  108. require.NoError(t, stateAPIUpdater.Store())
  109. ni, err := api.h.GetNodeInfoAPI()
  110. require.NoError(t, err)
  111. assert.Equal(t, lastBlock.Num, ni.StateAPI.Network.LastSyncBlock)
  112. assert.Equal(t, lastBatchNum, ni.StateAPI.Network.LastBatch.BatchNum)
  113. assert.Equal(t, currentSlotNum, ni.StateAPI.Network.CurrentSlot)
  114. assert.Equal(t, int(ni.StateAPI.Auction.ClosedAuctionSlots)+1, len(ni.StateAPI.Network.NextForgers))
  115. assert.Equal(t, ni.StateAPI.Rollup.Buckets[0].Withdrawals, apitypes.NewBigIntStr(big.NewInt(123)))
  116. assert.Equal(t, ni.StateAPI.Rollup.Buckets[2].Withdrawals, apitypes.NewBigIntStr(big.NewInt(43)))
  117. }
  118. func TestUpdateMetrics(t *testing.T) {
  119. // Update Metrics needs api.status.Network.LastBatch.BatchNum to be updated
  120. lastBlock := tc.blocks[3]
  121. lastBatchNum := common.BatchNum(12)
  122. currentSlotNum := int64(1)
  123. err := stateAPIUpdater.UpdateNetworkInfo(lastBlock, lastBlock, lastBatchNum, currentSlotNum)
  124. require.NoError(t, err)
  125. err = stateAPIUpdater.UpdateMetrics()
  126. require.NoError(t, err)
  127. require.NoError(t, stateAPIUpdater.Store())
  128. ni, err := api.h.GetNodeInfoAPI()
  129. require.NoError(t, err)
  130. assert.Greater(t, ni.StateAPI.Metrics.TransactionsPerBatch, float64(0))
  131. assert.Greater(t, ni.StateAPI.Metrics.BatchFrequency, float64(0))
  132. assert.Greater(t, ni.StateAPI.Metrics.TransactionsPerSecond, float64(0))
  133. assert.Greater(t, ni.StateAPI.Metrics.TotalAccounts, int64(0))
  134. assert.Greater(t, ni.StateAPI.Metrics.TotalBJJs, int64(0))
  135. assert.Greater(t, ni.StateAPI.Metrics.AvgTransactionFee, float64(0))
  136. }
  137. func TestUpdateRecommendedFee(t *testing.T) {
  138. err := stateAPIUpdater.UpdateRecommendedFee()
  139. require.NoError(t, err)
  140. require.NoError(t, stateAPIUpdater.Store())
  141. var minFeeUSD float64
  142. if api.l2 != nil {
  143. minFeeUSD = api.l2.MinFeeUSD()
  144. }
  145. ni, err := api.h.GetNodeInfoAPI()
  146. require.NoError(t, err)
  147. assert.Greater(t, ni.StateAPI.RecommendedFee.ExistingAccount, minFeeUSD)
  148. // assert.Equal(t, ni.StateAPI.RecommendedFee.CreatesAccount,
  149. // ni.StateAPI.RecommendedFee.ExistingAccount*createAccountExtraFeePercentage)
  150. // assert.Equal(t, ni.StateAPI.RecommendedFee.CreatesAccountAndRegister,
  151. // ni.StateAPI.RecommendedFee.ExistingAccount*createAccountInternalExtraFeePercentage)
  152. }
  153. func TestGetState(t *testing.T) {
  154. lastBlock := tc.blocks[3]
  155. lastBatchNum := common.BatchNum(12)
  156. currentSlotNum := int64(1)
  157. stateAPIUpdater.SetSCVars(&common.SCVariablesPtr{
  158. Rollup: &tc.rollupVars,
  159. Auction: &tc.auctionVars,
  160. WDelayer: &tc.wdelayerVars,
  161. })
  162. err := stateAPIUpdater.UpdateNetworkInfo(lastBlock, lastBlock, lastBatchNum, currentSlotNum)
  163. require.NoError(t, err)
  164. err = stateAPIUpdater.UpdateMetrics()
  165. require.NoError(t, err)
  166. err = stateAPIUpdater.UpdateRecommendedFee()
  167. require.NoError(t, err)
  168. require.NoError(t, stateAPIUpdater.Store())
  169. endpoint := apiURL + "state"
  170. var status testStatus
  171. require.NoError(t, doGoodReq("GET", endpoint, nil, &status))
  172. // SC vars
  173. // UpdateNetworkInfo will overwrite buckets withdrawal values
  174. // So they won't be checked here, they are checked at
  175. // TestUpdateNetworkInfo
  176. assertEqualRollupVariables(t, tc.rollupVars, status.Rollup, false)
  177. assertEqualAuctionVariables(t, tc.auctionVars, status.Auction)
  178. assert.Equal(t, tc.wdelayerVars, status.WithdrawalDelayer)
  179. // Network
  180. assert.Equal(t, lastBlock.Num, status.Network.LastEthBlock)
  181. assert.Equal(t, lastBlock.Num, status.Network.LastSyncBlock)
  182. // TODO: assert all the batch, not just the batch num
  183. assert.Equal(t, lastBatchNum, status.Network.LastBatch.BatchNum)
  184. assert.Equal(t, currentSlotNum, status.Network.CurrentSlot)
  185. assertNextForgers(t, tc.nextForgers, status.Network.NextForgers)
  186. // Metrics
  187. // TODO: perform real asserts (not just greater than 0)
  188. assert.Greater(t, status.Metrics.TransactionsPerBatch, float64(0))
  189. assert.Greater(t, status.Metrics.BatchFrequency, float64(0))
  190. assert.Greater(t, status.Metrics.TransactionsPerSecond, float64(0))
  191. assert.Greater(t, status.Metrics.TotalAccounts, int64(0))
  192. assert.Greater(t, status.Metrics.TotalBJJs, int64(0))
  193. assert.Greater(t, status.Metrics.AvgTransactionFee, float64(0))
  194. // Recommended fee
  195. // TODO: perform real asserts (not just greater than 0)
  196. assert.Greater(t, status.RecommendedFee.ExistingAccount, float64(0))
  197. // assert.Equal(t, status.RecommendedFee.CreatesAccount,
  198. // status.RecommendedFee.ExistingAccount*createAccountExtraFeePercentage)
  199. // assert.Equal(t, status.RecommendedFee.CreatesAccountAndRegister,
  200. // status.RecommendedFee.ExistingAccount*createAccountInternalExtraFeePercentage)
  201. }
  202. func assertNextForgers(t *testing.T, expected, actual []historydb.NextForgerAPI) {
  203. assert.Equal(t, len(expected), len(actual))
  204. for i := range expected {
  205. // ignore timestamps and other metadata
  206. actual[i].Period.FromTimestamp = expected[i].Period.FromTimestamp
  207. actual[i].Period.ToTimestamp = expected[i].Period.ToTimestamp
  208. actual[i].Coordinator.ItemID = expected[i].Coordinator.ItemID
  209. actual[i].Coordinator.EthBlockNum = expected[i].Coordinator.EthBlockNum
  210. assert.Equal(t, expected[i], actual[i])
  211. }
  212. }