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	AmountFloat float64          `meddler:"amount_f"`
123	TokenID     common.TokenID   `meddler:"token_id"`
124	BatchNum    *common.BatchNum `meddler:"batch_num"`     // batchNum in which this tx was forged. If the tx is L2, this must be != 0
125	EthBlockNum int64            `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
126	// L1
127	ToForgeL1TxsNum *int64             `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
128	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
129	FromEthAddr     *ethCommon.Address `meddler:"from_eth_addr"`
130	FromBJJ         *babyjub.PublicKey `meddler:"from_bjj"`
131	LoadAmount      *big.Int           `meddler:"load_amount,bigintnull"`
132	LoadAmountFloat *float64           `meddler:"load_amount_f"`
133	// L2
134	Fee   *common.FeeSelector `meddler:"fee"`
135	Nonce *common.Nonce       `meddler:"nonce"`
136}
137
138// TokenWithUSD add USD info to common.Token
139type TokenWithUSD struct {
140	ItemID      uint64            `json:"itemId" meddler:"item_id"`
141	TokenID     common.TokenID    `json:"id" meddler:"token_id"`
142	EthBlockNum int64             `json:"ethereumBlockNum" meddler:"eth_block_num"` // Ethereum block number in which this token was registered
143	EthAddr     ethCommon.Address `json:"ethereumAddress" meddler:"eth_addr"`
144	Name        string            `json:"name" meddler:"name"`
145	Symbol      string            `json:"symbol" meddler:"symbol"`
146	Decimals    uint64            `json:"decimals" meddler:"decimals"`
147	USD         *float64          `json:"USD" meddler:"usd"`
148	USDUpdate   *time.Time        `json:"fiatUpdate" meddler:"usd_update,utctime"`
149	TotalItems  uint64            `json:"-" meddler:"total_items"`
150	FirstItem   uint64            `json:"-" meddler:"first_item"`
151	LastItem    uint64            `json:"-" meddler:"last_item"`
152}
153
154// ExitAPI is a representation of a exit with additional information
155// required by the API, and extracted by joining token table
156type ExitAPI struct {
157	ItemID                 uint64                          `meddler:"item_id"`
158	BatchNum               common.BatchNum                 `meddler:"batch_num"`
159	AccountIdx             apitypes.HezIdx                 `meddler:"account_idx"`
160	MerkleProof            *merkletree.CircomVerifierProof `meddler:"merkle_proof,json"`
161	Balance                apitypes.BigIntStr              `meddler:"balance"`
162	InstantWithdrawn       *int64                          `meddler:"instant_withdrawn"`
163	DelayedWithdrawRequest *int64                          `meddler:"delayed_withdraw_request"`
164	DelayedWithdrawn       *int64                          `meddler:"delayed_withdrawn"`
165	TotalItems             uint64                          `meddler:"total_items"`
166	FirstItem              uint64                          `meddler:"first_item"`
167	LastItem               uint64                          `meddler:"last_item"`
168	TokenID                common.TokenID                  `meddler:"token_id"`
169	TokenItemID            uint64                          `meddler:"token_item_id"`
170	TokenEthBlockNum       int64                           `meddler:"token_block"`
171	TokenEthAddr           ethCommon.Address               `meddler:"eth_addr"`
172	TokenName              string                          `meddler:"name"`
173	TokenSymbol            string                          `meddler:"symbol"`
174	TokenDecimals          uint64                          `meddler:"decimals"`
175	TokenUSD               *float64                        `meddler:"usd"`
176	TokenUSDUpdate         *time.Time                      `meddler:"usd_update"`
177}
178
179// MarshalJSON is used to neast some of the fields of ExitAPI
180// without the need of auxiliar structs
181func (e ExitAPI) MarshalJSON() ([]byte, error) {
182	siblings := []string{}
183	for i := 0; i < len(e.MerkleProof.Siblings); i++ {
184		siblings = append(siblings, e.MerkleProof.Siblings[i].String())
185	}
186	return json.Marshal(map[string]interface{}{
187		"itemId":       e.ItemID,
188		"batchNum":     e.BatchNum,
189		"accountIndex": e.AccountIdx,
190		"merkleProof": map[string]interface{}{
191			"Root":     e.MerkleProof.Root.String(),
192			"Siblings": siblings,
193			"OldKey":   e.MerkleProof.OldKey.String(),
194			"OldValue": e.MerkleProof.OldValue.String(),
195			"IsOld0":   e.MerkleProof.IsOld0,
196			"Key":      e.MerkleProof.Key.String(),
197			"Value":    e.MerkleProof.Value.String(),
198			"Fnc":      e.MerkleProof.Fnc,
199		},
200		"balance":                e.Balance,
201		"instantWithdrawn":       e.InstantWithdrawn,
202		"delayedWithdrawRequest": e.DelayedWithdrawRequest,
203		"delayedWithdrawn":       e.DelayedWithdrawn,
204		"token": map[string]interface{}{
205			"id":               e.TokenID,
206			"itemId":           e.TokenItemID,
207			"ethereumBlockNum": e.TokenEthBlockNum,
208			"ethereumAddress":  e.TokenEthAddr,
209			"name":             e.TokenName,
210			"symbol":           e.TokenSymbol,
211			"decimals":         e.TokenDecimals,
212			"USD":              e.TokenUSD,
213			"fiatUpdate":       e.TokenUSDUpdate,
214		},
215	})
216}
217
218// CoordinatorAPI is a representation of a coordinator with additional information
219// required by the API
220type CoordinatorAPI struct {
221	ItemID      uint64            `json:"itemId" meddler:"item_id"`
222	Bidder      ethCommon.Address `json:"bidderAddr" meddler:"bidder_addr"`
223	Forger      ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
224	EthBlockNum int64             `json:"ethereumBlock" meddler:"eth_block_num"`
225	URL         string            `json:"URL" meddler:"url"`
226	TotalItems  uint64            `json:"-" meddler:"total_items"`
227	FirstItem   uint64            `json:"-" meddler:"first_item"`
228	LastItem    uint64            `json:"-" meddler:"last_item"`
229}
230
231// AccountAPI is a representation of a account with additional information
232// required by the API
233type AccountAPI struct {
234	ItemID           uint64              `meddler:"item_id"`
235	Idx              apitypes.HezIdx     `meddler:"idx"`
236	BatchNum         common.BatchNum     `meddler:"batch_num"`
237	PublicKey        apitypes.HezBJJ     `meddler:"bjj"`
238	EthAddr          apitypes.HezEthAddr `meddler:"eth_addr"`
239	Nonce            common.Nonce        `meddler:"-"` // max of 40 bits used
240	Balance          *apitypes.BigIntStr `meddler:"-"` // max of 192 bits used
241	TotalItems       uint64              `meddler:"total_items"`
242	FirstItem        uint64              `meddler:"first_item"`
243	LastItem         uint64              `meddler:"last_item"`
244	TokenID          common.TokenID      `meddler:"token_id"`
245	TokenItemID      int                 `meddler:"token_item_id"`
246	TokenEthBlockNum int64               `meddler:"token_block"`
247	TokenEthAddr     ethCommon.Address   `meddler:"token_eth_addr"`
248	TokenName        string              `meddler:"name"`
249	TokenSymbol      string              `meddler:"symbol"`
250	TokenDecimals    uint64              `meddler:"decimals"`
251	TokenUSD         *float64            `meddler:"usd"`
252	TokenUSDUpdate   *time.Time          `meddler:"usd_update"`
253}
254
255// MarshalJSON is used to neast some of the fields of AccountAPI
256// without the need of auxiliar structs
257func (account AccountAPI) MarshalJSON() ([]byte, error) {
258	jsonAccount := map[string]interface{}{
259		"itemId":             account.ItemID,
260		"accountIndex":       account.Idx,
261		"nonce":              account.Nonce,
262		"balance":            account.Balance,
263		"bjj":                account.PublicKey,
264		"hezEthereumAddress": account.EthAddr,
265		"token": map[string]interface{}{
266			"id":               account.TokenID,
267			"itemId":           account.TokenItemID,
268			"ethereumBlockNum": account.TokenEthBlockNum,
269			"ethereumAddress":  account.TokenEthAddr,
270			"name":             account.TokenName,
271			"symbol":           account.TokenSymbol,
272			"decimals":         account.TokenDecimals,
273			"USD":              account.TokenUSD,
274			"fiatUpdate":       account.TokenUSDUpdate,
275		},
276	}
277	return json.Marshal(jsonAccount)
278}
279
280// BatchAPI is a representation of a batch with additional information
281// required by the API, and extracted by joining block table
282type BatchAPI struct {
283	ItemID        uint64                 `json:"itemId" meddler:"item_id"`
284	BatchNum      common.BatchNum        `json:"batchNum" meddler:"batch_num"`
285	EthBlockNum   int64                  `json:"ethereumBlockNum" meddler:"eth_block_num"`
286	EthBlockHash  ethCommon.Hash         `json:"ethereumBlockHash" meddler:"hash"`
287	Timestamp     time.Time              `json:"timestamp" meddler:"timestamp,utctime"`
288	ForgerAddr    ethCommon.Address      `json:"forgerAddr" meddler:"forger_addr"`
289	CollectedFees apitypes.CollectedFees `json:"collectedFees" meddler:"fees_collected,json"`
290	TotalFeesUSD  *float64               `json:"historicTotalCollectedFeesUSD" meddler:"total_fees_usd"`
291	StateRoot     apitypes.BigIntStr     `json:"stateRoot" meddler:"state_root"`
292	NumAccounts   int                    `json:"numAccounts" meddler:"num_accounts"`
293	ExitRoot      apitypes.BigIntStr     `json:"exitRoot" meddler:"exit_root"`
294	ForgeL1TxsNum *int64                 `json:"forgeL1TransactionsNum" meddler:"forge_l1_txs_num"`
295	SlotNum       int64                  `json:"slotNum" meddler:"slot_num"`
296	TotalItems    uint64                 `json:"-" meddler:"total_items"`
297	FirstItem     uint64                 `json:"-" meddler:"first_item"`
298	LastItem      uint64                 `json:"-" meddler:"last_item"`
299}
300
301// Metrics define metrics of the network
302type Metrics struct {
303	TransactionsPerBatch  float64 `json:"transactionsPerBatch"`
304	BatchFrequency        float64 `json:"batchFrequency"`
305	TransactionsPerSecond float64 `json:"transactionsPerSecond"`
306	TotalAccounts         int64   `json:"totalAccounts"`
307	TotalBJJs             int64   `json:"totalBJJs"`
308	AvgTransactionFee     float64 `json:"avgTransactionFee"`
309}
310
311// BidAPI is a representation of a bid with additional information
312// required by the API
313type BidAPI struct {
314	ItemID      uint64             `json:"itemId" meddler:"item_id"`
315	SlotNum     int64              `json:"slotNum" meddler:"slot_num"`
316	BidValue    apitypes.BigIntStr `json:"bidValue" meddler:"bid_value"`
317	EthBlockNum int64              `json:"ethereumBlockNum" meddler:"eth_block_num"`
318	Bidder      ethCommon.Address  `json:"bidderAddr" meddler:"bidder_addr"`
319	Forger      ethCommon.Address  `json:"forgerAddr" meddler:"forger_addr"`
320	URL         string             `json:"URL" meddler:"url"`
321	Timestamp   time.Time          `json:"timestamp" meddler:"timestamp,utctime"`
322	TotalItems  uint64             `json:"-" meddler:"total_items"`
323	FirstItem   uint64             `json:"-" meddler:"first_item"`
324	LastItem    uint64             `json:"-" meddler:"last_item"`
325}