This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
306 lines (260 loc) · 7.47 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
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
package main
import (
"bufio"
"context"
"crypto/rand"
"flag"
"fmt"
"io"
"log"
mrand "math/rand"
"net/http"
_ "net/http/pprof"
"strings"
"sync/atomic"
"sync"
"time"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/peerstore"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"
wrtc "github.com/libp2p/go-libp2p/p2p/transport/webrtc"
"github.com/pkg/profile"
golog "github.com/ipfs/go-log/v2"
ma "github.com/multiformats/go-multiaddr"
)
// a global counter for the number of incoming streams
// processed
var incomingStreams uint32 = 0
const (
connectionOpenInterval = 1 * time.Second
streamOpenInterval = 100 * time.Millisecond
writeInterval = 500 * time.Millisecond
)
func main() {
tracer.Start(tracer.WithRuntimeMetrics())
defer tracer.Stop()
test()
select {}
}
func test() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// LibP2P code uses golog to log messages. They log with different
// string IDs (i.e. "swarm"). We can control the verbosity level for
// all loggers with:
golog.SetAllLoggers(golog.LevelInfo) // Change to INFO for extra info
// Parse options from the command line
listenF := flag.Int("l", 0, "wait for incoming connections")
targetF := flag.String("d", "", "target peer to dial")
insecureF := flag.Bool("insecure", false, "use an unencrypted connection")
tcpF := flag.String("t", "webrtc", "use quic instead of webrtc")
seedF := flag.Int64("seed", 0, "set random seed for id generation")
streamF := flag.Int("s", 1, "set number of streams")
profF := flag.Bool("f", false, "enable/disable cpu profile")
connF := flag.Int("c", 1, "total connections to open")
flag.Parse()
if *profF {
go func() {
http.ListenAndServe(":8081", nil)
}()
defer profile.Start(profile.ProfilePath(".")).Stop()
}
if *listenF == 0 && *targetF == "" {
log.Fatal("Please provide a port to bind on with -l")
}
if *targetF == "" {
// Make a host that listens on the given multiaddress
ha, err := makeBasicHost(*listenF, *tcpF, *insecureF, *seedF)
if err != nil {
log.Fatal(err)
}
startListener(ctx, ha, *listenF, *insecureF)
// Run until canceled.
<-ctx.Done()
} else {
var wg sync.WaitGroup
for i := 0; i < *connF; i++ {
go runSender(ctx, *targetF, *tcpF, *streamF, &wg)
time.Sleep(connectionOpenInterval)
}
wg.Wait()
}
}
// makeBasicHost creates a LibP2P host with a random peer ID listening on the
// given multiaddress. It won't encrypt the connection if insecure is true.
func makeBasicHost(listenPort int, tpt string, insecure bool, randseed int64, opts ...libp2p.Option) (host.Host, error) {
var r io.Reader
if randseed == 0 {
r = rand.Reader
} else {
r = mrand.New(mrand.NewSource(randseed))
}
// Generate a key pair for this host. We will use it at least
// to obtain a valid host ID.
priv, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, r)
if err != nil {
return nil, err
}
// setup infinite limits
mgr, err := rcmgr.NewResourceManager(rcmgr.NewFixedLimiter(rcmgr.InfiniteLimits))
if err != nil {
panic(err)
}
options := []libp2p.Option{
libp2p.DefaultTransports,
libp2p.Transport(wrtc.New),
libp2p.Identity(priv),
libp2p.DisableRelay(),
libp2p.ResourceManager(mgr),
}
options = append(options, opts...)
if listenPort != 0 {
fmtStr := "/ip4/0.0.0.0/udp/%d/webrtc"
switch tpt {
case "webrtc":
break
case "quic":
fmtStr = "/ip4/0.0.0.0/udp/%d/quic"
case "webtransport":
fmtStr = "/ip4/0.0.0.0/udp/%d/quic-v1/webtransport"
case "tcp":
fmtStr = "/ip4/0.0.0.0/tcp/%d"
case "websocket":
fmtStr = "/ip4/0.0.0.0/tcp/%d/ws"
default:
panic("bad transport: " + tpt)
}
options = append(options,
libp2p.ListenAddrStrings(fmt.Sprintf(fmtStr, listenPort)))
}
if insecure {
options = append(options, libp2p.NoSecurity)
}
return libp2p.New(options...)
}
func getHostAddress(ha host.Host) string {
// Build host multiaddress
hostAddr, _ := ma.NewMultiaddr(fmt.Sprintf("/p2p/%s", ha.ID().Pretty()))
// Now we can build a full multiaddress to reach this host
// by encapsulating both addresses:
if len(ha.Addrs()) == 0 {
return hostAddr.String()
}
addr := ha.Addrs()[0]
return addr.Encapsulate(hostAddr).String()
}
func startListener(ctx context.Context, ha host.Host, listenPort int, insecure bool) {
fullAddr := getHostAddress(ha)
log.Printf("I am %s\n", fullAddr)
// Set a stream handler on host A. /echo/1.0.0 is
// a user-defined protocol name.
ha.SetStreamHandler("/echo/1.0.0", func(s network.Stream) {
if err := doEcho(s); err != nil {
log.Println("reset stream, echo error: ", err)
log.Println("calling reset")
s.Reset()
} else {
s.Close()
}
})
log.Println("listening for connections")
}
func runSender(ctx context.Context, targetPeer string, tpt string, streamCount int, wg *sync.WaitGroup) {
ha, err := makeBasicHost(0, tpt, false, 1)
if err != nil {
panic(err)
}
fullAddr := getHostAddress(ha)
log.Printf("I am %s\n", fullAddr)
// Set a stream handler on host A. /echo/1.0.0 is
// a user-defined protocol name.
ha.SetStreamHandler("/echo/1.0.0", func(s network.Stream) {
log.Println("sender received new stream")
if err := doEcho(s); err != nil {
log.Println("error echo: ", err)
s.Reset()
} else {
log.Println("sender closing")
s.Close()
}
})
// Turn the targetPeer into a multiaddr.
maddr, err := ma.NewMultiaddr(targetPeer)
if err != nil {
log.Println("bad multiaddr: ", err)
return
}
// Extract the peer ID from the multiaddr.
info, err := peer.AddrInfoFromP2pAddr(maddr)
if err != nil {
log.Println(err)
return
}
log.Println(info)
// We have a peer ID and a targetAddr so we add it to the peerstore
// so LibP2P knows how to contact it
ha.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.PermanentAddrTTL)
log.Println("sender opening connection")
sendStr := strings.Builder{}
for i := 0; i < 1023; i++ {
sendStr.WriteRune('0')
}
sendStr.WriteRune('\n')
for i := 0; i < streamCount; i++ {
wg.Add(1)
idx := i
go func() {
defer wg.Done()
// make a new stream from host B to host A
// it should be handled on host A by the handler we set above because
// we use the same /echo/1.0.0 protocol
s, err := ha.NewStream(context.Background(), info.ID, "/echo/1.0.0")
if err != nil {
log.Printf("error opening stream: %v\n", err)
return
}
reader := bufio.NewReader(s)
for {
s.SetDeadline(time.Now().Add(5 * time.Second))
_, err = s.Write([]byte(sendStr.String()))
if err != nil {
log.Printf("[%d] error writing to remote: %v\n", idx, err)
return
}
_, err = reader.ReadString('\n')
if err != nil {
log.Printf("[%d] error reading from remote: %v\n", idx, err)
return
}
time.Sleep(writeInterval)
}
}()
time.Sleep(streamOpenInterval)
}
}
// doEcho reads a line of data a stream and writes it back
func doEcho(s network.Stream) error {
sn := atomic.AddUint32(&incomingStreams, 1)
log.Printf("processing incoming stream number: %d\n", sn)
buf := bufio.NewReader(s)
for {
s.SetDeadline(time.Now().Add(5 * time.Second))
str, err := buf.ReadString('\n')
if err != nil {
if err == io.EOF {
return nil
}
return err
}
_, err = s.Write([]byte(str))
if err != nil {
fmt.Println("error sending: %w", err)
return err
}
}
}