diff --git a/.github/workflows/auth-mode-e2e.yml b/.github/workflows/auth-mode-e2e.yml new file mode 100644 index 00000000..bcf6e855 --- /dev/null +++ b/.github/workflows/auth-mode-e2e.yml @@ -0,0 +1,73 @@ +name: Auth mode transactions + +on: + pull_request: + merge_group: + +permissions: + contents: read + +jobs: + auth-mode-e2e: + name: UNSPECIFIED, Cosmos, Mina, and smart-account transactions + runs-on: ubuntu-latest + timeout-minutes: 90 + defaults: + run: + working-directory: pulsar-chain + steps: + - name: Check out Pulsar + uses: actions/checkout@v4 + with: + path: pulsar-chain + + - name: Check out archive-wrapper contract + uses: actions/checkout@v4 + with: + repository: node101-io/archive-wrapper + ref: cd42a203ac6b43d24d9fbd57c323ecd52ea52bd5 + path: archive-wrapper + + - name: Check out pulsar-verifier contract + uses: actions/checkout@v4 + with: + repository: node101-io/pulsar-verifier + ref: e7582ba2aea2fa12b765221003a366868f39b3e8 + path: pulsar-verifier + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: pulsar-chain/go.mod + cache: true + cache-dependency-path: pulsar-chain/go.sum + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.10" + + - name: Run auth-mode transaction E2E + env: + ARCHIVE_WRAPPER_SOURCE: ${{ github.workspace }}/archive-wrapper + AUTH_MODE_E2E_ONLY: "1" + ENABLE_VERIFIER_SIDECARS: "1" + E2E_ARTIFACT_DIR: ${{ github.workspace }}/pulsar-chain/e2e-artifacts + PULSAR_VERIFIER_SOURCE: ${{ github.workspace }}/pulsar-verifier + run: | + set -o pipefail + ./scripts/test_archive_wrapper_deployment.sh shared 2>&1 \ + | sed -E \ + -e 's#postgres://[^ @]+@#postgres://[REDACTED]@#g' \ + -e 's/e2e-secret/[REDACTED]/g' \ + | tee auth-mode-e2e.log + + - name: Upload failure evidence + if: failure() + uses: actions/upload-artifact@v4 + with: + name: auth-mode-e2e-failure + if-no-files-found: ignore + path: | + pulsar-chain/auth-mode-e2e.log + pulsar-chain/e2e-artifacts/ diff --git a/.gitignore b/.gitignore index f83acbb7..8336f1d2 100644 --- a/.gitignore +++ b/.gitignore @@ -9,5 +9,7 @@ release/ *.log *.ign .docker/ +.cache/smartaccounts/ +.cache/pulsar-verifier/ __pycache__/ *.py[cod] diff --git a/Dockerfile b/Dockerfile index f08d95b2..66dbfe21 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,6 +2,8 @@ FROM golang:1.26.5-alpine3.24@sha256:0178a641fbb4858c5f1b48e34bdaabe0350a330a1b1149aabd498d0699ff5fb2 AS builder +RUN apk upgrade --no-cache libcrypto3 libssl3 + WORKDIR /src COPY go.mod go.sum ./ @@ -17,7 +19,8 @@ RUN --mount=type=cache,target=/go/pkg/mod \ FROM alpine:3.24@sha256:28bd5fe8b56d1bd048e5babf5b10710ebe0bae67db86916198a6eec434943f8b AS runtime -RUN apk add --no-cache bash ca-certificates curl python3 +RUN apk upgrade --no-cache libcrypto3 libssl3 \ + && apk add --no-cache bash ca-certificates curl python3 WORKDIR /opt/pulsar diff --git a/app/ante/handler.go b/app/ante/handler.go index 5c49854c..9f5cb153 100644 --- a/app/ante/handler.go +++ b/app/ante/handler.go @@ -19,6 +19,7 @@ import ( type HandlerOptions struct { AccountKeeper authante.AccountKeeper BankKeeper authtypes.BankKeeper + SmartAccountKeeper SmartAccountKeeper ExtensionOptionChecker authante.ExtensionOptionChecker FeegrantKeeper authante.FeegrantKeeper SignModeHandler *txsigning.HandlerMap @@ -48,6 +49,10 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "keyregistry keeper is required for ante builder") } + if options.SmartAccountKeeper == nil { + return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "smart account keeper is required for ante builder") + } + if options.MinaNetworkID == "" { return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "mina network ID is required for ante builder") } @@ -77,6 +82,12 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { options.Logger, ) + smartAccountVerifier := NewSmartAccountVerifier( + options.SmartAccountKeeper, + options.AccountKeeper, + options.SignModeHandler, + ) + anteDecorators := []sdk.AnteDecorator{ authante.NewSetUpContextDecorator(), authante.NewExtensionOptionsDecorator(NewTxAuthExtensionOptionChecker(options.ExtensionOptionChecker)), @@ -89,7 +100,7 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { NewRoutedSetPubKeyDecorator(cosmosSetPubKey), NewRoutedValidateSigCountDecorator(options.AccountKeeper, cosmosValidateSigCount), NewRoutedSigGasConsumeDecorator(options.AccountKeeper, cosmosSigGasConsume), - NewRoutedSigVerificationDecorator(cosmosSigVerify, minaVerifier), + NewRoutedSigVerificationDecorator(cosmosSigVerify, minaVerifier, smartAccountVerifier), NewStakingDecorator(options.KeyregistryKeeper), authante.NewIncrementSequenceDecorator(options.AccountKeeper), } diff --git a/app/ante/handler_test.go b/app/ante/handler_test.go index e55e4e4f..9b93904d 100644 --- a/app/ante/handler_test.go +++ b/app/ante/handler_test.go @@ -64,9 +64,21 @@ func (stubBankKeeper) SendCoinsFromAccountToModule(context.Context, sdk.AccAddre return nil } +type stubSmartAccountKeeper struct{} + +func (stubSmartAccountKeeper) IsSessionKeyAuthorized( + context.Context, + []byte, + []byte, + []byte, +) (bool, error) { + return false, nil +} + var ( - _ authante.AccountKeeper = stubAccountKeeper{} - _ authtypes.BankKeeper = stubBankKeeper{} + _ authante.AccountKeeper = stubAccountKeeper{} + _ authtypes.BankKeeper = stubBankKeeper{} + _ appante.SmartAccountKeeper = stubSmartAccountKeeper{} ) var stubKeyregistryKeeper = &keyregistrykeeper.Keeper{} @@ -77,12 +89,13 @@ func TestNewAnteHandler(t *testing.T) { t.Parallel() anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ - AccountKeeper: stubAccountKeeper{}, - BankKeeper: stubBankKeeper{}, - SignModeHandler: &txsigning.HandlerMap{}, - KeyregistryKeeper: stubKeyregistryKeeper, - MinaNetworkID: appante.DefaultMinaNetworkID, - Logger: log.NewNopLogger(), + AccountKeeper: stubAccountKeeper{}, + BankKeeper: stubBankKeeper{}, + SignModeHandler: &txsigning.HandlerMap{}, + KeyregistryKeeper: stubKeyregistryKeeper, + SmartAccountKeeper: stubSmartAccountKeeper{}, + MinaNetworkID: appante.DefaultMinaNetworkID, + Logger: log.NewNopLogger(), }) require.NoError(t, err) @@ -95,11 +108,12 @@ func TestNewAnteHandlerRequiresAccountKeeper(t *testing.T) { t.Parallel() anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ - BankKeeper: stubBankKeeper{}, - SignModeHandler: &txsigning.HandlerMap{}, - KeyregistryKeeper: stubKeyregistryKeeper, - MinaNetworkID: appante.DefaultMinaNetworkID, - Logger: log.NewNopLogger(), + BankKeeper: stubBankKeeper{}, + SignModeHandler: &txsigning.HandlerMap{}, + KeyregistryKeeper: stubKeyregistryKeeper, + SmartAccountKeeper: stubSmartAccountKeeper{}, + MinaNetworkID: appante.DefaultMinaNetworkID, + Logger: log.NewNopLogger(), }) require.ErrorContains(t, err, "account keeper is required for ante builder") @@ -112,11 +126,12 @@ func TestNewAnteHandlerRequiresBankKeeper(t *testing.T) { t.Parallel() anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ - AccountKeeper: stubAccountKeeper{}, - SignModeHandler: &txsigning.HandlerMap{}, - KeyregistryKeeper: stubKeyregistryKeeper, - MinaNetworkID: appante.DefaultMinaNetworkID, - Logger: log.NewNopLogger(), + AccountKeeper: stubAccountKeeper{}, + SignModeHandler: &txsigning.HandlerMap{}, + KeyregistryKeeper: stubKeyregistryKeeper, + SmartAccountKeeper: stubSmartAccountKeeper{}, + MinaNetworkID: appante.DefaultMinaNetworkID, + Logger: log.NewNopLogger(), }) require.ErrorContains(t, err, "bank keeper is required for ante builder") @@ -129,11 +144,12 @@ func TestNewAnteHandlerRequiresSignModeHandler(t *testing.T) { t.Parallel() anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ - AccountKeeper: stubAccountKeeper{}, - BankKeeper: stubBankKeeper{}, - KeyregistryKeeper: stubKeyregistryKeeper, - MinaNetworkID: appante.DefaultMinaNetworkID, - Logger: log.NewNopLogger(), + AccountKeeper: stubAccountKeeper{}, + BankKeeper: stubBankKeeper{}, + KeyregistryKeeper: stubKeyregistryKeeper, + SmartAccountKeeper: stubSmartAccountKeeper{}, + MinaNetworkID: appante.DefaultMinaNetworkID, + Logger: log.NewNopLogger(), }) require.ErrorContains(t, err, "sign mode handler is required for ante builder") @@ -146,11 +162,12 @@ func TestNewAnteHandlerRequiresKeyregistryKeeper(t *testing.T) { t.Parallel() anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ - AccountKeeper: stubAccountKeeper{}, - BankKeeper: stubBankKeeper{}, - SignModeHandler: &txsigning.HandlerMap{}, - MinaNetworkID: appante.DefaultMinaNetworkID, - Logger: log.NewNopLogger(), + AccountKeeper: stubAccountKeeper{}, + BankKeeper: stubBankKeeper{}, + SignModeHandler: &txsigning.HandlerMap{}, + SmartAccountKeeper: stubSmartAccountKeeper{}, + MinaNetworkID: appante.DefaultMinaNetworkID, + Logger: log.NewNopLogger(), }) require.ErrorContains(t, err, "keyregistry keeper is required for ante builder") @@ -163,11 +180,12 @@ func TestNewAnteHandlerRequiresMinaNetworkID(t *testing.T) { t.Parallel() anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ - AccountKeeper: stubAccountKeeper{}, - BankKeeper: stubBankKeeper{}, - SignModeHandler: &txsigning.HandlerMap{}, - KeyregistryKeeper: stubKeyregistryKeeper, - Logger: log.NewNopLogger(), + AccountKeeper: stubAccountKeeper{}, + BankKeeper: stubBankKeeper{}, + SignModeHandler: &txsigning.HandlerMap{}, + KeyregistryKeeper: stubKeyregistryKeeper, + SmartAccountKeeper: stubSmartAccountKeeper{}, + Logger: log.NewNopLogger(), }) require.ErrorContains(t, err, "mina network ID is required for ante builder") @@ -180,12 +198,13 @@ func TestNewAnteHandlerRejectsUnsupportedMinaNetworkID(t *testing.T) { t.Parallel() anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ - AccountKeeper: stubAccountKeeper{}, - BankKeeper: stubBankKeeper{}, - SignModeHandler: &txsigning.HandlerMap{}, - KeyregistryKeeper: stubKeyregistryKeeper, - MinaNetworkID: "unsupported", - Logger: log.NewNopLogger(), + AccountKeeper: stubAccountKeeper{}, + BankKeeper: stubBankKeeper{}, + SignModeHandler: &txsigning.HandlerMap{}, + KeyregistryKeeper: stubKeyregistryKeeper, + SmartAccountKeeper: stubSmartAccountKeeper{}, + MinaNetworkID: "unsupported", + Logger: log.NewNopLogger(), }) require.ErrorIs(t, err, sdkerrors.ErrLogic) @@ -198,14 +217,31 @@ func TestNewAnteHandlerRejectsUnsupportedMinaNetworkID(t *testing.T) { func TestNewAnteHandlerRequiresLogger(t *testing.T) { t.Parallel() + anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ + AccountKeeper: stubAccountKeeper{}, + BankKeeper: stubBankKeeper{}, + SignModeHandler: &txsigning.HandlerMap{}, + KeyregistryKeeper: stubKeyregistryKeeper, + SmartAccountKeeper: stubSmartAccountKeeper{}, + MinaNetworkID: appante.DefaultMinaNetworkID, + }) + + require.ErrorContains(t, err, "logger is required for ante builder") + require.Nil(t, anteHandler) +} + +func TestNewAnteHandlerRequiresSmartAccountKeeper(t *testing.T) { + t.Parallel() + anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ AccountKeeper: stubAccountKeeper{}, BankKeeper: stubBankKeeper{}, SignModeHandler: &txsigning.HandlerMap{}, KeyregistryKeeper: stubKeyregistryKeeper, MinaNetworkID: appante.DefaultMinaNetworkID, + Logger: log.NewNopLogger(), }) - require.ErrorContains(t, err, "logger is required for ante builder") + require.ErrorContains(t, err, "smart account keeper is required for ante builder") require.Nil(t, anteHandler) } diff --git a/app/ante/mina_verifier_test.go b/app/ante/mina_verifier_test.go index 6678108e..dafb4e2e 100644 --- a/app/ante/mina_verifier_test.go +++ b/app/ante/mina_verifier_test.go @@ -78,8 +78,9 @@ func TestResolveAuroFieldSignatureNetworkID(t *testing.T) { } type verifierAccountKeeper struct { - account sdk.AccountI - params authtypes.Params + account sdk.AccountI + params authtypes.Params + moduleAddress sdk.AccAddress } func (k verifierAccountKeeper) GetParams(context.Context) authtypes.Params { @@ -96,7 +97,7 @@ func (k verifierAccountKeeper) GetAccount(context.Context, sdk.AccAddress) sdk.A func (k verifierAccountKeeper) SetAccount(context.Context, sdk.AccountI) {} -func (k verifierAccountKeeper) GetModuleAddress(string) sdk.AccAddress { return nil } +func (k verifierAccountKeeper) GetModuleAddress(string) sdk.AccAddress { return k.moduleAddress } func (k verifierAccountKeeper) AddressCodec() address.Codec { return nil } diff --git a/app/ante/routed_setpubkey.go b/app/ante/routed_setpubkey.go index 92857652..e54eed1b 100644 --- a/app/ante/routed_setpubkey.go +++ b/app/ante/routed_setpubkey.go @@ -24,7 +24,7 @@ func (d RoutedSetPubKeyDecorator) AnteHandle( return ctx, err } - if mode == TxAuthModeMina { + if mode == TxAuthModeMina || mode == TxAuthModeSmartAccount { return next(ctx, tx, simulate) } diff --git a/app/ante/routed_setpubkey_test.go b/app/ante/routed_setpubkey_test.go index a65ba2a5..a2a939eb 100644 --- a/app/ante/routed_setpubkey_test.go +++ b/app/ante/routed_setpubkey_test.go @@ -31,6 +31,36 @@ func TestRoutedSetPubKeyDecoratorRoutesToCosmosDecorator(t *testing.T) { require.True(t, nextCalled) } +func TestRoutedSetPubKeyDecoratorSkipsForSmartAccount(t *testing.T) { + t.Parallel() + + ctx := setTxAuthMode( + newTestSDKContext(t), + TxAuthModeSmartAccount, + ) + + delegate := &recordingDecorator{} + nextCalled := false + + _, err := NewRoutedSetPubKeyDecorator(delegate).AnteHandle( + ctx, + nil, + false, + func( + nextCtx sdk.Context, + tx sdk.Tx, + simulate bool, + ) (sdk.Context, error) { + nextCalled = true + return nextCtx, nil + }, + ) + + require.NoError(t, err) + require.Zero(t, delegate.calls) + require.True(t, nextCalled) +} + // Mina-auth txs intentionally skip Cosmos pubkey population. // The decorator should fall through directly to the next handler. func TestRoutedSetPubKeyDecoratorSkipsForMina(t *testing.T) { diff --git a/app/ante/routed_siggascost.go b/app/ante/routed_siggascost.go index a5d4e822..b44220d7 100644 --- a/app/ante/routed_siggascost.go +++ b/app/ante/routed_siggascost.go @@ -39,7 +39,7 @@ func (d RoutedSigGasConsumeDecorator) AnteHandle( return ctx, err } - if mode != TxAuthModeMina { + if mode == TxAuthModeCosmos { return d.cosmosDecorator.AnteHandle(ctx, tx, simulate, next) } @@ -54,6 +54,33 @@ func (d RoutedSigGasConsumeDecorator) AnteHandle( return ctx, err } + if mode == TxAuthModeSmartAccount { + for _, sig := range sigs { + switch sig.Data.(type) { + case *signing.SingleSignatureData: + ctx.GasMeter().ConsumeGas( + params.SigVerifyCostED25519, + "ante verify: smart account", + ) + + case *signing.MultiSignatureData: + return ctx, errorsmod.Wrap( + sdkerrors.ErrInvalidType, + "smart-account transactions do not support multisig signatures", + ) + + default: + return ctx, errorsmod.Wrapf( + sdkerrors.ErrInvalidType, + "unexpected signature data type %T", + sig.Data, + ) + } + } + + return next(ctx, tx, simulate) + } + for _, sig := range sigs { switch sig.Data.(type) { case *signing.SingleSignatureData: diff --git a/app/ante/routed_siggascost_test.go b/app/ante/routed_siggascost_test.go index 082480bc..6608510f 100644 --- a/app/ante/routed_siggascost_test.go +++ b/app/ante/routed_siggascost_test.go @@ -226,3 +226,60 @@ func TestRoutedSigGasConsumeDecoratorStopsGasAccountingAtFirstInvalidSignature(t // The second signature is invalid, so only the first one should have consumed verification gas. require.Equal(t, uint64(params.SigVerifyCostSecp256k1), ctx.GasMeter().GasConsumed()-before) } + +func TestRoutedSigGasConsumeDecoratorConsumesEd25519GasForSmartAccount(t *testing.T) { + t.Parallel() + + ctx := setTxAuthMode(newGasMeteredContext(t), TxAuthModeSmartAccount) + params := authtypes.DefaultParams() + params.SigVerifyCostED25519 = 43 + before := ctx.GasMeter().GasConsumed() + nextCalled := false + + _, err := NewRoutedSigGasConsumeDecorator( + validateSigCountAccountKeeper{params: params}, + &recordingDecorator{}, + ).AnteHandle( + ctx, + stubSigVerifiableTx{ + sigs: []signingtypes.SignatureV2{ + {Data: &signingtypes.SingleSignatureData{}}, + }, + }, + false, + func(nextCtx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { + nextCalled = true + return nextCtx, nil + }, + ) + + require.NoError(t, err) + require.True(t, nextCalled) + require.Equal(t, uint64(params.SigVerifyCostED25519), ctx.GasMeter().GasConsumed()-before) +} + +func TestRoutedSigGasConsumeDecoratorRejectsSmartAccountMultisig(t *testing.T) { + t.Parallel() + + ctx := setTxAuthMode(newGasMeteredContext(t), TxAuthModeSmartAccount) + + _, err := NewRoutedSigGasConsumeDecorator( + validateSigCountAccountKeeper{}, + &recordingDecorator{}, + ).AnteHandle( + ctx, + stubSigVerifiableTx{ + sigs: []signingtypes.SignatureV2{ + {Data: &signingtypes.MultiSignatureData{}}, + }, + }, + false, + func(nextCtx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { + t.Fatal("next handler should not be called for smart-account multisig") + return nextCtx, nil + }, + ) + + require.ErrorIs(t, err, sdkerrors.ErrInvalidType) + require.Zero(t, ctx.GasMeter().GasConsumed()) +} diff --git a/app/ante/routed_sigverify.go b/app/ante/routed_sigverify.go index cbbfb804..aa32ff8d 100644 --- a/app/ante/routed_sigverify.go +++ b/app/ante/routed_sigverify.go @@ -1,26 +1,38 @@ package ante -import sdk "github.com/cosmos/cosmos-sdk/types" +import ( + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) // MinaSignatureVerifier verifies Mina-authenticated tx signatures. type MinaSignatureVerifier interface { VerifySignatures(ctx sdk.Context, tx sdk.Tx, simulate bool) error } +// SmartAccountSignatureVerifier verifies smart-account-authenticated tx signatures. +type SmartAccountSignatureVerifier interface { + VerifySignatures(ctx sdk.Context, tx sdk.Tx, simulate bool) error +} + // RoutedSigVerificationDecorator routes signature verification based on tx auth mode. type RoutedSigVerificationDecorator struct { - cosmosDecorator sdk.AnteDecorator - minaVerifier MinaSignatureVerifier + cosmosDecorator sdk.AnteDecorator + minaVerifier MinaSignatureVerifier + smartAccountVerifier SmartAccountSignatureVerifier } // NewRoutedSigVerificationDecorator creates a routed signature verification decorator. func NewRoutedSigVerificationDecorator( cosmosDecorator sdk.AnteDecorator, minaVerifier MinaSignatureVerifier, + smartAccountVerifier SmartAccountSignatureVerifier, ) RoutedSigVerificationDecorator { return RoutedSigVerificationDecorator{ - cosmosDecorator: cosmosDecorator, - minaVerifier: minaVerifier, + cosmosDecorator: cosmosDecorator, + minaVerifier: minaVerifier, + smartAccountVerifier: smartAccountVerifier, } } @@ -36,12 +48,24 @@ func (d RoutedSigVerificationDecorator) AnteHandle( return ctx, err } - if mode != TxAuthModeMina { + switch mode { + case TxAuthModeCosmos: return d.cosmosDecorator.AnteHandle(ctx, tx, simulate, next) - } + case TxAuthModeMina: + if err := d.minaVerifier.VerifySignatures(ctx, tx, simulate); err != nil { + return ctx, err + } - if err := d.minaVerifier.VerifySignatures(ctx, tx, simulate); err != nil { - return ctx, err + case TxAuthModeSmartAccount: + if err := d.smartAccountVerifier.VerifySignatures(ctx, tx, simulate); err != nil { + return ctx, err + } + + default: + return ctx, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "unsupported transaction authentication mode", + ) } return next(ctx, tx, simulate) diff --git a/app/ante/routed_sigverify_test.go b/app/ante/routed_sigverify_test.go index 6a8227dd..332838b9 100644 --- a/app/ante/routed_sigverify_test.go +++ b/app/ante/routed_sigverify_test.go @@ -14,10 +14,15 @@ func TestRoutedSigVerificationDecoratorRoutesToCosmosDecorator(t *testing.T) { ctx := setTxAuthMode(newTestSDKContext(t), TxAuthModeCosmos) delegate := &recordingDecorator{} - verifier := &recordingVerifier{} + minaVerifier := &recordingVerifier{} + smartAccountVerifier := &recordingVerifier{} nextCalled := false - _, err := NewRoutedSigVerificationDecorator(delegate, verifier).AnteHandle( + _, err := NewRoutedSigVerificationDecorator( + delegate, + minaVerifier, + smartAccountVerifier, + ).AnteHandle( ctx, nil, false, @@ -29,7 +34,8 @@ func TestRoutedSigVerificationDecoratorRoutesToCosmosDecorator(t *testing.T) { require.NoError(t, err) require.Equal(t, 1, delegate.calls) - require.Zero(t, verifier.calls) + require.Zero(t, minaVerifier.calls) + require.Zero(t, smartAccountVerifier.calls) require.True(t, nextCalled) } @@ -40,10 +46,15 @@ func TestRoutedSigVerificationDecoratorRoutesToMinaVerifier(t *testing.T) { ctx := setTxAuthMode(newTestSDKContext(t), TxAuthModeMina) delegate := &recordingDecorator{} - verifier := &recordingVerifier{} + minaVerifier := &recordingVerifier{} + smartAccountVerifier := &recordingVerifier{} nextCalled := false - _, err := NewRoutedSigVerificationDecorator(delegate, verifier).AnteHandle( + _, err := NewRoutedSigVerificationDecorator( + delegate, + minaVerifier, + smartAccountVerifier, + ).AnteHandle( ctx, nil, false, @@ -55,13 +66,14 @@ func TestRoutedSigVerificationDecoratorRoutesToMinaVerifier(t *testing.T) { require.NoError(t, err) require.Zero(t, delegate.calls) - require.Equal(t, 1, verifier.calls) + require.Equal(t, 1, minaVerifier.calls) + require.Zero(t, smartAccountVerifier.calls) require.True(t, nextCalled) } // Mina verifier failures must abort the ante chain immediately. // This preserves the verifier error rather than masking it in routing code. -func TestRoutedSigVerificationDecoratorPropagatesVerifierErrors(t *testing.T) { +func TestRoutedSigVerificationDecoratorPropagatesMinaVerifierErrors(t *testing.T) { t.Parallel() ctx := setTxAuthMode(newTestSDKContext(t), TxAuthModeMina) @@ -69,6 +81,59 @@ func TestRoutedSigVerificationDecoratorPropagatesVerifierErrors(t *testing.T) { _, err := NewRoutedSigVerificationDecorator( &recordingDecorator{}, &recordingVerifier{err: errVerifyFailed}, + &recordingVerifier{}, + ).AnteHandle( + ctx, + nil, + false, + func(nextCtx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { + t.Fatal("next handler should not be called when verifier fails") + return nextCtx, nil + }, + ) + + require.ErrorIs(t, err, errVerifyFailed) +} + +func TestRoutedSigVerificationDecoratorRoutesToSmartAccountVerifier(t *testing.T) { + t.Parallel() + + ctx := setTxAuthMode(newTestSDKContext(t), TxAuthModeSmartAccount) + delegate := &recordingDecorator{} + minaVerifier := &recordingVerifier{} + smartAccountVerifier := &recordingVerifier{} + nextCalled := false + + _, err := NewRoutedSigVerificationDecorator( + delegate, + minaVerifier, + smartAccountVerifier, + ).AnteHandle( + ctx, + nil, + false, + func(nextCtx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { + nextCalled = true + return nextCtx, nil + }, + ) + + require.NoError(t, err) + require.Zero(t, delegate.calls) + require.Zero(t, minaVerifier.calls) + require.Equal(t, 1, smartAccountVerifier.calls) + require.True(t, nextCalled) +} + +func TestRoutedSigVerificationDecoratorPropagatesSmartAccountVerifierErrors(t *testing.T) { + t.Parallel() + + ctx := setTxAuthMode(newTestSDKContext(t), TxAuthModeSmartAccount) + + _, err := NewRoutedSigVerificationDecorator( + &recordingDecorator{}, + &recordingVerifier{}, + &recordingVerifier{err: errVerifyFailed}, ).AnteHandle( ctx, nil, diff --git a/app/ante/routed_validate_sigcount.go b/app/ante/routed_validate_sigcount.go index 806ce959..ad44e6b7 100644 --- a/app/ante/routed_validate_sigcount.go +++ b/app/ante/routed_validate_sigcount.go @@ -39,7 +39,7 @@ func (d RoutedValidateSigCountDecorator) AnteHandle( return ctx, err } - if mode != TxAuthModeMina { + if mode == TxAuthModeCosmos { return d.cosmosDecorator.AnteHandle(ctx, tx, simulate, next) } @@ -54,6 +54,34 @@ func (d RoutedValidateSigCountDecorator) AnteHandle( return ctx, err } + if mode == TxAuthModeSmartAccount { + if len(sigs) != 1 { + return ctx, errorsmod.Wrapf( + sdkerrors.ErrUnauthorized, + "smart-account transactions require exactly one signature: got %d", + len(sigs), + ) + } + + switch sigs[0].Data.(type) { + case *signing.SingleSignatureData: + return next(ctx, tx, simulate) + + case *signing.MultiSignatureData: + return ctx, errorsmod.Wrap( + sdkerrors.ErrInvalidType, + "smart-account transactions do not support multisig signatures", + ) + + default: + return ctx, errorsmod.Wrapf( + sdkerrors.ErrInvalidType, + "unexpected signature data type %T", + sigs[0].Data, + ) + } + } + sigCount := 0 for _, sig := range sigs { switch sig.Data.(type) { diff --git a/app/ante/routed_validate_sigcount_test.go b/app/ante/routed_validate_sigcount_test.go index 3997cc0a..70f3f27a 100644 --- a/app/ante/routed_validate_sigcount_test.go +++ b/app/ante/routed_validate_sigcount_test.go @@ -241,3 +241,94 @@ func TestRoutedValidateSigCountDecoratorRejectsSignatureCountAboveLimit(t *testi require.ErrorIs(t, err, sdkerrors.ErrTooManySignatures) require.ErrorContains(t, err, "signatures: 2, limit: 1") } + +func TestRoutedValidateSigCountDecoratorAllowsSingleSmartAccountSignature(t *testing.T) { + t.Parallel() + + ctx := setTxAuthMode(newTestSDKContext(t), TxAuthModeSmartAccount) + nextCalled := false + + _, err := NewRoutedValidateSigCountDecorator( + validateSigCountAccountKeeper{}, + &recordingDecorator{}, + ).AnteHandle( + ctx, + stubSigVerifiableTx{ + sigs: []signingtypes.SignatureV2{ + {Data: &signingtypes.SingleSignatureData{}}, + }, + }, + false, + func(nextCtx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { + nextCalled = true + return nextCtx, nil + }, + ) + + require.NoError(t, err) + require.True(t, nextCalled) +} + +func TestRoutedValidateSigCountDecoratorRejectsInvalidSmartAccountSignatureCount(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + signatures []signingtypes.SignatureV2 + }{ + {name: "missing signature"}, + { + name: "multiple signatures", + signatures: []signingtypes.SignatureV2{ + {Data: &signingtypes.SingleSignatureData{}}, + {Data: &signingtypes.SingleSignatureData{}}, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ctx := setTxAuthMode(newTestSDKContext(t), TxAuthModeSmartAccount) + + _, err := NewRoutedValidateSigCountDecorator( + validateSigCountAccountKeeper{}, + &recordingDecorator{}, + ).AnteHandle( + ctx, + stubSigVerifiableTx{sigs: test.signatures}, + false, + func(nextCtx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { + t.Fatal("next handler should not be called for an invalid signature count") + return nextCtx, nil + }, + ) + + require.ErrorIs(t, err, sdkerrors.ErrUnauthorized) + }) + } +} + +func TestRoutedValidateSigCountDecoratorRejectsSmartAccountMultisig(t *testing.T) { + t.Parallel() + + ctx := setTxAuthMode(newTestSDKContext(t), TxAuthModeSmartAccount) + + _, err := NewRoutedValidateSigCountDecorator( + validateSigCountAccountKeeper{}, + &recordingDecorator{}, + ).AnteHandle( + ctx, + stubSigVerifiableTx{ + sigs: []signingtypes.SignatureV2{ + {Data: &signingtypes.MultiSignatureData{}}, + }, + }, + false, + func(nextCtx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { + t.Fatal("next handler should not be called for smart-account multisig") + return nextCtx, nil + }, + ) + + require.ErrorIs(t, err, sdkerrors.ErrInvalidType) +} diff --git a/app/ante/smart_account_verifier.go b/app/ante/smart_account_verifier.go new file mode 100644 index 00000000..1e60840a --- /dev/null +++ b/app/ante/smart_account_verifier.go @@ -0,0 +1,255 @@ +package ante + +import ( + "context" + + errorsmod "cosmossdk.io/errors" + txsigning "cosmossdk.io/x/tx/signing" + + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + signing "github.com/cosmos/cosmos-sdk/types/tx/signing" + authante "github.com/cosmos/cosmos-sdk/x/auth/ante" + authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + gogoproto "github.com/cosmos/gogoproto/proto" + + antetypes "github.com/node101-io/pulsar-chain/app/ante/types" + smartaccountstypes "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +type SmartAccountKeeper interface { + IsSessionKeyAuthorized(ctx context.Context, identity, accountAddr, publicKey []byte) (bool, error) +} + +// SmartAccountVerifier verifies smart-account transaction signatures. +type SmartAccountVerifier struct { + smartAccountsKeeper SmartAccountKeeper + accountKeeper authante.AccountKeeper + signModeHandler *txsigning.HandlerMap +} + +// NewSmartAccountVerifier creates a smart-account signature verifier. +func NewSmartAccountVerifier( + smartAccountsKeeper SmartAccountKeeper, + accountKeeper authante.AccountKeeper, + signModeHandler *txsigning.HandlerMap, +) SmartAccountVerifier { + return SmartAccountVerifier{ + smartAccountsKeeper: smartAccountsKeeper, + accountKeeper: accountKeeper, + signModeHandler: signModeHandler, + } +} + +// VerifySignatures verifies a smart-account transaction. +func (v SmartAccountVerifier) VerifySignatures( + ctx sdk.Context, + tx sdk.Tx, + simulate bool, +) error { + sigTx, ok := tx.(authsigning.Tx) + if !ok { + return errorsmod.Wrap( + sdkerrors.ErrTxDecode, + "invalid smart-account transaction type", + ) + } + + if sigTx.GetUnordered() { + return errorsmod.Wrap( + sdkerrors.ErrNotSupported, + "unordered smart-account transactions are not supported", + ) + } + + signatures, err := sigTx.GetSignaturesV2() + if err != nil { + return err + } + + signers, err := sigTx.GetSigners() + if err != nil { + return err + } + + if len(signatures) != 1 || len(signers) != 1 { + return errorsmod.Wrapf( + sdkerrors.ErrUnauthorized, + "smart-account transactions require one signer and one signature: signers %d, signatures %d", + len(signers), + len(signatures), + ) + } + + signature := signatures[0] + + signatureData, ok := signature.Data.(*signing.SingleSignatureData) + if !ok { + return errorsmod.Wrap( + sdkerrors.ErrInvalidType, + "smart-account transactions require single signature data", + ) + } + + if signatureData.SignMode != signing.SignMode_SIGN_MODE_DIRECT { + return errorsmod.Wrapf( + sdkerrors.ErrNotSupported, + "unsupported smart-account sign mode: %s", + signatureData.SignMode, + ) + } + + identity, err := smartAccountIdentityFromTx(tx) + if err != nil { + return err + } + + accountAddress := signers[0] + account, err := authante.GetSignerAcc( + ctx, + v.accountKeeper, + accountAddress, + ) + if err != nil { + return err + } + + if signature.Sequence != account.GetSequence() { + return errorsmod.Wrapf( + sdkerrors.ErrWrongSequence, + "account sequence mismatch, expected %d, got %d", + account.GetSequence(), + signature.Sequence, + ) + } + + if simulate { + return nil + } + + sessionPublicKey, ok := signature.PubKey.(*ed25519.PubKey) + if !ok { + return errorsmod.Wrap( + sdkerrors.ErrInvalidPubKey, + "smart-account transactions require an Ed25519 session public key", + ) + } + + authorized, err := v.smartAccountsKeeper.IsSessionKeyAuthorized( + ctx, + identity, + accountAddress, + sessionPublicKey.Bytes(), + ) + if err != nil { + return err + } + if !authorized { + return errorsmod.Wrap( + sdkerrors.ErrUnauthorized, + "session public key is not authorized for smart account", + ) + } + + if ctx.IsReCheckTx() || !ctx.IsSigverifyTx() { + return nil + } + + accountNumber := account.GetAccountNumber() + + signBytes, err := authsigning.GetSignBytesAdapter( + ctx, + v.signModeHandler, + signatureData.SignMode, + authsigning.SignerData{ + Address: account.GetAddress().String(), + ChainID: ctx.ChainID(), + AccountNumber: accountNumber, + Sequence: signature.Sequence, + }, + tx, + ) + if err != nil { + return errorsmod.Wrapf( + sdkerrors.ErrInvalidType, + "generate smart-account sign bytes: %v", + err, + ) + } + + if !sessionPublicKey.VerifySignature( + signBytes, + signatureData.Signature, + ) { + return errorsmod.Wrap( + sdkerrors.ErrUnauthorized, + "smart-account signature verification failed", + ) + } + + return nil +} + +func smartAccountIdentityFromTx(tx sdk.Tx) ([]byte, error) { + txWithExtensions, ok := tx.(HasExtensionOptionsTx) + if !ok { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "smart-account transaction has no extension options", + ) + } + + var identity []byte + found := false + + for _, option := range txWithExtensions.GetExtensionOptions() { + if option == nil || option.TypeUrl != txAuthModeExtensionTypeURL { + continue + } + + if found { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "multiple tx auth mode extensions found", + ) + } + found = true + + extension := &antetypes.TxAuthModeExtension{} + if err := gogoproto.Unmarshal(option.Value, extension); err != nil { + return nil, errorsmod.Wrapf( + sdkerrors.ErrTxDecode, + "invalid tx auth mode extension: %v", + err, + ) + } + + if extension.TxAuthMode != antetypes.TX_AUTH_MODE_SMART_ACCOUNT { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "smart-account verifier received a non-smart-account extension", + ) + } + + identity = extension.SmartAccountIdentity + } + + if !found { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "smart-account auth mode extension not found", + ) + } + + if len(identity) != smartaccountstypes.IdentitySize { + return nil, errorsmod.Wrapf( + sdkerrors.ErrInvalidRequest, + "smart-account identity must be %d bytes: got %d", + smartaccountstypes.IdentitySize, + len(identity), + ) + } + + return identity, nil +} diff --git a/app/ante/smart_account_verifier_test.go b/app/ante/smart_account_verifier_test.go new file mode 100644 index 00000000..2c1bc078 --- /dev/null +++ b/app/ante/smart_account_verifier_test.go @@ -0,0 +1,562 @@ +package ante + +import ( + "bytes" + "context" + "errors" + "testing" + + "cosmossdk.io/log" + txsigning "cosmossdk.io/x/tx/signing" + "github.com/cosmos/cosmos-sdk/client" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" + authante "github.com/cosmos/cosmos-sdk/x/auth/ante" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + gogoproto "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/require" + + antetypes "github.com/node101-io/pulsar-chain/app/ante/types" + keyregistrykeeper "github.com/node101-io/pulsar-chain/x/keyregistry/keeper" + smartaccountstypes "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +type recordingSmartAccountKeeper struct { + authorized bool + err error + calls int + identity []byte + accountAddress []byte + publicKey []byte +} + +type smartAccountVerifierBankKeeper struct{} + +func (smartAccountVerifierBankKeeper) IsSendEnabledCoins(context.Context, ...sdk.Coin) error { + return nil +} + +func (smartAccountVerifierBankKeeper) SendCoins( + context.Context, + sdk.AccAddress, + sdk.AccAddress, + sdk.Coins, +) error { + return nil +} + +func (smartAccountVerifierBankKeeper) SendCoinsFromAccountToModule( + context.Context, + sdk.AccAddress, + string, + sdk.Coins, +) error { + return nil +} + +func (k *recordingSmartAccountKeeper) IsSessionKeyAuthorized( + _ context.Context, + identity, accountAddress, publicKey []byte, +) (bool, error) { + k.calls++ + k.identity = append([]byte(nil), identity...) + k.accountAddress = append([]byte(nil), accountAddress...) + k.publicKey = append([]byte(nil), publicKey...) + + return k.authorized, k.err +} + +type stubSmartAccountTx struct { + stubAuthTx + extensionOptions []*codectypes.Any +} + +func (tx stubSmartAccountTx) GetExtensionOptions() []*codectypes.Any { + return tx.extensionOptions +} + +func mustSmartAccountExtensionAny(t *testing.T, identity []byte) *codectypes.Any { + t.Helper() + + bz, err := gogoproto.Marshal(&antetypes.TxAuthModeExtension{ + TxAuthMode: antetypes.TX_AUTH_MODE_SMART_ACCOUNT, + SmartAccountIdentity: identity, + }) + require.NoError(t, err) + + return &codectypes.Any{ + TypeUrl: txAuthModeExtensionTypeURL, + Value: bz, + } +} + +func buildSmartAccountVerifierTestTx( + t *testing.T, + txConfig client.TxConfig, + from sdk.AccAddress, + pubKey cryptotypes.PubKey, + identity []byte, + sequence uint64, + signature []byte, +) sdk.Tx { + t.Helper() + + builder := txConfig.NewTxBuilder() + to := sdk.AccAddress([]byte("smart-account-recipient")) + + err := builder.SetMsgs(banktypes.NewMsgSend( + from, + to, + sdk.NewCoins(sdk.NewInt64Coin("pmina", 1)), + )) + require.NoError(t, err) + + builder.SetGasLimit(200000) + builder.SetFeeAmount(sdk.NewCoins(sdk.NewInt64Coin("pmina", 1))) + builder.SetMemo("smart-account-verifier-test") + + extendedBuilder, ok := builder.(client.ExtendedTxBuilder) + require.True(t, ok) + extendedBuilder.SetExtensionOptions(mustSmartAccountExtensionAny(t, identity)) + + err = builder.SetSignatures(signingtypes.SignatureV2{ + PubKey: pubKey, + Data: &signingtypes.SingleSignatureData{ + SignMode: signingtypes.SignMode_SIGN_MODE_DIRECT, + Signature: signature, + }, + Sequence: sequence, + }) + require.NoError(t, err) + + return builder.GetTx() +} + +func newStubSmartAccountTx( + t *testing.T, + accountAddress, identity []byte, + pubKey cryptotypes.PubKey, + sequence uint64, +) stubSmartAccountTx { + t.Helper() + + return stubSmartAccountTx{ + stubAuthTx: stubAuthTx{ + signers: [][]byte{accountAddress}, + sigs: []signingtypes.SignatureV2{ + { + PubKey: pubKey, + Sequence: sequence, + Data: &signingtypes.SingleSignatureData{ + SignMode: signingtypes.SignMode_SIGN_MODE_DIRECT, + Signature: []byte{1}, + }, + }, + }, + }, + extensionOptions: []*codectypes.Any{ + mustSmartAccountExtensionAny(t, identity), + }, + } +} + +func TestSmartAccountVerifierAcceptsValidSignature(t *testing.T) { + t.Parallel() + + _, account := newVerifierAccount(t, 7, 11) + sessionPrivateKey := ed25519.GenPrivKey() + identity := bytes.Repeat([]byte{1}, smartaccountstypes.IdentitySize) + keeper := &recordingSmartAccountKeeper{authorized: true} + encoding := newVerifierEncodingConfig(t) + verifier := NewSmartAccountVerifier( + keeper, + verifierAccountKeeper{account: account}, + encoding.TxConfig.SignModeHandler(), + ) + ctx := newTestSDKContext(t).WithIsSigverifyTx(true) + + unsignedTx := buildSmartAccountVerifierTestTx( + t, + encoding.TxConfig, + account.GetAddress(), + sessionPrivateKey.PubKey(), + identity, + account.GetSequence(), + nil, + ) + signBytes := buildVerifierSignBytes( + t, + ctx, + encoding.TxConfig, + unsignedTx, + account, + account.GetSequence(), + signingtypes.SignMode_SIGN_MODE_DIRECT, + ) + signature, err := sessionPrivateKey.Sign(signBytes) + require.NoError(t, err) + + signedTx := buildSmartAccountVerifierTestTx( + t, + encoding.TxConfig, + account.GetAddress(), + sessionPrivateKey.PubKey(), + identity, + account.GetSequence(), + signature, + ) + + err = verifier.VerifySignatures(ctx, signedTx, false) + + require.NoError(t, err) + require.Equal(t, 1, keeper.calls) + require.Equal(t, identity, keeper.identity) + require.Equal(t, []byte(account.GetAddress()), keeper.accountAddress) + require.Equal(t, sessionPrivateKey.PubKey().Bytes(), keeper.publicKey) +} + +func TestAnteHandlerAcceptsSmartAccountTransaction(t *testing.T) { + t.Parallel() + + _, account := newVerifierAccount(t, 9, 12) + sessionPrivateKey := ed25519.GenPrivKey() + identity := bytes.Repeat([]byte{9}, smartaccountstypes.IdentitySize) + smartAccountKeeper := &recordingSmartAccountKeeper{authorized: true} + encoding := newVerifierEncodingConfig(t) + ctx := newTestSDKContext(t).WithIsSigverifyTx(true) + + unsignedTx := buildSmartAccountVerifierTestTx( + t, + encoding.TxConfig, + account.GetAddress(), + sessionPrivateKey.PubKey(), + identity, + account.GetSequence(), + nil, + ) + signBytes := buildVerifierSignBytes( + t, + ctx, + encoding.TxConfig, + unsignedTx, + account, + account.GetSequence(), + signingtypes.SignMode_SIGN_MODE_DIRECT, + ) + signature, err := sessionPrivateKey.Sign(signBytes) + require.NoError(t, err) + + signedTx := buildSmartAccountVerifierTestTx( + t, + encoding.TxConfig, + account.GetAddress(), + sessionPrivateKey.PubKey(), + identity, + account.GetSequence(), + signature, + ) + anteHandler, err := NewAnteHandler(HandlerOptions{ + AccountKeeper: verifierAccountKeeper{ + account: account, + moduleAddress: sdk.AccAddress([]byte("fee-collector-address")), + }, + BankKeeper: smartAccountVerifierBankKeeper{}, + SignModeHandler: encoding.TxConfig.SignModeHandler(), + SigGasConsumer: authante.DefaultSigVerificationGasConsumer, + KeyregistryKeeper: &keyregistrykeeper.Keeper{}, + SmartAccountKeeper: smartAccountKeeper, + MinaNetworkID: DefaultMinaNetworkID, + Logger: log.NewNopLogger(), + }) + require.NoError(t, err) + + _, err = anteHandler(ctx, signedTx, false) + + require.NoError(t, err) + require.Equal(t, 1, smartAccountKeeper.calls) + require.Equal(t, uint64(13), account.GetSequence()) +} + +func TestSmartAccountVerifierRejectsUnauthorizedSessionKey(t *testing.T) { + t.Parallel() + + _, account := newVerifierAccount(t, 1, 4) + sessionPrivateKey := ed25519.GenPrivKey() + identity := bytes.Repeat([]byte{2}, smartaccountstypes.IdentitySize) + keeper := &recordingSmartAccountKeeper{authorized: false} + verifier := NewSmartAccountVerifier( + keeper, + verifierAccountKeeper{account: account}, + &txsigning.HandlerMap{}, + ) + tx := newStubSmartAccountTx( + t, + account.GetAddress(), + identity, + sessionPrivateKey.PubKey(), + account.GetSequence(), + ) + + err := verifier.VerifySignatures(newTestSDKContext(t).WithIsSigverifyTx(true), tx, false) + + require.ErrorIs(t, err, sdkerrors.ErrUnauthorized) + require.Equal(t, 1, keeper.calls) +} + +func TestSmartAccountVerifierPropagatesKeeperError(t *testing.T) { + t.Parallel() + + _, account := newVerifierAccount(t, 1, 4) + sessionPrivateKey := ed25519.GenPrivKey() + identity := bytes.Repeat([]byte{3}, smartaccountstypes.IdentitySize) + expectedErr := errors.New("smart account state unavailable") + keeper := &recordingSmartAccountKeeper{err: expectedErr} + verifier := NewSmartAccountVerifier( + keeper, + verifierAccountKeeper{account: account}, + &txsigning.HandlerMap{}, + ) + tx := newStubSmartAccountTx( + t, + account.GetAddress(), + identity, + sessionPrivateKey.PubKey(), + account.GetSequence(), + ) + + err := verifier.VerifySignatures(newTestSDKContext(t).WithIsSigverifyTx(true), tx, false) + + require.ErrorIs(t, err, expectedErr) +} + +func TestSmartAccountVerifierRejectsWrongSequence(t *testing.T) { + t.Parallel() + + _, account := newVerifierAccount(t, 1, 4) + sessionPrivateKey := ed25519.GenPrivKey() + identity := bytes.Repeat([]byte{4}, smartaccountstypes.IdentitySize) + keeper := &recordingSmartAccountKeeper{authorized: true} + verifier := NewSmartAccountVerifier( + keeper, + verifierAccountKeeper{account: account}, + &txsigning.HandlerMap{}, + ) + tx := newStubSmartAccountTx( + t, + account.GetAddress(), + identity, + sessionPrivateKey.PubKey(), + account.GetSequence()+1, + ) + + err := verifier.VerifySignatures(newTestSDKContext(t).WithIsSigverifyTx(true), tx, false) + + require.ErrorIs(t, err, sdkerrors.ErrWrongSequence) +} + +func TestSmartAccountVerifierRejectsInvalidSignature(t *testing.T) { + t.Parallel() + + _, account := newVerifierAccount(t, 5, 8) + sessionPrivateKey := ed25519.GenPrivKey() + identity := bytes.Repeat([]byte{5}, smartaccountstypes.IdentitySize) + keeper := &recordingSmartAccountKeeper{authorized: true} + encoding := newVerifierEncodingConfig(t) + verifier := NewSmartAccountVerifier( + keeper, + verifierAccountKeeper{account: account}, + encoding.TxConfig.SignModeHandler(), + ) + tx := buildSmartAccountVerifierTestTx( + t, + encoding.TxConfig, + account.GetAddress(), + sessionPrivateKey.PubKey(), + identity, + account.GetSequence(), + make([]byte, ed25519.SignatureSize), + ) + + err := verifier.VerifySignatures(newTestSDKContext(t).WithIsSigverifyTx(true), tx, false) + + require.ErrorIs(t, err, sdkerrors.ErrUnauthorized) + require.ErrorContains(t, err, "signature verification failed") +} + +func TestSmartAccountVerifierSkipsCryptoVerificationDuringSimulation(t *testing.T) { + t.Parallel() + + _, account := newVerifierAccount(t, 1, 4) + identity := bytes.Repeat([]byte{6}, smartaccountstypes.IdentitySize) + keeper := &recordingSmartAccountKeeper{} + verifier := NewSmartAccountVerifier( + keeper, + verifierAccountKeeper{account: account}, + &txsigning.HandlerMap{}, + ) + tx := newStubSmartAccountTx( + t, + account.GetAddress(), + identity, + secp256k1.GenPrivKey().PubKey(), + account.GetSequence(), + ) + + err := verifier.VerifySignatures(newTestSDKContext(t).WithIsSigverifyTx(true), tx, true) + + require.NoError(t, err) + require.Zero(t, keeper.calls) +} + +func TestSmartAccountVerifierRejectsInvalidEnvelope(t *testing.T) { + t.Parallel() + + identity := bytes.Repeat([]byte{7}, smartaccountstypes.IdentitySize) + accountAddress := sdk.AccAddress([]byte("smart-account-signer")) + account := authtypes.NewBaseAccount(accountAddress, nil, 1, 4) + sessionPrivateKey := ed25519.GenPrivKey() + keeper := &recordingSmartAccountKeeper{authorized: true} + verifier := NewSmartAccountVerifier( + keeper, + verifierAccountKeeper{account: account}, + &txsigning.HandlerMap{}, + ) + + tests := []struct { + name string + tx sdk.Tx + want error + }{ + { + name: "invalid tx type", + tx: stubBasicTx{}, + want: sdkerrors.ErrTxDecode, + }, + { + name: "unordered tx", + tx: stubSmartAccountTx{stubAuthTx: stubAuthTx{ + unordered: true, + }}, + want: sdkerrors.ErrNotSupported, + }, + { + name: "missing signature", + tx: stubSmartAccountTx{ + stubAuthTx: stubAuthTx{signers: [][]byte{accountAddress}}, + }, + want: sdkerrors.ErrUnauthorized, + }, + { + name: "non ed25519 public key", + tx: newStubSmartAccountTx( + t, + accountAddress, + identity, + secp256k1.GenPrivKey().PubKey(), + account.GetSequence(), + ), + want: sdkerrors.ErrInvalidPubKey, + }, + { + name: "unsupported sign mode", + tx: stubSmartAccountTx{ + stubAuthTx: stubAuthTx{ + signers: [][]byte{accountAddress}, + sigs: []signingtypes.SignatureV2{ + { + PubKey: sessionPrivateKey.PubKey(), + Sequence: account.GetSequence(), + Data: &signingtypes.SingleSignatureData{ + SignMode: signingtypes.SignMode_SIGN_MODE_DIRECT_AUX, + }, + }, + }, + }, + extensionOptions: []*codectypes.Any{ + mustSmartAccountExtensionAny(t, identity), + }, + }, + want: sdkerrors.ErrNotSupported, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := verifier.VerifySignatures(newTestSDKContext(t).WithIsSigverifyTx(true), test.tx, false) + require.ErrorIs(t, err, test.want) + }) + } +} + +func TestSmartAccountIdentityFromTx(t *testing.T) { + t.Parallel() + + identity := bytes.Repeat([]byte{8}, smartaccountstypes.IdentitySize) + minaExtension := mustTxAuthModeExtensionAny(t, antetypes.TX_AUTH_MODE_MINA) + + tests := []struct { + name string + tx sdk.Tx + want []byte + wantErr error + }{ + { + name: "valid identity", + tx: stubSmartAccountTx{extensionOptions: []*codectypes.Any{ + mustSmartAccountExtensionAny(t, identity), + }}, + want: identity, + }, + { + name: "tx without extension support", + tx: stubAuthTx{}, + wantErr: sdkerrors.ErrInvalidRequest, + }, + { + name: "missing auth extension", + tx: stubSmartAccountTx{}, + wantErr: sdkerrors.ErrInvalidRequest, + }, + { + name: "wrong auth mode", + tx: stubSmartAccountTx{extensionOptions: []*codectypes.Any{ + minaExtension, + }}, + wantErr: sdkerrors.ErrInvalidRequest, + }, + { + name: "invalid identity length", + tx: stubSmartAccountTx{extensionOptions: []*codectypes.Any{ + mustSmartAccountExtensionAny(t, identity[:len(identity)-1]), + }}, + wantErr: sdkerrors.ErrInvalidRequest, + }, + { + name: "duplicate auth extension", + tx: stubSmartAccountTx{extensionOptions: []*codectypes.Any{ + mustSmartAccountExtensionAny(t, identity), + mustSmartAccountExtensionAny(t, identity), + }}, + wantErr: sdkerrors.ErrInvalidRequest, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + actual, err := smartAccountIdentityFromTx(test.tx) + if test.wantErr != nil { + require.ErrorIs(t, err, test.wantErr) + return + } + + require.NoError(t, err) + require.Equal(t, test.want, actual) + }) + } +} diff --git a/app/ante/test_helpers_test.go b/app/ante/test_helpers_test.go index 4c789408..38ebdd57 100644 --- a/app/ante/test_helpers_test.go +++ b/app/ante/test_helpers_test.go @@ -35,7 +35,7 @@ func (d *recordingDecorator) AnteHandle( return next(ctx, tx, simulate) } -// recordingVerifier tracks whether the Mina verification branch was invoked. +// recordingVerifier tracks whether a custom signature-verification branch was invoked. type recordingVerifier struct { calls int err error diff --git a/app/ante/tx_mode.go b/app/ante/tx_mode.go index f3e76744..ee1beab8 100644 --- a/app/ante/tx_mode.go +++ b/app/ante/tx_mode.go @@ -22,6 +22,7 @@ type TxAuthMode uint8 const ( TxAuthModeCosmos TxAuthMode = iota TxAuthModeMina + TxAuthModeSmartAccount ) // RegisterInterfaces registers ante extension interfaces. @@ -107,10 +108,13 @@ func ResolveTxAuthMode(tx sdk.Tx) (TxAuthMode, error) { } switch found.TxAuthMode { - case antetypes.TX_AUTH_MODE_COSMOS: + case antetypes.TX_AUTH_MODE_UNSPECIFIED, + antetypes.TX_AUTH_MODE_COSMOS: return TxAuthModeCosmos, nil case antetypes.TX_AUTH_MODE_MINA: return TxAuthModeMina, nil + case antetypes.TX_AUTH_MODE_SMART_ACCOUNT: + return TxAuthModeSmartAccount, nil default: return TxAuthModeCosmos, errorsmod.Wrapf( sdkerrors.ErrInvalidRequest, diff --git a/app/ante/tx_mode_test.go b/app/ante/tx_mode_test.go index 1c16d2b0..70a0fcf0 100644 --- a/app/ante/tx_mode_test.go +++ b/app/ante/tx_mode_test.go @@ -50,6 +50,35 @@ func TestResolveTxAuthModeDefaultsToCosmos(t *testing.T) { require.Equal(t, TxAuthModeCosmos, mode) } +func TestResolveTxAuthModeTreatsUnspecifiedAsCosmos(t *testing.T) { + t.Parallel() + + mode, err := ResolveTxAuthMode(stubExtensionTx{ + extensionOptions: []*codectypes.Any{ + mustTxAuthModeExtensionAny(t, antetypes.TX_AUTH_MODE_UNSPECIFIED), + }, + }) + + require.NoError(t, err) + require.Equal(t, TxAuthModeCosmos, mode) +} + +func TestResolveTxAuthModeReadsSmartAccountExtension(t *testing.T) { + t.Parallel() + + mode, err := ResolveTxAuthMode(stubExtensionTx{ + extensionOptions: []*codectypes.Any{ + mustTxAuthModeExtensionAny( + t, + antetypes.TX_AUTH_MODE_SMART_ACCOUNT, + ), + }, + }) + + require.NoError(t, err) + require.Equal(t, TxAuthModeSmartAccount, mode) +} + // A Mina extension must flip resolution into Mina mode. // This is the primary positive branch for custom auth-mode routing. func TestResolveTxAuthModeReadsMinaExtension(t *testing.T) { diff --git a/app/ante/types/tx_auth.pb.go b/app/ante/types/tx_auth.pb.go index 03c7af3b..ba12c805 100644 --- a/app/ante/types/tx_auth.pb.go +++ b/app/ante/types/tx_auth.pb.go @@ -33,18 +33,22 @@ const ( TX_AUTH_MODE_COSMOS TxAuthMode = 1 // TX_AUTH_MODE_MINA selects verification with the signer's registered Mina key. TX_AUTH_MODE_MINA TxAuthMode = 2 + // TX_AUTH_MODE_SMART_ACCOUNT selects verification with the registered Session key. + TX_AUTH_MODE_SMART_ACCOUNT TxAuthMode = 3 ) var TxAuthMode_name = map[int32]string{ 0: "TX_AUTH_MODE_UNSPECIFIED", 1: "TX_AUTH_MODE_COSMOS", 2: "TX_AUTH_MODE_MINA", + 3: "TX_AUTH_MODE_SMART_ACCOUNT", } var TxAuthMode_value = map[string]int32{ - "TX_AUTH_MODE_UNSPECIFIED": 0, - "TX_AUTH_MODE_COSMOS": 1, - "TX_AUTH_MODE_MINA": 2, + "TX_AUTH_MODE_UNSPECIFIED": 0, + "TX_AUTH_MODE_COSMOS": 1, + "TX_AUTH_MODE_MINA": 2, + "TX_AUTH_MODE_SMART_ACCOUNT": 3, } func (x TxAuthMode) String() string { @@ -57,7 +61,8 @@ func (TxAuthMode) EnumDescriptor() ([]byte, []int) { // TxAuthModeExtension marks the authentication mode of a transaction. type TxAuthModeExtension struct { - TxAuthMode TxAuthMode `protobuf:"varint,1,opt,name=tx_auth_mode,json=txAuthMode,proto3,enum=pulsarchain.ante.v1.TxAuthMode" json:"tx_auth_mode,omitempty"` + TxAuthMode TxAuthMode `protobuf:"varint,1,opt,name=tx_auth_mode,json=txAuthMode,proto3,enum=pulsarchain.ante.v1.TxAuthMode" json:"tx_auth_mode,omitempty"` + SmartAccountIdentity []byte `protobuf:"bytes,2,opt,name=smart_account_identity,json=smartAccountIdentity,proto3" json:"smart_account_identity,omitempty"` } func (m *TxAuthModeExtension) Reset() { *m = TxAuthModeExtension{} } @@ -101,25 +106,29 @@ func init() { func init() { proto.RegisterFile("pulsarchain/ante/v1/tx_auth.proto", fileDescriptor_5c6991cd595ed7d3) } var fileDescriptor_5c6991cd595ed7d3 = []byte{ - // 281 bytes of a gzipped FileDescriptorProto + // 346 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2c, 0x28, 0xcd, 0x29, 0x4e, 0x2c, 0x4a, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x4f, 0xcc, 0x2b, 0x49, 0xd5, 0x2f, 0x33, 0xd4, 0x2f, 0xa9, 0x88, 0x4f, 0x2c, 0x2d, 0xc9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x46, 0x52, 0xa2, 0x07, 0x52, 0xa2, 0x57, 0x66, 0x28, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x96, 0xd7, - 0x07, 0xb1, 0x20, 0x4a, 0x95, 0xe2, 0xb8, 0x84, 0x43, 0x2a, 0x1c, 0x4b, 0x4b, 0x32, 0x7c, 0xf3, - 0x53, 0x52, 0x5d, 0x2b, 0x4a, 0x52, 0xf3, 0x8a, 0x33, 0xf3, 0xf3, 0x84, 0x1c, 0xb9, 0x78, 0xa0, - 0x46, 0xc6, 0xe7, 0xe6, 0xa7, 0xa4, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x19, 0xc9, 0xeb, 0x61, - 0x31, 0x58, 0x0f, 0xa1, 0x3f, 0x88, 0xab, 0x04, 0xce, 0xb6, 0x62, 0xe9, 0x58, 0x20, 0xcf, 0xa0, - 0x95, 0xc0, 0xc5, 0x85, 0x90, 0x17, 0x92, 0xe1, 0x92, 0x08, 0x89, 0x88, 0x77, 0x0c, 0x0d, 0xf1, - 0x88, 0xf7, 0xf5, 0x77, 0x71, 0x8d, 0x0f, 0xf5, 0x0b, 0x0e, 0x70, 0x75, 0xf6, 0x74, 0xf3, 0x74, - 0x75, 0x11, 0x60, 0x10, 0x12, 0xe7, 0x12, 0x46, 0x91, 0x75, 0xf6, 0x0f, 0xf6, 0xf5, 0x0f, 0x16, - 0x60, 0x14, 0x12, 0xe5, 0x12, 0x44, 0x91, 0xf0, 0xf5, 0xf4, 0x73, 0x14, 0x60, 0x92, 0x62, 0xe9, - 0x58, 0x2c, 0xc7, 0xe0, 0xe4, 0x7d, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, - 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, - 0x86, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x79, 0xf9, 0x29, 0xa9, - 0x86, 0x06, 0x86, 0xba, 0x99, 0xf9, 0xfa, 0x10, 0x3f, 0xe8, 0x42, 0x03, 0xb0, 0xa0, 0x00, 0x12, - 0x88, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0xe0, 0x50, 0x31, 0x06, 0x04, 0x00, 0x00, 0xff, - 0xff, 0x15, 0x7c, 0x5e, 0x70, 0x65, 0x01, 0x00, 0x00, + 0x07, 0xb1, 0x20, 0x4a, 0x95, 0xa6, 0x30, 0x72, 0x09, 0x87, 0x54, 0x38, 0x96, 0x96, 0x64, 0xf8, + 0xe6, 0xa7, 0xa4, 0xba, 0x56, 0x94, 0xa4, 0xe6, 0x15, 0x67, 0xe6, 0xe7, 0x09, 0x39, 0x72, 0xf1, + 0x40, 0xcd, 0x8c, 0xcf, 0xcd, 0x4f, 0x49, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x33, 0x92, 0xd7, + 0xc3, 0x62, 0xb2, 0x1e, 0x42, 0x7f, 0x10, 0x57, 0x09, 0x9c, 0x2d, 0x64, 0xc2, 0x25, 0x56, 0x9c, + 0x9b, 0x58, 0x54, 0x12, 0x9f, 0x98, 0x9c, 0x9c, 0x5f, 0x9a, 0x57, 0x12, 0x9f, 0x99, 0x92, 0x9a, + 0x57, 0x92, 0x59, 0x52, 0x29, 0xc1, 0xa4, 0xc0, 0xa8, 0xc1, 0x13, 0x24, 0x02, 0x96, 0x75, 0x84, + 0x48, 0x7a, 0x42, 0xe5, 0xac, 0x58, 0x3a, 0x16, 0xc8, 0x33, 0x68, 0x35, 0x30, 0x72, 0x71, 0x21, + 0x8c, 0x15, 0x92, 0xe1, 0x92, 0x08, 0x89, 0x88, 0x77, 0x0c, 0x0d, 0xf1, 0x88, 0xf7, 0xf5, 0x77, + 0x71, 0x8d, 0x0f, 0xf5, 0x0b, 0x0e, 0x70, 0x75, 0xf6, 0x74, 0xf3, 0x74, 0x75, 0x11, 0x60, 0x10, + 0x12, 0xe7, 0x12, 0x46, 0x91, 0x75, 0xf6, 0x0f, 0xf6, 0xf5, 0x0f, 0x16, 0x60, 0x14, 0x12, 0xe5, + 0x12, 0x44, 0x91, 0xf0, 0xf5, 0xf4, 0x73, 0x14, 0x60, 0x12, 0x92, 0xe3, 0x92, 0x42, 0x11, 0x0e, + 0xf6, 0x75, 0x0c, 0x0a, 0x89, 0x77, 0x74, 0x76, 0xf6, 0x0f, 0xf5, 0x0b, 0x11, 0x60, 0x96, 0x62, + 0xe9, 0x58, 0x2c, 0xc7, 0xe0, 0xe4, 0x7d, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, + 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, + 0x51, 0x86, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x79, 0xf9, 0x29, + 0xa9, 0x86, 0x06, 0x86, 0xba, 0x99, 0xf9, 0xfa, 0x90, 0xa0, 0xd1, 0x85, 0x46, 0x4c, 0x41, 0x01, + 0x24, 0x72, 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0xa1, 0x6d, 0x0c, 0x08, 0x00, 0x00, + 0xff, 0xff, 0xee, 0x91, 0x21, 0x47, 0xbd, 0x01, 0x00, 0x00, } func (m *TxAuthModeExtension) Marshal() (dAtA []byte, err error) { @@ -142,6 +151,13 @@ func (m *TxAuthModeExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.SmartAccountIdentity) > 0 { + i -= len(m.SmartAccountIdentity) + copy(dAtA[i:], m.SmartAccountIdentity) + i = encodeVarintTxAuth(dAtA, i, uint64(len(m.SmartAccountIdentity))) + i-- + dAtA[i] = 0x12 + } if m.TxAuthMode != 0 { i = encodeVarintTxAuth(dAtA, i, uint64(m.TxAuthMode)) i-- @@ -170,6 +186,10 @@ func (m *TxAuthModeExtension) Size() (n int) { if m.TxAuthMode != 0 { n += 1 + sovTxAuth(uint64(m.TxAuthMode)) } + l = len(m.SmartAccountIdentity) + if l > 0 { + n += 1 + l + sovTxAuth(uint64(l)) + } return n } @@ -227,6 +247,40 @@ func (m *TxAuthModeExtension) Unmarshal(dAtA []byte) error { break } } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SmartAccountIdentity", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxAuth + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTxAuth + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTxAuth + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SmartAccountIdentity = append(m.SmartAccountIdentity[:0], dAtA[iNdEx:postIndex]...) + if m.SmartAccountIdentity == nil { + m.SmartAccountIdentity = []byte{} + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTxAuth(dAtA[iNdEx:]) diff --git a/app/app.go b/app/app.go index c2cae036..465e189c 100644 --- a/app/app.go +++ b/app/app.go @@ -58,6 +58,7 @@ import ( "github.com/node101-io/pulsar-chain/docs" bridge "github.com/node101-io/pulsar-chain/x/bridge/keeper" keyregistrymodulekeeper "github.com/node101-io/pulsar-chain/x/keyregistry/keeper" + smartaccountsmodulekeeper "github.com/node101-io/pulsar-chain/x/smartaccounts/keeper" verificationmodulekeeper "github.com/node101-io/pulsar-chain/x/verification/keeper" verificationsidecar "github.com/node101-io/pulsar-chain/x/verification/sidecar" votepersistencemodulekeeper "github.com/node101-io/pulsar-chain/x/votepersistence/keeper" @@ -127,6 +128,7 @@ type App struct { // VerificationSidecarClient is non-nil only when the app created the gRPC // client itself; retaining it here gives App.Close lifecycle ownership. VerificationSidecarClient *verificationsidecar.Client + SmartaccountsKeeper smartaccountsmodulekeeper.Keeper } // RegisterGRPCServerWithSkipCheckHeader registers application and standard health services. @@ -218,6 +220,7 @@ func New( &app.BridgeKeeper, &app.VerificationKeeper, &app.BridgeArchiveWrapperClient, + &app.SmartaccountsKeeper, ); err != nil { panic(err) } @@ -291,14 +294,15 @@ func New( baseapp.SetOptimisticExecution(), func(bApp *baseapp.BaseApp) { anteHandler, err := appante.NewAnteHandler(appante.HandlerOptions{ - AccountKeeper: app.AuthKeeper, - BankKeeper: app.BankKeeper, - FeegrantKeeper: app.FeeGrantKeeper, - SignModeHandler: app.txConfig.SignModeHandler(), - SigGasConsumer: authante.DefaultSigVerificationGasConsumer, - KeyregistryKeeper: &app.KeyregistryKeeper, - MinaNetworkID: string(minaNetworkID), - Logger: logger, + AccountKeeper: app.AuthKeeper, + BankKeeper: app.BankKeeper, + FeegrantKeeper: app.FeeGrantKeeper, + SignModeHandler: app.txConfig.SignModeHandler(), + SigGasConsumer: authante.DefaultSigVerificationGasConsumer, + KeyregistryKeeper: &app.KeyregistryKeeper, + SmartAccountKeeper: &app.SmartaccountsKeeper, + MinaNetworkID: string(minaNetworkID), + Logger: logger, }) if err != nil { panic(err) diff --git a/app/app_config.go b/app/app_config.go index 406d70a6..1c1fbd29 100644 --- a/app/app_config.go +++ b/app/app_config.go @@ -7,6 +7,8 @@ import ( bridgemoduletypes "github.com/node101-io/pulsar-chain/x/bridge/types" _ "github.com/node101-io/pulsar-chain/x/keyregistry/module" keyregistrymoduletypes "github.com/node101-io/pulsar-chain/x/keyregistry/types" + _ "github.com/node101-io/pulsar-chain/x/smartaccounts/module" + smartaccountsmoduletypes "github.com/node101-io/pulsar-chain/x/smartaccounts/types" _ "github.com/node101-io/pulsar-chain/x/verification/module" verificationmoduletypes "github.com/node101-io/pulsar-chain/x/verification/types" _ "github.com/node101-io/pulsar-chain/x/votepersistence/module" @@ -136,7 +138,7 @@ var ( // chain modules keyregistrymoduletypes.ModuleName, votepersistencemoduletypes.ModuleName, - }, + smartaccountsmoduletypes.ModuleName}, EndBlockers: []string{ govtypes.ModuleName, stakingtypes.ModuleName, @@ -147,7 +149,7 @@ var ( votepersistencemoduletypes.ModuleName, verificationmoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/endBlockers - }, + smartaccountsmoduletypes.ModuleName}, // The following is mostly only needed when ModuleName != StoreKey name. OverrideStoreKeys: []*runtimev1alpha1.StoreKeyConfig{ { @@ -188,7 +190,7 @@ var ( bridgemoduletypes.ModuleName, verificationmoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/initGenesis - }, + smartaccountsmoduletypes.ModuleName}, }), }, { @@ -300,6 +302,9 @@ var ( Config: appconfig.WrapAny(&verificationmoduletypes.Module{}), }, // this line is used by starport scaffolding # stargate/app/moduleConfig - }, + { + Name: smartaccountsmoduletypes.ModuleName, + Config: appconfig.WrapAny(&smartaccountsmoduletypes.Module{}), + }}, }) ) diff --git a/app/export_test.go b/app/export_test.go index 17f9f208..d1bfd36d 100644 --- a/app/export_test.go +++ b/app/export_test.go @@ -1,6 +1,7 @@ package app import ( + "bytes" "encoding/base64" "net" "testing" @@ -22,6 +23,7 @@ import ( minafield "github.com/node101-io/mina-signer-go/field" merkle "github.com/node101-io/mina-signer-go/merklelist" bridgetypes "github.com/node101-io/pulsar-chain/x/bridge/types" + smartaccountstypes "github.com/node101-io/pulsar-chain/x/smartaccounts/types" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/health" @@ -199,6 +201,14 @@ func TestZeroHeightExportNormalizesBridgeRootSnapshots(t *testing.T) { ) genesisState[bridgetypes.ModuleName] = oldApp.AppCodec().MustMarshalJSON(bridgeGenesis) + smartaccountsGenesis := &smartaccountstypes.GenesisState{ + Params: smartaccountstypes.Params{ + VerificationKeyHash: bytes.Repeat([]byte{0x01}, smartaccountstypes.VerificationKeyHashSize), + }, + } + + genesisState[smartaccountstypes.ModuleName] = oldApp.AppCodec().MustMarshalJSON(smartaccountsGenesis) + appState, err := cmtjson.Marshal(genesisState) require.NoError(t, err) _, err = oldApp.InitChain(&abci.RequestInitChain{ diff --git a/buf.lock b/buf.lock index fed6880d..a47d8a3d 100644 --- a/buf.lock +++ b/buf.lock @@ -20,5 +20,5 @@ deps: commit: c17df5b2beca46928cc87d5656bd5343 digest: b5:648a01e0170d4512dea7d564016165decd1ed6e34bef79fe54753e51ad7e27545709ad9157d7551270147d551155c595a2fb0bf5bb33b1c83040ddbce915c604 - name: buf.build/protocolbuffers/wellknowntypes - commit: 122a3d2fdc814e0bb6fcf821bcce7957 - digest: b5:1aafdaf51329062dcc57ee613e59e15e5529e994634599ff467501e4d6c670af04eaa4bee3f3da5db64518b3117c34865896eb9b096a15a81051ab82c34e7e95 + commit: f1151727eddb493abf82a1d919dc35e4 + digest: b5:e05c29a4347e1ef07cb978e9ece8a44c59c8cb6ff31884cd632f88266f81baaba7a67bcfc6ac52d8caada7f77faf2d37683af0d69755ef52d9f1288cd1fd5d93 diff --git a/config.yml b/config.yml index ec514aaf..6680b2bd 100644 --- a/config.yml +++ b/config.yml @@ -65,6 +65,9 @@ genesis: start_block_height: "541000" max_block_range: "1000" actions_reduced_root_snapshot_window_size: "4" + smartaccounts: + params: + verification_key_hash: "H+tIy6mnSrzGY5zHnUncjoHtn055HDcb32paoEspbus=" consensus: params: abci: diff --git a/docs/static/openapi.json b/docs/static/openapi.json index 2a4b8c7c..8d648ce5 100644 --- a/docs/static/openapi.json +++ b/docs/static/openapi.json @@ -1 +1 @@ -{"id":"github.com/node101-io/pulsar-chain","consumes":["application/json"],"produces":["application/json"],"swagger":"2.0","info":{"description":"Chain github.com/node101-io/pulsar-chain REST API","title":"HTTP API Console","contact":{"name":"github.com/node101-io/pulsar-chain"},"version":"version not set"},"paths":{"/node101-io/pulsar-chain/abci/v1/validator_set_with_powers/{block_height}":{"get":{"tags":["Query"],"operationId":"GithubComnode101IopulsarChainQuery_GetValidatorSetWithPowers","parameters":[{"type":"string","format":"int64","name":"block_height","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.abci.QueryGetValidatorSetWithPowersResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/abci/v1/vote_ext_body_by_height/{vote_extension_height}":{"get":{"tags":["Query"],"summary":"VoteExtBodyByHeight queries the vote extension body for a vote-extension\nconsensus height.","operationId":"GithubComnode101IopulsarChainQuery_VoteExtBodyByHeight","parameters":[{"type":"string","format":"int64","description":"vote_extension_height is the consensus height N where the vote extension is\nproduced. The returned body signs the transition from state N-2 to state N-1.","name":"vote_extension_height","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.abci.QueryVoteExtBodyByHeightResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/bridge/v1/actions_reduced_root":{"get":{"tags":["Query"],"summary":"ActionsReducedRoot Queries a list of ActionsReducedRoot items.","operationId":"GithubComnode101IopulsarChainQuery_ActionsReducedRoot","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.bridge.v1.QueryActionsReducedRootResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/bridge/v1/latest_action_hashes":{"get":{"tags":["Query"],"summary":"LatestActionHashes Queries a list of LatestActionHashes items.","operationId":"GithubComnode101IopulsarChainQuery_LatestActionHashes","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.bridge.v1.QueryLatestActionHashesResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/bridge/v1/params":{"get":{"tags":["Query"],"summary":"Parameters queries the parameters of the module.","operationId":"GithubComnode101IopulsarChainQuery_Params","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.bridge.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_user_cosmos_public_key/{user_mina_public_key}":{"get":{"tags":["Query"],"summary":"GetUserCosmosPublicKey Queries a list of GetUserCosmosPublicKey items.","operationId":"GithubComnode101IopulsarChainQuery_GetUserCosmosPublicKey","parameters":[{"type":"string","format":"byte","name":"user_mina_public_key","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetUserCosmosPublicKeyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_user_mina_public_key/{user_cosmos_public_key}":{"get":{"tags":["Query"],"summary":"GetUserMinaPublicKey Queries a list of GetUserMinaPublicKey items.","operationId":"GithubComnode101IopulsarChainQuery_GetUserMinaPublicKey","parameters":[{"type":"string","format":"byte","name":"user_cosmos_public_key","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetUserMinaPublicKeyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_validator_cosmos_pub_key/{validator_mina_pub_key}":{"get":{"tags":["Query"],"summary":"GetValidatorCosmosPubKey Queries a list of GetValidatorCosmosPubKey items.","operationId":"GithubComnode101IopulsarChainQuery_GetValidatorCosmosPubKey","parameters":[{"type":"string","format":"byte","name":"validator_mina_pub_key","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetValidatorCosmosPubKeyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_validator_mina_pub_key/{validator_cosmos_pub_key}":{"get":{"tags":["Query"],"summary":"GetValidatorMinaPubKey Queries a list of GetValidatorMinaPubKey items.","operationId":"GithubComnode101IopulsarChainQuery_GetValidatorMinaPubKey","parameters":[{"type":"string","format":"byte","name":"validator_cosmos_pub_key","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetValidatorMinaPubKeyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_validator_set_with_mina_keys":{"get":{"tags":["Query"],"summary":"GetValidatorSetWithMinaKeys returns the supplied validator set with each validator's registered Mina public key.","operationId":"GithubComnode101IopulsarChainQuery_GetValidatorSetWithMinaKeys","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetValidatorSetWithMinaKeysResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/key_signing_challenge":{"get":{"tags":["Query"],"summary":"GetKeySigningChallenge returns the state-bound field a Mina wallet must sign.","operationId":"GithubComnode101IopulsarChainQuery_GetKeySigningChallenge","parameters":[{"enum":["KEY_SIGNING_OPERATION_UNSPECIFIED","KEY_SIGNING_OPERATION_REGISTER","KEY_SIGNING_OPERATION_UPDATE"],"type":"string","default":"KEY_SIGNING_OPERATION_UNSPECIFIED","description":" - KEY_SIGNING_OPERATION_UNSPECIFIED: KEY_SIGNING_OPERATION_UNSPECIFIED is invalid for signing requests.\n - KEY_SIGNING_OPERATION_REGISTER: KEY_SIGNING_OPERATION_REGISTER creates the first stable-key association.\n - KEY_SIGNING_OPERATION_UPDATE: KEY_SIGNING_OPERATION_UPDATE replaces an existing Mina key.","name":"operation","in":"query"},{"enum":["ACTOR_TYPE_UNSPECIFIED","ACTOR_TYPE_USER","ACTOR_TYPE_VALIDATOR"],"type":"string","default":"ACTOR_TYPE_UNSPECIFIED","description":" - ACTOR_TYPE_UNSPECIFIED: ACTOR_TYPE_UNSPECIFIED is invalid for key-registry operations.\n - ACTOR_TYPE_USER: ACTOR_TYPE_USER identifies a user account key association.\n - ACTOR_TYPE_VALIDATOR: ACTOR_TYPE_VALIDATOR identifies a validator consensus key association.","name":"actor_type","in":"query"},{"type":"string","format":"byte","name":"cosmos_public_key","in":"query"},{"type":"string","format":"byte","name":"new_mina_public_key","in":"query"}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetKeySigningChallengeResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/params":{"get":{"tags":["Query"],"summary":"Parameters queries the parameters of the module.","operationId":"GithubComnode101IopulsarChainQuery_ParamsMixin17","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/commitments/{validator}":{"get":{"tags":["Query"],"summary":"CommitmentsByValidator lists retained commitments for a validator.","operationId":"GithubComnode101IopulsarChainQuery_CommitmentsByValidator","parameters":[{"type":"string","name":"validator","in":"path","required":true},{"type":"string","format":"byte","description":"key is a value returned in PageResponse.next_key to begin\nquerying the next page most efficiently. Only one of offset or key\nshould be set.","name":"pagination.key","in":"query"},{"type":"string","format":"uint64","description":"offset is a numeric offset that can be used when key is unavailable.\nIt is less efficient than using key. Only one of offset or key should\nbe set.","name":"pagination.offset","in":"query"},{"type":"string","format":"uint64","description":"limit is the total number of results to be returned in the result page.\nIf left empty it will default to a value to be set by each app.","name":"pagination.limit","in":"query"},{"type":"boolean","description":"count_total is set to true to indicate that the result set should include\na count of the total number of items available for pagination in UIs.\ncount_total is only respected when offset is used. It is ignored when key\nis set.","name":"pagination.count_total","in":"query"},{"type":"boolean","description":"reverse is set to true if results are to be returned in the descending order.","name":"pagination.reverse","in":"query"}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryCommitmentsByValidatorResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/commitments/{validator}/{commitment_height}":{"get":{"tags":["Query"],"summary":"Commitment returns one retained validator commitment.","operationId":"GithubComnode101IopulsarChainQuery_Commitment","parameters":[{"type":"string","name":"validator","in":"path","required":true},{"type":"string","format":"uint64","name":"commitment_height","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryCommitmentResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/params":{"get":{"tags":["Query"],"summary":"Params returns module parameters.","operationId":"GithubComnode101IopulsarChainQuery_ParamsMixin22","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/proofs/height/{submission_height}":{"get":{"tags":["Query"],"summary":"ProofsByHeight lists proofs submitted at a height.","operationId":"GithubComnode101IopulsarChainQuery_ProofsByHeight","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"string","format":"byte","description":"key is a value returned in PageResponse.next_key to begin\nquerying the next page most efficiently. Only one of offset or key\nshould be set.","name":"pagination.key","in":"query"},{"type":"string","format":"uint64","description":"offset is a numeric offset that can be used when key is unavailable.\nIt is less efficient than using key. Only one of offset or key should\nbe set.","name":"pagination.offset","in":"query"},{"type":"string","format":"uint64","description":"limit is the total number of results to be returned in the result page.\nIf left empty it will default to a value to be set by each app.","name":"pagination.limit","in":"query"},{"type":"boolean","description":"count_total is set to true to indicate that the result set should include\na count of the total number of items available for pagination in UIs.\ncount_total is only respected when offset is used. It is ignored when key\nis set.","name":"pagination.count_total","in":"query"},{"type":"boolean","description":"reverse is set to true if results are to be returned in the descending order.","name":"pagination.reverse","in":"query"}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryProofsByHeightResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/proofs/verification-id/{verification_id}":{"get":{"tags":["Query"],"summary":"ProofByVerificationId resolves the permanent verification request registry.","operationId":"GithubComnode101IopulsarChainQuery_ProofByVerificationId","parameters":[{"type":"string","format":"byte","name":"verification_id","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryProofResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/proofs/{submission_height}/{index_in_block}":{"get":{"tags":["Query"],"summary":"Proof returns a pending or finalized proof by key.","operationId":"GithubComnode101IopulsarChainQuery_Proof","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryProofResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/results/{submission_height}/{index_in_block}":{"get":{"tags":["Query"],"summary":"FinalProofResult returns an immutable finalized result.","operationId":"GithubComnode101IopulsarChainQuery_FinalProofResult","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryFinalProofResultResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/tallies/{submission_height}/{index_in_block}":{"get":{"tags":["Query"],"summary":"ProofTally returns the active tally for a pending proof.","operationId":"GithubComnode101IopulsarChainQuery_ProofTally","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryProofTallyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/votes/{submission_height}/{index_in_block}":{"get":{"tags":["Query"],"summary":"VerificationVotes lists effective votes for a proof.","operationId":"GithubComnode101IopulsarChainQuery_VerificationVotes","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true},{"type":"string","format":"byte","description":"key is a value returned in PageResponse.next_key to begin\nquerying the next page most efficiently. Only one of offset or key\nshould be set.","name":"pagination.key","in":"query"},{"type":"string","format":"uint64","description":"offset is a numeric offset that can be used when key is unavailable.\nIt is less efficient than using key. Only one of offset or key should\nbe set.","name":"pagination.offset","in":"query"},{"type":"string","format":"uint64","description":"limit is the total number of results to be returned in the result page.\nIf left empty it will default to a value to be set by each app.","name":"pagination.limit","in":"query"},{"type":"boolean","description":"count_total is set to true to indicate that the result set should include\na count of the total number of items available for pagination in UIs.\ncount_total is only respected when offset is used. It is ignored when key\nis set.","name":"pagination.count_total","in":"query"},{"type":"boolean","description":"reverse is set to true if results are to be returned in the descending order.","name":"pagination.reverse","in":"query"}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryVerificationVotesResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/votes/{submission_height}/{index_in_block}/{validator}":{"get":{"tags":["Query"],"summary":"Vote returns one validator's effective vote for a proof.","operationId":"GithubComnode101IopulsarChainQuery_Vote","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true},{"type":"string","name":"validator","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryVoteResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/votepersistence/v1/params":{"get":{"tags":["Query"],"summary":"Parameters queries the parameters of the module.","operationId":"GithubComnode101IopulsarChainQuery_ParamsMixin28","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.votepersistence.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/votepersistence/v1/vote_extensions":{"get":{"tags":["Query"],"summary":"VoteExtensions queries the currently persisted vote extensions.","operationId":"GithubComnode101IopulsarChainQuery_VoteExtensions","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.votepersistence.v1.QueryVoteExtensionsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}}},"definitions":{"cosmos.base.query.v1beta1.PageRequest":{"description":"message SomeRequest {\n Foo some_parameter = 1;\n PageRequest pagination = 2;\n }","type":"object","title":"PageRequest is to be embedded in gRPC request messages for efficient\npagination. Ex:","properties":{"count_total":{"description":"count_total is set to true to indicate that the result set should include\na count of the total number of items available for pagination in UIs.\ncount_total is only respected when offset is used. It is ignored when key\nis set.","type":"boolean"},"key":{"description":"key is a value returned in PageResponse.next_key to begin\nquerying the next page most efficiently. Only one of offset or key\nshould be set.","type":"string","format":"byte"},"limit":{"description":"limit is the total number of results to be returned in the result page.\nIf left empty it will default to a value to be set by each app.","type":"string","format":"uint64"},"offset":{"description":"offset is a numeric offset that can be used when key is unavailable.\nIt is less efficient than using key. Only one of offset or key should\nbe set.","type":"string","format":"uint64"},"reverse":{"description":"reverse is set to true if results are to be returned in the descending order.","type":"boolean"}}},"cosmos.base.query.v1beta1.PageResponse":{"description":"PageResponse is to be embedded in gRPC response messages where the\ncorresponding request message has used PageRequest.\n\n message SomeResponse {\n repeated Bar results = 1;\n PageResponse page = 2;\n }","type":"object","properties":{"next_key":{"description":"next_key is the key to be passed to PageRequest.key to\nquery the next page most efficiently. It will be empty if\nthere are no more results.","type":"string","format":"byte"},"total":{"type":"string","format":"uint64","title":"total is total number of results available if PageRequest.count_total\nwas set, its value is undefined otherwise"}}},"google.protobuf.Any":{"type":"object","properties":{"@type":{"type":"string"}},"additionalProperties":{}},"google.rpc.Status":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"details":{"type":"array","items":{"type":"object","$ref":"#/definitions/google.protobuf.Any"}},"message":{"type":"string"}}},"pulsarchain.abci.QueryGetValidatorSetWithPowersResponse":{"type":"object","properties":{"validators":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.common.ValidatorEntry"}}}},"pulsarchain.abci.QueryVoteExtBodyByHeightResponse":{"description":"QueryVoteExtBodyByHeightResponse defines the response for VoteExtBodyByHeight.","type":"object","properties":{"vote_ext_body":{"$ref":"#/definitions/pulsarchain.votepersistence.v1.VoteExtBody"}}},"pulsarchain.bridge.v1.Params":{"description":"Params defines the parameters for the module.","type":"object","properties":{"actions_reduced_root_snapshot_window_size":{"description":"actions_reduced_root_snapshot_window_size is the retained consensus root window.","type":"string","format":"int64"},"confirmation_depth":{"description":"confirmation_depth is the Mina finality depth used by the archive wrapper.","type":"string","format":"int64"},"contract_address":{"description":"contract_address is the Mina bridge contract address.","type":"string"},"max_block_range":{"description":"max_block_range is the maximum Mina height span processed by one request.","type":"string","format":"int64"},"start_block_height":{"description":"start_block_height is the first Mina block indexed by the bridge.","type":"string","format":"int64"}}},"pulsarchain.bridge.v1.QueryActionsReducedRootResponse":{"description":"QueryActionsReducedRootResponse defines the QueryActionsReducedRootResponse message.","type":"object","properties":{"actions_reduced_root":{"type":"string"}}},"pulsarchain.bridge.v1.QueryLatestActionHashesResponse":{"description":"QueryLatestActionHashesResponse defines the QueryLatestActionHashesResponse message.","type":"object","properties":{"action_hashes":{"description":"action_hashes is the ordered canonical hash batch that reconstructs\nthe root transition for the source Cosmos block.","type":"array","items":{"type":"string"}},"action_hashes_cosmos_block_height":{"description":"action_hashes_cosmos_block_height is the Cosmos block height where\nthis query batch was produced.","type":"string","format":"int64"},"latest_fetched_mina_height":{"description":"latest_fetched_mina_height is the inclusive upper Mina cursor of the\ncurrent batch. Together with start_mina_height it defines the consumed\nMina interval (start_mina_height, latest_fetched_mina_height].","type":"string","format":"int64"},"start_mina_height":{"description":"start_mina_height is the exclusive lower Mina cursor of the current batch.","type":"string","format":"int64"}}},"pulsarchain.bridge.v1.QueryParamsResponse":{"description":"QueryParamsResponse is response type for the Query/Params RPC method.","type":"object","properties":{"params":{"description":"params holds all the parameters of this module.","$ref":"#/definitions/pulsarchain.bridge.v1.Params"}}},"pulsarchain.common.ValidatorEntry":{"type":"object","properties":{"consensus_power":{"type":"string","format":"int64"},"validator_cosmos_pub_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.ActorType":{"description":"ActorType identifies the key-registry actor authorized by a signing challenge.\n\n - ACTOR_TYPE_UNSPECIFIED: ACTOR_TYPE_UNSPECIFIED is invalid for key-registry operations.\n - ACTOR_TYPE_USER: ACTOR_TYPE_USER identifies a user account key association.\n - ACTOR_TYPE_VALIDATOR: ACTOR_TYPE_VALIDATOR identifies a validator consensus key association.","type":"string","default":"ACTOR_TYPE_UNSPECIFIED","enum":["ACTOR_TYPE_UNSPECIFIED","ACTOR_TYPE_USER","ACTOR_TYPE_VALIDATOR"]},"pulsarchain.keyregistry.v1.KeySigningOperation":{"description":"KeySigningOperation identifies the key-registry state transition authorized\nby a wallet field signature.\n\n - KEY_SIGNING_OPERATION_UNSPECIFIED: KEY_SIGNING_OPERATION_UNSPECIFIED is invalid for signing requests.\n - KEY_SIGNING_OPERATION_REGISTER: KEY_SIGNING_OPERATION_REGISTER creates the first stable-key association.\n - KEY_SIGNING_OPERATION_UPDATE: KEY_SIGNING_OPERATION_UPDATE replaces an existing Mina key.","type":"string","default":"KEY_SIGNING_OPERATION_UNSPECIFIED","enum":["KEY_SIGNING_OPERATION_UNSPECIFIED","KEY_SIGNING_OPERATION_REGISTER","KEY_SIGNING_OPERATION_UPDATE"]},"pulsarchain.keyregistry.v1.Params":{"description":"Params defines the parameters for the module.","type":"object"},"pulsarchain.keyregistry.v1.QueryGetKeySigningChallengeResponse":{"description":"QueryGetKeySigningChallengeResponse contains the exact field and state version to sign.","type":"object","properties":{"challenge":{"type":"string"},"challenge_bytes":{"type":"string","format":"byte"},"new_key_version":{"type":"string","format":"uint64"},"previous_mina_public_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetUserCosmosPublicKeyResponse":{"description":"QueryGetUserCosmosPublicKeyResponse defines the QueryGetUserCosmosPublicKeyResponse message.","type":"object","properties":{"user_cosmos_public_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetUserMinaPublicKeyResponse":{"description":"QueryGetUserMinaPublicKeyResponse defines the QueryGetUserMinaPublicKeyResponse message.","type":"object","properties":{"user_mina_public_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetValidatorCosmosPubKeyResponse":{"description":"QueryGetValidatorCosmosPubKeyResponse defines the QueryGetValidatorCosmosPubKeyResponse message.","type":"object","properties":{"validator_cosmos_pub_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetValidatorMinaPubKeyResponse":{"description":"QueryGetValidatorMinaPubKeyResponse defines the QueryGetValidatorMinaPubKeyResponse message.","type":"object","properties":{"validator_mina_pub_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetValidatorSetWithMinaKeysResponse":{"description":"QueryGetValidatorSetWithMinaKeysResponse defines the response for GetValidatorSetWithMinaKeys.","type":"object","properties":{"registered_validators":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.keyregistry.v1.RegisteredValidatorSetEntry"}}}},"pulsarchain.keyregistry.v1.QueryParamsResponse":{"description":"QueryParamsResponse is response type for the Query/Params RPC method.","type":"object","properties":{"params":{"description":"params holds all the parameters of this module.","$ref":"#/definitions/pulsarchain.keyregistry.v1.Params"}}},"pulsarchain.keyregistry.v1.RegisteredValidatorSetEntry":{"type":"object","properties":{"consensus_power":{"type":"string","format":"int64"},"validator_cosmos_pub_key":{"type":"string","format":"byte"},"validator_mina_pub_key":{"type":"string","format":"byte"}}},"pulsarchain.verification.v1.CommitmentEntry":{"description":"CommitmentEntry is a query representation of a retained commitment.","type":"object","properties":{"commitment":{"$ref":"#/definitions/pulsarchain.verification.v1.CommitmentRecord"},"commitment_height":{"type":"string","format":"uint64"},"validator":{"type":"string"}}},"pulsarchain.verification.v1.CommitmentRecord":{"description":"CommitmentRecord stores a validator commitment root.","type":"object","properties":{"commitment":{"type":"string","format":"byte"}}},"pulsarchain.verification.v1.FinalProofResult":{"description":"FinalProofResult stores an immutable finalized proof outcome.","type":"object","properties":{"finalized_height":{"type":"string","format":"uint64"},"invalid_voting_power":{"type":"string","format":"int64"},"proof_hash":{"type":"string","format":"byte"},"proof_type":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofType"},"public_inputs_hash":{"type":"string","format":"byte"},"status":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofStatus"},"submission_height":{"type":"string","format":"uint64"},"total_voting_power":{"type":"string","format":"int64"},"valid_voting_power":{"type":"string","format":"int64"},"verification_id":{"type":"string","format":"byte"},"verification_key_hash":{"type":"string","format":"byte"},"voting_power_threshold":{"type":"string","format":"int64"}}},"pulsarchain.verification.v1.Params":{"description":"Params defines the governance-controlled verification module parameters.","type":"object","properties":{"max_proofs_per_block":{"type":"integer","format":"int64"}}},"pulsarchain.verification.v1.ProofKey":{"description":"ProofKey identifies a proof by absolute block height and in-block index.","type":"object","properties":{"index_in_block":{"type":"integer","format":"int64"},"submission_height":{"type":"string","format":"uint64"}}},"pulsarchain.verification.v1.ProofRecord":{"description":"ProofRecord stores the complete descriptor and its chain-derived identity.","type":"object","properties":{"proof_hash":{"type":"string","format":"byte"},"proof_type":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofType"},"public_inputs_hash":{"type":"string","format":"byte"},"verification_id":{"type":"string","format":"byte"},"verification_key_hash":{"type":"string","format":"byte"}}},"pulsarchain.verification.v1.ProofStatus":{"description":"ProofStatus is the finalized verification outcome.\n\n - PROOF_STATUS_PENDING: PROOF_STATUS_PENDING is the non-finalized status.\n - PROOF_STATUS_VALID: PROOF_STATUS_VALID means valid voting power exceeded two thirds.\n - PROOF_STATUS_INVALID: PROOF_STATUS_INVALID means invalid voting power exceeded two thirds.\n - PROOF_STATUS_INCONCLUSIVE: PROOF_STATUS_INCONCLUSIVE means neither side reached threshold.","type":"string","default":"PROOF_STATUS_PENDING","enum":["PROOF_STATUS_PENDING","PROOF_STATUS_VALID","PROOF_STATUS_INVALID","PROOF_STATUS_INCONCLUSIVE"]},"pulsarchain.verification.v1.ProofTally":{"description":"ProofTally stores the historical consensus power behind effective votes.","type":"object","properties":{"invalid_voting_power":{"type":"string","format":"int64"},"valid_voting_power":{"type":"string","format":"int64"}}},"pulsarchain.verification.v1.ProofType":{"description":"ProofType selects the verifier family. The exact statement and circuit are\nbound separately by the public-input and verification-key hashes.\n\n - PROOF_TYPE_UNSPECIFIED: PROOF_TYPE_UNSPECIFIED is invalid for proof submission.\n - PROOF_TYPE_MINA_PICKLES: PROOF_TYPE_MINA_PICKLES selects Mina's Pickles proof system.\n - PROOF_TYPE_NOIR_BARRETENBERG: PROOF_TYPE_NOIR_BARRETENBERG selects Noir proofs using Barretenberg.","type":"string","default":"PROOF_TYPE_UNSPECIFIED","enum":["PROOF_TYPE_UNSPECIFIED","PROOF_TYPE_MINA_PICKLES","PROOF_TYPE_NOIR_BARRETENBERG"]},"pulsarchain.verification.v1.QueryCommitmentResponse":{"description":"QueryCommitmentResponse contains one retained commitment.","type":"object","properties":{"commitment":{"$ref":"#/definitions/pulsarchain.verification.v1.CommitmentEntry"}}},"pulsarchain.verification.v1.QueryCommitmentsByValidatorResponse":{"description":"QueryCommitmentsByValidatorResponse contains retained commitments.","type":"object","properties":{"commitments":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.verification.v1.CommitmentEntry"}},"pagination":{"$ref":"#/definitions/cosmos.base.query.v1beta1.PageResponse"}}},"pulsarchain.verification.v1.QueryFinalProofResultResponse":{"description":"QueryFinalProofResultResponse contains an immutable proof result.","type":"object","properties":{"final_result":{"$ref":"#/definitions/pulsarchain.verification.v1.FinalProofResult"},"proof_key":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofKey"}}},"pulsarchain.verification.v1.QueryParamsResponse":{"description":"QueryParamsResponse contains verification parameters.","type":"object","properties":{"params":{"$ref":"#/definitions/pulsarchain.verification.v1.Params"}}},"pulsarchain.verification.v1.QueryProofResponse":{"description":"QueryProofResponse contains either pending or finalized proof state.","type":"object","properties":{"final_result":{"$ref":"#/definitions/pulsarchain.verification.v1.FinalProofResult"},"pending":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofRecord"},"proof_key":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofKey"}}},"pulsarchain.verification.v1.QueryProofTallyResponse":{"description":"QueryProofTallyResponse contains a pending proof tally.","type":"object","properties":{"proof_key":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofKey"},"tally":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofTally"}}},"pulsarchain.verification.v1.QueryProofsByHeightResponse":{"description":"QueryProofsByHeightResponse contains a page of proofs.","type":"object","properties":{"pagination":{"$ref":"#/definitions/cosmos.base.query.v1beta1.PageResponse"},"proofs":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.verification.v1.QueryProofResponse"}}}},"pulsarchain.verification.v1.QueryVerificationVotesResponse":{"description":"QueryVerificationVotesResponse contains effective votes.","type":"object","properties":{"pagination":{"$ref":"#/definitions/cosmos.base.query.v1beta1.PageResponse"},"votes":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.verification.v1.VerificationVoteEntry"}}}},"pulsarchain.verification.v1.QueryVoteResponse":{"description":"QueryVoteResponse contains one effective vote.","type":"object","properties":{"vote":{"$ref":"#/definitions/pulsarchain.verification.v1.VerificationVoteEntry"}}},"pulsarchain.verification.v1.VerificationVoteEntry":{"description":"VerificationVoteEntry is a query representation of an effective vote.","type":"object","properties":{"proof_key":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofKey"},"state":{"$ref":"#/definitions/pulsarchain.verification.v1.VoteState"},"validator":{"type":"string"}}},"pulsarchain.verification.v1.VoteState":{"description":"VoteState tracks a validator's effective vote.\n\n - VOTE_STATE_NONE: VOTE_STATE_NONE means the validator has not voted.\n - VOTE_STATE_TRUE: VOTE_STATE_TRUE is an effective valid vote.\n - VOTE_STATE_FALSE: VOTE_STATE_FALSE is an effective invalid vote.\n - VOTE_STATE_EQUIVOCATED: VOTE_STATE_EQUIVOCATED excludes conflicting votes from the tally.","type":"string","default":"VOTE_STATE_NONE","enum":["VOTE_STATE_NONE","VOTE_STATE_TRUE","VOTE_STATE_FALSE","VOTE_STATE_EQUIVOCATED"]},"pulsarchain.votepersistence.v1.Params":{"description":"Params defines the parameters for the module.","type":"object"},"pulsarchain.votepersistence.v1.QueryParamsResponse":{"description":"QueryParamsResponse is response type for the Query/Params RPC method.","type":"object","properties":{"params":{"description":"params holds all the parameters of this module.","$ref":"#/definitions/pulsarchain.votepersistence.v1.Params"}}},"pulsarchain.votepersistence.v1.QueryVoteExtensionsResponse":{"description":"QueryVoteExtensionsResponse defines the QueryVoteExtensionsResponse message.","type":"object","properties":{"persisted_vote_extensions_block_height":{"description":"persisted_vote_extensions_block_height is the signed source/current state\nheight. For vote extensions produced at height N, this value is N-2.","type":"string","format":"int64"},"query_block_height":{"type":"string","format":"int64"},"vote_extensions":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.votepersistence.v1.StoredVoteExtension"}}}},"pulsarchain.votepersistence.v1.StoredVoteExtension":{"description":"StoredVoteExtension defines a persisted Mina validator vote extension.","type":"object","properties":{"mina_public_key":{"type":"string","format":"byte"},"vote_extension":{"type":"string","format":"byte"}}},"pulsarchain.votepersistence.v1.VoteExtBody":{"description":"VoteExtBody defines the VoteExtBody message.","type":"object","properties":{"actions_reduced_root":{"type":"string","format":"byte"},"current_block_height":{"type":"string","format":"int64"},"current_state_root":{"type":"string","format":"byte"},"next_validator_set_hash":{"type":"string","format":"byte"}}}},"tags":[{"name":"VerificationService"},{"name":"Query"},{"name":"Msg"}]} \ No newline at end of file +{"id":"github.com/node101-io/pulsar-chain","consumes":["application/json"],"produces":["application/json"],"swagger":"2.0","info":{"description":"Chain github.com/node101-io/pulsar-chain REST API","title":"HTTP API Console","contact":{"name":"github.com/node101-io/pulsar-chain"},"version":"version not set"},"paths":{"/node101-io/pulsar-chain/abci/v1/validator_set_with_powers/{block_height}":{"get":{"tags":["Query"],"operationId":"GithubComnode101IopulsarChainQuery_GetValidatorSetWithPowers","parameters":[{"type":"string","format":"int64","name":"block_height","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.abci.QueryGetValidatorSetWithPowersResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/abci/v1/vote_ext_body_by_height/{vote_extension_height}":{"get":{"tags":["Query"],"summary":"VoteExtBodyByHeight queries the vote extension body for a vote-extension\nconsensus height.","operationId":"GithubComnode101IopulsarChainQuery_VoteExtBodyByHeight","parameters":[{"type":"string","format":"int64","description":"vote_extension_height is the consensus height N where the vote extension is\nproduced. The returned body signs the transition from state N-2 to state N-1.","name":"vote_extension_height","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.abci.QueryVoteExtBodyByHeightResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/bridge/v1/actions_reduced_root":{"get":{"tags":["Query"],"summary":"ActionsReducedRoot Queries a list of ActionsReducedRoot items.","operationId":"GithubComnode101IopulsarChainQuery_ActionsReducedRoot","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.bridge.v1.QueryActionsReducedRootResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/bridge/v1/latest_action_hashes":{"get":{"tags":["Query"],"summary":"LatestActionHashes Queries a list of LatestActionHashes items.","operationId":"GithubComnode101IopulsarChainQuery_LatestActionHashes","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.bridge.v1.QueryLatestActionHashesResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/bridge/v1/params":{"get":{"tags":["Query"],"summary":"Parameters queries the parameters of the module.","operationId":"GithubComnode101IopulsarChainQuery_Params","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.bridge.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_user_cosmos_public_key/{user_mina_public_key}":{"get":{"tags":["Query"],"summary":"GetUserCosmosPublicKey Queries a list of GetUserCosmosPublicKey items.","operationId":"GithubComnode101IopulsarChainQuery_GetUserCosmosPublicKey","parameters":[{"type":"string","format":"byte","name":"user_mina_public_key","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetUserCosmosPublicKeyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_user_mina_public_key/{user_cosmos_public_key}":{"get":{"tags":["Query"],"summary":"GetUserMinaPublicKey Queries a list of GetUserMinaPublicKey items.","operationId":"GithubComnode101IopulsarChainQuery_GetUserMinaPublicKey","parameters":[{"type":"string","format":"byte","name":"user_cosmos_public_key","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetUserMinaPublicKeyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_validator_cosmos_pub_key/{validator_mina_pub_key}":{"get":{"tags":["Query"],"summary":"GetValidatorCosmosPubKey Queries a list of GetValidatorCosmosPubKey items.","operationId":"GithubComnode101IopulsarChainQuery_GetValidatorCosmosPubKey","parameters":[{"type":"string","format":"byte","name":"validator_mina_pub_key","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetValidatorCosmosPubKeyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_validator_mina_pub_key/{validator_cosmos_pub_key}":{"get":{"tags":["Query"],"summary":"GetValidatorMinaPubKey Queries a list of GetValidatorMinaPubKey items.","operationId":"GithubComnode101IopulsarChainQuery_GetValidatorMinaPubKey","parameters":[{"type":"string","format":"byte","name":"validator_cosmos_pub_key","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetValidatorMinaPubKeyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/get_validator_set_with_mina_keys":{"get":{"tags":["Query"],"summary":"GetValidatorSetWithMinaKeys returns the supplied validator set with each validator's registered Mina public key.","operationId":"GithubComnode101IopulsarChainQuery_GetValidatorSetWithMinaKeys","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetValidatorSetWithMinaKeysResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/key_signing_challenge":{"get":{"tags":["Query"],"summary":"GetKeySigningChallenge returns the state-bound field a Mina wallet must sign.","operationId":"GithubComnode101IopulsarChainQuery_GetKeySigningChallenge","parameters":[{"enum":["KEY_SIGNING_OPERATION_UNSPECIFIED","KEY_SIGNING_OPERATION_REGISTER","KEY_SIGNING_OPERATION_UPDATE"],"type":"string","default":"KEY_SIGNING_OPERATION_UNSPECIFIED","description":" - KEY_SIGNING_OPERATION_UNSPECIFIED: KEY_SIGNING_OPERATION_UNSPECIFIED is invalid for signing requests.\n - KEY_SIGNING_OPERATION_REGISTER: KEY_SIGNING_OPERATION_REGISTER creates the first stable-key association.\n - KEY_SIGNING_OPERATION_UPDATE: KEY_SIGNING_OPERATION_UPDATE replaces an existing Mina key.","name":"operation","in":"query"},{"enum":["ACTOR_TYPE_UNSPECIFIED","ACTOR_TYPE_USER","ACTOR_TYPE_VALIDATOR"],"type":"string","default":"ACTOR_TYPE_UNSPECIFIED","description":" - ACTOR_TYPE_UNSPECIFIED: ACTOR_TYPE_UNSPECIFIED is invalid for key-registry operations.\n - ACTOR_TYPE_USER: ACTOR_TYPE_USER identifies a user account key association.\n - ACTOR_TYPE_VALIDATOR: ACTOR_TYPE_VALIDATOR identifies a validator consensus key association.","name":"actor_type","in":"query"},{"type":"string","format":"byte","name":"cosmos_public_key","in":"query"},{"type":"string","format":"byte","name":"new_mina_public_key","in":"query"}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryGetKeySigningChallengeResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/keyregistry/v1/params":{"get":{"tags":["Query"],"summary":"Parameters queries the parameters of the module.","operationId":"GithubComnode101IopulsarChainQuery_ParamsMixin17","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.keyregistry.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/smartaccounts/v1/get_session_keys_by_identity":{"get":{"tags":["Query"],"summary":"GetSessionKeysByIdentity Queries a list of GetSessionKeysByIdentity items.","operationId":"GithubComnode101IopulsarChainQuery_GetSessionKeysByIdentity","parameters":[{"type":"string","format":"byte","name":"identity","in":"query"},{"type":"string","format":"byte","description":"key is a value returned in PageResponse.next_key to begin\nquerying the next page most efficiently. Only one of offset or key\nshould be set.","name":"pagination.key","in":"query"},{"type":"string","format":"uint64","description":"offset is a numeric offset that can be used when key is unavailable.\nIt is less efficient than using key. Only one of offset or key should\nbe set.","name":"pagination.offset","in":"query"},{"type":"string","format":"uint64","description":"limit is the total number of results to be returned in the result page.\nIf left empty it will default to a value to be set by each app.","name":"pagination.limit","in":"query"},{"type":"boolean","description":"count_total is set to true to indicate that the result set should include\na count of the total number of items available for pagination in UIs.\ncount_total is only respected when offset is used. It is ignored when key\nis set.","name":"pagination.count_total","in":"query"},{"type":"boolean","description":"reverse is set to true if results are to be returned in the descending order.","name":"pagination.reverse","in":"query"}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.smartaccounts.v1.QueryGetSessionKeysByIdentityResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/smartaccounts/v1/params":{"get":{"tags":["Query"],"summary":"Parameters queries the parameters of the module.","operationId":"GithubComnode101IopulsarChainQuery_ParamsMixin22","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.smartaccounts.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/commitments/{validator}":{"get":{"tags":["Query"],"summary":"CommitmentsByValidator lists retained commitments for a validator.","operationId":"GithubComnode101IopulsarChainQuery_CommitmentsByValidator","parameters":[{"type":"string","name":"validator","in":"path","required":true},{"type":"string","format":"byte","description":"key is a value returned in PageResponse.next_key to begin\nquerying the next page most efficiently. Only one of offset or key\nshould be set.","name":"pagination.key","in":"query"},{"type":"string","format":"uint64","description":"offset is a numeric offset that can be used when key is unavailable.\nIt is less efficient than using key. Only one of offset or key should\nbe set.","name":"pagination.offset","in":"query"},{"type":"string","format":"uint64","description":"limit is the total number of results to be returned in the result page.\nIf left empty it will default to a value to be set by each app.","name":"pagination.limit","in":"query"},{"type":"boolean","description":"count_total is set to true to indicate that the result set should include\na count of the total number of items available for pagination in UIs.\ncount_total is only respected when offset is used. It is ignored when key\nis set.","name":"pagination.count_total","in":"query"},{"type":"boolean","description":"reverse is set to true if results are to be returned in the descending order.","name":"pagination.reverse","in":"query"}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryCommitmentsByValidatorResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/commitments/{validator}/{commitment_height}":{"get":{"tags":["Query"],"summary":"Commitment returns one retained validator commitment.","operationId":"GithubComnode101IopulsarChainQuery_Commitment","parameters":[{"type":"string","name":"validator","in":"path","required":true},{"type":"string","format":"uint64","name":"commitment_height","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryCommitmentResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/params":{"get":{"tags":["Query"],"summary":"Params returns module parameters.","operationId":"GithubComnode101IopulsarChainQuery_ParamsMixin27","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/proofs/height/{submission_height}":{"get":{"tags":["Query"],"summary":"ProofsByHeight lists proofs submitted at a height.","operationId":"GithubComnode101IopulsarChainQuery_ProofsByHeight","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"string","format":"byte","description":"key is a value returned in PageResponse.next_key to begin\nquerying the next page most efficiently. Only one of offset or key\nshould be set.","name":"pagination.key","in":"query"},{"type":"string","format":"uint64","description":"offset is a numeric offset that can be used when key is unavailable.\nIt is less efficient than using key. Only one of offset or key should\nbe set.","name":"pagination.offset","in":"query"},{"type":"string","format":"uint64","description":"limit is the total number of results to be returned in the result page.\nIf left empty it will default to a value to be set by each app.","name":"pagination.limit","in":"query"},{"type":"boolean","description":"count_total is set to true to indicate that the result set should include\na count of the total number of items available for pagination in UIs.\ncount_total is only respected when offset is used. It is ignored when key\nis set.","name":"pagination.count_total","in":"query"},{"type":"boolean","description":"reverse is set to true if results are to be returned in the descending order.","name":"pagination.reverse","in":"query"}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryProofsByHeightResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/proofs/verification-id/{verification_id}":{"get":{"tags":["Query"],"summary":"ProofByVerificationId resolves the permanent verification request registry.","operationId":"GithubComnode101IopulsarChainQuery_ProofByVerificationId","parameters":[{"type":"string","format":"byte","name":"verification_id","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryProofResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/proofs/{submission_height}/{index_in_block}":{"get":{"tags":["Query"],"summary":"Proof returns a pending or finalized proof by key.","operationId":"GithubComnode101IopulsarChainQuery_Proof","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryProofResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/results/{submission_height}/{index_in_block}":{"get":{"tags":["Query"],"summary":"FinalProofResult returns an immutable finalized result.","operationId":"GithubComnode101IopulsarChainQuery_FinalProofResult","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryFinalProofResultResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/tallies/{submission_height}/{index_in_block}":{"get":{"tags":["Query"],"summary":"ProofTally returns the active tally for a pending proof.","operationId":"GithubComnode101IopulsarChainQuery_ProofTally","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryProofTallyResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/votes/{submission_height}/{index_in_block}":{"get":{"tags":["Query"],"summary":"VerificationVotes lists effective votes for a proof.","operationId":"GithubComnode101IopulsarChainQuery_VerificationVotes","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true},{"type":"string","format":"byte","description":"key is a value returned in PageResponse.next_key to begin\nquerying the next page most efficiently. Only one of offset or key\nshould be set.","name":"pagination.key","in":"query"},{"type":"string","format":"uint64","description":"offset is a numeric offset that can be used when key is unavailable.\nIt is less efficient than using key. Only one of offset or key should\nbe set.","name":"pagination.offset","in":"query"},{"type":"string","format":"uint64","description":"limit is the total number of results to be returned in the result page.\nIf left empty it will default to a value to be set by each app.","name":"pagination.limit","in":"query"},{"type":"boolean","description":"count_total is set to true to indicate that the result set should include\na count of the total number of items available for pagination in UIs.\ncount_total is only respected when offset is used. It is ignored when key\nis set.","name":"pagination.count_total","in":"query"},{"type":"boolean","description":"reverse is set to true if results are to be returned in the descending order.","name":"pagination.reverse","in":"query"}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryVerificationVotesResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/verification/v1/votes/{submission_height}/{index_in_block}/{validator}":{"get":{"tags":["Query"],"summary":"Vote returns one validator's effective vote for a proof.","operationId":"GithubComnode101IopulsarChainQuery_Vote","parameters":[{"type":"string","format":"uint64","name":"submission_height","in":"path","required":true},{"type":"integer","format":"int64","name":"index_in_block","in":"path","required":true},{"type":"string","name":"validator","in":"path","required":true}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.verification.v1.QueryVoteResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/votepersistence/v1/params":{"get":{"tags":["Query"],"summary":"Parameters queries the parameters of the module.","operationId":"GithubComnode101IopulsarChainQuery_ParamsMixin33","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.votepersistence.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/node101-io/pulsar-chain/votepersistence/v1/vote_extensions":{"get":{"tags":["Query"],"summary":"VoteExtensions queries the currently persisted vote extensions.","operationId":"GithubComnode101IopulsarChainQuery_VoteExtensions","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/pulsarchain.votepersistence.v1.QueryVoteExtensionsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}}},"definitions":{"cosmos.base.query.v1beta1.PageRequest":{"description":"message SomeRequest {\n Foo some_parameter = 1;\n PageRequest pagination = 2;\n }","type":"object","title":"PageRequest is to be embedded in gRPC request messages for efficient\npagination. Ex:","properties":{"count_total":{"description":"count_total is set to true to indicate that the result set should include\na count of the total number of items available for pagination in UIs.\ncount_total is only respected when offset is used. It is ignored when key\nis set.","type":"boolean"},"key":{"description":"key is a value returned in PageResponse.next_key to begin\nquerying the next page most efficiently. Only one of offset or key\nshould be set.","type":"string","format":"byte"},"limit":{"description":"limit is the total number of results to be returned in the result page.\nIf left empty it will default to a value to be set by each app.","type":"string","format":"uint64"},"offset":{"description":"offset is a numeric offset that can be used when key is unavailable.\nIt is less efficient than using key. Only one of offset or key should\nbe set.","type":"string","format":"uint64"},"reverse":{"description":"reverse is set to true if results are to be returned in the descending order.","type":"boolean"}}},"cosmos.base.query.v1beta1.PageResponse":{"description":"PageResponse is to be embedded in gRPC response messages where the\ncorresponding request message has used PageRequest.\n\n message SomeResponse {\n repeated Bar results = 1;\n PageResponse page = 2;\n }","type":"object","properties":{"next_key":{"description":"next_key is the key to be passed to PageRequest.key to\nquery the next page most efficiently. It will be empty if\nthere are no more results.","type":"string","format":"byte"},"total":{"type":"string","format":"uint64","title":"total is total number of results available if PageRequest.count_total\nwas set, its value is undefined otherwise"}}},"google.protobuf.Any":{"type":"object","properties":{"@type":{"type":"string"}},"additionalProperties":{}},"google.rpc.Status":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"details":{"type":"array","items":{"type":"object","$ref":"#/definitions/google.protobuf.Any"}},"message":{"type":"string"}}},"pulsarchain.abci.QueryGetValidatorSetWithPowersResponse":{"type":"object","properties":{"validators":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.common.ValidatorEntry"}}}},"pulsarchain.abci.QueryVoteExtBodyByHeightResponse":{"description":"QueryVoteExtBodyByHeightResponse defines the response for VoteExtBodyByHeight.","type":"object","properties":{"vote_ext_body":{"$ref":"#/definitions/pulsarchain.votepersistence.v1.VoteExtBody"}}},"pulsarchain.bridge.v1.Params":{"description":"Params defines the parameters for the module.","type":"object","properties":{"actions_reduced_root_snapshot_window_size":{"description":"actions_reduced_root_snapshot_window_size is the retained consensus root window.","type":"string","format":"int64"},"confirmation_depth":{"description":"confirmation_depth is the Mina finality depth used by the archive wrapper.","type":"string","format":"int64"},"contract_address":{"description":"contract_address is the Mina bridge contract address.","type":"string"},"max_block_range":{"description":"max_block_range is the maximum Mina height span processed by one request.","type":"string","format":"int64"},"start_block_height":{"description":"start_block_height is the first Mina block indexed by the bridge.","type":"string","format":"int64"}}},"pulsarchain.bridge.v1.QueryActionsReducedRootResponse":{"description":"QueryActionsReducedRootResponse defines the QueryActionsReducedRootResponse message.","type":"object","properties":{"actions_reduced_root":{"type":"string"}}},"pulsarchain.bridge.v1.QueryLatestActionHashesResponse":{"description":"QueryLatestActionHashesResponse defines the QueryLatestActionHashesResponse message.","type":"object","properties":{"action_hashes":{"description":"action_hashes is the ordered canonical hash batch that reconstructs\nthe root transition for the source Cosmos block.","type":"array","items":{"type":"string"}},"action_hashes_cosmos_block_height":{"description":"action_hashes_cosmos_block_height is the Cosmos block height where\nthis query batch was produced.","type":"string","format":"int64"},"latest_fetched_mina_height":{"description":"latest_fetched_mina_height is the inclusive upper Mina cursor of the\ncurrent batch. Together with start_mina_height it defines the consumed\nMina interval (start_mina_height, latest_fetched_mina_height].","type":"string","format":"int64"},"start_mina_height":{"description":"start_mina_height is the exclusive lower Mina cursor of the current batch.","type":"string","format":"int64"}}},"pulsarchain.bridge.v1.QueryParamsResponse":{"description":"QueryParamsResponse is response type for the Query/Params RPC method.","type":"object","properties":{"params":{"description":"params holds all the parameters of this module.","$ref":"#/definitions/pulsarchain.bridge.v1.Params"}}},"pulsarchain.common.ValidatorEntry":{"type":"object","properties":{"consensus_power":{"type":"string","format":"int64"},"validator_cosmos_pub_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.ActorType":{"description":"ActorType identifies the key-registry actor authorized by a signing challenge.\n\n - ACTOR_TYPE_UNSPECIFIED: ACTOR_TYPE_UNSPECIFIED is invalid for key-registry operations.\n - ACTOR_TYPE_USER: ACTOR_TYPE_USER identifies a user account key association.\n - ACTOR_TYPE_VALIDATOR: ACTOR_TYPE_VALIDATOR identifies a validator consensus key association.","type":"string","default":"ACTOR_TYPE_UNSPECIFIED","enum":["ACTOR_TYPE_UNSPECIFIED","ACTOR_TYPE_USER","ACTOR_TYPE_VALIDATOR"]},"pulsarchain.keyregistry.v1.KeySigningOperation":{"description":"KeySigningOperation identifies the key-registry state transition authorized\nby a wallet field signature.\n\n - KEY_SIGNING_OPERATION_UNSPECIFIED: KEY_SIGNING_OPERATION_UNSPECIFIED is invalid for signing requests.\n - KEY_SIGNING_OPERATION_REGISTER: KEY_SIGNING_OPERATION_REGISTER creates the first stable-key association.\n - KEY_SIGNING_OPERATION_UPDATE: KEY_SIGNING_OPERATION_UPDATE replaces an existing Mina key.","type":"string","default":"KEY_SIGNING_OPERATION_UNSPECIFIED","enum":["KEY_SIGNING_OPERATION_UNSPECIFIED","KEY_SIGNING_OPERATION_REGISTER","KEY_SIGNING_OPERATION_UPDATE"]},"pulsarchain.keyregistry.v1.Params":{"description":"Params defines the parameters for the module.","type":"object"},"pulsarchain.keyregistry.v1.QueryGetKeySigningChallengeResponse":{"description":"QueryGetKeySigningChallengeResponse contains the exact field and state version to sign.","type":"object","properties":{"challenge":{"type":"string"},"challenge_bytes":{"type":"string","format":"byte"},"new_key_version":{"type":"string","format":"uint64"},"previous_mina_public_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetUserCosmosPublicKeyResponse":{"description":"QueryGetUserCosmosPublicKeyResponse defines the QueryGetUserCosmosPublicKeyResponse message.","type":"object","properties":{"user_cosmos_public_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetUserMinaPublicKeyResponse":{"description":"QueryGetUserMinaPublicKeyResponse defines the QueryGetUserMinaPublicKeyResponse message.","type":"object","properties":{"user_mina_public_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetValidatorCosmosPubKeyResponse":{"description":"QueryGetValidatorCosmosPubKeyResponse defines the QueryGetValidatorCosmosPubKeyResponse message.","type":"object","properties":{"validator_cosmos_pub_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetValidatorMinaPubKeyResponse":{"description":"QueryGetValidatorMinaPubKeyResponse defines the QueryGetValidatorMinaPubKeyResponse message.","type":"object","properties":{"validator_mina_pub_key":{"type":"string","format":"byte"}}},"pulsarchain.keyregistry.v1.QueryGetValidatorSetWithMinaKeysResponse":{"description":"QueryGetValidatorSetWithMinaKeysResponse defines the response for GetValidatorSetWithMinaKeys.","type":"object","properties":{"registered_validators":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.keyregistry.v1.RegisteredValidatorSetEntry"}}}},"pulsarchain.keyregistry.v1.QueryParamsResponse":{"description":"QueryParamsResponse is response type for the Query/Params RPC method.","type":"object","properties":{"params":{"description":"params holds all the parameters of this module.","$ref":"#/definitions/pulsarchain.keyregistry.v1.Params"}}},"pulsarchain.keyregistry.v1.RegisteredValidatorSetEntry":{"type":"object","properties":{"consensus_power":{"type":"string","format":"int64"},"validator_cosmos_pub_key":{"type":"string","format":"byte"},"validator_mina_pub_key":{"type":"string","format":"byte"}}},"pulsarchain.smartaccounts.v1.Params":{"description":"Params defines the parameters for the module.","type":"object","properties":{"verification_key_hash":{"type":"string","format":"byte"}}},"pulsarchain.smartaccounts.v1.QueryGetSessionKeysByIdentityResponse":{"description":"QueryGetSessionKeysByIdentityResponse defines the QueryGetSessionKeysByIdentityResponse message.","type":"object","properties":{"account_address":{"type":"string","format":"byte"},"pagination":{"description":"pagination describes this page of session keys.","$ref":"#/definitions/cosmos.base.query.v1beta1.PageResponse"},"session_keys":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.smartaccounts.v1.SessionKey"}}}},"pulsarchain.smartaccounts.v1.QueryParamsResponse":{"description":"QueryParamsResponse is response type for the Query/Params RPC method.","type":"object","properties":{"params":{"description":"params holds all the parameters of this module.","$ref":"#/definitions/pulsarchain.smartaccounts.v1.Params"}}},"pulsarchain.smartaccounts.v1.SessionKey":{"description":"SessionKey defines an Ed25519 public key and its exclusive expiration height.","type":"object","properties":{"expires_at_height":{"type":"string","format":"uint64"},"public_key":{"type":"string","format":"byte"}}},"pulsarchain.verification.v1.CommitmentEntry":{"description":"CommitmentEntry is a query representation of a retained commitment.","type":"object","properties":{"commitment":{"$ref":"#/definitions/pulsarchain.verification.v1.CommitmentRecord"},"commitment_height":{"type":"string","format":"uint64"},"validator":{"type":"string"}}},"pulsarchain.verification.v1.CommitmentRecord":{"description":"CommitmentRecord stores a validator commitment root.","type":"object","properties":{"commitment":{"type":"string","format":"byte"}}},"pulsarchain.verification.v1.FinalProofResult":{"description":"FinalProofResult stores an immutable finalized proof outcome.","type":"object","properties":{"finalized_height":{"type":"string","format":"uint64"},"invalid_voting_power":{"type":"string","format":"int64"},"proof_hash":{"type":"string","format":"byte"},"proof_type":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofType"},"public_inputs_hash":{"type":"string","format":"byte"},"status":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofStatus"},"submission_height":{"type":"string","format":"uint64"},"total_voting_power":{"type":"string","format":"int64"},"valid_voting_power":{"type":"string","format":"int64"},"verification_id":{"type":"string","format":"byte"},"verification_key_hash":{"type":"string","format":"byte"},"voting_power_threshold":{"type":"string","format":"int64"}}},"pulsarchain.verification.v1.Params":{"description":"Params defines the governance-controlled verification module parameters.","type":"object","properties":{"max_proofs_per_block":{"type":"integer","format":"int64"}}},"pulsarchain.verification.v1.ProofKey":{"description":"ProofKey identifies a proof by absolute block height and in-block index.","type":"object","properties":{"index_in_block":{"type":"integer","format":"int64"},"submission_height":{"type":"string","format":"uint64"}}},"pulsarchain.verification.v1.ProofRecord":{"description":"ProofRecord stores the complete descriptor and its chain-derived identity.","type":"object","properties":{"proof_hash":{"type":"string","format":"byte"},"proof_type":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofType"},"public_inputs_hash":{"type":"string","format":"byte"},"verification_id":{"type":"string","format":"byte"},"verification_key_hash":{"type":"string","format":"byte"}}},"pulsarchain.verification.v1.ProofStatus":{"description":"ProofStatus is the finalized verification outcome.\n\n - PROOF_STATUS_PENDING: PROOF_STATUS_PENDING is the non-finalized status.\n - PROOF_STATUS_VALID: PROOF_STATUS_VALID means valid voting power exceeded two thirds.\n - PROOF_STATUS_INVALID: PROOF_STATUS_INVALID means invalid voting power exceeded two thirds.\n - PROOF_STATUS_INCONCLUSIVE: PROOF_STATUS_INCONCLUSIVE means neither side reached threshold.","type":"string","default":"PROOF_STATUS_PENDING","enum":["PROOF_STATUS_PENDING","PROOF_STATUS_VALID","PROOF_STATUS_INVALID","PROOF_STATUS_INCONCLUSIVE"]},"pulsarchain.verification.v1.ProofTally":{"description":"ProofTally stores the historical consensus power behind effective votes.","type":"object","properties":{"invalid_voting_power":{"type":"string","format":"int64"},"valid_voting_power":{"type":"string","format":"int64"}}},"pulsarchain.verification.v1.ProofType":{"description":"ProofType selects the verifier family. The exact statement and circuit are\nbound separately by the public-input and verification-key hashes.\n\n - PROOF_TYPE_UNSPECIFIED: PROOF_TYPE_UNSPECIFIED is invalid for proof submission.\n - PROOF_TYPE_MINA_PICKLES: PROOF_TYPE_MINA_PICKLES selects Mina's Pickles proof system.\n - PROOF_TYPE_NOIR_BARRETENBERG: PROOF_TYPE_NOIR_BARRETENBERG selects Noir proofs using Barretenberg.","type":"string","default":"PROOF_TYPE_UNSPECIFIED","enum":["PROOF_TYPE_UNSPECIFIED","PROOF_TYPE_MINA_PICKLES","PROOF_TYPE_NOIR_BARRETENBERG"]},"pulsarchain.verification.v1.QueryCommitmentResponse":{"description":"QueryCommitmentResponse contains one retained commitment.","type":"object","properties":{"commitment":{"$ref":"#/definitions/pulsarchain.verification.v1.CommitmentEntry"}}},"pulsarchain.verification.v1.QueryCommitmentsByValidatorResponse":{"description":"QueryCommitmentsByValidatorResponse contains retained commitments.","type":"object","properties":{"commitments":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.verification.v1.CommitmentEntry"}},"pagination":{"$ref":"#/definitions/cosmos.base.query.v1beta1.PageResponse"}}},"pulsarchain.verification.v1.QueryFinalProofResultResponse":{"description":"QueryFinalProofResultResponse contains an immutable proof result.","type":"object","properties":{"final_result":{"$ref":"#/definitions/pulsarchain.verification.v1.FinalProofResult"},"proof_key":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofKey"}}},"pulsarchain.verification.v1.QueryParamsResponse":{"description":"QueryParamsResponse contains verification parameters.","type":"object","properties":{"params":{"$ref":"#/definitions/pulsarchain.verification.v1.Params"}}},"pulsarchain.verification.v1.QueryProofResponse":{"description":"QueryProofResponse contains either pending or finalized proof state.","type":"object","properties":{"final_result":{"$ref":"#/definitions/pulsarchain.verification.v1.FinalProofResult"},"pending":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofRecord"},"proof_key":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofKey"}}},"pulsarchain.verification.v1.QueryProofTallyResponse":{"description":"QueryProofTallyResponse contains a pending proof tally.","type":"object","properties":{"proof_key":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofKey"},"tally":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofTally"}}},"pulsarchain.verification.v1.QueryProofsByHeightResponse":{"description":"QueryProofsByHeightResponse contains a page of proofs.","type":"object","properties":{"pagination":{"$ref":"#/definitions/cosmos.base.query.v1beta1.PageResponse"},"proofs":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.verification.v1.QueryProofResponse"}}}},"pulsarchain.verification.v1.QueryVerificationVotesResponse":{"description":"QueryVerificationVotesResponse contains effective votes.","type":"object","properties":{"pagination":{"$ref":"#/definitions/cosmos.base.query.v1beta1.PageResponse"},"votes":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.verification.v1.VerificationVoteEntry"}}}},"pulsarchain.verification.v1.QueryVoteResponse":{"description":"QueryVoteResponse contains one effective vote.","type":"object","properties":{"vote":{"$ref":"#/definitions/pulsarchain.verification.v1.VerificationVoteEntry"}}},"pulsarchain.verification.v1.VerificationVoteEntry":{"description":"VerificationVoteEntry is a query representation of an effective vote.","type":"object","properties":{"proof_key":{"$ref":"#/definitions/pulsarchain.verification.v1.ProofKey"},"state":{"$ref":"#/definitions/pulsarchain.verification.v1.VoteState"},"validator":{"type":"string"}}},"pulsarchain.verification.v1.VoteState":{"description":"VoteState tracks a validator's effective vote.\n\n - VOTE_STATE_NONE: VOTE_STATE_NONE means the validator has not voted.\n - VOTE_STATE_TRUE: VOTE_STATE_TRUE is an effective valid vote.\n - VOTE_STATE_FALSE: VOTE_STATE_FALSE is an effective invalid vote.\n - VOTE_STATE_EQUIVOCATED: VOTE_STATE_EQUIVOCATED excludes conflicting votes from the tally.","type":"string","default":"VOTE_STATE_NONE","enum":["VOTE_STATE_NONE","VOTE_STATE_TRUE","VOTE_STATE_FALSE","VOTE_STATE_EQUIVOCATED"]},"pulsarchain.votepersistence.v1.Params":{"description":"Params defines the parameters for the module.","type":"object"},"pulsarchain.votepersistence.v1.QueryParamsResponse":{"description":"QueryParamsResponse is response type for the Query/Params RPC method.","type":"object","properties":{"params":{"description":"params holds all the parameters of this module.","$ref":"#/definitions/pulsarchain.votepersistence.v1.Params"}}},"pulsarchain.votepersistence.v1.QueryVoteExtensionsResponse":{"description":"QueryVoteExtensionsResponse defines the QueryVoteExtensionsResponse message.","type":"object","properties":{"persisted_vote_extensions_block_height":{"description":"persisted_vote_extensions_block_height is the signed source/current state\nheight. For vote extensions produced at height N, this value is N-2.","type":"string","format":"int64"},"query_block_height":{"type":"string","format":"int64"},"vote_extensions":{"type":"array","items":{"type":"object","$ref":"#/definitions/pulsarchain.votepersistence.v1.StoredVoteExtension"}}}},"pulsarchain.votepersistence.v1.StoredVoteExtension":{"description":"StoredVoteExtension defines a persisted Mina validator vote extension.","type":"object","properties":{"mina_public_key":{"type":"string","format":"byte"},"vote_extension":{"type":"string","format":"byte"}}},"pulsarchain.votepersistence.v1.VoteExtBody":{"description":"VoteExtBody defines the VoteExtBody message.","type":"object","properties":{"actions_reduced_root":{"type":"string","format":"byte"},"current_block_height":{"type":"string","format":"int64"},"current_state_root":{"type":"string","format":"byte"},"next_validator_set_hash":{"type":"string","format":"byte"}}}},"tags":[{"name":"VerificationService"},{"name":"Query"},{"name":"Msg"}]} \ No newline at end of file diff --git a/proto/pulsarchain/ante/v1/tx_auth.proto b/proto/pulsarchain/ante/v1/tx_auth.proto index 953462ce..4346816b 100644 --- a/proto/pulsarchain/ante/v1/tx_auth.proto +++ b/proto/pulsarchain/ante/v1/tx_auth.proto @@ -16,6 +16,8 @@ enum TxAuthMode { TX_AUTH_MODE_COSMOS = 1; // TX_AUTH_MODE_MINA selects verification with the signer's registered Mina key. TX_AUTH_MODE_MINA = 2; + // TX_AUTH_MODE_SMART_ACCOUNT selects verification with the registered Session key. + TX_AUTH_MODE_SMART_ACCOUNT = 3; } // TxAuthModeExtension marks the authentication mode of a transaction. @@ -23,4 +25,6 @@ message TxAuthModeExtension { option (gogoproto.goproto_getters) = false; TxAuthMode tx_auth_mode = 1; + + bytes smart_account_identity = 2; } diff --git a/proto/pulsarchain/bridge/v1/bridge_state.proto b/proto/pulsarchain/bridge/v1/bridge_state.proto index 2d1d9e66..a75cba2d 100644 --- a/proto/pulsarchain/bridge/v1/bridge_state.proto +++ b/proto/pulsarchain/bridge/v1/bridge_state.proto @@ -6,7 +6,6 @@ option go_package = "github.com/node101-io/pulsar-chain/x/bridge/types"; // BridgeState stores the bridge's processed Mina cursor. message BridgeState { - // latest_fetched_mina_height is the latest Mina height processed by the bridge. int64 latest_fetched_mina_height = 1; diff --git a/proto/pulsarchain/smartaccounts/module/v1/module.proto b/proto/pulsarchain/smartaccounts/module/v1/module.proto new file mode 100644 index 00000000..b8a8e546 --- /dev/null +++ b/proto/pulsarchain/smartaccounts/module/v1/module.proto @@ -0,0 +1,15 @@ +syntax = "proto3"; +package pulsarchain.smartaccounts.module.v1; + +import "cosmos/app/v1alpha1/module.proto"; + +option go_package = "github.com/node101-io/pulsar-chain/x/smartaccounts/types"; + +// Module is the config object for the module. +message Module { + option (cosmos.app.v1alpha1.module) = {go_import: "github.com/node101-io/pulsar-chain/x/smartaccounts"}; + + // authority defines the custom module authority. + // If not set, defaults to the governance module. + string authority = 1; +} diff --git a/proto/pulsarchain/smartaccounts/v1/genesis.proto b/proto/pulsarchain/smartaccounts/v1/genesis.proto new file mode 100644 index 00000000..48aa5b04 --- /dev/null +++ b/proto/pulsarchain/smartaccounts/v1/genesis.proto @@ -0,0 +1,25 @@ +syntax = "proto3"; +package pulsarchain.smartaccounts.v1; + +import "amino/amino.proto"; +import "gogoproto/gogo.proto"; +import "pulsarchain/smartaccounts/v1/params.proto"; +import "pulsarchain/smartaccounts/v1/types.proto"; + +option go_package = "github.com/node101-io/pulsar-chain/x/smartaccounts/types"; + +// GenesisState defines the smartaccounts module's genesis state. +message GenesisState { + // params defines all the parameters of the module. + Params params = 1 [ + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; + repeated SmartAccountEntry smart_accounts = 2 [(gogoproto.nullable) = false]; +} + +// SmartAccountEntry associates an identity with its smart-account state. +message SmartAccountEntry { + bytes identity = 1; + SmartAccount account = 2 [(gogoproto.nullable) = false]; +} diff --git a/proto/pulsarchain/smartaccounts/v1/params.proto b/proto/pulsarchain/smartaccounts/v1/params.proto new file mode 100644 index 00000000..fab32d3a --- /dev/null +++ b/proto/pulsarchain/smartaccounts/v1/params.proto @@ -0,0 +1,15 @@ +syntax = "proto3"; +package pulsarchain.smartaccounts.v1; + +import "amino/amino.proto"; +import "gogoproto/gogo.proto"; + +option go_package = "github.com/node101-io/pulsar-chain/x/smartaccounts/types"; + +// Params defines the parameters for the module. +message Params { + option (amino.name) = "pulsarchain/x/smartaccounts/Params"; + option (gogoproto.equal) = true; + + bytes verification_key_hash = 1; +} diff --git a/proto/pulsarchain/smartaccounts/v1/query.proto b/proto/pulsarchain/smartaccounts/v1/query.proto new file mode 100644 index 00000000..be26e23b --- /dev/null +++ b/proto/pulsarchain/smartaccounts/v1/query.proto @@ -0,0 +1,52 @@ +syntax = "proto3"; + +package pulsarchain.smartaccounts.v1; + +import "amino/amino.proto"; +import "cosmos/base/query/v1beta1/pagination.proto"; +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "pulsarchain/smartaccounts/v1/params.proto"; +import "pulsarchain/smartaccounts/v1/types.proto"; + +option go_package = "github.com/node101-io/pulsar-chain/x/smartaccounts/types"; + +// Query defines the gRPC querier service. +service Query { + // Parameters queries the parameters of the module. + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/node101-io/pulsar-chain/smartaccounts/v1/params"; + } + + // GetSessionKeysByIdentity Queries a list of GetSessionKeysByIdentity items. + rpc GetSessionKeysByIdentity(QueryGetSessionKeysByIdentityRequest) returns (QueryGetSessionKeysByIdentityResponse) { + option (google.api.http).get = "/node101-io/pulsar-chain/smartaccounts/v1/get_session_keys_by_identity"; + } +} + +// QueryParamsRequest is request type for the Query/Params RPC method. +message QueryParamsRequest {} + +// QueryParamsResponse is response type for the Query/Params RPC method. +message QueryParamsResponse { + // params holds all the parameters of this module. + Params params = 1 [ + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; +} + +// QueryGetSessionKeysByIdentityRequest defines the QueryGetSessionKeysByIdentityRequest message. +message QueryGetSessionKeysByIdentityRequest { + bytes identity = 1; + // pagination applies to the selected smart account's session keys. + cosmos.base.query.v1beta1.PageRequest pagination = 2; +} + +// QueryGetSessionKeysByIdentityResponse defines the QueryGetSessionKeysByIdentityResponse message. +message QueryGetSessionKeysByIdentityResponse { + bytes account_address = 1; + repeated SessionKey session_keys = 2; + // pagination describes this page of session keys. + cosmos.base.query.v1beta1.PageResponse pagination = 3; +} diff --git a/proto/pulsarchain/smartaccounts/v1/tx.proto b/proto/pulsarchain/smartaccounts/v1/tx.proto new file mode 100644 index 00000000..560f2128 --- /dev/null +++ b/proto/pulsarchain/smartaccounts/v1/tx.proto @@ -0,0 +1,56 @@ +syntax = "proto3"; + +package pulsarchain.smartaccounts.v1; + +import "amino/amino.proto"; +import "cosmos/msg/v1/msg.proto"; +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "pulsarchain/smartaccounts/v1/params.proto"; +import "pulsarchain/smartaccounts/v1/types.proto"; + +option go_package = "github.com/node101-io/pulsar-chain/x/smartaccounts/types"; + +// Msg defines the Msg service. +service Msg { + option (cosmos.msg.v1.service) = true; + + // UpdateParams defines a (governance) operation for updating the module + // parameters. The authority defaults to the x/gov module account. + rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); + + // AddPublicKey defines the AddPublicKey RPC. + rpc AddPublicKey(MsgAddPublicKey) returns (MsgAddPublicKeyResponse); +} + +// MsgUpdateParams is the Msg/UpdateParams request type. +message MsgUpdateParams { + option (cosmos.msg.v1.signer) = "authority"; + option (amino.name) = "pulsarchain/x/smartaccounts/MsgUpdateParams"; + + // authority is the address that controls the module (defaults to x/gov unless overwritten). + string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // params defines the module parameters to update. + // + // NOTE: All parameters must be supplied. + Params params = 2 [ + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +message MsgUpdateParamsResponse {} + +// MsgAddPublicKey defines the MsgAddPublicKey message. +message MsgAddPublicKey { + option (cosmos.msg.v1.signer) = "creator"; + string creator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + bytes verification_id = 2; + PublicKeyInputs public_key_inputs = 3; +} + +// MsgAddPublicKeyResponse defines the MsgAddPublicKeyResponse message. +message MsgAddPublicKeyResponse {} diff --git a/proto/pulsarchain/smartaccounts/v1/types.proto b/proto/pulsarchain/smartaccounts/v1/types.proto new file mode 100644 index 00000000..82fab9b0 --- /dev/null +++ b/proto/pulsarchain/smartaccounts/v1/types.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; +package pulsarchain.smartaccounts.v1; + +import "amino/amino.proto"; +import "gogoproto/gogo.proto"; + +option go_package = "github.com/node101-io/pulsar-chain/x/smartaccounts/types"; + +// SmartAccount binds a Cosmos account address to its authorized session keys. +message SmartAccount { + bytes account_address = 1; + repeated SessionKey session_keys = 2 [(gogoproto.nullable) = false]; +} + +// SessionKey defines an Ed25519 public key and its exclusive expiration height. +message SessionKey { + bytes public_key = 1; + uint64 expires_at_height = 2; +} + +// PublicKeyInputs defines the PublicKeyInputs message. +message PublicKeyInputs { + bytes session_public_key = 1; + uint64 expires_at_height = 2; + bytes identity = 3; +} diff --git a/proto/pulsarchain/verification/v1/query.proto b/proto/pulsarchain/verification/v1/query.proto index 186bd796..53f357d4 100644 --- a/proto/pulsarchain/verification/v1/query.proto +++ b/proto/pulsarchain/verification/v1/query.proto @@ -60,7 +60,10 @@ message QueryParamsRequest {} // QueryParamsResponse contains verification parameters. message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; + Params params = 1 [ + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; } // QueryProofRequest identifies a proof by key. diff --git a/scripts/deploy_local_lightnet.sh b/scripts/deploy_local_lightnet.sh index 5984310d..c0386ddb 100755 --- a/scripts/deploy_local_lightnet.sh +++ b/scripts/deploy_local_lightnet.sh @@ -24,6 +24,12 @@ LIGHTNET_OWNERSHIP_VALUE="mina-lightnet" WRAPPER_SOURCE="${ARCHIVE_WRAPPER_SOURCE:-$REPO_ROOT/../archive-wrapper}" WRAPPER_SHA="${ARCHIVE_WRAPPER_SHA:-cd42a203ac6b43d24d9fbd57c323ecd52ea52bd5}" WRAPPER_IMAGE="${ARCHIVE_WRAPPER_IMAGE:-archive-wrapper:lightnet}" +VERIFIER_SOURCE="${PULSAR_VERIFIER_SOURCE:-}" +VERIFIER_SHA="${PULSAR_VERIFIER_SHA:-e7582ba2aea2fa12b765221003a366868f39b3e8}" +VERIFIER_IMAGE="${PULSAR_VERIFIER_IMAGE:-pulsar-verifier:lightnet}" +VERIFIER_CACHE_ROOT="${PULSAR_VERIFIER_CACHE_ROOT:-$REPO_ROOT/.cache/pulsar-verifier}" +VERIFIER_REPOSITORY="https://github.com/node101-io/pulsar-verifier.git" +ENABLE_VERIFIER_SIDECARS="${ENABLE_VERIFIER_SIDECARS:-0}" PULSAR_IMAGE="" BRIDGE_CONFIRMATION_DEPTH="${BRIDGE_CONFIRMATION_DEPTH:-3}" BRIDGE_START_BLOCK_HEIGHT="${BRIDGE_START_BLOCK_HEIGHT:-1}" @@ -44,6 +50,7 @@ Recreates the local development stack with: - an existing running Mina Lightnet, or a new Dockerized Lightnet - the blocks_inserted LISTEN/NOTIFY trigger - one shared archive-wrapper in Docker + - optionally, one pulsar-verifier sidecar per validator - the requested number of Pulsar validators in Docker Destructive behavior: @@ -61,6 +68,14 @@ Optional environment variables: ARCHIVE_WRAPPER_SOURCE checkout path (default: ../archive-wrapper) ARCHIVE_WRAPPER_SHA commit to build (default pinned in the script) ARCHIVE_WRAPPER_IMAGE built image name (default: archive-wrapper:lightnet) + PULSAR_VERIFIER_SOURCE existing checkout override (default: automatic + pinned download under .cache/pulsar-verifier) + PULSAR_VERIFIER_SHA commit to build (default pinned in the script) + PULSAR_VERIFIER_IMAGE built image name (default: pulsar-verifier:lightnet) + PULSAR_VERIFIER_CACHE_ROOT automatic source cache (default: + .cache/pulsar-verifier) + ENABLE_VERIFIER_SIDECARS set to 1 to build and start verifier sidecars + (default: 0, chain-only deployment) PULSAR_DOCKER_PROJECT Compose project (default: pulsar-testnet-N) PULSAR_DOCKER_STATE_ROOT generated state root (default: .docker) PULSAR_DOCKER_IMAGE Pulsar image name (default derived from N) @@ -69,7 +84,9 @@ Optional environment variables: BRIDGE_CONFIRMATION_DEPTH local bridge confirmation depth (default: 3) BRIDGE_START_BLOCK_HEIGHT local bridge start height (default: 1) BRIDGE_MAX_BLOCK_RANGE local bridge query range (default: 1000) - + SMART_ACCOUNTS_VERIFICATION_KEY_HASH + 32-byte smartaccounts verification-key hash in hex + or base64 (default: value from config.yml) Default Mina Lightnet image: o1labs/mina-local-network@sha256:33e349241f5f3e8d336e5de9b35de2d4339fd8713b309e2b1b5fc375c2605b58 @@ -307,6 +324,10 @@ validate_positive_int "validator startup timeout" "$VALIDATOR_STARTUP_TIMEOUT" validate_positive_int "bridge confirmation depth" "$BRIDGE_CONFIRMATION_DEPTH" validate_positive_int "bridge start block height" "$BRIDGE_START_BLOCK_HEIGHT" validate_positive_int "bridge max block range" "$BRIDGE_MAX_BLOCK_RANGE" +if [[ "$ENABLE_VERIFIER_SIDECARS" != "0" && "$ENABLE_VERIFIER_SIDECARS" != "1" ]]; then + echo "ENABLE_VERIFIER_SIDECARS must be 0 or 1" >&2 + exit 1 +fi case "$DOCKER_PLATFORM" in linux/arm64 | linux/amd64) ;; @@ -343,9 +364,33 @@ fi WRAPPER_SOURCE="$(cd -- "$WRAPPER_SOURCE" && pwd)" git -C "$WRAPPER_SOURCE" cat-file -e "${WRAPPER_SHA}^{commit}" +if [[ "$ENABLE_VERIFIER_SIDECARS" == "1" ]]; then + if [[ -z "$VERIFIER_SOURCE" ]]; then + VERIFIER_CACHE_ROOT="$(python3 -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$VERIFIER_CACHE_ROOT")" + VERIFIER_SOURCE="$VERIFIER_CACHE_ROOT/$VERIFIER_SHA" + if [[ ! -d "$VERIFIER_SOURCE/.git" ]]; then + if [[ -e "$VERIFIER_SOURCE" && ! -d "$VERIFIER_SOURCE" ]]; then + echo "refusing invalid pulsar-verifier cache path: $VERIFIER_SOURCE" >&2 + exit 1 + fi + mkdir -p "$VERIFIER_SOURCE" + git -C "$VERIFIER_SOURCE" init --quiet + fi + if ! git -C "$VERIFIER_SOURCE" cat-file -e "${VERIFIER_SHA}^{commit}" 2>/dev/null; then + echo "==> Downloading pinned pulsar-verifier source" + git -C "$VERIFIER_SOURCE" fetch --depth 1 "$VERIFIER_REPOSITORY" "$VERIFIER_SHA" + fi + elif [[ ! -d "$VERIFIER_SOURCE/.git" ]]; then + echo "pulsar-verifier checkout not found at: $VERIFIER_SOURCE" >&2 + exit 1 + fi + VERIFIER_SOURCE="$(cd -- "$VERIFIER_SOURCE" && pwd)" + git -C "$VERIFIER_SOURCE" cat-file -e "${VERIFIER_SHA}^{commit}" +fi + detect_running_lightnet -echo "==> 1/5 Removing previous Pulsar and archive-wrapper state" +echo "==> 1/6 Removing previous Pulsar and archive-wrapper state" if (( REUSE_LIGHTNET == 1 )); then echo " preserving running owned Lightnet container: $LIGHTNET_CONTAINER" else @@ -355,9 +400,9 @@ cleanup_selected_project cleanup_owned_stale_lightnet if (( REUSE_LIGHTNET == 1 )); then - echo "==> 2/5 Reusing running Mina Lightnet with archive PostgreSQL" + echo "==> 2/6 Reusing running Mina Lightnet with archive PostgreSQL" else - echo "==> 2/5 Starting Mina Lightnet with archive PostgreSQL" + echo "==> 2/6 Starting Mina Lightnet with archive PostgreSQL" docker run -d \ --name "$LIGHTNET_CONTAINER" \ --label "${LIGHTNET_OWNERSHIP_LABEL}=${LIGHTNET_OWNERSHIP_VALUE}" \ @@ -376,7 +421,7 @@ fi wait_for_lightnet_archive -echo "==> 3/5 Installing the blocks_inserted LISTEN/NOTIFY trigger" +echo "==> 3/6 Installing the blocks_inserted LISTEN/NOTIFY trigger" install_notification_trigger trigger_exists="$(docker exec "$LIGHTNET_CONTAINER" \ @@ -387,7 +432,7 @@ if [[ "$trigger_exists" != "t" ]]; then exit 1 fi -echo "==> 4/5 Building the shared archive-wrapper image" +echo "==> 4/6 Building the shared archive-wrapper image" git -C "$WRAPPER_SOURCE" archive "$WRAPPER_SHA" | docker buildx build \ --load \ @@ -396,6 +441,20 @@ git -C "$WRAPPER_SOURCE" archive "$WRAPPER_SHA" | -t "$WRAPPER_IMAGE" \ - +if [[ "$ENABLE_VERIFIER_SIDECARS" == "1" ]]; then + echo "==> 5/6 Building the pulsar-verifier image" + # TODO: Build the verifier for DOCKER_PLATFORM when a pinned + # Barretenberg arm64 artifact is available; it currently requires amd64. + git -C "$VERIFIER_SOURCE" archive "$VERIFIER_SHA" | + docker buildx build \ + --load \ + --platform linux/amd64 \ + -t "$VERIFIER_IMAGE" \ + - +else + echo "==> 5/6 Verifier sidecars disabled" +fi + PG_USER="$(docker exec "$LIGHTNET_CONTAINER" printenv POSTGRES_USER)" PG_PASSWORD="$(docker exec "$LIGHTNET_CONTAINER" printenv POSTGRES_PASSWORD)" PG_DB="$(docker exec "$LIGHTNET_CONTAINER" printenv POSTGRES_DB)" @@ -414,6 +473,11 @@ export ARCHIVE_WRAPPER_MODE="shared" export ARCHIVE_WRAPPER_IMAGE="$WRAPPER_IMAGE" export ARCHIVE_WRAPPER_ADD_HOST_GATEWAY=1 export PULSAR_DOCKER_IMAGE="$PULSAR_IMAGE" +if [[ "$ENABLE_VERIFIER_SIDECARS" == "1" ]]; then + export PULSAR_VERIFIER_IMAGE="$VERIFIER_IMAGE" +else + unset PULSAR_VERIFIER_IMAGE +fi export PULSAR_DOCKER_PROJECT="$PROJECT_NAME" export PULSAR_DOCKER_STATE_ROOT="$STATE_ROOT" export PULSAR_BIND_HOST="127.0.0.1" @@ -423,7 +487,11 @@ export BRIDGE_START_BLOCK_HEIGHT export BRIDGE_MAX_BLOCK_RANGE export VALIDATOR_STARTUP_TIMEOUT -echo "==> 5/5 Starting Pulsar with $VALIDATOR_COUNT validators" +if [[ "$ENABLE_VERIFIER_SIDECARS" == "1" ]]; then + echo "==> 6/6 Starting Pulsar with $VALIDATOR_COUNT validators and verifier sidecars" +else + echo "==> 6/6 Starting Pulsar with $VALIDATOR_COUNT validators" +fi "$SCRIPT_DIR/docker_testnet.sh" up "$VALIDATOR_COUNT" for ((index = 1; index <= VALIDATOR_COUNT; index++)); do diff --git a/scripts/devtools/auth_mode_tx.go b/scripts/devtools/auth_mode_tx.go new file mode 100644 index 00000000..6aa2c0b7 --- /dev/null +++ b/scripts/devtools/auth_mode_tx.go @@ -0,0 +1,345 @@ +package main + +import ( + "bytes" + "context" + stdlibed25519 "crypto/ed25519" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "math" + "time" + + "github.com/bronlabs/bron-crypto/pkg/signatures/schnorrlike/mina" + "github.com/cosmos/cosmos-sdk/client" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + sdk "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" + signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" + authcodec "github.com/cosmos/cosmos-sdk/x/auth/codec" + authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + gogoproto "github.com/cosmos/gogoproto/proto" + minafield "github.com/node101-io/mina-signer-go/field" + "github.com/node101-io/mina-signer-go/poseidon" + "github.com/node101-io/mina-signer-go/privatekey" + antetypes "github.com/node101-io/pulsar-chain/app/ante/types" + keyregistrytypes "github.com/node101-io/pulsar-chain/x/keyregistry/types" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +const ( + minaTxSigningChallengePrefix = "pulsar-tx-auth-v1" + minaTxSigningChallengeVersion = byte(1) +) + +type minaRegistrationMaterial struct { + MinaPublicKey string `json:"mina_public_key"` + MinaSignature string `json:"mina_signature"` +} + +func runDeriveEd25519Pub(args []string, stdout io.Writer) error { + if len(args) != 1 { + return errors.New("usage: devtools derive-ed25519-pub ") + } + privateKeyBytes, err := decodeHexOrBase64(args[0]) + if err != nil { + return fmt.Errorf("decode Ed25519 private key: %w", err) + } + + var privateKey stdlibed25519.PrivateKey + switch len(privateKeyBytes) { + case stdlibed25519.SeedSize: + privateKey = stdlibed25519.NewKeyFromSeed(privateKeyBytes) + case stdlibed25519.PrivateKeySize: + privateKey = stdlibed25519.PrivateKey(privateKeyBytes) + default: + return fmt.Errorf( + "invalid Ed25519 private key length: got %d bytes, want %d-byte seed or %d-byte private key", + len(privateKeyBytes), + stdlibed25519.SeedSize, + stdlibed25519.PrivateKeySize, + ) + } + + publicKey := privateKey.Public().(stdlibed25519.PublicKey) + _, err = fmt.Fprintln(stdout, hex.EncodeToString(publicKey)) + return err +} + +func runMinaRegistrationMaterial(args []string, stdout io.Writer) error { + fs := flag.NewFlagSet("mina-registration-material", flag.ContinueOnError) + fs.SetOutput(io.Discard) + chainID := fs.String("chain-id", "", "chain ID") + cosmosPublicKeyValue := fs.String("cosmos-public-key", "", "Cosmos public key in hex or base64") + minaPrivateKeyValue := fs.String("mina-private-key", "", "Mina private key in hex or base64") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() != 0 || *chainID == "" || *cosmosPublicKeyValue == "" || *minaPrivateKeyValue == "" { + return errors.New("--chain-id, --cosmos-public-key, and --mina-private-key are required") + } + + cosmosPublicKey, err := decodeHexOrBase64(*cosmosPublicKeyValue) + if err != nil { + return fmt.Errorf("decode --cosmos-public-key: %w", err) + } + minaPrivateKey, err := parseMinaPrivateKey(*minaPrivateKeyValue) + if err != nil { + return err + } + minaPublicKey, err := minaPrivateKey.ToPublicKey() + if err != nil { + return fmt.Errorf("derive Mina public key: %w", err) + } + minaPublicKeyBytes := minaPublicKey.Bytes() + + challenge, err := keyregistrytypes.BuildKeySigningChallenge(keyregistrytypes.KeySigningChallengeInput{ + ChainID: *chainID, + Operation: keyregistrytypes.KeySigningOperation_KEY_SIGNING_OPERATION_REGISTER, + ActorType: keyregistrytypes.ActorType_ACTOR_TYPE_USER, + CosmosPublicKey: cosmosPublicKey, + NewMinaPublicKey: minaPublicKeyBytes, + }) + if err != nil { + return fmt.Errorf("build Mina registration challenge: %w", err) + } + minaSignature, err := minaPrivateKey.SignFieldElement(challenge) + if err != nil { + return fmt.Errorf("sign Mina registration challenge: %w", err) + } + + return json.NewEncoder(stdout).Encode(minaRegistrationMaterial{ + MinaPublicKey: hex.EncodeToString(minaPublicKeyBytes), + MinaSignature: hex.EncodeToString(minaSignature.Bytes()), + }) +} + +func runSendMinaAuthModeTx(args []string, stdout io.Writer) error { + fs := flag.NewFlagSet("send-mina-auth-mode-tx", flag.ContinueOnError) + fs.SetOutput(io.Discard) + grpcAddr := fs.String("grpc-addr", "127.0.0.1:9090", "chain gRPC endpoint") + chainID := fs.String("chain-id", "mytestnet", "chain ID") + from := fs.String("from", "", "sender account address") + to := fs.String("to", "", "recipient account address") + minaPrivateKeyValue := fs.String("mina-private-key", "", "Mina private key in hex or base64") + amountValue := fs.String("amount", "1pmina", "amount to send") + feeValue := fs.String("fees", "100pmina", "transaction fees") + gas := fs.Uint64("gas", 200000, "gas limit") + timeout := fs.Duration("timeout", 30*time.Second, "query and inclusion timeout") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() != 0 || *from == "" || *to == "" || *minaPrivateKeyValue == "" { + return errors.New("--from, --to, and --mina-private-key are required") + } + if *chainID == "" || *grpcAddr == "" || *gas == 0 || *timeout <= 0 { + return errors.New("--chain-id, --grpc-addr, --gas, and --timeout must be non-zero") + } + + addressCodec := authcodec.NewBech32Codec(pulsarAccountPrefix) + if _, err := addressCodec.StringToBytes(*from); err != nil { + return fmt.Errorf("invalid --from address: %w", err) + } + if _, err := addressCodec.StringToBytes(*to); err != nil { + return fmt.Errorf("invalid --to address: %w", err) + } + minaPrivateKey, err := parseMinaPrivateKey(*minaPrivateKeyValue) + if err != nil { + return err + } + amount, err := sdk.ParseCoinsNormalized(*amountValue) + if err != nil || amount.Empty() || !amount.IsAllPositive() { + return fmt.Errorf("invalid --amount %q", *amountValue) + } + fees, err := sdk.ParseCoinsNormalized(*feeValue) + if err != nil || !fees.IsValid() || fees.IsAnyNegative() { + return fmt.Errorf("invalid --fees %q", *feeValue) + } + + txConfig, err := newSmartAccountTxConfig(addressCodec) + if err != nil { + return err + } + conn, err := grpc.NewClient(*grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return fmt.Errorf("create gRPC client for %s: %w", *grpcAddr, err) + } + defer conn.Close() + + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + accountResponse, err := authtypes.NewQueryClient(conn).AccountInfo(ctx, &authtypes.QueryAccountInfoRequest{Address: *from}) + if err != nil { + return fmt.Errorf("query account %s: %w", *from, err) + } + account := accountResponse.GetInfo() + if account == nil { + return fmt.Errorf("account query returned no account info for %s", *from) + } + if account.PubKey == nil || account.PubKey.TypeUrl != "/cosmos.crypto.secp256k1.PubKey" { + return fmt.Errorf("account %s has no Cosmos public key", *from) + } + cosmosPublicKey := &secp256k1.PubKey{} + if err := gogoproto.Unmarshal(account.PubKey.Value, cosmosPublicKey); err != nil { + return fmt.Errorf("decode Cosmos public key for %s: %w", *from, err) + } + + txBuilder := txConfig.NewTxBuilder() + if err := txBuilder.SetMsgs(&banktypes.MsgSend{ + FromAddress: *from, + ToAddress: *to, + Amount: amount, + }); err != nil { + return fmt.Errorf("set MsgSend: %w", err) + } + txBuilder.SetFeeAmount(fees) + txBuilder.SetGasLimit(*gas) + + extendedBuilder, ok := txBuilder.(client.ExtendedTxBuilder) + if !ok { + return errors.New("tx builder does not support extension options") + } + extensionBytes, err := gogoproto.Marshal(&antetypes.TxAuthModeExtension{ + TxAuthMode: antetypes.TX_AUTH_MODE_MINA, + }) + if err != nil { + return fmt.Errorf("marshal Mina auth extension: %w", err) + } + extendedBuilder.SetExtensionOptions(&codectypes.Any{ + TypeUrl: "/" + gogoproto.MessageName(&antetypes.TxAuthModeExtension{}), + Value: extensionBytes, + }) + + signMode := signingtypes.SignMode_SIGN_MODE_DIRECT + placeholder := signingtypes.SignatureV2{ + PubKey: cosmosPublicKey, + Data: &signingtypes.SingleSignatureData{SignMode: signMode}, + Sequence: account.Sequence, + } + if err := txBuilder.SetSignatures(placeholder); err != nil { + return fmt.Errorf("set placeholder signature: %w", err) + } + signBytes, err := authsigning.GetSignBytesAdapter( + ctx, + txConfig.SignModeHandler(), + signMode, + authsigning.SignerData{ + Address: *from, + ChainID: *chainID, + AccountNumber: account.AccountNumber, + Sequence: account.Sequence, + }, + txBuilder.GetTx(), + ) + if err != nil { + return fmt.Errorf("build Mina sign bytes: %w", err) + } + challenge, err := buildMinaTxSigningChallenge(signBytes) + if err != nil { + return err + } + minaSignature, err := minaPrivateKey.SignFieldElement(challenge) + if err != nil { + return fmt.Errorf("sign Mina transaction challenge: %w", err) + } + if err := txBuilder.SetSignatures(signingtypes.SignatureV2{ + PubKey: cosmosPublicKey, + Data: &signingtypes.SingleSignatureData{ + SignMode: signMode, + Signature: minaSignature.Bytes(), + }, + Sequence: account.Sequence, + }); err != nil { + return fmt.Errorf("set Mina signature: %w", err) + } + + txBytes, err := txConfig.TxEncoder()(txBuilder.GetTx()) + if err != nil { + return fmt.Errorf("encode Mina transaction: %w", err) + } + broadcastResponse, err := txtypes.NewServiceClient(conn).BroadcastTx(ctx, &txtypes.BroadcastTxRequest{ + TxBytes: txBytes, + Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, + }) + if err != nil { + return fmt.Errorf("broadcast Mina transaction: %w", err) + } + checkTx := broadcastResponse.GetTxResponse() + if checkTx == nil { + return errors.New("broadcast returned no transaction response") + } + if checkTx.Code != 0 { + return fmt.Errorf("CheckTx rejected Mina transaction (codespace=%s code=%d): %s", checkTx.Codespace, checkTx.Code, checkTx.RawLog) + } + + for { + included, queryErr := txtypes.NewServiceClient(conn).GetTx(ctx, &txtypes.GetTxRequest{Hash: checkTx.TxHash}) + if queryErr == nil && included.GetTxResponse() != nil { + response := included.GetTxResponse() + if response.Code != 0 { + return fmt.Errorf("DeliverTx failed (tx_hash=%s codespace=%s code=%d): %s", response.TxHash, response.Codespace, response.Code, response.RawLog) + } + return writeSmartAccountTxResult(stdout, response) + } + if queryErr != nil && status.Code(queryErr) != codes.NotFound { + return fmt.Errorf("query Mina transaction %s: %w", checkTx.TxHash, queryErr) + } + select { + case <-ctx.Done(): + return fmt.Errorf("Mina transaction %s was not included before timeout: %w", checkTx.TxHash, ctx.Err()) + case <-time.After(500 * time.Millisecond): + } + } +} + +func parseMinaPrivateKey(value string) (*privatekey.PrivateKey, error) { + keyBytes, err := decodeHexOrBase64(value) + if err != nil { + return nil, fmt.Errorf("decode Mina private key: %w", err) + } + if len(keyBytes) != privatekey.Size() { + return nil, fmt.Errorf("invalid Mina private key length: got %d bytes, want %d", len(keyBytes), privatekey.Size()) + } + var rawPrivateKey [32]byte + copy(rawPrivateKey[:], keyBytes) + key, err := privatekey.NewPrivateKeyFromBytes(rawPrivateKey, mina.TestNet) + if err != nil { + return nil, fmt.Errorf("parse Mina private key: %w", err) + } + return key, nil +} + +func buildMinaTxSigningChallenge(signBytes []byte) (*minafield.FieldElement, error) { + if len(signBytes) == 0 { + return nil, errors.New("empty Mina transaction sign bytes") + } + if len(signBytes) > math.MaxUint32 { + return nil, errors.New("Mina transaction sign bytes exceed uint32 framing") + } + + payload := bytes.NewBuffer(make([]byte, 0, 5+len(signBytes))) + payload.WriteByte(minaTxSigningChallengeVersion) + var length [4]byte + binary.BigEndian.PutUint32(length[:], uint32(len(signBytes))) + payload.Write(length[:]) + payload.Write(signBytes) + hash, err := poseidon.NewPoseidon().HashWithPrefix(minaTxSigningChallengePrefix, payload.Bytes()) + if err != nil { + return nil, fmt.Errorf("hash Mina transaction challenge: %w", err) + } + challenge, err := minafield.NewFieldElement(hash) + if err != nil { + return nil, fmt.Errorf("decode Mina transaction challenge: %w", err) + } + return challenge, nil +} diff --git a/scripts/devtools/main.go b/scripts/devtools/main.go index 7c742967..d36de2fc 100644 --- a/scripts/devtools/main.go +++ b/scripts/devtools/main.go @@ -53,6 +53,26 @@ func run(args []string, stdout, stderr io.Writer) int { fmt.Fprintf(stderr, "error: %v\n", err) return 1 } + case "send-smart-account-tx": + if err := runSendSmartAccountTx(args[1:], stdout); err != nil { + fmt.Fprintf(stderr, "error: %v\n", err) + return 1 + } + case "mina-registration-material": + if err := runMinaRegistrationMaterial(args[1:], stdout); err != nil { + fmt.Fprintf(stderr, "error: %v\n", err) + return 1 + } + case "send-mina-auth-mode-tx": + if err := runSendMinaAuthModeTx(args[1:], stdout); err != nil { + fmt.Fprintf(stderr, "error: %v\n", err) + return 1 + } + case "derive-ed25519-pub": + if err := runDeriveEd25519Pub(args[1:], stdout); err != nil { + fmt.Fprintf(stderr, "error: %v\n", err) + return 1 + } case "-h", "--help", "help": printUsage(stdout) default: @@ -71,6 +91,10 @@ func printUsage(out io.Writer) { fmt.Fprintln(out, " derive-mina-pub ") fmt.Fprintln(out, " verify-vote-extensions [--grpc-addr addr] [--network-id id] [--timeout duration]") fmt.Fprintln(out, " query-archive-wrapper --address addr --transport-mode mode --latest height --target height") + fmt.Fprintln(out, " send-smart-account-tx --from addr --to addr --identity value --session-key-file path [flags]") + fmt.Fprintln(out, " mina-registration-material --chain-id id --cosmos-public-key value --mina-private-key value") + fmt.Fprintln(out, " send-mina-auth-mode-tx --from addr --to addr --mina-private-key value [flags]") + fmt.Fprintln(out, " derive-ed25519-pub ") } func runQueryArchiveWrapper(args []string, stdout io.Writer) error { diff --git a/scripts/devtools/smart_account_tx.go b/scripts/devtools/smart_account_tx.go new file mode 100644 index 00000000..be6e742a --- /dev/null +++ b/scripts/devtools/smart_account_tx.go @@ -0,0 +1,322 @@ +package main + +import ( + "context" + stdlibed25519 "crypto/ed25519" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + "time" + + "cosmossdk.io/core/address" + txsigning "cosmossdk.io/x/tx/signing" + "github.com/cosmos/cosmos-sdk/client" + clienttx "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + "github.com/cosmos/cosmos-sdk/std" + sdk "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" + signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" + "github.com/cosmos/cosmos-sdk/x/auth" + authcodec "github.com/cosmos/cosmos-sdk/x/auth/codec" + authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + gogoproto "github.com/cosmos/gogoproto/proto" + appante "github.com/node101-io/pulsar-chain/app/ante" + antetypes "github.com/node101-io/pulsar-chain/app/ante/types" + smartaccountstypes "github.com/node101-io/pulsar-chain/x/smartaccounts/types" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +const pulsarAccountPrefix = "pulsar" + +type smartAccountTxResult struct { + TxHash string `json:"tx_hash"` + Height int64 `json:"height"` + Code uint32 `json:"code"` + Codespace string `json:"codespace,omitempty"` + RawLog string `json:"raw_log,omitempty"` + GasWanted int64 `json:"gas_wanted"` + GasUsed int64 `json:"gas_used"` +} + +func runSendSmartAccountTx(args []string, stdout io.Writer) error { + fs := flag.NewFlagSet("send-smart-account-tx", flag.ContinueOnError) + fs.SetOutput(stdout) + grpcAddr := fs.String("grpc-addr", "127.0.0.1:9090", "Pulsar gRPC endpoint") + chainID := fs.String("chain-id", "mytestnet", "Pulsar chain id") + from := fs.String("from", "", "smart account's canonical Pulsar account address") + to := fs.String("to", "", "recipient Pulsar account address") + identityValue := fs.String("identity", "", "32-byte smart account identity, encoded as hex or base64") + sessionKeyFile := fs.String("session-key-file", "", "file containing a 32-byte Ed25519 seed or 64-byte private key, encoded as hex or base64") + amountValue := fs.String("amount", "1pmina", "coins to send") + feeValue := fs.String("fees", "100pmina", "transaction fees") + gas := fs.Uint64("gas", 200000, "transaction gas limit") + memo := fs.String("memo", "smart-account-local-test", "transaction memo") + wait := fs.Bool("wait", true, "wait for the transaction to be included in a block") + timeout := fs.Duration("timeout", 30*time.Second, "query, broadcast, and inclusion timeout") + if err := fs.Parse(args); err != nil { + if err == flag.ErrHelp { + return nil + } + return err + } + if fs.NArg() != 0 { + return fmt.Errorf("unexpected positional arguments: %s", strings.Join(fs.Args(), " ")) + } + if *from == "" || *to == "" || *identityValue == "" || *sessionKeyFile == "" { + return errors.New("--from, --to, --identity, and --session-key-file are required") + } + if *chainID == "" || *grpcAddr == "" || *gas == 0 || *timeout <= 0 { + return errors.New("--chain-id, --grpc-addr, --gas, and --timeout must be non-zero") + } + + addressCodec := authcodec.NewBech32Codec(pulsarAccountPrefix) + if _, err := addressCodec.StringToBytes(*from); err != nil { + return fmt.Errorf("invalid --from address: %w", err) + } + if _, err := addressCodec.StringToBytes(*to); err != nil { + return fmt.Errorf("invalid --to address: %w", err) + } + + identity, err := decodeHexOrBase64(*identityValue) + if err != nil { + return fmt.Errorf("decode --identity: %w", err) + } + if len(identity) != smartaccountstypes.IdentitySize { + return fmt.Errorf("invalid identity length: got %d bytes, want %d", len(identity), smartaccountstypes.IdentitySize) + } + + sessionPrivateKey, err := readSessionPrivateKey(*sessionKeyFile) + if err != nil { + return err + } + + amount, err := sdk.ParseCoinsNormalized(*amountValue) + if err != nil { + return fmt.Errorf("invalid --amount %q: %w", *amountValue, err) + } + if amount.Empty() || !amount.IsAllPositive() { + return fmt.Errorf("invalid --amount %q: amount must contain positive coins", *amountValue) + } + fees, err := sdk.ParseCoinsNormalized(*feeValue) + if err != nil { + return fmt.Errorf("invalid --fees %q: %w", *feeValue, err) + } + if !fees.IsValid() || fees.IsAnyNegative() { + return fmt.Errorf("invalid --fees %q: fees must contain non-negative valid coins", *feeValue) + } + + txConfig, err := newSmartAccountTxConfig(addressCodec) + if err != nil { + return err + } + + conn, err := grpc.NewClient(*grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return fmt.Errorf("create gRPC client for %s: %w", *grpcAddr, err) + } + defer conn.Close() + + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + + accountResponse, err := authtypes.NewQueryClient(conn).AccountInfo(ctx, &authtypes.QueryAccountInfoRequest{ + Address: *from, + }) + if err != nil { + return fmt.Errorf("query account %s: %w", *from, err) + } + account := accountResponse.GetInfo() + if account == nil { + return fmt.Errorf("account query returned no account info for %s", *from) + } + + txBuilder := txConfig.NewTxBuilder() + if err := txBuilder.SetMsgs(&banktypes.MsgSend{ + FromAddress: *from, + ToAddress: *to, + Amount: amount, + }); err != nil { + return fmt.Errorf("set MsgSend: %w", err) + } + txBuilder.SetFeeAmount(fees) + txBuilder.SetGasLimit(*gas) + txBuilder.SetMemo(*memo) + + extendedBuilder, ok := txBuilder.(client.ExtendedTxBuilder) + if !ok { + return errors.New("tx builder does not support extension options") + } + extension := &antetypes.TxAuthModeExtension{ + TxAuthMode: antetypes.TX_AUTH_MODE_SMART_ACCOUNT, + SmartAccountIdentity: identity, + } + extensionBytes, err := gogoproto.Marshal(extension) + if err != nil { + return fmt.Errorf("marshal smart account auth extension: %w", err) + } + extendedBuilder.SetExtensionOptions(&codectypes.Any{ + TypeUrl: "/" + gogoproto.MessageName(extension), + Value: extensionBytes, + }) + + placeholder := signingtypes.SignatureV2{ + PubKey: sessionPrivateKey.PubKey(), + Data: &signingtypes.SingleSignatureData{ + SignMode: signingtypes.SignMode_SIGN_MODE_DIRECT, + }, + Sequence: account.Sequence, + } + if err := txBuilder.SetSignatures(placeholder); err != nil { + return fmt.Errorf("set placeholder signature: %w", err) + } + + signature, err := clienttx.SignWithPrivKey( + ctx, + signingtypes.SignMode_SIGN_MODE_DIRECT, + authsigning.SignerData{ + Address: *from, + ChainID: *chainID, + AccountNumber: account.AccountNumber, + Sequence: account.Sequence, + }, + txBuilder, + sessionPrivateKey, + txConfig, + account.Sequence, + ) + if err != nil { + return fmt.Errorf("sign smart account transaction: %w", err) + } + if err := txBuilder.SetSignatures(signature); err != nil { + return fmt.Errorf("set signed transaction signature: %w", err) + } + + txBytes, err := txConfig.TxEncoder()(txBuilder.GetTx()) + if err != nil { + return fmt.Errorf("encode signed transaction: %w", err) + } + + txClient := txtypes.NewServiceClient(conn) + broadcastResponse, err := txClient.BroadcastTx(ctx, &txtypes.BroadcastTxRequest{ + TxBytes: txBytes, + Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, + }) + if err != nil { + return fmt.Errorf("broadcast transaction: %w", err) + } + checkTx := broadcastResponse.GetTxResponse() + if checkTx == nil { + return errors.New("broadcast returned no transaction response") + } + if checkTx.Code != 0 { + return fmt.Errorf("CheckTx rejected transaction (codespace=%s code=%d): %s", checkTx.Codespace, checkTx.Code, checkTx.RawLog) + } + if !*wait { + return writeSmartAccountTxResult(stdout, checkTx) + } + + for { + included, queryErr := txClient.GetTx(ctx, &txtypes.GetTxRequest{Hash: checkTx.TxHash}) + if queryErr == nil && included.GetTxResponse() != nil { + response := included.GetTxResponse() + if response.Code != 0 { + return fmt.Errorf("DeliverTx failed (tx_hash=%s codespace=%s code=%d): %s", response.TxHash, response.Codespace, response.Code, response.RawLog) + } + return writeSmartAccountTxResult(stdout, response) + } + if queryErr != nil && status.Code(queryErr) != codes.NotFound { + return fmt.Errorf("query transaction %s: %w", checkTx.TxHash, queryErr) + } + + select { + case <-ctx.Done(): + return fmt.Errorf("transaction %s passed CheckTx but was not found before timeout: %w", checkTx.TxHash, ctx.Err()) + case <-time.After(500 * time.Millisecond): + } + } +} + +func newSmartAccountTxConfig(addressCodec address.Codec) (client.TxConfig, error) { + interfaceRegistry, err := codectypes.NewInterfaceRegistryWithOptions(codectypes.InterfaceRegistryOptions{ + ProtoFiles: gogoproto.HybridResolver, + SigningOptions: txsigning.Options{ + AddressCodec: addressCodec, + ValidatorAddressCodec: authcodec.NewBech32Codec(pulsarAccountPrefix + "valoper"), + }, + }) + if err != nil { + return nil, fmt.Errorf("create interface registry: %w", err) + } + std.RegisterInterfaces(interfaceRegistry) + auth.AppModuleBasic{}.RegisterInterfaces(interfaceRegistry) + banktypes.RegisterInterfaces(interfaceRegistry) + appante.RegisterInterfaces(interfaceRegistry) + + return authtx.NewTxConfig(codec.NewProtoCodec(interfaceRegistry), authtx.DefaultSignModes), nil +} + +func readSessionPrivateKey(path string) (*ed25519.PrivKey, error) { + encoded, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("read --session-key-file: %w", err) + } + keyBytes, err := decodeHexOrBase64(string(encoded)) + if err != nil { + return nil, fmt.Errorf("decode --session-key-file: %w", err) + } + + switch len(keyBytes) { + case ed25519.SeedSize: + return &ed25519.PrivKey{Key: stdlibed25519.NewKeyFromSeed(keyBytes)}, nil + case ed25519.PrivKeySize: + seedDerived := stdlibed25519.NewKeyFromSeed(keyBytes[:ed25519.SeedSize]) + if !stdlibed25519.PrivateKey(keyBytes).Equal(seedDerived) { + return nil, errors.New("64-byte session private key contains a public-key suffix that does not match its seed") + } + return &ed25519.PrivKey{Key: append([]byte(nil), keyBytes...)}, nil + default: + return nil, fmt.Errorf("invalid session private key length: got %d bytes, want %d-byte seed or %d-byte private key", len(keyBytes), ed25519.SeedSize, ed25519.PrivKeySize) + } +} + +func decodeHexOrBase64(value string) ([]byte, error) { + value = strings.TrimSpace(value) + if value == "" { + return nil, errors.New("value is empty") + } + hexValue := strings.TrimPrefix(value, "0x") + if decoded, err := hex.DecodeString(hexValue); err == nil { + return decoded, nil + } + if decoded, err := base64.StdEncoding.DecodeString(value); err == nil { + return decoded, nil + } + return nil, errors.New("value is neither valid hex nor standard base64") +} + +func writeSmartAccountTxResult(out io.Writer, txResponse *sdk.TxResponse) error { + return json.NewEncoder(out).Encode(smartAccountTxResult{ + TxHash: txResponse.TxHash, + Height: txResponse.Height, + Code: txResponse.Code, + Codespace: txResponse.Codespace, + RawLog: txResponse.RawLog, + GasWanted: txResponse.GasWanted, + GasUsed: txResponse.GasUsed, + }) +} diff --git a/scripts/docker_testnet.sh b/scripts/docker_testnet.sh index 72e17183..cd9757fa 100755 --- a/scripts/docker_testnet.sh +++ b/scripts/docker_testnet.sh @@ -200,12 +200,11 @@ run_compose() { docker compose --project-name "$PROJECT_NAME" -f "$COMPOSE_FILE" "$@" } -declare -a VALIDATOR_SERVICES=() -declare -a VERIFIER_SERVICES=() +declare -a START_SERVICES=() for ((i = 1; i <= VALIDATOR_COUNT; i++)); do - VALIDATOR_SERVICES+=("validator${i}") + START_SERVICES+=("validator${i}") if [[ -n "${PULSAR_VERIFIER_IMAGE:-}" ]]; then - VERIFIER_SERVICES+=("verifier${i}") + START_SERVICES+=("verifier${i}") fi done @@ -226,7 +225,7 @@ case "$COMMAND" in fi if ! run_compose up --no-build -d --wait \ --wait-timeout "$VALIDATOR_STARTUP_TIMEOUT" \ - "${VALIDATOR_SERVICES[@]}" "${VERIFIER_SERVICES[@]}"; then + "${START_SERVICES[@]}"; then cleanup_partial_environment exit 1 fi diff --git a/scripts/generate_smart_account_noir_fixture.sh b/scripts/generate_smart_account_noir_fixture.sh new file mode 100755 index 00000000..2427d6ba --- /dev/null +++ b/scripts/generate_smart_account_noir_fixture.sh @@ -0,0 +1,317 @@ +#!/usr/bin/env bash + +set -Eeuo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/.." && pwd)" +CIRCUIT_DIR="$REPO_ROOT/testdata/smartaccounts/noir/bb-5.2.0" +TOOL_CACHE="${SMART_ACCOUNT_TOOL_CACHE:-$REPO_ROOT/.cache/smartaccounts}" +NARGO_VERSION="1.0.0-beta.25" +BB_VERSION="5.2.0" +BN254_MODULUS="21888242871839275222246405745257275088548364400416034343698204186575808495617" +EXPECTED_VK_HASH="1feb48cba9a74abcc6639cc79d49dc8e81ed9f4e791c371bdf6a5aa04b296eeb" + +usage() { + cat <<'EOF' +usage: scripts/generate_smart_account_noir_fixture.sh \ + --output-dir DIR \ + --session-private-key HEX \ + --session-public-key HEX \ + --expires-at-height UINT64 \ + --identity HEX \ + --account-address HEX + +Generates proof, public_inputs, and vk for the local smart-account E2E circuit. +Pinned Nargo and Barretenberg binaries are downloaded into a gitignored cache +when SMART_ACCOUNT_NARGO_BIN and SMART_ACCOUNT_BB_BIN are not provided. +EOF +} + +fail() { + echo "error: $*" >&2 + exit 1 +} + +require_cmd() { + if ! command -v "$1" >/dev/null 2>&1; then + fail "missing required command: $1" + fi +} + +OUTPUT_DIR="" +SESSION_PRIVATE_KEY="" +SESSION_PUBLIC_KEY="" +EXPIRES_AT_HEIGHT="" +IDENTITY="" +ACCOUNT_ADDRESS="" + +while (( $# > 0 )); do + case "$1" in + --output-dir) OUTPUT_DIR="${2:-}"; shift 2 ;; + --session-private-key) SESSION_PRIVATE_KEY="${2:-}"; shift 2 ;; + --session-public-key) SESSION_PUBLIC_KEY="${2:-}"; shift 2 ;; + --expires-at-height) EXPIRES_AT_HEIGHT="${2:-}"; shift 2 ;; + --identity) IDENTITY="${2:-}"; shift 2 ;; + --account-address) ACCOUNT_ADDRESS="${2:-}"; shift 2 ;; + -h | --help) usage; exit 0 ;; + *) usage >&2; fail "unknown argument: $1" ;; + esac +done + +[[ -n "$OUTPUT_DIR" ]] || fail "--output-dir is required" +[[ -n "$SESSION_PRIVATE_KEY" ]] || fail "--session-private-key is required" +[[ -n "$SESSION_PUBLIC_KEY" ]] || fail "--session-public-key is required" +[[ -n "$EXPIRES_AT_HEIGHT" ]] || fail "--expires-at-height is required" +[[ -n "$IDENTITY" ]] || fail "--identity is required" +[[ -n "$ACCOUNT_ADDRESS" ]] || fail "--account-address is required" + +require_cmd curl +require_cmd python3 +require_cmd tar + +case "$(uname -s):$(uname -m)" in + Darwin:arm64 | Darwin:aarch64) + NARGO_ASSET="nargo-aarch64-apple-darwin.tar.gz" + NARGO_SHA256="63ed453d09a65bfc78eef63252423126959d41c85de0da0cf54289c5e266ceb5" + BB_ASSET="barretenberg-arm64-darwin.tar.gz" + BB_SHA256="54be7645c83ac762a38a696cfe0c1495223a4f931b82720bc9e2e47f9a43bf86" + ;; + Darwin:x86_64) + NARGO_ASSET="nargo-x86_64-apple-darwin.tar.gz" + NARGO_SHA256="660567c645f841389b1e37ddebd4f6c75417763018ea034e08b28338bf27673c" + BB_ASSET="barretenberg-amd64-darwin.tar.gz" + BB_SHA256="abf46d12a1a89ae7dc62cf1a84c82873696e1ee6cf925ce241402c0f45736b4b" + ;; + Linux:aarch64 | Linux:arm64) + NARGO_ASSET="nargo-aarch64-unknown-linux-gnu.tar.gz" + NARGO_SHA256="4e86553af99e87c047bae40f1315234709e8d815f6158f3b8a00bf68f512a2b7" + BB_ASSET="barretenberg-arm64-linux.tar.gz" + BB_SHA256="5bdc0552865428ea50d81f4da25b5aa372f45cce33baa0419cbddcd532bdbf30" + ;; + Linux:x86_64) + NARGO_ASSET="nargo-x86_64-unknown-linux-gnu.tar.gz" + NARGO_SHA256="bf3410ab94933a4aebd1f988b67ae974c6c227f9456ed0f1e4a3716bb8a30fe9" + BB_ASSET="barretenberg-amd64-linux.tar.gz" + BB_SHA256="17ab8476961728cdc5c69b6c4ff427c9092cef11d1e0b0166929a0417dfa7cfb" + ;; + *) fail "unsupported prover platform: $(uname -s) $(uname -m)" ;; +esac + +download_tool() { + local name="$1" + local version="$2" + local asset="$3" + local expected_sha256="$4" + local url="$5" + local destination="$TOOL_CACHE/$name-$version/$name" + + if [[ -x "$destination" ]]; then + printf '%s\n' "$destination" + return + fi + + local download_dir + download_dir="$(mktemp -d "${TMPDIR:-/tmp}/pulsar-$name.XXXXXX")" + local archive="$download_dir/$asset" + + echo "==> Downloading $name $version" >&2 + if ! curl --fail --location --retry 3 "$url" --output "$archive"; then + fail "failed to download $name $version" + fi + python3 - "$archive" "$expected_sha256" <<'PY' +import hashlib +import pathlib +import sys + +path = pathlib.Path(sys.argv[1]) +expected = sys.argv[2] +actual = hashlib.sha256(path.read_bytes()).hexdigest() +if actual != expected: + raise SystemExit(f"SHA-256 mismatch for {path.name}: got {actual}, want {expected}") +PY + + mkdir -p "$(dirname -- "$destination")" + if ! tar -xzf "$archive" -C "$(dirname -- "$destination")"; then + fail "failed to extract $name $version" + fi + [[ -x "$destination" ]] || fail "$name archive did not contain an executable named $name" + printf '%s\n' "$destination" +} + +NARGO_BIN="${SMART_ACCOUNT_NARGO_BIN:-}" +if [[ -z "$NARGO_BIN" ]]; then + NARGO_BIN="$(download_tool \ + nargo "$NARGO_VERSION" "$NARGO_ASSET" "$NARGO_SHA256" \ + "https://github.com/noir-lang/noir/releases/download/v${NARGO_VERSION}/${NARGO_ASSET}")" +fi + +BB_BIN="${SMART_ACCOUNT_BB_BIN:-}" +if [[ -z "$BB_BIN" ]]; then + BB_BIN="$(download_tool \ + bb "$BB_VERSION" "$BB_ASSET" "$BB_SHA256" \ + "https://github.com/AztecProtocol/aztec-packages/releases/download/v${BB_VERSION}/${BB_ASSET}")" +fi + +[[ -x "$NARGO_BIN" ]] || fail "Nargo binary is not executable: $NARGO_BIN" +[[ -x "$BB_BIN" ]] || fail "Barretenberg binary is not executable: $BB_BIN" +"$NARGO_BIN" --version | grep -F "$NARGO_VERSION" >/dev/null || \ + fail "Nargo must be version $NARGO_VERSION" +[[ "$("$BB_BIN" --version)" == "$BB_VERSION" ]] || \ + fail "Barretenberg must be version $BB_VERSION" + +python3 - \ + "$SESSION_PRIVATE_KEY" \ + "$SESSION_PUBLIC_KEY" \ + "$EXPIRES_AT_HEIGHT" \ + "$IDENTITY" \ + "$ACCOUNT_ADDRESS" \ + "$BN254_MODULUS" <<'PY' +import sys + +private_key_hex, public_key_hex, expiry_text, identity_hex, address_hex, modulus_text = sys.argv[1:] + +def decode(name, value, expected_length): + try: + decoded = bytes.fromhex(value) + except ValueError as error: + raise SystemExit(f"{name} is not valid hex: {error}") from error + if len(decoded) != expected_length: + raise SystemExit(f"{name} must be {expected_length} bytes, got {len(decoded)}") + return decoded + +decode("session private key", private_key_hex, 32) +public_key = decode("session public key", public_key_hex, 32) +identity = decode("identity", identity_hex, 32) +decode("account address", address_hex, 20) + +try: + expiry = int(expiry_text) +except ValueError as error: + raise SystemExit("expires-at-height must be an integer") from error +if not 0 < expiry < 2**64: + raise SystemExit("expires-at-height must be a non-zero uint64") + +modulus = int(modulus_text) +for name, value in (("session public key", public_key), ("identity", identity)): + if int.from_bytes(value, "big") >= modulus: + raise SystemExit(f"{name} is not a canonical BN254 field element") +PY + +WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pulsar-smart-account-proof.XXXXXX")" +trap 'rm -rf -- "$WORK_DIR"' EXIT +mkdir -p "$WORK_DIR/src" +cp "$CIRCUIT_DIR/Nargo.toml" "$WORK_DIR/" +cp "$CIRCUIT_DIR/src/main.nr" "$WORK_DIR/src/main.nr" + +python3 - \ + "$WORK_DIR/Prover.toml" \ + "$SESSION_PUBLIC_KEY" \ + "$EXPIRES_AT_HEIGHT" \ + "$IDENTITY" \ + "$ACCOUNT_ADDRESS" <<'PY' +import pathlib +import sys + +path, public_key, expiry, identity, address = sys.argv[1:] +pathlib.Path(path).write_text( + f'session_public_key = "0x{public_key}"\n' + f'expires_at_height = "{expiry}"\n' + f'identity = "0x{identity}"\n' + f'account_address = "0x{address}"\n' + 'witness = "1"\n', + encoding="utf-8", +) +PY + +echo "==> Executing the smart-account Noir circuit" +( + cd "$WORK_DIR" + "$NARGO_BIN" execute smart_account_witness +) + +mkdir -p "$WORK_DIR/generated" "$TOOL_CACHE/bb-crs" "$OUTPUT_DIR" +echo "==> Generating the UltraHonk proof and verification key" +"$BB_BIN" prove \ + -s ultra_honk \ + -b "$WORK_DIR/target/smart_account_e2e.json" \ + -w "$WORK_DIR/target/smart_account_witness.gz" \ + -o "$WORK_DIR/generated" \ + --write_vk \ + --oracle_hash poseidon2 \ + --crs_path "$TOOL_CACHE/bb-crs" + +"$BB_BIN" verify \ + -s ultra_honk \ + -p "$WORK_DIR/generated/proof" \ + -k "$WORK_DIR/generated/vk" \ + -i "$WORK_DIR/generated/public_inputs" \ + --oracle_hash poseidon2 \ + --crs_path "$TOOL_CACHE/bb-crs" + +ACTUAL_VK_HASH="$(python3 - "$WORK_DIR/generated/vk" <<'PY' +import hashlib +import pathlib +import sys + +print(hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest()) +PY +)" +if [[ "$ACTUAL_VK_HASH" != "$EXPECTED_VK_HASH" ]]; then + fail "generated verification-key hash is $ACTUAL_VK_HASH, expected $EXPECTED_VK_HASH" +fi + +python3 - \ + "$WORK_DIR/generated/public_inputs" \ + "$SESSION_PUBLIC_KEY" \ + "$EXPIRES_AT_HEIGHT" \ + "$IDENTITY" \ + "$ACCOUNT_ADDRESS" <<'PY' +import pathlib +import sys + +path, public_key, expiry_text, identity, address = sys.argv[1:] +expected = ( + bytes.fromhex(public_key) + + int(expiry_text).to_bytes(32, "big") + + bytes.fromhex(identity) + + bytes.fromhex(address).rjust(32, b"\0") +) +actual = pathlib.Path(path).read_bytes() +if actual != expected: + raise SystemExit( + "generated public_inputs do not match the smartaccounts wire encoding" + ) +PY + +install -m 0644 "$WORK_DIR/generated/proof" "$OUTPUT_DIR/proof" +install -m 0644 "$WORK_DIR/generated/public_inputs" "$OUTPUT_DIR/public_inputs" +install -m 0644 "$WORK_DIR/generated/vk" "$OUTPUT_DIR/vk" +printf '%s\n' "$SESSION_PRIVATE_KEY" >"$OUTPUT_DIR/session-key.hex" + +python3 - \ + "$OUTPUT_DIR/fixture.json" \ + "$IDENTITY" \ + "$SESSION_PUBLIC_KEY" \ + "$EXPIRES_AT_HEIGHT" \ + "$ACCOUNT_ADDRESS" <<'PY' +import json +import pathlib +import sys + +path, identity, public_key, expiry, account_address = sys.argv[1:] +pathlib.Path(path).write_text( + json.dumps( + { + "identity_hex": identity, + "session_public_key_hex": public_key, + "expires_at_height": int(expiry), + "account_address_hex": account_address, + }, + indent=2, + ) + + "\n", + encoding="utf-8", +) +PY + +echo "==> Smart-account Noir fixture generated in $OUTPUT_DIR" diff --git a/scripts/render_docker_testnet.py b/scripts/render_docker_testnet.py index 40253235..00b96913 100755 --- a/scripts/render_docker_testnet.py +++ b/scripts/render_docker_testnet.py @@ -175,6 +175,7 @@ def render_compose(args: argparse.Namespace) -> dict: "MAX_BLOCK_RANGE": "${BRIDGE_MAX_BLOCK_RANGE:-}", "E2E_USER_MINA_PRIV_KEY": "${E2E_USER_MINA_PRIV_KEY:-}", "MIN_GAS_PRICE": "${E2E_MIN_GAS_PRICE:-}", + "SMART_ACCOUNTS_VERIFICATION_KEY_HASH": "${SMART_ACCOUNTS_VERIFICATION_KEY_HASH:-}", "ENABLE_VERIFIER_SIDECARS": "1" if args.verifier_image else "0", } ) diff --git a/scripts/send_cosmos_auth_mode_tx.sh b/scripts/send_cosmos_auth_mode_tx.sh new file mode 100755 index 00000000..a69ea6b1 --- /dev/null +++ b/scripts/send_cosmos_auth_mode_tx.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash + +set -Eeuo pipefail + +PROJECT_NAME="${PULSAR_DOCKER_PROJECT:-pulsar-testnet-3}" +CONTAINER="${PULSAR_VALIDATOR_CONTAINER:-${PROJECT_NAME}-validator1-1}" +VALIDATOR_HOME="${PULSAR_VALIDATOR_HOME:-/testnet/.pulsar-node1}" +CHAIN_ID="${CHAIN_ID:-mytestnet}" +FROM_KEY="${AUTH_MODE_FROM_KEY:-validator1}" +RECIPIENT_KEY="${AUTH_MODE_RECIPIENT_KEY:-auth-mode-recipient}" +AMOUNT="${AUTH_MODE_SEND_AMOUNT:-1pmina}" +FEES="${AUTH_MODE_FEES:-100pmina}" +NODE="${PULSAR_NODE:-tcp://127.0.0.1:26657}" +MODE="TX_AUTH_MODE_COSMOS" + +WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pulsar-cosmos-auth.XXXXXX")" +trap 'rm -rf -- "$WORK_DIR"' EXIT + +docker inspect "$CONTAINER" >/dev/null + +if ! docker exec "$CONTAINER" pulsard keys show "$RECIPIENT_KEY" \ + --home "$VALIDATOR_HOME" --keyring-backend test >/dev/null 2>&1; then + docker exec "$CONTAINER" pulsard keys add "$RECIPIENT_KEY" \ + --home "$VALIDATOR_HOME" --keyring-backend test >/dev/null 2>&1 +fi + +RECIPIENT_ADDRESS="$(docker exec "$CONTAINER" pulsard keys show "$RECIPIENT_KEY" \ + --address --home "$VALIDATOR_HOME" --keyring-backend test)" + +docker exec "$CONTAINER" pulsard tx bank send "$FROM_KEY" "$RECIPIENT_ADDRESS" "$AMOUNT" \ + --from "$FROM_KEY" \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test \ + --chain-id "$CHAIN_ID" \ + --node "$NODE" \ + --gas 200000 \ + --fees "$FEES" \ + --generate-only \ + --output json >"$WORK_DIR/unsigned.json" + +python3 - "$WORK_DIR/unsigned.json" "$MODE" >"$WORK_DIR/extended.json" <<'PY' +import json +import sys + +tx = json.load(open(sys.argv[1], encoding="utf-8")) +tx["body"]["extension_options"] = [{ + "@type": "/pulsarchain.ante.v1.TxAuthModeExtension", + "tx_auth_mode": sys.argv[2], +}] +json.dump(tx, sys.stdout) +PY + +docker exec -i "$CONTAINER" pulsard tx sign /dev/stdin \ + --from "$FROM_KEY" \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test \ + --chain-id "$CHAIN_ID" \ + --node "$NODE" \ + --output-document /dev/stdout \ + <"$WORK_DIR/extended.json" >"$WORK_DIR/signed.json" + +docker exec -i "$CONTAINER" pulsard tx broadcast /dev/stdin \ + --node "$NODE" --output json \ + <"$WORK_DIR/signed.json" >"$WORK_DIR/broadcast.json" + +TX_HASH="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["txhash"])' "$WORK_DIR/broadcast.json")" +for _ in $(seq 1 60); do + if docker exec "$CONTAINER" pulsard query tx "$TX_HASH" --node "$NODE" --output json \ + >"$WORK_DIR/result.json" 2>/dev/null; then + CODE="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["code"])' "$WORK_DIR/result.json")" + cat "$WORK_DIR/result.json" + [[ "$CODE" == "0" ]] + exit + fi + sleep 1 +done + +echo "error: transaction was not included: $TX_HASH" >&2 +exit 1 diff --git a/scripts/send_mina_auth_mode_tx.sh b/scripts/send_mina_auth_mode_tx.sh new file mode 100755 index 00000000..933eedcf --- /dev/null +++ b/scripts/send_mina_auth_mode_tx.sh @@ -0,0 +1,149 @@ +#!/usr/bin/env bash + +set -Eeuo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/.." && pwd)" +PROJECT_NAME="${PULSAR_DOCKER_PROJECT:-pulsar-testnet-3}" +CONTAINER="${PULSAR_VALIDATOR_CONTAINER:-${PROJECT_NAME}-validator1-1}" +VALIDATOR_HOME="${PULSAR_VALIDATOR_HOME:-/testnet/.pulsar-node1}" +CHAIN_ID="${CHAIN_ID:-mytestnet}" +FROM_KEY="${AUTH_MODE_FROM_KEY:-mina-auth-mode-sender}" +FUNDING_KEY="${AUTH_MODE_FUNDING_KEY:-validator1}" +RECIPIENT_KEY="${AUTH_MODE_RECIPIENT_KEY:-auth-mode-recipient}" +FUNDING_AMOUNT="${AUTH_MODE_FUNDING_AMOUNT:-1000000pmina}" +AMOUNT="${AUTH_MODE_SEND_AMOUNT:-1pmina}" +FEES="${AUTH_MODE_FEES:-100pmina}" +NODE="${PULSAR_NODE:-tcp://127.0.0.1:26657}" +GRPC_ADDR="${PULSAR_GRPC_ADDR:-127.0.0.1:9090}" + +WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pulsar-mina-auth.XXXXXX")" +trap 'rm -rf -- "$WORK_DIR"' EXIT + +docker inspect "$CONTAINER" >/dev/null + +if ! docker exec "$CONTAINER" pulsard keys show "$FROM_KEY" \ + --home "$VALIDATOR_HOME" --keyring-backend test >/dev/null 2>&1; then + docker exec "$CONTAINER" pulsard keys add "$FROM_KEY" \ + --home "$VALIDATOR_HOME" --keyring-backend test >/dev/null 2>&1 +fi + +if ! docker exec "$CONTAINER" pulsard keys show "$RECIPIENT_KEY" \ + --home "$VALIDATOR_HOME" --keyring-backend test >/dev/null 2>&1; then + docker exec "$CONTAINER" pulsard keys add "$RECIPIENT_KEY" \ + --home "$VALIDATOR_HOME" --keyring-backend test >/dev/null 2>&1 +fi + +FROM_ADDRESS="$(docker exec "$CONTAINER" pulsard keys show "$FROM_KEY" \ + --address --home "$VALIDATOR_HOME" --keyring-backend test)" +RECIPIENT_ADDRESS="$(docker exec "$CONTAINER" pulsard keys show "$RECIPIENT_KEY" \ + --address --home "$VALIDATOR_HOME" --keyring-backend test)" + +docker exec "$CONTAINER" pulsard tx bank send \ + "$FUNDING_KEY" "$FROM_ADDRESS" "$FUNDING_AMOUNT" \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test \ + --chain-id "$CHAIN_ID" \ + --node "$NODE" \ + --gas 200000 \ + --fees "$FEES" \ + --yes \ + --output json >"$WORK_DIR/funding-broadcast.json" + +FUNDING_TX_HASH="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["txhash"])' "$WORK_DIR/funding-broadcast.json")" +for _ in $(seq 1 60); do + if docker exec "$CONTAINER" pulsard query tx "$FUNDING_TX_HASH" --node "$NODE" --output json \ + >"$WORK_DIR/funding-result.json" 2>/dev/null; then + FUNDING_CODE="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["code"])' "$WORK_DIR/funding-result.json")" + if [[ "$FUNDING_CODE" != "0" ]]; then + cat "$WORK_DIR/funding-result.json" >&2 + exit 1 + fi + break + fi + sleep 1 +done +[[ -f "$WORK_DIR/funding-result.json" ]] || { + echo "error: Mina auth-mode sender funding transaction was not included: $FUNDING_TX_HASH" >&2 + exit 1 +} + +COSMOS_PUBLIC_KEY_BASE64="$(docker exec "$CONTAINER" pulsard keys show "$FROM_KEY" \ + --pubkey --home "$VALIDATOR_HOME" --keyring-backend test \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["key"])')" +COSMOS_PUBLIC_KEY_HEX="$(python3 -c 'import base64,sys; print(base64.b64decode(sys.argv[1], validate=True).hex())' "$COSMOS_PUBLIC_KEY_BASE64")" + +MINA_PRIVATE_KEY="${AUTH_MODE_MINA_PRIVATE_KEY:-$( + python3 "$SCRIPT_DIR/setup_local_testnet_helper.py" generate-default-mina-priv-key --index auth-mode-user +)}" + +cd "$REPO_ROOT" +go run -tags=purego ./scripts/devtools mina-registration-material \ + --chain-id "$CHAIN_ID" \ + --cosmos-public-key "$COSMOS_PUBLIC_KEY_BASE64" \ + --mina-private-key "$MINA_PRIVATE_KEY" \ + >"$WORK_DIR/mina-material.json" + +MINA_PUBLIC_KEY_HEX="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["mina_public_key"])' "$WORK_DIR/mina-material.json")" +MINA_SIGNATURE_HEX="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["mina_signature"])' "$WORK_DIR/mina-material.json")" + +if docker exec "$CONTAINER" pulsard query keyregistry get-user-mina-public-key \ + "$COSMOS_PUBLIC_KEY_HEX" --node "$NODE" --output json \ + >"$WORK_DIR/registered-key.json" 2>/dev/null; then + REGISTERED_MINA_KEY_HEX="$(python3 -c 'import base64,json,sys; print(base64.b64decode(json.load(open(sys.argv[1]))["user_mina_public_key"]).hex())' "$WORK_DIR/registered-key.json")" + if [[ "$REGISTERED_MINA_KEY_HEX" != "$MINA_PUBLIC_KEY_HEX" ]]; then + echo "error: $FROM_KEY already has a different Mina key registered" >&2 + exit 1 + fi +else + docker exec "$CONTAINER" pulsard tx keyregistry register-user-keys \ + "$COSMOS_PUBLIC_KEY_HEX" "$MINA_PUBLIC_KEY_HEX" "$MINA_SIGNATURE_HEX" \ + --from "$FROM_KEY" \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test \ + --chain-id "$CHAIN_ID" \ + --node "$NODE" \ + --gas 250000 \ + --fees "$FEES" \ + --yes \ + --output json >"$WORK_DIR/register-broadcast.json" + + REGISTER_TX_HASH="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["txhash"])' "$WORK_DIR/register-broadcast.json")" + for _ in $(seq 1 60); do + if docker exec "$CONTAINER" pulsard query tx "$REGISTER_TX_HASH" --node "$NODE" --output json \ + >"$WORK_DIR/register-result.json" 2>/dev/null; then + REGISTER_CODE="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["code"])' "$WORK_DIR/register-result.json")" + if [[ "$REGISTER_CODE" != "0" ]]; then + cat "$WORK_DIR/register-result.json" >&2 + exit 1 + fi + break + fi + sleep 1 + done + [[ -f "$WORK_DIR/register-result.json" ]] || { + echo "error: Mina key registration transaction was not included: $REGISTER_TX_HASH" >&2 + exit 1 + } +fi + +for attempt in $(seq 1 10); do + if TX_OUTPUT="$(go run -tags=purego ./scripts/devtools send-mina-auth-mode-tx \ + --grpc-addr "$GRPC_ADDR" \ + --chain-id "$CHAIN_ID" \ + --from "$FROM_ADDRESS" \ + --to "$RECIPIENT_ADDRESS" \ + --mina-private-key "$MINA_PRIVATE_KEY" \ + --amount "$AMOUNT" \ + --fees "$FEES" 2>&1)"; then + printf '%s\n' "$TX_OUTPUT" + exit 0 + fi + + if [[ "$TX_OUTPUT" != *"account sequence mismatch"* || "$attempt" == "10" ]]; then + printf '%s\n' "$TX_OUTPUT" >&2 + exit 1 + fi + + sleep 1 +done diff --git a/scripts/send_smart_account_tx.sh b/scripts/send_smart_account_tx.sh new file mode 100755 index 00000000..ef59fc3d --- /dev/null +++ b/scripts/send_smart_account_tx.sh @@ -0,0 +1,360 @@ +#!/usr/bin/env bash + +set -Eeuo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/.." && pwd)" +PROJECT_NAME="${PULSAR_DOCKER_PROJECT:-pulsar-testnet-3}" +CONTAINER="${PULSAR_VALIDATOR_CONTAINER:-${PROJECT_NAME}-validator1-1}" +VERIFIER_CONTAINER="${PULSAR_VERIFIER_CONTAINER:-${PROJECT_NAME}-verifier1-1}" +VALIDATOR_HOME="${PULSAR_VALIDATOR_HOME:-/testnet/.pulsar-node1}" +OWNER_KEY="${SMART_ACCOUNT_OWNER_KEY:-smart-account-owner}" +FIXTURE_GENERATOR="$SCRIPT_DIR/generate_smart_account_noir_fixture.sh" +SUBMISSION_PROTO_ROOT="$REPO_ROOT/testdata/smartaccounts/verifier-proto" +CHAIN_ID="${CHAIN_ID:-mytestnet}" +AMOUNT="${SMART_ACCOUNT_SEND_AMOUNT:-1pmina}" +FUND_AMOUNT="${SMART_ACCOUNT_FUND_AMOUNT:-1000000pmina}" +FEES="${SMART_ACCOUNT_FEES:-100pmina}" +GRPC_ADDR="${PULSAR_GRPC_ADDR:-127.0.0.1:9090}" +GRPCURL_IMAGE="${GRPCURL_IMAGE:-fullstorydev/grpcurl@sha256:085e183ca334eb4e81ca81ee12cbb2b2737505d1d77f5e33dabc5d066593d998}" +SESSION_PRIVATE_KEY="${SMART_ACCOUNT_SESSION_PRIVATE_KEY:-8a5eed4d959d619565a87e8193ad3c91abbce9d783497c004c1b08606c3d9b6b}" +IDENTITY_HEX="${SMART_ACCOUNT_IDENTITY_HEX:-2f833b7c56ed097e355807c19173647fd36cae0f66546b6d3c356a821d557e38}" +EXPIRATION_BLOCKS="${SMART_ACCOUNT_EXPIRATION_BLOCKS:-10000}" + +usage() { + cat <<'EOF' +usage: scripts/send_smart_account_tx.sh + +Runs the complete local smart-account end-to-end flow: + 1. generates a real UltraHonk proof with the pinned Nargo/Barretenberg tools + 2. submits the proof through the production verifier sidecar + 3. waits for the chain to finalize the proof as VALID + 4. funds the proof-bound Cosmos owner + 5. registers the proof-bound session key with AddPublicKey + 6. sends a bank transaction authenticated by that session key + +The chain must be deployed with verifier sidecars. The smartaccounts +verification_key_hash in config.yml must equal SHA-256 of this repository's +test-only smart-account circuit verification key. + +Optional environment variables: + PULSAR_DOCKER_PROJECT Compose project (default: pulsar-testnet-3) + PULSAR_VALIDATOR_CONTAINER validator1 container override + PULSAR_VERIFIER_CONTAINER verifier1 container override + SMART_ACCOUNT_SEND_AMOUNT final smart-account transfer (default: 1pmina) + SMART_ACCOUNT_FUND_AMOUNT owner funding amount (default: 1000000pmina) + SMART_ACCOUNT_FEES fee per transaction (default: 100pmina) + SMART_ACCOUNT_EXPIRATION_BLOCKS + session-key lifetime (default: 10000 blocks) + SMART_ACCOUNT_SESSION_PRIVATE_KEY + 32-byte field-compatible Ed25519 seed in hex + SMART_ACCOUNT_IDENTITY_HEX 32-byte field-compatible identity in hex + GRPCURL_IMAGE grpcurl container image +EOF +} + +case "${1:-}" in + -h | --help) + usage + exit 0 + ;; + "") ;; + *) + usage >&2 + exit 2 + ;; +esac + +fail() { + echo "error: $*" >&2 + exit 1 +} + +require_cmd() { + if ! command -v "$1" >/dev/null 2>&1; then + fail "missing required command: $1" + fi +} + +json_value() { + python3 -c 'import json,sys +value=json.load(open(sys.argv[1], encoding="utf-8")) +for key in sys.argv[2].split("."): + value=value[key] +print(value)' "$1" "$2" +} + +sha256_file() { + python3 -c 'import hashlib,pathlib,sys +print(hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest())' "$1" +} + +wait_for_tx() { + local tx_hash="$1" + local output="$2" + + for _ in $(seq 1 60); do + if docker exec "$CONTAINER" pulsard query tx "$tx_hash" \ + --node tcp://127.0.0.1:26657 \ + --output json >"$output" 2>/dev/null; then + local code + code="$(json_value "$output" code)" + if [[ "$code" != "0" ]]; then + echo "transaction $tx_hash failed:" >&2 + cat "$output" >&2 + return 1 + fi + return 0 + fi + sleep 1 + done + + echo "transaction was not included: $tx_hash" >&2 + return 1 +} + +require_cmd docker +require_cmd go +require_cmd python3 + +[[ -x "$FIXTURE_GENERATOR" ]] || fail "fixture generator is not executable: $FIXTURE_GENERATOR" +if ! [[ "$EXPIRATION_BLOCKS" =~ ^[0-9]+$ ]] || (( EXPIRATION_BLOCKS < 1 )); then + fail "SMART_ACCOUNT_EXPIRATION_BLOCKS must be a positive integer" +fi + +SUBMISSION_PROTO="$SUBMISSION_PROTO_ROOT/pulsar/verifier/v1/submission_service.proto" +[[ -f "$SUBMISSION_PROTO" ]] || fail "submission-service proto not found: $SUBMISSION_PROTO" + +docker inspect "$CONTAINER" >/dev/null 2>&1 || \ + fail "validator container not found: $CONTAINER" +docker inspect "$VERIFIER_CONTAINER" >/dev/null 2>&1 || \ + fail "verifier container not found: $VERIFIER_CONTAINER; deploy with PULSAR_VERIFIER_IMAGE set" + +WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pulsar-smart-account.XXXXXX")" +trap 'rm -rf -- "$WORK_DIR"' EXIT +FIXTURE_DIR="$WORK_DIR/fixture" + +if ! docker exec "$CONTAINER" pulsard keys show "$OWNER_KEY" \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test >/dev/null 2>&1; then + docker exec "$CONTAINER" pulsard keys add "$OWNER_KEY" \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test >/dev/null 2>&1 +fi + +OWNER_ADDRESS="$(docker exec "$CONTAINER" pulsard keys show "$OWNER_KEY" \ + --address --home "$VALIDATOR_HOME" --keyring-backend test)" +VALIDATOR_ADDRESS="$(docker exec "$CONTAINER" pulsard keys show validator1 \ + --address --home "$VALIDATOR_HOME" --keyring-backend test)" +OWNER_ADDRESS_HEX="$(docker exec "$CONTAINER" pulsard debug addr "$OWNER_ADDRESS" \ + | sed -n 's/^Address (hex): //p' | tr '[:upper:]' '[:lower:]')" +[[ "$OWNER_ADDRESS_HEX" =~ ^[0-9a-f]{40}$ ]] || \ + fail "could not derive the 20-byte canonical address for $OWNER_ADDRESS" + +CURRENT_HEIGHT="$(docker exec "$CONTAINER" pulsard status 2>/dev/null \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["sync_info"]["latest_block_height"])')" +EXPIRES_AT_HEIGHT="$((CURRENT_HEIGHT + EXPIRATION_BLOCKS))" + +SESSION_PUBLIC_KEY_HEX="$( + cd "$REPO_ROOT" + go run -tags=purego ./scripts/devtools derive-ed25519-pub "$SESSION_PRIVATE_KEY" +)" + +echo "==> Generating the smart-account Noir proof" +"$FIXTURE_GENERATOR" \ + --output-dir "$FIXTURE_DIR" \ + --session-private-key "$SESSION_PRIVATE_KEY" \ + --session-public-key "$SESSION_PUBLIC_KEY_HEX" \ + --expires-at-height "$EXPIRES_AT_HEIGHT" \ + --identity "$IDENTITY_HEX" \ + --account-address "$OWNER_ADDRESS_HEX" + +PROOF_HASH="$(sha256_file "$FIXTURE_DIR/proof")" +PUBLIC_INPUTS_HASH="$(sha256_file "$FIXTURE_DIR/public_inputs")" +VERIFICATION_KEY_HASH="$(sha256_file "$FIXTURE_DIR/vk")" +VERIFICATION_ID_HEX="$(python3 - "$PROOF_HASH" "$PUBLIC_INPUTS_HASH" "$VERIFICATION_KEY_HASH" <<'PY' +import hashlib +import sys + +proof_hash, public_inputs_hash, verification_key_hash = map(bytes.fromhex, sys.argv[1:]) +payload = ( + b"pulsar/verification/v1\x00" + + (2).to_bytes(4, byteorder="big") + + proof_hash + + public_inputs_hash + + verification_key_hash +) +print(hashlib.sha256(payload).hexdigest()) +PY +)" + +docker exec "$CONTAINER" pulsard query smartaccounts params \ + --node tcp://127.0.0.1:26657 \ + --output json >"$WORK_DIR/smartaccounts-params.json" +CHAIN_VERIFICATION_KEY_HASH="$(python3 - "$WORK_DIR/smartaccounts-params.json" <<'PY' +import base64 +import json +import sys + +value = json.load(open(sys.argv[1], encoding="utf-8"))["params"]["verification_key_hash"] +print(base64.b64decode(value, validate=True).hex()) +PY +)" +if [[ "$CHAIN_VERIFICATION_KEY_HASH" != "$VERIFICATION_KEY_HASH" ]]; then + fail "smartaccounts verification_key_hash does not match SHA-256(vk); redeploy with SMART_ACCOUNTS_VERIFICATION_KEY_HASH=$VERIFICATION_KEY_HASH" +fi + +echo "==> Submitting the real Noir smart-account proof through verifier1" +TX_RAW_BASE64="$(docker exec "$CONTAINER" bash -ceu ' + work="$(mktemp -d)" + trap '\''rm -rf "$work"'\'' EXIT + pulsard tx verification submit-proof "$1" noir-barretenberg "$2" "$3" \ + --from validator1 \ + --home "$4" \ + --keyring-backend test \ + --chain-id "$5" \ + --fees "$6" \ + --generate-only \ + --output json >"$work/unsigned.json" + pulsard tx sign "$work/unsigned.json" \ + --from validator1 \ + --home "$4" \ + --keyring-backend test \ + --chain-id "$5" \ + --output-document "$work/signed.json" + pulsard tx encode "$work/signed.json" +' -- "$PROOF_HASH" "$PUBLIC_INPUTS_HASH" "$VERIFICATION_KEY_HASH" "$VALIDATOR_HOME" "$CHAIN_ID" "$FEES")" + +python3 - "$FIXTURE_DIR" "$TX_RAW_BASE64" >"$WORK_DIR/submission-request.json" <<'PY' +import base64 +import json +import pathlib +import sys + +fixture = pathlib.Path(sys.argv[1]) +payload = { + "proof": { + "proofType": "PROOF_TYPE_NOIR_BARRETENBERG", + "proof": base64.b64encode((fixture / "proof").read_bytes()).decode(), + "publicInputs": base64.b64encode((fixture / "public_inputs").read_bytes()).decode(), + "verificationKey": base64.b64encode((fixture / "vk").read_bytes()).decode(), + }, + "txRaw": sys.argv[2].strip(), +} +json.dump(payload, sys.stdout) +PY + +docker run --rm -i \ + --network "container:${VERIFIER_CONTAINER}" \ + --mount "type=bind,src=$SUBMISSION_PROTO_ROOT,dst=/proto,readonly" \ + "$GRPCURL_IMAGE" -plaintext \ + -max-time 30 \ + -import-path /proto \ + -proto pulsar/verifier/v1/submission_service.proto \ + -d @ 127.0.0.1:50052 \ + pulsar.verifier.v1.SubmissionService/SubmitProof \ + <"$WORK_DIR/submission-request.json" >"$WORK_DIR/submission-response.json" + +RESPONSE_VERIFICATION_ID_HEX="$(python3 - "$WORK_DIR/submission-response.json" <<'PY' +import base64 +import json +import sys + +response = json.load(open(sys.argv[1], encoding="utf-8")) +print(base64.b64decode(response["verificationId"], validate=True).hex()) +PY +)" +if [[ "$RESPONSE_VERIFICATION_ID_HEX" != "$VERIFICATION_ID_HEX" ]]; then + fail "sidecar returned an unexpected verification ID: $RESPONSE_VERIFICATION_ID_HEX" +fi + +VERIFICATION_TX_HASH="$(python3 - "$WORK_DIR/submission-response.json" <<'PY' +import base64 +import json +import sys + +response = json.load(open(sys.argv[1], encoding="utf-8")) +print(base64.b64decode(response["transactionHash"], validate=True).hex().upper()) +PY +)" +wait_for_tx "$VERIFICATION_TX_HASH" "$WORK_DIR/verification-tx-result.json" + +echo "==> Waiting for proof finalization: $VERIFICATION_ID_HEX" +VERIFICATION_STATUS="" +for _ in $(seq 1 90); do + if docker exec "$CONTAINER" pulsard query verification proof-by-verification-id \ + "$VERIFICATION_ID_HEX" \ + --node tcp://127.0.0.1:26657 \ + --output json >"$WORK_DIR/verification-result.json" 2>/dev/null; then + VERIFICATION_STATUS="$(python3 - "$WORK_DIR/verification-result.json" <<'PY' +import json +import sys + +def find_status(value): + if isinstance(value, dict): + if "status" in value: + return value["status"] + for child in value.values(): + found = find_status(child) + if found is not None: + return found + elif isinstance(value, list): + for child in value: + found = find_status(child) + if found is not None: + return found + return None + +status = find_status(json.load(open(sys.argv[1], encoding="utf-8"))) +print(status or "") +PY +)" + [[ -n "$VERIFICATION_STATUS" ]] && break + fi + sleep 2 +done + +[[ -n "$VERIFICATION_STATUS" ]] || fail "proof did not finalize before timeout: $VERIFICATION_ID_HEX" +[[ "$VERIFICATION_STATUS" == "PROOF_STATUS_VALID" ]] || \ + fail "proof finalized with status $VERIFICATION_STATUS" + +echo "==> Funding proof-bound smart-account owner: $OWNER_ADDRESS" +docker exec "$CONTAINER" pulsard tx bank send validator1 "$OWNER_ADDRESS" "$FUND_AMOUNT" \ + --from validator1 \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test \ + --chain-id "$CHAIN_ID" \ + --node tcp://127.0.0.1:26657 \ + --gas 200000 \ + --fees "$FEES" \ + --yes \ + --output json >"$WORK_DIR/fund-broadcast.json" +FUND_TX_HASH="$(json_value "$WORK_DIR/fund-broadcast.json" txhash)" +wait_for_tx "$FUND_TX_HASH" "$WORK_DIR/fund-result.json" + +echo "==> Registering the proof-bound session key" +docker exec "$CONTAINER" pulsard tx smartaccounts add-public-key \ + "$VERIFICATION_ID_HEX" "$SESSION_PUBLIC_KEY_HEX" "$EXPIRES_AT_HEIGHT" "$IDENTITY_HEX" \ + --from "$OWNER_KEY" \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test \ + --chain-id "$CHAIN_ID" \ + --node tcp://127.0.0.1:26657 \ + --gas 300000 \ + --fees "$FEES" \ + --yes \ + --output json >"$WORK_DIR/add-key-broadcast.json" +ADD_KEY_TX_HASH="$(json_value "$WORK_DIR/add-key-broadcast.json" txhash)" +wait_for_tx "$ADD_KEY_TX_HASH" "$WORK_DIR/add-key-result.json" + +echo "==> Sending $AMOUNT with the smart-account session key" +cd "$REPO_ROOT" +go run -tags=purego ./scripts/devtools send-smart-account-tx \ + --grpc-addr "$GRPC_ADDR" \ + --chain-id "$CHAIN_ID" \ + --from "$OWNER_ADDRESS" \ + --to "$VALIDATOR_ADDRESS" \ + --identity "$IDENTITY_HEX" \ + --session-key-file "$FIXTURE_DIR/session-key.hex" \ + --amount "$AMOUNT" \ + --fees "$FEES" diff --git a/scripts/send_unspecified_auth_mode_tx.sh b/scripts/send_unspecified_auth_mode_tx.sh new file mode 100755 index 00000000..52b63046 --- /dev/null +++ b/scripts/send_unspecified_auth_mode_tx.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash + +set -Eeuo pipefail + +PROJECT_NAME="${PULSAR_DOCKER_PROJECT:-pulsar-testnet-3}" +CONTAINER="${PULSAR_VALIDATOR_CONTAINER:-${PROJECT_NAME}-validator1-1}" +VALIDATOR_HOME="${PULSAR_VALIDATOR_HOME:-/testnet/.pulsar-node1}" +CHAIN_ID="${CHAIN_ID:-mytestnet}" +FROM_KEY="${AUTH_MODE_FROM_KEY:-validator1}" +RECIPIENT_KEY="${AUTH_MODE_RECIPIENT_KEY:-auth-mode-recipient}" +AMOUNT="${AUTH_MODE_SEND_AMOUNT:-1pmina}" +FEES="${AUTH_MODE_FEES:-100pmina}" +NODE="${PULSAR_NODE:-tcp://127.0.0.1:26657}" +MODE="TX_AUTH_MODE_UNSPECIFIED" + +WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pulsar-unspecified-auth.XXXXXX")" +trap 'rm -rf -- "$WORK_DIR"' EXIT + +docker inspect "$CONTAINER" >/dev/null + +if ! docker exec "$CONTAINER" pulsard keys show "$RECIPIENT_KEY" \ + --home "$VALIDATOR_HOME" --keyring-backend test >/dev/null 2>&1; then + docker exec "$CONTAINER" pulsard keys add "$RECIPIENT_KEY" \ + --home "$VALIDATOR_HOME" --keyring-backend test >/dev/null 2>&1 +fi + +RECIPIENT_ADDRESS="$(docker exec "$CONTAINER" pulsard keys show "$RECIPIENT_KEY" \ + --address --home "$VALIDATOR_HOME" --keyring-backend test)" + +docker exec "$CONTAINER" pulsard tx bank send "$FROM_KEY" "$RECIPIENT_ADDRESS" "$AMOUNT" \ + --from "$FROM_KEY" \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test \ + --chain-id "$CHAIN_ID" \ + --node "$NODE" \ + --gas 200000 \ + --fees "$FEES" \ + --generate-only \ + --output json >"$WORK_DIR/unsigned.json" + +python3 - "$WORK_DIR/unsigned.json" "$MODE" >"$WORK_DIR/extended.json" <<'PY' +import json +import sys + +tx = json.load(open(sys.argv[1], encoding="utf-8")) +tx["body"]["extension_options"] = [{ + "@type": "/pulsarchain.ante.v1.TxAuthModeExtension", + "tx_auth_mode": sys.argv[2], +}] +json.dump(tx, sys.stdout) +PY + +docker exec -i "$CONTAINER" pulsard tx sign /dev/stdin \ + --from "$FROM_KEY" \ + --home "$VALIDATOR_HOME" \ + --keyring-backend test \ + --chain-id "$CHAIN_ID" \ + --node "$NODE" \ + --output-document /dev/stdout \ + <"$WORK_DIR/extended.json" >"$WORK_DIR/signed.json" + +docker exec -i "$CONTAINER" pulsard tx broadcast /dev/stdin \ + --node "$NODE" --output json \ + <"$WORK_DIR/signed.json" >"$WORK_DIR/broadcast.json" + +TX_HASH="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["txhash"])' "$WORK_DIR/broadcast.json")" +for _ in $(seq 1 60); do + if docker exec "$CONTAINER" pulsard query tx "$TX_HASH" --node "$NODE" --output json \ + >"$WORK_DIR/result.json" 2>/dev/null; then + CODE="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["code"])' "$WORK_DIR/result.json")" + cat "$WORK_DIR/result.json" + [[ "$CODE" == "0" ]] + exit + fi + sleep 1 +done + +echo "error: transaction was not included: $TX_HASH" >&2 +exit 1 diff --git a/scripts/setup_local_testnet.sh b/scripts/setup_local_testnet.sh index 3658054c..07f6202c 100755 --- a/scripts/setup_local_testnet.sh +++ b/scripts/setup_local_testnet.sh @@ -126,8 +126,11 @@ read_app_wrapper_config() { python3 "$PYTHON_HELPER" read-app-wrapper-config --app "$1" --key "$2" } -read_bridge_genesis_param() { - python3 "$PYTHON_HELPER" read-bridge-genesis-param --config "$1" --key "$2" +read_genesis_param() { + python3 "$PYTHON_HELPER" read-genesis-param \ + --config "$1" \ + --module "$2" \ + --key "$3" } generate_default_mina_priv_key() { @@ -182,10 +185,11 @@ resolve_default_mina_network_id() { printf '%s\n' "devnet" } -resolve_default_bridge_param() { +resolve_default_genesis_param() { local env_var_name="$1" - local config_key="$2" - local fallback="$3" + local module_name="$2" + local config_key="$3" + local fallback="$4" if [[ -n "${!env_var_name:-}" ]]; then printf '%s\n' "${!env_var_name}" @@ -194,7 +198,7 @@ resolve_default_bridge_param() { if [[ -f "$CHAIN_CONFIG_PATH" ]]; then local config_value - config_value="$(read_bridge_genesis_param "$CHAIN_CONFIG_PATH" "$config_key")" + config_value="$(read_genesis_param "$CHAIN_CONFIG_PATH" "$module_name" "$config_key")" if [[ -n "$config_value" ]]; then printf '%s\n' "$config_value" return @@ -501,12 +505,16 @@ declare -a NODE_GENESIS_FILES NODE_ADDRS NODE_COSMOS_PUB_KEYS NODE_IDS NODE_VERI declare -a NODE_WRAPPER_GRPC_ADDRESSES NODE_WRAPPER_GRPC_TRANSPORT_MODES DEFAULT_MINA_NETWORK_ID="$(resolve_default_mina_network_id)" -BRIDGE_CONFIRMATION_DEPTH="$(resolve_default_bridge_param "CONFIRMATION_DEPTH" "confirmation_depth" "32")" -BRIDGE_CONTRACT_ADDRESS="$(resolve_default_bridge_param "CONTRACT_ADDRESS" "contract_address" "B62qjRDirGFRf5dvNcGzMs5oWzQ2VyNcygnoKM2MkxB9PFUp7Utdraf")" -BRIDGE_START_BLOCK_HEIGHT="$(resolve_default_bridge_param "START_BLOCK_HEIGHT" "start_block_height" "1")" -BRIDGE_MAX_BLOCK_RANGE="$(resolve_default_bridge_param "MAX_BLOCK_RANGE" "max_block_range" "1000")" -BRIDGE_ACTIONS_REDUCED_ROOT_SNAPSHOT_WINDOW_SIZE="$(resolve_default_bridge_param "ACTIONS_REDUCED_ROOT_SNAPSHOT_WINDOW_SIZE" "actions_reduced_root_snapshot_window_size" "4")" - +BRIDGE_CONFIRMATION_DEPTH="$(resolve_default_genesis_param "CONFIRMATION_DEPTH" "bridge" "confirmation_depth" "32")" +BRIDGE_CONTRACT_ADDRESS="$(resolve_default_genesis_param "CONTRACT_ADDRESS" "bridge" "contract_address" "B62qjRDirGFRf5dvNcGzMs5oWzQ2VyNcygnoKM2MkxB9PFUp7Utdraf")" +BRIDGE_START_BLOCK_HEIGHT="$(resolve_default_genesis_param "START_BLOCK_HEIGHT" "bridge" "start_block_height" "1")" +BRIDGE_MAX_BLOCK_RANGE="$(resolve_default_genesis_param "MAX_BLOCK_RANGE" "bridge" "max_block_range" "1000")" +BRIDGE_ACTIONS_REDUCED_ROOT_SNAPSHOT_WINDOW_SIZE="$(resolve_default_genesis_param "ACTIONS_REDUCED_ROOT_SNAPSHOT_WINDOW_SIZE" "bridge" "actions_reduced_root_snapshot_window_size" "4")" +SMART_ACCOUNTS_VERIFICATION_KEY_HASH="$(resolve_default_genesis_param "SMART_ACCOUNTS_VERIFICATION_KEY_HASH" "smartaccounts" "verification_key_hash" "")" +if [[ -z "$SMART_ACCOUNTS_VERIFICATION_KEY_HASH" ]]; then + echo "smartaccounts verification key hash is required; set SMART_ACCOUNTS_VERIFICATION_KEY_HASH or genesis.app_state.smartaccounts.params.verification_key_hash in $CHAIN_CONFIG_PATH" >&2 + exit 1 +fi validate_positive_int "confirmation depth" "$BRIDGE_CONFIRMATION_DEPTH" validate_non_empty "contract address" "$BRIDGE_CONTRACT_ADDRESS" validate_positive_int "start block height" "$BRIDGE_START_BLOCK_HEIGHT" @@ -637,6 +645,11 @@ for ((i = 1; i <= VALIDATOR_COUNT; i++)); do NODE_ADDRS[i]="$("$BINARY_PATH" keys show "${NODE_KEY_NAMES[i]}" --address --home "${NODE_HOMES[i]}" --keyring-backend "$KEYRING_BACKEND")" done +echo "==> Setting smartaccounts genesis params..." +python3 "$PYTHON_HELPER" patch-smartaccounts-genesis \ + --genesis "$PRIMARY_GENESIS_FILE" \ + --verification-key-hash "$SMART_ACCOUNTS_VERIFICATION_KEY_HASH" + E2E_USER_MINA_PUB_KEY="" E2E_USER_COSMOS_PUB_KEY="" if [[ -n "${E2E_USER_MINA_PRIV_KEY:-}" ]]; then diff --git a/scripts/setup_local_testnet_helper.py b/scripts/setup_local_testnet_helper.py index f9ab7c01..67c6ef15 100644 --- a/scripts/setup_local_testnet_helper.py +++ b/scripts/setup_local_testnet_helper.py @@ -271,10 +271,14 @@ def read_config_path_value(config_path: str, path: list[str]) -> Optional[str]: return read_scalar_in_block(lines, start_index, end_index, parent_indent, path[-1]) -def read_bridge_genesis_param(config_path: str, key_name: str) -> int: +def read_genesis_param( + config_path: str, + module_name: str, + key_name: str, +) -> int: value = read_config_path_value( config_path, - ["genesis", "app_state", "bridge", "params", key_name], + ["genesis", "app_state", module_name, "params", key_name], ) if value is None: print("") @@ -282,8 +286,6 @@ def read_bridge_genesis_param(config_path: str, key_name: str) -> int: print(value) return 0 - - def read_mina_network_id(config_path: str) -> int: content = read_text(config_path) print( @@ -766,6 +768,50 @@ def patch_bridge_genesis( return 0 +def decode_smartaccounts_verification_key_hash(verification_key_hash: str) -> bytes: + encoded_hash = verification_key_hash.strip() + hex_hash = encoded_hash[2:] if encoded_hash.startswith("0x") else encoded_hash + + if re.fullmatch(r"[0-9a-fA-F]{64}", hex_hash): + hash_bytes = bytes.fromhex(hex_hash) + else: + try: + hash_bytes = base64.b64decode(encoded_hash, validate=True) + except ValueError as exc: + raise SystemExit( + "smartaccounts verification key hash must be valid hex or base64" + ) from exc + + if len(hash_bytes) != 32: + raise SystemExit( + "smartaccounts verification key hash must be 32 bytes: " + f"got {len(hash_bytes)}" + ) + + return hash_bytes + + +def patch_smartaccounts_genesis( + genesis_path: str, + verification_key_hash: str, +) -> int: + hash_bytes = decode_smartaccounts_verification_key_hash( + verification_key_hash + ) + + genesis = read_json(genesis_path) + smartaccounts = genesis.setdefault("app_state", {}).setdefault( + "smartaccounts", {} + ) + smartaccounts["params"] = { + "verification_key_hash": base64.b64encode(hash_bytes).decode("ascii") + } + smartaccounts.setdefault("smart_accounts", []) + + write_json(genesis_path, genesis) + return 0 + + def upsert_toml_key( app_toml: str, table_name: str, @@ -915,9 +961,10 @@ def build_parser() -> argparse.ArgumentParser: choices=("wrapper_grpc_address", "wrapper_grpc_transport_mode"), ) - read_bridge_param_cmd = subparsers.add_parser("read-bridge-genesis-param") - read_bridge_param_cmd.add_argument("--config", required=True) - read_bridge_param_cmd.add_argument("--key", required=True) + read_genesis_param_cmd = subparsers.add_parser("read-genesis-param") + read_genesis_param_cmd.add_argument("--config", required=True) + read_genesis_param_cmd.add_argument("--module", required=True) + read_genesis_param_cmd.add_argument("--key", required=True) read_gas_price = subparsers.add_parser("read-min-gas-price") read_gas_price.add_argument("--app", required=True) @@ -975,6 +1022,10 @@ def build_parser() -> argparse.ArgumentParser: "--actions-reduced-root-snapshot-window-size", required=True ) + patch_smartaccounts = subparsers.add_parser("patch-smartaccounts-genesis") + patch_smartaccounts.add_argument("--genesis", required=True) + patch_smartaccounts.add_argument("--verification-key-hash", required=True) + verify_registry = subparsers.add_parser("verify-validator-key-pairs") verify_registry.add_argument("--genesis", required=True) verify_registry.add_argument("--cosmos-key", action="append", required=True) @@ -1014,8 +1065,8 @@ def main() -> int: ) if args.command == "read-app-wrapper-config": return read_app_toml_string(args.app, "bridge", args.key) - if args.command == "read-bridge-genesis-param": - return read_bridge_genesis_param(args.config, args.key) + if args.command == "read-genesis-param": + return read_genesis_param(args.config, args.module, args.key) if args.command == "read-mina-network-id": return read_mina_network_id(args.config) if args.command == "read-min-gas-price": @@ -1062,6 +1113,11 @@ def main() -> int: args.max_block_range, args.actions_reduced_root_snapshot_window_size, ) + if args.command == "patch-smartaccounts-genesis": + return patch_smartaccounts_genesis( + args.genesis, + args.verification_key_hash, + ) if args.command == "verify-validator-key-pairs": return verify_validator_key_pairs(args.genesis, args.cosmos_key) if args.command == "check-validator-status": diff --git a/scripts/test_archive_wrapper_deployment.sh b/scripts/test_archive_wrapper_deployment.sh index ddf959b1..9515703c 100755 --- a/scripts/test_archive_wrapper_deployment.sh +++ b/scripts/test_archive_wrapper_deployment.sh @@ -7,6 +7,7 @@ REPO_ROOT="$(cd -- "$SCRIPT_DIR/.." && pwd)" WRAPPER_SOURCE="${ARCHIVE_WRAPPER_SOURCE:-$(cd -- "$REPO_ROOT/../archive-wrapper" && pwd)}" EXPECTED_WRAPPER_SHA="cd42a203ac6b43d24d9fbd57c323ecd52ea52bd5" ENABLE_VERIFIER_SIDECARS="${ENABLE_VERIFIER_SIDECARS:-0}" +AUTH_MODE_E2E_ONLY="${AUTH_MODE_E2E_ONLY:-0}" VERIFIER_SOURCE="${PULSAR_VERIFIER_SOURCE:-}" MODE="${1:-shared}" PROJECT="pulsar-wrapper-e2e-${MODE//[^a-zA-Z0-9]/-}-$$" @@ -310,15 +311,23 @@ esac require_cmd docker require_cmd git -require_cmd grpcurl -require_cmd node -require_cmd npm require_cmd python3 require_cmd timeout if [[ "$ENABLE_VERIFIER_SIDECARS" != "0" && "$ENABLE_VERIFIER_SIDECARS" != "1" ]]; then echo "ENABLE_VERIFIER_SIDECARS must be 0 or 1" >&2 exit 1 fi +if [[ "$AUTH_MODE_E2E_ONLY" != "0" && "$AUTH_MODE_E2E_ONLY" != "1" ]]; then + echo "AUTH_MODE_E2E_ONLY must be 0 or 1" >&2 + exit 1 +fi +if [[ "$AUTH_MODE_E2E_ONLY" == "1" ]]; then + require_cmd go +else + require_cmd grpcurl + require_cmd node + require_cmd npm +fi # Preserve the existing chain-only test unless verifier sidecars are explicitly enabled. if [[ "$ENABLE_VERIFIER_SIDECARS" == "1" ]]; then @@ -426,6 +435,32 @@ if [[ "$ENABLE_VERIFIER_SIDECARS" == "1" ]]; then compose up --no-build -d --wait --wait-timeout 240 verifier1 verifier2 verifier3 fi +if [[ "$AUTH_MODE_E2E_ONLY" == "1" ]]; then + validator1_container="$(compose ps -q validator1)" + auth_mode_env=( + "PULSAR_DOCKER_PROJECT=$PROJECT" + "PULSAR_VALIDATOR_CONTAINER=$validator1_container" + "PULSAR_GRPC_ADDR=127.0.0.1:${HOST_GRPC_PORTS[1]}" + ) + + echo "==> Sending a TX_AUTH_MODE_COSMOS transaction" + env "${auth_mode_env[@]}" "$SCRIPT_DIR/send_cosmos_auth_mode_tx.sh" + + echo "==> Sending a TX_AUTH_MODE_UNSPECIFIED transaction" + env "${auth_mode_env[@]}" "$SCRIPT_DIR/send_unspecified_auth_mode_tx.sh" + + echo "==> Registering a Mina key and sending a TX_AUTH_MODE_MINA transaction" + env "${auth_mode_env[@]}" "$SCRIPT_DIR/send_mina_auth_mode_tx.sh" + + if [[ "$ENABLE_VERIFIER_SIDECARS" == "1" ]]; then + echo "==> Generating, registering, and using a TX_AUTH_MODE_SMART_ACCOUNT transaction" + env "${auth_mode_env[@]}" "$SCRIPT_DIR/send_smart_account_tx.sh" + fi + + echo "Auth-mode transaction E2E passed" + exit 0 +fi + case "$MODE" in shared) wrapper_endpoints=(archive-wrapper:9095) ;; per-validator) diff --git a/scripts/test_deploy_local_lightnet.py b/scripts/test_deploy_local_lightnet.py index d14976ab..71d7e8a9 100644 --- a/scripts/test_deploy_local_lightnet.py +++ b/scripts/test_deploy_local_lightnet.py @@ -138,6 +138,17 @@ def write_state(value): log.write(json.dumps(args) + "\n") if "cat-file" in args: + source = Path(args[args.index("-C") + 1]) + if not (source / ".git" / "fetched").exists() and "feedface" in args[-1]: + raise SystemExit(1) + raise SystemExit(0) +if "init" in args: + source = Path(args[args.index("-C") + 1]) + (source / ".git").mkdir(parents=True, exist_ok=True) + raise SystemExit(0) +if "fetch" in args: + source = Path(args[args.index("-C") + 1]) + (source / ".git" / "fetched").write_text("ok", encoding="utf-8") raise SystemExit(0) if "archive" in args: sys.stdout.buffer.write(b"fake archive") @@ -156,6 +167,7 @@ def setUp(self): self.home = self.root / "home" self.state_root = self.root / "state" self.wrapper_source = self.root / "archive-wrapper" + self.verifier_cache_root = self.root / "verifier-cache" self.fake_bin = self.root / "bin" self.docker_log = self.root / "docker.log" self.git_log = self.root / "git.log" @@ -179,6 +191,7 @@ def setUp(self): "BRIDGE_MAX_BLOCK_RANGE", "BRIDGE_START_BLOCK_HEIGHT", "DOCKER_PLATFORM", + "ENABLE_VERIFIER_SIDECARS", "LIGHTNET_CONTAINER", "LIGHTNET_IMAGE", "LIGHTNET_POSTGRES_PORT", @@ -186,6 +199,10 @@ def setUp(self): "PULSAR_DOCKER_IMAGE", "PULSAR_DOCKER_PROJECT", "PULSAR_DOCKER_STATE_ROOT", + "PULSAR_VERIFIER_IMAGE", + "PULSAR_VERIFIER_CACHE_ROOT", + "PULSAR_VERIFIER_SHA", + "PULSAR_VERIFIER_SOURCE", "VALIDATOR_STARTUP_TIMEOUT", ): self.env.pop(key, None) @@ -203,6 +220,8 @@ def setUp(self): "PATH": f"{self.fake_bin}{os.pathsep}{self.env['PATH']}", "PULSAR_DOCKER_PROJECT": self.project, "PULSAR_DOCKER_STATE_ROOT": str(self.state_root), + "PULSAR_VERIFIER_CACHE_ROOT": str(self.verifier_cache_root), + "PULSAR_VERIFIER_SHA": "feedface", "VALIDATOR_STARTUP_TIMEOUT": "1", } ) @@ -259,6 +278,7 @@ def test_help_documents_cleanup_options_and_lifecycle_guide(self): "LIGHTNET_IMAGE", "LIGHTNET_READY_HEIGHT", "PULSAR_DOCKER_STATE_ROOT", + "ENABLE_VERIFIER_SIDECARS", "PULSAR_DOCKER_IMAGE", "BRIDGE_CONFIRMATION_DEPTH", "docs/local-lightnet-deployment.md", @@ -268,6 +288,89 @@ def test_help_documents_cleanup_options_and_lifecycle_guide(self): self.assertEqual([], self.read_calls(self.docker_log)) self.assertEqual([], self.read_calls(self.git_log)) + def test_defaults_to_chain_only_without_verifier_work(self): + self.set_lightnet_state("running-owned") + + result = self.run_deploy() + + self.assertEqual(0, result.returncode, result.stderr) + self.assertIn("Verifier sidecars disabled", result.stdout) + self.assertFalse(self.verifier_cache_root.exists()) + self.assertFalse( + any("feedface" in " ".join(call) for call in self.read_calls(self.git_log)) + ) + self.assertFalse( + any( + "pulsar-verifier" in " ".join(call) + for call in self.read_calls(self.docker_log) + ) + ) + + compose = json.loads( + (self.state_root / self.project / "compose.json").read_text( + encoding="utf-8" + ) + ) + self.assertEqual( + "0", compose["services"]["setup"]["environment"]["ENABLE_VERIFIER_SIDECARS"] + ) + self.assertNotIn("verifier1", compose["services"]) + self.assertNotIn("verifier2", compose["services"]) + + def test_explicit_zero_ignores_an_inherited_verifier_image(self): + self.set_lightnet_state("running-owned") + + result = self.run_deploy( + ENABLE_VERIFIER_SIDECARS="0", + PULSAR_VERIFIER_IMAGE="inherited-verifier:test", + ) + + self.assertEqual(0, result.returncode, result.stderr) + self.assertFalse( + any( + "inherited-verifier:test" in " ".join(call) + for call in self.read_calls(self.docker_log) + ) + ) + compose = json.loads( + (self.state_root / self.project / "compose.json").read_text( + encoding="utf-8" + ) + ) + self.assertEqual( + "0", compose["services"]["setup"]["environment"]["ENABLE_VERIFIER_SIDECARS"] + ) + self.assertNotIn("verifier1", compose["services"]) + self.assertNotIn("verifier2", compose["services"]) + + def test_explicit_opt_in_builds_and_starts_verifier_sidecars(self): + self.set_lightnet_state("running-owned") + + result = self.run_deploy(ENABLE_VERIFIER_SIDECARS="1") + + self.assertEqual(0, result.returncode, result.stderr) + self.assertIn("Building the pulsar-verifier image", result.stdout) + self.assertTrue( + (self.verifier_cache_root / "feedface" / ".git" / "fetched").exists() + ) + self.assertTrue( + any( + "pulsar-verifier:lightnet" in " ".join(call) + for call in self.read_calls(self.docker_log) + ) + ) + + compose = json.loads( + (self.state_root / self.project / "compose.json").read_text( + encoding="utf-8" + ) + ) + self.assertEqual( + "1", compose["services"]["setup"]["environment"]["ENABLE_VERIFIER_SIDECARS"] + ) + self.assertIn("verifier1", compose["services"]) + self.assertIn("verifier2", compose["services"]) + def test_cleans_only_selected_project_and_reuses_owned_running_lightnet(self): _, selected_sentinel = self.create_owned_project(self.project) unrelated_root, unrelated_sentinel = self.create_owned_project( @@ -375,6 +478,7 @@ def test_invalid_runtime_overrides_are_rejected_before_cleanup(self): ("BRIDGE_CONFIRMATION_DEPTH", "0", "positive integer"), ("BRIDGE_START_BLOCK_HEIGHT", "0", "positive integer"), ("BRIDGE_MAX_BLOCK_RANGE", "0", "positive integer"), + ("ENABLE_VERIFIER_SIDECARS", "yes", "must be 0 or 1"), ("DOCKER_PLATFORM", "linux/s390x", "Docker platform"), ) diff --git a/scripts/test_render_docker_testnet.py b/scripts/test_render_docker_testnet.py index 11095cc7..e680cb9d 100644 --- a/scripts/test_render_docker_testnet.py +++ b/scripts/test_render_docker_testnet.py @@ -54,6 +54,12 @@ def test_shared_topology_has_one_wrapper_and_one_data_volume(self): "${POSTGRES_URI:-}", compose["services"]["archive-wrapper"]["environment"]["POSTGRES_URI"], ) + self.assertEqual( + "${SMART_ACCOUNTS_VERIFICATION_KEY_HASH:-}", + compose["services"]["setup"]["environment"][ + "SMART_ACCOUNTS_VERIFICATION_KEY_HASH" + ], + ) for index in range(1, 4): self.assertEqual( diff --git a/scripts/test_setup_local_testnet_helper.py b/scripts/test_setup_local_testnet_helper.py index 2946ac63..1470f711 100644 --- a/scripts/test_setup_local_testnet_helper.py +++ b/scripts/test_setup_local_testnet_helper.py @@ -1,5 +1,8 @@ #!/usr/bin/env python3 +import base64 +import contextlib +import io import json import subprocess import sys @@ -437,6 +440,68 @@ def test_patch_bridge_genesis_sets_initial_bridge_state_fields(self): bridge["bridge_state"], ) + def test_patch_smartaccounts_genesis_sets_verification_key_hash(self): + genesis = self.write_temp("genesis.json", json.dumps({"app_state": {}})) + verification_key_hash = bytes(range(32)) + + self.assertEqual( + 0, + helper.patch_smartaccounts_genesis( + str(genesis), + base64.b64encode(verification_key_hash).decode("ascii"), + ), + ) + + payload = json.loads(genesis.read_text(encoding="utf-8")) + smartaccounts = payload["app_state"]["smartaccounts"] + self.assertEqual( + base64.b64encode(verification_key_hash).decode("ascii"), + smartaccounts["params"]["verification_key_hash"], + ) + self.assertEqual([], smartaccounts["smart_accounts"]) + + def test_reads_module_params_through_the_same_generic_path(self): + config = self.write_temp( + "config.yml", + """genesis: + app_state: + bridge: + params: + confirmation_depth: "32" + smartaccounts: + params: + verification_key_hash: "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=" +""", + ) + + cases = ( + ("bridge", "confirmation_depth", "32"), + ( + "smartaccounts", + "verification_key_hash", + "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=", + ), + ) + for module_name, key_name, expected in cases: + with self.subTest(module=module_name, key=key_name): + output = io.StringIO() + with contextlib.redirect_stdout(output): + self.assertEqual( + 0, + helper.read_genesis_param( + str(config), module_name, key_name + ), + ) + self.assertEqual(expected, output.getvalue().strip()) + + def test_patch_smartaccounts_genesis_rejects_invalid_hash(self): + genesis = self.write_temp("genesis.json", json.dumps({"app_state": {}})) + + for value in ("not-hex", "01" * 31, "01" * 33): + with self.subTest(value=value): + with self.assertRaises(SystemExit): + helper.patch_smartaccounts_genesis(str(genesis), value) + def test_render_e2e_seed_replaces_exactly_one_placeholder(self): template = self.write_temp( "seed.sql.tmpl", "fee_payer = '__E2E_MINA_PUBLIC_KEY__';\n" diff --git a/testdata/smartaccounts/noir/bb-5.2.0/Nargo.toml b/testdata/smartaccounts/noir/bb-5.2.0/Nargo.toml new file mode 100644 index 00000000..18d1e028 --- /dev/null +++ b/testdata/smartaccounts/noir/bb-5.2.0/Nargo.toml @@ -0,0 +1,6 @@ +[package] +name = "smart_account_e2e" +type = "bin" +authors = [""] + +[dependencies] diff --git a/testdata/smartaccounts/noir/bb-5.2.0/README.md b/testdata/smartaccounts/noir/bb-5.2.0/README.md new file mode 100644 index 00000000..5e07b0e0 --- /dev/null +++ b/testdata/smartaccounts/noir/bb-5.2.0/README.md @@ -0,0 +1,32 @@ +# Smart-account Noir E2E circuit + +This test-only circuit binds a proof to the four public fields consumed by +`x/smartaccounts` in this exact order: + +1. 32-byte Ed25519 session public key +2. expiration block height, encoded as a 32-byte big-endian integer +3. 32-byte identity +4. 20-byte Cosmos account address, left-padded to 32 bytes + +The circuit is intentionally limited to exercising the complete local +prover, verifier, verification-module, smartaccounts, and ante-handler flow. +It does not prove ownership of a production identity provider account. + +The pinned artifact contract is: + +- Nargo `1.0.0-beta.25` +- Barretenberg `5.2.0` +- UltraHonk +- Poseidon2 transcript +- zero knowledge enabled +- IPA accumulation disabled + +The canonical `SHA-256(vk)` is: + +```text +1feb48cba9a74abcc6639cc79d49dc8e81ed9f4e791c371bdf6a5aa04b296eeb +``` + +The same value is configured for the local network in `config.yml`. + +Generate a proof with `scripts/generate_smart_account_noir_fixture.sh`. diff --git a/testdata/smartaccounts/noir/bb-5.2.0/src/main.nr b/testdata/smartaccounts/noir/bb-5.2.0/src/main.nr new file mode 100644 index 00000000..7a59f77f --- /dev/null +++ b/testdata/smartaccounts/noir/bb-5.2.0/src/main.nr @@ -0,0 +1,13 @@ +fn main( + session_public_key: pub Field, + expires_at_height: pub Field, + identity: pub Field, + account_address: pub Field, + witness: Field, +) { + assert(session_public_key != 0); + assert(expires_at_height != 0); + assert(identity != 0); + assert(account_address != 0); + assert(witness != 0); +} diff --git a/testdata/smartaccounts/verifier-proto/pulsar/verifier/v1/proof.proto b/testdata/smartaccounts/verifier-proto/pulsar/verifier/v1/proof.proto new file mode 100644 index 00000000..b08d712c --- /dev/null +++ b/testdata/smartaccounts/verifier-proto/pulsar/verifier/v1/proof.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; + +package pulsar.verifier.v1; + +import "pulsarchain/verification/v1/types.proto"; + +// Proof carries every artifact required for independent verification. +message Proof { + pulsarchain.verification.v1.ProofType proof_type = 1; + bytes proof = 2; + bytes public_inputs = 3; + bytes verification_key = 4; +} diff --git a/testdata/smartaccounts/verifier-proto/pulsar/verifier/v1/submission_service.proto b/testdata/smartaccounts/verifier-proto/pulsar/verifier/v1/submission_service.proto new file mode 100644 index 00000000..1ce144d0 --- /dev/null +++ b/testdata/smartaccounts/verifier-proto/pulsar/verifier/v1/submission_service.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; + +package pulsar.verifier.v1; + +import "pulsar/verifier/v1/proof.proto"; + +// SubmissionService mirrors the production sidecar submission wire contract. +service SubmissionService { + rpc SubmitProof(SubmitProofRequest) returns (SubmitProofResponse); +} + +message SubmitProofRequest { + Proof proof = 1; + bytes tx_raw = 2; +} + +message SubmitProofResponse { + bytes verification_id = 1; + bytes transaction_hash = 2; +} diff --git a/testdata/smartaccounts/verifier-proto/pulsarchain/verification/v1/types.proto b/testdata/smartaccounts/verifier-proto/pulsarchain/verification/v1/types.proto new file mode 100644 index 00000000..4998167a --- /dev/null +++ b/testdata/smartaccounts/verifier-proto/pulsarchain/verification/v1/types.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; + +package pulsarchain.verification.v1; + +// ProofType mirrors the chain-owned verifier-family wire enum. +enum ProofType { + PROOF_TYPE_UNSPECIFIED = 0; + PROOF_TYPE_MINA_PICKLES = 1; + PROOF_TYPE_NOIR_BARRETENBERG = 2; +} diff --git a/x/smartaccounts/keeper/genesis.go b/x/smartaccounts/keeper/genesis.go new file mode 100644 index 00000000..32b358cf --- /dev/null +++ b/x/smartaccounts/keeper/genesis.go @@ -0,0 +1,65 @@ +package keeper + +import ( + "context" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +// InitGenesis initializes the module's state from a provided genesis state. +func (k Keeper) InitGenesis(ctx context.Context, genState types.GenesisState) error { + if err := genState.Validate(); err != nil { + return err + } + + for _, entry := range genState.SmartAccounts { + if err := k.smartAccounts.Set(ctx, entry.Identity, entry.Account); err != nil { + return err + } + } + + return k.Params.Set(ctx, genState.Params) +} + +// ExportGenesis returns the module's exported genesis. +func (k Keeper) ExportGenesis(ctx context.Context) (*types.GenesisState, error) { + var err error + + genesis := types.DefaultGenesis() + genesis.Params, err = k.Params.Get(ctx) + if err != nil { + return nil, err + } + + iter, err := k.smartAccounts.Iterate(ctx, nil) + if err != nil { + return nil, err + } + defer iter.Close() + + // ExportGenesis is not responsible for handling entry-level errors. + // Therefore, errors encountered in this loop are skipped. + for ; iter.Valid(); iter.Next() { + + acc, err := iter.Value() + if err != nil { + continue + } + identity, err := iter.Key() + if err != nil { + continue + } + + genesis.SmartAccounts = append(genesis.SmartAccounts, types.SmartAccountEntry{ + Identity: identity, + Account: acc, + }) + + } + + if err := genesis.Validate(); err != nil { + return nil, err + } + + return genesis, nil +} diff --git a/x/smartaccounts/keeper/genesis_test.go b/x/smartaccounts/keeper/genesis_test.go new file mode 100644 index 00000000..e6e957ef --- /dev/null +++ b/x/smartaccounts/keeper/genesis_test.go @@ -0,0 +1,43 @@ +package keeper_test + +import ( + "bytes" + "testing" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" + + "github.com/stretchr/testify/require" +) + +func TestGenesis(t *testing.T) { + identity := bytes.Repeat([]byte{0x02}, types.IdentitySize) + genesisState := types.GenesisState{ + Params: types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)), + SmartAccounts: []types.SmartAccountEntry{ + { + Identity: identity, + Account: types.SmartAccount{ + AccountAddress: bytes.Repeat([]byte{0x04}, 20), + SessionKeys: []types.SessionKey{ + { + PublicKey: bytes.Repeat([]byte{0x03}, types.SessionPublicKeySize), + ExpiresAtHeight: 100, + }, + }}, + }, + }, + } + + f := initFixture(t) + err := f.keeper.InitGenesis(f.ctx, genesisState) + require.NoError(t, err) + got, err := f.keeper.ExportGenesis(f.ctx) + require.NoError(t, err) + require.NotNil(t, got) + + require.EqualExportedValues(t, genesisState, *got) + + exists, err := f.keeper.HasSmartAccount(f.ctx, identity) + require.NoError(t, err) + require.True(t, exists) +} diff --git a/x/smartaccounts/keeper/keeper.go b/x/smartaccounts/keeper/keeper.go new file mode 100644 index 00000000..bde072b3 --- /dev/null +++ b/x/smartaccounts/keeper/keeper.go @@ -0,0 +1,254 @@ +package keeper + +import ( + "bytes" + "context" + "fmt" + + "cosmossdk.io/collections" + "cosmossdk.io/core/address" + corestore "cosmossdk.io/core/store" + errorsmod "cosmossdk.io/errors" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +// SmartAccountsMapName is the collections schema name for smart-account state. +const SmartAccountsMapName = "smart_accounts_map" + +type Keeper struct { + storeService corestore.KVStoreService + cdc codec.Codec + addressCodec address.Codec + // Address capable of executing a MsgUpdateParams message. + // Typically, this should be the x/gov module account. + authority []byte + + smartAccounts collections.Map[[]byte, types.SmartAccount] // identity -> smart account + + verificationKeeper types.VerificationKeeper + + Schema collections.Schema + Params collections.Item[types.Params] +} + +func NewKeeper( + storeService corestore.KVStoreService, + cdc codec.Codec, + addressCodec address.Codec, + authority []byte, + verificationKeeper types.VerificationKeeper, +) Keeper { + if _, err := addressCodec.BytesToString(authority); err != nil { + panic(fmt.Sprintf("invalid authority address %s: %s", authority, err)) + } + + sb := collections.NewSchemaBuilder(storeService) + + k := Keeper{ + storeService: storeService, + cdc: cdc, + addressCodec: addressCodec, + authority: authority, + + Params: collections.NewItem(sb, types.ParamsKey, "params", codec.CollValue[types.Params](cdc)), + + smartAccounts: collections.NewMap( + sb, + types.SmartAccountsKey, + SmartAccountsMapName, + collections.BytesKey, + codec.CollValue[types.SmartAccount](cdc)), + + verificationKeeper: verificationKeeper, + } + + schema, err := sb.Build() + if err != nil { + panic(err) + } + k.Schema = schema + + return k +} + +// GetAuthority returns the module's authority. +func (k Keeper) GetAuthority() []byte { + return k.authority +} + +// HasSmartAccount reports whether smart-account state exists for identity. +func (k Keeper) HasSmartAccount(ctx context.Context, identity []byte) (bool, error) { + + if identity == nil { + return false, types.ErrNilIdentity + } + + if len(identity) == 0 { + return false, types.ErrNilIdentity + } + + if len(identity) != types.IdentitySize { + return false, types.ErrIdentityInvalidLength + } + + return k.smartAccounts.Has(ctx, identity) +} + +// IsSessionKeyAuthorized reports whether publicKey is currently authorized +// for identity and accountAddr. +func (k Keeper) IsSessionKeyAuthorized(ctx context.Context, identity, accountAddr, publicKey []byte) (bool, error) { + if len(publicKey) == 0 { + return false, types.ErrNilPublicKey + } + + if len(publicKey) != types.SessionPublicKeySize { + return false, types.ErrPublicKeyInvalidLength + } + + if len(accountAddr) == 0 { + return false, types.ErrNilAccountAddress + } + + if err := sdk.VerifyAddressFormat(accountAddr); err != nil { + return false, errorsmod.Wrap(types.ErrInvalidAccountAddress, err.Error()) + } + + exists, err := k.HasSmartAccount(ctx, identity) + if err != nil { + return false, err + } + if !exists { + return false, nil + } + + account, err := k.smartAccounts.Get(ctx, identity) + if err != nil { + return false, err + } + + if !bytes.Equal(accountAddr, account.AccountAddress) { + return false, types.ErrAccountAddressMismatch + } + + currentHeight := uint64(sdk.UnwrapSDKContext(ctx).BlockHeight()) + for _, key := range account.SessionKeys { + if bytes.Equal(key.PublicKey, publicKey) && currentHeight < key.ExpiresAtHeight { + return true, nil + } + } + + return false, nil +} + +// AppendSessionKeyToSmartAccount adds an active session key to the smart account identified by identity. +func (k Keeper) AppendSessionKeyToSmartAccount(ctx context.Context, identity, accountAddress []byte, key types.SessionKey) error { + + if identity == nil { + return types.ErrNilIdentity + } + + if len(identity) == 0 { + return types.ErrNilIdentity + } + + if len(identity) != types.IdentitySize { + return types.ErrIdentityInvalidLength + } + + if key.PublicKey == nil { + return types.ErrNilPublicKey + } + + if len(key.PublicKey) != types.SessionPublicKeySize { + return types.ErrPublicKeyInvalidLength + } + + if key.ExpiresAtHeight == 0 { + return types.ErrInvalidExpirationHeight + } + + currentHeight := uint64(sdk.UnwrapSDKContext(ctx).BlockHeight()) + if key.ExpiresAtHeight <= currentHeight { + return types.ErrInvalidExpirationHeight + } + + if len(accountAddress) == 0 { + return types.ErrNilAccountAddress + } + + if err := sdk.VerifyAddressFormat(accountAddress); err != nil { + return errorsmod.Wrap(types.ErrInvalidAccountAddress, err.Error()) + } + + exists, err := k.HasSmartAccount(ctx, identity) + if err != nil { + return err + } + + if !exists { + err := k.smartAccounts.Set(ctx, identity, types.SmartAccount{ + AccountAddress: accountAddress, + SessionKeys: []types.SessionKey{ + key, + }, + }) + if err != nil { + return err + } + return nil + } + + acc, err := k.smartAccounts.Get(ctx, identity) + if err != nil { + return err + } + if !bytes.Equal(acc.AccountAddress, accountAddress) { + return types.ErrAccountAddressMismatch + } + + for _, existingKey := range acc.SessionKeys { + if bytes.Equal(existingKey.PublicKey, key.PublicKey) && + existingKey.ExpiresAtHeight == key.ExpiresAtHeight { + return types.ErrSessionKeyAlreadyExists + } + } + + // TODO: Evaluate and enforce a per-account session-key limit to keep + // state growth and authorization cost bounded. + acc.SessionKeys = append(acc.SessionKeys, key) + + if err := k.smartAccounts.Set(ctx, identity, acc); err != nil { + return err + } + + return k.pruneSessionKey(ctx, identity) +} + +func (k Keeper) pruneSessionKey(ctx context.Context, identity []byte) error { + + var validSessionKeys []types.SessionKey + + smartAcc, err := k.smartAccounts.Get(ctx, identity) + if err != nil { + return err + } + + currentBlockHeight := uint64(sdk.UnwrapSDKContext(ctx).BlockHeight()) + + for _, key := range smartAcc.SessionKeys { + + if currentBlockHeight >= key.ExpiresAtHeight { + continue + } + validSessionKeys = append(validSessionKeys, key) + } + + smartAcc.SessionKeys = validSessionKeys + if err := k.smartAccounts.Set(ctx, identity, smartAcc); err != nil { + return err + } + + return nil +} diff --git a/x/smartaccounts/keeper/keeper_test.go b/x/smartaccounts/keeper/keeper_test.go new file mode 100644 index 00000000..c1ce895f --- /dev/null +++ b/x/smartaccounts/keeper/keeper_test.go @@ -0,0 +1,77 @@ +package keeper_test + +import ( + "bytes" + "context" + "testing" + + "cosmossdk.io/core/address" + storetypes "cosmossdk.io/store/types" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" + "github.com/cosmos/cosmos-sdk/runtime" + "github.com/cosmos/cosmos-sdk/testutil" + sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/keeper" + module "github.com/node101-io/pulsar-chain/x/smartaccounts/module" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" + verificationtypes "github.com/node101-io/pulsar-chain/x/verification/types" +) + +type mockVerificationKeeper struct { + result verificationtypes.FinalProofResult + err error + requestedVerificationID []byte +} + +func (m *mockVerificationKeeper) FinalProofResultByVerificationID( + _ context.Context, + verificationID []byte, +) (verificationtypes.FinalProofResult, error) { + m.requestedVerificationID = bytes.Clone(verificationID) + return m.result, m.err +} + +type fixture struct { + ctx context.Context + keeper keeper.Keeper + addressCodec address.Codec + verificationKeeper *mockVerificationKeeper +} + +func initFixture(t *testing.T) *fixture { + t.Helper() + + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) + addressCodec := addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()) + storeKey := storetypes.NewKVStoreKey(types.StoreKey) + + storeService := runtime.NewKVStoreService(storeKey) + ctx := testutil.DefaultContextWithDB(t, storeKey, storetypes.NewTransientStoreKey("transient_test")).Ctx + + authority := authtypes.NewModuleAddress(types.GovModuleName) + verificationKeeper := &mockVerificationKeeper{} + + k := keeper.NewKeeper( + storeService, + encCfg.Codec, + addressCodec, + authority, + verificationKeeper, + ) + + // Initialize params + params := types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)) + if err := k.Params.Set(ctx, params); err != nil { + t.Fatalf("failed to set params: %v", err) + } + + return &fixture{ + ctx: ctx, + keeper: k, + addressCodec: addressCodec, + verificationKeeper: verificationKeeper, + } +} diff --git a/x/smartaccounts/keeper/msg_server.go b/x/smartaccounts/keeper/msg_server.go new file mode 100644 index 00000000..4fb6edf1 --- /dev/null +++ b/x/smartaccounts/keeper/msg_server.go @@ -0,0 +1,17 @@ +package keeper + +import ( + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +type msgServer struct { + Keeper +} + +// NewMsgServerImpl returns an implementation of the MsgServer interface +// for the provided Keeper. +func NewMsgServerImpl(keeper Keeper) types.MsgServer { + return &msgServer{Keeper: keeper} +} + +var _ types.MsgServer = msgServer{} diff --git a/x/smartaccounts/keeper/msg_server_add_public_key.go b/x/smartaccounts/keeper/msg_server_add_public_key.go new file mode 100644 index 00000000..8bd4519d --- /dev/null +++ b/x/smartaccounts/keeper/msg_server_add_public_key.go @@ -0,0 +1,95 @@ +package keeper + +import ( + "bytes" + "context" + + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" + verificationtypes "github.com/node101-io/pulsar-chain/x/verification/types" +) + +func (k msgServer) AddPublicKey(ctx context.Context, msg *types.MsgAddPublicKey) (*types.MsgAddPublicKeyResponse, error) { + + accountAddr, err := k.addressCodec.StringToBytes(msg.Creator) + if err != nil { + return nil, errorsmod.Wrap(err, "invalid creator address") + } + + if msg.VerificationId == nil { + return nil, types.ErrNilVerificationID + } + + if len(msg.VerificationId) != verificationtypes.VerificationIDSize { + return nil, types.ErrVerificationIDInvalidLength + } + + if msg.PublicKeyInputs == nil { + return nil, types.ErrNilPublicKeyInputs + } + if msg.PublicKeyInputs.Identity == nil { + return nil, types.ErrNilIdentity + } + if len(msg.PublicKeyInputs.Identity) != types.IdentitySize { + return nil, types.ErrIdentityInvalidLength + } + if msg.PublicKeyInputs.SessionPublicKey == nil { + return nil, types.ErrNilPublicKey + } + + if len(msg.PublicKeyInputs.SessionPublicKey) != types.SessionPublicKeySize { + return nil, types.ErrPublicKeyInvalidLength + } + + if msg.PublicKeyInputs.ExpiresAtHeight == 0 { + return nil, types.ErrInvalidExpirationHeight + } + + currentHeight := sdk.UnwrapSDKContext(ctx).BlockHeight() + + if msg.PublicKeyInputs.ExpiresAtHeight <= uint64(currentHeight) { + return nil, types.ErrInvalidExpirationHeight + } + + result, err := k.verificationKeeper.FinalProofResultByVerificationID( + ctx, + msg.VerificationId, + ) + if err != nil { + return nil, err + } + + if result.Status != verificationtypes.ProofStatus_PROOF_STATUS_VALID { + return nil, types.ErrProofNotValid + } + + params, err := k.Params.Get(ctx) + if err != nil { + return nil, err + } + + if !bytes.Equal(result.VerificationKeyHash, + params.VerificationKeyHash) { + return nil, types.ErrVerificationKeyMismatch + } + + publicKeyInputsHash, err := types.ComputePublicInputsHash(msg.PublicKeyInputs, accountAddr) + if err != nil { + return nil, err + } + + if !bytes.Equal(result.PublicInputsHash, + publicKeyInputsHash) { + return nil, types.ErrInvalidPublicInputsHash + } + + if err := k.AppendSessionKeyToSmartAccount(ctx, msg.PublicKeyInputs.Identity, accountAddr, types.SessionKey{ + PublicKey: msg.PublicKeyInputs.SessionPublicKey, + ExpiresAtHeight: msg.PublicKeyInputs.ExpiresAtHeight, + }); err != nil { + return nil, err + } + + return &types.MsgAddPublicKeyResponse{}, nil +} diff --git a/x/smartaccounts/keeper/msg_server_add_public_key_test.go b/x/smartaccounts/keeper/msg_server_add_public_key_test.go new file mode 100644 index 00000000..a2ad1fa7 --- /dev/null +++ b/x/smartaccounts/keeper/msg_server_add_public_key_test.go @@ -0,0 +1,269 @@ +package keeper_test + +import ( + "bytes" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/keeper" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" + verificationtypes "github.com/node101-io/pulsar-chain/x/verification/types" +) + +func TestAddPublicKey(t *testing.T) { + f := initFixture(t) + msg := validAddPublicKeyMessage(t, f) + server := keeper.NewMsgServerImpl(f.keeper) + + response, err := server.AddPublicKey(f.ctx, msg) + require.NoError(t, err) + require.NotNil(t, response) + require.Equal(t, msg.VerificationId, f.verificationKeeper.requestedVerificationID) + + exists, err := f.keeper.HasSmartAccount(f.ctx, msg.PublicKeyInputs.Identity) + require.NoError(t, err) + require.True(t, exists) + + accountAddress, err := f.addressCodec.StringToBytes(msg.Creator) + require.NoError(t, err) + genesis, err := f.keeper.ExportGenesis(f.ctx) + require.NoError(t, err) + require.Len(t, genesis.SmartAccounts, 1) + require.Equal(t, accountAddress, genesis.SmartAccounts[0].Account.AccountAddress) + + _, err = server.AddPublicKey(f.ctx, msg) + require.ErrorIs(t, err, types.ErrSessionKeyAlreadyExists) +} + +func TestAddPublicKeyRejectsCreatorNotBoundByProof(t *testing.T) { + f := initFixture(t) + msg := validAddPublicKeyMessage(t, f) + server := keeper.NewMsgServerImpl(f.keeper) + + otherCreator, err := f.addressCodec.BytesToString(bytes.Repeat([]byte{0x09}, 20)) + require.NoError(t, err) + msg.Creator = otherCreator + + _, err = server.AddPublicKey(f.ctx, msg) + require.ErrorIs(t, err, types.ErrInvalidPublicInputsHash) + + originalCreator, err := f.addressCodec.BytesToString(f.keeper.GetAuthority()) + require.NoError(t, err) + msg.Creator = originalCreator + + _, err = server.AddPublicKey(f.ctx, msg) + require.NoError(t, err) + + genesis, err := f.keeper.ExportGenesis(f.ctx) + require.NoError(t, err) + require.Len(t, genesis.SmartAccounts, 1) + require.Equal(t, f.keeper.GetAuthority(), genesis.SmartAccounts[0].Account.AccountAddress) +} + +func TestAddPublicKeyRejectsInvalidProofData(t *testing.T) { + f := initFixture(t) + msg := validAddPublicKeyMessage(t, f) + validResult := f.verificationKeeper.result + + invalidResult := validResult + invalidResult.Status = verificationtypes.ProofStatus_PROOF_STATUS_INVALID + + verificationKeyMismatch := validResult + verificationKeyMismatch.VerificationKeyHash = bytes.Clone(validResult.VerificationKeyHash) + verificationKeyMismatch.VerificationKeyHash[0] ^= 0xff + + publicInputsHashMismatch := validResult + publicInputsHashMismatch.PublicInputsHash = bytes.Clone(validResult.PublicInputsHash) + publicInputsHashMismatch.PublicInputsHash[0] ^= 0xff + + tests := []struct { + name string + result verificationtypes.FinalProofResult + verificationErr error + want error + }{ + { + name: "proof not found", + result: validResult, + verificationErr: verificationtypes.ErrProofNotFound, + want: verificationtypes.ErrProofNotFound, + }, + { + name: "proof is invalid", + result: invalidResult, + want: types.ErrProofNotValid, + }, + { + name: "verification key mismatch", + result: verificationKeyMismatch, + want: types.ErrVerificationKeyMismatch, + }, + { + name: "public inputs hash mismatch", + result: publicInputsHashMismatch, + want: types.ErrInvalidPublicInputsHash, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + f.verificationKeeper.result = test.result + f.verificationKeeper.err = test.verificationErr + + _, err := keeper.NewMsgServerImpl(f.keeper).AddPublicKey(f.ctx, msg) + require.ErrorIs(t, err, test.want) + }) + } +} + +func TestAddPublicKeyRejectsInvalidInputs(t *testing.T) { + f := initFixture(t) + validMsg := validAddPublicKeyMessage(t, f) + + tests := []struct { + name string + verificationID []byte + publicKeyInputs *types.PublicKeyInputs + want error + }{ + { + name: "nil verification ID", + publicKeyInputs: &types.PublicKeyInputs{ + SessionPublicKey: validMsg.PublicKeyInputs.SessionPublicKey, + ExpiresAtHeight: validMsg.PublicKeyInputs.ExpiresAtHeight, + Identity: validMsg.PublicKeyInputs.Identity, + }, + want: types.ErrNilVerificationID, + }, + { + name: "invalid verification ID length", + verificationID: validMsg.VerificationId[:verificationtypes.VerificationIDSize-1], + publicKeyInputs: &types.PublicKeyInputs{ + SessionPublicKey: validMsg.PublicKeyInputs.SessionPublicKey, + ExpiresAtHeight: validMsg.PublicKeyInputs.ExpiresAtHeight, + Identity: validMsg.PublicKeyInputs.Identity, + }, + want: types.ErrVerificationIDInvalidLength, + }, + { + name: "nil public key inputs", + verificationID: validMsg.VerificationId, + want: types.ErrNilPublicKeyInputs, + }, + { + name: "nil identity", + verificationID: validMsg.VerificationId, + publicKeyInputs: &types.PublicKeyInputs{ + SessionPublicKey: validMsg.PublicKeyInputs.SessionPublicKey, + ExpiresAtHeight: validMsg.PublicKeyInputs.ExpiresAtHeight, + }, + want: types.ErrNilIdentity, + }, + { + name: "invalid identity length", + verificationID: validMsg.VerificationId, + publicKeyInputs: &types.PublicKeyInputs{ + SessionPublicKey: validMsg.PublicKeyInputs.SessionPublicKey, + ExpiresAtHeight: validMsg.PublicKeyInputs.ExpiresAtHeight, + Identity: validMsg.PublicKeyInputs.Identity[:types.IdentitySize-1], + }, + want: types.ErrIdentityInvalidLength, + }, + { + name: "nil public key", + verificationID: validMsg.VerificationId, + publicKeyInputs: &types.PublicKeyInputs{ + ExpiresAtHeight: validMsg.PublicKeyInputs.ExpiresAtHeight, + Identity: validMsg.PublicKeyInputs.Identity, + }, + want: types.ErrNilPublicKey, + }, + { + name: "invalid public key length", + verificationID: validMsg.VerificationId, + publicKeyInputs: &types.PublicKeyInputs{ + SessionPublicKey: validMsg.PublicKeyInputs.SessionPublicKey[:types.SessionPublicKeySize-1], + ExpiresAtHeight: validMsg.PublicKeyInputs.ExpiresAtHeight, + Identity: validMsg.PublicKeyInputs.Identity, + }, + want: types.ErrPublicKeyInvalidLength, + }, + { + name: "zero expiration height", + verificationID: validMsg.VerificationId, + publicKeyInputs: &types.PublicKeyInputs{ + SessionPublicKey: validMsg.PublicKeyInputs.SessionPublicKey, + ExpiresAtHeight: 0, + Identity: validMsg.PublicKeyInputs.Identity, + }, + want: types.ErrInvalidExpirationHeight, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + msg := &types.MsgAddPublicKey{ + Creator: validMsg.Creator, + VerificationId: test.verificationID, + PublicKeyInputs: test.publicKeyInputs, + } + + _, err := keeper.NewMsgServerImpl(f.keeper).AddPublicKey(f.ctx, msg) + require.ErrorIs(t, err, test.want) + }) + } +} + +func TestAddPublicKeyRejectsExpiredSessionKey(t *testing.T) { + f := initFixture(t) + msg := validAddPublicKeyMessage(t, f) + + sdkCtx := sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(int64(msg.PublicKeyInputs.ExpiresAtHeight)) + + _, err := keeper.NewMsgServerImpl(f.keeper).AddPublicKey(sdkCtx, msg) + require.ErrorIs(t, err, types.ErrInvalidExpirationHeight) +} + +func validAddPublicKeyMessage(t *testing.T, f *fixture) *types.MsgAddPublicKey { + t.Helper() + + creator, err := f.addressCodec.BytesToString(f.keeper.GetAuthority()) + require.NoError(t, err) + accountAddress, err := f.addressCodec.StringToBytes(creator) + require.NoError(t, err) + + currentHeight := sdk.UnwrapSDKContext(f.ctx).BlockHeight() + inputs := &types.PublicKeyInputs{ + SessionPublicKey: bytes.Repeat([]byte{0x02}, types.SessionPublicKeySize), + ExpiresAtHeight: uint64(currentHeight) + 10, + Identity: bytes.Repeat([]byte{0x03}, types.IdentitySize), + } + publicInputsHash, err := types.ComputePublicInputsHash(inputs, accountAddress) + require.NoError(t, err) + + proofHash := bytes.Repeat([]byte{0x04}, verificationtypes.ProofHashSize) + verificationKeyHash := bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize) + verificationID, err := verificationtypes.ComputeVerificationID( + verificationtypes.ProofType_PROOF_TYPE_NOIR_BARRETENBERG, + proofHash, + publicInputsHash, + verificationKeyHash, + ) + require.NoError(t, err) + f.verificationKeeper.result = verificationtypes.FinalProofResult{ + ProofHash: bytes.Clone(proofHash), + ProofType: verificationtypes.ProofType_PROOF_TYPE_NOIR_BARRETENBERG, + Status: verificationtypes.ProofStatus_PROOF_STATUS_VALID, + PublicInputsHash: publicInputsHash, + VerificationKeyHash: verificationKeyHash, + VerificationId: bytes.Clone(verificationID[:]), + } + + return &types.MsgAddPublicKey{ + Creator: creator, + VerificationId: verificationID[:], + PublicKeyInputs: inputs, + } +} diff --git a/x/smartaccounts/keeper/msg_update_params.go b/x/smartaccounts/keeper/msg_update_params.go new file mode 100644 index 00000000..57a0b36a --- /dev/null +++ b/x/smartaccounts/keeper/msg_update_params.go @@ -0,0 +1,32 @@ +package keeper + +import ( + "bytes" + "context" + + errorsmod "cosmossdk.io/errors" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +func (k msgServer) UpdateParams(ctx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + authority, err := k.addressCodec.StringToBytes(req.Authority) + if err != nil { + return nil, errorsmod.Wrap(err, "invalid authority address") + } + + if !bytes.Equal(k.GetAuthority(), authority) { + expectedAuthorityStr, _ := k.addressCodec.BytesToString(k.GetAuthority()) + return nil, errorsmod.Wrapf(types.ErrInvalidSigner, "invalid authority; expected %s, got %s", expectedAuthorityStr, req.Authority) + } + + if err := req.Params.Validate(); err != nil { + return nil, err + } + + if err := k.Params.Set(ctx, req.Params); err != nil { + return nil, err + } + + return &types.MsgUpdateParamsResponse{}, nil +} diff --git a/x/smartaccounts/keeper/msg_update_params_test.go b/x/smartaccounts/keeper/msg_update_params_test.go new file mode 100644 index 00000000..5609cc08 --- /dev/null +++ b/x/smartaccounts/keeper/msg_update_params_test.go @@ -0,0 +1,70 @@ +package keeper_test + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/keeper" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +func TestMsgUpdateParams(t *testing.T) { + f := initFixture(t) + ms := keeper.NewMsgServerImpl(f.keeper) + + params := types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)) + require.NoError(t, f.keeper.Params.Set(f.ctx, params)) + + authorityStr, err := f.addressCodec.BytesToString(f.keeper.GetAuthority()) + require.NoError(t, err) + + // default params + testCases := []struct { + name string + input *types.MsgUpdateParams + expErr bool + expErrMsg string + }{ + { + name: "invalid authority", + input: &types.MsgUpdateParams{ + Authority: "invalid", + Params: params, + }, + expErr: true, + expErrMsg: "invalid authority", + }, + { + name: "invalid verification key hash", + input: &types.MsgUpdateParams{ + Authority: authorityStr, + Params: types.Params{}, + }, + expErr: true, + expErrMsg: "verification key hash must be 32 bytes", + }, + { + name: "all good", + input: &types.MsgUpdateParams{ + Authority: authorityStr, + Params: params, + }, + expErr: false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + _, err := ms.UpdateParams(f.ctx, tc.input) + + if tc.expErr { + require.Error(t, err) + require.Contains(t, err.Error(), tc.expErrMsg) + } else { + require.NoError(t, err) + } + }) + } +} diff --git a/x/smartaccounts/keeper/query.go b/x/smartaccounts/keeper/query.go new file mode 100644 index 00000000..977908a6 --- /dev/null +++ b/x/smartaccounts/keeper/query.go @@ -0,0 +1,17 @@ +package keeper + +import ( + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +var _ types.QueryServer = queryServer{} + +// NewQueryServerImpl returns an implementation of the QueryServer interface +// for the provided Keeper. +func NewQueryServerImpl(k Keeper) types.QueryServer { + return queryServer{k} +} + +type queryServer struct { + k Keeper +} diff --git a/x/smartaccounts/keeper/query_get_session_keys_by_identity.go b/x/smartaccounts/keeper/query_get_session_keys_by_identity.go new file mode 100644 index 00000000..d3f5d09d --- /dev/null +++ b/x/smartaccounts/keeper/query_get_session_keys_by_identity.go @@ -0,0 +1,104 @@ +package keeper + +import ( + "context" + "encoding/binary" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +const maxSessionKeysPageSize uint64 = 100 + +func (q queryServer) GetSessionKeysByIdentity(ctx context.Context, req *types.QueryGetSessionKeysByIdentityRequest) (*types.QueryGetSessionKeysByIdentityResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + if len(req.Identity) == 0 { + return nil, status.Error(codes.InvalidArgument, "empty identity") + } + + if len(req.Identity) != types.IdentitySize { + return nil, status.Error(codes.InvalidArgument, "invalid identity size") + } + + sdkCtx := sdk.UnwrapSDKContext(ctx) + + exists, err := q.k.HasSmartAccount(sdkCtx, req.Identity) + if err != nil { + return nil, status.Error(codes.Internal, "internal error") + } + + if !exists { + return nil, status.Error(codes.NotFound, "identity not found") + } + + acc, err := q.k.smartAccounts.Get(sdkCtx, req.Identity) + if err != nil { + return nil, status.Error(codes.Internal, "internal error") + } + + pageRequest := req.Pagination + + var offset uint64 + limit := maxSessionKeysPageSize + + if pageRequest != nil { + if pageRequest.Reverse { + return nil, status.Error( + codes.InvalidArgument, + "reverse pagination is not supported", + ) + } + + offset = pageRequest.Offset + if len(pageRequest.Key) != 0 { + if pageRequest.Offset != 0 { + return nil, status.Error( + codes.InvalidArgument, + "pagination key and offset cannot both be set", + ) + } + if len(pageRequest.Key) != 8 { + return nil, status.Error(codes.InvalidArgument, "invalid pagination key") + } + offset = binary.BigEndian.Uint64(pageRequest.Key) + } + + if pageRequest.Limit > 0 && pageRequest.Limit < limit { + limit = pageRequest.Limit + } + } + + total := uint64(len(acc.SessionKeys)) + + if offset > total { + offset = total + } + + end := total + if limit < total-offset { + end = offset + limit + } + + sessionKeys := make([]*types.SessionKey, 0, int(end-offset)) + for _, key := range acc.SessionKeys[offset:end] { + sessionKeys = append(sessionKeys, &key) + } + + pageResponse := &query.PageResponse{Total: total} + if end < total { + pageResponse.NextKey = make([]byte, 8) + binary.BigEndian.PutUint64(pageResponse.NextKey, end) + } + + return &types.QueryGetSessionKeysByIdentityResponse{ + AccountAddress: acc.AccountAddress, + SessionKeys: sessionKeys, + Pagination: pageResponse, + }, nil +} diff --git a/x/smartaccounts/keeper/query_get_session_keys_by_identity_test.go b/x/smartaccounts/keeper/query_get_session_keys_by_identity_test.go new file mode 100644 index 00000000..cfaac7ee --- /dev/null +++ b/x/smartaccounts/keeper/query_get_session_keys_by_identity_test.go @@ -0,0 +1,175 @@ +package keeper_test + +import ( + "bytes" + "encoding/binary" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + "github.com/node101-io/pulsar-chain/x/smartaccounts/keeper" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// TestGetSessionKeysByIdentityPagination verifies default page-size enforcement +// and continuation through the returned pagination key. +func TestGetSessionKeysByIdentityPagination(t *testing.T) { + f := initFixture(t) + identity := bytes.Repeat([]byte{0x01}, types.IdentitySize) + accountAddress := f.keeper.GetAuthority() + expiresAtHeight := uint64(sdk.UnwrapSDKContext(f.ctx).BlockHeight()) + 1_000 + + for i := uint64(1); i <= 105; i++ { + publicKey := make([]byte, types.SessionPublicKeySize) + binary.BigEndian.PutUint64(publicKey[types.SessionPublicKeySize-8:], i) + require.NoError(t, f.keeper.AppendSessionKeyToSmartAccount( + f.ctx, + identity, + accountAddress, + types.SessionKey{PublicKey: publicKey, ExpiresAtHeight: expiresAtHeight}, + )) + } + + server := keeper.NewQueryServerImpl(f.keeper) + firstPage, err := server.GetSessionKeysByIdentity( + f.ctx, + &types.QueryGetSessionKeysByIdentityRequest{Identity: identity}, + ) + require.NoError(t, err) + require.Len(t, firstPage.SessionKeys, 100) + require.Equal(t, uint64(105), firstPage.Pagination.Total) + require.Len(t, firstPage.Pagination.NextKey, 8) + + secondPage, err := server.GetSessionKeysByIdentity( + f.ctx, + &types.QueryGetSessionKeysByIdentityRequest{ + Identity: identity, + Pagination: &query.PageRequest{ + Key: firstPage.Pagination.NextKey, + Limit: 100, + }, + }, + ) + require.NoError(t, err) + require.Len(t, secondPage.SessionKeys, 5) + require.Equal(t, uint64(105), secondPage.Pagination.Total) + require.Empty(t, secondPage.Pagination.NextKey) +} + +// TestGetSessionKeysByIdentityRejectsInvalidPagination verifies that unsupported +// or malformed pagination options return InvalidArgument. +func TestGetSessionKeysByIdentityRejectsInvalidPagination(t *testing.T) { + f := initFixture(t) + identity := bytes.Repeat([]byte{0x01}, types.IdentitySize) + require.NoError(t, f.keeper.AppendSessionKeyToSmartAccount( + f.ctx, + identity, + f.keeper.GetAuthority(), + types.SessionKey{ + PublicKey: bytes.Repeat([]byte{0x02}, types.SessionPublicKeySize), + ExpiresAtHeight: uint64(sdk.UnwrapSDKContext(f.ctx).BlockHeight()) + 100, + }, + )) + + server := keeper.NewQueryServerImpl(f.keeper) + tests := []struct { + name string + pagination *query.PageRequest + }{ + {name: "reverse", pagination: &query.PageRequest{Reverse: true}}, + {name: "malformed key", pagination: &query.PageRequest{Key: []byte{0x01}}}, + {name: "key and offset", pagination: &query.PageRequest{Key: make([]byte, 8), Offset: 1}}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := server.GetSessionKeysByIdentity( + f.ctx, + &types.QueryGetSessionKeysByIdentityRequest{ + Identity: identity, + Pagination: test.pagination, + }, + ) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + }) + } +} + +// TestGetSessionKeysByIdentityOffsetAndLimit verifies offset-based pagination, +// session-key ordering, account ownership, total count, and the next-page key. +func TestGetSessionKeysByIdentityOffsetAndLimit(t *testing.T) { + f := initFixture(t) + identity := bytes.Repeat([]byte{0x01}, types.IdentitySize) + accountAddress := f.keeper.GetAuthority() + expiresAtHeight := uint64(sdk.UnwrapSDKContext(f.ctx).BlockHeight()) + 100 + + for i := byte(1); i <= 5; i++ { + publicKey := bytes.Repeat([]byte{i}, types.SessionPublicKeySize) + require.NoError(t, f.keeper.AppendSessionKeyToSmartAccount( + f.ctx, + identity, + accountAddress, + types.SessionKey{PublicKey: publicKey, ExpiresAtHeight: expiresAtHeight}, + )) + } + + response, err := keeper.NewQueryServerImpl(f.keeper).GetSessionKeysByIdentity( + f.ctx, + &types.QueryGetSessionKeysByIdentityRequest{ + Identity: identity, + Pagination: &query.PageRequest{ + Offset: 2, + Limit: 2, + }, + }, + ) + require.NoError(t, err) + require.Equal(t, accountAddress, response.AccountAddress) + require.Len(t, response.SessionKeys, 2) + require.Equal(t, bytes.Repeat([]byte{0x03}, types.SessionPublicKeySize), response.SessionKeys[0].PublicKey) + require.Equal(t, bytes.Repeat([]byte{0x04}, types.SessionPublicKeySize), response.SessionKeys[1].PublicKey) + require.Equal(t, uint64(5), response.Pagination.Total) + require.Equal(t, uint64(4), binary.BigEndian.Uint64(response.Pagination.NextKey)) +} + +// TestGetSessionKeysByIdentityRejectsInvalidRequest verifies request and identity +// validation, including the response for an unknown identity. +func TestGetSessionKeysByIdentityRejectsInvalidRequest(t *testing.T) { + f := initFixture(t) + server := keeper.NewQueryServerImpl(f.keeper) + + tests := []struct { + name string + req *types.QueryGetSessionKeysByIdentityRequest + want codes.Code + }{ + {name: "nil request", want: codes.InvalidArgument}, + { + name: "empty identity", + req: &types.QueryGetSessionKeysByIdentityRequest{}, + want: codes.InvalidArgument, + }, + { + name: "invalid identity size", + req: &types.QueryGetSessionKeysByIdentityRequest{Identity: []byte{0x01}}, + want: codes.InvalidArgument, + }, + { + name: "unknown identity", + req: &types.QueryGetSessionKeysByIdentityRequest{ + Identity: bytes.Repeat([]byte{0x01}, types.IdentitySize), + }, + want: codes.NotFound, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := server.GetSessionKeysByIdentity(f.ctx, test.req) + require.Equal(t, test.want, status.Code(err)) + }) + } +} diff --git a/x/smartaccounts/keeper/query_params.go b/x/smartaccounts/keeper/query_params.go new file mode 100644 index 00000000..c2e5d846 --- /dev/null +++ b/x/smartaccounts/keeper/query_params.go @@ -0,0 +1,26 @@ +package keeper + +import ( + "context" + "errors" + + "cosmossdk.io/collections" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +func (q queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + params, err := q.k.Params.Get(ctx) + if err != nil && !errors.Is(err, collections.ErrNotFound) { + return nil, status.Error(codes.Internal, "internal error") + } + + return &types.QueryParamsResponse{Params: params}, nil +} diff --git a/x/smartaccounts/keeper/query_params_test.go b/x/smartaccounts/keeper/query_params_test.go new file mode 100644 index 00000000..643ef346 --- /dev/null +++ b/x/smartaccounts/keeper/query_params_test.go @@ -0,0 +1,23 @@ +package keeper_test + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/keeper" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +func TestParamsQuery(t *testing.T) { + f := initFixture(t) + + qs := keeper.NewQueryServerImpl(f.keeper) + params := types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)) + require.NoError(t, f.keeper.Params.Set(f.ctx, params)) + + response, err := qs.Params(f.ctx, &types.QueryParamsRequest{}) + require.NoError(t, err) + require.Equal(t, &types.QueryParamsResponse{Params: params}, response) +} diff --git a/x/smartaccounts/keeper/smart_accounts_test.go b/x/smartaccounts/keeper/smart_accounts_test.go new file mode 100644 index 00000000..ba3c4a9e --- /dev/null +++ b/x/smartaccounts/keeper/smart_accounts_test.go @@ -0,0 +1,153 @@ +package keeper_test + +import ( + "bytes" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +func TestAppendSessionKeyToSmartAccount(t *testing.T) { + f := initFixture(t) + identity := bytes.Repeat([]byte{0x01}, types.IdentitySize) + accountAddress := f.keeper.GetAuthority() + key := types.SessionKey{ + PublicKey: bytes.Repeat([]byte{0x02}, types.SessionPublicKeySize), + ExpiresAtHeight: 10, + } + + exists, err := f.keeper.HasSmartAccount(f.ctx, identity) + require.NoError(t, err) + require.False(t, exists) + + require.NoError(t, f.keeper.AppendSessionKeyToSmartAccount(f.ctx, identity, accountAddress, key)) + + exists, err = f.keeper.HasSmartAccount(f.ctx, identity) + require.NoError(t, err) + require.True(t, exists) + + err = f.keeper.AppendSessionKeyToSmartAccount(f.ctx, identity, accountAddress, key) + require.ErrorIs(t, err, types.ErrSessionKeyAlreadyExists) + + genesis, err := f.keeper.ExportGenesis(f.ctx) + require.NoError(t, err) + require.Len(t, genesis.SmartAccounts, 1) + require.Equal(t, accountAddress, genesis.SmartAccounts[0].Account.AccountAddress) +} + +func TestAppendSessionKeyPrunesExpiredKeys(t *testing.T) { + f := initFixture(t) + identity := bytes.Repeat([]byte{0x01}, types.IdentitySize) + accountAddress := f.keeper.GetAuthority() + expiringKey := types.SessionKey{ + PublicKey: bytes.Repeat([]byte{0x02}, types.SessionPublicKeySize), + ExpiresAtHeight: 2, + } + + f.ctx = sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(1) + require.NoError(t, f.keeper.AppendSessionKeyToSmartAccount(f.ctx, identity, accountAddress, expiringKey)) + + f.ctx = sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(2) + activeKey := types.SessionKey{ + PublicKey: bytes.Repeat([]byte{0x03}, types.SessionPublicKeySize), + ExpiresAtHeight: 3, + } + require.NoError(t, f.keeper.AppendSessionKeyToSmartAccount(f.ctx, identity, accountAddress, activeKey)) + + genesis, err := f.keeper.ExportGenesis(f.ctx) + require.NoError(t, err) + require.Len(t, genesis.SmartAccounts, 1) + require.Equal(t, accountAddress, genesis.SmartAccounts[0].Account.AccountAddress) + require.Equal(t, []types.SessionKey{activeKey}, genesis.SmartAccounts[0].Account.SessionKeys) +} + +func TestIsSessionKeyAuthorized(t *testing.T) { + f := initFixture(t) + identity := bytes.Repeat([]byte{0x01}, types.IdentitySize) + unknownIdentity := bytes.Repeat([]byte{0x02}, types.IdentitySize) + accountAddress := f.keeper.GetAuthority() + publicKey := bytes.Repeat([]byte{0x03}, types.SessionPublicKeySize) + key := types.SessionKey{ + PublicKey: publicKey, + ExpiresAtHeight: 3, + } + + f.ctx = sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(1) + require.NoError(t, f.keeper.AppendSessionKeyToSmartAccount(f.ctx, identity, accountAddress, key)) + + authorized, err := f.keeper.IsSessionKeyAuthorized(f.ctx, identity, accountAddress, publicKey) + require.NoError(t, err) + require.True(t, authorized) + + authorized, err = f.keeper.IsSessionKeyAuthorized(f.ctx, unknownIdentity, accountAddress, publicKey) + require.NoError(t, err) + require.False(t, authorized) + + otherAddress := bytes.Repeat([]byte{0x09}, 20) + _, err = f.keeper.IsSessionKeyAuthorized(f.ctx, identity, otherAddress, publicKey) + require.ErrorIs(t, err, types.ErrAccountAddressMismatch) + + f.ctx = sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(3) + authorized, err = f.keeper.IsSessionKeyAuthorized(f.ctx, identity, accountAddress, publicKey) + require.NoError(t, err) + require.False(t, authorized) +} + +func TestAppendSessionKeyRejectsDifferentAccountAddress(t *testing.T) { + f := initFixture(t) + identity := bytes.Repeat([]byte{0x01}, types.IdentitySize) + accountAddress := f.keeper.GetAuthority() + key := types.SessionKey{ + PublicKey: bytes.Repeat([]byte{0x02}, types.SessionPublicKeySize), + ExpiresAtHeight: 10, + } + + require.NoError(t, f.keeper.AppendSessionKeyToSmartAccount(f.ctx, identity, accountAddress, key)) + + otherAddress := bytes.Repeat([]byte{0x09}, 20) + otherKey := types.SessionKey{ + PublicKey: bytes.Repeat([]byte{0x03}, types.SessionPublicKeySize), + ExpiresAtHeight: 11, + } + err := f.keeper.AppendSessionKeyToSmartAccount(f.ctx, identity, otherAddress, otherKey) + require.ErrorIs(t, err, types.ErrAccountAddressMismatch) +} + +func TestAppendSessionKeyRejectsInvalidAccountAddress(t *testing.T) { + f := initFixture(t) + identity := bytes.Repeat([]byte{0x01}, types.IdentitySize) + key := types.SessionKey{ + PublicKey: bytes.Repeat([]byte{0x02}, types.SessionPublicKeySize), + ExpiresAtHeight: 10, + } + + err := f.keeper.AppendSessionKeyToSmartAccount(f.ctx, identity, nil, key) + require.ErrorIs(t, err, types.ErrNilAccountAddress) + + err = f.keeper.AppendSessionKeyToSmartAccount(f.ctx, identity, bytes.Repeat([]byte{0x03}, 256), key) + require.ErrorIs(t, err, types.ErrInvalidAccountAddress) +} + +func TestHasSmartAccountValidation(t *testing.T) { + f := initFixture(t) + + tests := []struct { + name string + identity []byte + want error + }{ + {name: "nil identity", identity: nil, want: types.ErrNilIdentity}, + {name: "empty identity", identity: []byte{}, want: types.ErrNilIdentity}, + {name: "invalid identity length", identity: []byte{0x01}, want: types.ErrIdentityInvalidLength}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := f.keeper.HasSmartAccount(f.ctx, test.identity) + require.ErrorIs(t, err, test.want) + }) + } +} diff --git a/x/smartaccounts/module/autocli.go b/x/smartaccounts/module/autocli.go new file mode 100644 index 00000000..36d395c1 --- /dev/null +++ b/x/smartaccounts/module/autocli.go @@ -0,0 +1,52 @@ +package smartaccounts + +import ( + autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +// AutoCLIOptions implements the autocli.HasAutoCLIConfig interface. +func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { + return &autocliv1.ModuleOptions{ + Query: &autocliv1.ServiceCommandDescriptor{ + Service: types.Query_serviceDesc.ServiceName, + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "Params", + Use: "params", + Short: "Shows the parameters of the module", + }, + { + RpcMethod: "GetSessionKeysByIdentity", + Use: "get-session-keys-by-identity [identity]", + Short: "Query GetSessionKeysByIdentity", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{ + {ProtoField: "identity"}, + }, + }, + }, + }, + Tx: &autocliv1.ServiceCommandDescriptor{ + Service: types.Msg_serviceDesc.ServiceName, + EnhanceCustomCommand: true, // only required if you want to use the custom command + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "UpdateParams", + Skip: true, // skipped because authority gated + }, + { + RpcMethod: "AddPublicKey", + Use: "add-public-key [verification-id] [session-public-key] [expires-at-height] [identity]", + Short: "Add a session public key to a smart account", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{ + {ProtoField: "verification_id"}, + {ProtoField: "public_key_inputs.session_public_key"}, + {ProtoField: "public_key_inputs.expires_at_height"}, + {ProtoField: "public_key_inputs.identity"}, + }, + }, + }, + }, + } +} diff --git a/x/smartaccounts/module/depinject.go b/x/smartaccounts/module/depinject.go new file mode 100644 index 00000000..cf6f666f --- /dev/null +++ b/x/smartaccounts/module/depinject.go @@ -0,0 +1,65 @@ +package smartaccounts + +import ( + "cosmossdk.io/core/address" + "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/store" + "cosmossdk.io/depinject" + "cosmossdk.io/depinject/appconfig" + "github.com/cosmos/cosmos-sdk/codec" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/keeper" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" + verificationkeeper "github.com/node101-io/pulsar-chain/x/verification/keeper" +) + +var _ depinject.OnePerModuleType = AppModule{} + +// IsOnePerModuleType implements the depinject.OnePerModuleType interface. +func (AppModule) IsOnePerModuleType() {} + +func init() { + appconfig.Register( + &types.Module{}, + appconfig.Provide(ProvideModule), + ) +} + +type ModuleInputs struct { + depinject.In + + Config *types.Module + StoreService store.KVStoreService + Cdc codec.Codec + AddressCodec address.Codec + + AuthKeeper types.AuthKeeper + BankKeeper types.BankKeeper + VerificationKeeper verificationkeeper.Keeper +} + +type ModuleOutputs struct { + depinject.Out + + SmartaccountsKeeper keeper.Keeper + Module appmodule.AppModule +} + +func ProvideModule(in ModuleInputs) ModuleOutputs { + // default to governance authority if not provided + authority := authtypes.NewModuleAddress(types.GovModuleName) + if in.Config.Authority != "" { + authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority) + } + k := keeper.NewKeeper( + in.StoreService, + in.Cdc, + in.AddressCodec, + authority, + in.VerificationKeeper, + ) + m := NewAppModule(in.Cdc, k, in.AuthKeeper, in.BankKeeper) + + return ModuleOutputs{SmartaccountsKeeper: k, Module: m} +} diff --git a/x/smartaccounts/module/module.go b/x/smartaccounts/module/module.go new file mode 100644 index 00000000..012795da --- /dev/null +++ b/x/smartaccounts/module/module.go @@ -0,0 +1,143 @@ +package smartaccounts + +import ( + "context" + "encoding/json" + "fmt" + + "cosmossdk.io/core/appmodule" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "google.golang.org/grpc" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/keeper" + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +var ( + _ module.AppModuleBasic = (*AppModule)(nil) + _ module.AppModule = (*AppModule)(nil) //nolint:staticcheck // Legacy Cosmos SDK module interface is still required by the scaffold. + _ module.HasGenesis = (*AppModule)(nil) + + _ appmodule.AppModule = (*AppModule)(nil) + _ appmodule.HasBeginBlocker = (*AppModule)(nil) + _ appmodule.HasEndBlocker = (*AppModule)(nil) +) + +// AppModule implements the AppModule interface that defines the inter-dependent methods that modules need to implement +type AppModule struct { + cdc codec.Codec + keeper keeper.Keeper + authKeeper types.AuthKeeper + bankKeeper types.BankKeeper +} + +func NewAppModule( + cdc codec.Codec, + keeper keeper.Keeper, + authKeeper types.AuthKeeper, + bankKeeper types.BankKeeper, +) AppModule { + return AppModule{ + cdc: cdc, + keeper: keeper, + authKeeper: authKeeper, + bankKeeper: bankKeeper, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (AppModule) IsAppModule() {} + +// Name returns the name of the module as a string. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the amino codec +func (AppModule) RegisterLegacyAminoCodec(*codec.LegacyAmino) {} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + if err := types.RegisterQueryHandlerClient(clientCtx.CmdContext, mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } +} + +// RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message. +func (AppModule) RegisterInterfaces(registrar codectypes.InterfaceRegistry) { + types.RegisterInterfaces(registrar) +} + +// RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries +func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { + types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper)) + types.RegisterQueryServer(registrar, keeper.NewQueryServerImpl(am.keeper)) + + return nil +} + +// DefaultGenesis returns a default GenesisState for the module, marshalled to json.RawMessage. +// The default GenesisState need to be defined by the module developer and is primarily used for testing. +func (am AppModule) DefaultGenesis(codec.JSONCodec) json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesis()) +} + +// ValidateGenesis used to validate the GenesisState, given in its json.RawMessage form. +func (am AppModule) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { + var genState types.GenesisState + if err := am.cdc.UnmarshalJSON(bz, &genState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return genState.Validate() +} + +// InitGenesis performs the module's genesis initialization. It returns no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, _ codec.JSONCodec, gs json.RawMessage) { + var genState types.GenesisState + // Initialize global index to index in genesis state + if err := am.cdc.UnmarshalJSON(gs, &genState); err != nil { + panic(fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)) + } + + if err := am.keeper.InitGenesis(ctx, genState); err != nil { + panic(fmt.Errorf("failed to initialize %s genesis state: %w", types.ModuleName, err)) + } +} + +// ExportGenesis returns the module's exported genesis state as raw JSON bytes. +func (am AppModule) ExportGenesis(ctx sdk.Context, _ codec.JSONCodec) json.RawMessage { + genState, err := am.keeper.ExportGenesis(ctx) + if err != nil { + panic(fmt.Errorf("failed to export %s genesis state: %w", types.ModuleName, err)) + } + + bz, err := am.cdc.MarshalJSON(genState) + if err != nil { + panic(fmt.Errorf("failed to marshal %s genesis state: %w", types.ModuleName, err)) + } + + return bz +} + +// ConsensusVersion is a sequence number for state-breaking change of the module. +// It should be incremented on each consensus-breaking change introduced by the module. +// To avoid wrong/empty versions, the initial version should be set to 1. +func (AppModule) ConsensusVersion() uint64 { return 1 } + +// BeginBlock contains the logic that is automatically triggered at the beginning of each block. +// The begin block implementation is optional. +func (am AppModule) BeginBlock(_ context.Context) error { + return nil +} + +// EndBlock contains the logic that is automatically triggered at the end of each block. +// The end block implementation is optional. +func (am AppModule) EndBlock(_ context.Context) error { + return nil +} diff --git a/x/smartaccounts/module/simulation.go b/x/smartaccounts/module/simulation.go new file mode 100644 index 00000000..98148909 --- /dev/null +++ b/x/smartaccounts/module/simulation.go @@ -0,0 +1,36 @@ +package smartaccounts + +import ( + "bytes" + + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +// GenerateGenesisState creates a randomized GenState of the module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + accs := make([]string, len(simState.Accounts)) + for i, acc := range simState.Accounts { + accs[i] = acc.Address.String() + } + smartaccountsGenesis := types.GenesisState{ + Params: types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)), + } + simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&smartaccountsGenesis) +} + +// RegisterStoreDecoder registers a decoder. +func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) {} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { + operations := make([]simtypes.WeightedOperation, 0) + return operations +} + +// ProposalMsgs returns msgs used for governance proposals for simulations. +func (am AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg { + return []simtypes.WeightedProposalMsg{} +} diff --git a/x/smartaccounts/types/codec.go b/x/smartaccounts/types/codec.go new file mode 100644 index 00000000..bf8f4db7 --- /dev/null +++ b/x/smartaccounts/types/codec.go @@ -0,0 +1,18 @@ +package types + +import ( + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" +) + +func RegisterInterfaces(registrar codectypes.InterfaceRegistry) { + registrar.RegisterImplementations((*sdk.Msg)(nil), + &MsgAddPublicKey{}, + ) + + registrar.RegisterImplementations((*sdk.Msg)(nil), + &MsgUpdateParams{}, + ) + msgservice.RegisterMsgServiceDesc(registrar, &_Msg_serviceDesc) +} diff --git a/x/smartaccounts/types/errors.go b/x/smartaccounts/types/errors.go new file mode 100644 index 00000000..6c8d41ac --- /dev/null +++ b/x/smartaccounts/types/errors.go @@ -0,0 +1,27 @@ +package types + +// DONTCOVER + +import ( + "cosmossdk.io/errors" +) + +// x/smartaccounts module sentinel errors +var ( + ErrInvalidSigner = errors.Register(ModuleName, 1100, "expected gov account as only signer for proposal message") + ErrNilPublicKey = errors.Register(ModuleName, 1101, "nil public key") + ErrPublicKeyInvalidLength = errors.Register(ModuleName, 1102, "public key invalid length") + ErrInvalidExpirationHeight = errors.Register(ModuleName, 1103, "invalid expiration height") + ErrNilIdentity = errors.Register(ModuleName, 1104, "nil identity") + ErrSessionKeyAlreadyExists = errors.Register(ModuleName, 1105, "session key already exists") + ErrIdentityInvalidLength = errors.Register(ModuleName, 1106, "identity invalid length") + ErrNilPublicKeyInputs = errors.Register(ModuleName, 1107, "nil public key inputs") + ErrNilVerificationID = errors.Register(ModuleName, 1108, "nil verification ID") + ErrVerificationIDInvalidLength = errors.Register(ModuleName, 1109, "verification ID invalid length") + ErrProofNotValid = errors.Register(ModuleName, 1110, "proof is not valid") + ErrVerificationKeyMismatch = errors.Register(ModuleName, 1111, "verification key hash mismatch") + ErrInvalidPublicInputsHash = errors.Register(ModuleName, 1112, "invalid public inputs hash") + ErrNilAccountAddress = errors.Register(ModuleName, 1113, "nil account address") + ErrInvalidAccountAddress = errors.Register(ModuleName, 1114, "invalid account address") + ErrAccountAddressMismatch = errors.Register(ModuleName, 1115, "account address mismatch") +) diff --git a/x/smartaccounts/types/expected_keepers.go b/x/smartaccounts/types/expected_keepers.go new file mode 100644 index 00000000..0af7f80a --- /dev/null +++ b/x/smartaccounts/types/expected_keepers.go @@ -0,0 +1,34 @@ +package types + +import ( + "context" + + "cosmossdk.io/core/address" + sdk "github.com/cosmos/cosmos-sdk/types" + + verificationtypes "github.com/node101-io/pulsar-chain/x/verification/types" +) + +// AuthKeeper defines the expected interface for the Auth module. +type AuthKeeper interface { + AddressCodec() address.Codec + GetAccount(context.Context, sdk.AccAddress) sdk.AccountI // only used for simulation + // Methods imported from account should be defined here +} + +// BankKeeper defines the expected interface for the Bank module. +type BankKeeper interface { + SpendableCoins(context.Context, sdk.AccAddress) sdk.Coins + // Methods imported from bank should be defined here +} + +// ParamSubspace defines the expected Subspace interface for parameters. +type ParamSubspace interface { + Get(context.Context, []byte, interface{}) + Set(context.Context, []byte, interface{}) +} + +// VerificationKeeper defines the proof-result lookup required by smartaccounts. +type VerificationKeeper interface { + FinalProofResultByVerificationID(ctx context.Context, verificationID []byte) (verificationtypes.FinalProofResult, error) +} diff --git a/x/smartaccounts/types/genesis.go b/x/smartaccounts/types/genesis.go new file mode 100644 index 00000000..b90aa6e0 --- /dev/null +++ b/x/smartaccounts/types/genesis.go @@ -0,0 +1,74 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// DefaultGenesis returns the default genesis state +func DefaultGenesis() *GenesisState { + return &GenesisState{ + Params: DefaultParams(), + SmartAccounts: []SmartAccountEntry{}, + } +} + +// Validate performs basic genesis state validation returning an error upon any +// failure. +func (gs GenesisState) Validate() error { + if err := gs.Params.Validate(); err != nil { + return err + } + + identities := make(map[string]struct{}, len(gs.SmartAccounts)) + for i, entry := range gs.SmartAccounts { + if len(entry.Identity) != IdentitySize { + return fmt.Errorf( + "smart account %d identity must be %d bytes: got %d", + i, + IdentitySize, + len(entry.Identity), + ) + } + + identity := string(entry.Identity) + if _, exists := identities[identity]; exists { + return fmt.Errorf("duplicate smart account identity at index %d", i) + } + identities[identity] = struct{}{} + + if err := sdk.VerifyAddressFormat(entry.Account.AccountAddress); err != nil { + return fmt.Errorf("smart account %d has invalid account address: %w", i, err) + } + + sessionKeys := make(map[string]map[uint64]struct{}, len(entry.Account.SessionKeys)) + for j, key := range entry.Account.SessionKeys { + if len(key.PublicKey) != SessionPublicKeySize { + return fmt.Errorf( + "smart account %d session key %d must be %d bytes: got %d", + i, + j, + SessionPublicKeySize, + len(key.PublicKey), + ) + } + if key.ExpiresAtHeight == 0 { + return fmt.Errorf("smart account %d session key %d has zero expiration height", i, j) + } + + publicKey := string(key.PublicKey) + expirations, exists := sessionKeys[publicKey] + if !exists { + expirations = make(map[uint64]struct{}) + sessionKeys[publicKey] = expirations + } + if _, exists := expirations[key.ExpiresAtHeight]; exists { + return fmt.Errorf("duplicate session key at smart account %d index %d", i, j) + } + expirations[key.ExpiresAtHeight] = struct{}{} + } + } + + return nil +} diff --git a/x/smartaccounts/types/genesis.pb.go b/x/smartaccounts/types/genesis.pb.go new file mode 100644 index 00000000..5bf2276d --- /dev/null +++ b/x/smartaccounts/types/genesis.pb.go @@ -0,0 +1,621 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: pulsarchain/smartaccounts/v1/genesis.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// GenesisState defines the smartaccounts module's genesis state. +type GenesisState struct { + // params defines all the parameters of the module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + SmartAccounts []SmartAccountEntry `protobuf:"bytes,2,rep,name=smart_accounts,json=smartAccounts,proto3" json:"smart_accounts"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_a0f3311099fd44bf, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func (m *GenesisState) GetSmartAccounts() []SmartAccountEntry { + if m != nil { + return m.SmartAccounts + } + return nil +} + +// SmartAccountEntry associates an identity with its smart-account state. +type SmartAccountEntry struct { + Identity []byte `protobuf:"bytes,1,opt,name=identity,proto3" json:"identity,omitempty"` + Account SmartAccount `protobuf:"bytes,2,opt,name=account,proto3" json:"account"` +} + +func (m *SmartAccountEntry) Reset() { *m = SmartAccountEntry{} } +func (m *SmartAccountEntry) String() string { return proto.CompactTextString(m) } +func (*SmartAccountEntry) ProtoMessage() {} +func (*SmartAccountEntry) Descriptor() ([]byte, []int) { + return fileDescriptor_a0f3311099fd44bf, []int{1} +} +func (m *SmartAccountEntry) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SmartAccountEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SmartAccountEntry.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SmartAccountEntry) XXX_Merge(src proto.Message) { + xxx_messageInfo_SmartAccountEntry.Merge(m, src) +} +func (m *SmartAccountEntry) XXX_Size() int { + return m.Size() +} +func (m *SmartAccountEntry) XXX_DiscardUnknown() { + xxx_messageInfo_SmartAccountEntry.DiscardUnknown(m) +} + +var xxx_messageInfo_SmartAccountEntry proto.InternalMessageInfo + +func (m *SmartAccountEntry) GetIdentity() []byte { + if m != nil { + return m.Identity + } + return nil +} + +func (m *SmartAccountEntry) GetAccount() SmartAccount { + if m != nil { + return m.Account + } + return SmartAccount{} +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "pulsarchain.smartaccounts.v1.GenesisState") + proto.RegisterType((*SmartAccountEntry)(nil), "pulsarchain.smartaccounts.v1.SmartAccountEntry") +} + +func init() { + proto.RegisterFile("pulsarchain/smartaccounts/v1/genesis.proto", fileDescriptor_a0f3311099fd44bf) +} + +var fileDescriptor_a0f3311099fd44bf = []byte{ + // 324 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x2a, 0x28, 0xcd, 0x29, + 0x4e, 0x2c, 0x4a, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0xce, 0x4d, 0x2c, 0x2a, 0x49, 0x4c, 0x4e, + 0xce, 0x2f, 0xcd, 0x2b, 0x29, 0xd6, 0x2f, 0x33, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, + 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x41, 0x52, 0xab, 0x87, 0xa2, 0x56, 0xaf, 0xcc, + 0x50, 0x4a, 0x30, 0x31, 0x37, 0x33, 0x2f, 0x5f, 0x1f, 0x4c, 0x42, 0x34, 0x48, 0x89, 0xa4, 0xe7, + 0xa7, 0xe7, 0x83, 0x99, 0xfa, 0x20, 0x16, 0x54, 0x54, 0x13, 0xaf, 0x95, 0x05, 0x89, 0x45, 0x89, + 0xb9, 0x50, 0x1b, 0xa5, 0x34, 0xf0, 0x2a, 0x2d, 0xa9, 0x2c, 0x48, 0x85, 0xaa, 0x54, 0xda, 0xca, + 0xc8, 0xc5, 0xe3, 0x0e, 0x71, 0x6d, 0x70, 0x49, 0x62, 0x49, 0xaa, 0x90, 0x3b, 0x17, 0x1b, 0xc4, + 0x28, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x6e, 0x23, 0x15, 0x3d, 0x7c, 0xae, 0xd7, 0x0b, 0x00, 0xab, + 0x75, 0xe2, 0x3c, 0x71, 0x4f, 0x9e, 0x61, 0xc5, 0xf3, 0x0d, 0x5a, 0x8c, 0x41, 0x50, 0xed, 0x42, + 0x31, 0x5c, 0x7c, 0x60, 0xd5, 0xf1, 0x30, 0xe5, 0x12, 0x4c, 0x0a, 0xcc, 0x1a, 0xdc, 0x46, 0xfa, + 0xf8, 0x0d, 0x0c, 0x06, 0x09, 0x38, 0x42, 0x04, 0x5c, 0xf3, 0x4a, 0x8a, 0x2a, 0x9d, 0x58, 0x40, + 0x66, 0x07, 0xf1, 0x16, 0x23, 0x49, 0x14, 0x2b, 0x55, 0x73, 0x09, 0x62, 0xa8, 0x14, 0x92, 0xe2, + 0xe2, 0xc8, 0x4c, 0x49, 0xcd, 0x2b, 0xc9, 0x2c, 0xa9, 0x04, 0xbb, 0x9e, 0x27, 0x08, 0xce, 0x17, + 0xf2, 0xe2, 0x62, 0x87, 0x5a, 0x23, 0xc1, 0x04, 0xf6, 0x98, 0x16, 0xf1, 0xee, 0x80, 0x3a, 0x01, + 0x66, 0x80, 0x53, 0xd0, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, + 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0x59, 0xa4, + 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xe7, 0xe5, 0xa7, 0xa4, 0x1a, 0x1a, + 0x18, 0xea, 0x66, 0xe6, 0xeb, 0x43, 0x6c, 0xd2, 0x85, 0xc4, 0x47, 0x05, 0x5a, 0x8c, 0x80, 0xa3, + 0x23, 0x89, 0x0d, 0x1c, 0x1f, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7d, 0x27, 0x85, 0xd5, + 0x59, 0x02, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.SmartAccounts) > 0 { + for iNdEx := len(m.SmartAccounts) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.SmartAccounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *SmartAccountEntry) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SmartAccountEntry) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SmartAccountEntry) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Account.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Identity) > 0 { + i -= len(m.Identity) + copy(dAtA[i:], m.Identity) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.Identity))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovGenesis(uint64(l)) + if len(m.SmartAccounts) > 0 { + for _, e := range m.SmartAccounts { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func (m *SmartAccountEntry) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Identity) + if l > 0 { + n += 1 + l + sovGenesis(uint64(l)) + } + l = m.Account.Size() + n += 1 + l + sovGenesis(uint64(l)) + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SmartAccounts", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SmartAccounts = append(m.SmartAccounts, SmartAccountEntry{}) + if err := m.SmartAccounts[len(m.SmartAccounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SmartAccountEntry) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SmartAccountEntry: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SmartAccountEntry: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Identity", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Identity = append(m.Identity[:0], dAtA[iNdEx:postIndex]...) + if m.Identity == nil { + m.Identity = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Account", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Account.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/smartaccounts/types/genesis_test.go b/x/smartaccounts/types/genesis_test.go new file mode 100644 index 00000000..bd1bb6d7 --- /dev/null +++ b/x/smartaccounts/types/genesis_test.go @@ -0,0 +1,116 @@ +package types_test + +import ( + "bytes" + "testing" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" + "github.com/stretchr/testify/require" +) + +func TestGenesisState_Validate(t *testing.T) { + tests := []struct { + desc string + genState *types.GenesisState + valid bool + }{ + { + desc: "default requires verification key hash", + genState: types.DefaultGenesis(), + valid: true, + }, + { + desc: "valid genesis state", + genState: &types.GenesisState{ + Params: types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)), + SmartAccounts: []types.SmartAccountEntry{ + { + Identity: bytes.Repeat([]byte{0x02}, types.IdentitySize), + Account: types.SmartAccount{ + AccountAddress: bytes.Repeat([]byte{0x04}, 20), + SessionKeys: []types.SessionKey{ + { + PublicKey: bytes.Repeat([]byte{0x03}, types.SessionPublicKeySize), + ExpiresAtHeight: 100, + }, + }}, + }, + }, + }, + valid: true, + }, + { + desc: "missing verification key hash", + genState: &types.GenesisState{}, + valid: false, + }, + { + desc: "invalid smart account identity", + genState: &types.GenesisState{ + Params: types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)), + SmartAccounts: []types.SmartAccountEntry{ + {Identity: []byte{0x01}}, + }, + }, + valid: false, + }, + { + desc: "duplicate smart account identity", + genState: &types.GenesisState{ + Params: types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)), + SmartAccounts: []types.SmartAccountEntry{ + { + Identity: bytes.Repeat([]byte{0x02}, types.IdentitySize), + Account: types.SmartAccount{AccountAddress: bytes.Repeat([]byte{0x04}, 20)}, + }, + { + Identity: bytes.Repeat([]byte{0x02}, types.IdentitySize), + Account: types.SmartAccount{AccountAddress: bytes.Repeat([]byte{0x05}, 20)}, + }, + }, + }, + valid: false, + }, + { + desc: "invalid session key", + genState: &types.GenesisState{ + Params: types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)), + SmartAccounts: []types.SmartAccountEntry{ + { + Identity: bytes.Repeat([]byte{0x02}, types.IdentitySize), + Account: types.SmartAccount{ + AccountAddress: bytes.Repeat([]byte{0x04}, 20), + SessionKeys: []types.SessionKey{ + {PublicKey: []byte{0x03}, ExpiresAtHeight: 100}, + }}, + }, + }, + }, + valid: false, + }, + { + desc: "missing account address", + genState: &types.GenesisState{ + Params: types.NewParams(bytes.Repeat([]byte{0x01}, types.VerificationKeyHashSize)), + SmartAccounts: []types.SmartAccountEntry{ + {Identity: bytes.Repeat([]byte{0x02}, types.IdentitySize)}, + }, + }, + valid: false, + }, + } + for _, tc := range tests { + t.Run(tc.desc, func(t *testing.T) { + err := tc.genState.Validate() + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} + +func TestDefaultGenesisIsValid(t *testing.T) { + require.NoError(t, types.DefaultGenesis().Validate()) +} diff --git a/x/smartaccounts/types/keys.go b/x/smartaccounts/types/keys.go new file mode 100644 index 00000000..a9274df4 --- /dev/null +++ b/x/smartaccounts/types/keys.go @@ -0,0 +1,21 @@ +package types + +import "cosmossdk.io/collections" + +const ( + // ModuleName defines the module name + ModuleName = "smartaccounts" + + // StoreKey defines the primary module store key + StoreKey = ModuleName + + // GovModuleName duplicates the gov module's name to avoid a dependency with x/gov. + // It should be synced with the gov module's name if it is ever changed. + // See: https://github.com/cosmos/cosmos-sdk/blob/v0.52.0-beta.2/x/gov/types/keys.go#L9 + GovModuleName = "gov" +) + +// ParamsKey is the prefix to retrieve all Params +var ParamsKey = collections.NewPrefix("p_smartaccounts") + +var SmartAccountsKey = collections.NewPrefix("smart_accounts_key") diff --git a/x/smartaccounts/types/module.pb.go b/x/smartaccounts/types/module.pb.go new file mode 100644 index 00000000..2ebc07f9 --- /dev/null +++ b/x/smartaccounts/types/module.pb.go @@ -0,0 +1,324 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: pulsarchain/smartaccounts/module/v1/module.proto + +package types + +import ( + _ "cosmossdk.io/api/cosmos/app/v1alpha1" + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// Module is the config object for the module. +type Module struct { + // authority defines the custom module authority. + // If not set, defaults to the governance module. + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` +} + +func (m *Module) Reset() { *m = Module{} } +func (m *Module) String() string { return proto.CompactTextString(m) } +func (*Module) ProtoMessage() {} +func (*Module) Descriptor() ([]byte, []int) { + return fileDescriptor_7f695f04f9c4d3b5, []int{0} +} +func (m *Module) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Module) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Module.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Module) XXX_Merge(src proto.Message) { + xxx_messageInfo_Module.Merge(m, src) +} +func (m *Module) XXX_Size() int { + return m.Size() +} +func (m *Module) XXX_DiscardUnknown() { + xxx_messageInfo_Module.DiscardUnknown(m) +} + +var xxx_messageInfo_Module proto.InternalMessageInfo + +func (m *Module) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func init() { + proto.RegisterType((*Module)(nil), "pulsarchain.smartaccounts.module.v1.Module") +} + +func init() { + proto.RegisterFile("pulsarchain/smartaccounts/module/v1/module.proto", fileDescriptor_7f695f04f9c4d3b5) +} + +var fileDescriptor_7f695f04f9c4d3b5 = []byte{ + // 217 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x28, 0x28, 0xcd, 0x29, + 0x4e, 0x2c, 0x4a, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0xce, 0x4d, 0x2c, 0x2a, 0x49, 0x4c, 0x4e, + 0xce, 0x2f, 0xcd, 0x2b, 0x29, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, 0xd5, 0x2f, 0x33, 0x84, + 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x94, 0x91, 0x74, 0xe8, 0xa1, 0xe8, 0xd0, 0x83, + 0xaa, 0x2b, 0x33, 0x94, 0x52, 0x48, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0x4f, 0x2c, 0x28, 0xd0, + 0x2f, 0x33, 0x4c, 0xcc, 0x29, 0xc8, 0x48, 0x44, 0x35, 0x46, 0x29, 0x89, 0x8b, 0xcd, 0x17, 0xcc, + 0x17, 0x92, 0xe1, 0xe2, 0x4c, 0x2c, 0x2d, 0xc9, 0xc8, 0x2f, 0xca, 0x2c, 0xa9, 0x94, 0x60, 0x54, + 0x60, 0xd4, 0xe0, 0x0c, 0x42, 0x08, 0x58, 0x59, 0xed, 0x3a, 0x30, 0xed, 0x16, 0xa3, 0x09, 0x97, + 0x51, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x5e, 0x7e, 0x4a, 0xaa, + 0xa1, 0x81, 0xa1, 0x6e, 0x66, 0xbe, 0x3e, 0xc4, 0x31, 0xba, 0x10, 0xf7, 0x57, 0xa0, 0xfa, 0xc0, + 0x29, 0xe8, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, + 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0x2c, 0x48, 0x37, 0x4d, + 0xbf, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0xec, 0x7c, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, + 0xff, 0x58, 0x5b, 0x34, 0x43, 0x39, 0x01, 0x00, 0x00, +} + +func (m *Module) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Module) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintModule(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintModule(dAtA []byte, offset int, v uint64) int { + offset -= sovModule(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Module) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovModule(uint64(l)) + } + return n +} + +func sovModule(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozModule(x uint64) (n int) { + return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Module) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Module: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Authority = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipModule(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthModule + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupModule + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthModule + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowModule = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/smartaccounts/types/params.go b/x/smartaccounts/types/params.go new file mode 100644 index 00000000..fae66538 --- /dev/null +++ b/x/smartaccounts/types/params.go @@ -0,0 +1,33 @@ +package types + +import ( + "bytes" + "fmt" +) + +const VerificationKeyHashSize = 32 + +// NewParams creates a new Params instance. +func NewParams(verificationKeyHash []byte) Params { + return Params{VerificationKeyHash: verificationKeyHash} +} + +// DefaultParams returns a default set of parameters. +func DefaultParams() Params { + return Params{ + VerificationKeyHash: bytes.Repeat([]byte{0x00}, VerificationKeyHashSize), + } +} + +// Validate validates the set of params. +func (p Params) Validate() error { + if len(p.VerificationKeyHash) != VerificationKeyHashSize { + return fmt.Errorf( + "verification key hash must be %d bytes: got %d", + VerificationKeyHashSize, + len(p.VerificationKeyHash), + ) + } + + return nil +} diff --git a/x/smartaccounts/types/params.pb.go b/x/smartaccounts/types/params.pb.go new file mode 100644 index 00000000..f1b87cb7 --- /dev/null +++ b/x/smartaccounts/types/params.pb.go @@ -0,0 +1,351 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: pulsarchain/smartaccounts/v1/params.proto + +package types + +import ( + bytes "bytes" + fmt "fmt" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// Params defines the parameters for the module. +type Params struct { + VerificationKeyHash []byte `protobuf:"bytes,1,opt,name=verification_key_hash,json=verificationKeyHash,proto3" json:"verification_key_hash,omitempty"` +} + +func (m *Params) Reset() { *m = Params{} } +func (m *Params) String() string { return proto.CompactTextString(m) } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_07ef7ec9bd065507, []int{0} +} +func (m *Params) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Params.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Params) XXX_Merge(src proto.Message) { + xxx_messageInfo_Params.Merge(m, src) +} +func (m *Params) XXX_Size() int { + return m.Size() +} +func (m *Params) XXX_DiscardUnknown() { + xxx_messageInfo_Params.DiscardUnknown(m) +} + +var xxx_messageInfo_Params proto.InternalMessageInfo + +func (m *Params) GetVerificationKeyHash() []byte { + if m != nil { + return m.VerificationKeyHash + } + return nil +} + +func init() { + proto.RegisterType((*Params)(nil), "pulsarchain.smartaccounts.v1.Params") +} + +func init() { + proto.RegisterFile("pulsarchain/smartaccounts/v1/params.proto", fileDescriptor_07ef7ec9bd065507) +} + +var fileDescriptor_07ef7ec9bd065507 = []byte{ + // 237 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x2c, 0x28, 0xcd, 0x29, + 0x4e, 0x2c, 0x4a, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0xce, 0x4d, 0x2c, 0x2a, 0x49, 0x4c, 0x4e, + 0xce, 0x2f, 0xcd, 0x2b, 0x29, 0xd6, 0x2f, 0x33, 0xd4, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, + 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x41, 0x52, 0xaa, 0x87, 0xa2, 0x54, 0xaf, 0xcc, 0x50, + 0x4a, 0x30, 0x31, 0x37, 0x33, 0x2f, 0x5f, 0x1f, 0x4c, 0x42, 0x34, 0x48, 0x89, 0xa4, 0xe7, 0xa7, + 0xe7, 0x83, 0x99, 0xfa, 0x20, 0x16, 0x44, 0x54, 0x29, 0x93, 0x8b, 0x2d, 0x00, 0x6c, 0xac, 0x90, + 0x11, 0x97, 0x68, 0x59, 0x6a, 0x51, 0x66, 0x5a, 0x66, 0x72, 0x62, 0x49, 0x66, 0x7e, 0x5e, 0x7c, + 0x76, 0x6a, 0x65, 0x7c, 0x46, 0x62, 0x71, 0x86, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x4f, 0x90, 0x30, + 0xb2, 0xa4, 0x77, 0x6a, 0xa5, 0x47, 0x62, 0x71, 0x86, 0x95, 0xf6, 0x8b, 0x05, 0xf2, 0x8c, 0x5d, + 0xcf, 0x37, 0x68, 0x29, 0x21, 0x3b, 0xbc, 0x02, 0xcd, 0xe9, 0x10, 0x0b, 0x9c, 0x82, 0x4e, 0x3c, + 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, + 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0xca, 0x22, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, + 0x2f, 0x39, 0x3f, 0x57, 0x3f, 0x2f, 0x3f, 0x25, 0xd5, 0xd0, 0xc0, 0x50, 0x37, 0x33, 0x5f, 0x1f, + 0x62, 0xa6, 0x2e, 0x76, 0x43, 0x4b, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0xbe, 0x30, 0x06, + 0x04, 0x00, 0x00, 0xff, 0xff, 0xd0, 0xda, 0x82, 0x63, 0x39, 0x01, 0x00, 0x00, +} + +func (this *Params) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Params) + if !ok { + that2, ok := that.(Params) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.VerificationKeyHash, that1.VerificationKeyHash) { + return false + } + return true +} +func (m *Params) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.VerificationKeyHash) > 0 { + i -= len(m.VerificationKeyHash) + copy(dAtA[i:], m.VerificationKeyHash) + i = encodeVarintParams(dAtA, i, uint64(len(m.VerificationKeyHash))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintParams(dAtA []byte, offset int, v uint64) int { + offset -= sovParams(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.VerificationKeyHash) + if l > 0 { + n += 1 + l + sovParams(uint64(l)) + } + return n +} + +func sovParams(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozParams(x uint64) (n int) { + return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Params) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Params: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VerificationKeyHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.VerificationKeyHash = append(m.VerificationKeyHash[:0], dAtA[iNdEx:postIndex]...) + if m.VerificationKeyHash == nil { + m.VerificationKeyHash = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipParams(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthParams + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupParams + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthParams + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/smartaccounts/types/public_input_hash.go b/x/smartaccounts/types/public_input_hash.go new file mode 100644 index 00000000..b176b7e1 --- /dev/null +++ b/x/smartaccounts/types/public_input_hash.go @@ -0,0 +1,54 @@ +package types + +import ( + "crypto/sha256" + "encoding/binary" +) + +const publicInputFieldSize = 32 + +// ComputePublicInputsHash encodes and hashes the smart-account public inputs. +func ComputePublicInputsHash(inputs *PublicKeyInputs, accountAddress []byte) ([]byte, error) { + if inputs == nil { + return nil, ErrNilPublicKeyInputs + } + if inputs.SessionPublicKey == nil { + return nil, ErrNilPublicKey + } + if len(inputs.SessionPublicKey) != SessionPublicKeySize { + return nil, ErrPublicKeyInvalidLength + } + if inputs.ExpiresAtHeight == 0 { + return nil, ErrInvalidExpirationHeight + } + if len(inputs.Identity) == 0 { + return nil, ErrNilIdentity + } + if len(inputs.Identity) != IdentitySize { + return nil, ErrIdentityInvalidLength + } + if len(accountAddress) == 0 { + return nil, ErrNilAccountAddress + } + if len(accountAddress) != AccountAddressSize { + return nil, ErrInvalidAccountAddress + } + + rawPublicInputs := make([]byte, 0, 4*publicInputFieldSize) + rawPublicInputs = append(rawPublicInputs, inputs.SessionPublicKey...) + + var expiresAtHeight [publicInputFieldSize]byte + binary.BigEndian.PutUint64( + expiresAtHeight[publicInputFieldSize-8:], + inputs.ExpiresAtHeight, + ) + rawPublicInputs = append(rawPublicInputs, expiresAtHeight[:]...) + rawPublicInputs = append(rawPublicInputs, inputs.Identity...) + + var accountAddressField [publicInputFieldSize]byte + copy(accountAddressField[publicInputFieldSize-len(accountAddress):], accountAddress) + rawPublicInputs = append(rawPublicInputs, accountAddressField[:]...) + + hash := sha256.Sum256(rawPublicInputs) + return hash[:], nil +} diff --git a/x/smartaccounts/types/public_input_hash_test.go b/x/smartaccounts/types/public_input_hash_test.go new file mode 100644 index 00000000..6efa95b6 --- /dev/null +++ b/x/smartaccounts/types/public_input_hash_test.go @@ -0,0 +1,122 @@ +package types_test + +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/node101-io/pulsar-chain/x/smartaccounts/types" +) + +func TestComputePublicInputsHash(t *testing.T) { + inputs := validPublicKeyInputs() + accountAddress := bytes.Repeat([]byte{0x33}, types.AccountAddressSize) + + rawPublicInputs := make([]byte, 128) + copy(rawPublicInputs[:32], inputs.SessionPublicKey) + binary.BigEndian.PutUint64(rawPublicInputs[56:64], inputs.ExpiresAtHeight) + copy(rawPublicInputs[64:96], inputs.Identity) + copy(rawPublicInputs[128-types.AccountAddressSize:], accountAddress) + expected := sha256.Sum256(rawPublicInputs) + + actual, err := types.ComputePublicInputsHash(inputs, accountAddress) + require.NoError(t, err) + require.Equal(t, expected[:], actual) +} + +func TestComputePublicInputsHashValidation(t *testing.T) { + + validPublicKeyInputs := validPublicKeyInputs() + validAccountAddress := bytes.Repeat([]byte{0x33}, types.AccountAddressSize) + + tests := []struct { + name string + inputs *types.PublicKeyInputs + accountAddress []byte + want error + }{ + { + name: "nil inputs", + accountAddress: validAccountAddress, + want: types.ErrNilPublicKeyInputs, + }, + { + name: "nil public key", + inputs: &types.PublicKeyInputs{ + ExpiresAtHeight: validPublicKeyInputs.ExpiresAtHeight, + Identity: validPublicKeyInputs.Identity, + }, + accountAddress: validAccountAddress, + want: types.ErrNilPublicKey, + }, + { + name: "invalid public key length", + inputs: &types.PublicKeyInputs{ + SessionPublicKey: validPublicKeyInputs.SessionPublicKey[:types.SessionPublicKeySize-1], + ExpiresAtHeight: validPublicKeyInputs.ExpiresAtHeight, + Identity: validPublicKeyInputs.Identity, + }, + accountAddress: validAccountAddress, + want: types.ErrPublicKeyInvalidLength, + }, + { + name: "zero expiration height", + inputs: &types.PublicKeyInputs{ + SessionPublicKey: validPublicKeyInputs.SessionPublicKey, + ExpiresAtHeight: 0, + Identity: validPublicKeyInputs.Identity, + }, + accountAddress: validAccountAddress, + want: types.ErrInvalidExpirationHeight, + }, + { + name: "nil identity", + inputs: &types.PublicKeyInputs{ + SessionPublicKey: validPublicKeyInputs.SessionPublicKey, + ExpiresAtHeight: validPublicKeyInputs.ExpiresAtHeight, + }, + accountAddress: validAccountAddress, + want: types.ErrNilIdentity, + }, + { + name: "invalid identity length", + inputs: &types.PublicKeyInputs{ + SessionPublicKey: validPublicKeyInputs.SessionPublicKey, + ExpiresAtHeight: validPublicKeyInputs.ExpiresAtHeight, + Identity: validPublicKeyInputs.Identity[:types.IdentitySize-1], + }, + accountAddress: validAccountAddress, + want: types.ErrIdentityInvalidLength, + }, + { + name: "nil account address", + inputs: validPublicKeyInputs, + accountAddress: nil, + want: types.ErrNilAccountAddress, + }, + { + name: "invalid account address length", + inputs: validPublicKeyInputs, + accountAddress: validAccountAddress[:types.AccountAddressSize-1], + want: types.ErrInvalidAccountAddress, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := types.ComputePublicInputsHash(test.inputs, test.accountAddress) + require.ErrorIs(t, err, test.want) + }) + } +} + +func validPublicKeyInputs() *types.PublicKeyInputs { + return &types.PublicKeyInputs{ + SessionPublicKey: bytes.Repeat([]byte{0x11}, types.SessionPublicKeySize), + ExpiresAtHeight: 42, + Identity: bytes.Repeat([]byte{0x22}, types.IdentitySize), + } +} diff --git a/x/smartaccounts/types/query.pb.go b/x/smartaccounts/types/query.pb.go new file mode 100644 index 00000000..6c549cf0 --- /dev/null +++ b/x/smartaccounts/types/query.pb.go @@ -0,0 +1,1122 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: pulsarchain/smartaccounts/v1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + query "github.com/cosmos/cosmos-sdk/types/query" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// QueryParamsRequest is request type for the Query/Params RPC method. +type QueryParamsRequest struct { +} + +func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } +func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryParamsRequest) ProtoMessage() {} +func (*QueryParamsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_a3b4a6c0fe689fae, []int{0} +} +func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsRequest.Merge(m, src) +} +func (m *QueryParamsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo + +// QueryParamsResponse is response type for the Query/Params RPC method. +type QueryParamsResponse struct { + // params holds all the parameters of this module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } +func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryParamsResponse) ProtoMessage() {} +func (*QueryParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_a3b4a6c0fe689fae, []int{1} +} +func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsResponse.Merge(m, src) +} +func (m *QueryParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo + +func (m *QueryParamsResponse) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +// QueryGetSessionKeysByIdentityRequest defines the QueryGetSessionKeysByIdentityRequest message. +type QueryGetSessionKeysByIdentityRequest struct { + Identity []byte `protobuf:"bytes,1,opt,name=identity,proto3" json:"identity,omitempty"` + Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryGetSessionKeysByIdentityRequest) Reset() { *m = QueryGetSessionKeysByIdentityRequest{} } +func (m *QueryGetSessionKeysByIdentityRequest) String() string { return proto.CompactTextString(m) } +func (*QueryGetSessionKeysByIdentityRequest) ProtoMessage() {} +func (*QueryGetSessionKeysByIdentityRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_a3b4a6c0fe689fae, []int{2} +} +func (m *QueryGetSessionKeysByIdentityRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetSessionKeysByIdentityRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetSessionKeysByIdentityRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryGetSessionKeysByIdentityRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetSessionKeysByIdentityRequest.Merge(m, src) +} +func (m *QueryGetSessionKeysByIdentityRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryGetSessionKeysByIdentityRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetSessionKeysByIdentityRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetSessionKeysByIdentityRequest proto.InternalMessageInfo + +func (m *QueryGetSessionKeysByIdentityRequest) GetIdentity() []byte { + if m != nil { + return m.Identity + } + return nil +} + +func (m *QueryGetSessionKeysByIdentityRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryGetSessionKeysByIdentityResponse defines the QueryGetSessionKeysByIdentityResponse message. +type QueryGetSessionKeysByIdentityResponse struct { + AccountAddress []byte `protobuf:"bytes,1,opt,name=account_address,json=accountAddress,proto3" json:"account_address,omitempty"` + SessionKeys []*SessionKey `protobuf:"bytes,2,rep,name=session_keys,json=sessionKeys,proto3" json:"session_keys,omitempty"` + Pagination *query.PageResponse `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryGetSessionKeysByIdentityResponse) Reset() { *m = QueryGetSessionKeysByIdentityResponse{} } +func (m *QueryGetSessionKeysByIdentityResponse) String() string { return proto.CompactTextString(m) } +func (*QueryGetSessionKeysByIdentityResponse) ProtoMessage() {} +func (*QueryGetSessionKeysByIdentityResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_a3b4a6c0fe689fae, []int{3} +} +func (m *QueryGetSessionKeysByIdentityResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetSessionKeysByIdentityResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetSessionKeysByIdentityResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryGetSessionKeysByIdentityResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetSessionKeysByIdentityResponse.Merge(m, src) +} +func (m *QueryGetSessionKeysByIdentityResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryGetSessionKeysByIdentityResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetSessionKeysByIdentityResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetSessionKeysByIdentityResponse proto.InternalMessageInfo + +func (m *QueryGetSessionKeysByIdentityResponse) GetAccountAddress() []byte { + if m != nil { + return m.AccountAddress + } + return nil +} + +func (m *QueryGetSessionKeysByIdentityResponse) GetSessionKeys() []*SessionKey { + if m != nil { + return m.SessionKeys + } + return nil +} + +func (m *QueryGetSessionKeysByIdentityResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +func init() { + proto.RegisterType((*QueryParamsRequest)(nil), "pulsarchain.smartaccounts.v1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "pulsarchain.smartaccounts.v1.QueryParamsResponse") + proto.RegisterType((*QueryGetSessionKeysByIdentityRequest)(nil), "pulsarchain.smartaccounts.v1.QueryGetSessionKeysByIdentityRequest") + proto.RegisterType((*QueryGetSessionKeysByIdentityResponse)(nil), "pulsarchain.smartaccounts.v1.QueryGetSessionKeysByIdentityResponse") +} + +func init() { + proto.RegisterFile("pulsarchain/smartaccounts/v1/query.proto", fileDescriptor_a3b4a6c0fe689fae) +} + +var fileDescriptor_a3b4a6c0fe689fae = []byte{ + // 533 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x53, 0xc1, 0x6e, 0x13, 0x3b, + 0x14, 0x8d, 0x13, 0xbd, 0xe8, 0xe1, 0x54, 0x20, 0x4c, 0x17, 0x51, 0x54, 0x0d, 0x55, 0x54, 0x68, + 0xa8, 0x54, 0x3b, 0x13, 0x36, 0xdd, 0x12, 0xa4, 0x06, 0x54, 0x09, 0x95, 0x61, 0xc7, 0x82, 0xc8, + 0x33, 0xb1, 0xa6, 0x16, 0x1d, 0x7b, 0x3a, 0xf6, 0x44, 0xcc, 0x96, 0x25, 0x2b, 0x24, 0x3e, 0xa2, + 0x2c, 0xf9, 0x8c, 0x2e, 0x2b, 0xb1, 0x61, 0x85, 0x50, 0x82, 0xe0, 0x03, 0xf8, 0x01, 0x14, 0xdb, + 0x25, 0x09, 0xa8, 0x93, 0x22, 0x36, 0x91, 0x73, 0xe7, 0x9e, 0x7b, 0xce, 0xf1, 0xb9, 0x86, 0x9d, + 0x34, 0x3f, 0x56, 0x34, 0x8b, 0x8e, 0x28, 0x17, 0x44, 0x25, 0x34, 0xd3, 0x34, 0x8a, 0x64, 0x2e, + 0xb4, 0x22, 0x63, 0x9f, 0x9c, 0xe4, 0x2c, 0x2b, 0x70, 0x9a, 0x49, 0x2d, 0xd1, 0xc6, 0x42, 0x27, + 0x5e, 0xea, 0xc4, 0x63, 0xbf, 0x75, 0x93, 0x26, 0x5c, 0x48, 0x62, 0x7e, 0x2d, 0xa0, 0xb5, 0x13, + 0x49, 0x95, 0x48, 0x45, 0x42, 0xaa, 0x98, 0x9d, 0x44, 0xc6, 0x7e, 0xc8, 0x34, 0xf5, 0x49, 0x4a, + 0x63, 0x2e, 0xa8, 0xe6, 0x52, 0xb8, 0xde, 0xf5, 0x58, 0xc6, 0xd2, 0x1c, 0xc9, 0xec, 0xe4, 0xaa, + 0x1b, 0xb1, 0x94, 0xf1, 0x31, 0x23, 0x34, 0xe5, 0x84, 0x0a, 0x21, 0xb5, 0x81, 0x28, 0xf7, 0xf5, + 0x5e, 0xa9, 0xf4, 0x94, 0x66, 0x34, 0xb9, 0x68, 0x2d, 0x77, 0xa9, 0x8b, 0x94, 0xb9, 0xce, 0xf6, + 0x3a, 0x44, 0x4f, 0x67, 0x52, 0x0f, 0x0d, 0x3c, 0x60, 0x27, 0x39, 0x53, 0xba, 0xfd, 0x02, 0xde, + 0x5a, 0xaa, 0xaa, 0x54, 0x0a, 0xc5, 0xd0, 0x00, 0xd6, 0x2d, 0x4d, 0x13, 0x6c, 0x82, 0x4e, 0xa3, + 0xb7, 0x85, 0xcb, 0xee, 0x08, 0x5b, 0x74, 0xff, 0xda, 0xd9, 0xe7, 0xdb, 0x95, 0xf7, 0xdf, 0x3f, + 0xec, 0x80, 0xc0, 0xc1, 0xdb, 0x6f, 0x00, 0xdc, 0x32, 0x04, 0x03, 0xa6, 0x9f, 0x31, 0xa5, 0xb8, + 0x14, 0x07, 0xac, 0x50, 0xfd, 0xe2, 0xf1, 0x88, 0x09, 0xcd, 0x75, 0xe1, 0x84, 0xa0, 0x16, 0xfc, + 0x9f, 0xbb, 0x92, 0xe1, 0x5c, 0x0b, 0x7e, 0xfd, 0x47, 0xfb, 0x10, 0xce, 0xef, 0xb5, 0x59, 0x35, + 0x8a, 0xee, 0x62, 0x1b, 0x02, 0x9e, 0x85, 0x80, 0x6d, 0x9c, 0x2e, 0x04, 0x7c, 0x48, 0x63, 0xe6, + 0xe6, 0x06, 0x0b, 0xc8, 0xf6, 0x37, 0x00, 0xef, 0xac, 0x10, 0xe3, 0xfc, 0x6f, 0xc3, 0x1b, 0xce, + 0xdf, 0x90, 0x8e, 0x46, 0x19, 0x53, 0xca, 0x89, 0xba, 0xee, 0xca, 0x0f, 0x6c, 0x15, 0x1d, 0xc0, + 0x35, 0x65, 0x27, 0x0d, 0x5f, 0xb2, 0x42, 0x35, 0xab, 0x9b, 0xb5, 0x4e, 0xa3, 0xd7, 0x29, 0xbf, + 0xae, 0x39, 0x77, 0xd0, 0x50, 0x73, 0x1d, 0x68, 0xb0, 0xe4, 0xb3, 0x66, 0x7c, 0x6e, 0xaf, 0xf4, + 0x69, 0x25, 0x2f, 0x1a, 0xed, 0x9d, 0xd6, 0xe0, 0x7f, 0xc6, 0x28, 0x3a, 0x05, 0xb0, 0x6e, 0xd3, + 0x41, 0xdd, 0x72, 0x51, 0x7f, 0x2e, 0x47, 0xcb, 0xff, 0x0b, 0x84, 0x55, 0xd1, 0xde, 0x7b, 0xfd, + 0xf1, 0xeb, 0xbb, 0x6a, 0x0f, 0x75, 0x89, 0x90, 0x23, 0xe6, 0x77, 0xfd, 0x5d, 0x2e, 0x89, 0x9d, + 0xb2, 0x5b, 0xba, 0xcf, 0xe8, 0x07, 0x80, 0xcd, 0xcb, 0x72, 0x41, 0xfd, 0x2b, 0x28, 0x59, 0xb1, + 0x61, 0xad, 0x87, 0xff, 0x34, 0xc3, 0xf9, 0x7b, 0x62, 0xfc, 0x3d, 0x42, 0xfb, 0x57, 0xf7, 0x17, + 0x33, 0x3d, 0x5c, 0xdc, 0x91, 0x61, 0x58, 0x0c, 0x2f, 0x56, 0xbb, 0x1f, 0x9c, 0x4d, 0x3c, 0x70, + 0x3e, 0xf1, 0xc0, 0x97, 0x89, 0x07, 0xde, 0x4e, 0xbd, 0xca, 0xf9, 0xd4, 0xab, 0x7c, 0x9a, 0x7a, + 0x95, 0xe7, 0x7b, 0x31, 0xd7, 0x47, 0x79, 0x88, 0x23, 0x99, 0x5c, 0xca, 0xf5, 0xea, 0x37, 0x36, + 0xf3, 0xde, 0xc3, 0xba, 0x79, 0xf0, 0xf7, 0x7f, 0x06, 0x00, 0x00, 0xff, 0xff, 0x5e, 0x13, 0xb7, + 0x31, 0x02, 0x05, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + // Parameters queries the parameters of the module. + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + // GetSessionKeysByIdentity Queries a list of GetSessionKeysByIdentity items. + GetSessionKeysByIdentity(ctx context.Context, in *QueryGetSessionKeysByIdentityRequest, opts ...grpc.CallOption) (*QueryGetSessionKeysByIdentityResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/pulsarchain.smartaccounts.v1.Query/Params", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) GetSessionKeysByIdentity(ctx context.Context, in *QueryGetSessionKeysByIdentityRequest, opts ...grpc.CallOption) (*QueryGetSessionKeysByIdentityResponse, error) { + out := new(QueryGetSessionKeysByIdentityResponse) + err := c.cc.Invoke(ctx, "/pulsarchain.smartaccounts.v1.Query/GetSessionKeysByIdentity", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Parameters queries the parameters of the module. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + // GetSessionKeysByIdentity Queries a list of GetSessionKeysByIdentity items. + GetSessionKeysByIdentity(context.Context, *QueryGetSessionKeysByIdentityRequest) (*QueryGetSessionKeysByIdentityResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") +} +func (*UnimplementedQueryServer) GetSessionKeysByIdentity(ctx context.Context, req *QueryGetSessionKeysByIdentityRequest) (*QueryGetSessionKeysByIdentityResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetSessionKeysByIdentity not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryParamsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Params(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/pulsarchain.smartaccounts.v1.Query/Params", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_GetSessionKeysByIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryGetSessionKeysByIdentityRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).GetSessionKeysByIdentity(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/pulsarchain.smartaccounts.v1.Query/GetSessionKeysByIdentity", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).GetSessionKeysByIdentity(ctx, req.(*QueryGetSessionKeysByIdentityRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var Query_serviceDesc = _Query_serviceDesc +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "pulsarchain.smartaccounts.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + { + MethodName: "GetSessionKeysByIdentity", + Handler: _Query_GetSessionKeysByIdentity_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "pulsarchain/smartaccounts/v1/query.proto", +} + +func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *QueryGetSessionKeysByIdentityRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryGetSessionKeysByIdentityRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetSessionKeysByIdentityRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Identity) > 0 { + i -= len(m.Identity) + copy(dAtA[i:], m.Identity) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Identity))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryGetSessionKeysByIdentityResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryGetSessionKeysByIdentityResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetSessionKeysByIdentityResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if len(m.SessionKeys) > 0 { + for iNdEx := len(m.SessionKeys) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.SessionKeys[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.AccountAddress) > 0 { + i -= len(m.AccountAddress) + copy(dAtA[i:], m.AccountAddress) + i = encodeVarintQuery(dAtA, i, uint64(len(m.AccountAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryParamsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryGetSessionKeysByIdentityRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Identity) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryGetSessionKeysByIdentityResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.AccountAddress) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + if len(m.SessionKeys) > 0 { + for _, e := range m.SessionKeys { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryGetSessionKeysByIdentityRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryGetSessionKeysByIdentityRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetSessionKeysByIdentityRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Identity", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Identity = append(m.Identity[:0], dAtA[iNdEx:postIndex]...) + if m.Identity == nil { + m.Identity = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryGetSessionKeysByIdentityResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryGetSessionKeysByIdentityResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetSessionKeysByIdentityResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AccountAddress = append(m.AccountAddress[:0], dAtA[iNdEx:postIndex]...) + if m.AccountAddress == nil { + m.AccountAddress = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SessionKeys", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SessionKeys = append(m.SessionKeys, &SessionKey{}) + if err := m.SessionKeys[len(m.SessionKeys)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/smartaccounts/types/query.pb.gw.go b/x/smartaccounts/types/query.pb.gw.go new file mode 100644 index 00000000..d69570ae --- /dev/null +++ b/x/smartaccounts/types/query.pb.gw.go @@ -0,0 +1,236 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: pulsarchain/smartaccounts/v1/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := server.Params(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_Query_GetSessionKeysByIdentity_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_GetSessionKeysByIdentity_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetSessionKeysByIdentityRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_GetSessionKeysByIdentity_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.GetSessionKeysByIdentity(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_GetSessionKeysByIdentity_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetSessionKeysByIdentityRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_GetSessionKeysByIdentity_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.GetSessionKeysByIdentity(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_GetSessionKeysByIdentity_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_GetSessionKeysByIdentity_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_GetSessionKeysByIdentity_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_GetSessionKeysByIdentity_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_GetSessionKeysByIdentity_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_GetSessionKeysByIdentity_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"node101-io", "pulsar-chain", "smartaccounts", "v1", "params"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_GetSessionKeysByIdentity_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"node101-io", "pulsar-chain", "smartaccounts", "v1", "get_session_keys_by_identity"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_Params_0 = runtime.ForwardResponseMessage + + forward_Query_GetSessionKeysByIdentity_0 = runtime.ForwardResponseMessage +) diff --git a/x/smartaccounts/types/tx.pb.go b/x/smartaccounts/types/tx.pb.go new file mode 100644 index 00000000..f89d1c4c --- /dev/null +++ b/x/smartaccounts/types/tx.pb.go @@ -0,0 +1,1052 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: pulsarchain/smartaccounts/v1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// MsgUpdateParams is the Msg/UpdateParams request type. +type MsgUpdateParams struct { + // authority is the address that controls the module (defaults to x/gov unless overwritten). + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` + // params defines the module parameters to update. + // + // NOTE: All parameters must be supplied. + Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` +} + +func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } +func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParams) ProtoMessage() {} +func (*MsgUpdateParams) Descriptor() ([]byte, []int) { + return fileDescriptor_c2293ab44008f8fc, []int{0} +} +func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgUpdateParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParams.Merge(m, src) +} +func (m *MsgUpdateParams) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParams) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo + +func (m *MsgUpdateParams) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func (m *MsgUpdateParams) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +type MsgUpdateParamsResponse struct { +} + +func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } +func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParamsResponse) ProtoMessage() {} +func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_c2293ab44008f8fc, []int{1} +} +func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) +} +func (m *MsgUpdateParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo + +// MsgAddPublicKey defines the MsgAddPublicKey message. +type MsgAddPublicKey struct { + Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` + VerificationId []byte `protobuf:"bytes,2,opt,name=verification_id,json=verificationId,proto3" json:"verification_id,omitempty"` + PublicKeyInputs *PublicKeyInputs `protobuf:"bytes,3,opt,name=public_key_inputs,json=publicKeyInputs,proto3" json:"public_key_inputs,omitempty"` +} + +func (m *MsgAddPublicKey) Reset() { *m = MsgAddPublicKey{} } +func (m *MsgAddPublicKey) String() string { return proto.CompactTextString(m) } +func (*MsgAddPublicKey) ProtoMessage() {} +func (*MsgAddPublicKey) Descriptor() ([]byte, []int) { + return fileDescriptor_c2293ab44008f8fc, []int{2} +} +func (m *MsgAddPublicKey) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgAddPublicKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgAddPublicKey.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgAddPublicKey) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgAddPublicKey.Merge(m, src) +} +func (m *MsgAddPublicKey) XXX_Size() int { + return m.Size() +} +func (m *MsgAddPublicKey) XXX_DiscardUnknown() { + xxx_messageInfo_MsgAddPublicKey.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgAddPublicKey proto.InternalMessageInfo + +func (m *MsgAddPublicKey) GetCreator() string { + if m != nil { + return m.Creator + } + return "" +} + +func (m *MsgAddPublicKey) GetVerificationId() []byte { + if m != nil { + return m.VerificationId + } + return nil +} + +func (m *MsgAddPublicKey) GetPublicKeyInputs() *PublicKeyInputs { + if m != nil { + return m.PublicKeyInputs + } + return nil +} + +// MsgAddPublicKeyResponse defines the MsgAddPublicKeyResponse message. +type MsgAddPublicKeyResponse struct { +} + +func (m *MsgAddPublicKeyResponse) Reset() { *m = MsgAddPublicKeyResponse{} } +func (m *MsgAddPublicKeyResponse) String() string { return proto.CompactTextString(m) } +func (*MsgAddPublicKeyResponse) ProtoMessage() {} +func (*MsgAddPublicKeyResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_c2293ab44008f8fc, []int{3} +} +func (m *MsgAddPublicKeyResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgAddPublicKeyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgAddPublicKeyResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgAddPublicKeyResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgAddPublicKeyResponse.Merge(m, src) +} +func (m *MsgAddPublicKeyResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgAddPublicKeyResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgAddPublicKeyResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgAddPublicKeyResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgUpdateParams)(nil), "pulsarchain.smartaccounts.v1.MsgUpdateParams") + proto.RegisterType((*MsgUpdateParamsResponse)(nil), "pulsarchain.smartaccounts.v1.MsgUpdateParamsResponse") + proto.RegisterType((*MsgAddPublicKey)(nil), "pulsarchain.smartaccounts.v1.MsgAddPublicKey") + proto.RegisterType((*MsgAddPublicKeyResponse)(nil), "pulsarchain.smartaccounts.v1.MsgAddPublicKeyResponse") +} + +func init() { + proto.RegisterFile("pulsarchain/smartaccounts/v1/tx.proto", fileDescriptor_c2293ab44008f8fc) +} + +var fileDescriptor_c2293ab44008f8fc = []byte{ + // 492 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x53, 0x4f, 0x6b, 0x13, 0x41, + 0x14, 0xcf, 0x58, 0xac, 0x64, 0x0c, 0x86, 0x2e, 0x85, 0xa6, 0x41, 0xd6, 0x12, 0x14, 0x63, 0x24, + 0xbb, 0x26, 0xa2, 0x48, 0x0f, 0x42, 0x73, 0x91, 0x22, 0x85, 0xb2, 0xe2, 0x41, 0x2f, 0x61, 0xb2, + 0x3b, 0x4e, 0x06, 0xbb, 0x33, 0xc3, 0xcc, 0x6c, 0x68, 0x6e, 0xe2, 0xd1, 0x93, 0x1f, 0xc3, 0x63, + 0x0e, 0x7e, 0x88, 0x1e, 0x4b, 0x2f, 0x7a, 0x12, 0x49, 0x0e, 0xf9, 0x0a, 0x1e, 0x65, 0x67, 0x76, + 0xe9, 0x26, 0x84, 0x44, 0x2f, 0x21, 0xf3, 0xde, 0xef, 0xbd, 0xdf, 0x9f, 0x9d, 0x81, 0x0f, 0x44, + 0x72, 0xa6, 0x90, 0x0c, 0x87, 0x88, 0x32, 0x5f, 0xc5, 0x48, 0x6a, 0x14, 0x86, 0x3c, 0x61, 0x5a, + 0xf9, 0xa3, 0x8e, 0xaf, 0xcf, 0x3d, 0x21, 0xb9, 0xe6, 0xce, 0xdd, 0x02, 0xcc, 0x5b, 0x80, 0x79, + 0xa3, 0x4e, 0x7d, 0x07, 0xc5, 0x94, 0x71, 0xdf, 0xfc, 0xda, 0x81, 0xfa, 0x5e, 0xc8, 0x55, 0xcc, + 0x95, 0x1f, 0x2b, 0x92, 0x2e, 0x8a, 0x15, 0xc9, 0x1a, 0xfb, 0xb6, 0xd1, 0x37, 0x27, 0xdf, 0x1e, + 0xb2, 0xd6, 0x2e, 0xe1, 0x84, 0xdb, 0x7a, 0xfa, 0x2f, 0xab, 0x3e, 0x5a, 0xab, 0x50, 0x20, 0x89, + 0xe2, 0x7c, 0x41, 0x73, 0xbd, 0x99, 0xb1, 0xc0, 0x19, 0xb2, 0x71, 0x05, 0x60, 0xf5, 0x44, 0x91, + 0xb7, 0x22, 0x42, 0x1a, 0x9f, 0x9a, 0x1d, 0xce, 0x73, 0x58, 0x46, 0x89, 0x1e, 0x72, 0x49, 0xf5, + 0xb8, 0x06, 0x0e, 0x40, 0xb3, 0xdc, 0xab, 0x5d, 0x7d, 0x6f, 0xef, 0x66, 0x1a, 0x8f, 0xa2, 0x48, + 0x62, 0xa5, 0xde, 0x68, 0x49, 0x19, 0x09, 0xae, 0xa1, 0xce, 0x2b, 0xb8, 0x6d, 0x55, 0xd4, 0x6e, + 0x1c, 0x80, 0xe6, 0xed, 0xee, 0x7d, 0x6f, 0x5d, 0x58, 0x9e, 0x65, 0xeb, 0x95, 0x2f, 0x7e, 0xdd, + 0x2b, 0x7d, 0x9b, 0x4f, 0x5a, 0x20, 0xc8, 0xc6, 0x0f, 0x5f, 0x7e, 0x9e, 0x4f, 0x5a, 0xd7, 0x8b, + 0xbf, 0xcc, 0x27, 0xad, 0xc7, 0x45, 0x47, 0xe7, 0x4b, 0x9e, 0x96, 0x0c, 0x34, 0xf6, 0xe1, 0xde, + 0x52, 0x29, 0xc0, 0x4a, 0x70, 0xa6, 0x70, 0xe3, 0x87, 0xf5, 0x7b, 0x14, 0x45, 0xa7, 0xc9, 0xe0, + 0x8c, 0x86, 0xaf, 0xf1, 0xd8, 0xe9, 0xc2, 0x5b, 0xa1, 0xc4, 0x48, 0x73, 0xb9, 0xd1, 0x6d, 0x0e, + 0x74, 0x1e, 0xc2, 0xea, 0x08, 0x4b, 0xfa, 0x81, 0x86, 0x48, 0x53, 0xce, 0xfa, 0x34, 0x32, 0xa6, + 0x2b, 0xc1, 0x9d, 0x62, 0xf9, 0x38, 0x72, 0xde, 0xc1, 0x1d, 0x61, 0x98, 0xfa, 0x1f, 0xf1, 0xb8, + 0x4f, 0x99, 0x48, 0xb4, 0xaa, 0x6d, 0x99, 0x7c, 0xda, 0x1b, 0xf2, 0xc9, 0x05, 0x1e, 0x9b, 0xa1, + 0xa0, 0x2a, 0x16, 0x0b, 0x87, 0x95, 0x34, 0xa6, 0x5c, 0x51, 0x66, 0xba, 0x68, 0x2c, 0x37, 0xdd, + 0xfd, 0x03, 0xe0, 0xd6, 0x89, 0x22, 0x8e, 0x86, 0x95, 0x85, 0x0f, 0xbd, 0x41, 0xc0, 0x52, 0x86, + 0xf5, 0x67, 0xff, 0x05, 0xcf, 0xd9, 0x53, 0xd6, 0x85, 0xb8, 0x37, 0xb3, 0x16, 0xe1, 0xff, 0xc0, + 0xba, 0xca, 0x73, 0xfd, 0xe6, 0xa7, 0xf4, 0x4a, 0xf5, 0x82, 0x8b, 0xa9, 0x0b, 0x2e, 0xa7, 0x2e, + 0xf8, 0x3d, 0x75, 0xc1, 0xd7, 0x99, 0x5b, 0xba, 0x9c, 0xb9, 0xa5, 0x9f, 0x33, 0xb7, 0xf4, 0xfe, + 0x05, 0xa1, 0x7a, 0x98, 0x0c, 0xbc, 0x90, 0xc7, 0x3e, 0xe3, 0x11, 0xee, 0x3c, 0xe9, 0xb4, 0x29, + 0xf7, 0x2d, 0x59, 0x7b, 0xf5, 0x45, 0x33, 0x2f, 0x67, 0xb0, 0x6d, 0x9e, 0xce, 0xd3, 0xbf, 0x01, + 0x00, 0x00, 0xff, 0xff, 0x0a, 0xb9, 0x85, 0x51, 0x33, 0x04, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// MsgClient is the client API for Msg service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type MsgClient interface { + // UpdateParams defines a (governance) operation for updating the module + // parameters. The authority defaults to the x/gov module account. + UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) + // AddPublicKey defines the AddPublicKey RPC. + AddPublicKey(ctx context.Context, in *MsgAddPublicKey, opts ...grpc.CallOption) (*MsgAddPublicKeyResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { + out := new(MsgUpdateParamsResponse) + err := c.cc.Invoke(ctx, "/pulsarchain.smartaccounts.v1.Msg/UpdateParams", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) AddPublicKey(ctx context.Context, in *MsgAddPublicKey, opts ...grpc.CallOption) (*MsgAddPublicKeyResponse, error) { + out := new(MsgAddPublicKeyResponse) + err := c.cc.Invoke(ctx, "/pulsarchain.smartaccounts.v1.Msg/AddPublicKey", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + // UpdateParams defines a (governance) operation for updating the module + // parameters. The authority defaults to the x/gov module account. + UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) + // AddPublicKey defines the AddPublicKey RPC. + AddPublicKey(context.Context, *MsgAddPublicKey) (*MsgAddPublicKeyResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") +} +func (*UnimplementedMsgServer) AddPublicKey(ctx context.Context, req *MsgAddPublicKey) (*MsgAddPublicKeyResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method AddPublicKey not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateParams) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdateParams(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/pulsarchain.smartaccounts.v1.Msg/UpdateParams", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_AddPublicKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgAddPublicKey) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).AddPublicKey(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/pulsarchain.smartaccounts.v1.Msg/AddPublicKey", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).AddPublicKey(ctx, req.(*MsgAddPublicKey)) + } + return interceptor(ctx, in, info, handler) +} + +var Msg_serviceDesc = _Msg_serviceDesc +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "pulsarchain.smartaccounts.v1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "UpdateParams", + Handler: _Msg_UpdateParams_Handler, + }, + { + MethodName: "AddPublicKey", + Handler: _Msg_AddPublicKey_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "pulsarchain/smartaccounts/v1/tx.proto", +} + +func (m *MsgUpdateParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgAddPublicKey) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgAddPublicKey) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgAddPublicKey) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PublicKeyInputs != nil { + { + size, err := m.PublicKeyInputs.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if len(m.VerificationId) > 0 { + i -= len(m.VerificationId) + copy(dAtA[i:], m.VerificationId) + i = encodeVarintTx(dAtA, i, uint64(len(m.VerificationId))) + i-- + dAtA[i] = 0x12 + } + if len(m.Creator) > 0 { + i -= len(m.Creator) + copy(dAtA[i:], m.Creator) + i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgAddPublicKeyResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgAddPublicKeyResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgAddPublicKeyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgUpdateParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Params.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgUpdateParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgAddPublicKey) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Creator) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.VerificationId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.PublicKeyInputs != nil { + l = m.PublicKeyInputs.Size() + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgAddPublicKeyResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovTx(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTx(x uint64) (n int) { + return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgUpdateParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgUpdateParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Authority = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdateParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgUpdateParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgAddPublicKey) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgAddPublicKey: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgAddPublicKey: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Creator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VerificationId", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.VerificationId = append(m.VerificationId[:0], dAtA[iNdEx:postIndex]...) + if m.VerificationId == nil { + m.VerificationId = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKeyInputs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PublicKeyInputs == nil { + m.PublicKeyInputs = &PublicKeyInputs{} + } + if err := m.PublicKeyInputs.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgAddPublicKeyResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgAddPublicKeyResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgAddPublicKeyResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTx(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTx + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTx + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTx + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/smartaccounts/types/types.go b/x/smartaccounts/types/types.go new file mode 100644 index 00000000..96c57bc8 --- /dev/null +++ b/x/smartaccounts/types/types.go @@ -0,0 +1,8 @@ +package types + +const ( + SessionPublicKeySize = 32 + IdentitySize = 32 + AccountAddressSize = 20 + PublicInputsHashSize = 32 +) diff --git a/x/smartaccounts/types/types.pb.go b/x/smartaccounts/types/types.pb.go new file mode 100644 index 00000000..d964a1df --- /dev/null +++ b/x/smartaccounts/types/types.pb.go @@ -0,0 +1,865 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: pulsarchain/smartaccounts/v1/types.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// SmartAccount binds a Cosmos account address to its authorized session keys. +type SmartAccount struct { + AccountAddress []byte `protobuf:"bytes,1,opt,name=account_address,json=accountAddress,proto3" json:"account_address,omitempty"` + SessionKeys []SessionKey `protobuf:"bytes,2,rep,name=session_keys,json=sessionKeys,proto3" json:"session_keys"` +} + +func (m *SmartAccount) Reset() { *m = SmartAccount{} } +func (m *SmartAccount) String() string { return proto.CompactTextString(m) } +func (*SmartAccount) ProtoMessage() {} +func (*SmartAccount) Descriptor() ([]byte, []int) { + return fileDescriptor_5513da7f29cb5285, []int{0} +} +func (m *SmartAccount) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SmartAccount) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SmartAccount.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SmartAccount) XXX_Merge(src proto.Message) { + xxx_messageInfo_SmartAccount.Merge(m, src) +} +func (m *SmartAccount) XXX_Size() int { + return m.Size() +} +func (m *SmartAccount) XXX_DiscardUnknown() { + xxx_messageInfo_SmartAccount.DiscardUnknown(m) +} + +var xxx_messageInfo_SmartAccount proto.InternalMessageInfo + +func (m *SmartAccount) GetAccountAddress() []byte { + if m != nil { + return m.AccountAddress + } + return nil +} + +func (m *SmartAccount) GetSessionKeys() []SessionKey { + if m != nil { + return m.SessionKeys + } + return nil +} + +// SessionKey defines an Ed25519 public key and its exclusive expiration height. +type SessionKey struct { + PublicKey []byte `protobuf:"bytes,1,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` + ExpiresAtHeight uint64 `protobuf:"varint,2,opt,name=expires_at_height,json=expiresAtHeight,proto3" json:"expires_at_height,omitempty"` +} + +func (m *SessionKey) Reset() { *m = SessionKey{} } +func (m *SessionKey) String() string { return proto.CompactTextString(m) } +func (*SessionKey) ProtoMessage() {} +func (*SessionKey) Descriptor() ([]byte, []int) { + return fileDescriptor_5513da7f29cb5285, []int{1} +} +func (m *SessionKey) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SessionKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SessionKey.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SessionKey) XXX_Merge(src proto.Message) { + xxx_messageInfo_SessionKey.Merge(m, src) +} +func (m *SessionKey) XXX_Size() int { + return m.Size() +} +func (m *SessionKey) XXX_DiscardUnknown() { + xxx_messageInfo_SessionKey.DiscardUnknown(m) +} + +var xxx_messageInfo_SessionKey proto.InternalMessageInfo + +func (m *SessionKey) GetPublicKey() []byte { + if m != nil { + return m.PublicKey + } + return nil +} + +func (m *SessionKey) GetExpiresAtHeight() uint64 { + if m != nil { + return m.ExpiresAtHeight + } + return 0 +} + +// PublicKeyInputs defines the PublicKeyInputs message. +type PublicKeyInputs struct { + SessionPublicKey []byte `protobuf:"bytes,1,opt,name=session_public_key,json=sessionPublicKey,proto3" json:"session_public_key,omitempty"` + ExpiresAtHeight uint64 `protobuf:"varint,2,opt,name=expires_at_height,json=expiresAtHeight,proto3" json:"expires_at_height,omitempty"` + Identity []byte `protobuf:"bytes,3,opt,name=identity,proto3" json:"identity,omitempty"` +} + +func (m *PublicKeyInputs) Reset() { *m = PublicKeyInputs{} } +func (m *PublicKeyInputs) String() string { return proto.CompactTextString(m) } +func (*PublicKeyInputs) ProtoMessage() {} +func (*PublicKeyInputs) Descriptor() ([]byte, []int) { + return fileDescriptor_5513da7f29cb5285, []int{2} +} +func (m *PublicKeyInputs) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PublicKeyInputs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PublicKeyInputs.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PublicKeyInputs) XXX_Merge(src proto.Message) { + xxx_messageInfo_PublicKeyInputs.Merge(m, src) +} +func (m *PublicKeyInputs) XXX_Size() int { + return m.Size() +} +func (m *PublicKeyInputs) XXX_DiscardUnknown() { + xxx_messageInfo_PublicKeyInputs.DiscardUnknown(m) +} + +var xxx_messageInfo_PublicKeyInputs proto.InternalMessageInfo + +func (m *PublicKeyInputs) GetSessionPublicKey() []byte { + if m != nil { + return m.SessionPublicKey + } + return nil +} + +func (m *PublicKeyInputs) GetExpiresAtHeight() uint64 { + if m != nil { + return m.ExpiresAtHeight + } + return 0 +} + +func (m *PublicKeyInputs) GetIdentity() []byte { + if m != nil { + return m.Identity + } + return nil +} + +func init() { + proto.RegisterType((*SmartAccount)(nil), "pulsarchain.smartaccounts.v1.SmartAccount") + proto.RegisterType((*SessionKey)(nil), "pulsarchain.smartaccounts.v1.SessionKey") + proto.RegisterType((*PublicKeyInputs)(nil), "pulsarchain.smartaccounts.v1.PublicKeyInputs") +} + +func init() { + proto.RegisterFile("pulsarchain/smartaccounts/v1/types.proto", fileDescriptor_5513da7f29cb5285) +} + +var fileDescriptor_5513da7f29cb5285 = []byte{ + // 358 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x92, 0x4f, 0x4f, 0xf2, 0x40, + 0x10, 0xc6, 0xbb, 0x40, 0xde, 0xbc, 0x2e, 0x44, 0xa4, 0xf1, 0xd0, 0x10, 0xad, 0x84, 0x8b, 0x8d, + 0x91, 0xd6, 0xea, 0xc5, 0x2b, 0x9c, 0x34, 0x5e, 0xb0, 0x1c, 0x4c, 0xbc, 0x34, 0xa5, 0xdd, 0xb4, + 0x1b, 0x61, 0xb7, 0xe9, 0x6c, 0x09, 0xfd, 0x04, 0x26, 0x9e, 0xfc, 0x58, 0x1c, 0x39, 0x7a, 0x32, + 0x06, 0xbe, 0x88, 0x69, 0xb7, 0xe0, 0xbf, 0xc4, 0x83, 0x97, 0xcd, 0xec, 0x6f, 0xe6, 0x99, 0x99, + 0xec, 0x3e, 0xd8, 0x88, 0xd3, 0x09, 0x78, 0x89, 0x1f, 0x79, 0x94, 0x59, 0x30, 0xf5, 0x12, 0xe1, + 0xf9, 0x3e, 0x4f, 0x99, 0x00, 0x6b, 0x66, 0x5b, 0x22, 0x8b, 0x09, 0x98, 0x71, 0xc2, 0x05, 0x57, + 0x0f, 0x3e, 0x55, 0x9a, 0x5f, 0x2a, 0xcd, 0x99, 0xdd, 0x6e, 0x79, 0x53, 0xca, 0xb8, 0x55, 0x9c, + 0x52, 0xd0, 0xde, 0x0f, 0x79, 0xc8, 0x8b, 0xd0, 0xca, 0x23, 0x49, 0xbb, 0x4f, 0x08, 0x37, 0x46, + 0xb9, 0xba, 0x2f, 0xd5, 0xea, 0x31, 0x6e, 0x96, 0x8d, 0x5c, 0x2f, 0x08, 0x12, 0x02, 0xa0, 0xa1, + 0x0e, 0x32, 0x1a, 0xce, 0x6e, 0x89, 0xfb, 0x92, 0xaa, 0xb7, 0xb8, 0x01, 0x04, 0x80, 0x72, 0xe6, + 0x3e, 0x90, 0x0c, 0xb4, 0x4a, 0xa7, 0x6a, 0xd4, 0xcf, 0x0d, 0xf3, 0xb7, 0xbd, 0xcc, 0x91, 0x54, + 0xdc, 0x90, 0x6c, 0x50, 0x5b, 0xbc, 0x1e, 0x29, 0x4e, 0x1d, 0xb6, 0x04, 0xba, 0x77, 0x18, 0x7f, + 0x14, 0xa8, 0x87, 0x18, 0xc7, 0xe9, 0x78, 0x42, 0xfd, 0xbc, 0x7f, 0xb9, 0xc4, 0x8e, 0x24, 0x79, + 0xfa, 0x04, 0xb7, 0xc8, 0x3c, 0xa6, 0x09, 0x01, 0xd7, 0x13, 0x6e, 0x44, 0x68, 0x18, 0x09, 0xad, + 0xd2, 0x41, 0x46, 0xcd, 0x69, 0x96, 0x89, 0xbe, 0xb8, 0x2a, 0x70, 0xf7, 0x11, 0xe1, 0xe6, 0x70, + 0xa3, 0xbc, 0x66, 0x71, 0x2a, 0x40, 0x3d, 0xc5, 0xea, 0x66, 0xff, 0x1f, 0x63, 0xf6, 0xca, 0xcc, + 0xf0, 0x2f, 0xd3, 0xd4, 0x36, 0xfe, 0x4f, 0x03, 0xc2, 0x04, 0x15, 0x99, 0x56, 0x2d, 0xfa, 0x6d, + 0xef, 0x03, 0x67, 0xb1, 0xd2, 0xd1, 0x72, 0xa5, 0xa3, 0xb7, 0x95, 0x8e, 0x9e, 0xd7, 0xba, 0xb2, + 0x5c, 0xeb, 0xca, 0xcb, 0x5a, 0x57, 0xee, 0x2f, 0x43, 0x2a, 0xa2, 0x74, 0x6c, 0xfa, 0x7c, 0x6a, + 0x31, 0x1e, 0x10, 0xfb, 0xcc, 0xee, 0x51, 0x6e, 0xc9, 0xe7, 0xec, 0x49, 0x47, 0xcc, 0xbf, 0x79, + 0xa2, 0x30, 0xc4, 0xf8, 0x5f, 0xf1, 0x95, 0x17, 0xef, 0x01, 0x00, 0x00, 0xff, 0xff, 0xea, 0xf9, + 0xd0, 0x6b, 0x3d, 0x02, 0x00, 0x00, +} + +func (m *SmartAccount) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SmartAccount) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SmartAccount) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.SessionKeys) > 0 { + for iNdEx := len(m.SessionKeys) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.SessionKeys[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.AccountAddress) > 0 { + i -= len(m.AccountAddress) + copy(dAtA[i:], m.AccountAddress) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AccountAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *SessionKey) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SessionKey) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SessionKey) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ExpiresAtHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.ExpiresAtHeight)) + i-- + dAtA[i] = 0x10 + } + if len(m.PublicKey) > 0 { + i -= len(m.PublicKey) + copy(dAtA[i:], m.PublicKey) + i = encodeVarintTypes(dAtA, i, uint64(len(m.PublicKey))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PublicKeyInputs) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PublicKeyInputs) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PublicKeyInputs) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Identity) > 0 { + i -= len(m.Identity) + copy(dAtA[i:], m.Identity) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Identity))) + i-- + dAtA[i] = 0x1a + } + if m.ExpiresAtHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.ExpiresAtHeight)) + i-- + dAtA[i] = 0x10 + } + if len(m.SessionPublicKey) > 0 { + i -= len(m.SessionPublicKey) + copy(dAtA[i:], m.SessionPublicKey) + i = encodeVarintTypes(dAtA, i, uint64(len(m.SessionPublicKey))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *SmartAccount) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.AccountAddress) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.SessionKeys) > 0 { + for _, e := range m.SessionKeys { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *SessionKey) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.PublicKey) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.ExpiresAtHeight != 0 { + n += 1 + sovTypes(uint64(m.ExpiresAtHeight)) + } + return n +} + +func (m *PublicKeyInputs) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.SessionPublicKey) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.ExpiresAtHeight != 0 { + n += 1 + sovTypes(uint64(m.ExpiresAtHeight)) + } + l = len(m.Identity) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *SmartAccount) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SmartAccount: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SmartAccount: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AccountAddress = append(m.AccountAddress[:0], dAtA[iNdEx:postIndex]...) + if m.AccountAddress == nil { + m.AccountAddress = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SessionKeys", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SessionKeys = append(m.SessionKeys, SessionKey{}) + if err := m.SessionKeys[len(m.SessionKeys)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SessionKey) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SessionKey: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SessionKey: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PublicKey = append(m.PublicKey[:0], dAtA[iNdEx:postIndex]...) + if m.PublicKey == nil { + m.PublicKey = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ExpiresAtHeight", wireType) + } + m.ExpiresAtHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ExpiresAtHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PublicKeyInputs) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PublicKeyInputs: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PublicKeyInputs: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SessionPublicKey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SessionPublicKey = append(m.SessionPublicKey[:0], dAtA[iNdEx:postIndex]...) + if m.SessionPublicKey == nil { + m.SessionPublicKey = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ExpiresAtHeight", wireType) + } + m.ExpiresAtHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ExpiresAtHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Identity", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Identity = append(m.Identity[:0], dAtA[iNdEx:postIndex]...) + if m.Identity == nil { + m.Identity = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/verification/keeper/keeper.go b/x/verification/keeper/keeper.go index 4b76cdf0..83d3ba93 100644 --- a/x/verification/keeper/keeper.go +++ b/x/verification/keeper/keeper.go @@ -3,6 +3,7 @@ package keeper import ( "bytes" "context" + "errors" "fmt" "cosmossdk.io/collections" @@ -114,30 +115,40 @@ func (k Keeper) GetAuthority() []byte { return append([]byte(nil), k.authority...) } -func (k Keeper) FinalProofResultByProofHash( +// FinalProofResultByVerificationID resolves a finalized proof through its permanent verification ID. +func (k Keeper) FinalProofResultByVerificationID( ctx context.Context, - proofHash []byte, + verificationID []byte, ) (types.FinalProofResult, error) { - if len(proofHash) != types.ProofHashSize { - return types.FinalProofResult{}, types.ErrInvalidProofHash + if len(verificationID) != types.VerificationIDSize { + return types.FinalProofResult{}, types.ErrInvalidVerificationID } - iterator, err := k.FinalProofResults.Iterate(ctx, nil) + proofKey, err := k.SeenVerificationIDs.Get(ctx, verificationID) if err != nil { + if errors.Is(err, collections.ErrNotFound) { + return types.FinalProofResult{}, types.ErrProofNotFound + } return types.FinalProofResult{}, err } - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - result, err := iterator.Value() - if err != nil { - return types.FinalProofResult{}, err + result, err := k.FinalProofResults.Get( + ctx, + types.NewProofStoreKey( + proofKey.SubmissionHeight, + proofKey.IndexInBlock, + ), + ) + if err != nil { + if errors.Is(err, collections.ErrNotFound) { + return types.FinalProofResult{}, types.ErrProofNotFound } + return types.FinalProofResult{}, err + } - if bytes.Equal(result.ProofHash, proofHash) { - return result, nil - } + if !bytes.Equal(result.VerificationId, verificationID) { + return types.FinalProofResult{}, types.ErrProofStateCorrupted } - return types.FinalProofResult{}, types.ErrProofNotFound + return result, nil }