From e004bd3fc50e8924b82b040d35f67eccfbe02912 Mon Sep 17 00:00:00 2001 From: Marten Seemann Date: Sat, 21 Jan 2023 23:28:57 -0800 Subject: [PATCH] peerstore: make it possible to use an empty peer ID (#2006) --- p2p/host/peerstore/pstoremem/addr_book.go | 5 ++++- p2p/host/peerstore/test/addr_book_suite.go | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/p2p/host/peerstore/pstoremem/addr_book.go b/p2p/host/peerstore/pstoremem/addr_book.go index 28aa6d4d..fc4fd067 100644 --- a/p2p/host/peerstore/pstoremem/addr_book.go +++ b/p2p/host/peerstore/pstoremem/addr_book.go @@ -46,7 +46,10 @@ type addrSegment struct { } func (segments *addrSegments) get(p peer.ID) *addrSegment { - return segments[byte(p[len(p)-1])] + if len(p) == 0 { // it's not terribly useful to use an empty peer ID, but at least we should not panic + return segments[0] + } + return segments[uint8(p[len(p)-1])] } type clock interface { diff --git a/p2p/host/peerstore/test/addr_book_suite.go b/p2p/host/peerstore/test/addr_book_suite.go index dba2b3cd..62327e31 100644 --- a/p2p/host/peerstore/test/addr_book_suite.go +++ b/p2p/host/peerstore/test/addr_book_suite.go @@ -135,6 +135,12 @@ func testAddAddress(ab pstore.AddrBook, clk *mockClock.Mock) func(*testing.T) { ab.UpdateAddrs(id, 4*time.Second, 0) AssertAddressesEqual(t, nil, ab.Addrs(id)) }) + + t.Run("accessing an empty peer ID", func(t *testing.T) { + addrs := GenerateAddrs(5) + ab.AddAddrs("", addrs, time.Hour) + AssertAddressesEqual(t, addrs, ab.Addrs("")) + }) } }