-
Notifications
You must be signed in to change notification settings - Fork 2
/
db.go
122 lines (113 loc) · 2.22 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
package hashcash
import (
"database/sql"
"os"
"os/user"
"path/filepath"
_ "github.com/mattn/go-sqlite3"
)
const (
sqlCreateTable = "CREATE TABLE IF NOT EXISTS spent (creation_date TEXT NOT NULL, hashcash TEXT NOT NULL);"
sqlAddHash = "INSERT INTO spent VALUES (DATETIME('now', 'localtime'), ?);"
sqlHashExists = "SELECT hashcash FROM spent WHERE hashcash = ?;"
)
// DB instance
type DB struct {
name string
}
// Add a new hashcash entry to the database
func (d *DB) Add(hash string) error {
db, err := sql.Open("sqlite3", d.name)
if err != nil {
return err
}
defer db.Close()
_, err = db.Exec(sqlAddHash, hash)
if err != nil {
return err
}
return nil
}
// Spent checks if a hashcash entry already exists in the database
func (d *DB) Spent(hash string) bool {
db, err := sql.Open("sqlite3", d.name)
if err != nil {
return false
}
defer db.Close()
rows, err := db.Query(sqlHashExists, hash)
if err != nil {
return false
}
defer rows.Close()
for rows.Next() {
var s string
err = rows.Scan(&s)
if err != nil {
return false
}
}
return false
}
// exists determines a path/file exists
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
// createDBFile creates a new sqlite3 database file
func createDBFile(path string) error {
_, err := os.Create(path)
if err != nil {
return err
}
db, err := sql.Open("sqlite3", path)
if err != nil {
return err
}
defer db.Close()
_, err = db.Exec(sqlCreateTable)
if err != nil {
return err
}
return nil
}
// NewSQLite3DB creates a new DB Storage instance.
func NewSQLite3DB() (Storage, error) {
u, err := user.Current()
if err != nil {
return nil, err
}
var (
dbName = "spent.db"
dirName = ".hashcash"
path = filepath.Join(u.HomeDir, dirName)
)
created, err := exists(path)
if err != nil {
return nil, err
}
if !created {
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
return nil, err
}
}
path = filepath.Join(path, dbName)
created, err = exists(path)
if err != nil {
return nil, err
}
if !created {
err := createDBFile(path)
if err != nil {
return nil, err
}
}
return &DB{name: path}, nil
}