2018-03-17 11:53:21 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/syndtr/goleveldb/leveldb"
|
|
|
|
"github.com/syndtr/goleveldb/leveldb/opt"
|
|
|
|
"github.com/syndtr/goleveldb/leveldb/util"
|
|
|
|
)
|
|
|
|
|
2019-09-10 14:22:21 +00:00
|
|
|
// LevelDBOptions configuration for LevelDB.
|
|
|
|
type LevelDBOptions struct {
|
|
|
|
DataDirectoryPath string `yaml:"DataDirectoryPath"`
|
|
|
|
}
|
|
|
|
|
2019-02-13 18:01:10 +00:00
|
|
|
// LevelDBStore is the official storage implementation for storing and retrieving
|
2018-03-17 11:53:21 +00:00
|
|
|
// blockchain data.
|
|
|
|
type LevelDBStore struct {
|
|
|
|
db *leveldb.DB
|
|
|
|
path string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewLevelDBStore return a new LevelDBStore object that will
|
|
|
|
// initialize the database found at the given path.
|
2019-09-16 15:52:47 +00:00
|
|
|
func NewLevelDBStore(cfg LevelDBOptions) (*LevelDBStore, error) {
|
2019-09-10 14:22:21 +00:00
|
|
|
var opts *opt.Options = nil // should be exposed via LevelDBOptions if anything needed
|
|
|
|
|
|
|
|
db, err := leveldb.OpenFile(cfg.DataDirectoryPath, opts)
|
2018-03-17 11:53:21 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-02-19 11:48:48 +00:00
|
|
|
|
2018-03-17 11:53:21 +00:00
|
|
|
return &LevelDBStore{
|
2019-09-10 14:22:21 +00:00
|
|
|
path: cfg.DataDirectoryPath,
|
2018-03-17 11:53:21 +00:00
|
|
|
db: db,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put implements the Store interface.
|
|
|
|
func (s *LevelDBStore) Put(key, value []byte) error {
|
|
|
|
return s.db.Put(key, value, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get implements the Store interface.
|
|
|
|
func (s *LevelDBStore) Get(key []byte) ([]byte, error) {
|
2019-09-27 12:40:44 +00:00
|
|
|
value, err := s.db.Get(key, nil)
|
|
|
|
if err == leveldb.ErrNotFound {
|
|
|
|
err = ErrKeyNotFound
|
|
|
|
}
|
|
|
|
return value, err
|
2018-03-17 11:53:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// PutBatch implements the Store interface.
|
|
|
|
func (s *LevelDBStore) PutBatch(batch Batch) error {
|
|
|
|
lvldbBatch := batch.(*leveldb.Batch)
|
|
|
|
return s.db.Write(lvldbBatch, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Seek implements the Store interface.
|
|
|
|
func (s *LevelDBStore) Seek(key []byte, f func(k, v []byte)) {
|
|
|
|
iter := s.db.NewIterator(util.BytesPrefix(key), nil)
|
|
|
|
for iter.Next() {
|
|
|
|
f(iter.Key(), iter.Value())
|
|
|
|
}
|
|
|
|
iter.Release()
|
|
|
|
}
|
|
|
|
|
2018-03-21 16:11:04 +00:00
|
|
|
// Batch implements the Batch interface and returns a leveldb
|
|
|
|
// compatible Batch.
|
2018-03-17 11:53:21 +00:00
|
|
|
func (s *LevelDBStore) Batch() Batch {
|
|
|
|
return new(leveldb.Batch)
|
|
|
|
}
|
2019-09-16 15:52:47 +00:00
|
|
|
|
|
|
|
// Close implements the Store interface.
|
|
|
|
func (s *LevelDBStore) Close() error {
|
|
|
|
return s.db.Close()
|
|
|
|
}
|