-
Notifications
You must be signed in to change notification settings - Fork 424
/
reactor.go
327 lines (287 loc) · 10.1 KB
/
reactor.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
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
package mempool
import (
"context"
"errors"
"fmt"
"sync/atomic"
"time"
abci "github.com/cometbft/cometbft/abci/types"
protomem "github.com/cometbft/cometbft/api/cometbft/mempool/v1"
cfg "github.com/cometbft/cometbft/config"
"github.com/cometbft/cometbft/internal/clist"
cmtsync "github.com/cometbft/cometbft/internal/sync"
"github.com/cometbft/cometbft/libs/log"
"github.com/cometbft/cometbft/p2p"
"github.com/cometbft/cometbft/types"
"golang.org/x/sync/semaphore"
)
// Reactor handles mempool tx broadcasting amongst peers.
// It maintains a map from peer ID to counter, to prevent gossiping txs to the
// peers you received it from.
type Reactor struct {
p2p.BaseReactor
config *cfg.MempoolConfig
mempool *CListMempool
waitSync atomic.Bool
waitSyncCh chan struct{} // for signaling when to start receiving and sending txs
// `txSenders` maps every received transaction to the set of peer IDs that
// have sent the transaction to this node. Sender IDs are used during
// transaction propagation to avoid sending a transaction to a peer that
// already has it.
txSenders map[types.TxKey]map[p2p.ID]bool
txSendersMtx cmtsync.Mutex
// Semaphores to keep track of how many connections to peers are active for broadcasting
// transactions. Each semaphore has a capacity that puts an upper bound on the number of
// connections for different groups of peers.
activePersistentPeersSemaphore *semaphore.Weighted
activeNonPersistentPeersSemaphore *semaphore.Weighted
}
// NewReactor returns a new Reactor with the given config and mempool.
func NewReactor(config *cfg.MempoolConfig, mempool *CListMempool, waitSync bool) *Reactor {
memR := &Reactor{
config: config,
mempool: mempool,
waitSync: atomic.Bool{},
txSenders: make(map[types.TxKey]map[p2p.ID]bool),
}
memR.BaseReactor = *p2p.NewBaseReactor("Mempool", memR)
if waitSync {
memR.waitSync.Store(true)
memR.waitSyncCh = make(chan struct{})
}
memR.mempool.SetTxRemovedCallback(func(txKey types.TxKey) { memR.removeSenders(txKey) })
memR.activePersistentPeersSemaphore = semaphore.NewWeighted(int64(memR.config.ExperimentalMaxGossipConnectionsToPersistentPeers))
memR.activeNonPersistentPeersSemaphore = semaphore.NewWeighted(int64(memR.config.ExperimentalMaxGossipConnectionsToNonPersistentPeers))
return memR
}
// SetLogger sets the Logger on the reactor and the underlying mempool.
func (memR *Reactor) SetLogger(l log.Logger) {
memR.Logger = l
memR.mempool.SetLogger(l)
}
// OnStart implements p2p.BaseReactor.
func (memR *Reactor) OnStart() error {
if memR.WaitSync() {
memR.Logger.Info("Starting reactor in sync mode: tx propagation will start once sync completes")
}
if !memR.config.Broadcast {
memR.Logger.Info("Tx broadcasting is disabled")
}
return nil
}
// GetChannels implements Reactor by returning the list of channels for this
// reactor.
func (memR *Reactor) GetChannels() []*p2p.ChannelDescriptor {
largestTx := make([]byte, memR.config.MaxTxBytes)
batchMsg := protomem.Message{
Sum: &protomem.Message_Txs{
Txs: &protomem.Txs{Txs: [][]byte{largestTx}},
},
}
return []*p2p.ChannelDescriptor{
{
ID: MempoolChannel,
Priority: 5,
RecvMessageCapacity: batchMsg.Size(),
MessageType: &protomem.Message{},
},
}
}
// AddPeer implements Reactor.
// It starts a broadcast routine ensuring all txs are forwarded to the given peer.
func (memR *Reactor) AddPeer(peer p2p.Peer) {
if memR.config.Broadcast {
go func() {
// Always forward transactions to unconditional peers.
if !memR.Switch.IsPeerUnconditional(peer.ID()) {
// Depending on the type of peer, we choose a semaphore to limit the gossiping peers.
var peerSemaphore *semaphore.Weighted
if peer.IsPersistent() && memR.config.ExperimentalMaxGossipConnectionsToPersistentPeers > 0 {
peerSemaphore = memR.activePersistentPeersSemaphore
} else if !peer.IsPersistent() && memR.config.ExperimentalMaxGossipConnectionsToNonPersistentPeers > 0 {
peerSemaphore = memR.activeNonPersistentPeersSemaphore
}
if peerSemaphore != nil {
for peer.IsRunning() {
// Block on the semaphore until a slot is available to start gossiping with this peer.
// Do not block indefinitely, in case the peer is disconnected before gossiping starts.
ctxTimeout, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
// Block sending transactions to peer until one of the connections become
// available in the semaphore.
err := peerSemaphore.Acquire(ctxTimeout, 1)
cancel()
if err != nil {
continue
}
// Release semaphore to allow other peer to start sending transactions.
defer peerSemaphore.Release(1)
break
}
}
}
memR.mempool.metrics.ActiveOutboundConnections.Add(1)
defer memR.mempool.metrics.ActiveOutboundConnections.Add(-1)
memR.broadcastTxRoutine(peer)
}()
}
}
// Receive implements Reactor.
// It adds any received transactions to the mempool.
func (memR *Reactor) Receive(e p2p.Envelope) {
memR.Logger.Debug("Receive", "src", e.Src, "chId", e.ChannelID, "msg", e.Message)
switch msg := e.Message.(type) {
case *protomem.Txs:
if memR.WaitSync() {
memR.Logger.Debug("Ignored message received while syncing", "msg", msg)
return
}
protoTxs := msg.GetTxs()
if len(protoTxs) == 0 {
memR.Logger.Error("received empty txs from peer", "src", e.Src)
return
}
for _, txBytes := range protoTxs {
tx := types.Tx(txBytes)
reqRes, err := memR.mempool.CheckTx(tx)
if errors.Is(err, ErrTxInCache) {
memR.Logger.Debug("Tx already exists in cache", "tx", tx.String())
} else if err != nil {
memR.Logger.Info("Could not check tx", "tx", tx.String(), "err", err)
} else {
// Record the sender only when the transaction is valid and, as
// a consequence, added to the mempool. Senders are stored until
// the transaction is removed from the mempool. Note that it's
// possible a tx is still in the cache but no longer in the
// mempool. For example, after committing a block, txs are
// removed from mempool but not the cache.
reqRes.SetCallback(func(res *abci.Response) {
if res.GetCheckTx().Code == abci.CodeTypeOK {
memR.addSender(tx.Key(), e.Src.ID())
}
})
}
}
default:
memR.Logger.Error("unknown message type", "src", e.Src, "chId", e.ChannelID, "msg", e.Message)
memR.Switch.StopPeerForError(e.Src, fmt.Errorf("mempool cannot handle message of type: %T", e.Message))
return
}
// broadcasting happens from go routines per peer
}
func (memR *Reactor) EnableInOutTxs() {
memR.Logger.Info("enabling inbound and outbound transactions")
if !memR.waitSync.CompareAndSwap(true, false) {
return
}
// Releases all the blocked broadcastTxRoutine instances.
if memR.config.Broadcast {
close(memR.waitSyncCh)
}
}
func (memR *Reactor) WaitSync() bool {
return memR.waitSync.Load()
}
// PeerState describes the state of a peer.
type PeerState interface {
GetHeight() int64
}
// Send new mempool txs to peer.
func (memR *Reactor) broadcastTxRoutine(peer p2p.Peer) {
var next *clist.CElement
// If the node is catching up, don't start this routine immediately.
if memR.WaitSync() {
select {
case <-memR.waitSyncCh:
// EnableInOutTxs() has set WaitSync() to false.
case <-memR.Quit():
return
}
}
for {
// In case of both next.NextWaitChan() and peer.Quit() are variable at the same time
if !memR.IsRunning() || !peer.IsRunning() {
return
}
// This happens because the CElement we were looking at got garbage
// collected (removed). That is, .NextWait() returned nil. Go ahead and
// start from the beginning.
if next == nil {
select {
case <-memR.mempool.TxsWaitChan(): // Wait until a tx is available
if next = memR.mempool.TxsFront(); next == nil {
continue
}
case <-peer.Quit():
return
case <-memR.Quit():
return
}
}
// Make sure the peer is up to date.
peerState, ok := peer.Get(types.PeerStateKey).(PeerState)
if !ok {
// Peer does not have a state yet. We set it in the consensus reactor, but
// when we add peer in Switch, the order we call reactors#AddPeer is
// different every time due to us using a map. Sometimes other reactors
// will be initialized before the consensus reactor. We should wait a few
// milliseconds and retry.
time.Sleep(PeerCatchupSleepIntervalMS * time.Millisecond)
continue
}
// If we suspect that the peer is lagging behind, at least by more than
// one block, we don't send the transaction immediately. This code
// reduces the mempool size and the recheck-tx rate of the receiving
// node. See [RFC 103] for an analysis on this optimization.
//
// [RFC 103]: https://github.com/cometbft/cometbft/pull/735
memTx := next.Value.(*mempoolTx)
if peerState.GetHeight() < memTx.Height()-1 {
time.Sleep(PeerCatchupSleepIntervalMS * time.Millisecond)
continue
}
// NOTE: Transaction batching was disabled due to
// https://github.com/tendermint/tendermint/issues/5796
if !memR.isSender(memTx.tx.Key(), peer.ID()) {
success := peer.Send(p2p.Envelope{
ChannelID: MempoolChannel,
Message: &protomem.Txs{Txs: [][]byte{memTx.tx}},
})
if !success {
time.Sleep(PeerCatchupSleepIntervalMS * time.Millisecond)
continue
}
}
select {
case <-next.NextWaitChan():
// see the start of the for loop for nil check
next = next.Next()
case <-peer.Quit():
return
case <-memR.Quit():
return
}
}
}
func (memR *Reactor) isSender(txKey types.TxKey, peerID p2p.ID) bool {
memR.txSendersMtx.Lock()
defer memR.txSendersMtx.Unlock()
sendersSet, ok := memR.txSenders[txKey]
return ok && sendersSet[peerID]
}
func (memR *Reactor) addSender(txKey types.TxKey, senderID p2p.ID) bool {
memR.txSendersMtx.Lock()
defer memR.txSendersMtx.Unlock()
if sendersSet, ok := memR.txSenders[txKey]; ok {
sendersSet[senderID] = true
return false
}
memR.txSenders[txKey] = map[p2p.ID]bool{senderID: true}
return true
}
func (memR *Reactor) removeSenders(txKey types.TxKey) {
memR.txSendersMtx.Lock()
defer memR.txSendersMtx.Unlock()
if memR.txSenders != nil {
delete(memR.txSenders, txKey)
}
}