Skip to content

Commit b2af716

Browse files
authored
math: derive marshalled byte length from copy, not blind assumptions (cosmos#12010)
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()
1 parent 4459c2a commit b2af716

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

Diff for: math/int.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -383,17 +383,17 @@ func (i *Int) MarshalTo(data []byte) (n int, err error) {
383383
i.i = new(big.Int)
384384
}
385385
if i.i.BitLen() == 0 { // The value 0
386-
copy(data, []byte{0x30})
387-
return 1, nil
386+
n = copy(data, []byte{0x30})
387+
return n, nil
388388
}
389389

390390
bz, err := i.Marshal()
391391
if err != nil {
392392
return 0, err
393393
}
394394

395-
copy(data, bz)
396-
return len(bz), nil
395+
n = copy(data, bz)
396+
return n, nil
397397
}
398398

399399
// Unmarshal implements the gogo proto custom type interface.

Diff for: math/uint.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -162,17 +162,17 @@ func (u *Uint) MarshalTo(data []byte) (n int, err error) {
162162
u.i = new(big.Int)
163163
}
164164
if u.i.BitLen() == 0 { // The value 0
165-
copy(data, []byte{0x30})
166-
return 1, nil
165+
n = copy(data, []byte{0x30})
166+
return n, nil
167167
}
168168

169169
bz, err := u.Marshal()
170170
if err != nil {
171171
return 0, err
172172
}
173173

174-
copy(data, bz)
175-
return len(bz), nil
174+
n = copy(data, bz)
175+
return n, nil
176176
}
177177

178178
// Unmarshal implements the gogo proto custom type interface.

0 commit comments

Comments
 (0)