frontend: implement GetLatestBlock, GetBlock; refactoring

This commit is contained in:
George Tankersley
2018-12-11 02:31:23 -05:00
parent 80b063fe8e
commit f6def7cda8
4 changed files with 166 additions and 81 deletions

View File

@@ -40,10 +40,10 @@ func CreateTables(conn *sql.DB) error {
return err
}
func GetCurrentHeight(ctx context.Context, conn *sql.DB) (int, error) {
func GetCurrentHeight(ctx context.Context, db *sql.DB) (int, error) {
var height int
query := "SELECT current_height FROM state WHERE rowid = 1"
err := conn.QueryRowContext(ctx, query).Scan(&height)
err := db.QueryRowContext(ctx, query).Scan(&height)
return height, err
}
@@ -75,10 +75,10 @@ func SetCurrentHeight(conn *sql.DB, height int) error {
return nil
}
func GetBlock(ctx context.Context, conn *sql.DB, height int) (*rpc.CompactBlock, error) {
func GetBlock(ctx context.Context, db *sql.DB, height int) (*rpc.CompactBlock, error) {
var blockBytes []byte // avoid a copy with *RawBytes
query := "SELECT compact_encoding from blocks WHERE height = ?"
err := conn.QueryRow(query, height).Scan(&blockBytes)
err := db.QueryRowContext(ctx, query, height).Scan(&blockBytes)
if err != nil {
return nil, err
}
@@ -87,6 +87,18 @@ func GetBlock(ctx context.Context, conn *sql.DB, height int) (*rpc.CompactBlock,
return compactBlock, err
}
func GetBlockByHash(ctx context.Context, db *sql.DB, hash string) (*rpc.CompactBlock, error) {
var blockBytes []byte // avoid a copy with *RawBytes
query := "SELECT compact_encoding from blocks WHERE hash = ?"
err := db.QueryRowContext(ctx, query, hash).Scan(&blockBytes)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("getting block with hash %s", hash))
}
compactBlock := &rpc.CompactBlock{}
err = proto.Unmarshal(blockBytes, compactBlock)
return compactBlock, err
}
// [start, end]
func GetBlockRange(conn *sql.DB, start, end int) ([]*rpc.CompactBlock, error) {
// TODO sanity check range bounds
@@ -123,18 +135,6 @@ func GetBlockRange(conn *sql.DB, start, end int) ([]*rpc.CompactBlock, error) {
return compactBlocks, nil
}
func GetBlockByHash(conn *sql.DB, hash string) (*rpc.CompactBlock, error) {
var blockBytes []byte // avoid a copy with *RawBytes
query := "SELECT compact_encoding from blocks WHERE hash = ?"
err := conn.QueryRow(query, hash).Scan(&blockBytes)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("getting block with hash %s", hash))
}
compactBlock := &rpc.CompactBlock{}
err = proto.Unmarshal(blockBytes, compactBlock)
return compactBlock, err
}
func StoreBlock(conn *sql.DB, height int, hash string, sapling bool, version int, encoded []byte) error {
insertBlock := "INSERT INTO blocks (height, hash, has_sapling_tx, encoding_version, compact_encoding) values (?, ?, ?, ?, ?)"
_, err := conn.Exec(insertBlock, height, hash, sapling, version, encoded)