Skip to content

Commit

Permalink
Merge pull request #100 from whyrusleeping/steb/reject-negative-big-int
Browse files Browse the repository at this point in the history
fix: reject negative big integers
  • Loading branch information
whyrusleeping authored Jul 25, 2024
2 parents 7054243 + 2af0c21 commit cdbc4c7
Show file tree
Hide file tree
Showing 5 changed files with 139 additions and 0 deletions.
3 changes: 3 additions & 0 deletions gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,9 @@ func (g Gen) emitCborMarshalStructField(w io.Writer, f Field) error {
case bigIntType:
return g.doTemplate(w, f, `
{
if {{ .Name }} != nil && {{ .Name }}.Sign() < 0 {
return xerrors.Errorf("Value in field {{ .Name | js }} was a negative big-integer (not supported)")
}
if err := cw.CborWriteHeader(cbg.MajTag, 2); err != nil {
return err
}
Expand Down
1 change: 1 addition & 0 deletions testgen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func main() {
types.IntArrayNewType{},
types.IntArrayAliasNewType{},
types.MapTransparentType{},
types.BigIntContainer{},
); err != nil {
panic(err)
}
Expand Down
97 changes: 97 additions & 0 deletions testing/cbor_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 33 additions & 0 deletions testing/roundtrip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"math/big"
"math/rand"
"reflect"
"testing"
Expand Down Expand Up @@ -58,6 +59,38 @@ func TestLongStrings(t *testing.T) {
testTypeRoundtrips(t, reflect.TypeOf(LongString{}))
}

func TestBigInt(t *testing.T) {
for _, v := range []BigIntContainer{
{Int: big.NewInt(100)},
{Int: big.NewInt(0)},
{Int: nil},
} {

var buf bytes.Buffer
if err := v.MarshalCBOR(&buf); err != nil {
t.Fatal(err)
}

var o BigIntContainer
if err := o.UnmarshalCBOR(&buf); err != nil {
t.Fatal(err)
}
if v.Int == nil {
if o.Int.Sign() != 0 {
t.Fatal("expected nil to serialize to 0")
}
} else if v.Int.Cmp(o.Int) != 0 {
t.Fatal("did not round-trip")
}
}
var buf bytes.Buffer
v := BigIntContainer{Int: big.NewInt(-1)}
err := v.MarshalCBOR(&buf)
if err == nil {
t.Fatal("marshalling a negative int should have failed")
}
}

type RoundTripOptions struct {
Golden []byte
}
Expand Down
5 changes: 5 additions & 0 deletions testing/types.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package testing

import (
"math/big"
"math/rand"
"reflect"

Expand Down Expand Up @@ -194,3 +195,7 @@ func (ls LongString) Generate(rand *rand.Rand, size int) reflect.Value {
ols.Val = string(s)
return reflect.ValueOf(ols).Elem()
}

type BigIntContainer struct {
Int *big.Int
}

0 comments on commit cdbc4c7

Please sign in to comment.