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.

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