-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdatabase.go
107 lines (84 loc) · 2.09 KB
/
database.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package mscutil
import (
"os/user"
"bytes"
"path"
"fmt"
"github.com/syndtr/goleveldb/leveldb"
"encoding/binary"
"encoding/gob"
)
type LDBDatabase struct {
db *leveldb.DB
}
func (db *LDBDatabase) GetDb() *leveldb.DB{
return db.db
}
func NewLDBDatabase(name string) (*LDBDatabase, error) {
// This will eventually have to be something like a resource folder.
// it works on my system for now. Probably won't work on Windows
usr, _ := user.Current()
dbPath := path.Join(usr.HomeDir, ".mastercoin", name)
// Open the db
db, err := leveldb.OpenFile(dbPath, nil)
if err != nil {
return nil, err
}
database := &LDBDatabase{db: db}
return database, nil
}
func (db *LDBDatabase) Close() {
db.db.Close()
}
func (db *LDBDatabase) PutMap(key []byte, value interface{}){
b := new(bytes.Buffer)
e := gob.NewEncoder(b)
err := e.Encode(value)
if err != nil {
panic(err)
}
db.Put(key, b.Bytes())
}
func (db *LDBDatabase) PutAccount(addr string, sheet map[uint32]uint64){
db.PutMap([]byte(addr), sheet)
return
}
func (db *LDBDatabase) GetAccount(addr string) map[uint32]uint64 {
var account map[uint32]uint64
db.GetMap([]byte(addr), &account)
if len(account) == 0 {
account = map[uint32]uint64{1: uint64(0), 2: uint64(0)}
}
return account
}
func (db *LDBDatabase) GetMap(key []byte, value interface{}){
rawData, err := db.Get(key)
if err == nil && len(rawData) > 0{
b := bytes.NewBuffer(rawData)
e := gob.NewDecoder(b)
err := e.Decode(value)
if err != nil {
fmt.Println("Could not get/decode key", err.Error())
}
}
}
func (db *LDBDatabase) Put(key []byte, value []byte) {
err := db.db.Put(key, value, nil)
if err != nil {
fmt.Println("Error put", err)
}
}
func (db *LDBDatabase) Get(key []byte) ([]byte, error) {
return db.db.Get(key, nil)
}
func (db *LDBDatabase) CreateTxPack(key int64, pack []byte) {
buff := new(bytes.Buffer)
binary.Write(buff, binary.BigEndian, key)
db.Put(buff.Bytes(), pack)
}
func (db *LDBDatabase) GetTxPack(key int64) []byte {
buff := new(bytes.Buffer)
binary.Write(buff, binary.BigEndian, key)
data, _ := db.Get(buff.Bytes())
return data
}