database.go 1.63 KB
Newer Older
obscuren's avatar
obscuren committed
1 2 3
package ethdb

import (
obscuren's avatar
obscuren committed
4
	"fmt"
obscuren's avatar
obscuren committed
5

obscuren's avatar
obscuren committed
6
	"github.com/ethereum/go-ethereum/compression/rle"
obscuren's avatar
obscuren committed
7
	"github.com/ethereum/go-ethereum/common"
obscuren's avatar
obscuren committed
8
	"github.com/syndtr/goleveldb/leveldb"
9
	"github.com/syndtr/goleveldb/leveldb/iterator"
obscuren's avatar
obscuren committed
10 11 12
)

type LDBDatabase struct {
13 14
	db   *leveldb.DB
	comp bool
obscuren's avatar
obscuren committed
15 16
}

17
func NewLDBDatabase(file string) (*LDBDatabase, error) {
obscuren's avatar
obscuren committed
18
	// Open the db
19
	db, err := leveldb.OpenFile(file, nil)
obscuren's avatar
obscuren committed
20 21 22
	if err != nil {
		return nil, err
	}
23
	database := &LDBDatabase{db: db, comp: true}
obscuren's avatar
obscuren committed
24 25 26
	return database, nil
}

27 28 29 30 31 32
func (self *LDBDatabase) Put(key []byte, value []byte) {
	if self.comp {
		value = rle.Compress(value)
	}

	err := self.db.Put(key, value, nil)
obscuren's avatar
obscuren committed
33 34 35 36 37
	if err != nil {
		fmt.Println("Error put", err)
	}
}

38 39 40 41 42 43 44 45 46
func (self *LDBDatabase) Get(key []byte) ([]byte, error) {
	dat, err := self.db.Get(key, nil)
	if err != nil {
		return nil, err
	}

	if self.comp {
		return rle.Decompress(dat)
	}
obscuren's avatar
obscuren committed
47

48
	return dat, nil
49 50
}

51 52
func (self *LDBDatabase) Delete(key []byte) error {
	return self.db.Delete(key, nil)
obscuren's avatar
obscuren committed
53 54
}

55 56
func (self *LDBDatabase) LastKnownTD() []byte {
	data, _ := self.Get([]byte("LTD"))
obscuren's avatar
obscuren committed
57 58 59 60 61 62 63 64

	if len(data) == 0 {
		data = []byte{0x0}
	}

	return data
}

65 66 67 68
func (self *LDBDatabase) NewIterator() iterator.Iterator {
	return self.db.NewIterator(nil, nil)
}

obscuren's avatar
obscuren committed
69 70 71 72
func (self *LDBDatabase) Write(batch *leveldb.Batch) error {
	return self.db.Write(batch, nil)
}

73
func (self *LDBDatabase) Close() {
obscuren's avatar
obscuren committed
74
	// Close the leveldb database
75
	self.db.Close()
obscuren's avatar
obscuren committed
76 77
}

78 79
func (self *LDBDatabase) Print() {
	iter := self.db.NewIterator(nil, nil)
obscuren's avatar
obscuren committed
80 81 82 83 84
	for iter.Next() {
		key := iter.Key()
		value := iter.Value()

		fmt.Printf("%x(%d): ", key, len(key))
obscuren's avatar
obscuren committed
85
		node := common.NewValueFromBytes(value)
obscuren's avatar
obscuren committed
86 87 88
		fmt.Printf("%v\n", node)
	}
}