mpt: export func for decoding node with type

`NodeObject` can contain auxilliary fields and shouldn't be used from outside.
This commit is contained in:
Evgenii Stratonikov 2020-10-23 10:55:08 +03:00
parent 49d176010e
commit df1792c80b
3 changed files with 25 additions and 19 deletions

View file

@ -1,6 +1,8 @@
package mpt
import (
"fmt"
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/util"
@ -82,3 +84,23 @@ func encodeNodeWithType(n Node, w *io.BinWriter) {
w.WriteB(byte(n.Type()))
n.EncodeBinary(w)
}
// DecodeNodeWithType decodes node together with it's type.
func DecodeNodeWithType(r *io.BinReader) Node {
var n Node
switch typ := NodeType(r.ReadB()); typ {
case BranchT:
n = new(BranchNode)
case ExtensionT:
n = new(ExtensionNode)
case HashT:
n = new(HashNode)
case LeafT:
n = new(LeafNode)
default:
r.Err = fmt.Errorf("invalid node type: %x", typ)
return nil
}
n.DecodeBinary(r)
return n
}

View file

@ -4,7 +4,6 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/util"
@ -43,21 +42,7 @@ func (n NodeObject) EncodeBinary(w *io.BinWriter) {
// DecodeBinary implements io.Serializable.
func (n *NodeObject) DecodeBinary(r *io.BinReader) {
typ := NodeType(r.ReadB())
switch typ {
case BranchT:
n.Node = new(BranchNode)
case ExtensionT:
n.Node = new(ExtensionNode)
case HashT:
n.Node = new(HashNode)
case LeafT:
n.Node = new(LeafNode)
default:
r.Err = fmt.Errorf("invalid node type: %x", typ)
return
}
n.Node.DecodeBinary(r)
n.Node = DecodeNodeWithType(r)
}
// UnmarshalJSON implements json.Unmarshaler.

View file

@ -41,10 +41,9 @@ func TestGetProof_MarshalJSON(t *testing.T) {
require.Equal(t, 8, len(p.Result.Proof))
for i := range p.Result.Proof { // smoke test that every chunk is correctly encoded node
r := io.NewBinReaderFromBuf(p.Result.Proof[i])
var n mpt.NodeObject
n.DecodeBinary(r)
n := mpt.DecodeNodeWithType(r)
require.NoError(t, r.Err)
require.NotNil(t, n.Node)
require.NotNil(t, n)
}
})
}