Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(orm)!: timestamp encoding doesn't handle nil values properly #12273

Merged
merged 15 commits into from
Feb 9, 2023
Merged
Prev Previous commit
Next Next commit
fix tests
  • Loading branch information
aaronc committed Jun 15, 2022
commit 40167f0833d61aabe79d3c2a689b81d5966f9dab
35 changes: 35 additions & 0 deletions orm/encoding/ormfield/codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import (
"bytes"
"fmt"
"testing"
"time"

"google.golang.org/protobuf/types/known/timestamppb"

"github.com/cosmos/cosmos-sdk/orm/encoding/ormfield"

Expand Down Expand Up @@ -169,3 +172,35 @@ func TestCompactUInt64(t *testing.T) {
assert.Equal(t, y, y2)
})
}

func TestTimestamp(t *testing.T) {
cdc := ormfield.TimestampCodec{}

// nil value
buf := &bytes.Buffer{}
assert.NilError(t, cdc.Encode(protoreflect.Value{}, buf))
assert.Equal(t, 1, len(buf.Bytes()))
val, err := cdc.Decode(buf)
assert.NilError(t, err)
assert.Assert(t, !val.IsValid())

// no nanos
ts := timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 0, time.UTC))
val = protoreflect.ValueOfMessage(ts.ProtoReflect())
buf = &bytes.Buffer{}
assert.NilError(t, cdc.Encode(val, buf))
assert.Equal(t, 6, len(buf.Bytes()))
val2, err := cdc.Decode(buf)
assert.NilError(t, err)
assert.Equal(t, 0, cdc.Compare(val, val2))

// nanos
ts = timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 235809753, time.UTC))
val = protoreflect.ValueOfMessage(ts.ProtoReflect())
buf = &bytes.Buffer{}
assert.NilError(t, cdc.Encode(val, buf))
assert.Equal(t, 9, len(buf.Bytes()))
val2, err = cdc.Decode(buf)
assert.NilError(t, err)
assert.Equal(t, 0, cdc.Compare(val, val2))
}
4 changes: 2 additions & 2 deletions orm/encoding/ormfield/timestamp.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (t TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error {
nanosBz[i] = byte(nanosInt)
nanosInt >>= 8
}
nanosBz[0] = nanosBz[0] & 0xC0
nanosBz[0] = nanosBz[0] | 0xC0
_, err = w.Write(nanosBz[:])
return err
}
Expand Down Expand Up @@ -113,7 +113,7 @@ func (t TimestampCodec) Decode(r Reader) (protoreflect.Value, error) {
return protoreflect.Value{}, io.EOF
}

var nanos = int32(b0)
var nanos = int32(b0) & 0x3F // clear first two bits
for i := 0; i < 3; i++ {
nanos <<= 8
nanos |= int32(nanosBz[i])
Expand Down