-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
469 lines (429 loc) · 11.7 KB
/
Copy pathclient.go
File metadata and controls
469 lines (429 loc) · 11.7 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
type Status struct {
PeerID string `json:"peer_id"`
Peers int `json:"peers"`
ChainHeight int `json:"chain_height"`
BestHash string `json:"best_hash"`
TotalWork int64 `json:"total_work"`
MempoolSize int `json:"mempool_size"`
MempoolBytes int `json:"mempool_bytes"`
Syncing bool `json:"syncing"`
SyncProgress int `json:"sync_progress"`
SyncTarget int `json:"sync_target"`
SyncPercent string `json:"sync_percent"`
IdentityAge string `json:"identity_age"`
}
type Mempool struct {
Count int `json:"count"`
SizeBytes int `json:"size_bytes"`
MinFee int64 `json:"min_fee"`
MaxFee int64 `json:"max_fee"`
AvgFee float64 `json:"avg_fee"`
}
type PeersResp struct {
Count int `json:"count"`
Peers []struct {
PeerID string `json:"peer_id"`
Addrs []string `json:"addrs"`
} `json:"peers"`
}
type Mining struct {
Running bool `json:"running"`
Threads int `json:"threads"`
Hashrate float64 `json:"hashrate"`
HashCount int64 `json:"hash_count"`
BlocksFound int `json:"blocks_found"`
StartedAt string `json:"started_at"`
}
type Block struct {
Height int `json:"height"`
Hash string `json:"hash"`
TxCount int `json:"tx_count"`
Timestamp int64 `json:"timestamp"`
Reward int64 `json:"reward"`
}
// A source is a place a Blocknet node may be reachable: a data directory that
// holds the api.cookie, plus the localhost ports its API might bind. The CLI
// daemon uses a fixed port; the Tauri GUI wallet keeps its cookie under the
// platform app-data dir and binds a random port in a known range, so finding it
// takes a short scan.
type source struct {
label string
dataDir string
ports []int
}
func (s source) cookiePath() string { return filepath.Join(s.dataDir, "api.cookie") }
// resolved is a source we've actually reached: a concrete base URL plus the
// cookie and data dir that go with it.
type resolved struct {
label string
base string
cookie string
dataDir string
}
type Client struct {
sources []source
mu sync.Mutex
active *resolved
hc *http.Client // status/block polling
hcRaw *http.Client // user-initiated block inspection (longer timeout)
hcProbe *http.Client // endpoint discovery (short; many ports)
}
var errNoNode = errors.New("no node")
// guiAppDataDir mirrors Tauri's app_data_dir for identifier "com.blocknet.wallet"
// on each platform, so we can locate the GUI wallet's cookie and chain data.
func guiAppDataDir() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
const id = "com.blocknet.wallet"
switch runtime.GOOS {
case "darwin":
return filepath.Join(home, "Library", "Application Support", id)
case "windows":
if ad := os.Getenv("APPDATA"); ad != "" {
return filepath.Join(ad, id)
}
return filepath.Join(home, "AppData", "Roaming", id)
default: // linux and other unixes
if xdg := os.Getenv("XDG_DATA_HOME"); xdg != "" {
return filepath.Join(xdg, id)
}
return filepath.Join(home, ".local", "share", id)
}
}
func portRange(lo, hi int) []int {
ports := make([]int, 0, hi-lo+1)
for p := lo; p <= hi; p++ {
ports = append(ports, p)
}
return ports
}
func NewClient() (*Client, error) {
home, err := os.UserHomeDir()
if err != nil {
return nil, err
}
// Priority order: the CLI daemon on its fixed port first, then the GUI
// wallet. A source is only probed once its cookie exists, so listing both
// stays cheap when only one is installed.
sources := []source{
{label: "cli", dataDir: filepath.Join(home, ".config", "bnt", "data", "mainnet"), ports: []int{8332}},
}
if gui := guiAppDataDir(); gui != "" {
// The GUI binds a random port in 18432–18531 (pick_gui_api_port in the
// wallet); the live one is found by scanning the range.
sources = append(sources, source{label: "gui", dataDir: filepath.Join(gui, "data"), ports: portRange(18432, 18531)})
}
return &Client{
sources: sources,
hc: &http.Client{Timeout: 4 * time.Second},
// Block inspection is user-initiated and runs off the event loop, so it
// can afford to wait out chain-lock contention longer than the poll.
hcRaw: &http.Client{Timeout: 15 * time.Second},
hcProbe: &http.Client{Timeout: 400 * time.Millisecond},
}, nil
}
func (c *Client) currentActive() (resolved, bool) {
c.mu.Lock()
defer c.mu.Unlock()
if c.active == nil {
return resolved{}, false
}
return *c.active, true
}
func (c *Client) setActive(r resolved) {
c.mu.Lock()
c.active = &r
c.mu.Unlock()
}
func (c *Client) clearActive() {
c.mu.Lock()
c.active = nil
c.mu.Unlock()
}
func readToken(cookie string) string {
if b, err := os.ReadFile(cookie); err == nil {
return strings.TrimSpace(string(b))
}
return ""
}
// resolve scans the sources in priority order for a daemon that answers
// /api/status with the source's cookie and records the first match as active. A
// source without a cookie file is skipped (its node isn't running). Returns
// false when nothing is reachable yet.
func (c *Client) resolve(ctx context.Context) bool {
for _, s := range c.sources {
cookie := s.cookiePath()
token := readToken(cookie)
if token == "" {
continue
}
for _, port := range s.ports {
if ctx.Err() != nil {
return false
}
base := fmt.Sprintf("http://127.0.0.1:%d", port)
if c.probe(ctx, base, token) {
c.setActive(resolved{label: s.label, base: base, cookie: cookie, dataDir: s.dataDir})
return true
}
}
}
return false
}
// probe reports whether base is a Blocknet node that accepts this token. A 200
// is ours; a 401 is a foreign node on that port (reject); a transport error is
// nothing listening.
func (c *Client) probe(ctx context.Context, base, token string) bool {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/api/status", nil)
if err != nil {
return false
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := c.hcProbe.Do(req)
if err != nil {
return false
}
resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// transportErr reports whether err is a transport failure (nothing answered)
// rather than an HTTP status. A transport failure means the node we locked onto
// is gone, so the caller should re-resolve.
func transportErr(err error) bool {
if err == nil {
return false
}
if errors.Is(err, errNoNode) {
return true
}
return !strings.Contains(err.Error(), "-> ")
}
func (c *Client) get(ctx context.Context, path string, out any) error {
r, ok := c.currentActive()
if !ok {
return errNoNode
}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, r.base+path, nil)
req.Header.Set("Authorization", "Bearer "+readToken(r.cookie))
resp, err := c.hc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s -> %d", path, resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(out)
}
func (c *Client) getRaw(ctx context.Context, path string) ([]byte, error) {
r, ok := c.currentActive()
if !ok {
return nil, errNoNode
}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, r.base+path, nil)
req.Header.Set("Authorization", "Bearer "+readToken(r.cookie))
resp, err := c.hcRaw.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s -> %d", path, resp.StatusCode)
}
return io.ReadAll(resp.Body)
}
// srcView is a render-facing snapshot of a source: whether its cookie is present
// and whether it's the one we're connected through.
type srcView struct {
label string
cookie bool
active bool
}
func (c *Client) sourceViews() []srcView {
c.mu.Lock()
active := ""
if c.active != nil {
active = c.active.label
}
c.mu.Unlock()
out := make([]srcView, 0, len(c.sources))
for _, s := range c.sources {
_, err := os.Stat(s.cookiePath())
out = append(out, srcView{label: s.label, cookie: err == nil, active: s.label == active})
}
return out
}
// activeInfo returns the source we're connected through and its host:port, or
// ok=false when nothing is connected yet.
func (c *Client) activeInfo() (label, endpoint string, ok bool) {
c.mu.Lock()
defer c.mu.Unlock()
if c.active == nil {
return "", "", false
}
return c.active.label, strings.TrimPrefix(c.active.base, "http://"), true
}
func dirSize(path string) int64 {
var total int64
_ = filepath.WalkDir(path, func(_ string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if !d.IsDir() {
if info, e := d.Info(); e == nil {
total += info.Size()
}
}
return nil
})
return total
}
func diskLoop(ctx context.Context, c *Client, out chan<- snapshot) {
send := func(n int64) {
if n <= 0 {
return
}
select {
case out <- snapshot{disk: n}:
case <-ctx.Done():
}
}
// The active data dir isn't known until we connect (and can change if we
// reconnect to a different node), so walk it on first sight and every 15s
// after. The fast tick just watches for the dir to appear/change.
var lastDir string
fast := time.NewTicker(1 * time.Second)
defer fast.Stop()
slow := time.NewTicker(15 * time.Second)
defer slow.Stop()
for {
select {
case <-ctx.Done():
return
case <-fast.C:
if r, ok := c.currentActive(); ok && r.dataDir != lastDir {
lastDir = r.dataDir
send(dirSize(r.dataDir))
}
case <-slow.C:
if r, ok := c.currentActive(); ok {
send(dirSize(r.dataDir))
}
}
}
}
type snapshot struct {
status *Status
mempool *Mempool
peers *PeersResp
mining *Mining
newBlocks []Block
disk int64
err string
}
func poll(ctx context.Context, c *Client, out chan<- snapshot) {
lastHash := ""
backfilled := false
t := time.NewTicker(1500 * time.Millisecond)
defer t.Stop()
send := func(s snapshot) {
select {
case out <- s:
case <-ctx.Done():
}
}
fetch := func() {
var s snapshot
// Find a node to talk to (CLI or GUI). While waiting for one to come
// up, resolve runs every tick until it succeeds.
if _, ok := c.currentActive(); !ok {
if !c.resolve(ctx) {
s.err = "no node reachable"
send(s)
return
}
}
st := &Status{}
if err := c.get(ctx, "/api/status", st); err != nil {
// A transport error means the node we locked onto is gone; drop it
// so the next tick rescans (e.g. the GUI restarted on a new port).
if transportErr(err) {
c.clearActive()
}
s.err = err.Error()
send(s)
return
}
s.status = st
// During historic sync the node holds the chain lock for long
// stretches; keep the extra calls (which also contend) for when
// the node is caught up.
if !st.Syncing {
mp := &Mempool{}
if c.get(ctx, "/api/mempool", mp) == nil {
s.mempool = mp
}
mn := &Mining{}
if c.get(ctx, "/api/mining", mn) == nil {
s.mining = mn
}
}
if !backfilled {
send(s)
var blocks []Block
start := st.ChainHeight - 99
if start < 0 {
start = 0
}
for h := start; h <= st.ChainHeight; h++ {
var b Block
if c.get(ctx, fmt.Sprintf("/api/block/%d", h), &b) == nil {
blocks = append(blocks, b)
}
}
lastHash = st.BestHash
backfilled = true
send(snapshot{newBlocks: blocks})
return
}
// Only commit a block once we have its full record. If the fetch fails
// because the node is holding the chain lock during sync, leave
// lastHash untouched and retry on the next tick rather than pushing a
// stub carrying the short status hash and no timestamp.
if st.BestHash != lastHash {
var full Block
if c.get(ctx, fmt.Sprintf("/api/block/%d", st.ChainHeight), &full) == nil {
lastHash = st.BestHash
s.newBlocks = []Block{full}
}
}
send(s)
}
fetch()
for {
select {
case <-ctx.Done():
return
case <-t.C:
fetch()
}
}
}