-
Notifications
You must be signed in to change notification settings - Fork 20
/
notifs.go
63 lines (51 loc) · 1.5 KB
/
notifs.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
package rpc
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/decred/dcrd/wire"
"github.com/decred/slog"
)
type blockConnectedHandler struct {
blockConnected chan *wire.BlockHeader
log slog.Logger
}
// Notify is called every time a notification is received from dcrd client.
// A wsrpc.Client will never call Notify concurrently. Notify should not return
// an error because that will cause the client to close and no further
// notifications will be received until a new connection is established.
func (n *blockConnectedHandler) Notify(method string, msg json.RawMessage) error {
if method != "blockconnected" {
return nil
}
header, err := parseBlockConnected(msg)
if err != nil {
n.log.Errorf("Failed to parse dcrd block notification: %v", err)
return nil
}
n.blockConnected <- header
return nil
}
func (n *blockConnectedHandler) Close() error {
return nil
}
// parseBlockConnected extracts the block header from a
// blockconnected JSON-RPC notification.
func parseBlockConnected(msg json.RawMessage) (*wire.BlockHeader, error) {
var notif []string
err := json.Unmarshal(msg, ¬if)
if err != nil {
return nil, fmt.Errorf("json unmarshal error: %w", err)
}
if len(notif) == 0 {
return nil, errors.New("notification is empty")
}
var header wire.BlockHeader
err = header.Deserialize(hex.NewDecoder(bytes.NewReader([]byte(notif[0]))))
if err != nil {
return nil, fmt.Errorf("error creating block header from bytes: %w", err)
}
return &header, nil
}