Skip to content

Commit

Permalink
chore: codec/types: use reflect.Type.Implements not mandatory casts
Browse files Browse the repository at this point in the history
Creates a type from proto.Message which can be type asserted against
with reflect.Type.Implements and is a quick check instead of firstly
constructing an entire reflect.Value zero value then casting its
value to an interface/any then manually type asserting against
proto.Message.

Fixes #17084
  • Loading branch information
odeke-em committed Jul 20, 2023
1 parent 3d15233 commit 061e361
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions codec/types/interface_registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"cosmossdk.io/x/tx/signing"
)

var protoMessageType = reflect.TypeOf((*proto.Message)(nil)).Elem()

// AnyUnpacker is an interface which allows safely unpacking types packed
// in Any's against a whitelist of registered types
type AnyUnpacker interface {
Expand Down Expand Up @@ -305,11 +307,13 @@ func (registry *interfaceRegistry) UnpackAny(any *Any, iface interface{}) error
return fmt.Errorf("no concrete type registered for type URL %s against interface %T", any.TypeUrl, iface)
}

msg, ok := reflect.New(typ.Elem()).Interface().(proto.Message)
if !ok {
return fmt.Errorf("can't proto unmarshal %T", msg)
// Firstly check if the type implements proto.Message to avoid
// unnecessary invocations to reflect.New
if !typ.Implements(protoMessageType) {
return fmt.Errorf("can't proto unmarshal %T", typ)
}

msg := reflect.New(typ.Elem()).Interface().(proto.Message)
err := proto.Unmarshal(any.Value, msg)
if err != nil {
return err
Expand Down

0 comments on commit 061e361

Please sign in to comment.