kaspad/dbaccess/block.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

91 lines
2.1 KiB
Go

package dbaccess
import (
"github.com/kaspanet/kaspad/database"
"github.com/kaspanet/kaspad/util/daghash"
"github.com/pkg/errors"
)
const (
blockStoreName = "blocks"
)
var (
blockLocationsBucket = database.MakeBucket([]byte("block-locations"))
)
func blockLocationKey(hash *daghash.Hash) *database.Key {
return blockLocationsBucket.Key(hash[:])
}
// StoreBlock stores the given block in the database.
func StoreBlock(context *TxContext, hash *daghash.Hash, blockBytes []byte) error {
accessor, err := context.accessor()
if err != nil {
return err
}
// Make sure that the block does not already exist.
exists, err := HasBlock(context, hash)
if err != nil {
return err
}
if exists {
return errors.Errorf("block %s already exists", hash)
}
// Write the block's bytes to the block store
blockLocation, err := accessor.AppendToStore(blockStoreName, blockBytes)
if err != nil {
return err
}
// Write the block's hash to the blockLocations bucket
blockLocationsKey := blockLocationKey(hash)
err = accessor.Put(blockLocationsKey, blockLocation)
if err != nil {
return err
}
return nil
}
// HasBlock returns whether the block of the given hash has been
// previously inserted into the database.
func HasBlock(context Context, hash *daghash.Hash) (bool, error) {
accessor, err := context.accessor()
if err != nil {
return false, err
}
blockLocationsKey := blockLocationKey(hash)
return accessor.Has(blockLocationsKey)
}
// FetchBlock returns the block of the given hash. Returns
// ErrNotFound if the block had not been previously inserted
// into the database.
func FetchBlock(context Context, hash *daghash.Hash) ([]byte, error) {
accessor, err := context.accessor()
if err != nil {
return nil, err
}
blockLocationsKey := blockLocationKey(hash)
blockLocation, err := accessor.Get(blockLocationsKey)
if err != nil {
if database.IsNotFoundError(err) {
return nil, errors.Wrapf(err,
"block %s not found", hash)
}
return nil, err
}
bytes, err := accessor.RetrieveFromStore(blockStoreName, blockLocation)
if err != nil {
return nil, err
}
return bytes, nil
}