This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 283
/
db.go
330 lines (287 loc) · 8 KB
/
db.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package db
import (
"database/sql"
"fmt"
"path"
"sync"
"time"
"github.com/OpenBazaar/openbazaar-go/repo"
"github.com/OpenBazaar/openbazaar-go/schema"
"github.com/OpenBazaar/wallet-interface"
_ "github.com/mutecomm/go-sqlcipher"
"github.com/op/go-logging"
)
var log = logging.MustGetLogger("db")
type SQLiteDatastore struct {
config repo.Config
followers repo.FollowerStore
following repo.FollowingStore
offlineMessages repo.OfflineMessageStore
pointers repo.PointerStore
keys repo.KeyStore
stxos repo.SpentTransactionOutputStore
txns repo.TransactionStore
utxos repo.UnspentTransactionOutputStore
watchedScripts repo.WatchedScriptStore
settings repo.ConfigurationStore
inventory repo.InventoryStore
purchases repo.PurchaseStore
sales repo.SaleStore
cases repo.CaseStore
chat repo.ChatStore
notifications repo.NotificationStore
coupons repo.CouponStore
txMetadata repo.TransactionMetadataStore
moderatedStores repo.ModeratedStore
messages repo.MessageStore
db *sql.DB
lock *sync.Mutex
}
func Create(repoPath, password string, testnet bool, coinType wallet.CoinType) (*SQLiteDatastore, error) {
var dbPath string
if testnet {
dbPath = path.Join(repoPath, "datastore", "testnet.db")
} else {
dbPath = path.Join(repoPath, "datastore", "mainnet.db")
}
conn, err := sql.Open("sqlite3", dbPath)
if err != nil {
return nil, err
}
if password != "" {
p := "pragma key='" + password + "';"
_, err := conn.Exec(p)
if err != nil {
log.Error(err)
}
}
l := new(sync.Mutex)
return NewSQLiteDatastore(conn, l, coinType), nil
}
func NewSQLiteDatastore(db *sql.DB, l *sync.Mutex, coinType wallet.CoinType) *SQLiteDatastore {
return &SQLiteDatastore{
config: &ConfigDB{modelStore{db: db, lock: l}},
followers: NewFollowerStore(db, l),
following: NewFollowingStore(db, l),
offlineMessages: NewOfflineMessageStore(db, l),
pointers: NewPointerStore(db, l),
keys: NewKeyStore(db, l, coinType),
stxos: NewSpentTransactionStore(db, l, coinType),
txns: NewTransactionStore(db, l, coinType),
utxos: NewUnspentTransactionStore(db, l, coinType),
settings: NewConfigurationStore(db, l),
inventory: NewInventoryStore(db, l),
purchases: NewPurchaseStore(db, l),
sales: NewSaleStore(db, l),
watchedScripts: NewWatchedScriptStore(db, l, coinType),
cases: NewCaseStore(db, l),
chat: NewChatStore(db, l),
notifications: NewNotificationStore(db, l),
coupons: NewCouponStore(db, l),
txMetadata: NewTransactionMetadataStore(db, l),
moderatedStores: NewModeratedStore(db, l),
messages: NewMessageStore(db, l),
db: db,
lock: l,
}
}
type DB struct {
SqlDB *sql.DB
Lock *sync.Mutex
}
func (d *SQLiteDatastore) DB() *DB {
return &DB{d.db, d.lock}
}
func (d *SQLiteDatastore) Ping() error {
return d.db.Ping()
}
func (d *SQLiteDatastore) Close() {
d.db.Close()
}
func (d *SQLiteDatastore) Config() repo.Config {
return d.config
}
func (d *SQLiteDatastore) Followers() repo.FollowerStore {
return d.followers
}
func (d *SQLiteDatastore) Following() repo.FollowingStore {
return d.following
}
func (d *SQLiteDatastore) OfflineMessages() repo.OfflineMessageStore {
return d.offlineMessages
}
func (d *SQLiteDatastore) Pointers() repo.PointerStore {
return d.pointers
}
func (d *SQLiteDatastore) Keys() wallet.Keys {
return d.keys
}
func (d *SQLiteDatastore) Stxos() wallet.Stxos {
return d.stxos
}
func (d *SQLiteDatastore) Txns() wallet.Txns {
return d.txns
}
func (d *SQLiteDatastore) Utxos() wallet.Utxos {
return d.utxos
}
func (d *SQLiteDatastore) Settings() repo.ConfigurationStore {
return d.settings
}
func (d *SQLiteDatastore) Inventory() repo.InventoryStore {
return d.inventory
}
func (d *SQLiteDatastore) Purchases() repo.PurchaseStore {
return d.purchases
}
func (d *SQLiteDatastore) Sales() repo.SaleStore {
return d.sales
}
func (d *SQLiteDatastore) WatchedScripts() wallet.WatchedScripts {
return d.watchedScripts
}
func (d *SQLiteDatastore) Cases() repo.CaseStore {
return d.cases
}
func (d *SQLiteDatastore) Chat() repo.ChatStore {
return d.chat
}
func (d *SQLiteDatastore) Notifications() repo.NotificationStore {
return d.notifications
}
func (d *SQLiteDatastore) Coupons() repo.CouponStore {
return d.coupons
}
func (d *SQLiteDatastore) TxMetadata() repo.TransactionMetadataStore {
return d.txMetadata
}
func (d *SQLiteDatastore) ModeratedStores() repo.ModeratedStore {
return d.moderatedStores
}
// Messages - return the messages datastore
func (d *SQLiteDatastore) Messages() repo.MessageStore {
return d.messages
}
func (d *SQLiteDatastore) Copy(dbPath string, password string) error {
d.lock.Lock()
defer d.lock.Unlock()
var cp string
stmt := "select name from sqlite_master where type='table'"
rows, err := d.db.Query(stmt)
if err != nil {
log.Error(err)
return err
}
var tables []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return err
}
tables = append(tables, name)
}
if password == "" {
cp = `attach database '` + dbPath + `' as plaintext key '';`
for _, name := range tables {
cp = cp + "insert into plaintext." + name + " select * from main." + name + ";"
}
} else {
cp = `attach database '` + dbPath + `' as encrypted key '` + password + `';`
for _, name := range tables {
cp = cp + "insert into encrypted." + name + " select * from main." + name + ";"
}
}
_, err = d.db.Exec(cp)
if err != nil {
return err
}
return nil
}
func (s *SQLiteDatastore) InitTables(password string) error {
return initDatabaseTables(s.db, password)
}
func initDatabaseTables(db *sql.DB, password string) (err error) {
_, err = db.Exec(schema.InitializeDatabaseSQL(password))
return err
}
type ConfigDB struct {
modelStore
}
func (c *ConfigDB) Init(mnemonic string, identityKey []byte, password string, creationDate time.Time) error {
c.lock.Lock()
defer c.lock.Unlock()
if err := initDatabaseTables(c.db, password); err != nil {
return err
}
stmt, err := c.PrepareQuery("insert into config(key, value) values(?,?)")
if err != nil {
return err
}
defer stmt.Close()
_, err = stmt.Exec("mnemonic", mnemonic)
if err != nil {
return fmt.Errorf("set mnemonic: %s", err.Error())
}
_, err = stmt.Exec("identityKey", identityKey)
if err != nil {
return fmt.Errorf("set identity key: %s", err.Error())
}
_, err = stmt.Exec("creationDate", creationDate.Format(time.RFC3339))
if err != nil {
return fmt.Errorf("set creation date: %s", err.Error())
}
return nil
}
func (c *ConfigDB) GetMnemonic() (string, error) {
c.lock.Lock()
defer c.lock.Unlock()
stmt, err := c.PrepareQuery("select value from config where key=?")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
var mnemonic string
err = stmt.QueryRow("mnemonic").Scan(&mnemonic)
if err != nil {
log.Fatal(err)
}
return mnemonic, nil
}
func (c *ConfigDB) GetIdentityKey() ([]byte, error) {
c.lock.Lock()
defer c.lock.Unlock()
stmt, err := c.PrepareQuery("select value from config where key=?")
if err != nil {
return nil, err
}
defer stmt.Close()
var identityKey []byte
err = stmt.QueryRow("identityKey").Scan(&identityKey)
if err != nil {
return nil, err
}
return identityKey, nil
}
func (c *ConfigDB) GetCreationDate() (time.Time, error) {
c.lock.Lock()
defer c.lock.Unlock()
var t time.Time
stmt, err := c.PrepareQuery("select value from config where key=?")
if err != nil {
return t, err
}
defer stmt.Close()
var creationDate []byte
err = stmt.QueryRow("creationDate").Scan(&creationDate)
if err != nil {
return t, err
}
return time.Parse(time.RFC3339, string(creationDate))
}
func (c *ConfigDB) IsEncrypted() bool {
c.lock.Lock()
defer c.lock.Unlock()
pwdCheck := "select count(*) from sqlite_master;"
_, err := c.db.Exec(pwdCheck) // Fails if wrong password is entered
return err != nil
}