forked from checksum0/go-electrum
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
124 lines (107 loc) · 1.87 KB
/
util.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
package electrum
import (
"database/sql"
"encoding/json"
"fmt"
"sync"
_ "github.com/mattn/go-sqlite3"
)
func mustMarshalJSON(v interface{}) string {
b, err := json.Marshal(v)
if err != nil {
return fmt.Sprintf("%+v", v)
}
return string(b[:])
}
type TxCache struct {
mu sync.Mutex
db *sql.DB
}
func NewTxCache(db *sql.DB) (*TxCache, error) {
if db == nil {
var err error
db, err = sql.Open("sqlite3", "tx_cache.db")
if err != nil {
return nil, err
}
}
_, err := db.Exec(`
CREATE TABLE IF NOT EXISTS tx_cache (
txid VARCHAR(64) PRIMARY KEY,
tx TEXT,
is_detailed INTEGER DEFAULT 0
)
`)
if err != nil {
return nil, err
}
return &TxCache{db: db}, nil
}
func (c *TxCache) Close() error {
if c.db != nil {
return c.db.Close()
}
return nil
}
func (c *TxCache) Store(txID string, tx any) error {
b, err := json.Marshal(tx)
if err != nil {
return err
}
isDetailed := 0
switch tx.(type) {
case *DetailedTransaction:
isDetailed = 1
case DetailedTransaction:
isDetailed = 1
}
c.mu.Lock()
defer c.mu.Unlock()
_, err = c.db.Exec(
`INSERT INTO tx_cache (txid, tx, is_detailed) VALUES (?, ?, ?)
ON CONFLICT(txid) WHERE is_detailed = 0 DO UPDATE SET
tx = ?,
is_detailed = ?`,
txID,
string(b[:]),
isDetailed,
string(b[:]),
isDetailed,
)
if err != nil {
return err
}
return nil
}
func (c *TxCache) Load(txID string, tx any) (ok bool) {
c.mu.Lock()
row, err := c.db.Query(
"SELECT tx, is_detailed FROM tx_cache WHERE txid = ?",
txID,
)
c.mu.Unlock()
if err != nil {
return false
}
defer row.Close()
if !row.Next() {
return false
}
var data []byte
var isDetailed int
err = row.Scan(&data, &isDetailed)
if err != nil {
return false
}
switch tx.(type) {
case *DetailedTransaction:
if isDetailed == 0 {
return false
}
}
err = json.Unmarshal(data, tx)
if err != nil {
return false
}
return true
}