Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle unnamed tuple entries consistently on input and output #83

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion internal/signermsgs/en_error_messges.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ var (
MsgFixedLengthABIArrayMismatch = ffe("FF22036", "Input array is length %d, and required fixed array length is %d for component %s")
MsgTupleABIArrayMismatch = ffe("FF22037", "Input array is length %d, and required tuple component count is %d for component %s")
MsgTupleABINotArrayOrMap = ffe("FF22038", "Input type %T is not array or map for component %s")
MsgTupleInABINoName = ffe("FF22039", "Tuple child %d does not have a name for component %s")
MsgMissingInputKeyABITuple = ffe("FF22040", "Input map missing key '%s' required for tuple component %s")
MsgBadABITypeComponent = ffe("FF22041", "Bad ABI type component: %d")
MsgWrongTypeComponentABIEncode = ffe("FF22042", "Incorrect type expected=%s found=%T for ABI encoding of component %s")
Expand Down
50 changes: 50 additions & 0 deletions pkg/abi/abi.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,56 @@ func (a ABI) Errors() map[string]*Entry {
return m
}

// Returns the components value from the parsed error
func (a ABI) ParseError(revertData []byte) (*Entry, *ComponentValue, bool) {
return a.ParseErrorCtx(context.Background(), revertData)
}

// Returns the components value from the parsed error
func (a ABI) ParseErrorCtx(ctx context.Context, revertData []byte) (*Entry, *ComponentValue, bool) {
// Always include the default error
a = append(ABI{
{Type: Error, Name: "Error", Inputs: ParameterArray{{Name: "reason", Type: "string"}}},
}, a...)
for _, e := range a {
if e.Type == Error {
if cv, err := e.DecodeCallDataCtx(ctx, revertData); err == nil {
return e, cv, true
}
}
}
return nil, nil, false
}

func (a ABI) ErrorString(revertData []byte) (string, bool) {
return a.ErrorStringCtx(context.Background(), revertData)
}

func (a ABI) ErrorStringCtx(ctx context.Context, revertData []byte) (string, bool) {
var parsed []interface{}
e, cv, ok := a.ParseErrorCtx(ctx, revertData)
if ok {
if res, err := NewSerializer().SetFormattingMode(FormatAsFlatArrays).SerializeInterfaceCtx(ctx, cv); err == nil {
parsed, ok = res.([]interface{})
}
}
if !ok || parsed == nil {
return "", false
}
buff := new(bytes.Buffer)
buff.WriteString(e.Name)
buff.WriteRune('(')
for i, c := range parsed {
if i > 0 {
buff.WriteRune(',')
}
b, _ := json.Marshal(c)
buff.Write(b)
}
buff.WriteRune(')')
return buff.String(), true
}

// Validate processes all the components of all the parameters in this ABI entry
func (e *Entry) Validate() (err error) {
return e.ValidateCtx(context.Background())
Expand Down
69 changes: 69 additions & 0 deletions pkg/abi/abi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"github.com/hyperledger/firefly-common/pkg/ffapi"
"github.com/hyperledger/firefly-signer/pkg/ethtypes"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const sampleABI1 = `[
Expand Down Expand Up @@ -1027,3 +1028,71 @@ func TestComplexStructSolidityDef(t *testing.T) {
}, childStructs)

}

func TestErrorString(t *testing.T) {

customErrABI := ABI{
{
Type: Error,
Name: "ExampleError",
Inputs: ParameterArray{
{
Name: "param1",
Type: "string",
},
{
Name: "param2",
Type: "uint256",
},
},
},
}

revertReason, err := customErrABI[0].EncodeCallDataJSON([]byte(`{"param1":"test1","param2":12345}`))
assert.NoError(t, err)

errString, ok := customErrABI.ErrorString(revertReason)
assert.True(t, ok)
assert.Equal(t, `ExampleError("test1","12345")`, errString)

e, cv, ok := customErrABI.ParseError(revertReason)
assert.True(t, ok)
assert.NotNil(t, e)
assert.NotNil(t, cv)

exampleDefaultError := ethtypes.MustNewHexBytes0xPrefix(`0x08c379a0` +
`0000000000000000000000000000000000000000000000000000000000000020` +
`000000000000000000000000000000000000000000000000000000000000001a` +
`4e6f7420656e6f7567682045746865722070726f76696465642e000000000000`)
errString, ok = customErrABI.ErrorString(exampleDefaultError)
assert.True(t, ok)
assert.Equal(t, `Error("Not enough Ether provided.")`, errString)

mismatchError := ethtypes.MustNewHexBytes0xPrefix(`0x11223344`)
_, ok = customErrABI.ErrorString(mismatchError)
assert.False(t, ok)

}

func TestUnnamedInputOutput(t *testing.T) {

sampleABI := ABI{
{Type: Function, Name: "set", Inputs: ParameterArray{
{Type: "uint256"},
{Type: "string"},
}},
}

cv, err := sampleABI[0].Inputs.ParseJSON([]byte(`{"0":12345,"1":"test"}`))
require.NoError(t, err)
res, err := NewSerializer().SetFormattingMode(FormatAsFlatArrays).SerializeJSON(cv)
require.NoError(t, err)
require.JSONEq(t, `["12345","test"]`, string(res))

cv, err = sampleABI[0].Inputs.ParseJSON([]byte(`[12345,"test"]`))
require.NoError(t, err)
res, err = NewSerializer().SetFormattingMode(FormatAsObjects).SerializeJSON(cv)
require.NoError(t, err)
require.JSONEq(t, `{"0":"12345","1":"test"}`, string(res))

}
12 changes: 7 additions & 5 deletions pkg/abi/inputparsing.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"fmt"
"math/big"
"reflect"
"strconv"
"strings"

"github.com/hyperledger/firefly-common/pkg/i18n"
Expand Down Expand Up @@ -456,13 +457,14 @@ func walkTupleInput(ctx context.Context, breadcrumbs string, input interface{},
Children: make([]*ComponentValue, len(component.tupleChildren)),
}
for i, tupleChild := range component.tupleChildren {
if tupleChild.keyName == "" {
return nil, i18n.NewError(ctx, signermsgs.MsgTupleInABINoName, i, breadcrumbs)
keyName := tupleChild.keyName
if keyName == "" {
keyName = strconv.Itoa(i)
}
childBreadcrumbs := fmt.Sprintf("%s.%s", breadcrumbs, tupleChild.keyName)
v, ok := iMap[tupleChild.keyName]
childBreadcrumbs := fmt.Sprintf("%s.%s", breadcrumbs, keyName)
v, ok := iMap[keyName]
if !ok {
return nil, i18n.NewError(ctx, signermsgs.MsgMissingInputKeyABITuple, tupleChild.keyName, childBreadcrumbs)
return nil, i18n.NewError(ctx, signermsgs.MsgMissingInputKeyABITuple, keyName, childBreadcrumbs)
}
cv.Children[i], err = walkInput(ctx, childBreadcrumbs, v, component.tupleChildren[i])
if err != nil {
Expand Down
37 changes: 4 additions & 33 deletions pkg/abi/inputparsing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,10 @@ func TestGetIntegerFromInterface(t *testing.T) {
assert.Regexp(t, "FF22030", err)
assert.Nil(t, i)

i, err = getIntegerFromInterface(ctx, "ut", json.Number("wrong"))
assert.Regexp(t, "FF22030", err)
assert.Nil(t, i)

}

func TestGetFloatFromInterface(t *testing.T) {
Expand Down Expand Up @@ -668,39 +672,6 @@ func TestTuplesWrongType(t *testing.T) {

}

func TestTuplesMissingName(t *testing.T) {
const sample = `[
{
"name": "foo",
"type": "function",
"inputs": [
{
"name": "a",
"type": "tuple",
"components": [
{
"type": "uint256"
}
]
}
],
"outputs": []
}
]`

inputs := testABI(t, sample)[0].Inputs

// Fine if you use the array syntax
values := `{ "a": [12345] }`
_, err := inputs.ParseJSON([]byte(values))
assert.NoError(t, err)

// But the missing name is a problem for the object syntax
values = `{ "a": {"b":12345} }`
_, err = inputs.ParseJSON([]byte(values))
assert.Regexp(t, "FF22039", err)
}

func TestTupleEncodeIndividualFixedParam(t *testing.T) {
const sample = `[
{
Expand Down
6 changes: 3 additions & 3 deletions pkg/abi/signedi256.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ var posMax = map[uint16]*big.Int{}
var negMax = map[uint16]*big.Int{}

func init() {
for i := 8; i <= 256; i += 8 {
posMax[uint16(i)] = maxPositiveSignedInt(uint(i))
negMax[uint16(i)] = maxNegativeSignedInt(uint(i))
for i := uint16(8); i <= uint16(256); i += 8 {
posMax[i] = maxPositiveSignedInt(uint(i))
negMax[i] = maxNegativeSignedInt(uint(i))
}
}

Expand Down
5 changes: 4 additions & 1 deletion pkg/abi/typecomponents.go
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,7 @@ func parseMSuffix(ctx context.Context, abiTypeString string, ec *typeComponent,
if err != nil {
return i18n.WrapError(ctx, err, signermsgs.MsgInvalidABISuffix, abiTypeString, ec.elementaryType)
}
//nolint:gosec // we used bitSize on ParseUint above
ec.m = uint16(val)
if ec.m < ec.elementaryType.mMin || ec.m > ec.elementaryType.mMax {
return i18n.NewError(ctx, signermsgs.MsgInvalidABISuffix, abiTypeString, ec.elementaryType)
Expand All @@ -646,6 +647,7 @@ func parseNSuffix(ctx context.Context, abiTypeString string, ec *typeComponent,
if err != nil {
return i18n.WrapError(ctx, err, signermsgs.MsgInvalidABISuffix, abiTypeString, ec.elementaryType)
}
//nolint:gosec // we used bitSize on ParseUint above
ec.n = uint16(val)
if ec.n < ec.elementaryType.nMin || ec.n > ec.elementaryType.nMax {
return i18n.NewError(ctx, signermsgs.MsgInvalidABISuffix, abiTypeString, ec.elementaryType)
Expand All @@ -672,10 +674,11 @@ func parseMxNSuffix(ctx context.Context, abiTypeString string, ec *typeComponent

// parseArrayM parses the "8" in "uint256[8]" for a fixed length array of <type>[M]
func parseArrayM(ctx context.Context, abiTypeString string, ac *typeComponent, mStr string) error {
val, err := strconv.ParseUint(mStr, 10, 64)
val, err := strconv.ParseUint(mStr, 10, 32)
if err != nil {
return i18n.WrapError(ctx, err, signermsgs.MsgInvalidABIArraySpec, abiTypeString)
}
//nolint:gosec // we used bitSize on ParseUint above
ac.arrayLength = int(val)
return nil
}
Expand Down
Loading