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.

306 lines
9.9 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
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. "database/sql"
  4. "fmt"
  5. "math/big"
  6. "net/http"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. "github.com/hermeznetwork/hermez-node/apitypes"
  10. "github.com/hermeznetwork/hermez-node/common"
  11. "github.com/hermeznetwork/hermez-node/db/historydb"
  12. "github.com/hermeznetwork/tracerr"
  13. )
  14. // Network define status of the network
  15. type Network struct {
  16. LastEthBlock int64 `json:"lastEthereumBlock"`
  17. LastSyncBlock int64 `json:"lastSynchedBlock"`
  18. LastBatch *historydb.BatchAPI `json:"lastBatch"`
  19. CurrentSlot int64 `json:"currentSlot"`
  20. NextForgers []NextForger `json:"nextForgers"`
  21. }
  22. // NextForger is a representation of the information of a coordinator and the period will forge
  23. type NextForger struct {
  24. Coordinator historydb.CoordinatorAPI `json:"coordinator"`
  25. Period Period `json:"period"`
  26. }
  27. // Period is a representation of a period
  28. type Period struct {
  29. SlotNum int64 `json:"slotNum"`
  30. FromBlock int64 `json:"fromBlock"`
  31. ToBlock int64 `json:"toBlock"`
  32. FromTimestamp time.Time `json:"fromTimestamp"`
  33. ToTimestamp time.Time `json:"toTimestamp"`
  34. }
  35. func (a *API) getState(c *gin.Context) {
  36. // TODO: There are no events for the buckets information, so now this information will be 0
  37. a.status.RLock()
  38. status := a.status //nolint
  39. a.status.RUnlock()
  40. c.JSON(http.StatusOK, status) //nolint
  41. }
  42. // SC Vars
  43. // SetRollupVariables set Status.Rollup variables
  44. func (a *API) SetRollupVariables(rollupVariables common.RollupVariables) {
  45. a.status.Lock()
  46. var rollupVAPI historydb.RollupVariablesAPI
  47. rollupVAPI.EthBlockNum = rollupVariables.EthBlockNum
  48. rollupVAPI.FeeAddToken = apitypes.NewBigIntStr(rollupVariables.FeeAddToken)
  49. rollupVAPI.ForgeL1L2BatchTimeout = rollupVariables.ForgeL1L2BatchTimeout
  50. rollupVAPI.WithdrawalDelay = rollupVariables.WithdrawalDelay
  51. for i, bucket := range rollupVariables.Buckets {
  52. var apiBucket historydb.BucketParamsAPI
  53. apiBucket.CeilUSD = apitypes.NewBigIntStr(bucket.CeilUSD)
  54. apiBucket.Withdrawals = apitypes.NewBigIntStr(bucket.Withdrawals)
  55. apiBucket.BlockWithdrawalRate = apitypes.NewBigIntStr(bucket.BlockWithdrawalRate)
  56. apiBucket.MaxWithdrawals = apitypes.NewBigIntStr(bucket.MaxWithdrawals)
  57. rollupVAPI.Buckets[i] = apiBucket
  58. }
  59. rollupVAPI.SafeMode = rollupVariables.SafeMode
  60. a.status.Rollup = rollupVAPI
  61. a.status.Unlock()
  62. }
  63. // SetWDelayerVariables set Status.WithdrawalDelayer variables
  64. func (a *API) SetWDelayerVariables(wDelayerVariables common.WDelayerVariables) {
  65. a.status.Lock()
  66. a.status.WithdrawalDelayer = wDelayerVariables
  67. a.status.Unlock()
  68. }
  69. // SetAuctionVariables set Status.Auction variables
  70. func (a *API) SetAuctionVariables(auctionVariables common.AuctionVariables) {
  71. a.status.Lock()
  72. var auctionAPI historydb.AuctionVariablesAPI
  73. auctionAPI.EthBlockNum = auctionVariables.EthBlockNum
  74. auctionAPI.DonationAddress = auctionVariables.DonationAddress
  75. auctionAPI.BootCoordinator = auctionVariables.BootCoordinator
  76. auctionAPI.BootCoordinatorURL = auctionVariables.BootCoordinatorURL
  77. auctionAPI.DefaultSlotSetBidSlotNum = auctionVariables.DefaultSlotSetBidSlotNum
  78. auctionAPI.ClosedAuctionSlots = auctionVariables.ClosedAuctionSlots
  79. auctionAPI.OpenAuctionSlots = auctionVariables.OpenAuctionSlots
  80. auctionAPI.Outbidding = auctionVariables.Outbidding
  81. auctionAPI.SlotDeadline = auctionVariables.SlotDeadline
  82. for i, slot := range auctionVariables.DefaultSlotSetBid {
  83. auctionAPI.DefaultSlotSetBid[i] = apitypes.NewBigIntStr(slot)
  84. }
  85. for i, ratio := range auctionVariables.AllocationRatio {
  86. auctionAPI.AllocationRatio[i] = ratio
  87. }
  88. a.status.Auction = auctionAPI
  89. a.status.Unlock()
  90. }
  91. // Network
  92. // UpdateNetworkInfoBlock update Status.Network block related information
  93. func (a *API) UpdateNetworkInfoBlock(
  94. lastEthBlock, lastSyncBlock common.Block,
  95. ) {
  96. a.status.Network.LastSyncBlock = lastSyncBlock.Num
  97. a.status.Network.LastEthBlock = lastEthBlock.Num
  98. }
  99. // UpdateNetworkInfo update Status.Network information
  100. func (a *API) UpdateNetworkInfo(
  101. lastEthBlock, lastSyncBlock common.Block,
  102. lastBatchNum common.BatchNum, currentSlot int64,
  103. ) error {
  104. lastBatch, err := a.h.GetBatchAPI(lastBatchNum)
  105. if tracerr.Unwrap(err) == sql.ErrNoRows {
  106. lastBatch = nil
  107. } else if err != nil {
  108. return tracerr.Wrap(err)
  109. }
  110. lastClosedSlot := currentSlot + int64(a.status.Auction.ClosedAuctionSlots)
  111. nextForgers, err := a.getNextForgers(lastSyncBlock, currentSlot, lastClosedSlot)
  112. if tracerr.Unwrap(err) == sql.ErrNoRows {
  113. nextForgers = nil
  114. } else if err != nil {
  115. return tracerr.Wrap(err)
  116. }
  117. a.status.Lock()
  118. a.status.Network.LastSyncBlock = lastSyncBlock.Num
  119. a.status.Network.LastEthBlock = lastEthBlock.Num
  120. a.status.Network.LastBatch = lastBatch
  121. a.status.Network.CurrentSlot = currentSlot
  122. a.status.Network.NextForgers = nextForgers
  123. // Update buckets withdrawals
  124. bucketsUpdate, err := a.h.GetBucketUpdates()
  125. if tracerr.Unwrap(err) == sql.ErrNoRows {
  126. bucketsUpdate = nil
  127. } else if err != nil {
  128. return tracerr.Wrap(err)
  129. }
  130. for i, bucketParams := range a.status.Rollup.Buckets {
  131. for _, bucketUpdate := range bucketsUpdate {
  132. if bucketUpdate.NumBucket == i {
  133. bucketParams.Withdrawals = bucketUpdate.Withdrawals
  134. a.status.Rollup.Buckets[i] = bucketParams
  135. break
  136. }
  137. }
  138. }
  139. a.status.Unlock()
  140. return nil
  141. }
  142. // apiSlotToBigInts converts from [6]*apitypes.BigIntStr to [6]*big.Int
  143. func apiSlotToBigInts(defaultSlotSetBid [6]*apitypes.BigIntStr) ([6]*big.Int, error) {
  144. var slots [6]*big.Int
  145. for i, slot := range defaultSlotSetBid {
  146. bigInt, ok := new(big.Int).SetString(string(*slot), 10)
  147. if !ok {
  148. return slots, tracerr.Wrap(fmt.Errorf("can't convert %T into big.Int", slot))
  149. }
  150. slots[i] = bigInt
  151. }
  152. return slots, nil
  153. }
  154. // getNextForgers returns next forgers
  155. func (a *API) getNextForgers(lastBlock common.Block, currentSlot, lastClosedSlot int64) ([]NextForger, error) {
  156. secondsPerBlock := int64(15) //nolint:gomnd
  157. // currentSlot and lastClosedSlot included
  158. limit := uint(lastClosedSlot - currentSlot + 1)
  159. bids, _, err := a.h.GetBestBidsAPI(&currentSlot, &lastClosedSlot, nil, &limit, "ASC")
  160. if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows {
  161. return nil, tracerr.Wrap(err)
  162. }
  163. nextForgers := []NextForger{}
  164. // Get min bid info
  165. var minBidInfo []historydb.MinBidInfo
  166. if currentSlot >= a.status.Auction.DefaultSlotSetBidSlotNum {
  167. // All min bids can be calculated with the last update of AuctionVariables
  168. bigIntSlots, err := apiSlotToBigInts(a.status.Auction.DefaultSlotSetBid)
  169. if err != nil {
  170. return nil, tracerr.Wrap(err)
  171. }
  172. minBidInfo = []historydb.MinBidInfo{{
  173. DefaultSlotSetBid: bigIntSlots,
  174. DefaultSlotSetBidSlotNum: a.status.Auction.DefaultSlotSetBidSlotNum,
  175. }}
  176. } else {
  177. // Get all the relevant updates from the DB
  178. minBidInfo, err = a.h.GetAuctionVarsUntilSetSlotNum(lastClosedSlot, int(lastClosedSlot-currentSlot)+1)
  179. if err != nil {
  180. return nil, tracerr.Wrap(err)
  181. }
  182. }
  183. // Create nextForger for each slot
  184. for i := currentSlot; i <= lastClosedSlot; i++ {
  185. fromBlock := i*int64(a.cg.AuctionConstants.BlocksPerSlot) + a.cg.AuctionConstants.GenesisBlockNum
  186. toBlock := (i+1)*int64(a.cg.AuctionConstants.BlocksPerSlot) + a.cg.AuctionConstants.GenesisBlockNum - 1
  187. nextForger := NextForger{
  188. Period: Period{
  189. SlotNum: i,
  190. FromBlock: fromBlock,
  191. ToBlock: toBlock,
  192. FromTimestamp: lastBlock.Timestamp.Add(time.Second * time.Duration(secondsPerBlock*(fromBlock-lastBlock.Num))),
  193. ToTimestamp: lastBlock.Timestamp.Add(time.Second * time.Duration(secondsPerBlock*(toBlock-lastBlock.Num))),
  194. },
  195. }
  196. foundForger := false
  197. // If there is a bid for a slot, get forger (coordinator)
  198. for j := range bids {
  199. slotNum := bids[j].SlotNum
  200. if slotNum == i {
  201. // There's a bid for the slot
  202. // Check if the bid is greater than the minimum required
  203. for i := 0; i < len(minBidInfo); i++ {
  204. // Find the most recent update
  205. if slotNum >= minBidInfo[i].DefaultSlotSetBidSlotNum {
  206. // Get min bid
  207. minBidSelector := slotNum % int64(len(a.status.Auction.DefaultSlotSetBid))
  208. minBid := minBidInfo[i].DefaultSlotSetBid[minBidSelector]
  209. // Check if the bid has beaten the minimum
  210. bid, ok := new(big.Int).SetString(string(bids[j].BidValue), 10)
  211. if !ok {
  212. return nil, tracerr.New("Wrong bid value, error parsing it as big.Int")
  213. }
  214. if minBid.Cmp(bid) == 1 {
  215. // Min bid is greater than bid, the slot will be forged by boot coordinator
  216. break
  217. }
  218. foundForger = true
  219. break
  220. }
  221. }
  222. if !foundForger { // There is no bid or it's smaller than the minimum
  223. break
  224. }
  225. coordinator, err := a.h.GetCoordinatorAPI(bids[j].Bidder)
  226. if err != nil {
  227. return nil, tracerr.Wrap(err)
  228. }
  229. nextForger.Coordinator = *coordinator
  230. break
  231. }
  232. }
  233. // If there is no bid, the coordinator that will forge is boot coordinator
  234. if !foundForger {
  235. nextForger.Coordinator = historydb.CoordinatorAPI{
  236. Forger: a.status.Auction.BootCoordinator,
  237. URL: a.status.Auction.BootCoordinatorURL,
  238. }
  239. }
  240. nextForgers = append(nextForgers, nextForger)
  241. }
  242. return nextForgers, nil
  243. }
  244. // Metrics
  245. // UpdateMetrics update Status.Metrics information
  246. func (a *API) UpdateMetrics() error {
  247. a.status.RLock()
  248. if a.status.Network.LastBatch == nil {
  249. a.status.RUnlock()
  250. return nil
  251. }
  252. batchNum := a.status.Network.LastBatch.BatchNum
  253. a.status.RUnlock()
  254. metrics, err := a.h.GetMetrics(batchNum)
  255. if err != nil {
  256. return tracerr.Wrap(err)
  257. }
  258. a.status.Lock()
  259. a.status.Metrics = *metrics
  260. a.status.Unlock()
  261. return nil
  262. }
  263. // Recommended fee
  264. // UpdateRecommendedFee update Status.RecommendedFee information
  265. func (a *API) UpdateRecommendedFee() error {
  266. feeExistingAccount, err := a.h.GetAvgTxFee()
  267. if err != nil {
  268. return tracerr.Wrap(err)
  269. }
  270. a.status.Lock()
  271. a.status.RecommendedFee.ExistingAccount = feeExistingAccount
  272. a.status.RecommendedFee.CreatesAccount = createAccountExtraFeePercentage * feeExistingAccount
  273. a.status.RecommendedFee.CreatesAccountAndRegister = createAccountInternalExtraFeePercentage * feeExistingAccount
  274. a.status.Unlock()
  275. return nil
  276. }