From 2161f2dc98354322bb4f94abf8a8796479cfc74e Mon Sep 17 00:00:00 2001 From: Emmanuel T Odeke Date: Sat, 21 May 2022 19:22:55 +0300 Subject: [PATCH] math: derive marshalled byte length from copy, not blind assumptions The specification of "copy", the builtin function per https://pkg.go.dev/builtin#copy, says that it returns the minimum of len(src) and len(dst) when invoked as: copy(dst, src) of which the prior code blindly assumed that everytime that copy is invoked that the buffer provided had enough size to accomodate the contents of *.MarshalTo but this isn't true at all if len(data) is less than the values of .Marshal() --- math/int.go | 8 ++++---- math/uint.go | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/math/int.go b/math/int.go index 4c1e9ceb8491..159e2d7d224c 100644 --- a/math/int.go +++ b/math/int.go @@ -383,8 +383,8 @@ func (i *Int) MarshalTo(data []byte) (n int, err error) { i.i = new(big.Int) } if i.i.BitLen() == 0 { // The value 0 - copy(data, []byte{0x30}) - return 1, nil + n = copy(data, []byte{0x30}) + return n, nil } bz, err := i.Marshal() @@ -392,8 +392,8 @@ func (i *Int) MarshalTo(data []byte) (n int, err error) { return 0, err } - copy(data, bz) - return len(bz), nil + n = copy(data, bz) + return n, nil } // Unmarshal implements the gogo proto custom type interface. diff --git a/math/uint.go b/math/uint.go index 02efb9fc8dc2..8ce6105e9fb0 100644 --- a/math/uint.go +++ b/math/uint.go @@ -162,8 +162,8 @@ func (u *Uint) MarshalTo(data []byte) (n int, err error) { u.i = new(big.Int) } if u.i.BitLen() == 0 { // The value 0 - copy(data, []byte{0x30}) - return 1, nil + n = copy(data, []byte{0x30}) + return n, nil } bz, err := u.Marshal() @@ -171,8 +171,8 @@ func (u *Uint) MarshalTo(data []byte) (n int, err error) { return 0, err } - copy(data, bz) - return len(bz), nil + n = copy(data, bz) + return n, nil } // Unmarshal implements the gogo proto custom type interface.