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