arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/db/historydb/views.go
db/historydb/views.goRaw
  1package historydb
  2
  3import (
  4	"encoding/json"
  5	"math/big"
  6	"time"
  7
  8	ethCommon "github.com/ethereum/go-ethereum/common"
  9	"github.com/hermeznetwork/hermez-node/apitypes"
 10	"github.com/hermeznetwork/hermez-node/common"
 11	"github.com/iden3/go-iden3-crypto/babyjub"
 12	"github.com/iden3/go-merkletree"
 13)
 14
 15// TxAPI is a representation of a generic Tx with additional information
 16// required by the API, and extracted by joining block and token tables
 17type TxAPI struct {
 18	// Generic
 19	IsL1        bool                 `meddler:"is_l1"`
 20	TxID        common.TxID          `meddler:"id"`
 21	ItemID      uint64               `meddler:"item_id"`
 22	Type        common.TxType        `meddler:"type"`
 23	Position    int                  `meddler:"position"`
 24	FromIdx     *apitypes.HezIdx     `meddler:"from_idx"`
 25	FromEthAddr *apitypes.HezEthAddr `meddler:"from_eth_addr"`
 26	FromBJJ     *apitypes.HezBJJ     `meddler:"from_bjj"`
 27	ToIdx       apitypes.HezIdx      `meddler:"to_idx"`
 28	ToEthAddr   *apitypes.HezEthAddr `meddler:"to_eth_addr"`
 29	ToBJJ       *apitypes.HezBJJ     `meddler:"to_bjj"`
 30	Amount      apitypes.BigIntStr   `meddler:"amount"`
 31	HistoricUSD *float64             `meddler:"amount_usd"`
 32	BatchNum    *common.BatchNum     `meddler:"batch_num"`     // batchNum in which this tx was forged. If the tx is L2, this must be != 0
 33	EthBlockNum int64                `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
 34	// L1
 35	ToForgeL1TxsNum       *int64              `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
 36	UserOrigin            *bool               `meddler:"user_origin"`         // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
 37	LoadAmount            *apitypes.BigIntStr `meddler:"load_amount"`
 38	HistoricLoadAmountUSD *float64            `meddler:"load_amount_usd"`
 39	// L2
 40	Fee            *common.FeeSelector `meddler:"fee"`
 41	HistoricFeeUSD *float64            `meddler:"fee_usd"`
 42	Nonce          *common.Nonce       `meddler:"nonce"`
 43	// API extras
 44	Timestamp        time.Time         `meddler:"timestamp,utctime"`
 45	TotalItems       uint64            `meddler:"total_items"`
 46	FirstItem        uint64            `meddler:"first_item"`
 47	LastItem         uint64            `meddler:"last_item"`
 48	TokenID          common.TokenID    `meddler:"token_id"`
 49	TokenItemID      uint64            `meddler:"token_item_id"`
 50	TokenEthBlockNum int64             `meddler:"token_block"`
 51	TokenEthAddr     ethCommon.Address `meddler:"eth_addr"`
 52	TokenName        string            `meddler:"name"`
 53	TokenSymbol      string            `meddler:"symbol"`
 54	TokenDecimals    uint64            `meddler:"decimals"`
 55	TokenUSD         *float64          `meddler:"usd"`
 56	TokenUSDUpdate   *time.Time        `meddler:"usd_update"`
 57}
 58
 59// MarshalJSON is used to neast some of the fields of TxAPI
 60// without the need of auxiliar structs
 61func (tx TxAPI) MarshalJSON() ([]byte, error) {
 62	jsonTx := map[string]interface{}{
 63		"id":                     tx.TxID,
 64		"itemId":                 tx.ItemID,
 65		"type":                   tx.Type,
 66		"position":               tx.Position,
 67		"fromAccountIndex":       tx.FromIdx,
 68		"fromHezEthereumAddress": tx.FromEthAddr,
 69		"fromBJJ":                tx.FromBJJ,
 70		"toAccountIndex":         tx.ToIdx,
 71		"toHezEthereumAddress":   tx.ToEthAddr,
 72		"toBJJ":                  tx.ToBJJ,
 73		"amount":                 tx.Amount,
 74		"batchNum":               tx.BatchNum,
 75		"historicUSD":            tx.HistoricUSD,
 76		"timestamp":              tx.Timestamp,
 77		"L1Info":                 nil,
 78		"L2Info":                 nil,
 79		"token": map[string]interface{}{
 80			"id":               tx.TokenID,
 81			"itemId":           tx.TokenItemID,
 82			"ethereumBlockNum": tx.TokenEthBlockNum,
 83			"ethereumAddress":  tx.TokenEthAddr,
 84			"name":             tx.TokenName,
 85			"symbol":           tx.TokenSymbol,
 86			"decimals":         tx.TokenDecimals,
 87			"USD":              tx.TokenUSD,
 88			"fiatUpdate":       tx.TokenUSDUpdate,
 89		},
 90	}
 91	if tx.IsL1 {
 92		jsonTx["L1orL2"] = "L1"
 93		jsonTx["L1Info"] = map[string]interface{}{
 94			"toForgeL1TransactionsNum": tx.ToForgeL1TxsNum,
 95			"userOrigin":               tx.UserOrigin,
 96			"loadAmount":               tx.LoadAmount,
 97			"historicLoadAmountUSD":    tx.HistoricLoadAmountUSD,
 98			"ethereumBlockNum":         tx.EthBlockNum,
 99		}
100	} else {
101		jsonTx["L1orL2"] = "L2"
102		jsonTx["L2Info"] = map[string]interface{}{
103			"fee":            tx.Fee,
104			"historicFeeUSD": tx.HistoricFeeUSD,
105			"nonce":          tx.Nonce,
106		}
107	}
108	return json.Marshal(jsonTx)
109}
110
111// txWrite is an representatiion that merges common.L1Tx and common.L2Tx
112// in order to perform inserts into tx table
113type txWrite struct {
114	// Generic
115	IsL1            bool             `meddler:"is_l1"`
116	TxID            common.TxID      `meddler:"id"`
117	Type            common.TxType    `meddler:"type"`
118	Position        int              `meddler:"position"`
119	FromIdx         *common.Idx      `meddler:"from_idx"`
120	ToIdx           common.Idx       `meddler:"to_idx"`
121	Amount          *big.Int         `meddler:"amount,bigint"`
122	EffectiveAmount *big.Int         `meddler:"effective_amount,bigintnull"`
123	AmountFloat     float64          `meddler:"amount_f"`
124	TokenID         common.TokenID   `meddler:"token_id"`
125	BatchNum        *common.BatchNum `meddler:"batch_num"`     // batchNum in which this tx was forged. If the tx is L2, this must be != 0
126	EthBlockNum     int64            `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
127	// L1
128	ToForgeL1TxsNum     *int64             `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
129	UserOrigin          *bool              `meddler:"user_origin"`         // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
130	FromEthAddr         *ethCommon.Address `meddler:"from_eth_addr"`
131	FromBJJ             *babyjub.PublicKey `meddler:"from_bjj"`
132	LoadAmount          *big.Int           `meddler:"load_amount,bigintnull"`
133	EffectiveLoadAmount *big.Int           `meddler:"effective_load_amount,bigintnull"`
134	LoadAmountFloat     *float64           `meddler:"load_amount_f"`
135	// L2
136	Fee   *common.FeeSelector `meddler:"fee"`
137	Nonce *common.Nonce       `meddler:"nonce"`
138}
139
140// TokenWithUSD add USD info to common.Token
141type TokenWithUSD struct {
142	ItemID      uint64            `json:"itemId" meddler:"item_id"`
143	TokenID     common.TokenID    `json:"id" meddler:"token_id"`
144	EthBlockNum int64             `json:"ethereumBlockNum" meddler:"eth_block_num"` // Ethereum block number in which this token was registered
145	EthAddr     ethCommon.Address `json:"ethereumAddress" meddler:"eth_addr"`
146	Name        string            `json:"name" meddler:"name"`
147	Symbol      string            `json:"symbol" meddler:"symbol"`
148	Decimals    uint64            `json:"decimals" meddler:"decimals"`
149	USD         *float64          `json:"USD" meddler:"usd"`
150	USDUpdate   *time.Time        `json:"fiatUpdate" meddler:"usd_update,utctime"`
151	TotalItems  uint64            `json:"-" meddler:"total_items"`
152	FirstItem   uint64            `json:"-" meddler:"first_item"`
153	LastItem    uint64            `json:"-" meddler:"last_item"`
154}
155
156// ExitAPI is a representation of a exit with additional information
157// required by the API, and extracted by joining token table
158type ExitAPI struct {
159	ItemID                 uint64                          `meddler:"item_id"`
160	BatchNum               common.BatchNum                 `meddler:"batch_num"`
161	AccountIdx             apitypes.HezIdx                 `meddler:"account_idx"`
162	MerkleProof            *merkletree.CircomVerifierProof `meddler:"merkle_proof,json"`
163	Balance                apitypes.BigIntStr              `meddler:"balance"`
164	InstantWithdrawn       *int64                          `meddler:"instant_withdrawn"`
165	DelayedWithdrawRequest *int64                          `meddler:"delayed_withdraw_request"`
166	DelayedWithdrawn       *int64                          `meddler:"delayed_withdrawn"`
167	TotalItems             uint64                          `meddler:"total_items"`
168	FirstItem              uint64                          `meddler:"first_item"`
169	LastItem               uint64                          `meddler:"last_item"`
170	TokenID                common.TokenID                  `meddler:"token_id"`
171	TokenItemID            uint64                          `meddler:"token_item_id"`
172	TokenEthBlockNum       int64                           `meddler:"token_block"`
173	TokenEthAddr           ethCommon.Address               `meddler:"eth_addr"`
174	TokenName              string                          `meddler:"name"`
175	TokenSymbol            string                          `meddler:"symbol"`
176	TokenDecimals          uint64                          `meddler:"decimals"`
177	TokenUSD               *float64                        `meddler:"usd"`
178	TokenUSDUpdate         *time.Time                      `meddler:"usd_update"`
179}
180
181// MarshalJSON is used to neast some of the fields of ExitAPI
182// without the need of auxiliar structs
183func (e ExitAPI) MarshalJSON() ([]byte, error) {
184	siblings := []string{}
185	for i := 0; i < len(e.MerkleProof.Siblings); i++ {
186		siblings = append(siblings, e.MerkleProof.Siblings[i].String())
187	}
188	return json.Marshal(map[string]interface{}{
189		"itemId":       e.ItemID,
190		"batchNum":     e.BatchNum,
191		"accountIndex": e.AccountIdx,
192		"merkleProof": map[string]interface{}{
193			"Root":     e.MerkleProof.Root.String(),
194			"Siblings": siblings,
195			"OldKey":   e.MerkleProof.OldKey.String(),
196			"OldValue": e.MerkleProof.OldValue.String(),
197			"IsOld0":   e.MerkleProof.IsOld0,
198			"Key":      e.MerkleProof.Key.String(),
199			"Value":    e.MerkleProof.Value.String(),
200			"Fnc":      e.MerkleProof.Fnc,
201		},
202		"balance":                e.Balance,
203		"instantWithdrawn":       e.InstantWithdrawn,
204		"delayedWithdrawRequest": e.DelayedWithdrawRequest,
205		"delayedWithdrawn":       e.DelayedWithdrawn,
206		"token": map[string]interface{}{
207			"id":               e.TokenID,
208			"itemId":           e.TokenItemID,
209			"ethereumBlockNum": e.TokenEthBlockNum,
210			"ethereumAddress":  e.TokenEthAddr,
211			"name":             e.TokenName,
212			"symbol":           e.TokenSymbol,
213			"decimals":         e.TokenDecimals,
214			"USD":              e.TokenUSD,
215			"fiatUpdate":       e.TokenUSDUpdate,
216		},
217	})
218}
219
220// CoordinatorAPI is a representation of a coordinator with additional information
221// required by the API
222type CoordinatorAPI struct {
223	ItemID      uint64            `json:"itemId" meddler:"item_id"`
224	Bidder      ethCommon.Address `json:"bidderAddr" meddler:"bidder_addr"`
225	Forger      ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
226	EthBlockNum int64             `json:"ethereumBlock" meddler:"eth_block_num"`
227	URL         string            `json:"URL" meddler:"url"`
228	TotalItems  uint64            `json:"-" meddler:"total_items"`
229	FirstItem   uint64            `json:"-" meddler:"first_item"`
230	LastItem    uint64            `json:"-" meddler:"last_item"`
231}
232
233// AccountAPI is a representation of a account with additional information
234// required by the API
235type AccountAPI struct {
236	ItemID           uint64              `meddler:"item_id"`
237	Idx              apitypes.HezIdx     `meddler:"idx"`
238	BatchNum         common.BatchNum     `meddler:"batch_num"`
239	PublicKey        apitypes.HezBJJ     `meddler:"bjj"`
240	EthAddr          apitypes.HezEthAddr `meddler:"eth_addr"`
241	Nonce            common.Nonce        `meddler:"-"` // max of 40 bits used
242	Balance          *apitypes.BigIntStr `meddler:"-"` // max of 192 bits used
243	TotalItems       uint64              `meddler:"total_items"`
244	FirstItem        uint64              `meddler:"first_item"`
245	LastItem         uint64              `meddler:"last_item"`
246	TokenID          common.TokenID      `meddler:"token_id"`
247	TokenItemID      int                 `meddler:"token_item_id"`
248	TokenEthBlockNum int64               `meddler:"token_block"`
249	TokenEthAddr     ethCommon.Address   `meddler:"token_eth_addr"`
250	TokenName        string              `meddler:"name"`
251	TokenSymbol      string              `meddler:"symbol"`
252	TokenDecimals    uint64              `meddler:"decimals"`
253	TokenUSD         *float64            `meddler:"usd"`
254	TokenUSDUpdate   *time.Time          `meddler:"usd_update"`
255}
256
257// MarshalJSON is used to neast some of the fields of AccountAPI
258// without the need of auxiliar structs
259func (account AccountAPI) MarshalJSON() ([]byte, error) {
260	jsonAccount := map[string]interface{}{
261		"itemId":             account.ItemID,
262		"accountIndex":       account.Idx,
263		"nonce":              account.Nonce,
264		"balance":            account.Balance,
265		"bjj":                account.PublicKey,
266		"hezEthereumAddress": account.EthAddr,
267		"token": map[string]interface{}{
268			"id":               account.TokenID,
269			"itemId":           account.TokenItemID,
270			"ethereumBlockNum": account.TokenEthBlockNum,
271			"ethereumAddress":  account.TokenEthAddr,
272			"name":             account.TokenName,
273			"symbol":           account.TokenSymbol,
274			"decimals":         account.TokenDecimals,
275			"USD":              account.TokenUSD,
276			"fiatUpdate":       account.TokenUSDUpdate,
277		},
278	}
279	return json.Marshal(jsonAccount)
280}
281
282// BatchAPI is a representation of a batch with additional information
283// required by the API, and extracted by joining block table
284type BatchAPI struct {
285	ItemID        uint64                 `json:"itemId" meddler:"item_id"`
286	BatchNum      common.BatchNum        `json:"batchNum" meddler:"batch_num"`
287	EthBlockNum   int64                  `json:"ethereumBlockNum" meddler:"eth_block_num"`
288	EthBlockHash  ethCommon.Hash         `json:"ethereumBlockHash" meddler:"hash"`
289	Timestamp     time.Time              `json:"timestamp" meddler:"timestamp,utctime"`
290	ForgerAddr    ethCommon.Address      `json:"forgerAddr" meddler:"forger_addr"`
291	CollectedFees apitypes.CollectedFees `json:"collectedFees" meddler:"fees_collected,json"`
292	TotalFeesUSD  *float64               `json:"historicTotalCollectedFeesUSD" meddler:"total_fees_usd"`
293	StateRoot     apitypes.BigIntStr     `json:"stateRoot" meddler:"state_root"`
294	NumAccounts   int                    `json:"numAccounts" meddler:"num_accounts"`
295	ExitRoot      apitypes.BigIntStr     `json:"exitRoot" meddler:"exit_root"`
296	ForgeL1TxsNum *int64                 `json:"forgeL1TransactionsNum" meddler:"forge_l1_txs_num"`
297	SlotNum       int64                  `json:"slotNum" meddler:"slot_num"`
298	TotalItems    uint64                 `json:"-" meddler:"total_items"`
299	FirstItem     uint64                 `json:"-" meddler:"first_item"`
300	LastItem      uint64                 `json:"-" meddler:"last_item"`
301}
302
303// Metrics define metrics of the network
304type Metrics struct {
305	TransactionsPerBatch  float64 `json:"transactionsPerBatch"`
306	BatchFrequency        float64 `json:"batchFrequency"`
307	TransactionsPerSecond float64 `json:"transactionsPerSecond"`
308	TotalAccounts         int64   `json:"totalAccounts" meddler:"total_accounts"`
309	TotalBJJs             int64   `json:"totalBJJs" meddler:"total_bjjs"`
310	AvgTransactionFee     float64 `json:"avgTransactionFee"`
311}
312
313// MetricsTotals is used to get temporal information from HistoryDB
314// to calculate data to be stored into the Metrics struct
315type MetricsTotals struct {
316	TotalTransactions uint64          `meddler:"total_txs"`
317	FirstBatchNum     common.BatchNum `meddler:"batch_num"`
318	TotalBatches      int64           `meddler:"total_batches"`
319	TotalFeesUSD      float64         `meddler:"total_fees"`
320}
321
322// BidAPI is a representation of a bid with additional information
323// required by the API
324type BidAPI struct {
325	ItemID      uint64             `json:"itemId" meddler:"item_id"`
326	SlotNum     int64              `json:"slotNum" meddler:"slot_num"`
327	BidValue    apitypes.BigIntStr `json:"bidValue" meddler:"bid_value"`
328	EthBlockNum int64              `json:"ethereumBlockNum" meddler:"eth_block_num"`
329	Bidder      ethCommon.Address  `json:"bidderAddr" meddler:"bidder_addr"`
330	Forger      ethCommon.Address  `json:"forgerAddr" meddler:"forger_addr"`
331	URL         string             `json:"URL" meddler:"url"`
332	Timestamp   time.Time          `json:"timestamp" meddler:"timestamp,utctime"`
333	TotalItems  uint64             `json:"-" meddler:"total_items"`
334	FirstItem   uint64             `json:"-" meddler:"first_item"`
335	LastItem    uint64             `json:"-" meddler:"last_item"`
336}