database.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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/ethereum/go-ethereum/compression/rle"
  22. "github.com/syndtr/goleveldb/leveldb"
  23. "github.com/syndtr/goleveldb/leveldb/iterator"
  24. "github.com/syndtr/goleveldb/leveldb/opt"
  25. )
  26. const openFileLimit = 128
  27. type LDBDatabase struct {
  28. db *leveldb.DB
  29. comp bool
  30. }
  31. func NewLDBDatabase(file string) (*LDBDatabase, error) {
  32. // Open the db
  33. db, err := leveldb.OpenFile(file, &opt.Options{OpenFilesCacheCapacity: openFileLimit})
  34. if err != nil {
  35. return nil, err
  36. }
  37. database := &LDBDatabase{db: db, comp: false}
  38. return database, nil
  39. }
  40. func (self *LDBDatabase) Put(key []byte, value []byte) {
  41. if self.comp {
  42. value = rle.Compress(value)
  43. }
  44. err := self.db.Put(key, value, nil)
  45. if err != nil {
  46. fmt.Println("Error put", err)
  47. }
  48. }
  49. func (self *LDBDatabase) Get(key []byte) ([]byte, error) {
  50. dat, err := self.db.Get(key, nil)
  51. if err != nil {
  52. return nil, err
  53. }
  54. if self.comp {
  55. return rle.Decompress(dat)
  56. }
  57. return dat, nil
  58. }
  59. func (self *LDBDatabase) Delete(key []byte) error {
  60. return self.db.Delete(key, nil)
  61. }
  62. func (self *LDBDatabase) LastKnownTD() []byte {
  63. data, _ := self.Get([]byte("LTD"))
  64. if len(data) == 0 {
  65. data = []byte{0x0}
  66. }
  67. return data
  68. }
  69. func (self *LDBDatabase) NewIterator() iterator.Iterator {
  70. return self.db.NewIterator(nil, nil)
  71. }
  72. func (self *LDBDatabase) Write(batch *leveldb.Batch) error {
  73. return self.db.Write(batch, nil)
  74. }
  75. func (self *LDBDatabase) Close() {
  76. // Close the leveldb database
  77. self.db.Close()
  78. }