GetBestBlock height and hash from DB

This commit is contained in:
Martin Boehm 2018-01-24 18:02:46 +01:00
parent e72b437e23
commit 48057b2453
3 changed files with 20 additions and 5 deletions

View File

@ -26,7 +26,7 @@ type Blockchain interface {
}
type Index interface {
GetBestBlockHash() (string, error)
GetBestBlock() (uint32, string, error)
GetBlockHash(height uint32) (string, error)
GetTransactions(address string, lower uint32, higher uint32, fn func(txid string) error) error
ConnectBlock(block *bitcoin.Block) error
@ -192,7 +192,7 @@ func resyncIndex(chain Blockchain, index Index) error {
if err != nil {
return err
}
local, err := index.GetBestBlockHash()
_, local, err := index.GetBestBlock()
if err != nil {
local = ""
}

View File

@ -20,6 +20,7 @@ func RepairRocksDB(name string) error {
return gorocksdb.RepairDb(name, opts)
}
// RocksDB handle
type RocksDB struct {
db *gorocksdb.DB
wo *gorocksdb.WriteOptions
@ -292,10 +293,20 @@ func packOutpoint(txid string, vout uint32) ([]byte, error) {
// Block index
func (d *RocksDB) GetBestBlockHash() (string, error) {
return "", nil // TODO
// GetBestBlock returns the block hash of the block with highest height in the db
func (d *RocksDB) GetBestBlock() (uint32, string, error) {
it := d.db.NewIteratorCF(d.ro, d.cfh[cfHeight])
defer it.Close()
if it.SeekToLast(); it.Valid() {
bestHeight := unpackUint(it.Key().Data())
val, err := unpackBlockValue(it.Value().Data())
log.Printf("Bestblock: %d %s", bestHeight, val)
return bestHeight, val, err
}
return 0, "", nil
}
// GetBlockHash returns block hash at given height or empty string if not found
func (d *RocksDB) GetBlockHash(height uint32) (string, error) {
key := packUint(height)
val, err := d.db.GetCF(d.ro, d.cfh[cfHeight], key)
@ -339,6 +350,10 @@ func packUint(i uint32) []byte {
return buf
}
func unpackUint(buf []byte) uint32 {
return binary.BigEndian.Uint32(buf)
}
func packVaruint(i uint32) []byte {
buf := make([]byte, vlq.MaxLen32)
ofs := vlq.PutUint(buf, uint64(i))

View File

@ -84,7 +84,7 @@ func (s *HttpServer) info(w http.ResponseWriter, r *http.Request) {
}
func (s *HttpServer) bestBlockHash(w http.ResponseWriter, r *http.Request) {
hash, err := s.db.GetBestBlockHash()
_, hash, err := s.db.GetBestBlock()
if err != nil {
respondError(w, err, "bestBlockHash")
return