Skip to content

Commit

Permalink
Add nil checks to types package
Browse files Browse the repository at this point in the history
  • Loading branch information
gdbelvin committed Mar 8, 2018
1 parent a50a47e commit e8cf97c
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
3 changes: 3 additions & 0 deletions types/logroot.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ type LogRoot struct {

// ParseLogRoot verifies that b has the LOG_ROOT_FORMAT_V1 tag and returns a *LogRootV1
func ParseLogRoot(b []byte) (*LogRootV1, error) {
if b == nil {
return nil, fmt.Errorf("nil log root")
}
// Verify version
version := binary.BigEndian.Uint16(b)
if version != uint16(trillian.LogRootFormat_LOG_ROOT_FORMAT_V1) {
Expand Down
4 changes: 4 additions & 0 deletions types/logroot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ func TestParseLogRoot(t *testing.T) {
logRoot: []byte("foo"),
wantErr: true,
},
{
logRoot: nil,
wantErr: true,
},
} {
_, err := ParseLogRoot(tc.logRoot)
if got, want := err != nil, tc.wantErr; got != want {
Expand Down
3 changes: 3 additions & 0 deletions types/maproot.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ type MapRoot struct {

// ParseMapRoot verifies that b has the MAP_ROOT_FORMAT_V1 tag and returns a *MapRootV1
func ParseMapRoot(b []byte) (*MapRootV1, error) {
if b == nil {
return nil, fmt.Errorf("nil map root")
}
// Verify version
version := binary.BigEndian.Uint16(b)
if version != uint16(trillian.MapRootFormat_MAP_ROOT_FORMAT_V1) {
Expand Down
37 changes: 37 additions & 0 deletions types/maproot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,40 @@ func TestMapRoot(t *testing.T) {
}
}
}

func MustSerializeMapRoot(root *MapRootV1) []byte {
b, err := SerializeMapRoot(root)
if err != nil {
panic(err)
}
return b
}

func TestParseMapRoot(t *testing.T) {
for _, tc := range []struct {
mapRoot []byte
want *MapRootV1
wantErr bool
}{
{
want: &MapRootV1{
RootHash: []byte("foo"),
Metadata: []byte{},
},
mapRoot: MustSerializeMapRoot(&MapRootV1{
RootHash: []byte("foo"),
Metadata: []byte{},
}),
},
{mapRoot: []byte("foo"), wantErr: true},
{mapRoot: nil, wantErr: true},
} {
r, err := ParseMapRoot(tc.mapRoot)
if got, want := err != nil, tc.wantErr; got != want {
t.Errorf("ParseMapRoot(): %v, wantErr: %v", err, want)
}
if got, want := r, tc.want; !reflect.DeepEqual(got, want) {
t.Errorf("ParseMapRoot(): %v, want: %v", got, want)
}
}
}

0 comments on commit e8cf97c

Please sign in to comment.