diff --git a/blockbook.go b/blockbook.go index 57c5bbe4..5e39318b 100644 --- a/blockbook.go +++ b/blockbook.go @@ -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 = "" } diff --git a/db/rocksdb.go b/db/rocksdb.go index f8af9aab..ee7baf9d 100644 --- a/db/rocksdb.go +++ b/db/rocksdb.go @@ -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)) diff --git a/server/https.go b/server/https.go index 15236ab6..77914ad2 100644 --- a/server/https.go +++ b/server/https.go @@ -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