github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/swarm/storage/database.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package storage
    18  
    19  // this is a clone of an earlier state of the hubble vntdb/database
    20  // no need for queueing/caching
    21  
    22  import (
    23  	"fmt"
    24  
    25  	"github.com/syndtr/goleveldb/leveldb"
    26  	"github.com/syndtr/goleveldb/leveldb/iterator"
    27  	"github.com/syndtr/goleveldb/leveldb/opt"
    28  )
    29  
    30  const openFileLimit = 128
    31  
    32  type LDBDatabase struct {
    33  	db *leveldb.DB
    34  }
    35  
    36  func NewLDBDatabase(file string) (*LDBDatabase, error) {
    37  	// Open the db
    38  	db, err := leveldb.OpenFile(file, &opt.Options{OpenFilesCacheCapacity: openFileLimit})
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  
    43  	database := &LDBDatabase{db: db}
    44  
    45  	return database, nil
    46  }
    47  
    48  func (self *LDBDatabase) Put(key []byte, value []byte) {
    49  	err := self.db.Put(key, value, nil)
    50  	if err != nil {
    51  		fmt.Println("Error put", err)
    52  	}
    53  }
    54  
    55  func (self *LDBDatabase) Get(key []byte) ([]byte, error) {
    56  	dat, err := self.db.Get(key, nil)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  	return dat, nil
    61  }
    62  
    63  func (self *LDBDatabase) Delete(key []byte) error {
    64  	return self.db.Delete(key, nil)
    65  }
    66  
    67  func (self *LDBDatabase) LastKnownTD() []byte {
    68  	data, _ := self.Get([]byte("LTD"))
    69  
    70  	if len(data) == 0 {
    71  		data = []byte{0x0}
    72  	}
    73  
    74  	return data
    75  }
    76  
    77  func (self *LDBDatabase) NewIterator() iterator.Iterator {
    78  	return self.db.NewIterator(nil, nil)
    79  }
    80  
    81  func (self *LDBDatabase) Write(batch *leveldb.Batch) error {
    82  	return self.db.Write(batch, nil)
    83  }
    84  
    85  func (self *LDBDatabase) Close() {
    86  	// Close the leveldb database
    87  	self.db.Close()
    88  }