Skip to content

Commit cad64fb

Browse files
committed
rlp: stricter rules for structs and pointers
The rules have changed as follows: * When decoding into pointers, empty values no longer produce a nil pointer. This can be overriden for struct fields using the struct tag "nil". * When decoding into structs, the input list must contain an element for each field.
1 parent 1e2c93a commit cad64fb

4 files changed

Lines changed: 148 additions & 52 deletions

File tree

‎rlp/decode.go‎

Lines changed: 54 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -36,25 +36,34 @@ type Decoder interface {
3636
// If the type implements the Decoder interface, decode calls
3737
// DecodeRLP.
3838
//
39-
// To decode into a pointer, Decode will set the pointer to nil if the
40-
// input has size zero. If the input has nonzero size, Decode will
41-
// parse the input data into a value of the type being pointed to.
42-
// If the pointer is non-nil, the existing value will reused.
39+
// To decode into a pointer, Decode will decode into the value pointed
40+
// to. If the pointer is nil, a new value of the pointer's element
41+
// type is allocated. If the pointer is non-nil, the existing value
42+
// will reused.
4343
//
4444
// To decode into a struct, Decode expects the input to be an RLP
4545
// list. The decoded elements of the list are assigned to each public
46-
// field in the order given by the struct's definition. If the input
47-
// list has too few elements, no error is returned and the remaining
48-
// fields will have the zero value.
49-
// Recursive struct types are supported.
46+
// field in the order given by the struct's definition. The input list
47+
// must contain an element for each decoded field. Decode returns an
48+
// error if there are too few or too many elements.
49+
//
50+
// The decoding of struct fields honours one particular struct tag,
51+
// "nil". This tag applies to pointer-typed fields and changes the
52+
// decoding rules for the field such that input values of size zero
53+
// decode as a nil pointer. This tag can be useful when decoding recursive
54+
// types.
55+
//
56+
// type StructWithEmptyOK struct {
57+
// Foo *[20]byte `rlp:"nil"`
58+
// }
5059
//
5160
// To decode into a slice, the input must be a list and the resulting
5261
// slice will contain the input elements in order.
5362
// As a special case, if the slice has a byte-size element type, the input
5463
// can also be an RLP string.
5564
//
5665
// To decode into a Go string, the input must be an RLP string. The
57-
// bytes are taken as-is and will not necessarily be valid UTF-8.
66+
// input bytes are taken as-is and will not necessarily be valid UTF-8.
5867
//
5968
// To decode into an unsigned integer type, the input must also be an RLP
6069
// string. The bytes are interpreted as a big endian representation of
@@ -65,8 +74,8 @@ type Decoder interface {
6574
// To decode into an interface value, Decode stores one of these
6675
// in the value:
6776
//
68-
// []interface{}, for RLP lists
69-
// []byte, for RLP strings
77+
// []interface{}, for RLP lists
78+
// []byte, for RLP strings
7079
//
7180
// Non-empty interface types are not supported, nor are booleans,
7281
// signed integers, floating point numbers, maps, channels and
@@ -136,7 +145,7 @@ var (
136145
bigInt = reflect.TypeOf(big.Int{})
137146
)
138147

139-
func makeDecoder(typ reflect.Type) (dec decoder, err error) {
148+
func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) {
140149
kind := typ.Kind()
141150
switch {
142151
case typ.Implements(decoderInterface):
@@ -156,6 +165,9 @@ func makeDecoder(typ reflect.Type) (dec decoder, err error) {
156165
case kind == reflect.Struct:
157166
return makeStructDecoder(typ)
158167
case kind == reflect.Ptr:
168+
if tags.nilOK {
169+
return makeOptionalPtrDecoder(typ)
170+
}
159171
return makePtrDecoder(typ)
160172
case kind == reflect.Interface:
161173
return decodeInterface, nil
@@ -214,7 +226,7 @@ func makeListDecoder(typ reflect.Type) (decoder, error) {
214226
return decodeByteSlice, nil
215227
}
216228
}
217-
etypeinfo, err := cachedTypeInfo1(etype)
229+
etypeinfo, err := cachedTypeInfo1(etype, tags{})
218230
if err != nil {
219231
return nil, err
220232
}
@@ -352,11 +364,6 @@ func zero(val reflect.Value, start int) {
352364
}
353365
}
354366

355-
type field struct {
356-
index int
357-
info *typeinfo
358-
}
359-
360367
func makeStructDecoder(typ reflect.Type) (decoder, error) {
361368
fields, err := structFields(typ)
362369
if err != nil {
@@ -369,8 +376,7 @@ func makeStructDecoder(typ reflect.Type) (decoder, error) {
369376
for _, f := range fields {
370377
err = f.info.decoder(s, val.Field(f.index))
371378
if err == EOL {
372-
// too few elements. leave the rest at their zero value.
373-
break
379+
return &decodeError{msg: "too few elements", typ: typ}
374380
} else if err != nil {
375381
return addErrorContext(err, "."+typ.Field(f.index).Name)
376382
}
@@ -380,9 +386,35 @@ func makeStructDecoder(typ reflect.Type) (decoder, error) {
380386
return dec, nil
381387
}
382388

389+
// makePtrDecoder creates a decoder that decodes into
390+
// the pointer's element type.
383391
func makePtrDecoder(typ reflect.Type) (decoder, error) {
384392
etype := typ.Elem()
385-
etypeinfo, err := cachedTypeInfo1(etype)
393+
etypeinfo, err := cachedTypeInfo1(etype, tags{})
394+
if err != nil {
395+
return nil, err
396+
}
397+
dec := func(s *Stream, val reflect.Value) (err error) {
398+
newval := val
399+
if val.IsNil() {
400+
newval = reflect.New(etype)
401+
}
402+
if err = etypeinfo.decoder(s, newval.Elem()); err == nil {
403+
val.Set(newval)
404+
}
405+
return err
406+
}
407+
return dec, nil
408+
}
409+
410+
// makeOptionalPtrDecoder creates a decoder that decodes empty values
411+
// as nil. Non-empty values are decoded into a value of the element type,
412+
// just like makePtrDecoder does.
413+
//
414+
// This decoder is used for pointer-typed struct fields with struct tag "nil".
415+
func makeOptionalPtrDecoder(typ reflect.Type) (decoder, error) {
416+
etype := typ.Elem()
417+
etypeinfo, err := cachedTypeInfo1(etype, tags{})
386418
if err != nil {
387419
return nil, err
388420
}
@@ -706,7 +738,7 @@ func (s *Stream) Decode(val interface{}) error {
706738
if rval.IsNil() {
707739
return errDecodeIntoNil
708740
}
709-
info, err := cachedTypeInfo(rtyp.Elem())
741+
info, err := cachedTypeInfo(rtyp.Elem(), tags{})
710742
if err != nil {
711743
return err
712744
}

‎rlp/decode_test.go‎

Lines changed: 53 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ type simplestruct struct {
280280

281281
type recstruct struct {
282282
I uint
283-
Child *recstruct
283+
Child *recstruct `rlp:"nil"`
284284
}
285285

286286
var (
@@ -390,15 +390,33 @@ var decodeTests = []decodeTest{
390390
{input: "8105", ptr: new(big.Int), error: "rlp: non-canonical size information for *big.Int"},
391391

392392
// structs
393-
{input: "C0", ptr: new(simplestruct), value: simplestruct{0, ""}},
394-
{input: "C105", ptr: new(simplestruct), value: simplestruct{5, ""}},
395-
{input: "C50583343434", ptr: new(simplestruct), value: simplestruct{5, "444"}},
396393
{
397-
input: "C501C302C103",
394+
input: "C50583343434",
395+
ptr: new(simplestruct),
396+
value: simplestruct{5, "444"},
397+
},
398+
{
399+
input: "C601C402C203C0",
398400
ptr: new(recstruct),
399401
value: recstruct{1, &recstruct{2, &recstruct{3, nil}}},
400402
},
401403

404+
// struct errors
405+
{
406+
input: "C0",
407+
ptr: new(simplestruct),
408+
error: "rlp: too few elements for rlp.simplestruct",
409+
},
410+
{
411+
input: "C105",
412+
ptr: new(simplestruct),
413+
error: "rlp: too few elements for rlp.simplestruct",
414+
},
415+
{
416+
input: "C7C50583343434C0",
417+
ptr: new([]*simplestruct),
418+
error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]",
419+
},
402420
{
403421
input: "83222222",
404422
ptr: new(simplestruct),
@@ -417,19 +435,15 @@ var decodeTests = []decodeTest{
417435

418436
// pointers
419437
{input: "00", ptr: new(*[]byte), value: &[]byte{0}},
420-
{input: "80", ptr: new(*uint), value: (*uint)(nil)},
421-
{input: "C0", ptr: new(*uint), value: (*uint)(nil)},
438+
{input: "80", ptr: new(*uint), value: uintp(0)},
439+
{input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"},
422440
{input: "07", ptr: new(*uint), value: uintp(7)},
423441
{input: "8158", ptr: new(*uint), value: uintp(0x58)},
424442
{input: "C109", ptr: new(*[]uint), value: &[]uint{9}},
425443
{input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}},
426444

427445
// check that input position is advanced also for empty values.
428-
{input: "C3808005", ptr: new([]*uint), value: []*uint{nil, nil, uintp(5)}},
429-
430-
// pointer should be reset to nil
431-
{input: "05", ptr: sharedPtr, value: uintp(5)},
432-
{input: "80", ptr: sharedPtr, value: (*uint)(nil)},
446+
{input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}},
433447

434448
// interface{}
435449
{input: "00", ptr: new(interface{}), value: []byte{0}},
@@ -599,6 +613,33 @@ func ExampleDecode() {
599613
// Decoded value: rlp.example{A:0xa, B:0x14, private:0x0, String:"foobar"}
600614
}
601615

616+
func ExampleDecode_structTagNil() {
617+
// In this example, we'll use the "nil" struct tag to change
618+
// how a pointer-typed field is decoded. The input contains an RLP
619+
// list of one element, an empty string.
620+
input := []byte{0xC1, 0x80}
621+
622+
// This type uses the normal rules.
623+
// The empty input string is decoded as a pointer to an empty Go string.
624+
var normalRules struct {
625+
String *string
626+
}
627+
Decode(bytes.NewReader(input), &normalRules)
628+
fmt.Printf("normal: String = %q\n", *normalRules.String)
629+
630+
// This type uses the struct tag.
631+
// The empty input string is decoded as a nil pointer.
632+
var withEmptyOK struct {
633+
String *string `rlp:"nil"`
634+
}
635+
Decode(bytes.NewReader(input), &withEmptyOK)
636+
fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String)
637+
638+
// Output:
639+
// normal: String = ""
640+
// with nil tag: String = <nil>
641+
}
642+
602643
func ExampleStream() {
603644
input, _ := hex.DecodeString("C90A1486666F6F626172")
604645
s := NewStream(bytes.NewReader(input), 0)

‎rlp/encode.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ func (w *encbuf) Write(b []byte) (int, error) {
194194

195195
func (w *encbuf) encode(val interface{}) error {
196196
rval := reflect.ValueOf(val)
197-
ti, err := cachedTypeInfo(rval.Type())
197+
ti, err := cachedTypeInfo(rval.Type(), tags{})
198198
if err != nil {
199199
return err
200200
}
@@ -485,15 +485,15 @@ func writeInterface(val reflect.Value, w *encbuf) error {
485485
return nil
486486
}
487487
eval := val.Elem()
488-
ti, err := cachedTypeInfo(eval.Type())
488+
ti, err := cachedTypeInfo(eval.Type(), tags{})
489489
if err != nil {
490490
return err
491491
}
492492
return ti.writer(eval, w)
493493
}
494494

495495
func makeSliceWriter(typ reflect.Type) (writer, error) {
496-
etypeinfo, err := cachedTypeInfo1(typ.Elem())
496+
etypeinfo, err := cachedTypeInfo1(typ.Elem(), tags{})
497497
if err != nil {
498498
return nil, err
499499
}
@@ -530,7 +530,7 @@ func makeStructWriter(typ reflect.Type) (writer, error) {
530530
}
531531

532532
func makePtrWriter(typ reflect.Type) (writer, error) {
533-
etypeinfo, err := cachedTypeInfo1(typ.Elem())
533+
etypeinfo, err := cachedTypeInfo1(typ.Elem(), tags{})
534534
if err != nil {
535535
return nil, err
536536
}

‎rlp/typecache.go‎

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,55 +7,74 @@ import (
77

88
var (
99
typeCacheMutex sync.RWMutex
10-
typeCache = make(map[reflect.Type]*typeinfo)
10+
typeCache = make(map[typekey]*typeinfo)
1111
)
1212

1313
type typeinfo struct {
1414
decoder
1515
writer
1616
}
1717

18+
// represents struct tags
19+
type tags struct {
20+
nilOK bool
21+
}
22+
23+
type typekey struct {
24+
reflect.Type
25+
// the key must include the struct tags because they
26+
// might generate a different decoder.
27+
tags
28+
}
29+
1830
type decoder func(*Stream, reflect.Value) error
1931

2032
type writer func(reflect.Value, *encbuf) error
2133

22-
func cachedTypeInfo(typ reflect.Type) (*typeinfo, error) {
34+
func cachedTypeInfo(typ reflect.Type, tags tags) (*typeinfo, error) {
2335
typeCacheMutex.RLock()
24-
info := typeCache[typ]
36+
info := typeCache[typekey{typ, tags}]
2537
typeCacheMutex.RUnlock()
2638
if info != nil {
2739
return info, nil
2840
}
2941
// not in the cache, need to generate info for this type.
3042
typeCacheMutex.Lock()
3143
defer typeCacheMutex.Unlock()
32-
return cachedTypeInfo1(typ)
44+
return cachedTypeInfo1(typ, tags)
3345
}
3446

35-
func cachedTypeInfo1(typ reflect.Type) (*typeinfo, error) {
36-
info := typeCache[typ]
47+
func cachedTypeInfo1(typ reflect.Type, tags tags) (*typeinfo, error) {
48+
key := typekey{typ, tags}
49+
info := typeCache[key]
3750
if info != nil {
3851
// another goroutine got the write lock first
3952
return info, nil
4053
}
4154
// put a dummmy value into the cache before generating.
4255
// if the generator tries to lookup itself, it will get
4356
// the dummy value and won't call itself recursively.
44-
typeCache[typ] = new(typeinfo)
45-
info, err := genTypeInfo(typ)
57+
typeCache[key] = new(typeinfo)
58+
info, err := genTypeInfo(typ, tags)
4659
if err != nil {
4760
// remove the dummy value if the generator fails
48-
delete(typeCache, typ)
61+
delete(typeCache, key)
4962
return nil, err
5063
}
51-
*typeCache[typ] = *info
52-
return typeCache[typ], err
64+
*typeCache[key] = *info
65+
return typeCache[key], err
66+
}
67+
68+
type field struct {
69+
index int
70+
info *typeinfo
5371
}
5472

5573
func structFields(typ reflect.Type) (fields []field, err error) {
5674
for i := 0; i < typ.NumField(); i++ {
5775
if f := typ.Field(i); f.PkgPath == "" { // exported
58-
info, err := cachedTypeInfo1(f.Type)
76+
tags := parseStructTag(f.Tag.Get("rlp"))
77+
info, err := cachedTypeInfo1(f.Type, tags)
5978
if err != nil {
6079
return nil, err
6180
}
@@ -65,9 +84,13 @@ func structFields(typ reflect.Type) (fields []field, err error) {
6584
return fields, nil
6685
}
6786

68-
func genTypeInfo(typ reflect.Type) (info *typeinfo, err error) {
87+
func parseStructTag(tag string) tags {
88+
return tags{nilOK: tag == "nil"}
89+
}
90+
91+
func genTypeInfo(typ reflect.Type, tags tags) (info *typeinfo, err error) {
6992
info = new(typeinfo)
70-
if info.decoder, err = makeDecoder(typ); err != nil {
93+
if info.decoder, err = makeDecoder(typ, tags); err != nil {
7194
return nil, err
7295
}
7396
if info.writer, err = makeWriter(typ); err != nil {

0 commit comments

Comments
 (0)