Skip to content

Commit 965c9ba

Browse files
committed
rlp: fix encoding of one element strings and byte slices
The encoder was missing a special case for one element strings whose element is below 0x7f. Such strings must be encoded as a single byte without a string header.
1 parent 064279c commit 965c9ba

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

rlp/encode.go

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -203,8 +203,13 @@ func (w *encbuf) encodeStringHeader(size int) {
203203
}
204204

205205
func (w *encbuf) encodeString(b []byte) {
206-
w.encodeStringHeader(len(b))
207-
w.str = append(w.str, b...)
206+
if len(b) == 1 && b[0] <= 0x7F {
207+
// fits single byte, no string header
208+
w.str = append(w.str, b[0])
209+
} else {
210+
w.encodeStringHeader(len(b))
211+
w.str = append(w.str, b...)
212+
}
208213
}
209214

210215
func (w *encbuf) list() *listhead {
@@ -404,9 +409,6 @@ func writeBigInt(i *big.Int, w *encbuf) error {
404409
return fmt.Errorf("rlp: cannot encode negative *big.Int")
405410
} else if cmp == 0 {
406411
w.str = append(w.str, 0x80)
407-
} else if bits := i.BitLen(); bits < 8 {
408-
// fits single byte
409-
w.str = append(w.str, byte(i.Uint64()))
410412
} else {
411413
w.encodeString(i.Bytes())
412414
}
@@ -434,8 +436,13 @@ func writeByteArray(val reflect.Value, w *encbuf) error {
434436

435437
func writeString(val reflect.Value, w *encbuf) error {
436438
s := val.String()
437-
w.encodeStringHeader(len(s))
438-
w.str = append(w.str, s...)
439+
if len(s) == 1 && s[0] <= 0x7f {
440+
// fits single byte, no string header
441+
w.str = append(w.str, s[0])
442+
} else {
443+
w.encodeStringHeader(len(s))
444+
w.str = append(w.str, s...)
445+
}
439446
return nil
440447
}
441448

rlp/encode_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,18 @@ var encTests = []encTest{
103103

104104
// byte slices, strings
105105
{val: []byte{}, output: "80"},
106+
{val: []byte{0x7E}, output: "7E"},
107+
{val: []byte{0x7F}, output: "7F"},
108+
{val: []byte{0x80}, output: "8180"},
106109
{val: []byte{1, 2, 3}, output: "83010203"},
107110

108111
{val: []namedByteType{1, 2, 3}, output: "83010203"},
109112
{val: [...]namedByteType{1, 2, 3}, output: "83010203"},
110113

111114
{val: "", output: "80"},
115+
{val: "\x7E", output: "7E"},
116+
{val: "\x7F", output: "7F"},
117+
{val: "\x80", output: "8180"},
112118
{val: "dog", output: "83646F67"},
113119
{
114120
val: "Lorem ipsum dolor sit amet, consectetur adipisicing eli",

0 commit comments

Comments
 (0)