This repository was archived by the owner on Mar 22, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
437 lines (382 loc) · 11.4 KB
/
node.go
File metadata and controls
437 lines (382 loc) · 11.4 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
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
// NodeClient communicates with the blocknet daemon HTTP API.
type NodeClient struct {
baseURL string
token string
client *http.Client
mu sync.RWMutex
chainHeight uint64
syncing bool
// SSE reconnection management
sseReconnectAttempts int
sseLastReconnect time.Time
}
// BlockTemplate is the response from GET /api/mining/blocktemplate.
type BlockTemplate struct {
Block json.RawMessage `json:"block"`
Target string `json:"target"`
HeaderBase string `json:"header_base"`
RewardAddressUsed string `json:"reward_address_used"`
}
// NodeStatus is the response from GET /api/status.
type NodeStatus struct {
PeerID string `json:"peer_id"`
Peers int `json:"peers"`
ChainHeight uint64 `json:"chain_height"`
BestHash string `json:"best_hash"`
TotalWork uint64 `json:"total_work"`
MempoolSize int `json:"mempool_size"`
MempoolBytes int `json:"mempool_bytes"`
Syncing bool `json:"syncing"`
IdentityAge string `json:"identity_age"`
}
// NodeBlock is the response from GET /api/block/{id}.
type NodeBlock struct {
Height uint64 `json:"height"`
Hash string `json:"hash"`
Reward uint64 `json:"reward"`
Difficulty uint64 `json:"difficulty"`
TxCount int `json:"tx_count"`
}
// SubmitBlockResponse is the response from POST /api/mining/submitblock.
type SubmitBlockResponse struct {
Accepted bool `json:"accepted"`
Hash string `json:"hash"`
Height uint64 `json:"height"`
}
// WalletSendRequest is the body for POST /api/wallet/send.
type WalletSendRequest struct {
Address string `json:"address"`
Amount uint64 `json:"amount"`
}
// WalletSendResponse is the response from POST /api/wallet/send.
type WalletSendResponse struct {
TxID string `json:"txid"`
Fee uint64 `json:"fee"`
Change uint64 `json:"change"`
}
type WalletLoadResponse struct {
Loaded bool `json:"loaded"`
Address string `json:"address"`
}
type WalletUnlockResponse struct {
Locked bool `json:"locked"`
}
type WalletAddressResponse struct {
Address string `json:"address"`
ViewOnly bool `json:"view_only"`
}
// WalletBalance is the response from GET /api/wallet/balance.
type WalletBalance struct {
Spendable uint64 `json:"spendable"`
Pending uint64 `json:"pending"`
Total uint64 `json:"total"`
}
// SSEEvent represents a parsed server-sent event.
type SSEEvent struct {
Event string
Data string
}
// HTTPError represents a non-200 daemon API response.
type HTTPError struct {
Path string
StatusCode int
Body string
}
func (e *HTTPError) Error() string {
return fmt.Sprintf("%s %d: %s", e.Path, e.StatusCode, e.Body)
}
// IsHTTPStatus reports whether err (possibly wrapped) is an HTTPError with the given status.
func IsHTTPStatus(err error, status int) bool {
var httpErr *HTTPError
if !errors.As(err, &httpErr) {
return false
}
return httpErr.StatusCode == status
}
func NewNodeClient(baseURL, token string) *NodeClient {
return &NodeClient{
baseURL: strings.TrimRight(baseURL, "/"),
token: token,
client: &http.Client{
Timeout: 30 * time.Second,
},
}
}
func (n *NodeClient) doRequest(method, path string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, n.baseURL+path, body)
if err != nil {
return nil, err
}
if n.token != "" {
req.Header.Set("Authorization", "Bearer "+n.token)
}
req.Header.Set("Content-Type", "application/json")
return n.client.Do(req)
}
func (n *NodeClient) doRequestWithHeaders(method, path string, body io.Reader, headers map[string]string) (*http.Response, error) {
req, err := http.NewRequest(method, n.baseURL+path, body)
if err != nil {
return nil, err
}
if n.token != "" {
req.Header.Set("Authorization", "Bearer "+n.token)
}
req.Header.Set("Content-Type", "application/json")
for k, v := range headers {
if k == "" || v == "" {
continue
}
req.Header.Set(k, v)
}
return n.client.Do(req)
}
func (n *NodeClient) doGet(path string, out any) error {
resp, err := n.doRequest("GET", path, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return &HTTPError{Path: path, StatusCode: resp.StatusCode, Body: string(body)}
}
return json.NewDecoder(resp.Body).Decode(out)
}
func (n *NodeClient) doPost(path string, reqBody, out any) error {
return n.doPostWithHeaders(path, reqBody, out, nil)
}
func (n *NodeClient) doPostWithHeaders(path string, reqBody, out any, headers map[string]string) error {
data, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("marshal request: %w", err)
}
resp, err := n.doRequestWithHeaders("POST", path, bytes.NewReader(data), headers)
if err != nil {
return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return &HTTPError{Path: path, StatusCode: resp.StatusCode, Body: string(body)}
}
return json.Unmarshal(body, out)
}
// GetStatus fetches the node status and caches key fields.
func (n *NodeClient) GetStatus() (*NodeStatus, error) {
var status NodeStatus
if err := n.doGet("/api/status", &status); err != nil {
return nil, fmt.Errorf("node status: %w", err)
}
n.mu.Lock()
n.chainHeight = status.ChainHeight
n.syncing = status.Syncing
n.mu.Unlock()
return &status, nil
}
// GetBlockTemplate fetches a fresh block template for mining.
// If rewardAddress is set, it is passed to the daemon so coinbase pays that address.
func (n *NodeClient) GetBlockTemplate(rewardAddress string) (*BlockTemplate, error) {
var tmpl BlockTemplate
path := "/api/mining/blocktemplate"
if rewardAddress != "" {
path = fmt.Sprintf("%s?address=%s", path, url.QueryEscape(rewardAddress))
}
if err := n.doGet(path, &tmpl); err != nil {
return nil, fmt.Errorf("blocktemplate: %w", err)
}
return &tmpl, nil
}
// GetBlock fetches a block by height or hash from the node.
func (n *NodeClient) GetBlock(id string) (*NodeBlock, error) {
var block NodeBlock
if err := n.doGet("/api/block/"+id, &block); err != nil {
return nil, err
}
return &block, nil
}
// SubmitBlock submits a solved block to the node.
func (n *NodeClient) SubmitBlock(blockJSON json.RawMessage) (*SubmitBlockResponse, error) {
resp, err := n.doRequest("POST", "/api/mining/submitblock", bytes.NewReader(blockJSON))
if err != nil {
return nil, fmt.Errorf("submitblock: %w", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, &HTTPError{Path: "/api/mining/submitblock", StatusCode: resp.StatusCode, Body: string(body)}
}
var result SubmitBlockResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("decode submitblock: %w", err)
}
return &result, nil
}
// WalletSend sends BNT to an address via POST /api/wallet/send.
func (n *NodeClient) WalletSend(address string, amount uint64, idempotencyKey string) (*WalletSendResponse, error) {
var result WalletSendResponse
headers := map[string]string{}
if idempotencyKey != "" {
headers["Idempotency-Key"] = idempotencyKey
}
err := n.doPostWithHeaders("/api/wallet/send", &WalletSendRequest{
Address: address,
Amount: amount,
}, &result, headers)
if err != nil {
return nil, fmt.Errorf("wallet send: %w", err)
}
return &result, nil
}
// WalletLoad loads (or creates) a wallet in daemon mode.
func (n *NodeClient) WalletLoad(password string) (*WalletLoadResponse, error) {
var result WalletLoadResponse
err := n.doPost("/api/wallet/load", map[string]string{
"password": password,
}, &result)
if err != nil {
return nil, fmt.Errorf("wallet load: %w", err)
}
return &result, nil
}
// WalletUnlock unlocks the currently loaded wallet.
func (n *NodeClient) WalletUnlock(password string) (*WalletUnlockResponse, error) {
var result WalletUnlockResponse
err := n.doPost("/api/wallet/unlock", map[string]string{
"password": password,
}, &result)
if err != nil {
return nil, fmt.Errorf("wallet unlock: %w", err)
}
return &result, nil
}
// GetWalletAddress fetches the currently loaded wallet address.
func (n *NodeClient) GetWalletAddress() (*WalletAddressResponse, error) {
var addr WalletAddressResponse
if err := n.doGet("/api/wallet/address", &addr); err != nil {
return nil, fmt.Errorf("wallet address: %w", err)
}
return &addr, nil
}
// GetWalletBalance fetches the wallet balance.
func (n *NodeClient) GetWalletBalance() (*WalletBalance, error) {
var bal WalletBalance
if err := n.doGet("/api/wallet/balance", &bal); err != nil {
return nil, fmt.Errorf("wallet balance: %w", err)
}
return &bal, nil
}
// SubscribeBlocks opens an SSE connection to /api/events and sends events to the channel.
// Reconnects on failure with exponential backoff. Runs until ctx is cancelled.
func (n *NodeClient) SubscribeBlocks(ctx context.Context, ch chan<- SSEEvent) {
const (
maxReconnectAttempts = 10
baseBackoff = 5 * time.Second
maxBackoff = 5 * time.Minute
)
for {
if ctx.Err() != nil {
return
}
// Calculate backoff with exponential increase
var backoff time.Duration
if n.sseReconnectAttempts == 0 {
backoff = 0 // first attempt is immediate
} else if n.sseReconnectAttempts >= maxReconnectAttempts {
log.Printf("[node] SSE max reconnection attempts reached, waiting %v", maxBackoff)
backoff = maxBackoff
} else {
// Exponential backoff: 5s, 10s, 20s, 40s, 80s, ...
backoff = baseBackoff * time.Duration(1<<uint(n.sseReconnectAttempts-1))
if backoff > maxBackoff {
backoff = maxBackoff
}
}
if backoff > 0 {
log.Printf("[node] SSE reconnecting in %v (attempt %d)", backoff, n.sseReconnectAttempts+1)
select {
case <-ctx.Done():
return
case <-time.After(backoff):
}
}
n.sseReconnectAttempts++
n.sseLastReconnect = time.Now()
if err := n.streamSSE(ctx, ch); err != nil {
if ctx.Err() != nil {
return
}
log.Printf("[node] SSE connection lost: %v", err)
}
}
}
func (n *NodeClient) streamSSE(ctx context.Context, ch chan<- SSEEvent) error {
req, err := http.NewRequestWithContext(ctx, "GET", n.baseURL+"/api/events", nil)
if err != nil {
return err
}
if n.token != "" {
req.Header.Set("Authorization", "Bearer "+n.token)
}
req.Header.Set("Accept", "text/event-stream")
sseClient := &http.Client{}
resp, err := sseClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return &HTTPError{Path: "/api/events", StatusCode: resp.StatusCode, Body: string(body)}
}
// Reset reconnect counter on successful connection
n.sseReconnectAttempts = 0
scanner := bufio.NewScanner(resp.Body)
var event SSEEvent
for scanner.Scan() {
line := scanner.Text()
switch {
case strings.HasPrefix(line, "event: "):
event.Event = strings.TrimPrefix(line, "event: ")
case strings.HasPrefix(line, "data: "):
event.Data = strings.TrimPrefix(line, "data: ")
case line == "":
if event.Event != "" {
select {
case ch <- event:
case <-ctx.Done():
return ctx.Err()
}
event = SSEEvent{}
}
}
}
return scanner.Err()
}
// ChainHeight returns the last known chain height.
func (n *NodeClient) ChainHeight() uint64 {
n.mu.RLock()
defer n.mu.RUnlock()
return n.chainHeight
}
// Syncing returns whether the node is syncing.
func (n *NodeClient) Syncing() bool {
n.mu.RLock()
defer n.mu.RUnlock()
return n.syncing
}