kaspad/dbaccess/blockindex.go
Ori Newman 7609c50641
[NOD-885] Use database.Key and database.Bucket instead of byte slices (#692)
* [NOD-885] Create database.Key type

* [NOD-885] Rename FullKey()->FullKeyBytes() and Key()->KeyBytes()

* [NOD-885] Make Key.String return a hex string

* [NOD-885] Rename key parts

* [NOD-885] Rename separator->bucketSeparator

* [NOD-885] Rename SuffixBytes->Suffix and PrefixBytes->Prefix

* [NOD-885] Change comments

* [NOD-885] Change key prefix to bucket

* [NOD-885] Don't use database.NewKey inside dbaccess

* [NOD-885] Fix nil bug in Bucket.Path()

* [NOD-885] Rename helpers.go -> keys.go

* [NOD-885] Unexport database.NewKey

* [NOD-885] Remove redundant code in Bucket.Path()
2020-04-08 12:12:21 +03:00

59 lines
1.4 KiB
Go

package dbaccess
import (
"encoding/hex"
"github.com/kaspanet/kaspad/database"
"github.com/pkg/errors"
)
var (
blockIndexBucket = database.MakeBucket([]byte("block-index"))
)
// StoreIndexBlock stores a block in block-index
// representation to the database.
func StoreIndexBlock(context Context, blockIndexKey []byte, block []byte) error {
accessor, err := context.accessor()
if err != nil {
return err
}
key := blockIndexBucket.Key(blockIndexKey)
return accessor.Put(key, block)
}
// BlockIndexCursor opens a cursor over all the blocks-index
// blocks that have been previously added to the database.
func BlockIndexCursor(context Context) (database.Cursor, error) {
accessor, err := context.accessor()
if err != nil {
return nil, err
}
return accessor.Cursor(blockIndexBucket)
}
// BlockIndexCursorFrom opens a cursor over blocks-index blocks
// starting from the block with the given blockHash and
// blockBlueScore. Returns ErrNotFound if blockIndexKey is missing
// from the database.
func BlockIndexCursorFrom(context Context, blockIndexKey []byte) (database.Cursor, error) {
cursor, err := BlockIndexCursor(context)
if err != nil {
return nil, err
}
key := blockIndexBucket.Key(blockIndexKey)
err = cursor.Seek(key)
if IsNotFoundError(err) {
cursor.Close()
return nil, errors.Wrapf(database.ErrNotFound,
"entry not found for %s", hex.EncodeToString(blockIndexKey))
}
if err != nil {
return nil, err
}
return cursor, nil
}