forked from decred/dcrdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mempool.go
267 lines (229 loc) · 7.21 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
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
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
package explorer
import (
"sort"
"time"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrdata/txhelpers"
humanize "github.com/dustin/go-humanize"
)
// NumLatestMempoolTxns is the maximum number of mempool transactions that will
// be stored in MempoolData.LatestTransactions.
const NumLatestMempoolTxns = 5
func (exp *explorerUI) mempoolMonitor(txChan chan *NewMempoolTx) {
// Get the initial best block hash and time
lastBlockHash, _, lastBlockTime := exp.storeMempoolInfo()
// Process new transactions as they arrive
for {
ntx, ok := <-txChan
if !ok {
log.Infof("New Tx channel closed")
return
}
// A nil tx is the signal to stop
if ntx == nil {
return
}
// A tx with an empty hex is the new block signal
if ntx.Hex == "" {
lastBlockHash, _, lastBlockTime = exp.storeMempoolInfo()
exp.wsHub.HubRelay <- sigMempoolUpdate
continue
}
// Ignore this tx if it was received before the last block
if ntx.Time < lastBlockTime {
continue
}
msgTx, err := txhelpers.MsgTxFromHex(ntx.Hex)
if err != nil {
log.Debugf("Failed to decode transaction: %v", err)
continue
}
hash := msgTx.TxHash().String()
// If this is a vote, decode vote bits
var voteInfo *VoteInfo
if ok := stake.IsSSGen(msgTx); ok {
validation, version, bits, choices, err := txhelpers.SSGenVoteChoices(msgTx, exp.ChainParams)
if !voteForLastBlock(lastBlockHash, validation.Hash.String()) {
continue
}
if err != nil {
log.Debugf("Cannot get vote choices for %s", hash)
} else {
voteInfo = &VoteInfo{
Validation: BlockValidation{
Hash: validation.Hash.String(),
Height: validation.Height,
Validity: validation.Validity,
},
Version: version,
Bits: bits,
Choices: choices,
TicketSpent: msgTx.TxIn[1].PreviousOutPoint.Hash.String(),
}
}
}
tx := MempoolTx{
Hash: hash,
Time: ntx.Time,
Size: int32(len(ntx.Hex) / 2),
TotalOut: txhelpers.TotalOutFromMsgTx(msgTx).ToCoin(),
Type: txhelpers.DetermineTxTypeString(msgTx),
VoteInfo: voteInfo,
}
// Add the tx to the appropriate tx slice in MempoolData and update the
// count for the transaction type.
exp.MempoolData.Lock()
switch tx.Type {
case "Ticket":
exp.MempoolData.Tickets = append([]MempoolTx{tx}, exp.MempoolData.Tickets...)
exp.MempoolData.NumTickets++
case "Vote":
if idx, ok := exp.MempoolData.TicketIndexes[tx.VoteInfo.TicketSpent]; ok {
tx.VoteInfo.MempoolTicketIndex = idx
} else {
idx := len(exp.MempoolData.TicketIndexes) + 1
exp.MempoolData.TicketIndexes[tx.VoteInfo.TicketSpent] = idx
tx.VoteInfo.MempoolTicketIndex = idx
}
exp.MempoolData.Votes = append([]MempoolTx{tx}, exp.MempoolData.Votes...)
exp.MempoolData.NumVotes++
case "Regular":
exp.MempoolData.Transactions = append([]MempoolTx{tx}, exp.MempoolData.Transactions...)
exp.MempoolData.NumRegular++
case "Revocation":
exp.MempoolData.Revocations = append([]MempoolTx{tx}, exp.MempoolData.Revocations...)
exp.MempoolData.NumRevokes++
}
// Update latest transactions, popping the oldest transaction off the
// back if necessary to limit to NumLatestMempoolTxns.
numLatest := len(exp.MempoolData.LatestTransactions)
if numLatest >= NumLatestMempoolTxns {
exp.MempoolData.LatestTransactions = append([]MempoolTx{tx},
exp.MempoolData.LatestTransactions[:numLatest-1]...)
} else {
exp.MempoolData.LatestTransactions = append([]MempoolTx{tx},
exp.MempoolData.LatestTransactions...)
}
// Store totals
exp.MempoolData.NumAll++
exp.MempoolData.TotalOut += tx.TotalOut
exp.MempoolData.TotalSize += tx.Size
exp.MempoolData.FormattedTotalSize = humanize.Bytes(uint64(exp.MempoolData.TotalSize))
exp.MempoolData.Unlock()
// Broadcast the new transaction
exp.wsHub.HubRelay <- sigNewTx
exp.wsHub.NewTxChan <- &tx
}
}
func (exp *explorerUI) StopMempoolMonitor(txChan chan *NewMempoolTx) {
log.Infof("Stopping mempool monitor")
txChan <- nil
}
func (exp *explorerUI) StartMempoolMonitor(newTxChan chan *NewMempoolTx) {
go exp.mempoolMonitor(newTxChan)
}
func (exp *explorerUI) storeMempoolInfo() (lastBlockHash string, lastBlock int64, lastBlockTime int64) {
defer func(start time.Time) {
log.Debugf("storeMempoolInfo() completed in %v",
time.Since(start))
}(time.Now())
memtxs := exp.blockData.GetMempool()
if memtxs == nil {
log.Error("Could not get mempool transactions")
return
}
lastBlockHash, lastBlock, lastBlockTime = exp.getLastBlock()
// RPC succeeded, but mempool is empty
if len(memtxs) == 0 {
return
}
// Get the NumLatestMempoolTxns latest transactions in mempool
var latest []MempoolTx
sort.Sort(byTime(memtxs))
if len(memtxs) > NumLatestMempoolTxns {
latest = memtxs[:NumLatestMempoolTxns]
} else {
latest = memtxs
}
tickets := make([]MempoolTx, 0)
votes := make([]MempoolTx, 0)
revs := make([]MempoolTx, 0)
regular := make([]MempoolTx, 0)
var totalOut float64
var totalSize int32
// Categorize the transactions, and bin votes by ticket spent
txindexes := make(map[string]int)
for _, tx := range memtxs {
switch tx.Type {
case "Ticket":
tickets = append(tickets, tx)
case "Vote":
if !voteForLastBlock(lastBlockHash, tx.VoteInfo.Validation.Hash) {
continue
}
if idx, ok := txindexes[tx.VoteInfo.TicketSpent]; ok {
tx.VoteInfo.MempoolTicketIndex = idx
} else {
idx := len(txindexes) + 1
txindexes[tx.VoteInfo.TicketSpent] = idx
tx.VoteInfo.MempoolTicketIndex = idx
}
votes = append(votes, tx)
case "Revocation":
revs = append(revs, tx)
default:
regular = append(regular, tx)
}
totalOut += tx.TotalOut
totalSize += tx.Size
}
// Store the results in MempoolData for the web page
exp.MempoolData.Lock()
defer exp.MempoolData.Unlock()
exp.MempoolData.Transactions = regular
exp.MempoolData.Tickets = tickets
exp.MempoolData.Revocations = revs
exp.MempoolData.Votes = votes
exp.MempoolData.MempoolShort = MempoolShort{
LastBlockHeight: lastBlock,
LastBlockTime: lastBlockTime,
TotalOut: totalOut,
TotalSize: totalSize,
NumAll: len(memtxs),
NumTickets: len(tickets),
NumVotes: len(votes),
NumRegular: len(regular),
NumRevokes: len(revs),
LatestTransactions: latest,
FormattedTotalSize: humanize.Bytes(uint64(totalSize)),
TicketIndexes: txindexes,
}
return
}
func voteForLastBlock(blockHash, validationHash string) bool {
return blockHash == validationHash && blockHash != ""
}
// getLastBlock returns the last block hash, height and time
func (exp *explorerUI) getLastBlock() (lastBlockHash string, lastBlock int64, lastBlockTime int64) {
exp.NewBlockDataMtx.RLock()
lastBlock = exp.NewBlockData.Height
lastBlockTime = exp.NewBlockData.BlockTime
exp.NewBlockDataMtx.RUnlock()
lastBlockHash, err := exp.blockData.GetBlockHash(lastBlock)
if err != nil {
log.Warnf("Could not get bloch hash for last block")
}
return
}
type byTime []MempoolTx
func (txs byTime) Less(i, j int) bool {
return txs[i].Time > txs[j].Time
}
func (txs byTime) Len() int {
return len(txs)
}
func (txs byTime) Swap(i, j int) {
txs[i], txs[j] = txs[j], txs[i]
}