-
Notifications
You must be signed in to change notification settings - Fork 565
/
codec.go
85 lines (69 loc) · 2.63 KB
/
codec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package types
import (
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)
var (
// ModuleCdc references the global interchain accounts module codec. Note, the codec
// should ONLY be used in certain instances of tests and for JSON encoding.
//
// The actual codec used for serialization should be provided to interchain accounts and
// defined at the application level.
ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
)
// RegisterInterfaces registers the concrete InterchainAccount implementation against the associated
// x/auth AccountI and GenesisAccount interfaces
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
registry.RegisterImplementations((*authtypes.AccountI)(nil), &InterchainAccount{})
registry.RegisterImplementations((*authtypes.GenesisAccount)(nil), &InterchainAccount{})
}
// SerializeCosmosTx serializes a slice of sdk.Msg's using the CosmosTx type. The sdk.Msg's are
// packed into Any's and inserted into the Messages field of a CosmosTx. The proto marshaled CosmosTx
// bytes are returned. Only the ProtoCodec is supported for serializing messages.
func SerializeCosmosTx(cdc codec.BinaryCodec, msgs []sdk.Msg) (bz []byte, err error) {
// only ProtoCodec is supported
if _, ok := cdc.(*codec.ProtoCodec); !ok {
return nil, sdkerrors.Wrap(ErrInvalidCodec, "only ProtoCodec is supported for receiving messages on the host chain")
}
msgAnys := make([]*codectypes.Any, len(msgs))
for i, msg := range msgs {
msgAnys[i], err = codectypes.NewAnyWithValue(msg)
if err != nil {
return nil, err
}
}
cosmosTx := &CosmosTx{
Messages: msgAnys,
}
bz, err = cdc.Marshal(cosmosTx)
if err != nil {
return nil, err
}
return bz, nil
}
// DeserializeCosmosTx unmarshals and unpacks a slice of transaction bytes
// into a slice of sdk.Msg's. Only the ProtoCodec is supported for message
// deserialization.
func DeserializeCosmosTx(cdc codec.BinaryCodec, data []byte) ([]sdk.Msg, error) {
// only ProtoCodec is supported
if _, ok := cdc.(*codec.ProtoCodec); !ok {
return nil, sdkerrors.Wrap(ErrInvalidCodec, "only ProtoCodec is supported for receiving messages on the host chain")
}
var cosmosTx CosmosTx
if err := cdc.Unmarshal(data, &cosmosTx); err != nil {
return nil, err
}
msgs := make([]sdk.Msg, len(cosmosTx.Messages))
for i, any := range cosmosTx.Messages {
var msg sdk.Msg
err := cdc.UnpackAny(any, &msg)
if err != nil {
return nil, err
}
msgs[i] = msg
}
return msgs, nil
}