forked from cometbft/cometbft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_util.go
342 lines (294 loc) · 8.11 KB
/
test_util.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package p2p
import (
"fmt"
"net"
"time"
"github.com/cometbft/cometbft/config"
"github.com/cometbft/cometbft/crypto/ed25519"
cmtnet "github.com/cometbft/cometbft/internal/net"
"github.com/cometbft/cometbft/libs/log"
"github.com/cometbft/cometbft/p2p/internal/fuzz"
na "github.com/cometbft/cometbft/p2p/netaddr"
ni "github.com/cometbft/cometbft/p2p/nodeinfo"
"github.com/cometbft/cometbft/p2p/nodekey"
"github.com/cometbft/cometbft/p2p/transport/tcp/conn"
)
const testCh = 0x01
// ------------------------------------------------
func AddPeerToSwitchPeerSet(sw *Switch, peer Peer) {
sw.peers.Add(peer) //nolint:errcheck // ignore error
}
func CreateRandomPeer(outbound bool) Peer {
addr, netAddr := na.CreateRoutableAddr()
p := &peer{
peerConn: peerConn{
outbound: outbound,
socketAddr: netAddr,
},
nodeInfo: mockNodeInfo{netAddr},
mconn: &conn.MConnection{},
metrics: NopMetrics(),
}
p.SetLogger(log.TestingLogger().With("peer", addr))
return p
}
// ------------------------------------------------------------------
// Connects switches via arbitrary net.Conn. Used for testing.
const TestHost = "localhost"
// MakeConnectedSwitches returns n switches, initialized according to the
// initSwitch function, and connected according to the connect function.
func MakeConnectedSwitches(cfg *config.P2PConfig,
n int,
initSwitch func(int, *Switch) *Switch,
connect func([]*Switch, int, int),
) []*Switch {
switches := MakeSwitches(cfg, n, initSwitch)
return StartAndConnectSwitches(switches, connect)
}
// MakeSwitches returns n switches.
// initSwitch defines how the i'th switch should be initialized (ie. with what reactors).
func MakeSwitches(
cfg *config.P2PConfig,
n int,
initSwitch func(int, *Switch) *Switch,
) []*Switch {
switches := make([]*Switch, n)
for i := 0; i < n; i++ {
switches[i] = MakeSwitch(cfg, i, initSwitch)
}
return switches
}
// StartAndConnectSwitches connects the switches according to the connect function.
// If connect==Connect2Switches, the switches will be fully connected.
// NOTE: panics if any switch fails to start.
func StartAndConnectSwitches(
switches []*Switch,
connect func([]*Switch, int, int),
) []*Switch {
if err := StartSwitches(switches); err != nil {
panic(err)
}
for i := 0; i < len(switches); i++ {
for j := i + 1; j < len(switches); j++ {
connect(switches, i, j)
}
}
return switches
}
// Connect2Switches will connect switches i and j via net.Pipe().
// Blocks until a connection is established.
// NOTE: caller ensures i and j are within bounds.
func Connect2Switches(switches []*Switch, i, j int) {
switchI := switches[i]
switchJ := switches[j]
c1, c2 := conn.NetPipe()
doneCh := make(chan struct{})
go func() {
err := switchI.addPeerWithConnection(c1)
if err != nil {
panic(err)
}
doneCh <- struct{}{}
}()
go func() {
err := switchJ.addPeerWithConnection(c2)
if err != nil {
panic(err)
}
doneCh <- struct{}{}
}()
<-doneCh
<-doneCh
}
// ConnectStarSwitches will connect switches c and j via net.Pipe().
func ConnectStarSwitches(c int) func([]*Switch, int, int) {
// Blocks until a connection is established.
// NOTE: caller ensures i and j is within bounds.
return func(switches []*Switch, i, j int) {
if i != c {
return
}
switchI := switches[i]
switchJ := switches[j]
c1, c2 := conn.NetPipe()
doneCh := make(chan struct{})
go func() {
err := switchI.addPeerWithConnection(c1)
if err != nil {
panic(err)
}
doneCh <- struct{}{}
}()
go func() {
err := switchJ.addPeerWithConnection(c2)
if err != nil {
panic(err)
}
doneCh <- struct{}{}
}()
<-doneCh
<-doneCh
}
}
func (sw *Switch) addPeerWithConnection(conn net.Conn) error {
pc, err := testInboundPeerConn(conn, sw.config)
if err != nil {
if err := conn.Close(); err != nil {
sw.Logger.Error("Error closing connection", "err", err)
}
return err
}
ni, err := handshake(sw.nodeInfo, conn, time.Second)
if err != nil {
if cErr := conn.Close(); cErr != nil {
sw.Logger.Error("Error closing connection", "err", cErr)
}
return err
}
p := newPeer(
pc,
MConnConfig(sw.config),
ni,
sw.reactorsByCh,
sw.msgTypeByChID,
sw.streamDescs,
sw.StopPeerForError,
)
if err = sw.addPeer(p); err != nil {
if cErr := conn.Close(); cErr != nil {
sw.Logger.Error("Error closing connection", "err", cErr)
}
return err
}
return nil
}
// StartSwitches calls sw.Start() for each given switch.
// It returns the first encountered error.
func StartSwitches(switches []*Switch) error {
for _, s := range switches {
err := s.Start() // start switch and reactors
if err != nil {
return err
}
}
return nil
}
func MakeSwitch(
cfg *config.P2PConfig,
i int,
initSwitch func(int, *Switch) *Switch,
opts ...SwitchOption,
) *Switch {
nk := nodekey.NodeKey{
PrivKey: ed25519.GenPrivKey(),
}
nodeInfo := testNodeInfo(nk.ID(), fmt.Sprintf("node%d", i))
addr, err := na.NewFromString(
na.IDAddrString(nk.ID(), nodeInfo.ListenAddr),
)
if err != nil {
panic(err)
}
t := &mockTransport{}
if err := t.Listen(*addr); err != nil {
panic(err)
}
// TODO: let the config be passed in?
sw := initSwitch(i, NewSwitch(cfg, t, opts...))
sw.SetLogger(log.TestingLogger().With("switch", i))
sw.SetNodeKey(&nk)
// reset channels
for ch := range sw.reactorsByCh {
if ch != testCh {
nodeInfo.Channels = append(nodeInfo.Channels, ch)
}
}
sw.SetNodeInfo(nodeInfo)
return sw
}
func testInboundPeerConn(
conn net.Conn,
config *config.P2PConfig,
// ourNodePrivKey crypto.PrivKey,
) (peerConn, error) {
return testPeerConn(conn, config, false, false, nil)
}
func testPeerConn(
rawConn net.Conn,
cfg *config.P2PConfig,
outbound, persistent bool,
// _ourNodePrivKey crypto.PrivKey,
socketAddr *na.NetAddr,
) (pc peerConn, err error) {
conn := rawConn
// Fuzz connection
if cfg.TestFuzz {
// so we have time to do peer handshakes and get set up
conn = fuzz.ConnAfterFromConfig(conn, 10*time.Second, cfg.TestFuzzConfig)
}
// Only the information we already have
return newPeerConn(outbound, persistent, conn, socketAddr), nil
}
// ----------------------------------------------------------------
// rand node info
type AddrBookMock struct {
Addrs map[string]struct{}
OurAddrs map[string]struct{}
PrivateAddrs map[string]struct{}
}
var _ AddrBook = (*AddrBookMock)(nil)
func (book *AddrBookMock) AddAddress(addr *na.NetAddr, _ *na.NetAddr) error {
book.Addrs[addr.String()] = struct{}{}
return nil
}
func (book *AddrBookMock) AddOurAddress(addr *na.NetAddr) {
book.OurAddrs[addr.String()] = struct{}{}
}
func (book *AddrBookMock) OurAddress(addr *na.NetAddr) bool {
_, ok := book.OurAddrs[addr.String()]
return ok
}
func (*AddrBookMock) MarkGood(nodekey.ID) {}
func (book *AddrBookMock) HasAddress(addr *na.NetAddr) bool {
_, ok := book.Addrs[addr.String()]
return ok
}
func (book *AddrBookMock) RemoveAddress(addr *na.NetAddr) {
delete(book.Addrs, addr.String())
}
func (*AddrBookMock) Save() {}
func (book *AddrBookMock) AddPrivateIDs(addrs []string) {
for _, addr := range addrs {
book.PrivateAddrs[addr] = struct{}{}
}
}
type mockNodeInfo struct {
addr *na.NetAddr
}
func (ni mockNodeInfo) ID() nodekey.ID { return ni.addr.ID }
func (ni mockNodeInfo) NetAddr() (*na.NetAddr, error) { return ni.addr, nil }
func (mockNodeInfo) Validate() error { return nil }
func (mockNodeInfo) CompatibleWith(ni.NodeInfo) error { return nil }
func (mockNodeInfo) Handshake(net.Conn, time.Duration) (ni.NodeInfo, error) { return nil, nil }
func testNodeInfo(id nodekey.ID, name string) ni.Default {
return ni.Default{
ProtocolVersion: ni.NewProtocolVersion(0, 0, 0),
DefaultNodeID: id,
ListenAddr: fmt.Sprintf("127.0.0.1:%d", getFreePort()),
Network: "testing",
Version: "1.2.3-rc0-deadbeef",
Channels: []byte{testCh},
Moniker: name,
Other: ni.DefaultOther{
TxIndex: "on",
RPCAddress: fmt.Sprintf("127.0.0.1:%d", getFreePort()),
},
}
}
func getFreePort() int {
port, err := cmtnet.GetFreePort()
if err != nil {
panic(err)
}
return port
}