From 3bd747ee20d28c9073fe458b83bd025461a78e4c Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 24 Oct 2024 10:59:35 +0400 Subject: [PATCH] refactor(p2p/netaddress)!: move to netaddr (#4303) Refs #4302 **Important: no logic has been changed; just moving stuff and updating interfaces.** ## Public API Changes * Package Renaming: The `netaddress` package is renamed to `netaddr`. * Removal of Prefix: The `NetAddress` prefix has been removed from relevant types and methods for better alignment with Go naming conventions. --- cmd/cometbft/commands/testnet.go | 4 +- .../explanation/core/running-in-production.md | 4 +- node/node.go | 6 +- node/setup.go | 6 +- p2p/errors.go | 6 +- p2p/handshake.go | 10 +- p2p/mock/peer.go | 20 +-- p2p/mock_transport.go | 12 +- p2p/mocks/peer.go | 10 +- p2p/{netaddress => netaddr}/errors.go | 18 +-- .../netaddress.go => netaddr/netaddr.go} | 142 +++++++++--------- .../netaddr_test.go} | 40 ++--- p2p/nodeinfo/node_info.go | 16 +- p2p/nodeinfo/node_info_test.go | 10 +- p2p/peer.go | 14 +- p2p/peer_set_test.go | 36 ++--- p2p/peer_test.go | 16 +- p2p/pex/addrbook.go | 70 ++++----- p2p/pex/addrbook_test.go | 62 ++++---- p2p/pex/errors.go | 20 +-- p2p/pex/known_address.go | 20 +-- p2p/pex/pex_reactor.go | 46 +++--- p2p/pex/pex_reactor_test.go | 28 ++-- p2p/switch.go | 56 +++---- p2p/switch_test.go | 20 +-- p2p/test_util.go | 22 +-- p2p/transport.go | 12 +- p2p/transport/tcp/errors.go | 8 +- p2p/transport/tcp/tcp.go | 24 +-- p2p/transport/tcp/tcp_test.go | 26 ++-- rpc/core/net.go | 4 +- 31 files changed, 394 insertions(+), 394 deletions(-) rename p2p/{netaddress => netaddr}/errors.go (74%) rename p2p/{netaddress/netaddress.go => netaddr/netaddr.go} (68%) rename p2p/{netaddress/netaddress_test.go => netaddr/netaddr_test.go} (81%) diff --git a/cmd/cometbft/commands/testnet.go b/cmd/cometbft/commands/testnet.go index 802b9698e73..2197bf02bb9 100644 --- a/cmd/cometbft/commands/testnet.go +++ b/cmd/cometbft/commands/testnet.go @@ -13,7 +13,7 @@ import ( cfg "github.com/cometbft/cometbft/config" cmtrand "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/libs/bytes" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" "github.com/cometbft/cometbft/privval" "github.com/cometbft/cometbft/types" @@ -256,7 +256,7 @@ func persistentPeersString(config *cfg.Config) (string, error) { if err != nil { return "", err } - persistentPeers[i] = na.IDAddressString(nk.ID(), fmt.Sprintf("%s:%d", hostnameOrIP(i), p2pPort)) + persistentPeers[i] = na.IDAddrString(nk.ID(), fmt.Sprintf("%s:%d", hostnameOrIP(i), p2pPort)) } return strings.Join(persistentPeers, ","), nil } diff --git a/docs/explanation/core/running-in-production.md b/docs/explanation/core/running-in-production.md index 2c8cde9052c..71384a007bb 100644 --- a/docs/explanation/core/running-in-production.md +++ b/docs/explanation/core/running-in-production.md @@ -20,7 +20,7 @@ CometBFT keeps multiple distinct databases in the `$CMTHOME/data`: used to temporarily store intermediate results during block processing. - `tx_index.db`: Indexes transactions and by tx hash and height. The tx results are indexed if they are added to the `FinalizeBlock` response in the application. -> By default, CometBFT will only index transactions by their hash and height, if you want the result events to be indexed, see [indexing transactions](../../guides/app-dev/indexing-transactions.md#adding-events) +> By default, CometBFT will only index transactions by their hash and height, if you want the result events to be indexed, see [indexing transactions](../../guides/app-dev/indexing-transactions.md#adding-events) for details. Applications can expose block pruning strategies to the node operator. @@ -382,7 +382,7 @@ application to process the committed block. By default, CometBFT checks whenever a peer's address is routable before saving it to the address book. The address is considered as routable if the IP -is [valid and within allowed ranges](https://github.com/cometbft/cometbft/blob/main/p2p/netaddress.go#L258). +is [valid and within allowed ranges](https://github.com/cometbft/cometbft/blob/main/p2p/netaddr/netaddr.go#L258). This may not be the case for private or local networks, where your IP range is usually strictly limited and private. If that case, you need to set `addr_book_strict` diff --git a/node/node.go b/node/node.go index 5351ff02c2c..a2b6cc72df9 100644 --- a/node/node.go +++ b/node/node.go @@ -28,7 +28,7 @@ import ( "github.com/cometbft/cometbft/light" mempl "github.com/cometbft/cometbft/mempool" "github.com/cometbft/cometbft/p2p" - na "github.com/cometbft/cometbft/p2p/netaddress" + 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/pex" @@ -530,7 +530,7 @@ func NewNodeWithCliParams(ctx context.Context, // // We need to set Seeds and PersistentPeers on the switch, // since it needs to be able to use these (and their DNS names) - // even if the PEX is off. We can include the DNS name in the NetAddress, + // even if the PEX is off. We can include the DNS name in the na.NetAddr, // but it would still be nice to have a clear list of the current "PersistentPeers" // somewhere that we can return with net_info. // @@ -613,7 +613,7 @@ func (n *Node) OnStart() error { } // Start the transport. - addr, err := na.NewNetAddressString(na.IDAddressString(n.nodeKey.ID(), n.config.P2P.ListenAddress)) + addr, err := na.NewFromString(na.IDAddrString(n.nodeKey.ID(), n.config.P2P.ListenAddress)) if err != nil { return err } diff --git a/node/setup.go b/node/setup.go index 11c3415a649..3226ce63bfd 100644 --- a/node/setup.go +++ b/node/setup.go @@ -26,7 +26,7 @@ import ( "github.com/cometbft/cometbft/light" mempl "github.com/cometbft/cometbft/mempool" "github.com/cometbft/cometbft/p2p" - na "github.com/cometbft/cometbft/p2p/netaddress" + 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/pex" @@ -519,14 +519,14 @@ func createAddrBookAndSetOnSwitch(config *cfg.Config, sw *p2p.Switch, // Add ourselves to addrbook to prevent dialing ourselves if config.P2P.ExternalAddress != "" { - addr, err := na.NewNetAddressString(na.IDAddressString(nodeKey.ID(), config.P2P.ExternalAddress)) + addr, err := na.NewFromString(na.IDAddrString(nodeKey.ID(), config.P2P.ExternalAddress)) if err != nil { return nil, fmt.Errorf("p2p.external_address is incorrect: %w", err) } addrBook.AddOurAddress(addr) } if config.P2P.ListenAddress != "" { - addr, err := na.NewNetAddressString(na.IDAddressString(nodeKey.ID(), config.P2P.ListenAddress)) + addr, err := na.NewFromString(na.IDAddrString(nodeKey.ID(), config.P2P.ListenAddress)) if err != nil { return nil, fmt.Errorf("p2p.laddr is incorrect: %w", err) } diff --git a/p2p/errors.go b/p2p/errors.go index 422cd7adf1e..fb1f438ee9b 100644 --- a/p2p/errors.go +++ b/p2p/errors.go @@ -4,7 +4,7 @@ import ( "fmt" "net" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" ) @@ -30,7 +30,7 @@ func (e ErrSwitchDuplicatePeerIP) Error() string { // ErrSwitchConnectToSelf to be raised when trying to connect to itself. type ErrSwitchConnectToSelf struct { - Addr *na.NetAddress + Addr *na.NetAddr } func (e ErrSwitchConnectToSelf) Error() string { @@ -38,7 +38,7 @@ func (e ErrSwitchConnectToSelf) Error() string { } type ErrSwitchAuthenticationFailure struct { - Dialed *na.NetAddress + Dialed *na.NetAddr Got nodekey.ID } diff --git a/p2p/handshake.go b/p2p/handshake.go index 6f2959e6048..5f1783a9c18 100644 --- a/p2p/handshake.go +++ b/p2p/handshake.go @@ -7,7 +7,7 @@ import ( tmp2p "github.com/cometbft/cometbft/api/cometbft/p2p/v1" "github.com/cometbft/cometbft/libs/protoio" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" ni "github.com/cometbft/cometbft/p2p/nodeinfo" "github.com/cometbft/cometbft/p2p/nodekey" ) @@ -15,7 +15,7 @@ import ( // ErrRejected indicates that a Peer was rejected carrying additional // information as to the reason. type ErrRejected struct { - addr na.NetAddress + addr na.NetAddr conn net.Conn err error id nodekey.ID @@ -27,8 +27,8 @@ type ErrRejected struct { isSelf bool } -// Addr returns the NetAddress for the rejected Peer. -func (e ErrRejected) Addr() na.NetAddress { +// Addr returns the network address for the rejected Peer. +func (e ErrRejected) Addr() na.NetAddr { return e.addr } @@ -136,7 +136,7 @@ func handshake(ourNodeInfo ni.NodeInfo, c net.Conn, handshakeTimeout time.Durati // Reject self. if ourNodeInfo.ID() == nodeInfo.ID() { return nil, ErrRejected{ - addr: *na.NewNetAddress(nodeInfo.ID(), c.RemoteAddr()), + addr: *na.New(nodeInfo.ID(), c.RemoteAddr()), conn: c, id: nodeInfo.ID(), isSelf: true, diff --git a/p2p/mock/peer.go b/p2p/mock/peer.go index 996401d470a..6b7a2c01131 100644 --- a/p2p/mock/peer.go +++ b/p2p/mock/peer.go @@ -6,7 +6,7 @@ import ( "github.com/cometbft/cometbft/crypto/ed25519" "github.com/cometbft/cometbft/libs/service" "github.com/cometbft/cometbft/p2p" - na "github.com/cometbft/cometbft/p2p/netaddress" + 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" @@ -16,7 +16,7 @@ type Peer struct { *service.BaseService ip net.IP id nodekey.ID - addr *na.NetAddress + addr *na.NetAddr kv map[string]any Outbound, Persistent bool server, client net.Conn @@ -25,11 +25,11 @@ type Peer struct { // NewPeer creates and starts a new mock peer. If the ip // is nil, random routable address is used. func NewPeer(ip net.IP) *Peer { - var netAddr *na.NetAddress + var netAddr *na.NetAddr if ip == nil { _, netAddr = na.CreateRoutableAddr() } else { - netAddr = na.NewNetAddressIPPort(ip, 26656) + netAddr = na.NewFromIPPort(ip, 26656) } nodeKey := nodekey.NodeKey{PrivKey: ed25519.GenPrivKey()} netAddr.ID = nodeKey.ID() @@ -77,9 +77,9 @@ func (mp *Peer) Get(key string) any { func (mp *Peer) Set(key string, value any) { mp.kv[key] = value } -func (mp *Peer) RemoteIP() net.IP { return mp.ip } -func (mp *Peer) SocketAddr() *na.NetAddress { return mp.addr } -func (mp *Peer) RemoteAddr() net.Addr { return &net.TCPAddr{IP: mp.ip, Port: 8800} } -func (mp *Peer) Conn() net.Conn { return mp.server } -func (*Peer) SetRemovalFailed() {} -func (*Peer) GetRemovalFailed() bool { return false } +func (mp *Peer) RemoteIP() net.IP { return mp.ip } +func (mp *Peer) SocketAddr() *na.NetAddr { return mp.addr } +func (mp *Peer) RemoteAddr() net.Addr { return &net.TCPAddr{IP: mp.ip, Port: 8800} } +func (mp *Peer) Conn() net.Conn { return mp.server } +func (*Peer) SetRemovalFailed() {} +func (*Peer) GetRemovalFailed() bool { return false } diff --git a/p2p/mock_transport.go b/p2p/mock_transport.go index 7b5f815c04a..8b059437a1b 100644 --- a/p2p/mock_transport.go +++ b/p2p/mock_transport.go @@ -4,15 +4,15 @@ import ( "net" "time" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" ) type mockTransport struct { ln net.Listener - addr na.NetAddress + addr na.NetAddr } -func (t *mockTransport) Listen(addr na.NetAddress) error { +func (t *mockTransport) Listen(addr na.NetAddr) error { ln, err := net.Listen("tcp", addr.DialString()) if err != nil { return err @@ -22,16 +22,16 @@ func (t *mockTransport) Listen(addr na.NetAddress) error { return nil } -func (t *mockTransport) NetAddress() na.NetAddress { +func (t *mockTransport) NetAddr() na.NetAddr { return t.addr } -func (t *mockTransport) Accept() (net.Conn, *na.NetAddress, error) { +func (t *mockTransport) Accept() (net.Conn, *na.NetAddr, error) { c, err := t.ln.Accept() return c, nil, err } -func (*mockTransport) Dial(addr na.NetAddress) (net.Conn, error) { +func (*mockTransport) Dial(addr na.NetAddr) (net.Conn, error) { return addr.DialTimeout(time.Second) } diff --git a/p2p/mocks/peer.go b/p2p/mocks/peer.go index ba8762662bd..332d64028b0 100644 --- a/p2p/mocks/peer.go +++ b/p2p/mocks/peer.go @@ -10,7 +10,7 @@ import ( net "net" - netaddress "github.com/cometbft/cometbft/p2p/netaddress" + netaddr "github.com/cometbft/cometbft/p2p/netaddr" nodeinfo "github.com/cometbft/cometbft/p2p/nodeinfo" @@ -350,19 +350,19 @@ func (_m *Peer) SetRemovalFailed() { } // SocketAddr provides a mock function with given fields: -func (_m *Peer) SocketAddr() *netaddress.NetAddress { +func (_m *Peer) SocketAddr() *netaddr.NetAddr { ret := _m.Called() if len(ret) == 0 { panic("no return value specified for SocketAddr") } - var r0 *netaddress.NetAddress - if rf, ok := ret.Get(0).(func() *netaddress.NetAddress); ok { + var r0 *netaddr.NetAddr + if rf, ok := ret.Get(0).(func() *netaddr.NetAddr); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*netaddress.NetAddress) + r0 = ret.Get(0).(*netaddr.NetAddr) } } diff --git a/p2p/netaddress/errors.go b/p2p/netaddr/errors.go similarity index 74% rename from p2p/netaddress/errors.go rename to p2p/netaddr/errors.go index d653ea5863e..ed0492f568e 100644 --- a/p2p/netaddress/errors.go +++ b/p2p/netaddr/errors.go @@ -1,4 +1,4 @@ -package netaddress +package netaddr import ( "errors" @@ -13,35 +13,35 @@ var ( ErrInvalidIP = errors.New("invalid IP address") ) -type ErrNetAddressNoID struct { +type ErrNoID struct { Addr string } -func (e ErrNetAddressNoID) Error() string { +func (e ErrNoID) Error() string { return fmt.Sprintf("address (%s) does not contain ID", e.Addr) } -type ErrNetAddressInvalid struct { +type ErrInvalid struct { Addr string Err error } -func (e ErrNetAddressInvalid) Error() string { +func (e ErrInvalid) Error() string { return fmt.Sprintf("invalid address (%s): %v", e.Addr, e.Err) } -func (e ErrNetAddressInvalid) Unwrap() error { return e.Err } +func (e ErrInvalid) Unwrap() error { return e.Err } -type ErrNetAddressLookup struct { +type ErrLookup struct { Addr string Err error } -func (e ErrNetAddressLookup) Error() string { +func (e ErrLookup) Error() string { return fmt.Sprintf("error looking up host (%s): %v", e.Addr, e.Err) } -func (e ErrNetAddressLookup) Unwrap() error { return e.Err } +func (e ErrLookup) Unwrap() error { return e.Err } type ErrInvalidPort struct { Port uint32 diff --git a/p2p/netaddress/netaddress.go b/p2p/netaddr/netaddr.go similarity index 68% rename from p2p/netaddress/netaddress.go rename to p2p/netaddr/netaddr.go index ece626f2cf7..aeb46a19ca5 100644 --- a/p2p/netaddress/netaddress.go +++ b/p2p/netaddr/netaddr.go @@ -2,7 +2,7 @@ // Originally Copyright (c) 2013-2014 Conformal Systems LLC. // https://github.com/conformal/btcd/blob/master/LICENSE -package netaddress +package netaddr import ( "encoding/hex" @@ -18,37 +18,37 @@ import ( "github.com/cometbft/cometbft/p2p/nodekey" ) -// EmptyNetAddress defines the string representation of an empty NetAddress. -const EmptyNetAddress = "" +// Empty defines the string representation of an empty NetAddress. +const Empty = "" -// NetAddress defines information about a peer on the network +// NetAddr defines information about a peer on the network // including its ID, IP address, and port. -type NetAddress struct { +type NetAddr struct { ID nodekey.ID `json:"id"` IP net.IP `json:"ip"` Port uint16 `json:"port"` } -// IDAddressString returns id@hostPort. It strips the leading +// IDAddrString returns id@hostPort. It strips the leading // protocol from protocolHostPort if it exists. -func IDAddressString(id nodekey.ID, protocolHostPort string) string { +func IDAddrString(id nodekey.ID, protocolHostPort string) string { hostPort := removeProtocolIfDefined(protocolHostPort) return fmt.Sprintf("%s@%s", id, hostPort) } -// NewNetAddress returns a new NetAddress using the provided TCP +// New returns a new address using the provided TCP // address. When testing, other net.Addr (except TCP) will result in // using 0.0.0.0:0. When normal run, other net.Addr (except TCP) will // panic. Panics if ID is invalid. // TODO: socks proxies? -func NewNetAddress(id nodekey.ID, addr net.Addr) *NetAddress { +func New(id nodekey.ID, addr net.Addr) *NetAddr { tcpAddr, ok := addr.(*net.TCPAddr) if !ok { if flag.Lookup("test.v") == nil { // normal run panic(fmt.Sprintf("Only TCPAddrs are supported. Got: %v", addr)) } // in testing - netAddr := NewNetAddressIPPort(net.IP("127.0.0.1"), 0) + netAddr := NewFromIPPort(net.IP("127.0.0.1"), 0) netAddr.ID = id return netAddr } @@ -59,25 +59,25 @@ func NewNetAddress(id nodekey.ID, addr net.Addr) *NetAddress { ip := tcpAddr.IP port := uint16(tcpAddr.Port) - na := NewNetAddressIPPort(ip, port) + na := NewFromIPPort(ip, port) na.ID = id return na } -// NewNetAddressString returns a new NetAddress using the provided address in +// NewFromString returns a new address using the provided address in // the form of "ID@IP:Port". // Also resolves the host if host is not an IP. -// Errors are of type ErrNetAddressXxx where Xxx is in (NoID, Invalid, Lookup). -func NewNetAddressString(addr string) (*NetAddress, error) { +// Errors are of type ErrXxx where Xxx is in (NoID, Invalid, Lookup). +func NewFromString(addr string) (*NetAddr, error) { addrWithoutProtocol := removeProtocolIfDefined(addr) spl := strings.Split(addrWithoutProtocol, "@") if len(spl) != 2 { - return nil, ErrNetAddressInvalid{Addr: addr, Err: ErrNetAddressNoID{addr}} + return nil, ErrInvalid{Addr: addr, Err: ErrNoID{addr}} } // get ID if err := ValidateID(nodekey.ID(spl[0])); err != nil { - return nil, ErrNetAddressInvalid{addrWithoutProtocol, err} + return nil, ErrInvalid{addrWithoutProtocol, err} } var id nodekey.ID id, addrWithoutProtocol = nodekey.ID(spl[0]), spl[1] @@ -85,10 +85,10 @@ func NewNetAddressString(addr string) (*NetAddress, error) { // get host and port host, portStr, err := net.SplitHostPort(addrWithoutProtocol) if err != nil { - return nil, ErrNetAddressInvalid{addrWithoutProtocol, err} + return nil, ErrInvalid{addrWithoutProtocol, err} } if len(host) == 0 { - return nil, ErrNetAddressInvalid{ + return nil, ErrInvalid{ addrWithoutProtocol, ErrEmptyHost, } @@ -98,28 +98,28 @@ func NewNetAddressString(addr string) (*NetAddress, error) { if ip == nil { ips, err := net.LookupIP(host) if err != nil { - return nil, ErrNetAddressLookup{host, err} + return nil, ErrLookup{host, err} } ip = ips[0] } port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { - return nil, ErrNetAddressInvalid{portStr, err} + return nil, ErrInvalid{portStr, err} } - na := NewNetAddressIPPort(ip, uint16(port)) + na := NewFromIPPort(ip, uint16(port)) na.ID = id return na, nil } -// NewNetAddressStrings returns an array of NetAddress'es build using +// NewFromStrings returns an array of Addr'es build using // the provided strings. -func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error) { - netAddrs := make([]*NetAddress, 0) +func NewFromStrings(addrs []string) ([]*NetAddr, []error) { + netAddrs := make([]*NetAddr, 0) errs := make([]error, 0) for _, addr := range addrs { - netAddr, err := NewNetAddressString(addr) + netAddr, err := NewFromString(addr) if err != nil { errs = append(errs, err) } else { @@ -129,37 +129,37 @@ func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error) { return netAddrs, errs } -// NewNetAddressIPPort returns a new NetAddress using the provided IP +// NewFromIPPort returns a new Addr using the provided IP // and port number. -func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress { - return &NetAddress{ +func NewFromIPPort(ip net.IP, port uint16) *NetAddr { + return &NetAddr{ IP: ip, Port: port, } } -// NetAddressFromProto converts a Protobuf NetAddress into a native struct. -func NetAddressFromProto(pb tmp2p.NetAddress) (*NetAddress, error) { //nolint:revive +// NewFromProto converts a Protobuf NetAddress into a native struct. +func NewFromProto(pb tmp2p.NetAddress) (*NetAddr, error) { ip := net.ParseIP(pb.IP) if ip == nil { - return nil, ErrNetAddressInvalid{Addr: pb.IP, Err: ErrInvalidIP} + return nil, ErrInvalid{Addr: pb.IP, Err: ErrInvalidIP} } if pb.Port >= 1<<16 { - return nil, ErrNetAddressInvalid{Addr: pb.IP, Err: ErrInvalidPort{pb.Port}} + return nil, ErrInvalid{Addr: pb.IP, Err: ErrInvalidPort{pb.Port}} } - return &NetAddress{ + return &NetAddr{ ID: nodekey.ID(pb.ID), IP: ip, Port: uint16(pb.Port), }, nil } -// NetAddressesFromProto converts a slice of Protobuf NetAddresses into a native slice. -func NetAddressesFromProto(pbs []tmp2p.NetAddress) ([]*NetAddress, error) { - nas := make([]*NetAddress, 0, len(pbs)) +// AddrsFromProtos converts a slice of Protobuf NetAddresses into a native slice. +func AddrsFromProtos(pbs []tmp2p.NetAddress) ([]*NetAddr, error) { + nas := make([]*NetAddr, 0, len(pbs)) for _, pb := range pbs { - na, err := NetAddressFromProto(pb) + na, err := NewFromProto(pb) if err != nil { return nil, err } @@ -168,8 +168,8 @@ func NetAddressesFromProto(pbs []tmp2p.NetAddress) ([]*NetAddress, error) { return nas, nil } -// NetAddressesToProto converts a slice of NetAddresses into a Protobuf slice. -func NetAddressesToProto(nas []*NetAddress) []tmp2p.NetAddress { +// AddrsToProtos converts a slice of addresses into a Protobuf slice. +func AddrsToProtos(nas []*NetAddr) []tmp2p.NetAddress { pbs := make([]tmp2p.NetAddress, 0, len(nas)) for _, na := range nas { if na != nil { @@ -179,8 +179,8 @@ func NetAddressesToProto(nas []*NetAddress) []tmp2p.NetAddress { return pbs } -// ToProto converts a NetAddress to Protobuf. -func (na *NetAddress) ToProto() tmp2p.NetAddress { +// ToProto converts an Addr to Protobuf. +func (na *NetAddr) ToProto() tmp2p.NetAddress { return tmp2p.NetAddress{ ID: string(na.ID), IP: na.IP.String(), @@ -190,16 +190,16 @@ func (na *NetAddress) ToProto() tmp2p.NetAddress { // Equals reports whether na and other are the same addresses, // including their ID, IP, and Port. -func (na *NetAddress) Equals(other any) bool { - if o, ok := other.(*NetAddress); ok { +func (na *NetAddr) Equals(other any) bool { + if o, ok := other.(*NetAddr); ok { return na.String() == o.String() } return false } // Same returns true is na has the same non-empty ID or DialString as other. -func (na *NetAddress) Same(other any) bool { - if o, ok := other.(*NetAddress); ok { +func (na *NetAddr) Same(other any) bool { + if o, ok := other.(*NetAddr); ok { if na.DialString() == o.DialString() { return true } @@ -211,22 +211,22 @@ func (na *NetAddress) Same(other any) bool { } // String representation: @:. -func (na *NetAddress) String() string { +func (na *NetAddr) String() string { if na == nil { - return EmptyNetAddress + return Empty } addrStr := na.DialString() if na.ID != "" { - addrStr = IDAddressString(na.ID, addrStr) + addrStr = IDAddrString(na.ID, addrStr) } return addrStr } -func (na *NetAddress) DialString() string { +func (na *NetAddr) DialString() string { if na == nil { - return "" + return Empty } return net.JoinHostPort( na.IP.String(), @@ -235,7 +235,7 @@ func (na *NetAddress) DialString() string { } // Dial calls net.Dial on the address. -func (na *NetAddress) Dial() (net.Conn, error) { +func (na *NetAddr) Dial() (net.Conn, error) { conn, err := net.Dial("tcp", na.DialString()) if err != nil { return nil, err @@ -244,7 +244,7 @@ func (na *NetAddress) Dial() (net.Conn, error) { } // DialTimeout calls net.DialTimeout on the address. -func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error) { +func (na *NetAddr) DialTimeout(timeout time.Duration) (net.Conn, error) { conn, err := net.DialTimeout("tcp", na.DialString(), timeout) if err != nil { return nil, err @@ -253,7 +253,7 @@ func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error) { } // Routable returns true if the address is routable. -func (na *NetAddress) Routable() bool { +func (na *NetAddr) Routable() bool { if err := na.Valid(); err != nil { return false } @@ -264,7 +264,7 @@ func (na *NetAddress) Routable() bool { // For IPv4 these are either a 0 or all bits set address. For IPv6 a zero // address or one that matches the RFC3849 documentation address format. -func (na *NetAddress) Valid() error { +func (na *NetAddr) Valid() error { if err := ValidateID(na.ID); err != nil { return ErrInvalidPeerID{na.ID, err} } @@ -273,24 +273,24 @@ func (na *NetAddress) Valid() error { return ErrNoIP } if na.IP.IsUnspecified() || na.RFC3849() || na.IP.Equal(net.IPv4bcast) { - return ErrNetAddressInvalid{na.IP.String(), ErrInvalidIP} + return ErrInvalid{na.IP.String(), ErrInvalidIP} } return nil } // HasID returns true if the address has an ID. // NOTE: It does not check whether the ID is valid or not. -func (na *NetAddress) HasID() bool { +func (na *NetAddr) HasID() bool { return string(na.ID) != "" } // Local returns true if it is a local address. -func (na *NetAddress) Local() bool { +func (na *NetAddr) Local() bool { return na.IP.IsLoopback() || zero4.Contains(na.IP) } // ReachabilityTo checks whenever o can be reached from na. -func (na *NetAddress) ReachabilityTo(o *NetAddress) int { +func (na *NetAddr) ReachabilityTo(o *NetAddr) int { const ( unreachable = 0 Default = iota @@ -385,21 +385,21 @@ func ipNet(ip string, ones, bits int) net.IPNet { return net.IPNet{IP: net.ParseIP(ip), Mask: net.CIDRMask(ones, bits)} } -func (na *NetAddress) RFC1918() bool { +func (na *NetAddr) RFC1918() bool { return rfc1918_10.Contains(na.IP) || rfc1918_192.Contains(na.IP) || rfc1918_172.Contains(na.IP) } -func (na *NetAddress) RFC3849() bool { return rfc3849.Contains(na.IP) } -func (na *NetAddress) RFC3927() bool { return rfc3927.Contains(na.IP) } -func (na *NetAddress) RFC3964() bool { return rfc3964.Contains(na.IP) } -func (na *NetAddress) RFC4193() bool { return rfc4193.Contains(na.IP) } -func (na *NetAddress) RFC4380() bool { return rfc4380.Contains(na.IP) } -func (na *NetAddress) RFC4843() bool { return rfc4843.Contains(na.IP) } -func (na *NetAddress) RFC4862() bool { return rfc4862.Contains(na.IP) } -func (na *NetAddress) RFC6052() bool { return rfc6052.Contains(na.IP) } -func (na *NetAddress) RFC6145() bool { return rfc6145.Contains(na.IP) } -func (na *NetAddress) OnionCatTor() bool { return onionCatNet.Contains(na.IP) } +func (na *NetAddr) RFC3849() bool { return rfc3849.Contains(na.IP) } +func (na *NetAddr) RFC3927() bool { return rfc3927.Contains(na.IP) } +func (na *NetAddr) RFC3964() bool { return rfc3964.Contains(na.IP) } +func (na *NetAddr) RFC4193() bool { return rfc4193.Contains(na.IP) } +func (na *NetAddr) RFC4380() bool { return rfc4380.Contains(na.IP) } +func (na *NetAddr) RFC4843() bool { return rfc4843.Contains(na.IP) } +func (na *NetAddr) RFC4862() bool { return rfc4862.Contains(na.IP) } +func (na *NetAddr) RFC6052() bool { return rfc6052.Contains(na.IP) } +func (na *NetAddr) RFC6145() bool { return rfc6145.Contains(na.IP) } +func (na *NetAddr) OnionCatTor() bool { return onionCatNet.Contains(na.IP) } func removeProtocolIfDefined(addr string) string { if strings.Contains(addr, "://") { @@ -423,7 +423,7 @@ func ValidateID(id nodekey.ID) error { } // Used for testing. -func CreateRoutableAddr() (addr string, netAddr *NetAddress) { +func CreateRoutableAddr() (addr string, netAddr *NetAddr) { for { var err error addr = fmt.Sprintf("%X@%v.%v.%v.%v:26656", @@ -432,7 +432,7 @@ func CreateRoutableAddr() (addr string, netAddr *NetAddress) { cmtrand.Int()%256, cmtrand.Int()%256, cmtrand.Int()%256) - netAddr, err = NewNetAddressString(addr) + netAddr, err = NewFromString(addr) if err != nil { panic(err) } diff --git a/p2p/netaddress/netaddress_test.go b/p2p/netaddr/netaddr_test.go similarity index 81% rename from p2p/netaddress/netaddress_test.go rename to p2p/netaddr/netaddr_test.go index b7287ccc8e2..eac3e30bb0a 100644 --- a/p2p/netaddress/netaddress_test.go +++ b/p2p/netaddr/netaddr_test.go @@ -1,4 +1,4 @@ -package netaddress +package netaddr import ( "net" @@ -9,11 +9,11 @@ import ( "github.com/stretchr/testify/require" ) -func TestNetAddress_String(t *testing.T) { +func Test_String(t *testing.T) { tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080") require.NoError(t, err) - netAddr := NewNetAddress("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", tcpAddr) + netAddr := New("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", tcpAddr) var wg sync.WaitGroup @@ -31,23 +31,23 @@ func TestNetAddress_String(t *testing.T) { require.Equal(t, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", s) } -func TestNewNetAddress(t *testing.T) { +func TestNew(t *testing.T) { tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080") require.NoError(t, err) assert.Panics(t, func() { - NewNetAddress("", tcpAddr) + New("", tcpAddr) }) - addr := NewNetAddress("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", tcpAddr) + addr := New("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", tcpAddr) assert.Equal(t, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", addr.String()) assert.NotPanics(t, func() { - NewNetAddress("", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8000}) - }, "Calling NewNetAddress with UDPAddr should not panic in testing") + New("", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8000}) + }, "Calling New with UDPAddr should not panic in testing") } -func TestNewNetAddressString(t *testing.T) { +func TestNewFromString(t *testing.T) { testCases := []struct { name string addr string @@ -111,20 +111,20 @@ func TestNewNetAddressString(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - addr, err := NewNetAddressString(tc.addr) + addr, err := NewFromString(tc.addr) if tc.correct { if assert.NoError(t, err, tc.addr) { //nolint:testifylint // require.Error doesn't work with the conditional here assert.Equal(t, tc.expected, addr.String()) } } else { - require.ErrorAs(t, err, &ErrNetAddressInvalid{Addr: addr.String(), Err: err}) + require.ErrorAs(t, err, &ErrInvalid{Addr: addr.String(), Err: err}) } }) } } -func TestNewNetAddressStrings(t *testing.T) { - addrs, errs := NewNetAddressStrings([]string{ +func TestNewFromStrings(t *testing.T) { + addrs, errs := NewFromStrings([]string{ "127.0.0.1:8080", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeed@127.0.0.2:8080", @@ -133,12 +133,12 @@ func TestNewNetAddressStrings(t *testing.T) { assert.Len(t, errs, 1) } -func TestNewNetAddressIPPort(t *testing.T) { - addr := NewNetAddressIPPort(net.ParseIP("127.0.0.1"), 8080) +func TestNewFromIPPort(t *testing.T) { + addr := NewFromIPPort(net.ParseIP("127.0.0.1"), 8080) assert.Equal(t, "127.0.0.1:8080", addr.String()) } -func TestNetAddressProperties(t *testing.T) { +func TestProperties(t *testing.T) { // TODO add more test cases testCases := []struct { addr string @@ -151,7 +151,7 @@ func TestNetAddressProperties(t *testing.T) { } for _, tc := range testCases { - addr, err := NewNetAddressString(tc.addr) + addr, err := NewFromString(tc.addr) require.NoError(t, err) err = addr.Valid() @@ -165,7 +165,7 @@ func TestNetAddressProperties(t *testing.T) { } } -func TestNetAddressReachabilityTo(t *testing.T) { +func TestReachabilityTo(t *testing.T) { // TODO add more test cases testCases := []struct { addr string @@ -181,10 +181,10 @@ func TestNetAddressReachabilityTo(t *testing.T) { } for _, tc := range testCases { - addr, err := NewNetAddressString(tc.addr) + addr, err := NewFromString(tc.addr) require.NoError(t, err) - other, err := NewNetAddressString(tc.other) + other, err := NewFromString(tc.other) require.NoError(t, err) assert.Equal(t, tc.reachability, addr.ReachabilityTo(other)) diff --git a/p2p/nodeinfo/node_info.go b/p2p/nodeinfo/node_info.go index fdf0e7bb18a..7e9b4983816 100644 --- a/p2p/nodeinfo/node_info.go +++ b/p2p/nodeinfo/node_info.go @@ -8,7 +8,7 @@ import ( tmp2p "github.com/cometbft/cometbft/api/cometbft/p2p/v1" cmtstrings "github.com/cometbft/cometbft/internal/strings" cmtbytes "github.com/cometbft/cometbft/libs/bytes" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" ) @@ -28,7 +28,7 @@ func MaxNodeInfoSize() int { // and determines if we're compatible. type NodeInfo interface { ID() nodekey.ID - NetAddress() (*na.NetAddress, error) + NetAddr() (*na.NetAddr, error) Validate() error CompatibleWith(other NodeInfo) error } @@ -62,7 +62,7 @@ type DefaultNodeInfo struct { ProtocolVersion ProtocolVersion `json:"protocol_version"` // Authenticate - // TODO: replace with NetAddress + // TODO: replace with na.NetAddr DefaultNodeID nodekey.ID `json:"id"` // authenticated identifier ListenAddr string `json:"listen_addr"` // accepting incoming @@ -105,7 +105,7 @@ func (info DefaultNodeInfo) Validate() error { // ID is already validated. // Validate ListenAddr. - _, err := na.NewNetAddressString(na.IDAddressString(info.ID(), info.ListenAddr)) + _, err := na.NewFromString(na.IDAddrString(info.ID(), info.ListenAddr)) if err != nil { return err } @@ -206,13 +206,13 @@ OUTER_LOOP: return nil } -// NetAddress returns a NetAddress derived from the DefaultNodeInfo - +// NetAddr returns a NetAddr derived from the DefaultNodeInfo - // it includes the authenticated peer ID and the self-reported // ListenAddr. Note that the ListenAddr is not authenticated and // may not match that address actually dialed if its an outbound peer. -func (info DefaultNodeInfo) NetAddress() (*na.NetAddress, error) { - idAddr := na.IDAddressString(info.ID(), info.ListenAddr) - return na.NewNetAddressString(idAddr) +func (info DefaultNodeInfo) NetAddr() (*na.NetAddr, error) { + idAddr := na.IDAddrString(info.ID(), info.ListenAddr) + return na.NewFromString(idAddr) } func (info DefaultNodeInfo) HasChannel(chID byte) bool { diff --git a/p2p/nodeinfo/node_info_test.go b/p2p/nodeinfo/node_info_test.go index e1df79cb8b5..b7f700be841 100644 --- a/p2p/nodeinfo/node_info_test.go +++ b/p2p/nodeinfo/node_info_test.go @@ -11,18 +11,18 @@ import ( "github.com/cometbft/cometbft/crypto/ed25519" cmtnet "github.com/cometbft/cometbft/internal/net" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" ) const testCh = 0x01 type mockNodeInfo struct { - addr *na.NetAddress + addr *na.NetAddr } func (ni mockNodeInfo) ID() nodekey.ID { return ni.addr.ID } -func (ni mockNodeInfo) NetAddress() (*na.NetAddress, error) { return ni.addr, nil } +func (ni mockNodeInfo) NetAddr() (*na.NetAddr, error) { return ni.addr, nil } func (mockNodeInfo) Validate() error { return nil } func (mockNodeInfo) CompatibleWith(NodeInfo) error { return nil } func (mockNodeInfo) Handshake(net.Conn, time.Duration) (NodeInfo, error) { return nil, nil } @@ -81,8 +81,8 @@ func TestNodeInfoValidate(t *testing.T) { {"Duplicate Channel", func(ni *DefaultNodeInfo) { ni.Channels = dupChannels }, true}, {"Good Channels", func(ni *DefaultNodeInfo) { ni.Channels = ni.Channels[:5] }, false}, - {"Invalid NetAddress", func(ni *DefaultNodeInfo) { ni.ListenAddr = "not-an-address" }, true}, - {"Good NetAddress", func(ni *DefaultNodeInfo) { ni.ListenAddr = "0.0.0.0:26656" }, false}, + {"Invalid NetAddr", func(ni *DefaultNodeInfo) { ni.ListenAddr = "not-an-address" }, true}, + {"Good NetAddr", func(ni *DefaultNodeInfo) { ni.ListenAddr = "0.0.0.0:26656" }, false}, {"Non-ASCII Version", func(ni *DefaultNodeInfo) { ni.Version = nonASCII }, true}, {"Empty tab Version", func(ni *DefaultNodeInfo) { ni.Version = emptyTab }, true}, diff --git a/p2p/peer.go b/p2p/peer.go index a599c55b406..27ff3b93a8f 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -11,7 +11,7 @@ import ( "github.com/cometbft/cometbft/internal/cmap" "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/libs/service" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" ni "github.com/cometbft/cometbft/p2p/nodeinfo" "github.com/cometbft/cometbft/p2p/nodekey" tcpconn "github.com/cometbft/cometbft/p2p/transport/tcp/conn" @@ -41,7 +41,7 @@ type Peer interface { NodeInfo() ni.NodeInfo // peer's info Status() tcpconn.ConnectionStatus - SocketAddr() *na.NetAddress // actual address of the socket + SocketAddr() *na.NetAddr // actual address of the socket HasChannel(chID byte) bool // Does the peer implement this channel? Send(e Envelope) bool // Send a message to the peer, blocking version @@ -62,7 +62,7 @@ type peerConn struct { persistent bool conn net.Conn // Source connection - socketAddr *na.NetAddress + socketAddr *na.NetAddr // cached RemoteIP() ip net.IP @@ -71,7 +71,7 @@ type peerConn struct { func newPeerConn( outbound, persistent bool, conn net.Conn, - socketAddr *na.NetAddress, + socketAddr *na.NetAddr, ) peerConn { return peerConn{ outbound: outbound, @@ -248,7 +248,7 @@ func (p *peer) NodeInfo() ni.NodeInfo { // For outbound peers, it's the address dialed (after DNS resolution). // For inbound peers, it's the address returned by the underlying connection // (not what's reported in the peer's NodeInfo). -func (p *peer) SocketAddr() *na.NetAddress { +func (p *peer) SocketAddr() *na.NetAddr { return p.peerConn.socketAddr } @@ -465,13 +465,13 @@ func createMConnection( ) } -func wrapPeer(c net.Conn, ni ni.NodeInfo, cfg peerConfig, socketAddr *na.NetAddress, mConfig tcpconn.MConnConfig) Peer { +func wrapPeer(c net.Conn, ni ni.NodeInfo, cfg peerConfig, socketAddr *na.NetAddr, mConfig tcpconn.MConnConfig) Peer { persistent := false if cfg.isPersistent != nil { if cfg.outbound { persistent = cfg.isPersistent(socketAddr) } else { - selfReportedAddr, err := ni.NetAddress() + selfReportedAddr, err := ni.NetAddr() if err == nil { persistent = cfg.isPersistent(selfReportedAddr) } diff --git a/p2p/peer_set_test.go b/p2p/peer_set_test.go index be6c0119242..fb184c108f8 100644 --- a/p2p/peer_set_test.go +++ b/p2p/peer_set_test.go @@ -9,7 +9,7 @@ import ( "github.com/cometbft/cometbft/crypto/ed25519" "github.com/cometbft/cometbft/libs/service" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" ni "github.com/cometbft/cometbft/p2p/nodeinfo" "github.com/cometbft/cometbft/p2p/nodekey" ) @@ -21,23 +21,23 @@ type mockPeer struct { id nodekey.ID } -func (mp *mockPeer) FlushStop() { mp.Stop() } //nolint:errcheck // ignore error -func (*mockPeer) HasChannel(byte) bool { return true } -func (*mockPeer) TrySend(Envelope) bool { return true } -func (*mockPeer) Send(Envelope) bool { return true } -func (*mockPeer) NodeInfo() ni.NodeInfo { return ni.DefaultNodeInfo{} } -func (*mockPeer) Status() ConnectionStatus { return ConnectionStatus{} } -func (mp *mockPeer) ID() nodekey.ID { return mp.id } -func (*mockPeer) IsOutbound() bool { return false } -func (*mockPeer) IsPersistent() bool { return true } -func (*mockPeer) Get(s string) any { return s } -func (*mockPeer) Set(string, any) {} -func (mp *mockPeer) RemoteIP() net.IP { return mp.ip } -func (*mockPeer) SocketAddr() *na.NetAddress { return nil } -func (mp *mockPeer) RemoteAddr() net.Addr { return &net.TCPAddr{IP: mp.ip, Port: 8800} } -func (*mockPeer) Conn() net.Conn { return nil } -func (*mockPeer) SetRemovalFailed() {} -func (*mockPeer) GetRemovalFailed() bool { return false } +func (mp *mockPeer) FlushStop() { mp.Stop() } //nolint:errcheck // ignore error +func (*mockPeer) HasChannel(byte) bool { return true } +func (*mockPeer) TrySend(Envelope) bool { return true } +func (*mockPeer) Send(Envelope) bool { return true } +func (*mockPeer) NodeInfo() ni.NodeInfo { return ni.DefaultNodeInfo{} } +func (*mockPeer) Status() ConnectionStatus { return ConnectionStatus{} } +func (mp *mockPeer) ID() nodekey.ID { return mp.id } +func (*mockPeer) IsOutbound() bool { return false } +func (*mockPeer) IsPersistent() bool { return true } +func (*mockPeer) Get(s string) any { return s } +func (*mockPeer) Set(string, any) {} +func (mp *mockPeer) RemoteIP() net.IP { return mp.ip } +func (*mockPeer) SocketAddr() *na.NetAddr { return nil } +func (mp *mockPeer) RemoteAddr() net.Addr { return &net.TCPAddr{IP: mp.ip, Port: 8800} } +func (*mockPeer) Conn() net.Conn { return nil } +func (*mockPeer) SetRemovalFailed() {} +func (*mockPeer) GetRemovalFailed() bool { return false } // Returns a mock peer. func newMockPeer(ip net.IP) *mockPeer { diff --git a/p2p/peer_test.go b/p2p/peer_test.go index 0956b3414ff..9b85951a9af 100644 --- a/p2p/peer_test.go +++ b/p2p/peer_test.go @@ -18,7 +18,7 @@ import ( "github.com/cometbft/cometbft/crypto/ed25519" "github.com/cometbft/cometbft/libs/bytes" "github.com/cometbft/cometbft/libs/log" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" ni "github.com/cometbft/cometbft/p2p/nodeinfo" "github.com/cometbft/cometbft/p2p/nodekey" tcpconn "github.com/cometbft/cometbft/p2p/transport/tcp/conn" @@ -79,7 +79,7 @@ func TestPeerSend(t *testing.T) { } func createOutboundPeerAndPerformHandshake( - addr *na.NetAddress, + addr *na.NetAddr, config *config.P2PConfig, mConfig tcpconn.MConnConfig, ) (*peer, error) { @@ -119,7 +119,7 @@ func createOutboundPeerAndPerformHandshake( return p, nil } -func testDial(addr *na.NetAddress, cfg *config.P2PConfig) (net.Conn, error) { +func testDial(addr *na.NetAddr, cfg *config.P2PConfig) (net.Conn, error) { if cfg.TestDialFail { return nil, errors.New("dial err (peerConfig.DialFail == true)") } @@ -132,7 +132,7 @@ func testDial(addr *na.NetAddress, cfg *config.P2PConfig) (net.Conn, error) { } func testOutboundPeerConn( - addr *na.NetAddress, + addr *na.NetAddr, config *config.P2PConfig, persistent bool, // ourNodePrivKey crypto.PrivKey, @@ -165,13 +165,13 @@ func testOutboundPeerConn( type remotePeer struct { PrivKey crypto.PrivKey Config *config.P2PConfig - addr *na.NetAddress + addr *na.NetAddr channels bytes.HexBytes listenAddr string listener net.Listener } -func (rp *remotePeer) Addr() *na.NetAddress { +func (rp *remotePeer) Addr() *na.NetAddr { return rp.addr } @@ -189,7 +189,7 @@ func (rp *remotePeer) Start() { golog.Fatalf("net.Listen tcp :0: %+v", e) } rp.listener = l - rp.addr = na.NewNetAddress(nodekey.PubKeyToID(rp.PrivKey.PubKey()), l.Addr()) + rp.addr = na.New(nodekey.PubKeyToID(rp.PrivKey.PubKey()), l.Addr()) if rp.channels == nil { rp.channels = []byte{testCh} } @@ -200,7 +200,7 @@ func (rp *remotePeer) Stop() { rp.listener.Close() } -func (rp *remotePeer) Dial(addr *na.NetAddress) (net.Conn, error) { +func (rp *remotePeer) Dial(addr *na.NetAddr) (net.Conn, error) { pc, err := testOutboundPeerConn(addr, rp.Config, false) if err != nil { return nil, err diff --git a/p2p/pex/addrbook.go b/p2p/pex/addrbook.go index c286804b795..c1d05eb5a83 100644 --- a/p2p/pex/addrbook.go +++ b/p2p/pex/addrbook.go @@ -22,7 +22,7 @@ import ( cmtmath "github.com/cometbft/cometbft/libs/math" "github.com/cometbft/cometbft/libs/service" cmtsync "github.com/cometbft/cometbft/libs/sync" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" ) @@ -39,18 +39,18 @@ type AddrBook interface { service.Service // Add our own addresses so we don't later add ourselves - AddOurAddress(addr *na.NetAddress) + AddOurAddress(addr *na.NetAddr) // Check if it is our address - OurAddress(addr *na.NetAddress) bool + OurAddress(addr *na.NetAddr) bool AddPrivateIDs(ids []string) // Add and remove an address - AddAddress(addr *na.NetAddress, src *na.NetAddress) error - RemoveAddress(addr *na.NetAddress) + AddAddress(addr *na.NetAddr, src *na.NetAddr) error + RemoveAddress(addr *na.NetAddr) // Check if the address is in the book - HasAddress(addr *na.NetAddress) bool + HasAddress(addr *na.NetAddr) bool // Do we need more peers? NeedMoreAddrs() bool @@ -59,22 +59,22 @@ type AddrBook interface { Empty() bool // Pick an address to dial - PickAddress(biasTowardsNewAddrs int) *na.NetAddress + PickAddress(biasTowardsNewAddrs int) *na.NetAddr // Mark address MarkGood(id nodekey.ID) - MarkAttempt(addr *na.NetAddress) - MarkBad(addr *na.NetAddress, dur time.Duration) // Move peer to bad peers list + MarkAttempt(addr *na.NetAddr) + MarkBad(addr *na.NetAddr, dur time.Duration) // Move peer to bad peers list // Add bad peers back to addrBook ReinstateBadPeers() - IsGood(addr *na.NetAddress) bool - IsBanned(addr *na.NetAddress) bool + IsGood(addr *na.NetAddr) bool + IsBanned(addr *na.NetAddr) bool // Send a selection of addresses to peers - GetSelection() []*na.NetAddress + GetSelection() []*na.NetAddr // Send a selection of addresses with bias - GetSelectionWithBias(biasTowardsNewAddrs int) []*na.NetAddress + GetSelectionWithBias(biasTowardsNewAddrs int) []*na.NetAddr Size() int @@ -181,7 +181,7 @@ func (a *addrBook) FilePath() string { // ------------------------------------------------------- // AddOurAddress one of our addresses. -func (a *addrBook) AddOurAddress(addr *na.NetAddress) { +func (a *addrBook) AddOurAddress(addr *na.NetAddr) { a.mtx.Lock() defer a.mtx.Unlock() @@ -190,7 +190,7 @@ func (a *addrBook) AddOurAddress(addr *na.NetAddress) { } // OurAddress returns true if it is our address. -func (a *addrBook) OurAddress(addr *na.NetAddress) bool { +func (a *addrBook) OurAddress(addr *na.NetAddr) bool { a.mtx.Lock() defer a.mtx.Unlock() @@ -211,7 +211,7 @@ func (a *addrBook) AddPrivateIDs(ids []string) { // Add address to a "new" bucket. If it's already in one, only add it probabilistically. // Returns error if the addr is non-routable. Does not add self. // NOTE: addr must not be nil. -func (a *addrBook) AddAddress(addr *na.NetAddress, src *na.NetAddress) error { +func (a *addrBook) AddAddress(addr *na.NetAddr, src *na.NetAddr) error { a.mtx.Lock() defer a.mtx.Unlock() @@ -219,7 +219,7 @@ func (a *addrBook) AddAddress(addr *na.NetAddress, src *na.NetAddress) error { } // RemoveAddress implements AddrBook - removes the address from the book. -func (a *addrBook) RemoveAddress(addr *na.NetAddress) { +func (a *addrBook) RemoveAddress(addr *na.NetAddr) { a.mtx.Lock() defer a.mtx.Unlock() @@ -228,7 +228,7 @@ func (a *addrBook) RemoveAddress(addr *na.NetAddress) { // IsGood returns true if peer was ever marked as good and haven't // done anything wrong since then. -func (a *addrBook) IsGood(addr *na.NetAddress) bool { +func (a *addrBook) IsGood(addr *na.NetAddr) bool { a.mtx.Lock() defer a.mtx.Unlock() @@ -236,7 +236,7 @@ func (a *addrBook) IsGood(addr *na.NetAddress) bool { } // IsBanned returns true if the peer is currently banned. -func (a *addrBook) IsBanned(addr *na.NetAddress) bool { +func (a *addrBook) IsBanned(addr *na.NetAddr) bool { a.mtx.Lock() _, ok := a.badPeers[addr.ID] a.mtx.Unlock() @@ -245,7 +245,7 @@ func (a *addrBook) IsBanned(addr *na.NetAddress) bool { } // HasAddress returns true if the address is in the book. -func (a *addrBook) HasAddress(addr *na.NetAddress) bool { +func (a *addrBook) HasAddress(addr *na.NetAddr) bool { a.mtx.Lock() defer a.mtx.Unlock() @@ -270,7 +270,7 @@ func (a *addrBook) Empty() bool { // and determines how biased we are to pick an address from a new bucket. // PickAddress returns nil if the AddrBook is empty or if we try to pick // from an empty bucket. -func (a *addrBook) PickAddress(biasTowardsNewAddrs int) *na.NetAddress { +func (a *addrBook) PickAddress(biasTowardsNewAddrs int) *na.NetAddr { a.mtx.Lock() defer a.mtx.Unlock() @@ -335,7 +335,7 @@ func (a *addrBook) MarkGood(id nodekey.ID) { } // MarkAttempt implements AddrBook - it marks that an attempt was made to connect to the address. -func (a *addrBook) MarkAttempt(addr *na.NetAddress) { +func (a *addrBook) MarkAttempt(addr *na.NetAddr) { a.mtx.Lock() defer a.mtx.Unlock() @@ -348,7 +348,7 @@ func (a *addrBook) MarkAttempt(addr *na.NetAddress) { // MarkBad implements AddrBook. Kicks address out from book, places // the address in the badPeers pool. -func (a *addrBook) MarkBad(addr *na.NetAddress, banTime time.Duration) { +func (a *addrBook) MarkBad(addr *na.NetAddr, banTime time.Duration) { a.mtx.Lock() defer a.mtx.Unlock() @@ -382,7 +382,7 @@ func (a *addrBook) ReinstateBadPeers() { // GetSelection implements AddrBook. // It randomly selects some addresses (old & new). Suitable for peer-exchange protocols. // Must never return a nil address. -func (a *addrBook) GetSelection() []*na.NetAddress { +func (a *addrBook) GetSelection() []*na.NetAddr { a.mtx.Lock() defer a.mtx.Unlock() @@ -401,7 +401,7 @@ func (a *addrBook) GetSelection() []*na.NetAddress { // XXX: instead of making a list of all addresses, shuffling, and slicing a random chunk, // could we just select a random numAddresses of indexes? - allAddr := make([]*na.NetAddress, bookSize) + allAddr := make([]*na.NetAddr, bookSize) i := 0 for _, ka := range a.addrLookup { allAddr[i] = ka.Addr @@ -432,7 +432,7 @@ func percentageOfNum(p, n int) int { // biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to // that range) and determines how biased we are to pick an address from a new // bucket. -func (a *addrBook) GetSelectionWithBias(biasTowardsNewAddrs int) []*na.NetAddress { +func (a *addrBook) GetSelectionWithBias(biasTowardsNewAddrs int) []*na.NetAddr { a.mtx.Lock() defer a.mtx.Unlock() @@ -631,7 +631,7 @@ func (a *addrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress { // adds the address to a "new" bucket. if its already in one, // it only adds it probabilistically. -func (a *addrBook) addAddress(addr, src *na.NetAddress) error { +func (a *addrBook) addAddress(addr, src *na.NetAddr) error { if addr == nil || src == nil { return ErrAddrBookNilAddr{addr, src} } @@ -687,7 +687,7 @@ func (a *addrBook) addAddress(addr, src *na.NetAddress) error { return a.addToNewBucket(ka, bucket) } -func (a *addrBook) randomPickAddresses(bucketType byte, num int) []*na.NetAddress { +func (a *addrBook) randomPickAddresses(bucketType byte, num int) []*na.NetAddr { var buckets []map[string]*knownAddress switch bucketType { case bucketTypeNew: @@ -707,7 +707,7 @@ func (a *addrBook) randomPickAddresses(bucketType byte, num int) []*na.NetAddres addresses = append(addresses, ka) } } - selection := make([]*na.NetAddress, 0, num) + selection := make([]*na.NetAddr, 0, num) chosenSet := make(map[string]bool, num) rand.Shuffle(total, func(i, j int) { addresses[i], addresses[j] = addresses[j], addresses[i] @@ -783,7 +783,7 @@ func (a *addrBook) moveToOld(ka *knownAddress) { } } -func (a *addrBook) removeAddress(addr *na.NetAddress) { +func (a *addrBook) removeAddress(addr *na.NetAddr) { ka := a.addrLookup[addr.ID] if ka == nil { return @@ -792,7 +792,7 @@ func (a *addrBook) removeAddress(addr *na.NetAddress) { a.removeFromAllBuckets(ka) } -func (a *addrBook) addBadPeer(addr *na.NetAddress, banTime time.Duration) bool { +func (a *addrBook) addBadPeer(addr *na.NetAddr, banTime time.Duration) bool { // check it exists in addrbook ka := a.addrLookup[addr.ID] // check address is not already there @@ -813,7 +813,7 @@ func (a *addrBook) addBadPeer(addr *na.NetAddress, banTime time.Duration) bool { // calculate bucket placements // hash(key + sourcegroup + int64(hash(key + group + sourcegroup)) % bucket_per_group) % num_new_buckets. -func (a *addrBook) calcNewBucket(addr, src *na.NetAddress) int { +func (a *addrBook) calcNewBucket(addr, src *na.NetAddr) int { data1 := []byte{} data1 = append(data1, []byte(a.key)...) data1 = append(data1, []byte(a.groupKey(addr))...) @@ -834,7 +834,7 @@ func (a *addrBook) calcNewBucket(addr, src *na.NetAddress) int { } // hash(key + group + int64(hash(key + addr)) % buckets_per_group) % num_old_buckets. -func (a *addrBook) calcOldBucket(addr *na.NetAddress) int { +func (a *addrBook) calcOldBucket(addr *na.NetAddr) int { data1 := []byte{} data1 = append(data1, []byte(a.key)...) data1 = append(data1, []byte(addr.String())...) @@ -859,11 +859,11 @@ func (a *addrBook) calcOldBucket(addr *na.NetAddress) int { // This is the /16 for IPv4 (e.g. 1.2.0.0), the /32 (/36 for he.net) for IPv6, the string // "local" for a local address and the string "unroutable" for an unroutable // address. -func (a *addrBook) groupKey(na *na.NetAddress) string { +func (a *addrBook) groupKey(na *na.NetAddr) string { return groupKeyFor(na, a.routabilityStrict) } -func groupKeyFor(na *na.NetAddress, routabilityStrict bool) string { +func groupKeyFor(na *na.NetAddr, routabilityStrict bool) string { if routabilityStrict && na.Local() { return "local" } diff --git a/p2p/pex/addrbook_test.go b/p2p/pex/addrbook_test.go index 83c28b614ab..c9d918b26f1 100644 --- a/p2p/pex/addrbook_test.go +++ b/p2p/pex/addrbook_test.go @@ -15,7 +15,7 @@ import ( cmtrand "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/libs/log" cmtmath "github.com/cometbft/cometbft/libs/math" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" ) @@ -33,7 +33,7 @@ func TestAddrBookPickAddress(t *testing.T) { addr := book.PickAddress(50) assert.Nil(t, addr, "expected no address") - randAddrs := randNetAddressPairs(t, 1) + randAddrs := randNetAddrPairs(t, 1) addrSrc := randAddrs[0] err := book.AddAddress(addrSrc.addr, addrSrc.src) require.NoError(t, err) @@ -75,7 +75,7 @@ func TestAddrBookSaveLoad(t *testing.T) { assert.True(t, book.Empty()) // 100 addresses - randAddrs := randNetAddressPairs(t, 100) + randAddrs := randNetAddrPairs(t, 100) for _, addrSrc := range randAddrs { err := book.AddAddress(addrSrc.addr, addrSrc.src) @@ -97,7 +97,7 @@ func TestAddrBookLookup(t *testing.T) { fname := createTempFileName() defer deleteTempFile(fname) - randAddrs := randNetAddressPairs(t, 100) + randAddrs := randNetAddrPairs(t, 100) book := NewAddrBook(fname, true) book.SetLogger(log.TestingLogger()) @@ -116,7 +116,7 @@ func TestAddrBookPromoteToOld(t *testing.T) { fname := createTempFileName() defer deleteTempFile(fname) - randAddrs := randNetAddressPairs(t, 100) + randAddrs := randNetAddrPairs(t, 100) book := NewAddrBook(fname, true) book.SetLogger(log.TestingLogger()) @@ -163,7 +163,7 @@ func TestAddrBookHandlesDuplicates(t *testing.T) { book := NewAddrBook(fname, true) book.SetLogger(log.TestingLogger()) - randAddrs := randNetAddressPairs(t, 100) + randAddrs := randNetAddrPairs(t, 100) differentSrc := randIPv4Address(t) for _, addrSrc := range randAddrs { @@ -178,21 +178,21 @@ func TestAddrBookHandlesDuplicates(t *testing.T) { assert.Equal(t, 100, book.Size()) } -type netAddressPair struct { - addr *na.NetAddress - src *na.NetAddress +type netAddrPair struct { + addr *na.NetAddr + src *na.NetAddr } -func randNetAddressPairs(t *testing.T, n int) []netAddressPair { +func randNetAddrPairs(t *testing.T, n int) []netAddrPair { t.Helper() - randAddrs := make([]netAddressPair, n) + randAddrs := make([]netAddrPair, n) for i := 0; i < n; i++ { - randAddrs[i] = netAddressPair{addr: randIPv4Address(t), src: randIPv4Address(t)} + randAddrs[i] = netAddrPair{addr: randIPv4Address(t), src: randIPv4Address(t)} } return randAddrs } -func randIPv4Address(t *testing.T) *na.NetAddress { +func randIPv4Address(t *testing.T) *na.NetAddr { t.Helper() for { ip := fmt.Sprintf("%v.%v.%v.%v", @@ -203,8 +203,8 @@ func randIPv4Address(t *testing.T) *na.NetAddress { ) port := cmtrand.Intn(65535-1) + 1 id := nodekey.ID(hex.EncodeToString(cmtrand.Bytes(nodekey.IDByteLength))) - idAddr := na.IDAddressString(id, fmt.Sprintf("%v:%v", ip, port)) - addr, err := na.NewNetAddressString(idAddr) + idAddr := na.IDAddrString(id, fmt.Sprintf("%v:%v", ip, port)) + addr, err := na.NewFromString(idAddr) require.NoError(t, err) if addr.Routable() { return addr @@ -279,14 +279,14 @@ func TestAddrBookGetSelection(t *testing.T) { assert.Equal(t, addr, book.GetSelection()[0]) // 3) add a bunch of addresses - randAddrs := randNetAddressPairs(t, 100) + randAddrs := randNetAddrPairs(t, 100) for _, addrSrc := range randAddrs { err := book.AddAddress(addrSrc.addr, addrSrc.src) require.NoError(t, err) } // check there is no duplicates - addrs := make(map[string]*na.NetAddress) + addrs := make(map[string]*na.NetAddr) selection := book.GetSelection() for _, addr := range selection { if dup, ok := addrs[addr.String()]; ok { @@ -323,14 +323,14 @@ func TestAddrBookGetSelectionWithBias(t *testing.T) { assert.Equal(t, addr, selection[0]) // 3) add a bunch of addresses - randAddrs := randNetAddressPairs(t, 100) + randAddrs := randNetAddrPairs(t, 100) for _, addrSrc := range randAddrs { err := book.AddAddress(addrSrc.addr, addrSrc.src) require.NoError(t, err) } // check there is no duplicates - addrs := make(map[string]*na.NetAddress) + addrs := make(map[string]*na.NetAddr) selection = book.GetSelectionWithBias(biasTowardsNewAddrs) for _, addr := range selection { if dup, ok := addrs[addr.String()]; ok { @@ -402,9 +402,9 @@ func TestAddrBookHasAddress(t *testing.T) { assert.False(t, book.HasAddress(addr)) } -func testCreatePrivateAddrs(t *testing.T, numAddrs int) ([]*na.NetAddress, []string) { +func testCreatePrivateAddrs(t *testing.T, numAddrs int) ([]*na.NetAddr, []string) { t.Helper() - addrs := make([]*na.NetAddress, numAddrs) + addrs := make([]*na.NetAddr, numAddrs) for i := 0; i < numAddrs; i++ { addrs[i] = randIPv4Address(t) } @@ -609,13 +609,13 @@ func TestAddrBookAddDoesNotOverwriteOldIP(t *testing.T) { // to ensure we aren't in a case that got probabilistically ignored numOverrideAttempts := 10 - peerRealAddr, err := na.NewNetAddressString(peerID + "@" + peerRealIP) + peerRealAddr, err := na.NewFromString(peerID + "@" + peerRealIP) require.NoError(t, err) - peerOverrideAttemptAddr, err := na.NewNetAddressString(peerID + "@" + peerOverrideAttemptIP) + peerOverrideAttemptAddr, err := na.NewFromString(peerID + "@" + peerOverrideAttemptIP) require.NoError(t, err) - src, err := na.NewNetAddressString(srcAddr) + src, err := na.NewFromString(srcAddr) require.NoError(t, err) book := NewAddrBook(fname, true) @@ -679,7 +679,7 @@ func TestAddrBookGroupKey(t *testing.T) { for i, tc := range testCases { nip := net.ParseIP(tc.ip) - key := groupKeyFor(na.NewNetAddressIPPort(nip, 26656), false) + key := groupKeyFor(na.NewFromIPPort(nip, 26656), false) assert.Equal(t, tc.expKey, key, "#%d", i) } @@ -709,12 +709,12 @@ func TestAddrBookGroupKey(t *testing.T) { for i, tc := range testCases { nip := net.ParseIP(tc.ip) - key := groupKeyFor(na.NewNetAddressIPPort(nip, 26656), true) + key := groupKeyFor(na.NewFromIPPort(nip, 26656), true) assert.Equal(t, tc.expKey, key, "#%d", i) } } -func assertMOldAndNNewAddrsInSelection(t *testing.T, m, n int, addrs []*na.NetAddress, book *addrBook) { +func assertMOldAndNNewAddrsInSelection(t *testing.T, m, n int, addrs []*na.NetAddr, book *addrBook) { t.Helper() nOld, nNew := countOldAndNewAddrsInSelection(addrs, book) assert.Equal(t, m, nOld, "old addresses") @@ -750,14 +750,14 @@ func createAddrBookWithMOldAndNNewAddrs(t *testing.T, nOld, nNew int) (book *add book.SetLogger(log.TestingLogger()) assert.Zero(t, book.Size()) - randAddrs := randNetAddressPairs(t, nOld) + randAddrs := randNetAddrPairs(t, nOld) for _, addr := range randAddrs { err := book.AddAddress(addr.addr, addr.src) require.NoError(t, err) book.MarkGood(addr.addr.ID) } - randAddrs = randNetAddressPairs(t, nNew) + randAddrs = randNetAddrPairs(t, nNew) for _, addr := range randAddrs { err := book.AddAddress(addr.addr, addr.src) require.NoError(t, err) @@ -766,7 +766,7 @@ func createAddrBookWithMOldAndNNewAddrs(t *testing.T, nOld, nNew int) (book *add return book, fname } -func countOldAndNewAddrsInSelection(addrs []*na.NetAddress, book *addrBook) (nOld, nNew int) { +func countOldAndNewAddrsInSelection(addrs []*na.NetAddr, book *addrBook) (nOld, nNew int) { for _, addr := range addrs { if book.IsGood(addr) { nOld++ @@ -781,7 +781,7 @@ func countOldAndNewAddrsInSelection(addrs []*na.NetAddress, book *addrBook) (nOl // Returns: // - seqLens - the lengths of the sequences of addresses of same type // - seqTypes - the types of sequences in selection. -func analyseSelectionLayout(book *addrBook, addrs []*na.NetAddress) (seqLens, seqTypes []int) { +func analyseSelectionLayout(book *addrBook, addrs []*na.NetAddr) (seqLens, seqTypes []int) { // address types are: 0 - nil, 1 - new, 2 - old var ( prevType = 0 diff --git a/p2p/pex/errors.go b/p2p/pex/errors.go index 54792a4681b..84bf7813533 100644 --- a/p2p/pex/errors.go +++ b/p2p/pex/errors.go @@ -5,7 +5,7 @@ import ( "fmt" "time" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" ) @@ -16,7 +16,7 @@ var ( ) type ErrAddrBookNonRoutable struct { - Addr *na.NetAddress + Addr *na.NetAddr } func (err ErrAddrBookNonRoutable) Error() string { @@ -24,7 +24,7 @@ func (err ErrAddrBookNonRoutable) Error() string { } type ErrAddrBookOldAddressNewBucket struct { - Addr *na.NetAddress + Addr *na.NetAddr BucketID int } @@ -35,7 +35,7 @@ func (err ErrAddrBookOldAddressNewBucket) Error() string { } type ErrAddrBookSelf struct { - Addr *na.NetAddress + Addr *na.NetAddr } func (err ErrAddrBookSelf) Error() string { @@ -43,7 +43,7 @@ func (err ErrAddrBookSelf) Error() string { } type ErrAddrBookPrivate struct { - Addr *na.NetAddress + Addr *na.NetAddr } func (err ErrAddrBookPrivate) Error() string { @@ -55,7 +55,7 @@ func (ErrAddrBookPrivate) PrivateAddr() bool { } type ErrAddrBookPrivateSrc struct { - Src *na.NetAddress + Src *na.NetAddr } func (err ErrAddrBookPrivateSrc) Error() string { @@ -67,8 +67,8 @@ func (ErrAddrBookPrivateSrc) PrivateAddr() bool { } type ErrAddrBookNilAddr struct { - Addr *na.NetAddress - Src *na.NetAddress + Addr *na.NetAddr + Src *na.NetAddr } func (err ErrAddrBookNilAddr) Error() string { @@ -76,7 +76,7 @@ func (err ErrAddrBookNilAddr) Error() string { } type ErrAddrBookInvalidAddr struct { - Addr *na.NetAddress + Addr *na.NetAddr AddrErr error } @@ -86,7 +86,7 @@ func (err ErrAddrBookInvalidAddr) Error() string { // ErrAddressBanned is thrown when the address has been banned and therefore cannot be used. type ErrAddressBanned struct { - Addr *na.NetAddress + Addr *na.NetAddr } func (err ErrAddressBanned) Error() string { diff --git a/p2p/pex/known_address.go b/p2p/pex/known_address.go index 51a7550a18e..e408f271ca5 100644 --- a/p2p/pex/known_address.go +++ b/p2p/pex/known_address.go @@ -3,24 +3,24 @@ package pex import ( "time" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" ) // knownAddress tracks information about a known network address // that is used to determine how viable an address is. type knownAddress struct { - Addr *na.NetAddress `json:"addr"` - Src *na.NetAddress `json:"src"` - Buckets []int `json:"buckets"` - Attempts int32 `json:"attempts"` - BucketType byte `json:"bucket_type"` - LastAttempt time.Time `json:"last_attempt"` - LastSuccess time.Time `json:"last_success"` - LastBanTime time.Time `json:"last_ban_time"` + Addr *na.NetAddr `json:"addr"` + Src *na.NetAddr `json:"src"` + Buckets []int `json:"buckets"` + Attempts int32 `json:"attempts"` + BucketType byte `json:"bucket_type"` + LastAttempt time.Time `json:"last_attempt"` + LastSuccess time.Time `json:"last_success"` + LastBanTime time.Time `json:"last_ban_time"` } -func newKnownAddress(addr *na.NetAddress, src *na.NetAddress) *knownAddress { +func newKnownAddress(addr *na.NetAddr, src *na.NetAddr) *knownAddress { return &knownAddress{ Addr: addr, Src: src, diff --git a/p2p/pex/pex_reactor.go b/p2p/pex/pex_reactor.go index 476d7959fe7..49228046b85 100644 --- a/p2p/pex/pex_reactor.go +++ b/p2p/pex/pex_reactor.go @@ -12,7 +12,7 @@ import ( cmtmath "github.com/cometbft/cometbft/libs/math" "github.com/cometbft/cometbft/libs/service" "github.com/cometbft/cometbft/p2p" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" tcpconn "github.com/cometbft/cometbft/p2p/transport/tcp/conn" ) @@ -23,7 +23,7 @@ const ( // PexChannel is a channel for PEX messages. PexChannel = byte(0x00) - // over-estimate of max NetAddress size + // over-estimate of max na.NetAddr size // hexID (40) + IP (16) + Port (2) + Name (100) ... // NOTE: dont use massive DNS name .. maxAddressSize = 256 @@ -57,7 +57,7 @@ const ( // Reactor handles PEX (peer exchange) and ensures that an // adequate number of peers are connected to the switch. // -// It uses `AddrBook` (address book) to store `NetAddress`es of the peers. +// It uses `AddrBook` (address book) to store `na.NetAddr`es of the peers. // // ## Preventing abuse // @@ -76,7 +76,7 @@ type Reactor struct { requestsSent *cmap.CMap // ID->struct{}: unanswered send requests lastReceivedRequests *cmap.CMap // ID->time.Time: last time peer requested from us - seedAddrs []*na.NetAddress + seedAddrs []*na.NetAddr attemptsToDial sync.Map // address (string) -> {number of attempts (int), last time dialed (time.Time)} @@ -192,9 +192,9 @@ func (r *Reactor) AddPeer(p Peer) { } } else { // inbound peer is its own source - addr, err := p.NodeInfo().NetAddress() + addr, err := p.NodeInfo().NetAddr() if err != nil { - r.Logger.Error("Failed to get peer NetAddress", "err", err, "peer", p) + r.Logger.Error("Failed to get peer NetAddr", "err", err, "peer", p) return } @@ -270,7 +270,7 @@ func (r *Reactor) Receive(e p2p.Envelope) { case *tmp2p.PexAddrs: // If we asked for addresses, add them to the book - addrs, err := na.NetAddressesFromProto(msg.Addrs) + addrs, err := na.AddrsFromProtos(msg.Addrs) if err != nil { r.Switch.StopPeerForError(e.Src, err) r.book.MarkBad(e.Src.SocketAddr(), defaultBanTime) @@ -341,14 +341,14 @@ func (r *Reactor) RequestAddrs(p Peer) { // ReceiveAddrs adds the given addrs to the addrbook if there's an open // request for this peer and deletes the open request. // If there's no open request for the src peer, it returns an error. -func (r *Reactor) ReceiveAddrs(addrs []*na.NetAddress, src Peer) error { +func (r *Reactor) ReceiveAddrs(addrs []*na.NetAddr, src Peer) error { id := string(src.ID()) if !r.requestsSent.Has(id) { return ErrUnsolicitedList } r.requestsSent.Delete(id) - srcAddr, err := src.NodeInfo().NetAddress() + srcAddr, err := src.NodeInfo().NetAddr() if err != nil { return err } @@ -379,10 +379,10 @@ func (r *Reactor) ReceiveAddrs(addrs []*na.NetAddress, src Peer) error { } // SendAddrs sends addrs to the peer. -func (*Reactor) SendAddrs(p Peer, netAddrs []*na.NetAddress) { +func (*Reactor) SendAddrs(p Peer, netAddrs []*na.NetAddr) { e := p2p.Envelope{ ChannelID: PexChannel, - Message: &tmp2p.PexAddrs{Addrs: na.NetAddressesToProto(netAddrs)}, + Message: &tmp2p.PexAddrs{Addrs: na.AddrsToProtos(netAddrs)}, } p.Send(e) } @@ -456,7 +456,7 @@ func (r *Reactor) ensurePeers() { // NOTE: range here is [10, 90]. Too high ? newBias := cmtmath.MinInt(out, 8)*10 + 10 - toDial := make(map[nodekey.ID]*na.NetAddress) + toDial := make(map[nodekey.ID]*na.NetAddr) // Try maxAttempts times to pick numToDial addresses to dial maxAttempts := numToDial * 3 @@ -483,7 +483,7 @@ func (r *Reactor) ensurePeers() { // Dial picked addresses for _, addr := range toDial { - go func(addr *na.NetAddress) { + go func(addr *na.NetAddr) { err := r.dialPeer(addr) if err != nil { switch err.(type) { @@ -519,7 +519,7 @@ func (r *Reactor) ensurePeers() { } } -func (r *Reactor) dialAttemptsInfo(addr *na.NetAddress) (attempts int, lastDialed time.Time) { +func (r *Reactor) dialAttemptsInfo(addr *na.NetAddr) (attempts int, lastDialed time.Time) { _attempts, ok := r.attemptsToDial.Load(addr.DialString()) if !ok { return 0, time.Time{} @@ -528,7 +528,7 @@ func (r *Reactor) dialAttemptsInfo(addr *na.NetAddress) (attempts int, lastDiale return atd.number, atd.lastDialed } -func (r *Reactor) dialPeer(addr *na.NetAddress) error { +func (r *Reactor) dialPeer(addr *na.NetAddr) error { attempts, lastDialed := r.dialAttemptsInfo(addr) if !r.Switch.IsPeerPersistent(addr) && attempts > maxAttemptsToDial { r.book.MarkBad(addr, defaultBanTime) @@ -569,7 +569,7 @@ func (r *Reactor) dialPeer(addr *na.NetAddress) error { } // maxBackoffDurationForPeer caps the backoff duration for persistent peers. -func (r *Reactor) maxBackoffDurationForPeer(addr *na.NetAddress, planned time.Duration) time.Duration { +func (r *Reactor) maxBackoffDurationForPeer(addr *na.NetAddr, planned time.Duration) time.Duration { if r.config.PersistentPeersMaxDialPeriod > 0 && planned > r.config.PersistentPeersMaxDialPeriod && r.Switch.IsPeerPersistent(addr) { @@ -583,16 +583,16 @@ func (r *Reactor) maxBackoffDurationForPeer(addr *na.NetAddress, planned time.Du // return err if user provided any badly formatted seed addresses. // Doesn't error if the seed node can't be reached. // numOnline returns -1 if no seed nodes were in the initial configuration. -func (r *Reactor) checkSeeds() (numOnline int, netAddrs []*na.NetAddress, err error) { +func (r *Reactor) checkSeeds() (numOnline int, netAddrs []*na.NetAddr, err error) { lSeeds := len(r.config.Seeds) if lSeeds == 0 { return -1, nil, nil } - netAddrs, errs := na.NewNetAddressStrings(r.config.Seeds) + netAddrs, errs := na.NewFromStrings(r.config.Seeds) numOnline = lSeeds - len(errs) for _, err := range errs { switch e := err.(type) { - case na.ErrNetAddressLookup: + case na.ErrLookup: r.Logger.Error("Connecting to seed failed", "err", e) default: return 0, nil, ErrSeedNodeConfig{Err: err} @@ -624,7 +624,7 @@ func (r *Reactor) dialSeeds() { // AttemptsToDial returns the number of attempts to dial specific address. It // returns 0 if never attempted or successfully connected. -func (r *Reactor) AttemptsToDial(addr *na.NetAddress) int { +func (r *Reactor) AttemptsToDial(addr *na.NetAddr) int { lAttempts, attempted := r.attemptsToDial.Load(addr.DialString()) if attempted { return lAttempts.(_attemptsToDial).number @@ -675,13 +675,13 @@ func (r *Reactor) nodeHasSomePeersOrDialingAny() bool { // crawlPeerInfo handles temporary data needed for the network crawling // performed during seed/crawler mode. type crawlPeerInfo struct { - Addr *na.NetAddress `json:"addr"` + Addr *na.NetAddr `json:"addr"` // The last time we crawled the peer or attempted to do so. LastCrawled time.Time `json:"last_crawled"` } // crawlPeers will crawl the network looking for new peer addresses. -func (r *Reactor) crawlPeers(addrs []*na.NetAddress) { +func (r *Reactor) crawlPeers(addrs []*na.NetAddr) { now := time.Now() for _, addr := range addrs { @@ -743,7 +743,7 @@ func (r *Reactor) attemptDisconnects() { } } -func markAddrInBookBasedOnErr(addr *na.NetAddress, book AddrBook, err error) { +func markAddrInBookBasedOnErr(addr *na.NetAddr, book AddrBook, err error) { // TODO: detect more "bad peer" scenarios switch err.(type) { case p2p.ErrSwitchAuthenticationFailure: diff --git a/p2p/pex/pex_reactor_test.go b/p2p/pex/pex_reactor_test.go index 4cd8c9552b8..e06810e519f 100644 --- a/p2p/pex/pex_reactor_test.go +++ b/p2p/pex/pex_reactor_test.go @@ -17,7 +17,7 @@ import ( "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/p2p" "github.com/cometbft/cometbft/p2p/mock" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/types" ) @@ -98,7 +98,7 @@ func TestPEXReactorRunning(t *testing.T) { } addOtherNodeAddrToAddrBook := func(switchIndex, otherSwitchIndex int) { - addr := switches[otherSwitchIndex].NetAddress() + addr := switches[otherSwitchIndex].NetAddr() err := books[switchIndex].AddAddress(addr, addr) require.NoError(t, err) } @@ -215,7 +215,7 @@ func TestCheckSeeds(t *testing.T) { peerSwitch.Stop() //nolint:errcheck // ignore for tests // 2. create seed - seed := testCreateSeed(dir, 1, []*na.NetAddress{}, []*na.NetAddress{}) + seed := testCreateSeed(dir, 1, []*na.NetAddr{}, []*na.NetAddr{}) // 3. test create peer with online seed works peerSwitch = testCreatePeerWithSeed(dir, 2, seed) @@ -238,7 +238,7 @@ func TestCheckSeeds(t *testing.T) { Seeds: []string{ "ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657", "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657", - seed.NetAddress().String(), + seed.NetAddr().String(), }, } peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig) @@ -253,7 +253,7 @@ func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) { defer os.RemoveAll(dir) // 1. create seed - seed := testCreateSeed(dir, 0, []*na.NetAddress{}, []*na.NetAddress{}) + seed := testCreateSeed(dir, 0, []*na.NetAddr{}, []*na.NetAddr{}) require.NoError(t, seed.Start()) defer seed.Stop() //nolint:errcheck // ignore for tests @@ -276,13 +276,13 @@ func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) { cfg.MaxNumOutboundPeers = 2 var id int - var knownAddrs []*na.NetAddress + var knownAddrs []*na.NetAddr // 1. Create some peers for id = 0; id < cfg.MaxNumOutboundPeers+1; id++ { peer := testCreateDefaultPeer(dir, id) require.NoError(t, peer.Start()) - addr := peer.NetAddress() + addr := peer.NetAddr() defer peer.Stop() //nolint:errcheck // ignore for tests knownAddrs = append(knownAddrs, addr) @@ -336,7 +336,7 @@ func TestPEXReactorSeedMode(t *testing.T) { defer peerSwitch.Stop() //nolint:errcheck // ignore for tests // 1. Test crawlPeers dials the peer - pexR.crawlPeers([]*na.NetAddress{peerSwitch.NetAddress()}) + pexR.crawlPeers([]*na.NetAddr{peerSwitch.NetAddr()}) assert.Equal(t, 1, sw.Peers().Size()) assert.True(t, sw.Peers().Has(peerSwitch.NodeInfo().ID())) @@ -374,11 +374,11 @@ func TestPEXReactorDoesNotDisconnectFromPersistentPeerInSeedMode(t *testing.T) { require.NoError(t, peerSwitch.Start()) defer peerSwitch.Stop() //nolint:errcheck // ignore for tests - err = sw.AddPersistentPeers([]string{peerSwitch.NetAddress().String()}) + err = sw.AddPersistentPeers([]string{peerSwitch.NetAddr().String()}) require.NoError(t, err) // 1. Test crawlPeers dials the peer - pexR.crawlPeers([]*na.NetAddress{peerSwitch.NetAddress()}) + pexR.crawlPeers([]*na.NetAddr{peerSwitch.NetAddr()}) assert.Equal(t, 1, sw.Peers().Size()) assert.True(t, sw.Peers().Has(peerSwitch.NodeInfo().ID())) @@ -413,7 +413,7 @@ func TestPEXReactorDialsPeerUpToMaxAttemptsInSeedMode(t *testing.T) { // imitate maxAttemptsToDial reached pexR.attemptsToDial.Store(addr.DialString(), _attemptsToDial{maxAttemptsToDial + 1, time.Now()}) - pexR.crawlPeers([]*na.NetAddress{addr}) + pexR.crawlPeers([]*na.NetAddr{addr}) assert.False(t, book.HasAddress(addr)) } @@ -466,7 +466,7 @@ func TestPEXReactorSeedModeFlushStop(t *testing.T) { reactor := switches[0].Reactors()["pex"].(*Reactor) peerID := switches[1].NodeInfo().ID() - err = switches[1].DialPeerWithAddress(switches[0].NetAddress()) + err = switches[1].DialPeerWithAddress(switches[0].NetAddr()) require.NoError(t, err) // sleep up to a second while waiting for the peer to send us a message. @@ -632,7 +632,7 @@ func testCreateDefaultPeer(dir string, id int) *p2p.Switch { // Creates a seed which knows about the provided addresses / source address pairs. // Starting and stopping the seed is left to the caller. -func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*na.NetAddress) *p2p.Switch { +func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*na.NetAddr) *p2p.Switch { seed := p2p.MakeSwitch( cfg, id, @@ -663,7 +663,7 @@ func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*na.NetAddress) * // Starting and stopping the peer is left to the caller. func testCreatePeerWithSeed(dir string, id int, seed *p2p.Switch) *p2p.Switch { conf := &ReactorConfig{ - Seeds: []string{seed.NetAddress().String()}, + Seeds: []string{seed.NetAddr().String()}, } return testCreatePeerWithConfig(dir, id, conf) } diff --git a/p2p/switch.go b/p2p/switch.go index c135202ae3d..0474289d8dd 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -12,7 +12,7 @@ import ( "github.com/cometbft/cometbft/internal/cmap" "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/libs/service" - na "github.com/cometbft/cometbft/p2p/netaddress" + 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" @@ -55,13 +55,13 @@ func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig { // An AddrBook represents an address book from the pex package, which is used // to store peer addresses. type AddrBook interface { - AddAddress(addr *na.NetAddress, src *na.NetAddress) error + AddAddress(addr *na.NetAddr, src *na.NetAddr) error AddPrivateIDs(ids []string) - AddOurAddress(addr *na.NetAddress) - OurAddress(addr *na.NetAddress) bool + AddOurAddress(addr *na.NetAddr) + OurAddress(addr *na.NetAddr) bool MarkGood(id nodekey.ID) - RemoveAddress(addr *na.NetAddress) - HasAddress(addr *na.NetAddress) bool + RemoveAddress(addr *na.NetAddr) + HasAddress(addr *na.NetAddr) bool Save() } @@ -90,7 +90,7 @@ type Switch struct { nodeKey *nodekey.NodeKey // our node privkey addrBook AddrBook // peers addresses with whom we'll maintain constant connection - persistentPeersAddrs []*na.NetAddress + persistentPeersAddrs []*na.NetAddr unconditionalPeerIDs map[nodekey.ID]struct{} transport Transport @@ -103,9 +103,9 @@ type Switch struct { metrics *Metrics } -// NetAddress returns the address the switch is listening on. -func (sw *Switch) NetAddress() *na.NetAddress { - addr := sw.transport.NetAddress() +// NetAddr returns the address the switch is listening on. +func (sw *Switch) NetAddr() *na.NetAddr { + addr := sw.transport.NetAddr() return &addr } @@ -130,7 +130,7 @@ func NewSwitch( metrics: NopMetrics(), transport: transport, filterTimeout: defaultFilterTimeout, - persistentPeersAddrs: make([]*na.NetAddress, 0), + persistentPeersAddrs: make([]*na.NetAddr, 0), unconditionalPeerIDs: make(map[nodekey.ID]struct{}), } @@ -334,12 +334,12 @@ func (sw *Switch) StopPeerForError(peer Peer, reason any) { sw.stopAndRemovePeer(peer, reason) if peer.IsPersistent() { - var addr *na.NetAddress + var addr *na.NetAddr if peer.IsOutbound() { // socket address for outbound peers addr = peer.SocketAddr() } else { // self-reported address for inbound peers var err error - addr, err = peer.NodeInfo().NetAddress() + addr, err = peer.NodeInfo().NetAddr() if err != nil { sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong", "peer", peer, "err", err) @@ -394,7 +394,7 @@ func (sw *Switch) stopAndRemovePeer(p Peer, reason any) { // TODO: be more explicit with error types so we only retry on certain failures // - ie. if we're getting ErrDuplicatePeer we can stop // because the addrbook got us the peer back already -func (sw *Switch) reconnectToPeer(addr *na.NetAddress) { +func (sw *Switch) reconnectToPeer(addr *na.NetAddr) { if sw.reconnecting.Has(string(addr.ID)) { return } @@ -470,18 +470,18 @@ func isPrivateAddr(err error) bool { // DialPeersAsync dials a list of peers asynchronously in random order. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources). -// It ignores ErrNetAddressLookup. However, if there are other errors, first +// It ignores na.ErrLookup. However, if there are other errors, first // encounter is returned. // Nop if there are no peers. func (sw *Switch) DialPeersAsync(peers []string) error { - netAddrs, errs := na.NewNetAddressStrings(peers) + netAddrs, errs := na.NewFromStrings(peers) // report all the errors for _, err := range errs { sw.Logger.Error("Error in peer's address", "err", err) } - // return first non-ErrNetAddressLookup error + // return first non-ErrLookup error for _, err := range errs { - if errors.As(err, &na.ErrNetAddressLookup{}) { + if errors.As(err, &na.ErrLookup{}) { continue } return err @@ -490,8 +490,8 @@ func (sw *Switch) DialPeersAsync(peers []string) error { return nil } -func (sw *Switch) dialPeersAsync(netAddrs []*na.NetAddress) { - ourAddr := sw.NetAddress() +func (sw *Switch) dialPeersAsync(netAddrs []*na.NetAddr) { + ourAddr := sw.NetAddr() // TODO: this code feels like it's in the wrong place. // The integration tests depend on the addrBook being saved @@ -547,7 +547,7 @@ func (sw *Switch) dialPeersAsync(netAddrs []*na.NetAddress) { // and authenticates successfully. // If we're currently dialing this address or it belongs to an existing peer, // ErrCurrentlyDialingOrExistingAddress is returned. -func (sw *Switch) DialPeerWithAddress(addr *na.NetAddress) error { +func (sw *Switch) DialPeerWithAddress(addr *na.NetAddr) error { if sw.IsDialingOrExistingAddress(addr) { return ErrCurrentlyDialingOrExistingAddress{addr.String()} } @@ -566,25 +566,25 @@ func (sw *Switch) randomSleep(interval time.Duration) { // IsDialingOrExistingAddress returns true if switch has a peer with the given // address or dialing it at the moment. -func (sw *Switch) IsDialingOrExistingAddress(addr *na.NetAddress) bool { +func (sw *Switch) IsDialingOrExistingAddress(addr *na.NetAddr) bool { return sw.dialing.Has(string(addr.ID)) || sw.peers.Has(addr.ID) || (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP)) } // AddPersistentPeers allows you to set persistent peers. It ignores -// ErrNetAddressLookup. However, if there are other errors, first encounter is +// na.ErrLookup. However, if there are other errors, first encounter is // returned. func (sw *Switch) AddPersistentPeers(addrs []string) error { sw.Logger.Info("Adding persistent peers", "addrs", addrs) - netAddrs, errs := na.NewNetAddressStrings(addrs) + netAddrs, errs := na.NewFromStrings(addrs) // report all the errors for _, err := range errs { sw.Logger.Error("Error in peer's address", "err", err) } - // return first non-ErrNetAddressLookup error + // return first non-ErrLookup error for _, err := range errs { - if errors.As(err, &na.ErrNetAddressLookup{}) { + if errors.As(err, &na.ErrLookup{}) { continue } return err @@ -622,7 +622,7 @@ func (sw *Switch) AddPrivatePeerIDs(ids []string) error { return nil } -func (sw *Switch) IsPeerPersistent(na *na.NetAddress) bool { +func (sw *Switch) IsPeerPersistent(na *na.NetAddr) bool { for _, pa := range sw.persistentPeersAddrs { if pa.Equals(na) { return true @@ -747,7 +747,7 @@ func (sw *Switch) acceptRoutine() { // If peer is started successfully, reconnectLoop will start when // StopPeerForError is called. func (sw *Switch) addOutboundPeerWithConfig( - addr *na.NetAddress, + addr *na.NetAddr, cfg *config.P2PConfig, ) error { sw.Logger.Debug("Dialing peer", "address", addr) diff --git a/p2p/switch_test.go b/p2p/switch_test.go index 275f7bbf750..c1225c865bf 100644 --- a/p2p/switch_test.go +++ b/p2p/switch_test.go @@ -24,7 +24,7 @@ import ( "github.com/cometbft/cometbft/crypto/ed25519" "github.com/cometbft/cometbft/libs/log" cmtsync "github.com/cometbft/cometbft/libs/sync" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/transport/tcp" tcpconn "github.com/cometbft/cometbft/p2p/transport/tcp/conn" ) @@ -593,7 +593,7 @@ func TestSwitchReconnectsToInboundPersistentPeer(t *testing.T) { err = sw.AddPersistentPeers([]string{rp.Addr().String()}) require.NoError(t, err) - conn, err := rp.Dial(sw.NetAddress()) + conn, err := rp.Dial(sw.NetAddr()) require.NoError(t, err) time.Sleep(50 * time.Millisecond) require.NotNil(t, sw.Peers().Get(rp.ID())) @@ -693,7 +693,7 @@ func TestSwitchAcceptRoutine(t *testing.T) { peer := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} peers = append(peers, peer) peer.Start() - c, err := peer.Dial(sw.NetAddress()) + c, err := peer.Dial(sw.NetAddr()) require.NoError(t, err) // spawn a reading routine to prevent connection from closing go func(c net.Conn) { @@ -712,7 +712,7 @@ func TestSwitchAcceptRoutine(t *testing.T) { // 2. check we close new connections if we already have MaxNumInboundPeers peers peer := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} peer.Start() - conn, err := peer.Dial(sw.NetAddress()) + conn, err := peer.Dial(sw.NetAddr()) require.NoError(t, err) // check conn is closed one := make([]byte, 1) @@ -724,7 +724,7 @@ func TestSwitchAcceptRoutine(t *testing.T) { // 3. check we connect to unconditional peers despite the limit. for _, peer := range unconditionalPeers { - c, err := peer.Dial(sw.NetAddress()) + c, err := peer.Dial(sw.NetAddr()) require.NoError(t, err) // spawn a reading routine to prevent connection from closing go func(c net.Conn) { @@ -754,15 +754,15 @@ type errorTransport struct { var _ Transport = errorTransport{} -func (errorTransport) NetAddress() na.NetAddress { +func (errorTransport) NetAddr() na.NetAddr { panic("not implemented") } -func (et errorTransport) Accept() (net.Conn, *na.NetAddress, error) { +func (et errorTransport) Accept() (net.Conn, *na.NetAddr, error) { return nil, nil, et.acceptErr } -func (errorTransport) Dial(na.NetAddress) (net.Conn, error) { +func (errorTransport) Dial(na.NetAddr) (net.Conn, error) { panic("not implemented") } @@ -848,7 +848,7 @@ func TestSwitch_InitPeerIsNotCalledBeforeRemovePeer(t *testing.T) { rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg} rp.Start() defer rp.Stop() - _, err = rp.Dial(sw.NetAddress()) + _, err = rp.Dial(sw.NetAddr()) require.NoError(t, err) // wait till the switch adds rp to the peer set, then stop the peer asynchronously @@ -861,7 +861,7 @@ func TestSwitch_InitPeerIsNotCalledBeforeRemovePeer(t *testing.T) { } // simulate peer reconnecting to us - _, err = rp.Dial(sw.NetAddress()) + _, err = rp.Dial(sw.NetAddr()) require.NoError(t, err) // wait till the switch adds rp to the peer set time.Sleep(50 * time.Millisecond) diff --git a/p2p/test_util.go b/p2p/test_util.go index da235e851f1..d07110205e3 100644 --- a/p2p/test_util.go +++ b/p2p/test_util.go @@ -10,7 +10,7 @@ import ( 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/netaddress" + 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" @@ -210,8 +210,8 @@ func MakeSwitch( PrivKey: ed25519.GenPrivKey(), } nodeInfo := testNodeInfo(nk.ID(), fmt.Sprintf("node%d", i)) - addr, err := na.NewNetAddressString( - na.IDAddressString(nk.ID(), nodeInfo.ListenAddr), + addr, err := na.NewFromString( + na.IDAddrString(nk.ID(), nodeInfo.ListenAddr), ) if err != nil { panic(err) @@ -253,7 +253,7 @@ func testPeerConn( cfg *config.P2PConfig, outbound, persistent bool, // _ourNodePrivKey crypto.PrivKey, - socketAddr *na.NetAddress, + socketAddr *na.NetAddr, ) (pc peerConn, err error) { conn := rawConn @@ -278,26 +278,26 @@ type AddrBookMock struct { var _ AddrBook = (*AddrBookMock)(nil) -func (book *AddrBookMock) AddAddress(addr *na.NetAddress, _ *na.NetAddress) error { +func (book *AddrBookMock) AddAddress(addr *na.NetAddr, _ *na.NetAddr) error { book.Addrs[addr.String()] = struct{}{} return nil } -func (book *AddrBookMock) AddOurAddress(addr *na.NetAddress) { +func (book *AddrBookMock) AddOurAddress(addr *na.NetAddr) { book.OurAddrs[addr.String()] = struct{}{} } -func (book *AddrBookMock) OurAddress(addr *na.NetAddress) bool { +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.NetAddress) bool { +func (book *AddrBookMock) HasAddress(addr *na.NetAddr) bool { _, ok := book.Addrs[addr.String()] return ok } -func (book *AddrBookMock) RemoveAddress(addr *na.NetAddress) { +func (book *AddrBookMock) RemoveAddress(addr *na.NetAddr) { delete(book.Addrs, addr.String()) } func (*AddrBookMock) Save() {} @@ -308,11 +308,11 @@ func (book *AddrBookMock) AddPrivateIDs(addrs []string) { } type mockNodeInfo struct { - addr *na.NetAddress + addr *na.NetAddr } func (ni mockNodeInfo) ID() nodekey.ID { return ni.addr.ID } -func (ni mockNodeInfo) NetAddress() (*na.NetAddress, error) { return ni.addr, nil } +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 } diff --git a/p2p/transport.go b/p2p/transport.go index dc48dce87f3..327e8ad2ce6 100644 --- a/p2p/transport.go +++ b/p2p/transport.go @@ -5,7 +5,7 @@ import ( "github.com/cosmos/gogoproto/proto" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" ) // peerConfig is used to bundle data we need to fully setup a Peer with an @@ -21,7 +21,7 @@ type peerConfig struct { // isPersistent allows you to set a function, which, given socket address // (for outbound peers) OR self-reported address (for inbound peers), tells // if the peer is persistent or not. - isPersistent func(*na.NetAddress) bool + isPersistent func(*na.NetAddr) bool reactorsByCh map[byte]Reactor msgTypeByChID map[byte]proto.Message metrics *Metrics @@ -31,14 +31,14 @@ type peerConfig struct { // the transport. Each transport is also responsible to filter establishing // peers specific to its domain. type Transport interface { - // NetAddress returns the NetAddress of the local node. - NetAddress() na.NetAddress + // NetAddr returns the network address of the local node. + NetAddr() na.NetAddr // Accept waits for and returns the next connection to the local node. - Accept() (net.Conn, *na.NetAddress, error) + Accept() (net.Conn, *na.NetAddr, error) // Dial dials the given address and returns a connection. - Dial(addr na.NetAddress) (net.Conn, error) + Dial(addr na.NetAddr) (net.Conn, error) // Cleanup any resources associated with the given connection. // diff --git a/p2p/transport/tcp/errors.go b/p2p/transport/tcp/errors.go index cdf3c192373..787b4345bd4 100644 --- a/p2p/transport/tcp/errors.go +++ b/p2p/transport/tcp/errors.go @@ -4,7 +4,7 @@ import ( "fmt" "net" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" ) @@ -25,7 +25,7 @@ func (ErrFilterTimeout) Error() string { // ErrRejected indicates that a Peer was rejected carrying additional // information as to the reason. type ErrRejected struct { - addr na.NetAddress + addr na.NetAddr conn net.Conn err error id nodekey.ID @@ -34,8 +34,8 @@ type ErrRejected struct { isFiltered bool } -// Addr returns the NetAddress for the rejected Peer. -func (e ErrRejected) Addr() na.NetAddress { +// Addr returns the network address for the rejected Peer. +func (e ErrRejected) Addr() na.NetAddr { return e.addr } diff --git a/p2p/transport/tcp/tcp.go b/p2p/transport/tcp/tcp.go index a155ca74e9f..9a6f795e3f8 100644 --- a/p2p/transport/tcp/tcp.go +++ b/p2p/transport/tcp/tcp.go @@ -10,7 +10,7 @@ import ( "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/p2p/internal/fuzz" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" "github.com/cometbft/cometbft/p2p/transport/tcp/conn" ) @@ -29,7 +29,7 @@ type IPResolver interface { // accept is the container to carry the upgraded connection from an // asynchronously running routine to the Accept method. type accept struct { - netAddr *na.NetAddress + netAddr *na.NetAddr conn net.Conn err error } @@ -38,7 +38,7 @@ type accept struct { // behavior. type transportLifecycle interface { Close() error - Listen(addr na.NetAddress) error + Listen(addr na.NetAddr) error } // ConnFilterFunc to be implemented by filter hooks after a new connection has @@ -98,7 +98,7 @@ func MultiplexTransportMaxIncomingConnections(n int) MultiplexTransportOption { // MultiplexTransport accepts and dials tcp connections and upgrades them to // multiplexed peers. type MultiplexTransport struct { - netAddr na.NetAddress + netAddr na.NetAddr listener net.Listener maxIncomingConnections int // see MaxIncomingConnections @@ -144,13 +144,13 @@ func NewMultiplexTransport( } } -// NetAddress implements Transport. -func (mt *MultiplexTransport) NetAddress() na.NetAddress { +// NetAddr implements Transport. +func (mt *MultiplexTransport) NetAddr() na.NetAddr { return mt.netAddr } // Accept implements Transport. -func (mt *MultiplexTransport) Accept() (net.Conn, *na.NetAddress, error) { +func (mt *MultiplexTransport) Accept() (net.Conn, *na.NetAddr, error) { select { // This case should never have any side-effectful/blocking operations to // ensure that quality peers are ready to be used. @@ -169,7 +169,7 @@ func (mt *MultiplexTransport) Accept() (net.Conn, *na.NetAddress, error) { // Dial implements Transport. func (mt *MultiplexTransport) Dial( - addr na.NetAddress, + addr na.NetAddr, ) (net.Conn, error) { c, err := addr.DialTimeout(mt.dialTimeout) if err != nil { @@ -206,7 +206,7 @@ func (mt *MultiplexTransport) Close() error { } // Listen implements transportLifecycle. -func (mt *MultiplexTransport) Listen(addr na.NetAddress) error { +func (mt *MultiplexTransport) Listen(addr na.NetAddr) error { ln, err := net.Listen("tcp", addr.DialString()) if err != nil { return err @@ -267,7 +267,7 @@ func (mt *MultiplexTransport) acceptPeers() { var ( secretConn *conn.SecretConnection - netAddr *na.NetAddress + netAddr *na.NetAddr ) err := mt.filterConn(c) @@ -276,7 +276,7 @@ func (mt *MultiplexTransport) acceptPeers() { if err == nil { addr := c.RemoteAddr() id := nodekey.PubKeyToID(secretConn.RemotePubKey()) - netAddr = na.NewNetAddress(id, addr) + netAddr = na.New(id, addr) } } @@ -343,7 +343,7 @@ func (mt *MultiplexTransport) filterConn(c net.Conn) (err error) { func (mt *MultiplexTransport) upgrade( c net.Conn, - dialedAddr *na.NetAddress, + dialedAddr *na.NetAddr, ) (secretConn *conn.SecretConnection, err error) { defer func() { if err != nil { diff --git a/p2p/transport/tcp/tcp_test.go b/p2p/transport/tcp/tcp_test.go index f651c48fe54..644bba97c53 100644 --- a/p2p/transport/tcp/tcp_test.go +++ b/p2p/transport/tcp/tcp_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/cometbft/cometbft/crypto/ed25519" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" "github.com/cometbft/cometbft/p2p/nodekey" "github.com/cometbft/cometbft/p2p/transport/tcp/conn" ) @@ -42,7 +42,7 @@ func TestTransportMultiplex_ConnFilter(t *testing.T) { }, )(mt) - addr, err := na.NewNetAddressString(na.IDAddressString(id, "127.0.0.1:0")) + addr, err := na.NewFromString(na.IDAddrString(id, "127.0.0.1:0")) if err != nil { t.Fatal(err) } @@ -54,7 +54,7 @@ func TestTransportMultiplex_ConnFilter(t *testing.T) { errc := make(chan error) go func() { - addr := na.NewNetAddress(id, mt.listener.Addr()) + addr := na.New(id, mt.listener.Addr()) _, err := addr.Dial() if err != nil { @@ -95,7 +95,7 @@ func TestTransportMultiplex_ConnFilterTimeout(t *testing.T) { }, )(mt) - addr, err := na.NewNetAddressString(na.IDAddressString(id, "127.0.0.1:0")) + addr, err := na.NewFromString(na.IDAddrString(id, "127.0.0.1:0")) if err != nil { t.Fatal(err) } @@ -106,7 +106,7 @@ func TestTransportMultiplex_ConnFilterTimeout(t *testing.T) { errc := make(chan error) go func() { - addr := na.NewNetAddress(id, mt.listener.Addr()) + addr := na.New(id, mt.listener.Addr()) _, err := addr.Dial() if err != nil { @@ -138,7 +138,7 @@ func TestTransportMultiplex_MaxIncomingConnections(t *testing.T) { MultiplexTransportMaxIncomingConnections(0)(mt) - addr, err := na.NewNetAddressString(na.IDAddressString(id, "127.0.0.1:0")) + addr, err := na.NewFromString(na.IDAddrString(id, "127.0.0.1:0")) if err != nil { t.Fatal(err) } @@ -148,7 +148,7 @@ func TestTransportMultiplex_MaxIncomingConnections(t *testing.T) { t.Fatal(err) } - laddr := na.NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + laddr := na.New(mt.nodeKey.ID(), mt.listener.Addr()) // Connect more peers than max for i := 0; i <= maxIncomingConns; i++ { @@ -175,7 +175,7 @@ func TestTransportMultiplex_MaxIncomingConnections(t *testing.T) { func TestTransportMultiplex_AcceptMultiple(t *testing.T) { mt := testSetupMultiplexTransport(t) - laddr := na.NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + laddr := na.New(mt.nodeKey.ID(), mt.listener.Addr()) var ( seed = rand.New(rand.NewSource(time.Now().UnixNano())) @@ -222,7 +222,7 @@ func TestTransportMultiplex_AcceptMultiple(t *testing.T) { } } -func testDialer(dialAddr na.NetAddress, errc chan error) { +func testDialer(dialAddr na.NetAddr, errc chan error) { var ( pv = ed25519.GenPrivKey() dialer = newMultiplexTransport( @@ -255,7 +255,7 @@ func TestTransportMultiplexAcceptNonBlocking(t *testing.T) { // Simulate slow Peer. go func() { - addr := na.NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + addr := na.New(mt.nodeKey.ID(), mt.listener.Addr()) c, err := addr.Dial() if err != nil { @@ -295,7 +295,7 @@ func TestTransportMultiplexAcceptNonBlocking(t *testing.T) { PrivKey: fastNodePV, }, ) - addr := na.NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) + addr := na.New(mt.nodeKey.ID(), mt.listener.Addr()) _, err := dialer.Dial(*addr) if err != nil { @@ -331,7 +331,7 @@ func TestTransportMultiplexDialRejectWrongID(t *testing.T) { ) wrongID := nodekey.PubKeyToID(ed25519.GenPrivKey().PubKey()) - addr := na.NewNetAddress(wrongID, mt.listener.Addr()) + addr := na.New(wrongID, mt.listener.Addr()) _, err := dialer.Dial(*addr) if err != nil { @@ -385,7 +385,7 @@ func testSetupMultiplexTransport(t *testing.T) *MultiplexTransport { ) ) - addr, err := na.NewNetAddressString(na.IDAddressString(id, "127.0.0.1:0")) + addr, err := na.NewFromString(na.IDAddrString(id, "127.0.0.1:0")) if err != nil { t.Fatal(err) } diff --git a/rpc/core/net.go b/rpc/core/net.go index 1b79dcbe482..003b0e487df 100644 --- a/rpc/core/net.go +++ b/rpc/core/net.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/cometbft/cometbft/p2p" - na "github.com/cometbft/cometbft/p2p/netaddress" + na "github.com/cometbft/cometbft/p2p/netaddr" ni "github.com/cometbft/cometbft/p2p/nodeinfo" ctypes "github.com/cometbft/cometbft/rpc/core/types" rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" @@ -142,7 +142,7 @@ func getIDs(peers []string) ([]string, error) { for _, peer := range peers { spl := strings.Split(peer, "@") if len(spl) != 2 { - return nil, na.ErrNetAddressNoID{Addr: peer} + return nil, na.ErrNoID{Addr: peer} } ids = append(ids, spl[0]) }