Skip to content
Merged
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
4 changes: 1 addition & 3 deletions actions/action.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 3 additions & 5 deletions apperrors/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
76 changes: 34 additions & 42 deletions database/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"log/slog"
"os"
"path/filepath"
"strconv"
"testing"

"github.com/node101-io/archive-wrapper/actions"
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
})
}
}
Expand Down Expand Up @@ -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 {
Expand Down
19 changes: 0 additions & 19 deletions database/helpers.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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
Expand Down
93 changes: 28 additions & 65 deletions fetchmina/fetch.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package fetchmina

import (
"bytes"
"context"
"errors"
"fmt"
Expand All @@ -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"
)

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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,
Expand All @@ -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 {
Expand All @@ -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)
Comment thread
korayakpinar marked this conversation as resolved.
Resolved
if err != nil {
return 0, 0, apperrors.ErrInvalidAmount
}

return actions.ActionType(actionTypeValue), amount, nil
}
Loading
Loading