-
Notifications
You must be signed in to change notification settings - Fork 22
/
mempool.go
181 lines (166 loc) · 4.56 KB
/
mempool.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
package missed
import (
"bytes"
"context"
"encoding/json"
"fmt"
rpchttp "github.com/tendermint/tendermint/rpc/client/http"
"github.com/tendermint/tendermint/types"
"io"
"net/http"
"strconv"
"time"
)
const trackUnconfirmed = 900 // length of ringbuffer for tracking mempool. TODO: rethink this approach
func mkTxPoint(scaling int) []*txCountPoint {
now := time.Now().UTC()
u := make([]*txCountPoint, trackUnconfirmed/scaling)
for i := len(u) - 1; i > 0; i-- {
u[i] = &txCountPoint{
Time: now.Add(time.Duration(-i*scaling) * time.Second),
Pending: 0,
}
}
return u
}
var UnconfirmedCache = []byte(`[]`)
var unconfirmed = mkTxPoint(1)
var confirmed = mkTxPoint(1)
func WatchUnconfirmed(ctx context.Context, updates chan []byte, client *http.Client, baseUrl, origApi string, started chan interface{}) {
<- started
failed := make(chan interface{})
points := make(chan *txCountPoint)
go streamMemPool(ctx, client, baseUrl, points, failed)
for {
subClient, _ := rpchttp.New(origApi, "/websocket")
err := subClient.Start()
if err != nil {
l.Fatal(origApi, err)
}
query := "tm.event = 'NewBlock'"
freshBlocks, err := subClient.Subscribe(ctx, "test-client", query)
if err != nil {
l.Fatal(origApi, err)
}
func() {
defer subClient.Stop()
for {
select {
case <-ctx.Done():
l.Println("WatchUnconfirmed() exiting: parent exited")
return
case <-failed:
l.Println("WatchUnconfirmed() exiting: streamMemPool failed")
return
case b := <-freshBlocks:
updates <- []byte(fmt.Sprintf(`["%s",%d,"Confirmed Tx"]`,
b.Data.(types.EventDataNewBlock).Block.Time.Format(time.RFC3339),
len(b.Data.(types.EventDataNewBlock).Block.Txs),
))
confirmed[len(confirmed)-1] = &txCountPoint{
Time: b.Data.(types.EventDataNewBlock).Block.Time,
Pending: len(b.Data.(types.EventDataNewBlock).Block.Txs),
}
case p := <-points:
updates <- []byte(fmt.Sprintf(`["%s",%d,"Pending Tx"]`, p.Time.Format(time.RFC3339), p.Pending))
confirmed = append(confirmed[1:], &txCountPoint{
Time: p.Time,
Pending: 0,
})
unconfirmed = append(unconfirmed[1:], p)
if time.Now().Second()%5 == 0 {
buf := bytes.NewBufferString(`[[`)
prefix := ""
for i := range unconfirmed {
buf.WriteString(fmt.Sprintf(`%s["%s",%d,"Pending Tx"]`, prefix, unconfirmed[i].Time.UTC().Format(time.RFC3339), unconfirmed[i].Pending))
prefix = ","
}
buf.WriteString(`],[`)
prefix = ""
for i := range confirmed {
buf.WriteString(fmt.Sprintf(`%s["%s",%d,"Confirmed Tx"]`, prefix, confirmed[i].Time.UTC().Format(time.RFC3339), confirmed[i].Pending))
prefix = ","
}
buf.WriteString(`]]`)
UnconfirmedCache = buf.Bytes()
}
}
}
}()
time.Sleep(10*time.Second)
}
}
type txCountPoint struct {
Time time.Time `json:"time"`
Pending int `json:"pending"`
}
// unconfirmResp is a stripped down version of RPC response only holding total count
type unconfirmResp struct {
Result struct {
Total string `json:"total"`
} `json:"result"`
}
func (u *unconfirmResp) total() int {
if u == nil {
return 0
}
i, _ := strconv.Atoi(u.Result.Total)
return i
}
// streamMemPool sends the result from 'num_unconfirmed_txs' to a channel.
// this is going to work a lot better with a unix socket since tcp gets expensive when polling.
func streamMemPool(ctx context.Context, client *http.Client, baseUrl string, points chan *txCountPoint, failed chan interface{}) {
defer close(failed)
tick := time.NewTicker(time.Second)
for {
select {
case <-ctx.Done():
return
case <-tick.C:
go func() {
var (
body []byte
err error
resp *http.Response
t = time.Now().UTC()
)
c, cancel := context.WithTimeout(context.Background(), time.Second-1)
defer cancel()
req, _ := http.NewRequestWithContext(c, "GET", baseUrl+`/num_unconfirmed_txs`, nil)
resp, err = client.Do(req)
if err != nil {
l.Println("refresh mempool length:", err)
points <- &txCountPoint{
Time: t,
Pending: 0,
}
return
}
body, err = io.ReadAll(resp.Body)
if err != nil {
l.Println(err)
points <- &txCountPoint{
Time: t,
Pending: 0,
}
return
}
defer resp.Body.Close()
ucr := &unconfirmResp{}
err = json.Unmarshal(body, ucr)
if err != nil {
l.Println(err)
points <- &txCountPoint{
Time: t,
Pending: 0,
}
return
}
points <- &txCountPoint{
Time: t,
Pending: ucr.total(),
}
}()
}
}
}