Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make it safe to roundtrip Split... and Join #250

Merged
merged 3 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions multiaddr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -974,3 +974,43 @@ func TestHTTPPath(t *testing.T) {
require.Equal(t, "tmp/bar", string(component.RawValue()))
})
}

func FuzzSplitRoundtrip(f *testing.F) {
for _, v := range good {
f.Add(v, uint(0))
}

f.Fuzz(func(t *testing.T, addrStr string, splitOnProto uint) {
addr, err := NewMultiaddr(addrStr)
if err != nil {
t.Skip() // Skip inputs that are not valid multiaddrs
}

// Test SplitFirst
first, rest := SplitFirst(addr)
joined := Join(first, rest)
require.Equal(t, addr, joined, "SplitFirst and Join should round-trip")

// Test SplitLast
rest, last := SplitLast(addr)
joined = Join(rest, last)
require.Equal(t, addr, joined, "SplitLast and Join should round-trip")

p := addr.Protocols()
if err != nil || len(p) == 0 {
MarcoPolo marked this conversation as resolved.
Show resolved Hide resolved
t.Skip() // Skip if no components or error
}

selectedProto := p[int(splitOnProto)%len(p)]
MarcoPolo marked this conversation as resolved.
Show resolved Hide resolved

// Test SplitFunc
splitFunc := func(c Component) bool {
return c.Protocol().Code == selectedProto.Code
}
before, after := SplitFunc(addr, splitFunc)
joined = Join(before, after)
if !addr.Equal(joined) {
t.Errorf("Join(SplitFunc(addr, selectedComponent)) = %s; want %s", joined, addr)
}
})
}
6 changes: 6 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,18 @@ func Join(ms ...Multiaddr) Multiaddr {

length := 0
for _, m := range ms {
if m == nil {
continue
}
length += len(m.Bytes())
}

bidx := 0
b := make([]byte, length)
for _, mb := range ms {
if mb == nil {
continue
}
bidx += copy(b[bidx:], mb.Bytes())
}
return &multiaddr{bytes: b}
MarcoPolo marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
Loading