-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
194 lines (177 loc) · 4.33 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gcash/bchd/chaincfg/chainhash"
"github.com/gcash/bchd/rpcclient"
"github.com/gcash/bchutil"
"github.com/gorilla/websocket"
"io"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"strings"
"time"
)
type Notif struct {
Txid string `json:"txid"`
FinalizationTIme string `json:"finalizationTime"`
}
type limitMap struct {
limit int
count int
notifications map[int]Notif
}
func (m *limitMap) Append(n Notif) {
var toDelete []int
if len(m.notifications) >= m.limit {
for i := range m.notifications {
if i < m.count + 1 - m.limit {
toDelete = append(toDelete, i)
}
}
}
for _, i := range toDelete {
delete(m.notifications, i)
}
m.notifications[m.count+1] = n
m.count++
}
func (m *limitMap) Notifications() []Notif {
var notifs []Notif
for _, n := range m.notifications {
notifs = append(notifs, n)
}
return notifs
}
var newConn chan *websocket.Conn
var doneConn chan *websocket.Conn
var notifications *limitMap
func main() {
notifications = &limitMap{
notifications: make(map[int]Notif),
limit: 8,
}
notifChan := make(chan Notif)
newConn = make(chan *websocket.Conn)
doneConn = make(chan *websocket.Conn)
if err := connectBchdWebsocket(notifChan); err != nil {
log.Fatal(err)
}
go listenChans(newConn, notifChan)
http.HandleFunc("/ws", handleWebsocket)
http.HandleFunc("/notifications", handleNotifications)
http.Handle("/", http.StripPrefix("/", http.HandlerFunc(static_handler)))
log.Println("Listening...")
http.ListenAndServe(":3000", nil)
}
// generate with: go-bindata -prefix "static/" -pkg main -o bindata.go static/...
func static_handler(rw http.ResponseWriter, req *http.Request) {
var path string = req.URL.Path
if path == "" {
path = "index.html"
}
if bs, err := Asset(path); err != nil {
rw.WriteHeader(http.StatusNotFound)
} else {
var reader = bytes.NewBuffer(bs)
io.Copy(rw, reader)
}
}
func listenChans(newConn chan *websocket.Conn, newNotif chan Notif) {
conns := make(map[*websocket.Conn]struct{})
for {
select {
case conn := <- newConn:
conns[conn] = struct{}{}
case conn := <- doneConn:
delete(conns, conn)
case n := <- newNotif:
notifications.Append(n)
out, err := json.MarshalIndent(&n, "", " ")
if err != nil {
log.Println(err)
continue
}
for conn := range conns {
conn.WriteMessage(websocket.TextMessage, out)
}
}
}
}
func connectBchdWebsocket(notificationChan chan Notif) error {
// Only override the handlers for notifications you care about.
// Also note most of these handlers will only be called if you register
// for notifications. See the documentation of the rpcclient
// NotificationHandlers type for more details about each handler.
ntfnHandlers := rpcclient.NotificationHandlers{
OnTxFinalized: func(txid *chainhash.Hash, finalizationTime time.Duration) {
notificationChan <- Notif{txid.String(), finalizationTime.String()}
},
}
// Connect to local bchd RPC server using websockets.
bchdHomeDir := bchutil.AppDataDir("bchd", false)
certs, err := ioutil.ReadFile(filepath.Join(bchdHomeDir, "rpc.cert"))
if err != nil {
return err
}
connCfg := &rpcclient.ConnConfig{
Host: "localhost:8334",
Endpoint: "ws",
User: "alice",
Pass: "letmein",
Certificates: certs,
}
client, err := rpcclient.New(connCfg, &ntfnHandlers)
if err != nil {
return err
}
if err := client.NotifyAvalanche(); err != nil {
return err
}
return nil
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
host := strings.Split(r.Host, ":")
if host[0] == "localhost" {
return true
}
return false
},
}
//
func handleWebsocket(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
newConn <- c
go func() {
defer c.Close()
for {
_, _, err := c.ReadMessage()
if err != nil {
doneConn <- c
break
}
}
}()
}
// GET /notifications. Returns a JSON list of the last 8 notifications
func handleNotifications(w http.ResponseWriter, r *http.Request) {
notifs := notifications.Notifications()
out, err := json.MarshalIndent(¬ifs, "", " ")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(notifs) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
fmt.Fprint(w, string(out))
}