/
keycache.go
267 lines (242 loc) · 6.07 KB
/
keycache.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
package pseudohsm
import (
"bufio"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/bytom-gm/crypto/sm2/chainkd"
)
// Minimum amount of time between cache reloads. This limit applies if the platform does
// not support change notifications. It also applies if the keystore directory does not
// exist yet, the code will attempt to create a watcher at most this often.
const minReloadInterval = 2 * time.Second
type keysByFile []XPub
func (s keysByFile) Len() int { return len(s) }
func (s keysByFile) Less(i, j int) bool { return s[i].File < s[j].File }
func (s keysByFile) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// AmbiguousKeyError is returned when attempting to unlock
// an XPub for which more than one file exists.
type AmbiguousKeyError struct {
Pubkey string
Matches []XPub
}
func (err *AmbiguousKeyError) Error() string {
files := ""
for i, a := range err.Matches {
files += a.File
if i < len(err.Matches)-1 {
files += ", "
}
}
return fmt.Sprintf("multiple keys match keys (%s)", files)
}
// keyCache is a live index of all keys in the keystore.
type keyCache struct {
keydir string
watcher *watcher
mu sync.Mutex
all keysByFile
byPubs map[chainkd.XPub][]XPub
throttle *time.Timer
}
func newKeyCache(keydir string) *keyCache {
kc := &keyCache{
keydir: keydir,
byPubs: make(map[chainkd.XPub][]XPub),
}
kc.watcher = newWatcher(kc)
return kc
}
func (kc *keyCache) hasKey(xpub chainkd.XPub) bool {
kc.maybeReload()
kc.mu.Lock()
defer kc.mu.Unlock()
return len(kc.byPubs[xpub]) > 0
}
func (kc *keyCache) hasAlias(alias string) bool {
xpubs := kc.keys()
for _, xpub := range xpubs {
if xpub.Alias == alias {
return true
}
}
return false
}
func (kc *keyCache) add(newKey XPub) {
kc.mu.Lock()
defer kc.mu.Unlock()
i := sort.Search(len(kc.all), func(i int) bool { return kc.all[i].File >= newKey.File })
if i < len(kc.all) && kc.all[i] == newKey {
return
}
// newKey is not in the cache.
kc.all = append(kc.all, XPub{})
copy(kc.all[i+1:], kc.all[i:])
kc.all[i] = newKey
kc.byPubs[newKey.XPub] = append(kc.byPubs[newKey.XPub], newKey)
}
func (kc *keyCache) keys() []XPub {
kc.maybeReload()
kc.mu.Lock()
defer kc.mu.Unlock()
cpy := make([]XPub, len(kc.all))
copy(cpy, kc.all)
return cpy
}
func (kc *keyCache) maybeReload() {
kc.mu.Lock()
defer kc.mu.Unlock()
if kc.watcher.running {
return // A watcher is running and will keep the cache up-to-date.
}
if kc.throttle == nil {
kc.throttle = time.NewTimer(0)
} else {
select {
case <-kc.throttle.C:
default:
return // The cache was reloaded recently.
}
}
kc.watcher.start()
kc.reload()
kc.throttle.Reset(minReloadInterval)
}
// find returns the cached keys for alias if there is a unique match.
// The exact matching rules are explained by the documentation of Account.
// Callers must hold ac.mu.
func (kc *keyCache) find(xpub XPub) (XPub, error) {
// Limit search to xpub candidates if possible.
matches := kc.all
if (xpub.XPub != chainkd.XPub{}) {
matches = kc.byPubs[xpub.XPub]
}
if xpub.File != "" {
// If only the basename is specified, complete the path.
if !strings.ContainsRune(xpub.File, filepath.Separator) {
xpub.File = filepath.Join(kc.keydir, xpub.File)
}
for i := range matches {
if matches[i].File == xpub.File {
return matches[i], nil
}
}
if (xpub.XPub == chainkd.XPub{}) {
return XPub{}, ErrLoadKey
}
}
switch len(matches) {
case 1:
return matches[0], nil
case 0:
return XPub{}, ErrLoadKey
default:
err := &AmbiguousKeyError{Pubkey: hex.EncodeToString(xpub.XPub[:]), Matches: make([]XPub, len(matches))}
copy(err.Matches, matches)
return XPub{}, err
}
}
// reload caches addresses of existing key.
// Callers must hold ac.mu.
func (kc *keyCache) reload() {
keys, err := kc.scan()
if err != nil {
log.WithField("load keys error", err).Error("can't load keys")
}
kc.all = keys
sort.Sort(kc.all)
for k := range kc.byPubs {
delete(kc.byPubs, k)
}
for _, k := range keys {
kc.byPubs[k.XPub] = append(kc.byPubs[k.XPub], k)
}
log.WithField("cache has keys:", len(kc.all)).Debug("reloaded keys")
}
func (kc *keyCache) scan() ([]XPub, error) {
files, err := ioutil.ReadDir(kc.keydir)
if err != nil {
return nil, err
}
var (
buf = new(bufio.Reader)
keys []XPub
keyJSON struct {
Alias string `json:"alias"`
XPub chainkd.XPub `json:"xpub"`
}
)
for _, fi := range files {
path := filepath.Join(kc.keydir, fi.Name())
if skipKeyFile(fi) {
//log.Printf("ignoring file %v", path)
//fmt.Printf("ignoring file %v", path)
continue
}
fd, err := os.Open(path)
if err != nil {
//log.Printf(err)
fmt.Printf("err")
continue
}
buf.Reset(fd)
// Parse the address.
keyJSON.Alias = ""
err = json.NewDecoder(buf).Decode(&keyJSON)
switch {
case err != nil:
log.WithField("decode json err", err).Errorf("can't decode key %s: %v", path, err)
case (keyJSON.Alias == ""):
log.WithField("can't decode key, key path:", path).Warn("missing or void alias")
default:
keys = append(keys, XPub{XPub: keyJSON.XPub, Alias: keyJSON.Alias, File: path})
}
fd.Close()
}
return keys, err
}
func (kc *keyCache) delete(removed XPub) {
kc.mu.Lock()
defer kc.mu.Unlock()
kc.all = removeKey(kc.all, removed)
if ba := removeKey(kc.byPubs[removed.XPub], removed); len(ba) == 0 {
delete(kc.byPubs, removed.XPub)
} else {
kc.byPubs[removed.XPub] = ba
}
}
func removeKey(slice []XPub, elem XPub) []XPub {
for i := range slice {
if slice[i] == elem {
return append(slice[:i], slice[i+1:]...)
}
}
return slice
}
func skipKeyFile(fi os.FileInfo) bool {
// Skip editor backups and UNIX-style hidden files.
if strings.HasSuffix(fi.Name(), "~") || strings.HasPrefix(fi.Name(), ".") {
return true
}
// Skip misc special files, directories (yes, symlinks too).
if fi.IsDir() || fi.Mode()&os.ModeType != 0 {
return true
}
return false
}
func (kc *keyCache) close() {
kc.mu.Lock()
kc.watcher.close()
if kc.throttle != nil {
kc.throttle.Stop()
}
kc.mu.Unlock()
}