diff --git a/p2p/protocol/autonatv2/autonat.go b/p2p/protocol/autonatv2/autonat.go index 9543bf2a8d..8c40899a36 100644 --- a/p2p/protocol/autonatv2/autonat.go +++ b/p2p/protocol/autonatv2/autonat.go @@ -142,11 +142,11 @@ func (an *AutoNAT) CheckReachability(ctx context.Context, highPriorityAddrs []ma func (an *AutoNAT) validPeer() peer.ID { peers := an.host.Peerstore().Peers() idx := 0 - for _, p := range an.host.Peerstore().Peers() { - if proto, err := an.host.Peerstore().SupportsProtocols(p, DialProtocol); len(proto) == 0 || err != nil { + for i := 0; i < len(peers); i++ { + if proto, err := an.host.Peerstore().SupportsProtocols(peers[i], DialProtocol); len(proto) == 0 || err != nil { continue } - peers[idx] = p + peers[idx] = peers[i] idx++ } if idx == 0 { diff --git a/p2p/protocol/autonatv2/client.go b/p2p/protocol/autonatv2/client.go index 680361395f..caaf9f45f7 100644 --- a/p2p/protocol/autonatv2/client.go +++ b/p2p/protocol/autonatv2/client.go @@ -18,11 +18,15 @@ import ( //go:generate protoc --go_out=. --go_opt=Mpbv2/autonat.proto=./pbv2 pbv2/autonat.proto +// Client implements the client for making dial requests for AutoNAT v2. It verifies successful +// dials and provides an option to send data for amplification attack prevention. type Client struct { host host.Host dialCharge []byte - mu sync.Mutex + mu sync.Mutex + // attemptQueues maps nonce to the channel for providing the local multiaddr of the connection + // the nonce was received on attemptQueues map[uint64]chan ma.Multiaddr } @@ -30,6 +34,8 @@ func NewClient(h host.Host) *Client { return &Client{host: h, dialCharge: make([]byte, 4096), attemptQueues: make(map[uint64]chan ma.Multiaddr)} } +// CheckReachability verifies address reachability with a AutoNAT v2 server p. It'll provide data for amplification +// attack prevention for high priority addresses and not for low priority addresses. func (ac *Client) CheckReachability(ctx context.Context, p peer.ID, highPriorityAddrs []ma.Multiaddr, lowPriorityAddrs []ma.Multiaddr) ([]Result, error) { ctx, cancel := context.WithTimeout(ctx, streamTimeout) defer cancel() diff --git a/p2p/protocol/autonatv2/server.go b/p2p/protocol/autonatv2/server.go index 484e182a5c..fca45328c6 100644 --- a/p2p/protocol/autonatv2/server.go +++ b/p2p/protocol/autonatv2/server.go @@ -18,7 +18,6 @@ import ( "golang.org/x/exp/rand" ) - type dataRequestPolicyFunc = func(s network.Stream, dialAddr ma.Multiaddr) bool const ( @@ -268,7 +267,7 @@ func (r *rateLimiter) Accept(p peer.ID) bool { func (r *rateLimiter) cleanup(p peer.ID, now time.Time) { idx := len(r.reqs) for i, t := range r.reqs { - if now.Sub(t).Minutes() <= 1 { + if now.Sub(t) < time.Minute { idx = i break } @@ -277,7 +276,7 @@ func (r *rateLimiter) cleanup(p peer.ID, now time.Time) { idx = len(r.peerReqs[p]) for i, t := range r.peerReqs[p] { - if now.Sub(t).Minutes() <= 1 { + if now.Sub(t) < time.Minute { idx = i break }