forked from Onyx-Protocol/Onyx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
txdb.go
59 lines (50 loc) · 1.26 KB
/
txdb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Package txdb provides storage for Chain Protocol blockchain
// data structures.
package txdb
import (
"context"
"strconv"
"chain/database/pg"
"chain/errors"
"chain/log"
)
// New creates a Store and Pool backed by the txdb with the provided
// db handle.
func New(db pg.DB) (*Store, *Pool) {
return NewStore(db), NewPool(db)
}
func ListenBlocks(ctx context.Context, dbURL string) (<-chan uint64, error) {
listener, err := pg.NewListener(ctx, dbURL, "newblock")
if err != nil {
return nil, err
}
c := make(chan uint64)
go func() {
defer func() {
listener.Close()
close(c)
}()
for {
select {
case <-ctx.Done():
return
case n := <-listener.Notify:
height, err := strconv.ParseUint(n.Extra, 10, 64)
if err != nil {
log.Error(ctx, errors.Wrap(err, "parsing db notification payload"))
return
}
c <- height
}
}
}()
return c, nil
}
// GetRawBlock queries the database for the block at the provided height.
// The block is returned as raw bytes.
func (s *Store) GetRawBlock(ctx context.Context, height uint64) ([]byte, error) {
const q = `SELECT data FROM blocks WHERE height = $1`
var block []byte
err := s.db.QueryRow(ctx, q, height).Scan(&block)
return block, errors.Wrap(err, "querying blocks from the db")
}