From 918d7e65bf4eaf86e00144d45268a67ac87c4910 Mon Sep 17 00:00:00 2001 From: Evgeniy Stratonikov Date: Fri, 10 Sep 2021 21:34:48 +0300 Subject: [PATCH] smartcontract: unmarhal `null` values properly First we unmarshal `null` to `[]byte`, then we marshal it to the empty string. Signed-off-by: Evgeniy Stratonikov --- pkg/smartcontract/parameter.go | 14 ++++++++++---- pkg/smartcontract/parameter_test.go | 12 ++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/pkg/smartcontract/parameter.go b/pkg/smartcontract/parameter.go index 0702e17f8..ebf2e237e 100644 --- a/pkg/smartcontract/parameter.go +++ b/pkg/smartcontract/parameter.go @@ -1,6 +1,7 @@ package smartcontract import ( + "bytes" "encoding/base64" "encoding/binary" "encoding/hex" @@ -54,6 +55,12 @@ func (p Parameter) MarshalJSON() ([]byte, error) { resultRawValue json.RawMessage resultErr error ) + if p.Value == nil { + if _, ok := validParamTypes[p.Type]; ok && p.Type != UnknownType { + return json.Marshal(rawParameter{Type: p.Type}) + } + return nil, fmt.Errorf("can't marshal %s", p.Type) + } switch p.Type { case BoolType, StringType, Hash160Type, Hash256Type: resultRawValue, resultErr = json.Marshal(p.Value) @@ -66,9 +73,7 @@ func (p Parameter) MarshalJSON() ([]byte, error) { valStr := strconv.FormatInt(val, 10) resultRawValue = json.RawMessage(`"` + valStr + `"`) case PublicKeyType, ByteArrayType, SignatureType: - if p.Value == nil { - resultRawValue = []byte("null") - } else if p.Type == PublicKeyType { + if p.Type == PublicKeyType { resultRawValue, resultErr = json.Marshal(hex.EncodeToString(p.Value.([]byte))) } else { resultRawValue, resultErr = json.Marshal(base64.StdEncoding.EncodeToString(p.Value.([]byte))) @@ -110,7 +115,8 @@ func (p *Parameter) UnmarshalJSON(data []byte) (err error) { return } p.Type = r.Type - if len(r.Value) == 0 { + p.Value = nil + if len(r.Value) == 0 || bytes.Equal(r.Value, []byte("null")) { return } switch r.Type { diff --git a/pkg/smartcontract/parameter_test.go b/pkg/smartcontract/parameter_test.go index 021f9ca9d..82aba2317 100644 --- a/pkg/smartcontract/parameter_test.go +++ b/pkg/smartcontract/parameter_test.go @@ -41,6 +41,10 @@ var marshalJSONTestCases = []struct { input: Parameter{Type: ByteArrayType}, result: `{"type":"ByteString","value":null}`, }, + { + input: Parameter{Type: SignatureType}, + result: `{"type":"Signature"}`, + }, { input: Parameter{ Type: PublicKeyType, @@ -195,6 +199,14 @@ var unmarshalJSONTestCases = []struct { input: `{"type":"String","value":"Some string"}`, result: Parameter{Type: StringType, Value: "Some string"}, }, + { + input: `{"type":"Signature"}`, + result: Parameter{Type: SignatureType}, + }, + { + input: `{"type":"Signature","value":null }`, + result: Parameter{Type: SignatureType}, + }, { input: `{"type":"Array","value":[ {"type": "String", "value": "str 1"},