diff --git a/rlp/encodel.go b/rlp/encodel.go index 0cb5c35ce..cbbe0637c 100644 --- a/rlp/encodel.go +++ b/rlp/encodel.go @@ -62,19 +62,76 @@ func U64Len(i uint64) int { } func EncodeU64(i uint64, to []byte) int { - if i > 128 { - beLen := (bits.Len64(i) + 7) / 8 - to[0] = 128 + byte(beLen) - binary.BigEndian.PutUint64(to[1:], i) - copy(to[1:], to[1+8-beLen:1+8]) - return 1 + beLen - } if i == 0 { to[0] = 128 return 1 } - to[0] = byte(i) - return 1 + if i < 128 { + to[0] = byte(i) // fits single byte + return 1 + } + + b := to[1:] + l := 0 + + // writes i to b in big endian byte order, using the least number of bytes needed to represent i. + switch { + case i < (1 << 8): + b[0] = byte(i) + l = 1 + case i < (1 << 16): + b[0] = byte(i >> 8) + b[1] = byte(i) + l = 2 + case i < (1 << 24): + b[0] = byte(i >> 16) + b[1] = byte(i >> 8) + b[2] = byte(i) + l = 3 + case i < (1 << 32): + b[0] = byte(i >> 24) + b[1] = byte(i >> 16) + b[2] = byte(i >> 8) + b[3] = byte(i) + l = 4 + case i < (1 << 40): + b[0] = byte(i >> 32) + b[1] = byte(i >> 24) + b[2] = byte(i >> 16) + b[3] = byte(i >> 8) + b[4] = byte(i) + l = 5 + case i < (1 << 48): + b[0] = byte(i >> 40) + b[1] = byte(i >> 32) + b[2] = byte(i >> 24) + b[3] = byte(i >> 16) + b[4] = byte(i >> 8) + b[5] = byte(i) + l = 6 + case i < (1 << 56): + b[0] = byte(i >> 48) + b[1] = byte(i >> 40) + b[2] = byte(i >> 32) + b[3] = byte(i >> 24) + b[4] = byte(i >> 16) + b[5] = byte(i >> 8) + b[6] = byte(i) + l = 7 + default: + b[0] = byte(i >> 56) + b[1] = byte(i >> 48) + b[2] = byte(i >> 40) + b[3] = byte(i >> 32) + b[4] = byte(i >> 24) + b[5] = byte(i >> 16) + b[6] = byte(i >> 8) + b[7] = byte(i) + l = 8 + } + + to[0] = 128 + byte(l) + return 1 + l } func StringLen(sLen int) int { diff --git a/txpool/pool_fuzz_test.go b/txpool/pool_fuzz_test.go index 456e8d2cd..2a3a6e829 100644 --- a/txpool/pool_fuzz_test.go +++ b/txpool/pool_fuzz_test.go @@ -255,7 +255,7 @@ func fakeRlpTx(slot *TxSlot, data []byte) []byte { buf[0] = byte(DynamicFeeTxType) p := 1 p += rlp.EncodeListPrefix(dataLen, buf[p:]) - p += rlp.EncodeU64(1, buf[p:]) + p += rlp.EncodeU64(1, buf[p:]) //chainID p += rlp.EncodeU64(slot.nonce, buf[p:]) p += rlp.EncodeU64(slot.tip, buf[p:]) p += rlp.EncodeU64(slot.feeCap, buf[p:])