Skip to content

wire: ignore retired Tor v2 addresses in addr messages - #2663

Open
Harshil-1603 wants to merge 1 commit into
btcsuite:masterfrom
Harshil-1603:fix/ignore-torv2-addresses
Open

Harshil-1603 wants to merge 1 commit into
btcsuite:masterfrom
Harshil-1603:fix/ignore-torv2-addresses

Conversation

@Harshil-1603

Copy link
Copy Markdown

Change Description

BIP-155 requires retired Tor v2 addresses to be ignored on receipt and never relayed. Both legacy addr messages using OnionCat encoding and addrv2 messages currently retain and serialize them.

Skip Tor v2 entries when decoding both message types and filter them when encoding, writing the count of entries actually emitted. The addrv2 decoder consumes the complete address and port before signaling a skipped network ID, preserving subsequent entries. IPv4 and Tor v3 addresses remain intact; the historical address conversion helpers remain available.

Fixes #2660 for network address message reception and relay.

Steps to Test

  • New mixed-address decode/encode regressions fail on the base revision and pass with this change.
  • make unit and make unit-race across all ten modules using an in-tree workspace so downstream tests use the changed wire module.
  • go vet ./..., go build ./..., git diff --check, and golangci-lint v2.15.0 against the actual upstream base (dd169fe): no new findings. The configured older lint baseline reports 16 pre-existing root findings. The wire check also has no new findings against dd169fe; the configured older baseline reports 12 pre-existing errcheck findings in unrelated wire files.

Pull Request Checklist

  • Hosted CI passes (pending maintainer workflow approval).
  • Regression tests cover ignored addresses, entry counts, stream alignment, and unaffected networks.
  • The change is a substantive protocol fix.
  • New code follows repository formatting and documentation conventions.

Specification: https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki

AI assistance: prepared with Codex and verified using the checks above.

@allocz allocz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code makes sense, but needs refactoring. Commit message should explain the objective of the patch, and what was done to fulfill the objective.

