Skip to content

Commit 05743ac

Browse files
authored
Merge pull request #354 from blinklabs-io/fix/cbor-value-panic
fix: recover panics when decoding CBOR maps
2 parents 101e68d + 094a255 commit 05743ac

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

cbor/value.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414

1515
package cbor
1616

17+
import (
18+
"fmt"
19+
)
20+
1721
// Helpful wrapper for parsing arbitrary CBOR data which may contain types that
1822
// cannot be easily represented in Go (such as maps with bytestring keys)
1923
type Value struct {
@@ -22,12 +26,20 @@ type Value struct {
2226
cborData string
2327
}
2428

25-
func (v *Value) UnmarshalCBOR(data []byte) error {
29+
func (v *Value) UnmarshalCBOR(data []byte) (err error) {
2630
// Save the original CBOR
2731
v.cborData = string(data[:])
2832
cborType := data[0] & CBOR_TYPE_MASK
2933
switch cborType {
3034
case CBOR_TYPE_MAP:
35+
// There are certain types that cannot be used as map keys in Go but are valid in CBOR. Trying to
36+
// parse CBOR containing a map with keys of one of those types will cause a panic. We setup this
37+
// deferred function to recover from a possible panic and return an error
38+
defer func() {
39+
if r := recover(); r != nil {
40+
err = fmt.Errorf("decode failure, probably due to type unsupported by Go: %v", r)
41+
}
42+
}()
3143
tmpValue := map[Value]Value{}
3244
if _, err := Decode(data, &tmpValue); err != nil {
3345
return err

0 commit comments

Comments
 (0)