forked from fairbank-io/electrum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
113 lines (96 loc) · 1.65 KB
/
cache.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
package electrum
import (
"database/sql"
"encoding/json"
"sync"
_ "github.com/glebarez/go-sqlite"
)
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("sqlite", "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 *RichTx:
isDetailed = 1
case RichTx:
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) 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 *RichTx:
if isDetailed == 0 {
return false
}
}
err = json.Unmarshal(data, tx)
return err == nil
}