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.

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