Skip to content
This repository has been archived by the owner on Sep 6, 2022. It is now read-only.

Commit

Permalink
reject JSON serialized AddrInfo if the ID is missing
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Feb 12, 2021
1 parent 9f33b0e commit 43d94f1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 22 deletions.
17 changes: 10 additions & 7 deletions peer/addrinfo_serde.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package peer

import (
"encoding/json"
"errors"

ma "github.com/multiformats/go-multiaddr"
)
Expand All @@ -22,14 +23,16 @@ func (pi *AddrInfo) UnmarshalJSON(b []byte) error {
if err := json.Unmarshal(b, &data); err != nil {
return err
}
if id, ok := data["ID"]; ok {
if idString, ok := id.(string); ok {
pid, err := IDB58Decode(idString)
if err != nil {
return err
}
pi.ID = pid
id, ok := data["ID"]
if !ok {
return errors.New("no peer ID")
}
if idString, ok := id.(string); ok {
pid, err := IDB58Decode(idString)
if err != nil {
return err
}
pi.ID = pid
}
if addrsEntry, ok := data["Addrs"]; ok {
if addrs, ok := addrsEntry.([]interface{}); ok {
Expand Down
39 changes: 24 additions & 15 deletions peer/addrinfo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,19 +135,28 @@ func TestAddrInfosFromP2pAddrs(t *testing.T) {
}

func TestAddrInfoJSON(t *testing.T) {
ai := AddrInfo{ID: testID, Addrs: []ma.Multiaddr{maddrFull}}
out, err := ai.MarshalJSON()
if err != nil {
t.Fatal(err)
}
var addrInfo AddrInfo
if err := addrInfo.UnmarshalJSON(out); err != nil {
t.Fatal(err)
}
if addrInfo.ID != testID {
t.Fatalf("expected ID to equal %s, got %s", testID.Pretty(), addrInfo.ID.Pretty())
}
if len(addrInfo.Addrs) != 1 || !addrInfo.Addrs[0].Equal(maddrFull) {
t.Fatalf("expected addrs to match %v, got %v", maddrFull, addrInfo.Addrs)
}
t.Run("valid AddrInfo", func(t *testing.T) {
ai := AddrInfo{ID: testID, Addrs: []ma.Multiaddr{maddrFull}}
out, err := ai.MarshalJSON()
if err != nil {
t.Fatal(err)
}
var addrInfo AddrInfo
if err := addrInfo.UnmarshalJSON(out); err != nil {
t.Fatal(err)
}
if addrInfo.ID != testID {
t.Fatalf("expected ID to equal %s, got %s", testID.Pretty(), addrInfo.ID.Pretty())
}
if len(addrInfo.Addrs) != 1 || !addrInfo.Addrs[0].Equal(maddrFull) {
t.Fatalf("expected addrs to match %v, got %v", maddrFull, addrInfo.Addrs)
}
})
t.Run("missing ID", func(t *testing.T) {
s := []byte(`{"Addrs":["/ip4/127.0.0.1/tcp/1234/p2p/QmS3zcG7LhYZYSJMhyRZvTddvbNUqtt8BJpaSs6mi1K5Va"]}`)
var addrInfo AddrInfo
if err := addrInfo.UnmarshalJSON(s); err == nil || err.Error() != "no peer ID" {
t.Fatalf("expected no peer ID error, got %v", err)
}
})
}

0 comments on commit 43d94f1

Please sign in to comment.