Comment thread wire/torv2_gossip_test.go Outdated
Comment on lines +10 to +92
func TestAddrMessagesIgnoreTorV2(t *testing.T) {
ip := net.ParseIP("8.8.8.8")
onion := net.ParseIP("fd87:d87e:eb43:2020:2020:2020:2020:2020")
legacy := []*NetAddress{
NewNetAddressIPPort(ip, 8333, SFNodeNetwork),
NewNetAddressIPPort(onion, 8333, SFNodeNetwork),
NewNetAddressIPPort(net.ParseIP("1.1.1.1"), 8333, SFNodeNetwork),
}
now := time.Unix(1700000000, 0)
v2 := []*NetAddressV2{
NetAddressV2FromBytes(now, SFNodeNetwork, ip, 8333),
NetAddressV2FromBytes(now, SFNodeNetwork, onion, 8333),
NetAddressV2FromBytes(now, SFNodeNetwork, bytes.Repeat([]byte{1}, TorV3Size), 8333),
NetAddressV2FromBytes(now, SFNodeNetwork, net.ParseIP("1.1.1.1"), 8333),
}
t.Run("legacy", func(t *testing.T) {
var raw bytes.Buffer
if err := WriteVarInt(&raw, ProtocolVersion, uint64(len(legacy))); err != nil {
t.Fatal(err)
}
for _, addr := range legacy {
if err := writeNetAddress(&raw, ProtocolVersion, addr, true); err != nil {
t.Fatal(err)
}
}
var decoded MsgAddr
if err := decoded.BtcDecode(&raw, ProtocolVersion, BaseEncoding); err != nil {
t.Fatal(err)
}
if len(decoded.AddrList) != 2 || raw.Len() != 0 {
t.Fatalf("decode retained Tor v2: %d addresses, %d trailing bytes", len(decoded.AddrList), raw.Len())
}
var encoded bytes.Buffer
if err := (&MsgAddr{AddrList: legacy}).BtcEncode(&encoded, ProtocolVersion, BaseEncoding); err != nil {
t.Fatal(err)
}
if encoded.Bytes()[0] != 2 {
t.Fatalf("encoded address count %d, want 2", encoded.Bytes()[0])
}
var roundTrip MsgAddr
if err := roundTrip.BtcDecode(&encoded, ProtocolVersion, BaseEncoding); err != nil {
t.Fatal(err)
}
if len(roundTrip.AddrList) != 2 || encoded.Len() != 0 {
t.Fatal("incorrect filtered payload")
}
})
t.Run("addrv2", func(t *testing.T) {
var raw bytes.Buffer
if err := WriteVarInt(&raw, ProtocolVersion, uint64(len(v2))); err != nil {
t.Fatal(err)
}
for _, addr := range v2 {
if err := writeNetAddressV2(&raw, ProtocolVersion, addr); err != nil {
t.Fatal(err)
}
}
var decoded MsgAddrV2
if err := decoded.BtcDecode(&raw, ProtocolVersion, BaseEncoding); err != nil {
t.Fatal(err)
}
if len(decoded.AddrList) != 3 || raw.Len() != 0 {
t.Fatalf("decode retained Tor v2: %d addresses, %d trailing bytes", len(decoded.AddrList), raw.Len())
}
if !decoded.AddrList[1].IsTorV3() {
t.Fatal("Tor v3 was not retained")
}
var encoded bytes.Buffer
if err := (&MsgAddrV2{AddrList: v2}).BtcEncode(&encoded, ProtocolVersion, BaseEncoding); err != nil {
t.Fatal(err)
}
if encoded.Bytes()[0] != 3 {
t.Fatalf("encoded address count %d, want 3", encoded.Bytes()[0])
}
var roundTrip MsgAddrV2
if err := roundTrip.BtcDecode(&encoded, ProtocolVersion, BaseEncoding); err != nil {
t.Fatal(err)
}
if len(roundTrip.AddrList) != 3 || encoded.Len() != 0 {
t.Fatal("incorrect filtered payload")
}
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test code does not follow the formatting rules.

Comment thread wire/msgaddrv2.go Outdated
count := len(m.AddrList)
count := 0
for _, na := range m.AddrList {
if _, retired := na.Addr.(*torv2Addr); !retired {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not a common syntax for _, ok type assertion, also, I would like to see comments explaining better the reasoning about what you are doing in the code, as this makes the code more readable. Remember to use empty lines between logical stanzas.

@allocz allocz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Commits can be squashed.

Note that this is breaking change, as several of the modified procedures are exported, which now have a new behavior, and therefore a major version bump is required if we don't want to break dependents.

Comment thread wire/msgaddrv2.go Outdated

// Tor v2 is retired; keep its entries out of outgoing addr messages.
for _, na := range m.AddrList {
_, ok := na.Addr.(*torv2Addr)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that the comment // Tor v2 is retired; keep its entries out of outgoing addr messages. should be above this line, right? Also you can use just if _, ok := na.Addr.(*torv2Addr).

Comment thread wire/netaddressv2.go Outdated
Comment on lines +391 to +393
// Consume the complete entry before skipping it so the next
// address remains aligned in the enclosing addrv2 message.
return ErrSkippedNetworkID

@allocz allocz Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this way, bad tor v2 addresses may fail with ErrInvalidAddressSize, and the BIP-0155 specifies that we should handle the torv2 net ID as if it is unknown, so you can instead edit this commit with the following patch:

diff --git a/wire/netaddressv2.go b/wire/netaddressv2.go
index f269bb72..abbad930 100644
--- a/wire/netaddressv2.go
+++ b/wire/netaddressv2.go
@@ -301,13 +301,7 @@ func readNetAddressV2(r io.Reader, pver uint32, na *NetAddressV2) error {
                return err
        }

-       if !isKnownNetworkID(netID) {
-               // In the case of an unknown networkID, we'll read the address
-               // size and error with ErrInvalidAddressSize if it's greater
-               // than maxAddrV2Size. If the address size is within the valid
-               // range, we'll just read and discard the address. In this
-               // case, ErrSkippedNetworkID will be returned to signal to the
-               // caller to continue reading.
+       consumeAddrBytes := func(r io.Reader) error {
                if decodedSize > maxAddrV2Size {
                        return ErrInvalidAddressSize
                }
@@ -318,6 +312,21 @@ func readNetAddressV2(r io.Reader, pver uint32, na *NetAddressV2) error {
                        return err
                }

+               return nil
+       }
+
+       if !isKnownNetworkID(netID) {
+               // In the case of an unknown networkID, we'll read the address
+               // size and error with ErrInvalidAddressSize if it's greater
+               // than maxAddrV2Size. If the address size is within the valid
+               // range, we'll just read and discard the address. In this
+               // case, ErrSkippedNetworkID will be returned to signal to the
+               // caller to continue reading.
+               err := consumeAddrBytes(r)
+               if err != nil {
+                       return err
+               }
+
                return ErrSkippedNetworkID
        }

@@ -373,24 +382,16 @@ func readNetAddressV2(r io.Reader, pver uint32, na *NetAddressV2) error {
                        return ErrSkippedNetworkID
                }
        case torv2:
-               addr := &torv2Addr{}
-               addr.netID = torv2
-               if decodedSize != uint64(torv2Size) {
-                       return ErrInvalidAddressSize
-               }
-
-               if err := readElement(r, &addr.addr); err != nil {
-                       return err
-               }
-
-               na.Port, err = binarySerializer.Uint16(r, bigEndian)
+               // BIP-0155 requires torv2 addresses to be processed as if the
+               // network is unknown. So we just consume the address bytes and
+               // then return ErrSkippedNetworkID.
+               err := consumeAddrBytes(r)
                if err != nil {
                        return err
                }

-               // Consume the complete entry before skipping it so the next
-               // address remains aligned in the enclosing addrv2 message.
                return ErrSkippedNetworkID
+
        case torv3:
                addr := &torv3Addr{}
                addr.netID = torv3
diff --git a/wire/netaddressv2_test.go b/wire/netaddressv2_test.go
index d3b28b22..f631ddc6 100644
--- a/wire/netaddressv2_test.go
+++ b/wire/netaddressv2_test.go
@@ -265,11 +265,14 @@ func TestReadNetAddressV2(t *testing.T) {
                        nil,
                },

-               // Invalid torv2 size.
+               // Torv2 with an unexpected size is skipped.
                {
-                       []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x02},
+                       []byte{
+                               0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x01,
+                               0x02, 0x03, 0x00, 0x00,
+                       },
                        "",
-                       ErrInvalidAddressSize,
+                       ErrSkippedNetworkID,
                },

                // Retired torv2 encoding is consumed and ignored.

@Harshil-1603
Harshil-1603 force-pushed the fix/ignore-torv2-addresses branch from ccb51d9 to 8a40d08 Compare November 14, 2026 08:32

@allocz allocz left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can add new test table entries into the tests that already exists instead of just creating new tests for procedures that already have test tables for, for example, readAddressV2 already has TestReadNetAddressV2, MsgAddrV2.BtcDecode already has TestAddrV2Decode, etc. Tbh we can even test the readNetAddressV2 indirectly in the table that tests MsgAddrV2.BtcDecode.

@allocz allocz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've rewritten the tests of msgaddr and msgaddrv2 and also added more test
cases.

As encoding and decoding are not symmetric it's better to keep the tests
split in the case of the msgaddr and msgaddrv2, so some of the tests
were rewritten and more test cases were added.

I think that now the tests are simpler and easier to read.

My suggestions are the following

  1. Keep the following patch as the only commit of the PR
  2. Update the commit description to close the PR #2684
  3. I think that you can put me as Co-Author of the commit
    (allocz alloczr@gmail.com), as I've spent a significant amount of time
    rewriting the tests.

full patch (against master):

diff --git a/wire/msgaddr.go b/wire/msgaddr.go
index 4b2b193b..b9327a9f 100644
--- a/wire/msgaddr.go
+++ b/wire/msgaddr.go
@@ -83,6 +83,10 @@ func (msg *MsgAddr) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) err
                if err != nil {
                        return err
                }
+               // Tor v2 is retired and must not be relayed.
+               if isOnionCatTor(na.IP) {
+                       continue
+               }
                msg.AddAddress(na)
        }
        return nil
@@ -93,7 +97,12 @@ func (msg *MsgAddr) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) err
 func (msg *MsgAddr) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
        // Protocol versions before MultipleAddressVersion only allowed 1 address
        // per message.
-       count := len(msg.AddrList)
+       count := 0
+       for _, na := range msg.AddrList {
+               if !isOnionCatTor(na.IP) {
+                       count++
+               }
+       }
        if pver < MultipleAddressVersion && count > 1 {
                str := fmt.Sprintf("too many addresses for message of "+
                        "protocol version %v [count %v, max 1]", pver, count)
@@ -112,6 +121,9 @@ func (msg *MsgAddr) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) err
        }

        for _, na := range msg.AddrList {
+               if isOnionCatTor(na.IP) {
+                       continue
+               }
                err = writeNetAddress(w, pver, na, true)
                if err != nil {
                        return err
diff --git a/wire/msgaddr_test.go b/wire/msgaddr_test.go
index 7516d324..17db399b 100644
--- a/wire/msgaddr_test.go
+++ b/wire/msgaddr_test.go
@@ -97,110 +97,256 @@ func TestAddr(t *testing.T) {
        }
 }

-// TestAddrWire tests the MsgAddr wire encode and decode for various numbers
-// of addresses and protocol versions.
-func TestAddrWire(t *testing.T) {
-       // A couple of NetAddresses to use for testing.
-       na := &NetAddress{
-               Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST
-               Services:  SFNodeNetwork,
-               IP:        net.ParseIP("127.0.0.1"),
-               Port:      8333,
+// TestAddrEncode checks that encoding an addr message produces the expected
+// serialized output with different protocol versions, an number of addresses.
+func TestAddrEncode(t *testing.T) {
+       t.Parallel()
+
+       pver := ProtocolVersion
+       enc := BaseEncoding
+
+       ts := time.Unix(0x00000001, 0)
+       tsStr := "01000000"
+
+       sf := SFNodeNetwork
+       sfStr := "0100000000000000"
+
+       port := uint16(0x0001)
+       portStr := "0001"
+
+       // ipv4 host.
+       ipv4HostStr := "000000000000000000000000" + "00000001"
+       ipv4Host := mustHex(ipv4HostStr)
+
+       // ipv6 v4 mapped host.
+       ipv6v4HostStr := "00000000000000000000FFFF00000001"
+       ipv6v4Host := mustHex(ipv6v4HostStr)
+
+       // ipv6 host.
+       ipv6HostStr := "20010DB8000000000000000000000001"
+       ipv6Host := mustHex(ipv6HostStr)
+
+       // ipv6 onionCat torv2 host.
+       onionCatPrefix := "FD87D87EEB43"
+       ipv6OnionCatHostStr := onionCatPrefix + "00000000000000000001"
+       ipv6OnionCatHost := mustHex(ipv6OnionCatHostStr)
+
+       addresses0 := []*NetAddress{
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       IP:        ipv4Host,
+                       Port:      port,
+               },
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       IP:        ipv6v4Host,
+                       Port:      port,
+               },
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       IP:        ipv6Host,
+                       Port:      port,
+               },
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       IP:        ipv6OnionCatHost,
+                       Port:      port,
+               },
        }
-       na2 := &NetAddress{
-               Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST
-               Services:  SFNodeNetwork,
-               IP:        net.ParseIP("192.168.0.1"),
-               Port:      8334,
+
+       msgEncoded0 := mustHexAppend(
+               "03", // addr count
+
+               tsStr,
+               sfStr,
+               ipv4HostStr,
+               portStr,
+
+               tsStr,
+               sfStr,
+               ipv6v4HostStr,
+               portStr,
+
+               tsStr,
+               sfStr,
+               ipv6HostStr,
+               portStr,
+
+               // onionCat torv2 must be skipped (BIP-0155).
+       )
+
+       tests := []struct {
+               name        string
+               msg         *MsgAddr
+               wantEncoded []byte
+               pver        uint32
+       }{
+               {
+                       "latest protocol version with no addresses",
+                       &MsgAddr{},
+                       mustHex("00"), // length of zero.
+                       pver,
+               },
+               {
+                       "skip encoding torv2 addr between multiple addresses",
+                       &MsgAddr{AddrList: addresses0},
+                       msgEncoded0,
+                       pver,
+               },
+               {
+                       "protocol version MultipleAddressVersion-1 with no " +
+                               "addresses",
+                       &MsgAddr{},
+                       mustHex("00"), // length of zero.
+                       MultipleAddressVersion - 1,
+               },
        }

-       // Empty address message.
-       noAddr := NewMsgAddr()
-       noAddrEncoded := []byte{
-               0x00, // Varint for number of addresses
+       for _, test := range tests {
+               t.Run(test.name, func(t *testing.T) {
+                       var buf bytes.Buffer
+
+                       err := test.msg.BtcEncode(&buf, pver, enc)
+                       if err != nil {
+                               t.Fatalf("unexpected error: %s", err)
+                       }
+
+                       if !bytes.Equal(test.wantEncoded, buf.Bytes()) {
+                               t.Fatalf("bad encoding; \nwant: %x\n got: %x",
+                                       test.wantEncoded, buf.Bytes())
+                       }
+               })
        }
+}

-       // Address message with multiple addresses.
-       multiAddr := NewMsgAddr()
-       multiAddr.AddAddresses(na, na2)
-       multiAddrEncoded := []byte{
-               0x02,                   // Varint for number of addresses
-               0x29, 0xab, 0x5f, 0x49, // Timestamp
-               0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // SFNodeNetwork
-               0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-               0x00, 0x00, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x01, // IP 127.0.0.1
-               0x20, 0x8d, // Port 8333 in big-endian
-               0x29, 0xab, 0x5f, 0x49, // Timestamp
-               0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // SFNodeNetwork
-               0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-               0x00, 0x00, 0xff, 0xff, 0xc0, 0xa8, 0x00, 0x01, // IP 192.168.0.1
-               0x20, 0x8e, // Port 8334 in big-endian
+// TestAddrDecode checks that decoding an addr message from the wire results
+// in the expected parsed data, with different protocol versions, an number of
+// addresses.
+func TestAddrDecode(t *testing.T) {
+       t.Parallel()
+
+       pver := ProtocolVersion
+       enc := BaseEncoding
+
+       ts := time.Unix(0x00000001, 0)
+       tsStr := "01000000"
+
+       sf := SFNodeNetwork
+       sfStr := "0100000000000000"
+
+       port := uint16(0x0001)
+       portStr := "0001"
+
+       // ipv4 host.
+       ipv4HostStr := "000000000000000000000000" + "00000001"
+       ipv4Host := mustHex(ipv4HostStr)
+
+       // ipv6 v4 mapped host.
+       ipv6v4HostStr := "00000000000000000000FFFF00000001"
+       ipv6v4Host := mustHex(ipv6v4HostStr)
+
+       // ipv6 host.
+       ipv6HostStr := "20010DB8000000000000000000000001"
+       ipv6Host := mustHex(ipv6HostStr)
+
+       // ipv6 onionCat torv2 host.
+       onionCatPrefix := "FD87D87EEB43"
+       ipv6OnionCatHostStr := onionCatPrefix + "00000000000000000001"
+
+       msgEncoded0 := mustHexAppend(
+               "04", // addr count
+
+               tsStr,
+               sfStr,
+               ipv4HostStr,
+               portStr,
+
+               tsStr,
+               sfStr,
+               ipv6v4HostStr,
+               portStr,

+               tsStr,
+               sfStr,
+               ipv6HostStr,
+               portStr,
+
+               tsStr,
+               sfStr,
+               ipv6OnionCatHostStr,
+               portStr,
+       )
+
+       addresses0 := []*NetAddress{
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       IP:        ipv4Host,
+                       Port:      port,
+               },
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       IP:        ipv6v4Host,
+                       Port:      port,
+               },
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       IP:        ipv6Host,
+                       Port:      port,
+               },
+
+               // torv2 addresses must be skipped (BIP-0155).
        }

        tests := []struct {
-               in   *MsgAddr        // Message to encode
-               out  *MsgAddr        // Expected decoded message
-               buf  []byte          // Wire encoding
-               pver uint32          // Protocol version for wire encoding
-               enc  MessageEncoding // Message encoding format
+               name    string
+               encoded []byte
+               wantMsg *MsgAddr
+               pver    uint32
        }{
-               // Latest protocol version with no addresses.
                {
-                       noAddr,
-                       noAddr,
-                       noAddrEncoded,
-                       ProtocolVersion,
-                       BaseEncoding,
+                       "latest protocol version with no addresses",
+                       mustHex("00"), // zero addresses.
+                       &MsgAddr{AddrList: []*NetAddress{}},
+                       pver,
                },
-
-               // Latest protocol version with multiple addresses.
                {
-                       multiAddr,
-                       multiAddr,
-                       multiAddrEncoded,
-                       ProtocolVersion,
-                       BaseEncoding,
+                       "skip encoding torv2 addr between multiple addresses",
+                       msgEncoded0,
+                       &MsgAddr{AddrList: addresses0},
+                       pver,
                },
-
-               // Protocol version MultipleAddressVersion-1 with no addresses.
                {
-                       noAddr,
-                       noAddr,
-                       noAddrEncoded,
+                       "protocol version MultipleAddressVersion-1 with no " +
+                               "addresses",
+                       mustHex("00"), // zero addresses.
+                       &MsgAddr{AddrList: []*NetAddress{}},
                        MultipleAddressVersion - 1,
-                       BaseEncoding,
                },
        }

-       t.Logf("Running %d tests", len(tests))
-       for i, test := range tests {
-               // Encode the message to wire format.
-               var buf bytes.Buffer
-               err := test.in.BtcEncode(&buf, test.pver, test.enc)
-               if err != nil {
-                       t.Errorf("BtcEncode #%d error %v", i, err)
-                       continue
-               }
-               if !bytes.Equal(buf.Bytes(), test.buf) {
-                       t.Errorf("BtcEncode #%d\n got: %s want: %s", i,
-                               spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
-                       continue
-               }
+       for _, test := range tests {
+               t.Run(test.name, func(t *testing.T) {
+                       var msg MsgAddr
+                       err := msg.BtcDecode(
+                               bytes.NewReader(test.encoded), pver, enc,
+                       )
+                       if err != nil {
+                               t.Fatalf("unexpected error: %s", err)
+                       }

-               // Decode the message from wire format.
-               var msg MsgAddr
-               rbuf := bytes.NewReader(test.buf)
-               err = msg.BtcDecode(rbuf, test.pver, test.enc)
-               if err != nil {
-                       t.Errorf("BtcDecode #%d error %v", i, err)
-                       continue
-               }
-               if !reflect.DeepEqual(&msg, test.out) {
-                       t.Errorf("BtcDecode #%d\n got: %s want: %s", i,
-                               spew.Sdump(msg), spew.Sdump(test.out))
-                       continue
-               }
+                       if !reflect.DeepEqual(test.wantMsg, &msg) {
+                               t.Fatalf("unexpected msg: \nwant:\n%s\ngot:"+
+                                       "\n%s", spew.Sdump(test.wantMsg),
+                                       spew.Sdump(&msg))
+                       }
+               })
        }
 }

diff --git a/wire/msgaddrv2.go b/wire/msgaddrv2.go
index 9edca51b..9d95d2f2 100644
--- a/wire/msgaddrv2.go
+++ b/wire/msgaddrv2.go
@@ -64,7 +64,16 @@ func (m *MsgAddrV2) BtcDecode(r io.Reader, pver uint32,
 func (m *MsgAddrV2) BtcEncode(w io.Writer, pver uint32,
        enc MessageEncoding) error {

-       count := len(m.AddrList)
+       // Count supported addresses so the header matches the payload.
+       count := 0
+       for _, na := range m.AddrList {
+               if _, ok := na.Addr.(*torv2Addr); ok {
+                       continue
+               }
+
+               count++
+       }
+
        if count > MaxV2AddrPerMsg {
                str := fmt.Sprintf("too many addresses for message: "+
                        "got %v, max %v", count, MaxV2AddrPerMsg)
@@ -77,6 +86,11 @@ func (m *MsgAddrV2) BtcEncode(w io.Writer, pver uint32,
        }

        for _, na := range m.AddrList {
+               // Tor v2 is retired; omit its entries from outgoing messages.
+               if _, ok := na.Addr.(*torv2Addr); ok {
+                       continue
+               }
+
                err = writeNetAddressV2(w, pver, na)
                if err != nil {
                        return err
diff --git a/wire/msgaddrv2_test.go b/wire/msgaddrv2_test.go
index 40abd567..bd40cec0 100644
--- a/wire/msgaddrv2_test.go
+++ b/wire/msgaddrv2_test.go
@@ -2,81 +2,450 @@ package wire

 import (
        "bytes"
-       "io"
+       "reflect"
        "testing"
+       "time"
+
+       "github.com/davecgh/go-spew/spew"
 )

+// TestAddrV2Encode checks that encoding an addrv2 message produces the expected
+// serialized output, ignoring certain addresses.
+func TestAddrV2Encode(t *testing.T) {
+       t.Parallel()
+
+       pver := ProtocolVersion
+       enc := BaseEncoding
+
+       ts := time.Unix(0x00000001, 0)
+       tsStr := "01000000"
+
+       sf := SFNodeNetwork
+       sfStr := "01"
+
+       port := uint16(0x0001)
+       portStr := "0001"
+
+       // IPV4 host.
+       ipv4HostStr := "00000001"
+       ipv4Host := ipv4Addr{
+               addr:  [ipv4Size]byte(mustHex(ipv4HostStr)),
+               netID: ipv4,
+       }
+
+       // IPV6 host.
+       ipv6HostStr := "20010DB8000000000000000000000001"
+       ipv6Host := ipv6Addr{
+               addr:  [ipv6Size]byte(mustHex(ipv6HostStr)),
+               netID: ipv6,
+       }
+
+       // Torv2 host.
+       torv2HostStr := "00000000000000000001"
+       torv2Host := torv2Addr{
+               addr:  [torv2Size]byte(mustHex(torv2HostStr)),
+               netID: torv2,
+       }
+
+       // Torv3 host.
+       torV3HostStr := "0000000000000000000000000000000000000000000000000000" +
+               "000000000001"
+       torv3Host := torv3Addr{
+               addr:  [TorV3Size]byte(mustHex(torV3HostStr)),
+               netID: torv3,
+       }
+
+       addresses0 := []*NetAddressV2{
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       Addr:      &ipv4Host,
+                       Port:      port,
+               },
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       Addr:      &ipv6Host,
+                       Port:      port,
+               },
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       Addr:      &torv2Host,
+                       Port:      port,
+               },
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       Addr:      &torv3Host,
+                       Port:      port,
+               },
+       }
+
+       msg0Encoded := mustHexAppend(
+               "03", // addr count
+
+               tsStr,
+               sfStr,
+               "01", // ipv4 NetId
+               "04", // addr length
+               ipv4HostStr,
+               portStr,
+
+               tsStr,
+               sfStr,
+               "02", // ipv6 NetId
+               "10", // addr length
+               ipv6HostStr,
+               portStr,
+
+               // torv2 is skipped as required by BIP-0155.
+
+               tsStr,
+               sfStr,
+               "04", // torv3 NetId
+               "20", // addr length
+               torV3HostStr,
+               portStr,
+       )
+
+       tests := []struct {
+               name string
+               msg  *MsgAddrV2
+               want []byte
+       }{
+               {
+                       "all supported addresses with torv2 not serialized",
+                       &MsgAddrV2{AddrList: addresses0},
+                       msg0Encoded,
+               },
+       }
+
+       for _, test := range tests {
+               t.Run(test.name, func(t *testing.T) {
+                       var buf bytes.Buffer
+
+                       err := test.msg.BtcEncode(&buf, pver, enc)
+                       if err != nil {
+                               t.Fatalf("unexpected error: %s", err)
+                       }
+
+                       if !bytes.Equal(test.want, buf.Bytes()) {
+                               t.Fatalf("unexpected encoding; \nwant: %x\n "+
+                                       "got: %x", test.want, buf.Bytes())
+                       }
+               })
+       }
+}
+
 // TestAddrV2Decode checks that decoding an addrv2 message off the wire behaves
-// as expected. This means ignoring certain addresses, and failing in certain
-// failure scenarios.
+// as expected, ignoring certain addresses.
 func TestAddrV2Decode(t *testing.T) {
+       t.Parallel()
+
+       pver := ProtocolVersion
+       enc := BaseEncoding
+
+       ts := time.Unix(0x00000001, 0)
+       tsStr := "01000000"
+
+       sf := SFNodeNetwork
+       sfStr := "01"
+
+       port := uint16(0x0001)
+       portStr := "0001"
+
+       // IPV4 host.
+       ipv4HostStr := "00000001"
+       ipv4Host := ipv4Addr{
+               addr:  [ipv4Size]byte(mustHex(ipv4HostStr)),
+               netID: ipv4,
+       }
+
+       // IPV6 mapped IPV4 host.
+       ipv6v4HostStr := "00000000000000000000FFFF" + "00000002"
+
+       // IPV6 host.
+       ipv6HostStr := "20010DB8000000000000000000000001"
+       ipv6Host := ipv6Addr{
+               addr:  [ipv6Size]byte(mustHex(ipv6HostStr)),
+               netID: ipv6,
+       }
+
+       // Torv2 host.
+       torv2HostStr := "00000000000000000001"
+
+       // IPV6 OnionCat encoded torv2 host.
+       onionCatPrefix := "FD87D87EEB43"
+       ipv6OnionCatTorv2String := onionCatPrefix + "00000000000000000002"
+
+       // Torv3 host.
+       torv3HostStr := "0000000000000000000000000000000000000000000000000000" +
+               "000000000001"
+       torv3Host := torv3Addr{
+               addr:  [TorV3Size]byte(mustHex(torv3HostStr)),
+               netID: torv3,
+       }
+
+       // i2p host.
+       i2pHostStr := "000000000000000000000000000000000000000000000000000000" +
+               "0000000001"
+
+       // cjdns host.
+       cjdnsHostStr := "00000000000000000000000000000001"
+
+       // iggdrasil host.
+       iggdrasilHostStr := "00000000000000000000000000000001"
+
+       msg0Encoded := mustHexAppend(
+               "09", // addr count
+
+               // ipv4.
+               tsStr,
+               sfStr,
+               "01", // ipv4 NetId
+               "04", // addr length
+               ipv4HostStr,
+               portStr,
+
+               // ipv6 v4 mapped.
+               tsStr,
+               sfStr,
+               "02", // ipv6 NetId
+               "10", // addr length
+               ipv6v4HostStr,
+               portStr,
+
+               // ipv6.
+               tsStr,
+               sfStr,
+               "02", // ipv6 NetId
+               "10", // addr length
+               ipv6HostStr,
+               portStr,
+
+               // ipv6 onioncat torv2.
+               tsStr,
+               sfStr,
+               "02", // ipv6 NetId
+               "10", // addr length
+               ipv6OnionCatTorv2String,
+               portStr,
+
+               // torv2.
+               tsStr,
+               sfStr,
+               "03", // torv2 NetId
+               "0A", // addr length
+               torv2HostStr,
+               portStr,
+
+               // torv3.
+               tsStr,
+               sfStr,
+               "04", // torv3 NetId
+               "20", // addr length
+               torv3HostStr,
+               portStr,
+
+               // i2p.
+               tsStr,
+               sfStr,
+               "05", // i2p NetId
+               "20", // addr length
+               i2pHostStr,
+               portStr,
+
+               // cjdns.
+               tsStr,
+               sfStr,
+               "06", // cjdns NetId
+               "10", // addr length
+               cjdnsHostStr,
+               portStr,
+
+               // iggdrasil.
+               tsStr,
+               sfStr,
+               "07", // iggdrasil NetId
+               "10", // addr length
+               iggdrasilHostStr,
+               portStr,
+       )
+
+       addresses0 := []*NetAddressV2{
+               // ipv4.
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       Addr:      &ipv4Host,
+                       Port:      port,
+               },
+
+               // ipv6 v4 mapped must be skipped.
+
+               // ipv6.
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       Addr:      &ipv6Host,
+                       Port:      port,
+               },
+
+               // ipv6 onioncat torv2: must be skipped (BIP-0155).
+
+               // torv2: must be skipped (BIP-0155).
+
+               // torv3.
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       Addr:      &torv3Host,
+                       Port:      port,
+               },
+
+               // i2p: should be skipped.
+
+               // cjdns: should be skipped.
+
+               // iggdrasil: should be skipped.
+       }
+
+       msg1Encoded := mustHexAppend(
+               "03", // addr count
+
+               // torv2 with wrong address size is skipped.
+               tsStr,
+               sfStr,
+               "03", // torv2 NetId
+               "01", // addr length
+               "00",
+               portStr,
+
+               // iggdrasil with wrong address size is skipped.
+               tsStr,
+               sfStr,
+               "07", // iggdrasil NetId
+               "01", // addr length
+               "00",
+               portStr,
+
+               // ipv4.
+               tsStr,
+               sfStr,
+               "01", // ipv4 NetId
+               "04", // addr length
+               ipv4HostStr,
+               portStr,
+       )
+
+       addresses1 := []*NetAddressV2{
+               {
+                       Timestamp: ts,
+                       Services:  sf,
+                       Addr:      &ipv4Host,
+                       Port:      port,
+               },
+       }
+
        tests := []struct {
-               buf           []byte
-               expectedError bool
-               expectedAddrs int
+               name string
+               msg  []byte
+               want *MsgAddrV2
        }{
-               // Exceeding max addresses.
                {
-                       []byte{0xfd, 0xff, 0xff},
-                       true,
-                       0,
+                       "all networks with torv2, cjdns, i2p and iggdrasil " +
+                               "skipped",
+                       msg0Encoded,
+                       &MsgAddrV2{AddrList: addresses0},
                },
-
-               // Invalid address size.
                {
-                       []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x05},
-                       true,
-                       0,
+                       "skip torv2 and iggdrasil with wrong address size",
+                       msg1Encoded,
+                       &MsgAddrV2{AddrList: addresses1},
                },
+       }
+
+       for _, test := range tests {
+               t.Run(test.name, func(t *testing.T) {
+                       var msg MsgAddrV2
+                       err := msg.BtcDecode(
+                               bytes.NewReader(test.msg), pver, enc,
+                       )
+                       if err != nil {
+                               t.Fatalf("unexpected error: %s", err)
+                       }

-               // One valid address and one skipped address
+                       if !reflect.DeepEqual(test.want, &msg) {
+                               t.Fatalf("unexpected message; \nwant:\n%s\n"+
+                                       "got:\n%s", spew.Sdump(test.want),
+                                       spew.Sdump(&msg))
+                       }
+               })
+       }
+}
+
+// TestAddrV2DecodeErrors perform negative tests for decoding addrv2 messages,
+// asserting that some bad messages causes errors.
+func TestAddrV2DecodeErrors(t *testing.T) {
+       t.Parallel()
+
+       pver := ProtocolVersion
+       enc := BaseEncoding
+
+       tests := []struct {
+               name    string
+               encoded []byte
+       }{
+               {
+                       "exceeding max addresses",
+                       mustHex("FDE903"), // 1001 in little endian compactSize
+               },
                {
-                       []byte{
-                               0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04,
-                               0x7f, 0x00, 0x00, 0x01, 0x22, 0x22, 0x00, 0x00,
-                               0x00, 0x00, 0x00, 0x02, 0x10, 0xfd, 0x87, 0xd8,
-                               0x7e, 0xeb, 0x43, 0xff, 0xfe, 0xcc, 0x39, 0xa8,
-                               0x73, 0x69, 0x15, 0xff, 0xff, 0x22, 0x22,
-                       },
-                       false,
-                       1,
+                       "invalid address size",
+                       mustHexAppend(
+                               "01",
+                               "00000000",
+                               "00",
+                               "01", // ipv4
+                               "05", // ipv4 length is 4, not 5 bytes
+                       ),
                },
-               // Truncated address.
                {
-                       []byte{
-                               0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04,
-                               0x7f, 0x00, 0x00,
-                       },
-                       true,
-                       0,
+                       "truncated address",
+                       mustHexAppend(
+                               "01",
+                               "00000000",
+                               "00",
+                               "01", // ipv4
+                               "04",
+                               "7F0000", // Three byte ipv4 address with
+                               // missing port.
+                       ),
+               },
+               {
+                       "missing port",
+                       mustHexAppend(
+                               "01",
+                               "00000000",
+                               "00",
+                               "01", // ipv4
+                               "04",
+                               "00000001",
+                               // port missing here
+                       ),
                },
        }

-       t.Logf("Running %d tests", len(tests))
-       for i, test := range tests {
-               r := bytes.NewReader(test.buf)
-               m := &MsgAddrV2{}
+       for _, test := range tests {
+               t.Run(test.name, func(t *testing.T) {
+                       var msg MsgAddrV2

-               err := m.BtcDecode(r, 0, LatestEncoding)
-               if test.expectedError {
+                       r := bytes.NewReader(test.encoded)
+                       err := msg.BtcDecode(r, pver, enc)
                        if err == nil {
-                               t.Errorf("Test #%d expected error", i)
+                               t.Fatalf("expecting error, but got nil")
                        }
-
-                       continue
-               } else if err != nil {
-                       t.Errorf("Test #%d unexpected error %v", i, err)
-               }
-
-               // Trying to read more should give EOF.
-               var b [1]byte
-               if _, err := r.Read(b[:]); err != io.EOF {
-                       t.Errorf("Test #%d did not cleanly finish reading", i)
-               }
-
-               if len(m.AddrList) != test.expectedAddrs {
-                       t.Errorf("Test #%d expected %d addrs, instead of %d",
-                               i, test.expectedAddrs, len(m.AddrList))
-               }
+               })
        }
 }
diff --git a/wire/netaddressv2.go b/wire/netaddressv2.go
index 1cf11234..62beea66 100644
--- a/wire/netaddressv2.go
+++ b/wire/netaddressv2.go
@@ -30,14 +30,14 @@ var (
        // maximum size for an unknown networkID.
        ErrInvalidAddressSize = fmt.Errorf("invalid address size")

-       // ErrSkippedNetworkID is returned when the cjdns, i2p, or unknown
-       // networks are encountered during decoding. btcd does not support i2p
-       // or cjdns addresses. In the case of an unknown networkID, this is so
-       // that a future BIP reserving a new networkID does not cause older
-       // addrv2-supporting btcd software to disconnect upon receiving the new
-       // addresses. This error can also be returned when an OnionCat-encoded
-       // torv2 address is received with the ipv6 networkID. This error
-       // signals to the caller to continue reading.
+       // ErrSkippedNetworkID is returned when the torv2, cjdns, i2p, or
+       // unknown networks are encountered during decoding. Tor v2 is retired
+       // per BIP-0155. btcd does not support i2p or cjdns addresses. For an
+       // unknown networkID, this is so that a future BIP reserving a new
+       // networkID does not cause older addrv2-supporting btcd software to
+       // disconnect upon receiving the new addresses. This error can also be
+       // returned when an OnionCat-encoded torv2 address is received with the
+       // ipv6 networkID. This error signals to the caller to continue reading.
        ErrSkippedNetworkID = fmt.Errorf("skipped networkID")
 )

@@ -300,8 +300,8 @@ func readNetAddressV2(r io.Reader, pver uint32, na *NetAddressV2) error {
                return err
        }

-       if !isKnownNetworkID(netID) {
-               // In the case of an unknown networkID, we'll read the address
+       if !isKnownNetworkID(netID) || networkID(netID) == torv2 {
+               // For unknown or retired Tor v2 networks, read the address
                // size and error with ErrInvalidAddressSize if it's greater
                // than maxAddrV2Size. If the address size is within the valid
                // range, we'll just read and discard the address. In this
@@ -371,23 +371,6 @@ func readNetAddressV2(r io.Reader, pver uint32, na *NetAddressV2) error {
                if isIPv4Mapped(addr.addr[:]) {
                        return ErrSkippedNetworkID
                }
-       case torv2:
-               addr := &torv2Addr{}
-               addr.netID = torv2
-               if decodedSize != uint64(torv2Size) {
-                       return ErrInvalidAddressSize
-               }
-
-               if err := readElement(r, &addr.addr); err != nil {
-                       return err
-               }
-
-               na.Port, err = binarySerializer.Uint16(r, bigEndian)
-               if err != nil {
-                       return err
-               }
-
-               na.Addr = addr
        case torv3:
                addr := &torv3Addr{}
                addr.netID = torv3
diff --git a/wire/netaddressv2_test.go b/wire/netaddressv2_test.go
index d9e7819e..abefe21f 100644
--- a/wire/netaddressv2_test.go
+++ b/wire/netaddressv2_test.go
@@ -265,22 +265,23 @@ func TestReadNetAddressV2(t *testing.T) {
                        nil,
                },

-               // Invalid torv2 size.
+               // Torv2 with an unexpected size is skipped.
                {
-                       []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x02},
+                       []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03,
+                               0x01, 0x02, 0x03, 0x00, 0x00},
                        "",
-                       ErrInvalidAddressSize,
+                       ErrSkippedNetworkID,
                },

-               // Valid torv2 encoding.
+               // Retired torv2 encoding is consumed and ignored.
                {
                        []byte{
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0a, 0x20,
                                0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
                                0x20, 0x22, 0x22,
                        },
-                       string(torv2),
-                       nil,
+                       "",
+                       ErrSkippedNetworkID,
                },

                // Invalid torv3 size.
@@ -343,6 +344,17 @@ func TestReadNetAddressV2(t *testing.T) {
                        string(cjdns),
                        ErrSkippedNetworkID,
                },
+               // Retired Tor v2 retains unknown-network error bounds.
+               {
+                       []byte{0, 0, 0, 0, 0, byte(torv2), 0xfd, 0x01, 0x02},
+                       "",
+                       ErrInvalidAddressSize,
+               },
+               {
+                       []byte{0, 0, 0, 0, 0, byte(torv2), 3, 1, 2},
+                       "",
+                       io.ErrUnexpectedEOF,
+               },
        }

        t.Logf("Running %d tests", len(tests))
diff --git a/wire/testhelpers_test.go b/wire/testhelpers_test.go
new file mode 100644
index 00000000..6d12e5e7
--- /dev/null
+++ b/wire/testhelpers_test.go
@@ -0,0 +1,25 @@
+package wire
+
+import (
+       "encoding/hex"
+)
+
+// mustHexAppend convert an hexadecimal string in a byte slice.
+func mustHex(hexStr string) []byte {
+       b, err := hex.DecodeString(hexStr)
+       if err != nil {
+               panic(err)
+       }
+
+       return b
+}
+
+// mustHexAppend convert multiple hexadecimal strings in a single byte slice.
+func mustHexAppend(hexStr ...string) []byte {
+       var buf []byte
+       for _, s := range hexStr {
+               buf = append(buf, mustHex(s)...)
+       }
+
+       return buf
+}

Do not relay retired Tor v2 addresses in legacy addr or addrv2 messages.
Consume bounded Tor v2 entries like unknown networks, including unusual
lengths, without misaligning following entries. Preserve oversize and
truncation errors, omit retired entries on encode and count only retained
entries.

Separate encoding and decoding tests, cover supported and skipped
networks, and check malformed frames. Apply allocz's review test rewrite,
using the case's protocol version and correctly named helper comments.

Refs btcsuite#2684.

Co-authored-by: allocz <alloczr@gmail.com>
Assisted-by: OpenAI Codex
@Harshil-1603
Harshil-1603 force-pushed the fix/ignore-torv2-addresses branch from 90d4f3d to 8df9014 Compare November 19, 2026 13:41

@allocz allocz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug]: drop TorV2 support

2 participants