hermez-node/db/historydb/historydb.go
db/historydb/historydb.goRaw
1package historydb
2
3import (
4 "database/sql"
5 "errors"
6 "fmt"
7 "math"
8 "math/big"
9
10 ethCommon "github.com/ethereum/go-ethereum/common"
11 "github.com/hermeznetwork/hermez-node/common"
12 "github.com/hermeznetwork/hermez-node/db"
13 "github.com/hermeznetwork/hermez-node/log"
14 "github.com/iden3/go-iden3-crypto/babyjub"
15 "github.com/jmoiron/sqlx"
16
17 //nolint:errcheck // driver for postgres DB
18 _ "github.com/lib/pq"
19 "github.com/russross/meddler"
20)
21
22const (
23 // OrderAsc indicates ascending order when using pagination
24 OrderAsc = "ASC"
25 // OrderDesc indicates descending order when using pagination
26 OrderDesc = "DESC"
27)
28
29// TODO(Edu): Document here how HistoryDB is kept consistent
30
31// HistoryDB persist the historic of the rollup
32type HistoryDB struct {
33 db *sqlx.DB
34}
35
36// NewHistoryDB initialize the DB
37func NewHistoryDB(db *sqlx.DB) *HistoryDB {
38 return &HistoryDB{db: db}
39}
40
41// AddBlock insert a block into the DB
42func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
43func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
44 return meddler.Insert(d, "block", block)
45}
46
47// AddBlocks inserts blocks into the DB
48func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
49 return hdb.addBlocks(hdb.db, blocks)
50}
51
52func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
53 return db.BulkInsert(
54 d,
55 `INSERT INTO block (
56 eth_block_num,
57 timestamp,
58 hash
59 ) VALUES %s;`,
60 blocks[:],
61 )
62}
63
64// GetBlock retrieve a block from the DB, given a block number
65func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
66 block := &common.Block{}
67 err := meddler.QueryRow(
68 hdb.db, block,
69 "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
70 )
71 return block, err
72}
73
74// GetAllBlocks retrieve all blocks from the DB
75func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
76 var blocks []*common.Block
77 err := meddler.QueryAll(
78 hdb.db, &blocks,
79 "SELECT * FROM block;",
80 )
81 return db.SlicePtrsToSlice(blocks).([]common.Block), err
82}
83
84// GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
85func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
86 var blocks []*common.Block
87 err := meddler.QueryAll(
88 hdb.db, &blocks,
89 "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2;",
90 from, to,
91 )
92 return db.SlicePtrsToSlice(blocks).([]common.Block), err
93}
94
95// GetLastBlock retrieve the block with the highest block number from the DB
96func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
97 block := &common.Block{}
98 err := meddler.QueryRow(
99 hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
100 )
101 return block, err
102}
103
104// AddBatch insert a Batch into the DB
105func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
106func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
107 // Calculate total collected fees in USD
108 // Get IDs of collected tokens for fees
109 tokenIDs := []common.TokenID{}
110 for id := range batch.CollectedFees {
111 tokenIDs = append(tokenIDs, id)
112 }
113 // Get USD value of the tokens
114 type tokenPrice struct {
115 ID common.TokenID `meddler:"token_id"`
116 USD *float64 `meddler:"usd"`
117 Decimals int `meddler:"decimals"`
118 }
119 var tokenPrices []*tokenPrice
120 if len(tokenIDs) > 0 {
121 query, args, err := sqlx.In(
122 "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?)",
123 tokenIDs,
124 )
125 if err != nil {
126 return err
127 }
128 query = hdb.db.Rebind(query)
129 if err := meddler.QueryAll(
130 hdb.db, &tokenPrices, query, args...,
131 ); err != nil {
132 return err
133 }
134 }
135 // Calculate total collected
136 var total float64
137 for _, tokenPrice := range tokenPrices {
138 if tokenPrice.USD == nil {
139 continue
140 }
141 f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
142 amount, _ := f.Float64()
143 total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
144 }
145 batch.TotalFeesUSD = &total
146 // Insert to DB
147 return meddler.Insert(d, "batch", batch)
148}
149
150// AddBatches insert Bids into the DB
151func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
152 return hdb.addBatches(hdb.db, batches)
153}
154func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
155 for i := 0; i < len(batches); i++ {
156 if err := hdb.addBatch(d, &batches[i]); err != nil {
157 return err
158 }
159 }
160 return nil
161}
162
163// GetBatchAPI return the batch with the given batchNum
164func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error) {
165 batch := &BatchAPI{}
166 return batch, meddler.QueryRow(
167 hdb.db, batch,
168 `SELECT batch.*, block.timestamp, block.hash
169 FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num
170 WHERE batch_num = $1;`, batchNum,
171 )
172}
173
174// GetBatchesAPI return the batches applying the given filters
175func (hdb *HistoryDB) GetBatchesAPI(
176 minBatchNum, maxBatchNum, slotNum *uint,
177 forgerAddr *ethCommon.Address,
178 fromItem, limit *uint, order string,
179) ([]BatchAPI, *db.Pagination, error) {
180 var query string
181 var args []interface{}
182 queryStr := `SELECT batch.*, block.timestamp, block.hash,
183 count(*) OVER() AS total_items, MIN(batch.item_id) OVER() AS first_item,
184 MAX(batch.item_id) OVER() AS last_item
185 FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num `
186 // Apply filters
187 nextIsAnd := false
188 // minBatchNum filter
189 if minBatchNum != nil {
190 if nextIsAnd {
191 queryStr += "AND "
192 } else {
193 queryStr += "WHERE "
194 }
195 queryStr += "batch.batch_num > ? "
196 args = append(args, minBatchNum)
197 nextIsAnd = true
198 }
199 // maxBatchNum filter
200 if maxBatchNum != nil {
201 if nextIsAnd {
202 queryStr += "AND "
203 } else {
204 queryStr += "WHERE "
205 }
206 queryStr += "batch.batch_num < ? "
207 args = append(args, maxBatchNum)
208 nextIsAnd = true
209 }
210 // slotNum filter
211 if slotNum != nil {
212 if nextIsAnd {
213 queryStr += "AND "
214 } else {
215 queryStr += "WHERE "
216 }
217 queryStr += "batch.slot_num = ? "
218 args = append(args, slotNum)
219 nextIsAnd = true
220 }
221 // forgerAddr filter
222 if forgerAddr != nil {
223 if nextIsAnd {
224 queryStr += "AND "
225 } else {
226 queryStr += "WHERE "
227 }
228 queryStr += "batch.forger_addr = ? "
229 args = append(args, forgerAddr)
230 nextIsAnd = true
231 }
232 // pagination
233 if fromItem != nil {
234 if nextIsAnd {
235 queryStr += "AND "
236 } else {
237 queryStr += "WHERE "
238 }
239 if order == OrderAsc {
240 queryStr += "batch.item_id >= ? "
241 } else {
242 queryStr += "batch.item_id <= ? "
243 }
244 args = append(args, fromItem)
245 }
246 queryStr += "ORDER BY batch.item_id "
247 if order == OrderAsc {
248 queryStr += " ASC "
249 } else {
250 queryStr += " DESC "
251 }
252 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
253 query = hdb.db.Rebind(queryStr)
254 log.Debug(query)
255 batchPtrs := []*BatchAPI{}
256 if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil {
257 return nil, nil, err
258 }
259 batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI)
260 if len(batches) == 0 {
261 return nil, nil, sql.ErrNoRows
262 }
263 return batches, &db.Pagination{
264 TotalItems: batches[0].TotalItems,
265 FirstItem: batches[0].FirstItem,
266 LastItem: batches[0].LastItem,
267 }, nil
268}
269
270// GetAllBatches retrieve all batches from the DB
271func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
272 var batches []*common.Batch
273 err := meddler.QueryAll(
274 hdb.db, &batches,
275 `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
276 batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
277 batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch;`,
278 )
279 return db.SlicePtrsToSlice(batches).([]common.Batch), err
280}
281
282// GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
283func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
284 var batches []*common.Batch
285 err := meddler.QueryAll(
286 hdb.db, &batches,
287 "SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;",
288 from, to,
289 )
290 return db.SlicePtrsToSlice(batches).([]common.Batch), err
291}
292
293// GetLastBatchNum returns the BatchNum of the latest forged batch
294func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
295 row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
296 var batchNum common.BatchNum
297 return batchNum, row.Scan(&batchNum)
298}
299
300// GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
301// batches. If there's no batch in the DB (nil, nil) is returned.
302func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
303 row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
304 lastL1TxsNum := new(int64)
305 return lastL1TxsNum, row.Scan(&lastL1TxsNum)
306}
307
308// Reorg deletes all the information that was added into the DB after the
309// lastValidBlock. If lastValidBlock is negative, all block information is
310// deleted.
311func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
312 var err error
313 if lastValidBlock < 0 {
314 _, err = hdb.db.Exec("DELETE FROM block;")
315 } else {
316 _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
317 }
318 return err
319}
320
321// SyncPoD stores all the data that can be changed / added on a block in the PoD SC
322func (hdb *HistoryDB) SyncPoD(
323 blockNum uint64,
324 bids []common.Bid,
325 coordinators []common.Coordinator,
326 vars *common.AuctionVars,
327) error {
328 return nil
329}
330
331// AddBids insert Bids into the DB
332func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
333func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
334 // TODO: check the coordinator info
335 return db.BulkInsert(
336 d,
337 "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
338 bids[:],
339 )
340}
341
342// GetBids return the bids
343func (hdb *HistoryDB) GetBids() ([]common.Bid, error) {
344 var bids []*common.Bid
345 err := meddler.QueryAll(
346 hdb.db, &bids,
347 "SELECT * FROM bid;",
348 )
349 return db.SlicePtrsToSlice(bids).([]common.Bid), err
350}
351
352// AddCoordinators insert Coordinators into the DB
353func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
354 return hdb.addCoordinators(hdb.db, coordinators)
355}
356func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
357 return db.BulkInsert(
358 d,
359 "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
360 coordinators[:],
361 )
362}
363
364// AddExitTree insert Exit tree into the DB
365func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
366 return hdb.addExitTree(hdb.db, exitTree)
367}
368func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
369 return db.BulkInsert(
370 d,
371 "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
372 "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
373 exitTree[:],
374 )
375}
376
377// AddToken insert a token into the DB
378func (hdb *HistoryDB) AddToken(token *common.Token) error {
379 return meddler.Insert(hdb.db, "token", token)
380}
381
382// AddTokens insert tokens into the DB
383func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
384func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
385 return db.BulkInsert(
386 d,
387 `INSERT INTO token (
388 token_id,
389 eth_block_num,
390 eth_addr,
391 name,
392 symbol,
393 decimals
394 ) VALUES %s;`,
395 tokens[:],
396 )
397}
398
399// UpdateTokenValue updates the USD value of a token
400func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
401 _, err := hdb.db.Exec(
402 "UPDATE token SET usd = $1 WHERE symbol = $2;",
403 value, tokenSymbol,
404 )
405 return err
406}
407
408// GetToken returns a token from the DB given a TokenID
409func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
410 token := &TokenWithUSD{}
411 err := meddler.QueryRow(
412 hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
413 )
414 return token, err
415}
416
417// GetAllTokens returns all tokens from the DB
418func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
419 var tokens []*TokenWithUSD
420 err := meddler.QueryAll(
421 hdb.db, &tokens,
422 "SELECT * FROM token ORDER BY token_id;",
423 )
424 return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err
425}
426
427// GetTokens returns a list of tokens from the DB
428func (hdb *HistoryDB) GetTokens(ids []common.TokenID, symbols []string, name string, fromItem, limit *uint, order string) ([]TokenWithUSD, *db.Pagination, error) {
429 var query string
430 var args []interface{}
431 queryStr := `SELECT * , COUNT(*) OVER() AS total_items, MIN(token.item_id) OVER() AS first_item, MAX(token.item_id) OVER() AS last_item FROM token `
432 // Apply filters
433 nextIsAnd := false
434 if len(ids) > 0 {
435 queryStr += "WHERE token_id IN (?) "
436 nextIsAnd = true
437 args = append(args, ids)
438 }
439 if len(symbols) > 0 {
440 if nextIsAnd {
441 queryStr += "AND "
442 } else {
443 queryStr += "WHERE "
444 }
445 queryStr += "symbol IN (?) "
446 args = append(args, symbols)
447 nextIsAnd = true
448 }
449 if name != "" {
450 if nextIsAnd {
451 queryStr += "AND "
452 } else {
453 queryStr += "WHERE "
454 }
455 queryStr += "name ~ ? "
456 args = append(args, name)
457 nextIsAnd = true
458 }
459 if fromItem != nil {
460 if nextIsAnd {
461 queryStr += "AND "
462 } else {
463 queryStr += "WHERE "
464 }
465 if order == OrderAsc {
466 queryStr += "item_id >= ? "
467 } else {
468 queryStr += "item_id <= ? "
469 }
470 args = append(args, fromItem)
471 }
472 // pagination
473 queryStr += "ORDER BY item_id "
474 if order == OrderAsc {
475 queryStr += "ASC "
476 } else {
477 queryStr += "DESC "
478 }
479 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
480 query, argsQ, err := sqlx.In(queryStr, args...)
481 if err != nil {
482 return nil, nil, err
483 }
484 query = hdb.db.Rebind(query)
485 tokens := []*TokenWithUSD{}
486 if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
487 return nil, nil, err
488 }
489 if len(tokens) == 0 {
490 return nil, nil, sql.ErrNoRows
491 }
492 return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), &db.Pagination{
493 TotalItems: tokens[0].TotalItems,
494 FirstItem: tokens[0].FirstItem,
495 LastItem: tokens[0].LastItem,
496 }, nil
497}
498
499// GetTokenSymbols returns all the token symbols from the DB
500func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
501 var tokenSymbols []string
502 rows, err := hdb.db.Query("SELECT symbol FROM token;")
503 if err != nil {
504 return nil, err
505 }
506 sym := new(string)
507 for rows.Next() {
508 err = rows.Scan(sym)
509 if err != nil {
510 return nil, err
511 }
512 tokenSymbols = append(tokenSymbols, *sym)
513 }
514 return tokenSymbols, nil
515}
516
517// AddAccounts insert accounts into the DB
518func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
519 return hdb.addAccounts(hdb.db, accounts)
520}
521func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
522 return db.BulkInsert(
523 d,
524 `INSERT INTO account (
525 idx,
526 token_id,
527 batch_num,
528 bjj,
529 eth_addr
530 ) VALUES %s;`,
531 accounts[:],
532 )
533}
534
535// GetAccounts returns a list of accounts from the DB
536func (hdb *HistoryDB) GetAccounts() ([]common.Account, error) {
537 var accs []*common.Account
538 err := meddler.QueryAll(
539 hdb.db, &accs,
540 "SELECT * FROM account ORDER BY idx;",
541 )
542 return db.SlicePtrsToSlice(accs).([]common.Account), err
543}
544
545// AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
546// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
547// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
548func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
549
550// addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
551// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
552// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
553func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
554 txs := []txWrite{}
555 for i := 0; i < len(l1txs); i++ {
556 af := new(big.Float).SetInt(l1txs[i].Amount)
557 amountFloat, _ := af.Float64()
558 laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
559 loadAmountFloat, _ := laf.Float64()
560 txs = append(txs, txWrite{
561 // Generic
562 IsL1: true,
563 TxID: l1txs[i].TxID,
564 Type: l1txs[i].Type,
565 Position: l1txs[i].Position,
566 FromIdx: &l1txs[i].FromIdx,
567 ToIdx: l1txs[i].ToIdx,
568 Amount: l1txs[i].Amount,
569 AmountFloat: amountFloat,
570 TokenID: l1txs[i].TokenID,
571 BatchNum: l1txs[i].BatchNum,
572 EthBlockNum: l1txs[i].EthBlockNum,
573 // L1
574 ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
575 UserOrigin: &l1txs[i].UserOrigin,
576 FromEthAddr: &l1txs[i].FromEthAddr,
577 FromBJJ: l1txs[i].FromBJJ,
578 LoadAmount: l1txs[i].LoadAmount,
579 LoadAmountFloat: &loadAmountFloat,
580 })
581 }
582 return hdb.addTxs(d, txs)
583}
584
585// AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
586func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
587
588// addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
589func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
590 txs := []txWrite{}
591 for i := 0; i < len(l2txs); i++ {
592 f := new(big.Float).SetInt(l2txs[i].Amount)
593 amountFloat, _ := f.Float64()
594 txs = append(txs, txWrite{
595 // Generic
596 IsL1: false,
597 TxID: l2txs[i].TxID,
598 Type: l2txs[i].Type,
599 Position: l2txs[i].Position,
600 FromIdx: &l2txs[i].FromIdx,
601 ToIdx: l2txs[i].ToIdx,
602 Amount: l2txs[i].Amount,
603 AmountFloat: amountFloat,
604 BatchNum: &l2txs[i].BatchNum,
605 EthBlockNum: l2txs[i].EthBlockNum,
606 // L2
607 Fee: &l2txs[i].Fee,
608 Nonce: &l2txs[i].Nonce,
609 })
610 }
611 return hdb.addTxs(d, txs)
612}
613
614func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
615 return db.BulkInsert(
616 d,
617 `INSERT INTO tx (
618 is_l1,
619 id,
620 type,
621 position,
622 from_idx,
623 to_idx,
624 amount,
625 amount_f,
626 token_id,
627 batch_num,
628 eth_block_num,
629 to_forge_l1_txs_num,
630 user_origin,
631 from_eth_addr,
632 from_bjj,
633 load_amount,
634 load_amount_f,
635 fee,
636 nonce
637 ) VALUES %s;`,
638 txs[:],
639 )
640}
641
642// // GetTxs returns a list of txs from the DB
643// func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
644// var txs []*common.Tx
645// err := meddler.QueryAll(
646// hdb.db, &txs,
647// `SELECT * FROM tx
648// ORDER BY (batch_num, position) ASC`,
649// )
650// return db.SlicePtrsToSlice(txs).([]common.Tx), err
651// }
652
653// GetHistoryTx returns a tx from the DB given a TxID
654func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*HistoryTx, error) {
655 tx := &HistoryTx{}
656 err := meddler.QueryRow(
657 hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
658 tx.from_idx, tx.to_idx, tx.amount, tx.token_id, tx.amount_usd,
659 tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
660 tx.from_eth_addr, tx.from_bjj, tx.load_amount,
661 tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
662 token.token_id, token.eth_block_num AS token_block,
663 token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
664 token.usd_update, block.timestamp
665 FROM tx INNER JOIN token ON tx.token_id = token.token_id
666 INNER JOIN block ON tx.eth_block_num = block.eth_block_num
667 WHERE tx.id = $1;`, txID,
668 )
669 return tx, err
670}
671
672// GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
673// and pagination info
674func (hdb *HistoryDB) GetHistoryTxs(
675 ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
676 tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
677 fromItem, limit *uint, order string,
678) ([]HistoryTx, *db.Pagination, error) {
679 if ethAddr != nil && bjj != nil {
680 return nil, nil, errors.New("ethAddr and bjj are incompatible")
681 }
682 var query string
683 var args []interface{}
684 queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
685 tx.from_idx, tx.to_idx, tx.amount, tx.token_id, tx.amount_usd,
686 tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
687 tx.from_eth_addr, tx.from_bjj, tx.load_amount,
688 tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
689 token.token_id, token.eth_block_num AS token_block,
690 token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
691 token.usd_update, block.timestamp, count(*) OVER() AS total_items,
692 MIN(tx.item_id) OVER() AS first_item, MAX(tx.item_id) OVER() AS last_item
693 FROM tx INNER JOIN token ON tx.token_id = token.token_id
694 INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
695 // Apply filters
696 nextIsAnd := false
697 // ethAddr filter
698 if ethAddr != nil {
699 queryStr = `WITH acc AS
700 (select idx from account where eth_addr = ?) ` + queryStr
701 queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
702 nextIsAnd = true
703 args = append(args, ethAddr)
704 } else if bjj != nil { // bjj filter
705 queryStr = `WITH acc AS
706 (select idx from account where bjj = ?) ` + queryStr
707 queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
708 nextIsAnd = true
709 args = append(args, bjj)
710 }
711 // tokenID filter
712 if tokenID != nil {
713 if nextIsAnd {
714 queryStr += "AND "
715 } else {
716 queryStr += "WHERE "
717 }
718 queryStr += "tx.token_id = ? "
719 args = append(args, tokenID)
720 nextIsAnd = true
721 }
722 // idx filter
723 if idx != nil {
724 if nextIsAnd {
725 queryStr += "AND "
726 } else {
727 queryStr += "WHERE "
728 }
729 queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
730 args = append(args, idx, idx)
731 nextIsAnd = true
732 }
733 // batchNum filter
734 if batchNum != nil {
735 if nextIsAnd {
736 queryStr += "AND "
737 } else {
738 queryStr += "WHERE "
739 }
740 queryStr += "tx.batch_num = ? "
741 args = append(args, batchNum)
742 nextIsAnd = true
743 }
744 // txType filter
745 if txType != nil {
746 if nextIsAnd {
747 queryStr += "AND "
748 } else {
749 queryStr += "WHERE "
750 }
751 queryStr += "tx.type = ? "
752 args = append(args, txType)
753 nextIsAnd = true
754 }
755 if fromItem != nil {
756 if nextIsAnd {
757 queryStr += "AND "
758 } else {
759 queryStr += "WHERE "
760 }
761 if order == OrderAsc {
762 queryStr += "tx.item_id >= ? "
763 } else {
764 queryStr += "tx.item_id <= ? "
765 }
766 args = append(args, fromItem)
767 nextIsAnd = true
768 }
769 if nextIsAnd {
770 queryStr += "AND "
771 } else {
772 queryStr += "WHERE "
773 }
774 queryStr += "tx.batch_num IS NOT NULL "
775
776 // pagination
777 queryStr += "ORDER BY tx.item_id "
778 if order == OrderAsc {
779 queryStr += " ASC "
780 } else {
781 queryStr += " DESC "
782 }
783 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
784 query = hdb.db.Rebind(queryStr)
785 log.Debug(query)
786 txsPtrs := []*HistoryTx{}
787 if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
788 return nil, nil, err
789 }
790 txs := db.SlicePtrsToSlice(txsPtrs).([]HistoryTx)
791 if len(txs) == 0 {
792 return nil, nil, sql.ErrNoRows
793 }
794 return txs, &db.Pagination{
795 TotalItems: txs[0].TotalItems,
796 FirstItem: txs[0].FirstItem,
797 LastItem: txs[0].LastItem,
798 }, nil
799}
800
801// GetAllExits returns all exit from the DB
802func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
803 var exits []*common.ExitInfo
804 err := meddler.QueryAll(
805 hdb.db, &exits,
806 `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
807 exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
808 exit_tree.delayed_withdrawn FROM exit_tree;`,
809 )
810 return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
811}
812
813// GetExit returns a exit from the DB
814func (hdb *HistoryDB) GetExit(batchNum *uint, idx *common.Idx) (*HistoryExit, error) {
815 exit := &HistoryExit{}
816 err := meddler.QueryRow(
817 hdb.db, exit, `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
818 token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
819 FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
820 INNER JOIN token ON account.token_id = token.token_id
821 WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
822 )
823 return exit, err
824}
825
826// GetExits returns a list of exits from the DB and pagination info
827func (hdb *HistoryDB) GetExits(
828 ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
829 tokenID *common.TokenID, idx *common.Idx, batchNum *uint,
830 fromItem, limit *uint, order string,
831) ([]HistoryExit, *db.Pagination, error) {
832 if ethAddr != nil && bjj != nil {
833 return nil, nil, errors.New("ethAddr and bjj are incompatible")
834 }
835 var query string
836 var args []interface{}
837 queryStr := `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
838 token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
839 token.usd_update, COUNT(*) OVER() AS total_items, MIN(exit_tree.item_id) OVER() AS first_item, MAX(exit_tree.item_id) OVER() AS last_item
840 FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
841 INNER JOIN token ON account.token_id = token.token_id `
842 // Apply filters
843 nextIsAnd := false
844 // ethAddr filter
845 if ethAddr != nil {
846 queryStr += "WHERE account.eth_addr = ? "
847 nextIsAnd = true
848 args = append(args, ethAddr)
849 } else if bjj != nil { // bjj filter
850 queryStr += "WHERE account.bjj = ? "
851 nextIsAnd = true
852 args = append(args, bjj)
853 }
854 // tokenID filter
855 if tokenID != nil {
856 if nextIsAnd {
857 queryStr += "AND "
858 } else {
859 queryStr += "WHERE "
860 }
861 queryStr += "account.token_id = ? "
862 args = append(args, tokenID)
863 nextIsAnd = true
864 }
865 // idx filter
866 if idx != nil {
867 if nextIsAnd {
868 queryStr += "AND "
869 } else {
870 queryStr += "WHERE "
871 }
872 queryStr += "exit_tree.account_idx = ? "
873 args = append(args, idx)
874 nextIsAnd = true
875 }
876 // batchNum filter
877 if batchNum != nil {
878 if nextIsAnd {
879 queryStr += "AND "
880 } else {
881 queryStr += "WHERE "
882 }
883 queryStr += "exit_tree.batch_num = ? "
884 args = append(args, batchNum)
885 nextIsAnd = true
886 }
887 if fromItem != nil {
888 if nextIsAnd {
889 queryStr += "AND "
890 } else {
891 queryStr += "WHERE "
892 }
893 if order == OrderAsc {
894 queryStr += "exit_tree.item_id >= ? "
895 } else {
896 queryStr += "exit_tree.item_id <= ? "
897 }
898 args = append(args, fromItem)
899 // nextIsAnd = true
900 }
901 // pagination
902 queryStr += "ORDER BY exit_tree.item_id "
903 if order == OrderAsc {
904 queryStr += " ASC "
905 } else {
906 queryStr += " DESC "
907 }
908 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
909 query = hdb.db.Rebind(queryStr)
910 // log.Debug(query)
911 exits := []*HistoryExit{}
912 if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
913 return nil, nil, err
914 }
915 if len(exits) == 0 {
916 return nil, nil, sql.ErrNoRows
917 }
918 return db.SlicePtrsToSlice(exits).([]HistoryExit), &db.Pagination{
919 TotalItems: exits[0].TotalItems,
920 FirstItem: exits[0].FirstItem,
921 LastItem: exits[0].LastItem,
922 }, nil
923}
924
925// // GetTx returns a tx from the DB
926// func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
927// tx := new(common.Tx)
928// return tx, meddler.QueryRow(
929// hdb.db, tx,
930// "SELECT * FROM tx WHERE id = $1;",
931// txID,
932// )
933// }
934
935// GetAllL1UserTxs returns all L1UserTxs from the DB
936func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
937 var txs []*common.L1Tx
938 err := meddler.QueryAll(
939 hdb.db, &txs,
940 `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
941 tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
942 tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
943 FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
944 )
945 return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
946}
947
948// GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
949func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
950 var txs []*common.L1Tx
951 err := meddler.QueryAll(
952 hdb.db, &txs,
953 `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
954 tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
955 tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
956 FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
957 )
958 return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
959}
960
961// GetAllL2Txs returns all L2Txs from the DB
962func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
963 var txs []*common.L2Tx
964 err := meddler.QueryAll(
965 hdb.db, &txs,
966 `SELECT tx.id, tx.batch_num, tx.position,
967 tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
968 tx.type, tx.eth_block_num
969 FROM tx WHERE is_l1 = FALSE;`,
970 )
971 return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
972}
973
974// GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
975func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
976 var txs []*common.L1Tx
977 err := meddler.QueryAll(
978 hdb.db, &txs,
979 `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
980 tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
981 tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
982 FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
983 toForgeL1TxsNum,
984 )
985 return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
986}
987
988// TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
989
990// GetLastTxsPosition for a given to_forge_l1_txs_num
991func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
992 row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
993 var lastL1TxsPosition int
994 return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
995}
996
997// AddBlockSCData stores all the information of a block retrieved by the
998// Synchronizer. Blocks should be inserted in order, leaving no gaps because
999// the pagination system of the API/DB depends on this. Within blocks, all
1000// items should also be in the correct order (Accounts, Tokens, Txs, etc.)
1001func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
1002 txn, err := hdb.db.Begin()
1003 if err != nil {
1004 return err
1005 }
1006 defer func() {
1007 if err != nil {
1008 errRollback := txn.Rollback()
1009 if errRollback != nil {
1010 log.Errorw("Rollback", "err", errRollback)
1011 }
1012 }
1013 }()
1014
1015 // Add block
1016 err = hdb.addBlock(txn, &blockData.Block)
1017 if err != nil {
1018 return err
1019 }
1020
1021 // Add Coordinators
1022 if len(blockData.Coordinators) > 0 {
1023 err = hdb.addCoordinators(txn, blockData.Coordinators)
1024 if err != nil {
1025 return err
1026 }
1027 }
1028
1029 // Add Bids
1030 if len(blockData.Bids) > 0 {
1031 err = hdb.addBids(txn, blockData.Bids)
1032 if err != nil {
1033 return err
1034 }
1035 }
1036
1037 // Add Tokens
1038 if len(blockData.AddedTokens) > 0 {
1039 err = hdb.addTokens(txn, blockData.AddedTokens)
1040 if err != nil {
1041 return err
1042 }
1043 }
1044
1045 // Add l1 Txs
1046 if len(blockData.L1UserTxs) > 0 {
1047 err = hdb.addL1Txs(txn, blockData.L1UserTxs)
1048 if err != nil {
1049 return err
1050 }
1051 }
1052
1053 // Add Batches
1054 for i := range blockData.Batches {
1055 batch := &blockData.Batches[i]
1056 // Add Batch: this will trigger an update on the DB
1057 // that will set the batch num of forged L1 txs in this batch
1058 err = hdb.addBatch(txn, &batch.Batch)
1059 if err != nil {
1060 return err
1061 }
1062
1063 // Add unforged l1 Txs
1064 if batch.L1Batch {
1065 if len(batch.L1CoordinatorTxs) > 0 {
1066 err = hdb.addL1Txs(txn, batch.L1CoordinatorTxs)
1067 if err != nil {
1068 return err
1069 }
1070 }
1071 }
1072
1073 // Add l2 Txs
1074 if len(batch.L2Txs) > 0 {
1075 err = hdb.addL2Txs(txn, batch.L2Txs)
1076 if err != nil {
1077 return err
1078 }
1079 }
1080
1081 // Add accounts
1082 if len(batch.CreatedAccounts) > 0 {
1083 err = hdb.addAccounts(txn, batch.CreatedAccounts)
1084 if err != nil {
1085 return err
1086 }
1087 }
1088
1089 // Add exit tree
1090 if len(batch.ExitTree) > 0 {
1091 err = hdb.addExitTree(txn, batch.ExitTree)
1092 if err != nil {
1093 return err
1094 }
1095 }
1096
1097 // TODO: INSERT CONTRACTS VARS
1098 }
1099
1100 return txn.Commit()
1101}
1102
1103// GetCoordinator returns a coordinator by its bidderAddr
1104func (hdb *HistoryDB) GetCoordinator(bidderAddr ethCommon.Address) (*HistoryCoordinator, error) {
1105 coordinator := &HistoryCoordinator{}
1106 err := meddler.QueryRow(
1107 hdb.db, coordinator, `SELECT * FROM coordinator WHERE bidder_addr = $1;`, bidderAddr,
1108 )
1109 return coordinator, err
1110}
1111
1112// GetCoordinators returns a list of coordinators from the DB and pagination info
1113func (hdb *HistoryDB) GetCoordinators(fromItem, limit *uint, order string) ([]HistoryCoordinator, *db.Pagination, error) {
1114 var query string
1115 var args []interface{}
1116 queryStr := `SELECT coordinator.*,
1117 COUNT(*) OVER() AS total_items, MIN(coordinator.item_id) OVER() AS first_item, MAX(coordinator.item_id) OVER() AS last_item
1118 FROM coordinator `
1119 // Apply filters
1120 if fromItem != nil {
1121 queryStr += "WHERE "
1122 if order == OrderAsc {
1123 queryStr += "coordinator.item_id >= ? "
1124 } else {
1125 queryStr += "coordinator.item_id <= ? "
1126 }
1127 args = append(args, fromItem)
1128 }
1129 // pagination
1130 queryStr += "ORDER BY coordinator.item_id "
1131 if order == OrderAsc {
1132 queryStr += " ASC "
1133 } else {
1134 queryStr += " DESC "
1135 }
1136 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
1137 query = hdb.db.Rebind(queryStr)
1138
1139 coordinators := []*HistoryCoordinator{}
1140 if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
1141 return nil, nil, err
1142 }
1143 if len(coordinators) == 0 {
1144 return nil, nil, sql.ErrNoRows
1145 }
1146 return db.SlicePtrsToSlice(coordinators).([]HistoryCoordinator), &db.Pagination{
1147 TotalItems: coordinators[0].TotalItems,
1148 FirstItem: coordinators[0].FirstItem,
1149 LastItem: coordinators[0].LastItem,
1150 }, nil
1151}