diff --git a/actions/action.pb.go b/actions/action.pb.go index d664490..3ebfb73 100644 --- a/actions/action.pb.go +++ b/actions/action.pb.go @@ -52,9 +52,7 @@ func (ActionType) EnumDescriptor() ([]byte, []int) { } type Action struct { - BlockHeight int64 `protobuf:"varint,1,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` - // x_coordinate is the account's affine Pallas x-coordinate encoded as a - // 32-byte canonical big-endian field element. + BlockHeight int64 `protobuf:"varint,1,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` XCoordinate []byte `protobuf:"bytes,2,opt,name=x_coordinate,json=xCoordinate,proto3" json:"x_coordinate,omitempty"` // is_odd selects the affine y-coordinate with odd parity. IsOdd bool `protobuf:"varint,3,opt,name=is_odd,json=isOdd,proto3" json:"is_odd,omitempty"` diff --git a/apperrors/error.go b/apperrors/error.go index 641fee6..084192b 100644 --- a/apperrors/error.go +++ b/apperrors/error.go @@ -51,14 +51,12 @@ var ( // ErrNilAction reports that a nil action was encountered where a concrete action was required. ErrNilAction = errors.New("nil action") - // ErrInvalidActionType reports that an action payload contains an unsupported type. + // ErrInvalidActionType reports that an action-type field cannot be parsed as an integer. ErrInvalidActionType = errors.New("invalid action type") - // ErrInvalidAmount reports that an action amount is malformed or non-positive. + // ErrInvalidAmount reports that an action amount cannot be parsed as a signed 64-bit integer. ErrInvalidAmount = errors.New("invalid action amount") - // ErrInvalidActionData reports that an action payload is missing required fields. + // ErrInvalidActionData reports that an action payload cannot be decoded into the wrapper representation. ErrInvalidActionData = errors.New("invalid action data") - // ErrEmptyXCoordinate reports that an action payload is missing the x-coordinate of account's pubkey. - ErrEmptyXCoordinate = errors.New("empty x coordinate") ) var ( diff --git a/database/db_test.go b/database/db_test.go index 17bde56..de16be6 100644 --- a/database/db_test.go +++ b/database/db_test.go @@ -8,6 +8,7 @@ import ( "log/slog" "os" "path/filepath" + "strconv" "testing" "github.com/node101-io/archive-wrapper/actions" @@ -66,16 +67,15 @@ func TestDbManager_InsertThenGet(t *testing.T) { } -func TestDbManagerInsertRejectsInvalidXCoordinate(t *testing.T) { +func TestDbManagerInsertAllowsAnyXCoordinate(t *testing.T) { tests := []struct { - name string - x []byte - wantErr error + name string + x []byte }{ - {name: "empty", x: nil, wantErr: apperrors.ErrEmptyXCoordinate}, - {name: "short", x: []byte{1}, wantErr: apperrors.ErrInvalidActionData}, - {name: "long", x: make([]byte, minafield.NewField().ElementSize()+1), wantErr: apperrors.ErrInvalidActionData}, - {name: "non-canonical", x: bytes.Repeat([]byte{0xff}, minafield.NewField().ElementSize()), wantErr: apperrors.ErrInvalidActionData}, + {name: "empty", x: nil}, + {name: "short", x: []byte{1}}, + {name: "long", x: make([]byte, minafield.NewField().ElementSize()+1)}, + {name: "non-canonical", x: bytes.Repeat([]byte{0xff}, minafield.NewField().ElementSize())}, } for _, tt := range tests { @@ -85,8 +85,32 @@ func TestDbManagerInsertRejectsInvalidXCoordinate(t *testing.T) { require.NoError(t, err) defer func() { require.NoError(t, manager.Close()) }() - err = manager.Insert(testRecordWithX(10, tt.x)) - require.ErrorIs(t, err, tt.wantErr) + record := testRecordWithX(10, tt.x) + require.NoError(t, manager.Insert(record)) + + got, err := manager.Get(record.Key) + require.NoError(t, err) + require.Equal(t, tt.x, got.Actions[0].XCoordinate) + }) + } +} + +func TestDbManagerInsertAllowsNonPositiveAmount(t *testing.T) { + for _, amount := range []int64{0, -1} { + t.Run(strconv.FormatInt(amount, 10), func(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + manager, err := NewDbManager(t.TempDir(), blockHeightDatabaseKey, logger) + require.NoError(t, err) + defer func() { require.NoError(t, manager.Close()) }() + + record := testRecordWithX(10, canonicalXCoordinate()) + record.Actions[0].Amount = amount + + require.NoError(t, manager.Insert(record)) + + got, err := manager.Get(record.Key) + require.NoError(t, err) + require.Equal(t, amount, got.Actions[0].Amount) }) } } @@ -474,38 +498,6 @@ func TestDbManagerGetRejectsCorruptPersistedRecord(t *testing.T) { }}, }), }, - { - name: "invalid action", - height: 10, - persisted: marshalRecord(t, actions.DbRecord{ - Key: 10, - Actions: []*actions.Action{{ - BlockHeight: 10, - XCoordinate: canonicalXCoordinate(), - IsOdd: true, - ActionType: actions.ActionType_DEPOSIT, - Amount: 0, - }}, - }), - }, - { - name: "short x coordinate", - height: 10, - persisted: marshalRecord(t, testRecordWithX(10, []byte{1})), - }, - { - name: "long x coordinate", - height: 10, - persisted: marshalRecord(t, testRecordWithX(10, make([]byte, minafield.NewField().ElementSize()+1))), - }, - { - name: "non-canonical x coordinate", - height: 10, - persisted: marshalRecord(t, testRecordWithX( - 10, - bytes.Repeat([]byte{0xff}, minafield.NewField().ElementSize()), - )), - }, } for _, tt := range tests { diff --git a/database/helpers.go b/database/helpers.go index 802762b..0e4a73e 100644 --- a/database/helpers.go +++ b/database/helpers.go @@ -1,13 +1,10 @@ package database import ( - "bytes" "encoding/binary" - cosmosErrors "cosmossdk.io/errors" actions "github.com/node101-io/archive-wrapper/actions" "github.com/node101-io/archive-wrapper/apperrors" - minafield "github.com/node101-io/mina-signer-go/field" ) func encodeBlockHeight(height int64) []byte { @@ -36,26 +33,10 @@ func validateRecord(record actions.DbRecord) error { return apperrors.ErrNilAction } - if act.BlockHeight <= 0 { - return apperrors.ErrBlockHeightMustBeBiggerThanZero - } - if act.BlockHeight != record.Key { return apperrors.ErrInvalidKey } - if act.Amount <= 0 { - return cosmosErrors.Wrap(apperrors.ErrInvalidAmount, "non-positive amount") - } - - if len(act.XCoordinate) == 0 { - return apperrors.ErrEmptyXCoordinate - } - - fieldElement, err := minafield.NewFieldElement(act.XCoordinate) - if err != nil || !bytes.Equal(fieldElement.Bytes(), act.XCoordinate) { - return cosmosErrors.Wrap(apperrors.ErrInvalidActionData, "invalid x coordinate") - } } return nil diff --git a/fetchmina/fetch.go b/fetchmina/fetch.go index 46d015c..5a9a719 100644 --- a/fetchmina/fetch.go +++ b/fetchmina/fetch.go @@ -1,7 +1,6 @@ package fetchmina import ( - "bytes" "context" "errors" "fmt" @@ -18,6 +17,7 @@ import ( "github.com/node101-io/archive-wrapper/apperrors" sqlcdb "github.com/node101-io/archive-wrapper/fetchmina/db" "github.com/node101-io/mina-signer-go/address" + minafield "github.com/node101-io/mina-signer-go/field" ) @@ -85,7 +85,7 @@ func (c *MinaClient) GetMinaBlockHeight(ctx context.Context) (int64, error) { return height, nil } -// FetchActions returns supported zkApp actions for blockHeight on the cached best chain. +// FetchActions returns zkApp actions for blockHeight on the cached best chain. // It returns ErrBestChainBlockNotFound when the selected chain has no block at that height yet. func (c *MinaClient) FetchActions(ctx context.Context, blockHeight int64) ([]actions.Action, error) { if blockHeight <= 0 { @@ -123,9 +123,6 @@ func (c *MinaClient) FetchActions(ctx context.Context, blockHeight int64) ([]act if err != nil { return nil, err } - if action == nil { - continue - } result = append(result, *action) } @@ -234,37 +231,26 @@ func actionFromRawData(blockHeight int64, data []string) (*actions.Action, error if len(data) == 0 { return nil, nil } - - actionTypeValue, err := strconv.Atoi(data[actionTypeIndex]) - if err != nil { - return nil, err - } - - switch actions.ActionType(actionTypeValue) { - case actions.ActionType_UNSPECIFIED: - return nil, nil - case actions.ActionType_DEPOSIT, actions.ActionType_WITHDRAW: - default: - return nil, nil + if len(data) < minimumActionFields { + return nil, cosmosErrors.Wrapf( + apperrors.ErrInvalidActionData, + "action payload has %d fields; expected at least %d", + len(data), + minimumActionFields, + ) } actionType, amount, err := parseActionData(data) if err != nil { return nil, err } - if actionType == actions.ActionType_UNSPECIFIED { - return nil, nil - } xCoordinateBytes, err := fieldBytesFromDecimal(data[actionXCoordinateIndex]) if err != nil { return nil, err } - isOdd, err := parseIsOddField(data[actionIsOddIndex]) - if err != nil { - return nil, err - } + isOdd := parseIsOddField(data[actionIsOddIndex]) return &actions.Action{ BlockHeight: blockHeight, @@ -278,35 +264,29 @@ func actionFromRawData(blockHeight int64, data []string) (*actions.Action, error func fieldBytesFromDecimal(s string) ([]byte, error) { n, ok := new(big.Int).SetString(s, 10) if !ok || n.Sign() < 0 { - return nil, cosmosErrors.Wrap(apperrors.ErrInvalidActionData, "invalid account x_coordinate") + return nil, cosmosErrors.Wrap( + apperrors.ErrInvalidActionData, + "invalid account x_coordinate", + ) } - size := minafield.NewField().ElementSize() raw := n.Bytes() - if len(raw) > size { - return nil, cosmosErrors.Wrap(apperrors.ErrInvalidActionData, "invalid account x_coordinate") + size := minafield.NewField().ElementSize() + + // Oversized/non-canonical values are forwarded for Pulsar to reject. + if len(raw) >= size { + return raw, nil } + // Preserve the existing 32-byte wire representation for valid values. b := make([]byte, size) copy(b[size-len(raw):], raw) - fieldElement, err := minafield.NewFieldElement(b) - if err != nil || !bytes.Equal(fieldElement.Bytes(), b) { - return nil, cosmosErrors.Wrap(apperrors.ErrInvalidActionData, "invalid account x_coordinate") - } - return b, nil } -func parseIsOddField(v string) (bool, error) { - switch v { - case "0": - return false, nil - case "1": - return true, nil - default: - return false, cosmosErrors.Wrap(apperrors.ErrInvalidActionData, "invalid account is_odd") - } +func parseIsOddField(v string) bool { + return v == "1" } func wrapQueryError(operation string, err error) error { @@ -328,32 +308,15 @@ func parseActionData(data []string) (actions.ActionType, int64, error) { return 0, 0, cosmosErrors.Wrap(apperrors.ErrInvalidActionData, "missing action type") } - actionTypeValue, err := strconv.Atoi(data[actionTypeIndex]) + actionTypeValue, err := strconv.ParseInt(data[actionTypeIndex], 10, 32) if err != nil { return 0, 0, apperrors.ErrInvalidActionType } - switch actionTypeValue { - case int(actions.ActionType_UNSPECIFIED): - return actions.ActionType_UNSPECIFIED, 0, nil - - case int(actions.ActionType_DEPOSIT), int(actions.ActionType_WITHDRAW): - // These action types expect the amount field to be present. - if len(data) < minimumActionFields { - return 0, 0, cosmosErrors.Wrap(apperrors.ErrInvalidActionData, "missing fields") - } - - amount, err := strconv.ParseInt(data[actionAmountIndex], 10, 64) - if err != nil { - return 0, 0, apperrors.ErrInvalidAmount - } - if amount <= 0 { - return 0, 0, cosmosErrors.Wrap(apperrors.ErrInvalidAmount, "non-positive amount") - } - - return actions.ActionType(actionTypeValue), amount, nil - - default: - return 0, 0, apperrors.ErrInvalidActionType + amount, err := strconv.ParseInt(data[actionAmountIndex], 10, 64) + if err != nil { + return 0, 0, apperrors.ErrInvalidAmount } + + return actions.ActionType(actionTypeValue), amount, nil } diff --git a/fetchmina/fetch_test.go b/fetchmina/fetch_test.go index 104e5e5..f3a1c06 100644 --- a/fetchmina/fetch_test.go +++ b/fetchmina/fetch_test.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "log/slog" + "math/big" "testing" "github.com/jackc/pgx/v5" @@ -72,6 +73,30 @@ func TestActionFromRawDataBuildsAction(t *testing.T) { } } +func TestActionFromRawDataRejectsIncompletePayloads(t *testing.T) { + tests := []struct { + name string + data []string + }{ + {name: "one field", data: []string{"1"}}, + {name: "two fields", data: []string{"1", "7"}}, + {name: "three fields", data: []string{"1", "7", "1"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var action *actions.Action + var err error + + require.NotPanics(t, func() { + action, err = actionFromRawData(99, tt.data) + }) + require.Nil(t, action) + require.ErrorIs(t, err, apperrors.ErrInvalidActionData) + }) + } +} + func TestFieldBytesFromDecimal(t *testing.T) { tests := []struct { name string @@ -91,7 +116,7 @@ func TestFieldBytesFromDecimal(t *testing.T) { } } -func TestFieldBytesFromDecimalRejectsInvalidValues(t *testing.T) { +func TestFieldBytesFromDecimalRejectsMalformedValues(t *testing.T) { tests := []struct { name string value string @@ -99,8 +124,6 @@ func TestFieldBytesFromDecimalRejectsInvalidValues(t *testing.T) { {name: "empty", value: ""}, {name: "malformed", value: "not-a-number"}, {name: "negative", value: "-1"}, - {name: "field modulus", value: pallasBaseFieldModulus}, - {name: "above field byte size", value: integerAboveFieldByteSize}, } for _, tt := range tests { @@ -113,67 +136,107 @@ func TestFieldBytesFromDecimalRejectsInvalidValues(t *testing.T) { } } -func TestParseIsOddField(t *testing.T) { +func TestFieldBytesFromDecimalForwardsNonCanonicalValues(t *testing.T) { tests := []struct { name string value string - want bool }{ - {name: "even", value: "0", want: false}, - {name: "odd", value: "1", want: true}, + {name: "field modulus", value: pallasBaseFieldModulus}, + {name: "above field byte size", value: integerAboveFieldByteSize}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := parseIsOddField(tt.value) + got, err := fieldBytesFromDecimal(tt.value) + require.NoError(t, err) - require.Equal(t, tt.want, got) + require.Equal(t, tt.value, new(big.Int).SetBytes(got).String()) }) } } -func TestParseIsOddFieldRejectsInvalidValues(t *testing.T) { +func TestParseIsOddField(t *testing.T) { tests := []struct { name string value string + want bool }{ - {name: "empty", value: ""}, - {name: "negative", value: "-1"}, - {name: "greater than one", value: "2"}, - {name: "boolean text", value: "true"}, + {name: "even", value: "0", want: false}, + {name: "odd", value: "1", want: true}, + {name: "contract-invalid value defaults to even", value: "2", want: false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := parseIsOddField(tt.value) - - require.False(t, got) - require.ErrorIs(t, err, apperrors.ErrInvalidActionData) + got := parseIsOddField(tt.value) + require.Equal(t, tt.want, got) }) } } -func TestActionFromRawDataRejectsInvalidFields(t *testing.T) { +func TestActionFromRawDataDefersContractInvariantValidation(t *testing.T) { tests := []struct { - name string - data []string - wantErr error + name string + data []string + wantActionType actions.ActionType + wantAmount int64 + wantIsOdd bool }{ - {name: "missing fields", data: []string{"1", "7"}, wantErr: apperrors.ErrInvalidActionData}, - {name: "invalid x coordinate", data: []string{"1", pallasBaseFieldModulus, "1", "42"}, wantErr: apperrors.ErrInvalidActionData}, - {name: "invalid parity", data: []string{"1", "7", "2", "42"}, wantErr: apperrors.ErrInvalidActionData}, + { + name: "unspecified action type", + data: []string{"0", "7", "0", "42"}, + wantActionType: actions.ActionType_UNSPECIFIED, + wantAmount: 42, + }, + { + name: "unknown action type", + data: []string{"3", "7", "1", "42"}, + wantActionType: actions.ActionType(3), + wantAmount: 42, + wantIsOdd: true, + }, + { + name: "zero amount", + data: []string{"1", "7", "1", "0"}, + wantActionType: actions.ActionType_DEPOSIT, + wantAmount: 0, + wantIsOdd: true, + }, + { + name: "negative amount", + data: []string{"2", "7", "0", "-1"}, + wantActionType: actions.ActionType_WITHDRAW, + wantAmount: -1, + }, + { + name: "contract-invalid parity defaults to even", + data: []string{"1", "7", "2", "42"}, + wantActionType: actions.ActionType_DEPOSIT, + wantAmount: 42, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { action, err := actionFromRawData(99, tt.data) - require.Nil(t, action) - require.ErrorIs(t, err, tt.wantErr) + require.NoError(t, err) + require.NotNil(t, action) + require.Equal(t, tt.wantActionType, action.ActionType) + require.Equal(t, tt.wantAmount, action.Amount) + require.Equal(t, tt.wantIsOdd, action.IsOdd) }) } } +func TestActionFromRawDataForwardsNonCanonicalXCoordinate(t *testing.T) { + action, err := actionFromRawData(99, []string{"1", pallasBaseFieldModulus, "1", "42"}) + + require.NoError(t, err) + require.NotNil(t, action) + require.Equal(t, pallasBaseFieldModulus, new(big.Int).SetBytes(action.XCoordinate).String()) +} + func TestGetMinaBlockHeightWrapsRetryableQueryErrors(t *testing.T) { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) querier := &trackingQuerier{ diff --git a/proto/actions/action.proto b/proto/actions/action.proto index 0b0e085..d655f22 100644 --- a/proto/actions/action.proto +++ b/proto/actions/action.proto @@ -16,8 +16,7 @@ message Action { option (gogoproto.goproto_getters) = false; int64 block_height = 1; - // x_coordinate is the account's affine Pallas x-coordinate encoded as a - // 32-byte canonical big-endian field element. + bytes x_coordinate = 2; // is_odd selects the affine y-coordinate with odd parity. bool is_odd = 3;