arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
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 * FROM batch;",
 276	)
 277	return db.SlicePtrsToSlice(batches).([]common.Batch), err
 278}
 279
 280// GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
 281func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
 282	var batches []*common.Batch
 283	err := meddler.QueryAll(
 284		hdb.db, &batches,
 285		"SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;",
 286		from, to,
 287	)
 288	return db.SlicePtrsToSlice(batches).([]common.Batch), err
 289}
 290
 291// GetLastBatchNum returns the BatchNum of the latest forged batch
 292func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
 293	row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
 294	var batchNum common.BatchNum
 295	return batchNum, row.Scan(&batchNum)
 296}
 297
 298// GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
 299// batches.  If there's no batch in the DB (nil, nil) is returned.
 300func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
 301	row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
 302	lastL1TxsNum := new(int64)
 303	return lastL1TxsNum, row.Scan(&lastL1TxsNum)
 304}
 305
 306// Reorg deletes all the information that was added into the DB after the
 307// lastValidBlock.  If lastValidBlock is negative, all block information is
 308// deleted.
 309func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
 310	var err error
 311	if lastValidBlock < 0 {
 312		_, err = hdb.db.Exec("DELETE FROM block;")
 313	} else {
 314		_, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
 315	}
 316	return err
 317}
 318
 319// SyncPoD stores all the data that can be changed / added on a block in the PoD SC
 320func (hdb *HistoryDB) SyncPoD(
 321	blockNum uint64,
 322	bids []common.Bid,
 323	coordinators []common.Coordinator,
 324	vars *common.AuctionVars,
 325) error {
 326	return nil
 327}
 328
 329// AddBids insert Bids into the DB
 330func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
 331func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
 332	// TODO: check the coordinator info
 333	return db.BulkInsert(
 334		d,
 335		"INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
 336		bids[:],
 337	)
 338}
 339
 340// GetBids return the bids
 341func (hdb *HistoryDB) GetBids() ([]common.Bid, error) {
 342	var bids []*common.Bid
 343	err := meddler.QueryAll(
 344		hdb.db, &bids,
 345		"SELECT * FROM bid;",
 346	)
 347	return db.SlicePtrsToSlice(bids).([]common.Bid), err
 348}
 349
 350// AddCoordinators insert Coordinators into the DB
 351func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
 352	return hdb.addCoordinators(hdb.db, coordinators)
 353}
 354func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
 355	return db.BulkInsert(
 356		d,
 357		"INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
 358		coordinators[:],
 359	)
 360}
 361
 362// AddExitTree insert Exit tree into the DB
 363func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
 364	return hdb.addExitTree(hdb.db, exitTree)
 365}
 366func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
 367	return db.BulkInsert(
 368		d,
 369		"INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
 370			"instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
 371		exitTree[:],
 372	)
 373}
 374
 375// AddToken insert a token into the DB
 376func (hdb *HistoryDB) AddToken(token *common.Token) error {
 377	return meddler.Insert(hdb.db, "token", token)
 378}
 379
 380// AddTokens insert tokens into the DB
 381func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
 382func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
 383	return db.BulkInsert(
 384		d,
 385		`INSERT INTO token (
 386			token_id,
 387			eth_block_num,
 388			eth_addr,
 389			name,
 390			symbol,
 391			decimals
 392		) VALUES %s;`,
 393		tokens[:],
 394	)
 395}
 396
 397// UpdateTokenValue updates the USD value of a token
 398func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
 399	_, err := hdb.db.Exec(
 400		"UPDATE token SET usd = $1 WHERE symbol = $2;",
 401		value, tokenSymbol,
 402	)
 403	return err
 404}
 405
 406// GetToken returns a token from the DB given a TokenID
 407func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
 408	token := &TokenWithUSD{}
 409	err := meddler.QueryRow(
 410		hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
 411	)
 412	return token, err
 413}
 414
 415// GetAllTokens returns all tokens from the DB
 416func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
 417	var tokens []*TokenWithUSD
 418	err := meddler.QueryAll(
 419		hdb.db, &tokens,
 420		"SELECT * FROM token ORDER BY token_id;",
 421	)
 422	return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err
 423}
 424
 425// GetTokens returns a list of tokens from the DB
 426func (hdb *HistoryDB) GetTokens(ids []common.TokenID, symbols []string, name string, fromItem, limit *uint, order string) ([]TokenWithUSD, *db.Pagination, error) {
 427	var query string
 428	var args []interface{}
 429	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 `
 430	// Apply filters
 431	nextIsAnd := false
 432	if len(ids) > 0 {
 433		queryStr += "WHERE token_id IN (?) "
 434		nextIsAnd = true
 435		args = append(args, ids)
 436	}
 437	if len(symbols) > 0 {
 438		if nextIsAnd {
 439			queryStr += "AND "
 440		} else {
 441			queryStr += "WHERE "
 442		}
 443		queryStr += "symbol IN (?) "
 444		args = append(args, symbols)
 445		nextIsAnd = true
 446	}
 447	if name != "" {
 448		if nextIsAnd {
 449			queryStr += "AND "
 450		} else {
 451			queryStr += "WHERE "
 452		}
 453		queryStr += "name ~ ? "
 454		args = append(args, name)
 455		nextIsAnd = true
 456	}
 457	if fromItem != nil {
 458		if nextIsAnd {
 459			queryStr += "AND "
 460		} else {
 461			queryStr += "WHERE "
 462		}
 463		if order == OrderAsc {
 464			queryStr += "item_id >= ? "
 465		} else {
 466			queryStr += "item_id <= ? "
 467		}
 468		args = append(args, fromItem)
 469	}
 470	// pagination
 471	queryStr += "ORDER BY item_id "
 472	if order == OrderAsc {
 473		queryStr += "ASC "
 474	} else {
 475		queryStr += "DESC "
 476	}
 477	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 478	query, argsQ, err := sqlx.In(queryStr, args...)
 479	if err != nil {
 480		return nil, nil, err
 481	}
 482	query = hdb.db.Rebind(query)
 483	tokens := []*TokenWithUSD{}
 484	if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
 485		return nil, nil, err
 486	}
 487	if len(tokens) == 0 {
 488		return nil, nil, sql.ErrNoRows
 489	}
 490	return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), &db.Pagination{
 491		TotalItems: tokens[0].TotalItems,
 492		FirstItem:  tokens[0].FirstItem,
 493		LastItem:   tokens[0].LastItem,
 494	}, nil
 495}
 496
 497// GetTokenSymbols returns all the token symbols from the DB
 498func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
 499	var tokenSymbols []string
 500	rows, err := hdb.db.Query("SELECT symbol FROM token;")
 501	if err != nil {
 502		return nil, err
 503	}
 504	sym := new(string)
 505	for rows.Next() {
 506		err = rows.Scan(sym)
 507		if err != nil {
 508			return nil, err
 509		}
 510		tokenSymbols = append(tokenSymbols, *sym)
 511	}
 512	return tokenSymbols, nil
 513}
 514
 515// AddAccounts insert accounts into the DB
 516func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
 517	return hdb.addAccounts(hdb.db, accounts)
 518}
 519func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
 520	return db.BulkInsert(
 521		d,
 522		`INSERT INTO account (
 523			idx,
 524			token_id,
 525			batch_num,
 526			bjj,
 527			eth_addr
 528		) VALUES %s;`,
 529		accounts[:],
 530	)
 531}
 532
 533// GetAccounts returns a list of accounts from the DB
 534func (hdb *HistoryDB) GetAccounts() ([]common.Account, error) {
 535	var accs []*common.Account
 536	err := meddler.QueryAll(
 537		hdb.db, &accs,
 538		"SELECT * FROM account ORDER BY idx;",
 539	)
 540	return db.SlicePtrsToSlice(accs).([]common.Account), err
 541}
 542
 543// AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
 544// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
 545// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
 546func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
 547
 548// addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
 549// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
 550// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
 551func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
 552	txs := []txWrite{}
 553	for i := 0; i < len(l1txs); i++ {
 554		af := new(big.Float).SetInt(l1txs[i].Amount)
 555		amountFloat, _ := af.Float64()
 556		laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
 557		loadAmountFloat, _ := laf.Float64()
 558		txs = append(txs, txWrite{
 559			// Generic
 560			IsL1:        true,
 561			TxID:        l1txs[i].TxID,
 562			Type:        l1txs[i].Type,
 563			Position:    l1txs[i].Position,
 564			FromIdx:     &l1txs[i].FromIdx,
 565			ToIdx:       l1txs[i].ToIdx,
 566			Amount:      l1txs[i].Amount,
 567			AmountFloat: amountFloat,
 568			TokenID:     l1txs[i].TokenID,
 569			BatchNum:    l1txs[i].BatchNum,
 570			EthBlockNum: l1txs[i].EthBlockNum,
 571			// L1
 572			ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
 573			UserOrigin:      &l1txs[i].UserOrigin,
 574			FromEthAddr:     &l1txs[i].FromEthAddr,
 575			FromBJJ:         l1txs[i].FromBJJ,
 576			LoadAmount:      l1txs[i].LoadAmount,
 577			LoadAmountFloat: &loadAmountFloat,
 578		})
 579	}
 580	return hdb.addTxs(d, txs)
 581}
 582
 583// AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
 584func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
 585
 586// addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
 587func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
 588	txs := []txWrite{}
 589	for i := 0; i < len(l2txs); i++ {
 590		f := new(big.Float).SetInt(l2txs[i].Amount)
 591		amountFloat, _ := f.Float64()
 592		txs = append(txs, txWrite{
 593			// Generic
 594			IsL1:        false,
 595			TxID:        l2txs[i].TxID,
 596			Type:        l2txs[i].Type,
 597			Position:    l2txs[i].Position,
 598			FromIdx:     &l2txs[i].FromIdx,
 599			ToIdx:       l2txs[i].ToIdx,
 600			Amount:      l2txs[i].Amount,
 601			AmountFloat: amountFloat,
 602			BatchNum:    &l2txs[i].BatchNum,
 603			EthBlockNum: l2txs[i].EthBlockNum,
 604			// L2
 605			Fee:   &l2txs[i].Fee,
 606			Nonce: &l2txs[i].Nonce,
 607		})
 608	}
 609	return hdb.addTxs(d, txs)
 610}
 611
 612func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
 613	return db.BulkInsert(
 614		d,
 615		`INSERT INTO tx (
 616			is_l1,
 617			id,
 618			type,
 619			position,
 620			from_idx,
 621			to_idx,
 622			amount,
 623			amount_f,
 624			token_id,
 625			batch_num,
 626			eth_block_num,
 627			to_forge_l1_txs_num,
 628			user_origin,
 629			from_eth_addr,
 630			from_bjj,
 631			load_amount,
 632			load_amount_f,
 633			fee,
 634			nonce
 635		) VALUES %s;`,
 636		txs[:],
 637	)
 638}
 639
 640// // GetTxs returns a list of txs from the DB
 641// func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
 642// 	var txs []*common.Tx
 643// 	err := meddler.QueryAll(
 644// 		hdb.db, &txs,
 645// 		`SELECT * FROM tx
 646// 		ORDER BY (batch_num, position) ASC`,
 647// 	)
 648// 	return db.SlicePtrsToSlice(txs).([]common.Tx), err
 649// }
 650
 651// GetHistoryTx returns a tx from the DB given a TxID
 652func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*HistoryTx, error) {
 653	tx := &HistoryTx{}
 654	err := meddler.QueryRow(
 655		hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position, 
 656		tx.from_idx, tx.to_idx, tx.amount, tx.token_id, tx.amount_usd, 
 657		tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin, 
 658		tx.from_eth_addr, tx.from_bjj, tx.load_amount, 
 659		tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
 660		token.token_id, token.eth_block_num AS token_block,
 661		token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
 662		token.usd_update, block.timestamp
 663		FROM tx INNER JOIN token ON tx.token_id = token.token_id 
 664		INNER JOIN block ON tx.eth_block_num = block.eth_block_num 
 665		WHERE tx.id = $1;`, txID,
 666	)
 667	return tx, err
 668}
 669
 670// GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
 671// and pagination info
 672func (hdb *HistoryDB) GetHistoryTxs(
 673	ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
 674	tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
 675	fromItem, limit *uint, order string,
 676) ([]HistoryTx, *db.Pagination, error) {
 677	if ethAddr != nil && bjj != nil {
 678		return nil, nil, errors.New("ethAddr and bjj are incompatible")
 679	}
 680	var query string
 681	var args []interface{}
 682	queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position, 
 683	tx.from_idx, tx.to_idx, tx.amount, tx.token_id, tx.amount_usd, 
 684	tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin, 
 685	tx.from_eth_addr, tx.from_bjj, tx.load_amount, 
 686	tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
 687	token.token_id, token.eth_block_num AS token_block,
 688	token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
 689	token.usd_update, block.timestamp, count(*) OVER() AS total_items, 
 690	MIN(tx.item_id)  OVER() AS first_item, MAX(tx.item_id) OVER() AS last_item 
 691	FROM tx INNER JOIN token ON tx.token_id = token.token_id 
 692	INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
 693	// Apply filters
 694	nextIsAnd := false
 695	// ethAddr filter
 696	if ethAddr != nil {
 697		queryStr = `WITH acc AS 
 698		(select idx from account where eth_addr = ?) ` + queryStr
 699		queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
 700		nextIsAnd = true
 701		args = append(args, ethAddr)
 702	} else if bjj != nil { // bjj filter
 703		queryStr = `WITH acc AS 
 704		(select idx from account where bjj = ?) ` + queryStr
 705		queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
 706		nextIsAnd = true
 707		args = append(args, bjj)
 708	}
 709	// tokenID filter
 710	if tokenID != nil {
 711		if nextIsAnd {
 712			queryStr += "AND "
 713		} else {
 714			queryStr += "WHERE "
 715		}
 716		queryStr += "tx.token_id = ? "
 717		args = append(args, tokenID)
 718		nextIsAnd = true
 719	}
 720	// idx filter
 721	if idx != nil {
 722		if nextIsAnd {
 723			queryStr += "AND "
 724		} else {
 725			queryStr += "WHERE "
 726		}
 727		queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
 728		args = append(args, idx, idx)
 729		nextIsAnd = true
 730	}
 731	// batchNum filter
 732	if batchNum != nil {
 733		if nextIsAnd {
 734			queryStr += "AND "
 735		} else {
 736			queryStr += "WHERE "
 737		}
 738		queryStr += "tx.batch_num = ? "
 739		args = append(args, batchNum)
 740		nextIsAnd = true
 741	}
 742	// txType filter
 743	if txType != nil {
 744		if nextIsAnd {
 745			queryStr += "AND "
 746		} else {
 747			queryStr += "WHERE "
 748		}
 749		queryStr += "tx.type = ? "
 750		args = append(args, txType)
 751		nextIsAnd = true
 752	}
 753	if fromItem != nil {
 754		if nextIsAnd {
 755			queryStr += "AND "
 756		} else {
 757			queryStr += "WHERE "
 758		}
 759		if order == OrderAsc {
 760			queryStr += "tx.item_id >= ? "
 761		} else {
 762			queryStr += "tx.item_id <= ? "
 763		}
 764		args = append(args, fromItem)
 765		nextIsAnd = true
 766	}
 767	if nextIsAnd {
 768		queryStr += "AND "
 769	} else {
 770		queryStr += "WHERE "
 771	}
 772	queryStr += "tx.batch_num IS NOT NULL "
 773
 774	// pagination
 775	queryStr += "ORDER BY tx.item_id "
 776	if order == OrderAsc {
 777		queryStr += " ASC "
 778	} else {
 779		queryStr += " DESC "
 780	}
 781	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 782	query = hdb.db.Rebind(queryStr)
 783	log.Debug(query)
 784	txsPtrs := []*HistoryTx{}
 785	if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
 786		return nil, nil, err
 787	}
 788	txs := db.SlicePtrsToSlice(txsPtrs).([]HistoryTx)
 789	if len(txs) == 0 {
 790		return nil, nil, sql.ErrNoRows
 791	}
 792	return txs, &db.Pagination{
 793		TotalItems: txs[0].TotalItems,
 794		FirstItem:  txs[0].FirstItem,
 795		LastItem:   txs[0].LastItem,
 796	}, nil
 797}
 798
 799// GetExit returns a exit from the DB
 800func (hdb *HistoryDB) GetExit(batchNum *uint, idx *common.Idx) (*HistoryExit, error) {
 801	exit := &HistoryExit{}
 802	err := meddler.QueryRow(
 803		hdb.db, exit, `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
 804		token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
 805		FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx 
 806		INNER JOIN token ON account.token_id = token.token_id 
 807		WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
 808	)
 809	return exit, err
 810}
 811
 812// GetExits returns a list of exits from the DB and pagination info
 813func (hdb *HistoryDB) GetExits(
 814	ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
 815	tokenID *common.TokenID, idx *common.Idx, batchNum *uint,
 816	fromItem, limit *uint, order string,
 817) ([]HistoryExit, *db.Pagination, error) {
 818	if ethAddr != nil && bjj != nil {
 819		return nil, nil, errors.New("ethAddr and bjj are incompatible")
 820	}
 821	var query string
 822	var args []interface{}
 823	queryStr := `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
 824	token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
 825	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
 826	FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx 
 827	INNER JOIN token ON account.token_id = token.token_id `
 828	// Apply filters
 829	nextIsAnd := false
 830	// ethAddr filter
 831	if ethAddr != nil {
 832		queryStr += "WHERE account.eth_addr = ? "
 833		nextIsAnd = true
 834		args = append(args, ethAddr)
 835	} else if bjj != nil { // bjj filter
 836		queryStr += "WHERE account.bjj = ? "
 837		nextIsAnd = true
 838		args = append(args, bjj)
 839	}
 840	// tokenID filter
 841	if tokenID != nil {
 842		if nextIsAnd {
 843			queryStr += "AND "
 844		} else {
 845			queryStr += "WHERE "
 846		}
 847		queryStr += "account.token_id = ? "
 848		args = append(args, tokenID)
 849		nextIsAnd = true
 850	}
 851	// idx filter
 852	if idx != nil {
 853		if nextIsAnd {
 854			queryStr += "AND "
 855		} else {
 856			queryStr += "WHERE "
 857		}
 858		queryStr += "exit_tree.account_idx = ? "
 859		args = append(args, idx)
 860		nextIsAnd = true
 861	}
 862	// batchNum filter
 863	if batchNum != nil {
 864		if nextIsAnd {
 865			queryStr += "AND "
 866		} else {
 867			queryStr += "WHERE "
 868		}
 869		queryStr += "exit_tree.batch_num = ? "
 870		args = append(args, batchNum)
 871		nextIsAnd = true
 872	}
 873	if fromItem != nil {
 874		if nextIsAnd {
 875			queryStr += "AND "
 876		} else {
 877			queryStr += "WHERE "
 878		}
 879		if order == OrderAsc {
 880			queryStr += "exit_tree.item_id >= ? "
 881		} else {
 882			queryStr += "exit_tree.item_id <= ? "
 883		}
 884		args = append(args, fromItem)
 885		// nextIsAnd = true
 886	}
 887	// pagination
 888	queryStr += "ORDER BY exit_tree.item_id "
 889	if order == OrderAsc {
 890		queryStr += " ASC "
 891	} else {
 892		queryStr += " DESC "
 893	}
 894	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 895	query = hdb.db.Rebind(queryStr)
 896	// log.Debug(query)
 897	exits := []*HistoryExit{}
 898	if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
 899		return nil, nil, err
 900	}
 901	if len(exits) == 0 {
 902		return nil, nil, sql.ErrNoRows
 903	}
 904	return db.SlicePtrsToSlice(exits).([]HistoryExit), &db.Pagination{
 905		TotalItems: exits[0].TotalItems,
 906		FirstItem:  exits[0].FirstItem,
 907		LastItem:   exits[0].LastItem,
 908	}, nil
 909}
 910
 911// // GetTx returns a tx from the DB
 912// func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
 913// 	tx := new(common.Tx)
 914// 	return tx, meddler.QueryRow(
 915// 		hdb.db, tx,
 916// 		"SELECT * FROM tx WHERE id = $1;",
 917// 		txID,
 918// 	)
 919// }
 920
 921// GetAllL1UserTxs returns all L1UserTxs from the DB
 922func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
 923	var txs []*common.L1Tx
 924	err := meddler.QueryAll(
 925		hdb.db, &txs,
 926		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
 927		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
 928		tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
 929		FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
 930	)
 931	return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
 932}
 933
 934// GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
 935func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
 936	var txs []*common.L1Tx
 937	err := meddler.QueryAll(
 938		hdb.db, &txs,
 939		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
 940		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
 941		tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
 942		FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
 943		toForgeL1TxsNum,
 944	)
 945	return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
 946}
 947
 948// TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
 949
 950// GetLastTxsPosition for a given to_forge_l1_txs_num
 951func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
 952	row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
 953	var lastL1TxsPosition int
 954	return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
 955}
 956
 957// AddBlockSCData stores all the information of a block retrieved by the
 958// Synchronizer.  Blocks should be inserted in order, leaving no gaps because
 959// the pagination system of the API/DB depends on this.  Within blocks, all
 960// items should also be in the correct order (Accounts, Tokens, Txs, etc.)
 961func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
 962	txn, err := hdb.db.Begin()
 963	if err != nil {
 964		return err
 965	}
 966	defer func() {
 967		if err != nil {
 968			errRollback := txn.Rollback()
 969			if errRollback != nil {
 970				log.Errorw("Rollback", "err", errRollback)
 971			}
 972		}
 973	}()
 974
 975	// Add block
 976	err = hdb.addBlock(txn, &blockData.Block)
 977	if err != nil {
 978		return err
 979	}
 980
 981	// Add Coordinators
 982	if len(blockData.Coordinators) > 0 {
 983		err = hdb.addCoordinators(txn, blockData.Coordinators)
 984		if err != nil {
 985			return err
 986		}
 987	}
 988
 989	// Add Bids
 990	if len(blockData.Bids) > 0 {
 991		err = hdb.addBids(txn, blockData.Bids)
 992		if err != nil {
 993			return err
 994		}
 995	}
 996
 997	// Add Tokens
 998	if len(blockData.AddedTokens) > 0 {
 999		err = hdb.addTokens(txn, blockData.AddedTokens)
1000		if err != nil {
1001			return err
1002		}
1003	}
1004
1005	// Add l1 Txs
1006	if len(blockData.L1UserTxs) > 0 {
1007		err = hdb.addL1Txs(txn, blockData.L1UserTxs)
1008		if err != nil {
1009			return err
1010		}
1011	}
1012
1013	// Add Batches
1014	for i := range blockData.Batches {
1015		batch := &blockData.Batches[i]
1016		// Add Batch: this will trigger an update on the DB
1017		// that will set the batch num of forged L1 txs in this batch
1018		err = hdb.addBatch(txn, &batch.Batch)
1019		if err != nil {
1020			return err
1021		}
1022
1023		// Add unforged l1 Txs
1024		if batch.L1Batch {
1025			if len(batch.L1CoordinatorTxs) > 0 {
1026				err = hdb.addL1Txs(txn, batch.L1CoordinatorTxs)
1027				if err != nil {
1028					return err
1029				}
1030			}
1031		}
1032
1033		// Add l2 Txs
1034		if len(batch.L2Txs) > 0 {
1035			err = hdb.addL2Txs(txn, batch.L2Txs)
1036			if err != nil {
1037				return err
1038			}
1039		}
1040
1041		// Add accounts
1042		if len(batch.CreatedAccounts) > 0 {
1043			err = hdb.addAccounts(txn, batch.CreatedAccounts)
1044			if err != nil {
1045				return err
1046			}
1047		}
1048
1049		// Add exit tree
1050		if len(batch.ExitTree) > 0 {
1051			err = hdb.addExitTree(txn, batch.ExitTree)
1052			if err != nil {
1053				return err
1054			}
1055		}
1056
1057		// TODO: INSERT CONTRACTS VARS
1058	}
1059
1060	return txn.Commit()
1061}
1062
1063// GetCoordinator returns a coordinator by its bidderAddr
1064func (hdb *HistoryDB) GetCoordinator(bidderAddr ethCommon.Address) (*HistoryCoordinator, error) {
1065	coordinator := &HistoryCoordinator{}
1066	err := meddler.QueryRow(
1067		hdb.db, coordinator, `SELECT * FROM coordinator WHERE bidder_addr = $1;`, bidderAddr,
1068	)
1069	return coordinator, err
1070}
1071
1072// GetCoordinators returns a list of coordinators from the DB and pagination info
1073func (hdb *HistoryDB) GetCoordinators(fromItem, limit *uint, order string) ([]HistoryCoordinator, *db.Pagination, error) {
1074	var query string
1075	var args []interface{}
1076	queryStr := `SELECT coordinator.*, 
1077	COUNT(*) OVER() AS total_items, MIN(coordinator.item_id) OVER() AS first_item, MAX(coordinator.item_id) OVER() AS last_item
1078	FROM coordinator `
1079	// Apply filters
1080	if fromItem != nil {
1081		queryStr += "WHERE "
1082		if order == OrderAsc {
1083			queryStr += "coordinator.item_id >= ? "
1084		} else {
1085			queryStr += "coordinator.item_id <= ? "
1086		}
1087		args = append(args, fromItem)
1088	}
1089	// pagination
1090	queryStr += "ORDER BY coordinator.item_id "
1091	if order == OrderAsc {
1092		queryStr += " ASC "
1093	} else {
1094		queryStr += " DESC "
1095	}
1096	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
1097	query = hdb.db.Rebind(queryStr)
1098
1099	coordinators := []*HistoryCoordinator{}
1100	if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
1101		return nil, nil, err
1102	}
1103	if len(coordinators) == 0 {
1104		return nil, nil, sql.ErrNoRows
1105	}
1106	return db.SlicePtrsToSlice(coordinators).([]HistoryCoordinator), &db.Pagination{
1107		TotalItems: coordinators[0].TotalItems,
1108		FirstItem:  coordinators[0].FirstItem,
1109		LastItem:   coordinators[0].LastItem,
1110	}, nil
1111}