database.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. package storage
  17. // this is a clone of an earlier state of the ethereum ethdb/database
  18. // no need for queueing/caching
  19. import (
  20. "fmt"
  21. "github.com/syndtr/goleveldb/leveldb"
  22. "github.com/syndtr/goleveldb/leveldb/iterator"
  23. "github.com/syndtr/goleveldb/leveldb/opt"
  24. )
  25. const openFileLimit = 128
  26. type LDBDatabase struct {
  27. db *leveldb.DB
  28. }
  29. func NewLDBDatabase(file string) (*LDBDatabase, error) {
  30. // Open the db
  31. db, err := leveldb.OpenFile(file, &opt.Options{OpenFilesCacheCapacity: openFileLimit})
  32. if err != nil {
  33. return nil, err
  34. }
  35. database := &LDBDatabase{db: db}
  36. return database, nil
  37. }
  38. func (self *LDBDatabase) Put(key []byte, value []byte) {
  39. err := self.db.Put(key, value, nil)
  40. if err != nil {
  41. fmt.Println("Error put", err)
  42. }
  43. }
  44. func (self *LDBDatabase) Get(key []byte) ([]byte, error) {
  45. dat, err := self.db.Get(key, nil)
  46. if err != nil {
  47. return nil, err
  48. }
  49. return dat, nil
  50. }
  51. func (self *LDBDatabase) Delete(key []byte) error {
  52. return self.db.Delete(key, nil)
  53. }
  54. func (self *LDBDatabase) LastKnownTD() []byte {
  55. data, _ := self.Get([]byte("LTD"))
  56. if len(data) == 0 {
  57. data = []byte{0x0}
  58. }
  59. return data
  60. }
  61. func (self *LDBDatabase) NewIterator() iterator.Iterator {
  62. return self.db.NewIterator(nil, nil)
  63. }
  64. func (self *LDBDatabase) Write(batch *leveldb.Batch) error {
  65. return self.db.Write(batch, nil)
  66. }
  67. func (self *LDBDatabase) Close() {
  68. // Close the leveldb database
  69. self.db.Close()
  70. }