arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/db/historydb/historydb.go
db/historydb/historydb.goRaw
 1package historydb
 2
 3import (
 4	"fmt"
 5
 6	"github.com/gobuffalo/packr/v2"
 7	"github.com/hermeznetwork/hermez-node/common"
 8	"github.com/hermeznetwork/hermez-node/db"
 9	"github.com/jmoiron/sqlx"
10	_ "github.com/lib/pq" // driver for postgres DB
11	migrate "github.com/rubenv/sql-migrate"
12	"github.com/russross/meddler"
13)
14
15// HistoryDB persist the historic of the rollup
16type HistoryDB struct {
17	db *sqlx.DB
18}
19
20// NewHistoryDB initialize the DB
21func NewHistoryDB(port int, host, user, password, dbname string) (*HistoryDB, error) {
22	// Connect to DB
23	psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
24	hdb, err := sqlx.Connect("postgres", psqlconn)
25	if err != nil {
26		return nil, err
27	}
28	// Init meddler
29	db.InitMeddler()
30	meddler.Default = meddler.PostgreSQL
31
32	// Run DB migrations
33	migrations := &migrate.PackrMigrationSource{
34		Box: packr.New("history-migrations", "./migrations"),
35	}
36	if _, err := migrate.Exec(hdb.DB, "postgres", migrations, migrate.Up); err != nil {
37		return nil, err
38	}
39
40	return &HistoryDB{hdb}, nil
41}
42
43// addBlocks insert blocks into the DB
44func (hdb *HistoryDB) addBlocks(blocks []common.Block) error {
45	return db.BulkInsert(
46		hdb.db,
47		"INSERT INTO block (eth_block_num, timestamp, hash) VALUES %s",
48		blocks[:],
49	)
50}
51
52// GetBlocks retrrieve blocks from the DB
53func (hdb *HistoryDB) GetBlocks(from, to uint64) ([]*common.Block, error) {
54	var blocks []*common.Block
55	err := meddler.QueryAll(
56		hdb.db, &blocks,
57		"SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2",
58		from, to,
59	)
60	return blocks, err
61}
62
63// reorg deletes all the information that was added into the DB after the lastValidBlock
64// WARNING: this is a draaft of the function, useful at the moment for tests
65func (hdb *HistoryDB) reorg(lastValidBlock uint64) error {
66	_, err := hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
67	return err
68}
69
70// addBids insert Bids into the DB
71func (hdb *HistoryDB) addBids(bids []common.Bid) error {
72	// TODO: check the coordinator info
73	return db.BulkInsert(
74		hdb.db,
75		"INSERT INTO bid (slot_num, forger_addr, bid_value, eth_block_num) VALUES %s",
76		bids[:],
77	)
78}
79
80// GetBidsByBlock return the bids done between the block from and to
81func (hdb *HistoryDB) GetBidsByBlock(from, to uint64) ([]*common.Bid, error) {
82	var bids []*common.Bid
83	err := meddler.QueryAll(
84		hdb.db, &bids,
85		"SELECT * FROM bid WHERE $1 <= eth_block_num AND eth_block_num < $2",
86		from, to,
87	)
88	return bids, err
89}
90
91// Close frees the resources used by HistoryDB
92func (hdb *HistoryDB) Close() error {
93	return hdb.db.Close()
94}