From 7be028ff7cedda21100ecca50fce84b872e441af Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Thu, 16 Jan 2025 17:53:44 -0300 Subject: [PATCH] sdk: test and fix encode/decode relay lists. --- sdk/event_relays.go | 5 ++- sdk/event_relays_test.go | 81 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 sdk/event_relays_test.go diff --git a/sdk/event_relays.go b/sdk/event_relays.go index 5423c1e..c014bf5 100644 --- a/sdk/event_relays.go +++ b/sdk/event_relays.go @@ -21,6 +21,9 @@ func makeEventRelayKey(eventID []byte) []byte { func encodeRelayList(relays []string) []byte { totalSize := 0 for _, relay := range relays { + if len(relay) > 256 { + continue + } totalSize += 1 + len(relay) // 1 byte for length prefix } @@ -41,7 +44,7 @@ func encodeRelayList(relays []string) []byte { } func decodeRelayList(data []byte) []string { - relays := make([]string, 0) + relays := make([]string, 0, 6) offset := 0 for offset < len(data) { diff --git a/sdk/event_relays_test.go b/sdk/event_relays_test.go new file mode 100644 index 0000000..1cdfcd9 --- /dev/null +++ b/sdk/event_relays_test.go @@ -0,0 +1,81 @@ +package sdk + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestEncodeDecodeRelayList(t *testing.T) { + tests := []struct { + name string + relays []string + }{ + { + name: "empty list", + relays: []string{}, + }, + { + name: "single relay", + relays: []string{"wss://relay.example.com"}, + }, + { + name: "multiple relays", + relays: []string{ + "wss://relay1.example.com", + "wss://relay23.example.com", + "wss://relay456.example.com", + }, + }, + { + name: "relays with varying lengths", + relays: []string{ + "wss://a.com", + "wss://very-long-relay-url.example.com", + "wss://b.com", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // test encoding + encoded := encodeRelayList(tt.relays) + require.NotNil(t, encoded) + + // test decoding + decoded := decodeRelayList(encoded) + require.Equal(t, tt.relays, decoded) + }) + } + + t.Run("malformed data", func(t *testing.T) { + // test with truncated data + decoded := decodeRelayList([]byte{5, 'h', 'e'}) // length prefix of 5 but only 2 bytes of data + require.Nil(t, decoded) + + // test with invalid length prefix + decoded = decodeRelayList([]byte{255}) // length prefix but no data + require.Nil(t, decoded) + }) + + t.Run("skip too long relay URLs", func(t *testing.T) { + // create a long URL by repeating 'a' 257 times + longURL := "wss://" + strings.Repeat("a", 257) + ".com" + longRelays := []string{ + "wss://normal.example.com", + longURL, + "wss://also-normal.example.com", + } + + encoded := encodeRelayList(longRelays) + decoded := decodeRelayList(encoded) + + // should only contain the normal URLs + require.Equal(t, []string{ + "wss://normal.example.com", + "wss://also-normal.example.com", + }, decoded) + }) +}