Skip to content
This repository has been archived by the owner on May 13, 2022. It is now read-only.

Commit

Permalink
Fixed rlp encoding extra leading zeros on uint64
Browse files Browse the repository at this point in the history
When a uint64 fits perfectly in a multiple 8 bits, a leading zero was being added to the encoded value, for example 233 was encoded (prefix elided) as `00 e9` while it should have been `e9`

Simply changed the way the amount of byte required is computed so the right amount of leading zeros is correctly removed after encoding.

For uint64 value <= 255, this will even save an allocation since we will more often enter the `encodeUint8` case which is faster (theorically).

Signed-off-by: Matthieu Vachon <[email protected]>
  • Loading branch information
Matthieu Vachon authored and maoueh committed May 19, 2021
1 parent 97c7eda commit 9b4113e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
7 changes: 4 additions & 3 deletions encoding/rlp/rlp.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,14 @@ func encodeUint8(input uint8) ([]byte, error) {
}

func encodeUint64(i uint64) ([]byte, error) {
size := bits.Len64(i)/8 + 1
if size == 1 {
// Byte-wise ceiling
byteCount := (bits.Len64(i) + 7) / 8
if byteCount == 1 {
return encodeUint8(uint8(i))
}
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(i))
return encodeString(b[8-size:])
return encodeString(b[8-byteCount:])
}

func encodeBigInt(b *big.Int) ([]byte, error) {
Expand Down
12 changes: 6 additions & 6 deletions encoding/rlp/rlp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,14 @@ func TestEncoding(t *testing.T) {
t.Run("Integers", func(t *testing.T) {
var tests = []testCase{
{
[]uint64{23, 30400},
[]byte{0xc4, 0x17, 0x82, 0x76, 0xc0},
[][]byte{{23}, {0x76, 0xc0}},
[]uint64{23, 233, 30400},
[]byte{0xc6, 0x17, 0x81, 0xe9, 0x82, 0x76, 0xc0},
[][]byte{{23}, {233}, {0x76, 0xc0}},
},
{
[]*big.Int{big.NewInt(23), big.NewInt(30400)},
[]byte{0xc4, 0x17, 0x82, 0x76, 0xc0},
[][]byte{{23}, {0x76, 0xc0}},
[]*big.Int{big.NewInt(23), big.NewInt(233), big.NewInt(30400)},
[]byte{0xc6, 0x17, 0x81, 0xe9, 0x82, 0x76, 0xc0},
[][]byte{{23}, {233}, {0x76, 0xc0}},
},
}

Expand Down

0 comments on commit 9b4113e

Please sign in to comment.