Merge pull request #1242 from nspcc-dev/fix/json

Implement lossless stackitem to json conversion
This commit is contained in:
Roman Khimov 2020-08-04 12:59:47 +03:00 committed by GitHub
commit fa5ff8dd95
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 562 additions and 208 deletions

View file

@ -6,7 +6,6 @@ import (
"fmt"
"math/big"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
)
@ -406,18 +405,24 @@ func (s *Stack) PopSigElements() ([][]byte, error) {
return elems, nil
}
// ToContractParameters converts Stack to slice of smartcontract.Parameter.
func (s *Stack) ToContractParameters() []smartcontract.Parameter {
items := make([]smartcontract.Parameter, 0, s.Len())
// ToArray converts stack to an array of stackitems with top item being the last.
func (s *Stack) ToArray() []stackitem.Item {
items := make([]stackitem.Item, 0, s.len)
s.IterBack(func(e *Element) {
// Each item is independent.
seen := make(map[stackitem.Item]bool)
items = append(items, smartcontract.ParameterFromStackItem(e.value, seen))
items = append(items, e.Item())
})
return items
}
// MarshalJSON implements JSON marshalling interface.
func (s *Stack) MarshalJSON() ([]byte, error) {
return json.Marshal(s.ToContractParameters())
items := s.ToArray()
arr := make([]json.RawMessage, len(items))
for i := range items {
data, err := stackitem.ToJSONWithTypes(items[i])
if err == nil {
arr[i] = data
}
}
return json.Marshal(arr)
}