diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 9d8f23c1a3..42fb38c9c4 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -25,7 +25,7 @@ jobs: go.sum - uses: golangci/golangci-lint-action@v3.7.0 with: - version: v1.54.2 + version: v1.55.2 args: --timeout 10m github-token: ${{ secrets.github_token }} if: env.GIT_DIFF diff --git a/README.md b/README.md index 7d6baafd71..a33446a3bc 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ This repo attempts to conform to [conventional commits](https://www.conventional ### Tools -1. Install [golangci-lint](https://golangci-lint.run/usage/install/) +1. Install [golangci-lint](https://golangci-lint.run/usage/install/) 1.55.2 1. Install [markdownlint](https://github.com/DavidAnson/markdownlint) 1. Install [hadolint](https://github.com/hadolint/hadolint) 1. Install [yamllint](https://yamllint.readthedocs.io/en/stable/quickstart.html) diff --git a/app/app.go b/app/app.go index 90666e85b0..b8c68384b8 100644 --- a/app/app.go +++ b/app/app.go @@ -9,6 +9,7 @@ import ( mintkeeper "github.com/celestiaorg/celestia-app/x/mint/keeper" minttypes "github.com/celestiaorg/celestia-app/x/mint/types" "github.com/celestiaorg/celestia-app/x/upgrade" + upgradetypes "github.com/celestiaorg/celestia-app/x/upgrade/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" @@ -85,6 +86,7 @@ import ( "github.com/celestiaorg/celestia-app/app/ante" "github.com/celestiaorg/celestia-app/app/encoding" "github.com/celestiaorg/celestia-app/pkg/appconsts" + v1 "github.com/celestiaorg/celestia-app/pkg/appconsts/v1" v2 "github.com/celestiaorg/celestia-app/pkg/appconsts/v2" "github.com/celestiaorg/celestia-app/pkg/proof" blobmodule "github.com/celestiaorg/celestia-app/x/blob" @@ -155,11 +157,12 @@ var ( vesting.AppModuleBasic{}, blobmodule.AppModuleBasic{}, bsmodule.AppModuleBasic{}, + upgrade.AppModuleBasic{}, ) // ModuleEncodingRegisters keeps track of all the module methods needed to // register interfaces and specific type to encoding config - ModuleEncodingRegisters = extractRegisters(ModuleBasics, upgrade.TypeRegister{}) + ModuleEncodingRegisters = extractRegisters(ModuleBasics) // module account permissions maccPerms = map[string][]string{ @@ -267,9 +270,8 @@ func New( keys := sdk.NewKVStoreKeys( authtypes.StoreKey, authzkeeper.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, - govtypes.StoreKey, paramstypes.StoreKey, upgrade.StoreKey, feegrant.StoreKey, + govtypes.StoreKey, paramstypes.StoreKey, upgradetypes.StoreKey, feegrant.StoreKey, evidencetypes.StoreKey, capabilitytypes.StoreKey, - blobmoduletypes.StoreKey, bsmoduletypes.StoreKey, ibctransfertypes.StoreKey, ibchost.StoreKey, @@ -333,7 +335,7 @@ func New( ) app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.AccountKeeper) - app.UpgradeKeeper = upgrade.NewKeeper(keys[upgrade.StoreKey], upgradeHeight) + app.UpgradeKeeper = upgrade.NewKeeper(keys[upgradetypes.StoreKey], upgradeHeight, app.StakingKeeper) app.BlobstreamKeeper = *bsmodulekeeper.NewKeeper( appCodec, @@ -399,8 +401,6 @@ func New( app.BlobKeeper = *blobmodulekeeper.NewKeeper( appCodec, - keys[blobmoduletypes.StoreKey], - keys[blobmoduletypes.MemStoreKey], app.GetSubspace(blobmoduletypes.ModuleName), ) blobmod := blobmodule.NewAppModule(appCodec, app.BlobKeeper) @@ -442,6 +442,7 @@ func New( transferModule, blobmod, bsmod, + upgrade.NewAppModule(app.UpgradeKeeper), ) // During begin block slashing happens after distr.BeginBlocker so that @@ -468,7 +469,7 @@ func New( paramstypes.ModuleName, authz.ModuleName, vestingtypes.ModuleName, - upgrade.ModuleName, + upgradetypes.ModuleName, ) app.mm.SetOrderEndBlockers( @@ -491,7 +492,7 @@ func New( paramstypes.ModuleName, authz.ModuleName, vestingtypes.ModuleName, - upgrade.ModuleName, + upgradetypes.ModuleName, ) // NOTE: The genutils module must occur after staking so that pools are @@ -519,7 +520,7 @@ func New( feegrant.ModuleName, paramstypes.ModuleName, authz.ModuleName, - upgrade.ModuleName, + upgradetypes.ModuleName, ) app.QueryRouter().AddRoute(proof.TxInclusionQueryPath, proof.QueryTxInclusionProof) @@ -573,10 +574,17 @@ func (app *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.R // EndBlocker application updates every end block func (app *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { res := app.mm.EndBlock(ctx, req) - // NOTE: this is a specific feature for upgrading to v2 as v3 and onward is expected - // to be coordinated through the signalling protocol - if app.UpgradeKeeper.ShouldUpgrade(req.Height) { - app.SetAppVersion(ctx, v2.Version) + // NOTE: this is a specific feature for upgrading from v1 to v2. It will be deprecated in v3 + if app.UpgradeKeeper.ShouldUpgradeToV2(req.Height) { + if app.AppVersion(ctx) == v1.Version { + app.SetAppVersion(ctx, v2.Version) + } + // from v2 to v3 and onwards we use a signalling mechanism + } else if shouldUpgrade, version := app.UpgradeKeeper.ShouldUpgrade(); shouldUpgrade { + // Version changes must be increasing. Downgrades are not permitted + if version > app.AppVersion(ctx) { + app.SetAppVersion(ctx, version) + } } return res } diff --git a/app/test/block_production_test.go b/app/test/block_production_test.go index f8bfb5435a..2b3418677c 100644 --- a/app/test/block_production_test.go +++ b/app/test/block_production_test.go @@ -1,4 +1,4 @@ -package app +package app_test import ( "testing" diff --git a/app/test/integration_test.go b/app/test/integration_test.go index 775dfff370..ba2d1ab516 100644 --- a/app/test/integration_test.go +++ b/app/test/integration_test.go @@ -7,7 +7,6 @@ import ( "fmt" "os" "testing" - "time" "github.com/celestiaorg/celestia-app/test/util/blobfactory" "github.com/celestiaorg/celestia-app/test/util/testfactory" @@ -16,7 +15,6 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/suite" @@ -31,7 +29,6 @@ import ( "github.com/celestiaorg/celestia-app/pkg/user" blobtypes "github.com/celestiaorg/celestia-app/x/blob/types" - sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" tmrand "github.com/tendermint/tendermint/libs/rand" coretypes "github.com/tendermint/tendermint/types" @@ -54,12 +51,7 @@ type IntegrationTestSuite struct { func (s *IntegrationTestSuite) SetupSuite() { t := s.T() - - numAccounts := 142 - s.accounts = make([]string, numAccounts) - for i := 0; i < numAccounts; i++ { - s.accounts[i] = tmrand.Str(20) - } + s.accounts = testnode.RandomAccounts(142) cfg := testnode.DefaultConfig().WithFundedAccounts(s.accounts...) @@ -80,47 +72,41 @@ func (s *IntegrationTestSuite) SetupSuite() { func (s *IntegrationTestSuite) TestMaxBlockSize() { t := s.T() - // tendermint's default tx size limit is 1Mb, so we get close to that - equallySized1MbTxGen := func(c client.Context) []coretypes.Tx { + singleBlobTxGen := func(c client.Context) []coretypes.Tx { return blobfactory.RandBlobTxsWithAccounts( s.ecfg, tmrand.NewRand(), s.cctx.Keyring, c.GRPCClient, - 950000, + 600*kibibyte, 1, false, s.accounts[:20], ) } - // Tendermint's default tx size limit is 1 MiB, so we get close to that by - // generating transactions of size 600 KB because 3 blobs per transaction * - // 200,000 bytes each = 600,000 total bytes = 600 KB per transaction. - randMultiBlob1MbTxGen := func(c client.Context) []coretypes.Tx { + // This tx generator generates txs that contain 3 blobs each of 200 KiB so + // 600 KiB total per transaction. + multiBlobTxGen := func(c client.Context) []coretypes.Tx { return blobfactory.RandBlobTxsWithAccounts( s.ecfg, tmrand.NewRand(), s.cctx.Keyring, c.GRPCClient, - 200000, // 200 KB + 200*kibibyte, 3, false, s.accounts[20:40], ) } - // Generate 80 randomly sized txs (max size == 50 KB). Generate these - // transactions using some of the same accounts as the previous generator to - // ensure that the sequence number is being utilized correctly in blob - // txs - randoTxGen := func(c client.Context) []coretypes.Tx { + randomTxGen := func(c client.Context) []coretypes.Tx { return blobfactory.RandBlobTxsWithAccounts( s.ecfg, tmrand.NewRand(), s.cctx.Keyring, c.GRPCClient, - 50000, + 50*kibibyte, 8, true, s.accounts[40:120], @@ -131,20 +117,10 @@ func (s *IntegrationTestSuite) TestMaxBlockSize() { name string txGenerator func(clientCtx client.Context) []coretypes.Tx } - tests := []test{ - { - "20 1Mb txs", - equallySized1MbTxGen, - }, - { - "20 1Mb multiblob txs", - randMultiBlob1MbTxGen, - }, - { - "80 random txs", - randoTxGen, - }, + {"singleBlobTxGen", singleBlobTxGen}, + {"multiBlobTxGen", multiBlobTxGen}, + {"randomTxGen", randomTxGen}, } for _, tc := range tests { s.Run(tc.name, func() { @@ -152,6 +128,10 @@ func (s *IntegrationTestSuite) TestMaxBlockSize() { hashes := make([]string, len(txs)) for i, tx := range txs { + // The default CometBFT mempool MaxTxBytes is 1 MiB so the generators in + // this test must create transactions that are smaller than that. + require.LessOrEqual(t, len(tx), 1*mebibyte) + res, err := s.cctx.Context.BroadcastTxSync(tx) require.NoError(t, err) assert.Equal(t, abci.CodeTypeOK, res.Code, res.RawLog) @@ -167,10 +147,7 @@ func (s *IntegrationTestSuite) TestMaxBlockSize() { for _, hash := range hashes { resp, err := testnode.QueryTx(s.cctx.Context, hash, true) require.NoError(t, err) - assert.NotNil(t, resp) - if resp == nil { - continue - } + require.NotNil(t, resp) require.Equal(t, abci.CodeTypeOK, resp.TxResult.Code, resp.TxResult.Log) heights[resp.Height]++ // ensure that some gas was used @@ -195,7 +172,7 @@ func (s *IntegrationTestSuite) TestMaxBlockSize() { require.EqualValues(t, v2.Version, blockRes.Block.Header.Version.App) sizes = append(sizes, size) - ExtendBlobTest(t, blockRes.Block) + ExtendBlockTest(t, blockRes.Block) } // ensure that at least one of the blocks used the max square size assert.Contains(t, sizes, uint64(appconsts.DefaultGovMaxSquareSize)) @@ -204,71 +181,6 @@ func (s *IntegrationTestSuite) TestMaxBlockSize() { } } -func (s *IntegrationTestSuite) TestSubmitPayForBlob() { - t := s.T() - ns1 := appns.MustNewV0(bytes.Repeat([]byte{1}, appns.NamespaceVersionZeroIDSize)) - - mustNewBlob := func(ns appns.Namespace, data []byte, shareVersion uint8) *blob.Blob { - return blob.New(ns, data, shareVersion) - } - - type test struct { - name string - blob *blob.Blob - opts []user.TxOption - } - - tests := []test{ - { - "small random typical", - mustNewBlob(ns1, tmrand.Bytes(3000), appconsts.ShareVersionZero), - []user.TxOption{ - user.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(app.BondDenom, sdk.NewInt(1)))), - user.SetGasLimit(1_000_000_000), - }, - }, - { - "large random typical", - mustNewBlob(ns1, tmrand.Bytes(350000), appconsts.ShareVersionZero), - []user.TxOption{ - user.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(app.BondDenom, sdk.NewInt(10)))), - user.SetGasLimit(1_000_000_000), - }, - }, - { - "medium random with memo", - mustNewBlob(ns1, tmrand.Bytes(100000), appconsts.ShareVersionZero), - []user.TxOption{ - user.SetMemo("lol I could stick the rollup block here if I wanted to"), - user.SetGasLimit(1_000_000_000), - }, - }, - { - "medium random with timeout height", - mustNewBlob(ns1, tmrand.Bytes(100000), appconsts.ShareVersionZero), - []user.TxOption{ - user.SetTimeoutHeight(10000), - user.SetGasLimit(1_000_000_000), - }, - }, - } - for _, tc := range tests { - s.Run(tc.name, func() { - // occasionally this test will error that the mempool is full (code - // 20) so we wait a few blocks for the txs to clear - require.NoError(t, s.cctx.WaitForBlocks(3)) - - addr := testfactory.GetAddress(s.cctx.Keyring, s.accounts[141]) - signer, err := user.SetupSigner(s.cctx.GoContext(), s.cctx.Keyring, s.cctx.GRPCClient, addr, s.ecfg) - require.NoError(t, err) - res, err := signer.SubmitPayForBlob(context.TODO(), []*blob.Blob{tc.blob, tc.blob}, tc.opts...) - require.NoError(t, err) - require.NotNil(t, res) - require.Equal(t, abci.CodeTypeOK, res.Code, res.Logs) - }) - } -} - func (s *IntegrationTestSuite) TestUnwrappedPFBRejection() { t := s.T() @@ -294,13 +206,12 @@ func (s *IntegrationTestSuite) TestUnwrappedPFBRejection() { func (s *IntegrationTestSuite) TestShareInclusionProof() { t := s.T() - // generate 100 randomly sized txs (max size == 100kb) txs := blobfactory.RandBlobTxsWithAccounts( s.ecfg, tmrand.NewRand(), s.cctx.Keyring, s.cctx.GRPCClient, - 100000, + 100*kibibyte, 1, true, s.accounts[120:140], @@ -348,9 +259,9 @@ func (s *IntegrationTestSuite) TestShareInclusionProof() { } } -// ExtendBlobTest re-extends the block and compares the data roots to ensure +// ExtendBlockTest re-extends the block and compares the data roots to ensure // that the public functions for extending the block are working correctly. -func ExtendBlobTest(t *testing.T, block *coretypes.Block) { +func ExtendBlockTest(t *testing.T, block *coretypes.Block) { eds, err := app.ExtendBlock(block.Data, block.Header.Version.App) require.NoError(t, err) dah, err := da.NewDataAvailabilityHeader(eds) @@ -370,71 +281,12 @@ func (s *IntegrationTestSuite) TestEmptyBlock() { blockRes, err := s.cctx.Client.Block(s.cctx.GoContext(), &h) require.NoError(t, err) require.True(t, app.IsEmptyBlock(blockRes.Block.Data, blockRes.Block.Header.Version.App)) - ExtendBlobTest(t, blockRes.Block) - } -} - -// TestSubmitPayForBlob_blobSizes verifies the tx response ABCI code when -// SubmitPayForBlob is invoked with different blob sizes. -func (s *IntegrationTestSuite) TestSubmitPayForBlob_blobSizes() { - t := s.T() - require.NoError(t, s.cctx.WaitForBlocks(3)) - addr := testfactory.GetAddress(s.cctx.Keyring, s.accounts[141]) - signer, err := user.SetupSigner(s.cctx.GoContext(), s.cctx.Keyring, s.cctx.GRPCClient, addr, s.ecfg) - require.NoError(t, err) - - type testCase struct { - name string - blob *blob.Blob - // txResponseCode is the expected tx response ABCI code. - txResponseCode uint32 - } - testCases := []testCase{ - { - name: "1,000 byte blob", - blob: mustNewBlob(1_000), - txResponseCode: abci.CodeTypeOK, - }, - { - name: "10,000 byte blob", - blob: mustNewBlob(10_000), - txResponseCode: abci.CodeTypeOK, - }, - { - name: "100,000 byte blob", - blob: mustNewBlob(100_000), - txResponseCode: abci.CodeTypeOK, - }, - { - name: "1,000,000 byte blob", - blob: mustNewBlob(1_000_000), - txResponseCode: abci.CodeTypeOK, - }, - { - name: "10,000,000 byte blob returns err tx too large", - blob: mustNewBlob(10_000_000), - txResponseCode: errors.ErrTxTooLarge.ABCICode(), - }, - } - - for _, tc := range testCases { - s.Run(tc.name, func() { - subCtx, cancel := context.WithTimeout(s.cctx.GoContext(), 30*time.Second) - defer cancel() - res, err := signer.SubmitPayForBlob(subCtx, []*blob.Blob{tc.blob}, user.SetGasLimit(1_000_000_000)) - if tc.txResponseCode == abci.CodeTypeOK { - require.NoError(t, err) - } else { - require.Error(t, err) - } - require.NotNil(t, res) - require.Equal(t, tc.txResponseCode, res.Code, res.Logs) - }) + ExtendBlockTest(t, blockRes.Block) } } -func mustNewBlob(blobSize int) *blob.Blob { - ns1 := appns.MustNewV0(bytes.Repeat([]byte{1}, appns.NamespaceVersionZeroIDSize)) - data := tmrand.Bytes(blobSize) - return blob.New(ns1, data, appconsts.ShareVersionZero) +func newBlobWithSize(size int) *blob.Blob { + ns := appns.MustNewV0(bytes.Repeat([]byte{1}, appns.NamespaceVersionZeroIDSize)) + data := tmrand.Bytes(size) + return blob.New(ns, data, appconsts.ShareVersionZero) } diff --git a/app/test/max_total_blob_size_test.go b/app/test/max_total_blob_size_test.go index 8c7875f2f9..9c9bafcef7 100644 --- a/app/test/max_total_blob_size_test.go +++ b/app/test/max_total_blob_size_test.go @@ -7,22 +7,13 @@ import ( "github.com/celestiaorg/celestia-app/app" "github.com/celestiaorg/celestia-app/app/encoding" - "github.com/celestiaorg/celestia-app/pkg/appconsts" "github.com/celestiaorg/celestia-app/pkg/blob" - "github.com/celestiaorg/celestia-app/pkg/square" "github.com/celestiaorg/celestia-app/pkg/user" "github.com/celestiaorg/celestia-app/test/util/testfactory" "github.com/celestiaorg/celestia-app/test/util/testnode" blobtypes "github.com/celestiaorg/celestia-app/x/blob/types" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - abci "github.com/tendermint/tendermint/abci/types" -) - -const ( - mebibyte = 1_048_576 // one mebibyte in bytes - squareSize = 64 ) func TestMaxTotalBlobSizeSuite(t *testing.T) { @@ -63,9 +54,9 @@ func (s *MaxTotalBlobSizeSuite) SetupSuite() { require.NoError(t, cctx.WaitForNextBlock()) } -// TestSubmitPayForBlob_blobSizes verifies the tx response ABCI code when -// SubmitPayForBlob is invoked with different blob sizes. -func (s *MaxTotalBlobSizeSuite) TestSubmitPayForBlob_blobSizes() { +// TestErrTotalBlobSizeTooLarge verifies that submitting a 2 MiB blob hits +// ErrTotalBlobSizeTooLarge. +func (s *MaxTotalBlobSizeSuite) TestErrTotalBlobSizeTooLarge() { t := s.T() type testCase struct { @@ -75,19 +66,9 @@ func (s *MaxTotalBlobSizeSuite) TestSubmitPayForBlob_blobSizes() { want uint32 } testCases := []testCase{ - { - name: "1 byte blob", - blob: mustNewBlob(1), - want: abci.CodeTypeOK, - }, - { - name: "1 mebibyte blob", - blob: mustNewBlob(mebibyte), - want: abci.CodeTypeOK, - }, { name: "2 mebibyte blob", - blob: mustNewBlob(2 * mebibyte), + blob: newBlobWithSize(2 * mebibyte), want: blobtypes.ErrTotalBlobSizeTooLarge.ABCICode(), }, } @@ -105,16 +86,6 @@ func (s *MaxTotalBlobSizeSuite) TestSubmitPayForBlob_blobSizes() { require.NoError(t, err) require.NotNil(t, res) require.Equal(t, tc.want, res.Code, res.Logs) - - sq, err := square.Construct([][]byte{blobTx}, appconsts.LatestVersion, squareSize) - if tc.want == abci.CodeTypeOK { - // verify that if the tx was accepted, the blob can fit in a square - assert.NoError(t, err) - assert.False(t, sq.IsEmpty()) - } else { - // verify that if the tx was rejected, the blob can not fit in a square - assert.Error(t, err) - } }) } } diff --git a/app/test/square_size_test.go b/app/test/square_size_test.go index 0577cc635d..f2ebd07ca2 100644 --- a/app/test/square_size_test.go +++ b/app/test/square_size_test.go @@ -60,8 +60,7 @@ func (s *SquareSizeIntegrationTest) SetupSuite() { // TestSquareSizeUpperBound sets the app's params to specific sizes, then fills the // block with spam txs to measure that the desired max is getting hit -// The "_Flaky" suffix indicates that the test may fail non-deterministically especially when executed in CI. -func (s *SquareSizeIntegrationTest) TestSquareSizeUpperBound_Flaky() { +func (s *SquareSizeIntegrationTest) TestSquareSizeUpperBound() { t := s.T() type test struct { diff --git a/app/test/unit_test.go b/app/test/unit_test.go new file mode 100644 index 0000000000..83fa292438 --- /dev/null +++ b/app/test/unit_test.go @@ -0,0 +1,6 @@ +package app_test + +const ( + kibibyte = 1024 + mebibyte = 1024 * kibibyte +) diff --git a/app/version.go b/app/version.go index 3d05ee87cf..49c3cc71b0 100644 --- a/app/version.go +++ b/app/version.go @@ -8,6 +8,8 @@ import ( "github.com/celestiaorg/celestia-app/x/blob" "github.com/celestiaorg/celestia-app/x/blobstream" "github.com/celestiaorg/celestia-app/x/mint" + "github.com/celestiaorg/celestia-app/x/upgrade" + upgradetypes "github.com/celestiaorg/celestia-app/x/upgrade/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/vesting" @@ -31,6 +33,15 @@ var ( // versions that the current state machine supports supportedVersions = []uint64{v1.Version, v2.Version} + v1moduleVersionMap = make(module.VersionMap) + v2moduleVersionMap = make(module.VersionMap) +) + +const DefaultInitialVersion = v1.Version + +// this is used as a compile time consistency check across different module +// based maps +func init() { v1moduleVersionMap = module.VersionMap{ "bank": bank.AppModule{}.ConsensusVersion(), "auth": auth.AppModule{}.ConsensusVersion(), @@ -53,23 +64,25 @@ var ( "transfer": transfer.AppModule{}.ConsensusVersion(), } - // There is currently complete parity between v1 and v2 modules, but this - // will likely change - v2moduleVersionMap = v1moduleVersionMap -) - -const DefaultInitialVersion = v1.Version + // v2 has all the same modules as v1 with the addition of an upgrade module + v2moduleVersionMap = make(module.VersionMap) + for k, v := range v1moduleVersionMap { + v2moduleVersionMap[k] = v + } + v2moduleVersionMap[upgradetypes.ModuleName] = upgrade.AppModule{}.ConsensusVersion() -// this is used as a compile time consistency check across different module -// based maps -func init() { for moduleName := range ModuleBasics { + isSupported := false for _, v := range supportedVersions { versionMap := GetModuleVersion(v) - if _, ok := versionMap[moduleName]; !ok { - panic(fmt.Sprintf("inconsistency: module %s not found in module version map for version %d", moduleName, v)) + if _, ok := versionMap[moduleName]; ok { + isSupported = true + break } } + if !isSupported { + panic(fmt.Sprintf("inconsistency: module %s not found in any version", moduleName)) + } } } diff --git a/pkg/square/square_test.go b/pkg/square/square_test.go index 798955dc3f..b3beb7dcb0 100644 --- a/pkg/square/square_test.go +++ b/pkg/square/square_test.go @@ -13,7 +13,7 @@ import ( "github.com/celestiaorg/celestia-app/pkg/blob" "github.com/celestiaorg/celestia-app/pkg/da" "github.com/celestiaorg/celestia-app/pkg/inclusion" - ns "github.com/celestiaorg/celestia-app/pkg/namespace" + appns "github.com/celestiaorg/celestia-app/pkg/namespace" "github.com/celestiaorg/celestia-app/pkg/shares" "github.com/celestiaorg/celestia-app/pkg/square" "github.com/celestiaorg/celestia-app/test/util/blobfactory" @@ -25,6 +25,10 @@ import ( coretypes "github.com/tendermint/tendermint/types" ) +const ( + mebibyte = 1_048_576 // one mebibyte in bytes +) + func TestSquareConstruction(t *testing.T) { rand := tmrand.NewRand() signer, err := testnode.NewOfflineSigner() @@ -42,6 +46,11 @@ func TestSquareConstruction(t *testing.T) { _, err = square.Construct(coretypes.Txs(pfbTxs).ToSliceOfBytes(), appconsts.LatestVersion, 2) require.Error(t, err) }) + t.Run("construction should fail if a single PFB tx contains a blob that is too large to fit in the square", func(t *testing.T) { + pfbTxs := blobfactory.RandBlobTxs(signer, rand, 1, 1, 2*mebibyte) + _, err := square.Construct(coretypes.Txs(pfbTxs).ToSliceOfBytes(), appconsts.LatestVersion, 64) + require.Error(t, err) + }) } func TestSquareTxShareRange(t *testing.T) { @@ -119,7 +128,7 @@ func TestSquareTxShareRange(t *testing.T) { // len(blobSizes[i]) number of blobs per BlobTx. Note: not suitable for using in // prepare or process proposal, as the signatures will be invalid since this // does not query for relevant account numbers or sequences. -func generateBlobTxsWithNamespaces(t *testing.T, namespaces []ns.Namespace, blobSizes [][]int) [][]byte { +func generateBlobTxsWithNamespaces(t *testing.T, namespaces []appns.Namespace, blobSizes [][]int) [][]byte { encCfg := encoding.MakeConfig(app.ModuleEncodingRegisters...) const acc = "signer" kr, _ := testnode.NewKeyring(acc) @@ -134,12 +143,10 @@ func generateBlobTxsWithNamespaces(t *testing.T, namespaces []ns.Namespace, blob ) } -// The "_Flaky" suffix indicates that the test may fail non-deterministically especially when executed in CI. -func TestSquareBlobShareRange_Flaky(t *testing.T) { - rand := tmrand.NewRand() +func TestSquareBlobShareRange(t *testing.T) { signer, err := testnode.NewOfflineSigner() require.NoError(t, err) - txs := blobfactory.RandBlobTxsRandomlySized(signer, rand, 10, 1000, 10).ToSliceOfBytes() + txs := blobfactory.RandBlobTxsRandomlySized(signer, tmrand.NewRand(), 10, 1000, 10).ToSliceOfBytes() builder, err := square.NewBuilder(appconsts.DefaultSquareSizeUpperBound, appconsts.LatestVersion, txs...) require.NoError(t, err) @@ -153,6 +160,7 @@ func TestSquareBlobShareRange_Flaky(t *testing.T) { for blobIdx := range blobTx.Blobs { shareRange, err := square.BlobShareRange(txs, pfbIdx, blobIdx, appconsts.LatestVersion) require.NoError(t, err) + require.LessOrEqual(t, shareRange.End, len(dataSquare)) blobShares := dataSquare[shareRange.Start:shareRange.End] blobSharesBytes, err := rawData(blobShares) require.NoError(t, err) diff --git a/proto/celestia/upgrade/v1/query.proto b/proto/celestia/upgrade/v1/query.proto new file mode 100644 index 0000000000..d8580d6268 --- /dev/null +++ b/proto/celestia/upgrade/v1/query.proto @@ -0,0 +1,28 @@ +syntax = "proto3"; +package celestia.upgrade.v1; + +import "google/api/annotations.proto"; + +option go_package = "github.com/celestiaorg/celestia-app/x/upgrade/types"; + +// Query defines the upgrade Query service. +service Query { + // VersionTally allows the querying of the tally of voting power by all + // validators that have signalled for each version + rpc VersionTally(QueryVersionTallyRequest) + returns (QueryVersionTallyResponse) { + option (google.api.http).get = "/upgrade/v1/tally/{version}"; + } +} + +// QueryVersionTallyRequest is the request type for the UpgradeStatus RPC +// method. +message QueryVersionTallyRequest { uint64 version = 1; } + +// QueryVersionTallyResponse is the response type for the UpgradeStatus RPC +// method. +message QueryVersionTallyResponse { + uint64 voting_power = 1; + uint64 threshold_power = 2; + uint64 total_voting_power = 3; +} diff --git a/proto/celestia/upgrade/v1/tx.proto b/proto/celestia/upgrade/v1/tx.proto new file mode 100644 index 0000000000..9d8666a7fd --- /dev/null +++ b/proto/celestia/upgrade/v1/tx.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; +package celestia.upgrade.v1; + +import "google/api/annotations.proto"; + +option go_package = "github.com/celestiaorg/celestia-app/x/upgrade/types"; + +// Msg defines the upgrade Msg service. +service Msg { + // SignalVersion allows the validator to signal for an upgrade + rpc SignalVersion(MsgSignalVersion) returns (MsgSignalVersionResponse) { + option (google.api.http).post = "/upgrade/v1/signal"; + } +} + +// MsgSignalVersion signals for an upgrade +message MsgSignalVersion { + string validator_address = 1; + uint64 version = 2; +} + +// MsgSignalVersionResponse describes the response returned after the submission +// of a SignalVersion +message MsgSignalVersionResponse {} diff --git a/proto/celestia/upgrade/v1/types.proto b/proto/celestia/upgrade/v1/types.proto deleted file mode 100644 index cee2591479..0000000000 --- a/proto/celestia/upgrade/v1/types.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; -package celestia.upgrade.v1; - -option go_package = "github.com/celestiaorg/celestia-app/x/upgrade"; - -// MsgVersionChange is a message that signals an app version change -message MsgVersionChange { - // the app version this message proposes upgrading to - uint64 version = 1; -} diff --git a/test/util/keeper/blob.go b/test/util/keeper/blob.go deleted file mode 100644 index 40b7b791a9..0000000000 --- a/test/util/keeper/blob.go +++ /dev/null @@ -1,53 +0,0 @@ -package keeper - -import ( - "testing" - - testutil "github.com/celestiaorg/celestia-app/test/util" - "github.com/celestiaorg/celestia-app/x/blob/keeper" - "github.com/celestiaorg/celestia-app/x/blob/types" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - typesparams "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - tmdb "github.com/tendermint/tm-db" -) - -func BlobKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { - storeKey := sdk.NewKVStoreKey(types.StoreKey) - memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) - - db := tmdb.NewMemDB() - stateStore := store.NewCommitMultiStore(db) - stateStore.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, db) - stateStore.MountStoreWithDB(memStoreKey, storetypes.StoreTypeMemory, nil) - require.NoError(t, stateStore.LoadLatestVersion()) - - registry := codectypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(registry) - - paramsSubspace := typesparams.NewSubspace(cdc, - testutil.MakeTestCodec(), - storeKey, - memStoreKey, - "Blob", - ) - k := keeper.NewKeeper( - cdc, - storeKey, - memStoreKey, - paramsSubspace, - ) - - ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) - - // Initialize params - k.SetParams(ctx, types.DefaultParams()) - - return k, ctx -} diff --git a/test/util/testnode/accounts.go b/test/util/testnode/accounts.go new file mode 100644 index 0000000000..d1eae0251b --- /dev/null +++ b/test/util/testnode/accounts.go @@ -0,0 +1,12 @@ +package testnode + +import tmrand "github.com/tendermint/tendermint/libs/rand" + +// RandomAccounts returns a list of n random accounts +func RandomAccounts(n int) (accounts []string) { + for i := 0; i < n; i++ { + account := tmrand.Str(20) + accounts = append(accounts, account) + } + return accounts +} diff --git a/test/util/testnode/accounts_test.go b/test/util/testnode/accounts_test.go new file mode 100644 index 0000000000..73dbee8687 --- /dev/null +++ b/test/util/testnode/accounts_test.go @@ -0,0 +1,13 @@ +package testnode + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestRandomAccounts(t *testing.T) { + got := RandomAccounts(2) + assert.Len(t, got, 2) + assert.NotEqual(t, got[0], got[1]) +} diff --git a/test/util/testnode/full_node_test.go b/test/util/testnode/full_node_test.go index a2e9dca5d8..7d040a07d6 100644 --- a/test/util/testnode/full_node_test.go +++ b/test/util/testnode/full_node_test.go @@ -19,7 +19,14 @@ import ( coretypes "github.com/tendermint/tendermint/rpc/core/types" ) +const ( + kibibyte = 1024 +) + func TestIntegrationTestSuite(t *testing.T) { + if testing.Short() { + t.Skip("skipping full node integration test in short mode.") + } suite.Run(t, new(IntegrationTestSuite)) } @@ -31,40 +38,31 @@ type IntegrationTestSuite struct { } func (s *IntegrationTestSuite) SetupSuite() { - if testing.Short() { - s.T().Skip("skipping full node integration test in short mode.") - } t := s.T() - - accounts := make([]string, 10) - for i := 0; i < 10; i++ { - accounts[i] = tmrand.Str(10) - } + s.accounts = RandomAccounts(10) ecfg := encoding.MakeConfig(app.ModuleEncodingRegisters...) blobGenState := blobtypes.DefaultGenesis() blobGenState.Params.GovMaxSquareSize = uint64(appconsts.DefaultSquareSizeUpperBound) cfg := DefaultConfig(). - WithFundedAccounts(accounts...). + WithFundedAccounts(s.accounts...). WithModifiers(genesis.SetBlobParams(ecfg.Codec, blobGenState.Params)) cctx, _, _ := NewNetwork(t, cfg) s.cctx = cctx - s.accounts = accounts } -// The "_Flaky" suffix indicates that the test may fail non-deterministically especially when executed in CI. -func (s *IntegrationTestSuite) Test_Liveness_Flaky() { +func (s *IntegrationTestSuite) Test_verifyTimeIotaMs() { require := s.Require() err := s.cctx.WaitForNextBlock() require.NoError(err) - // check that we're actually able to set the consensus params + var params *coretypes.ResultConsensusParams // this query can be flaky with fast block times, so we repeat it multiple // times in attempt to decrease flakiness - for i := 0; i < 40; i++ { - params, err = s.cctx.Client.ConsensusParams(context.TODO(), nil) + for i := 0; i < 100; i++ { + params, err = s.cctx.Client.ConsensusParams(context.Background(), nil) if err == nil && params != nil { break } @@ -73,21 +71,19 @@ func (s *IntegrationTestSuite) Test_Liveness_Flaky() { require.NoError(err) require.NotNil(params) require.Equal(int64(1), params.ConsensusParams.Block.TimeIotaMs) - _, err = s.cctx.WaitForHeight(20) - require.NoError(err) } -func (s *IntegrationTestSuite) Test_PostData() { +func (s *IntegrationTestSuite) TestPostData() { require := s.Require() - _, err := s.cctx.PostData(s.accounts[0], flags.BroadcastBlock, appns.RandomBlobNamespace(), tmrand.Bytes(100000)) + _, err := s.cctx.PostData(s.accounts[0], flags.BroadcastBlock, appns.RandomBlobNamespace(), tmrand.Bytes(kibibyte)) require.NoError(err) } -func (s *IntegrationTestSuite) Test_FillBlock() { +func (s *IntegrationTestSuite) TestFillBlock() { require := s.Require() for squareSize := 2; squareSize <= appconsts.DefaultGovMaxSquareSize; squareSize *= 2 { - resp, err := s.cctx.FillBlock(squareSize, s.accounts, flags.BroadcastSync) + resp, err := s.cctx.FillBlock(squareSize, s.accounts[1], flags.BroadcastSync) require.NoError(err) err = s.cctx.WaitForBlocks(3) @@ -103,7 +99,7 @@ func (s *IntegrationTestSuite) Test_FillBlock() { } } -func (s *IntegrationTestSuite) Test_FillBlock_InvalidSquareSizeError() { +func (s *IntegrationTestSuite) TestFillBlock_InvalidSquareSizeError() { tests := []struct { name string squareSize int @@ -127,7 +123,7 @@ func (s *IntegrationTestSuite) Test_FillBlock_InvalidSquareSizeError() { for _, tc := range tests { s.Run(tc.name, func() { - _, actualErr := s.cctx.FillBlock(tc.squareSize, s.accounts, flags.BroadcastAsync) + _, actualErr := s.cctx.FillBlock(tc.squareSize, s.accounts[2], flags.BroadcastAsync) s.Equal(tc.expectedErr, actualErr) }) } diff --git a/test/util/testnode/node_interaction_api.go b/test/util/testnode/node_interaction_api.go index cf8e2e3bbb..77984ca146 100644 --- a/test/util/testnode/node_interaction_api.go +++ b/test/util/testnode/node_interaction_api.go @@ -277,7 +277,7 @@ func (c *Context) PostData(account, broadcastMode string, ns appns.Namespace, bl // create a square of the desired size. broadcast mode indicates if the tx // should be submitted async, sync, or block. (see flags.BroadcastModeSync). If // broadcast mode is the string zero value, then it will be set to block. -func (c *Context) FillBlock(squareSize int, accounts []string, broadcastMode string) (*sdk.TxResponse, error) { +func (c *Context) FillBlock(squareSize int, account string, broadcastMode string) (*sdk.TxResponse, error) { if squareSize < appconsts.MinSquareSize+1 || (squareSize&(squareSize-1) != 0) { return nil, fmt.Errorf("unsupported squareSize: %d", squareSize) } @@ -291,7 +291,7 @@ func (c *Context) FillBlock(squareSize int, accounts []string, broadcastMode str // we use a formula to guarantee that the tx is the exact size needed to force a specific square size. blobSize := shares.AvailableBytesFromSparseShares(shareCount) - return c.PostData(accounts[0], broadcastMode, appns.RandomBlobNamespace(), tmrand.Bytes(blobSize)) + return c.PostData(account, broadcastMode, appns.RandomBlobNamespace(), tmrand.Bytes(blobSize)) } // HeightForTimestamp returns the block height for the first block after a diff --git a/x/blob/client/testutil/integration_test.go b/x/blob/client/testutil/integration_test.go index 0674189940..886777c4cf 100644 --- a/x/blob/client/testutil/integration_test.go +++ b/x/blob/client/testutil/integration_test.go @@ -1,7 +1,6 @@ package testutil import ( - "bytes" "encoding/hex" "fmt" "strconv" @@ -40,15 +39,10 @@ func NewIntegrationTestSuite(cfg cosmosnet.Config) *IntegrationTestSuite { return &IntegrationTestSuite{cfg: cfg} } -// Note: the SetupSuite may act flaky especially in CI. func (s *IntegrationTestSuite) SetupSuite() { - if testing.Short() { - s.T().Skip("skipping integration test in short mode.") - } s.T().Log("setting up integration test suite") net := network.New(s.T(), s.cfg, username) - s.network = net s.kr = net.Validators[0].ClientCtx.Keyring _, err := s.network.WaitForHeight(1) @@ -62,10 +56,8 @@ func (s *IntegrationTestSuite) TearDownSuite() { func (s *IntegrationTestSuite) TestSubmitPayForBlob() { require := s.Require() - val := s.network.Validators[0] + validator := s.network.Validators[0] hexNamespace := hex.EncodeToString(appns.RandomBlobNamespaceID()) - invalidNamespaceID := hex.EncodeToString(bytes.Repeat([]byte{0}, 8)) // invalid because ID is expected to be 10 bytes - hexBlob := "0204033704032c0b162109000908094d425837422c2116" testCases := []struct { @@ -89,58 +81,14 @@ func (s *IntegrationTestSuite) TestSubmitPayForBlob() { expectedCode: 0, respType: &sdk.TxResponse{}, }, - { - name: "unsupported share version", - args: []string{ - hexNamespace, - hexBlob, - fmt.Sprintf("--from=%s", username), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(2))).String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=1", paycli.FlagShareVersion), - }, - expectErr: true, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - { - name: "invalid namespace ID", - args: []string{ - invalidNamespaceID, - hexBlob, - fmt.Sprintf("--from=%s", username), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(2))).String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - }, - expectErr: true, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - { - name: "invalid namespace version", - args: []string{ - hexNamespace, - hexBlob, - fmt.Sprintf("--from=%s", username), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(2))).String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=1", paycli.FlagNamespaceVersion), - }, - expectErr: true, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, } for _, tc := range testCases { tc := tc - s.Require().NoError(s.network.WaitForNextBlock()) + require.NoError(s.network.WaitForNextBlock()) s.Run(tc.name, func() { cmd := paycli.CmdPayForBlob() - clientCtx := val.ClientCtx + clientCtx := validator.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { @@ -182,7 +130,9 @@ func (s *IntegrationTestSuite) TestSubmitPayForBlob() { } } -// The "_Flaky" suffix indicates that the test may fail non-deterministically especially when executed in CI. -func TestIntegrationTestSuite_Flaky(t *testing.T) { +func TestIntegrationTestSuite(t *testing.T) { + if testing.Short() { + t.Skip("skipping integration test in short mode.") + } suite.Run(t, NewIntegrationTestSuite(network.DefaultConfig())) } diff --git a/x/blob/keeper/gas_test.go b/x/blob/keeper/gas_test.go index ee4df5760a..90c9593bda 100644 --- a/x/blob/keeper/gas_test.go +++ b/x/blob/keeper/gas_test.go @@ -1,53 +1,15 @@ -package keeper +package keeper_test import ( "testing" "github.com/celestiaorg/celestia-app/pkg/appconsts" "github.com/celestiaorg/celestia-app/x/blob/types" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - typesparams "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - tmdb "github.com/tendermint/tm-db" ) -func keeper(t *testing.T) (*Keeper, store.CommitMultiStore) { - storeKey := sdk.NewKVStoreKey(types.StoreKey) - memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) - - db := tmdb.NewMemDB() - stateStore := store.NewCommitMultiStore(db) - stateStore.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, db) - stateStore.MountStoreWithDB(memStoreKey, storetypes.StoreTypeMemory, nil) - require.NoError(t, stateStore.LoadLatestVersion()) - - registry := codectypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(registry) - tempCtx := sdk.NewContext(stateStore, tmproto.Header{}, false, nil) - - aminoCdc := codec.NewLegacyAmino() - paramsSubspace := typesparams.NewSubspace(cdc, - aminoCdc, - storeKey, - memStoreKey, - "Blob", - ) - k := NewKeeper( - cdc, - storeKey, - memStoreKey, - paramsSubspace, - ) - k.SetParams(tempCtx, types.DefaultParams()) - - return k, stateStore -} - func TestPayForBlobGas(t *testing.T) { type testCase struct { name string @@ -87,7 +49,7 @@ func TestPayForBlobGas(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - k, stateStore := keeper(t) + k, stateStore, _ := CreateKeeper(t) ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, nil) _, err := k.PayForBlobs(sdk.WrapSDKContext(ctx), &tc.msg) require.NoError(t, err) @@ -100,7 +62,7 @@ func TestPayForBlobGas(t *testing.T) { func TestChangingGasParam(t *testing.T) { msg := types.MsgPayForBlobs{BlobSizes: []uint32{1024}} - k, stateStore := keeper(t) + k, stateStore, _ := CreateKeeper(t) tempCtx := sdk.NewContext(stateStore, tmproto.Header{}, false, nil) ctx1 := sdk.NewContext(stateStore, tmproto.Header{}, false, nil) diff --git a/x/blob/genesis_test.go b/x/blob/keeper/genesis_test.go similarity index 77% rename from x/blob/genesis_test.go rename to x/blob/keeper/genesis_test.go index c21ebfba20..5dc450c55e 100644 --- a/x/blob/genesis_test.go +++ b/x/blob/keeper/genesis_test.go @@ -1,9 +1,8 @@ -package blob_test +package keeper_test import ( "testing" - keepertest "github.com/celestiaorg/celestia-app/test/util/keeper" "github.com/celestiaorg/celestia-app/x/blob" "github.com/celestiaorg/celestia-app/x/blob/types" "github.com/stretchr/testify/require" @@ -14,7 +13,7 @@ func TestGenesis(t *testing.T) { Params: types.DefaultParams(), } - k, ctx := keepertest.BlobKeeper(t) + k, _, ctx := CreateKeeper(t) blob.InitGenesis(ctx, *k, genesisState) got := blob.ExportGenesis(ctx, *k) require.NotNil(t, got) diff --git a/x/blob/keeper/grpc_query_params_test.go b/x/blob/keeper/grpc_query_params_test.go index 2fa47a714c..3398c8ecae 100644 --- a/x/blob/keeper/grpc_query_params_test.go +++ b/x/blob/keeper/grpc_query_params_test.go @@ -3,14 +3,13 @@ package keeper_test import ( "testing" - testkeeper "github.com/celestiaorg/celestia-app/test/util/keeper" "github.com/celestiaorg/celestia-app/x/blob/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" ) func TestParamsQuery(t *testing.T) { - keeper, ctx := testkeeper.BlobKeeper(t) + keeper, _, ctx := CreateKeeper(t) wctx := sdk.WrapSDKContext(ctx) params := types.DefaultParams() keeper.SetParams(ctx, params) diff --git a/x/blob/keeper/keeper.go b/x/blob/keeper/keeper.go index 5111bd70ae..bb69acfd29 100644 --- a/x/blob/keeper/keeper.go +++ b/x/blob/keeper/keeper.go @@ -6,7 +6,6 @@ import ( "github.com/celestiaorg/celestia-app/x/blob/types" "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/tendermint/tendermint/libs/log" @@ -19,15 +18,11 @@ const ( // Keeper handles all the state changes for the blob module. type Keeper struct { cdc codec.BinaryCodec - storeKey storetypes.StoreKey - memKey storetypes.StoreKey paramStore paramtypes.Subspace } func NewKeeper( cdc codec.BinaryCodec, - storeKey, - memKey storetypes.StoreKey, ps paramtypes.Subspace, ) *Keeper { if !ps.HasKeyTable() { @@ -36,8 +31,6 @@ func NewKeeper( return &Keeper{ cdc: cdc, - storeKey: storeKey, - memKey: memKey, paramStore: ps, } } diff --git a/x/blob/keeper/keeper_test.go b/x/blob/keeper/keeper_test.go index 44dcc4a0cb..abe48a2ce0 100644 --- a/x/blob/keeper/keeper_test.go +++ b/x/blob/keeper/keeper_test.go @@ -1,4 +1,4 @@ -package keeper +package keeper_test import ( "bytes" @@ -8,18 +8,27 @@ import ( "github.com/celestiaorg/celestia-app/pkg/appconsts" "github.com/celestiaorg/celestia-app/pkg/blob" appns "github.com/celestiaorg/celestia-app/pkg/namespace" + testutil "github.com/celestiaorg/celestia-app/test/util" + "github.com/celestiaorg/celestia-app/x/blob/keeper" "github.com/celestiaorg/celestia-app/x/blob/types" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" proto "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + tmversion "github.com/tendermint/tendermint/proto/tendermint/version" + tmdb "github.com/tendermint/tm-db" ) // TestPayForBlobs verifies the attributes on the emitted event. func TestPayForBlobs(t *testing.T) { - k, stateStore := keeper(t) - ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, nil) + k, _, ctx := CreateKeeper(t) signer := "celestia15drmhzw5kwgenvemy30rqqqgq52axf5wwrruf7" namespace := appns.MustNewV0(bytes.Repeat([]byte{1}, appns.NamespaceVersionZeroIDSize)) namespaces := [][]byte{namespace.Bytes()} @@ -62,3 +71,37 @@ func createMsgPayForBlob(t *testing.T, signer string, namespace appns.Namespace, require.NoError(t, err) return msg } + +func CreateKeeper(t *testing.T) (*keeper.Keeper, store.CommitMultiStore, sdk.Context) { + storeKey := sdk.NewKVStoreKey(paramtypes.StoreKey) + tStoreKey := storetypes.NewTransientStoreKey(paramtypes.TStoreKey) + + db := tmdb.NewMemDB() + stateStore := store.NewCommitMultiStore(db) + stateStore.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, db) + stateStore.MountStoreWithDB(tStoreKey, storetypes.StoreTypeTransient, nil) + require.NoError(t, stateStore.LoadLatestVersion()) + + registry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(registry) + ctx := sdk.NewContext(stateStore, tmproto.Header{ + Version: tmversion.Consensus{ + Block: 1, + App: 1, + }, + }, false, nil) + + paramsSubspace := paramtypes.NewSubspace(cdc, + testutil.MakeTestCodec(), + storeKey, + tStoreKey, + types.ModuleName, + ) + k := keeper.NewKeeper( + cdc, + paramsSubspace, + ) + k.SetParams(ctx, types.DefaultParams()) + + return k, stateStore, ctx +} diff --git a/x/blob/keeper/params_test.go b/x/blob/keeper/params_test.go index 01abbbbec5..95a533d880 100644 --- a/x/blob/keeper/params_test.go +++ b/x/blob/keeper/params_test.go @@ -3,13 +3,12 @@ package keeper_test import ( "testing" - testkeeper "github.com/celestiaorg/celestia-app/test/util/keeper" "github.com/celestiaorg/celestia-app/x/blob/types" "github.com/stretchr/testify/require" ) func TestGetParams(t *testing.T) { - k, ctx := testkeeper.BlobKeeper(t) + k, _, ctx := CreateKeeper(t) params := types.DefaultParams() k.SetParams(ctx, params) diff --git a/x/upgrade/ibc.go b/x/upgrade/ibc.go new file mode 100644 index 0000000000..dcfc1ce799 --- /dev/null +++ b/x/upgrade/ibc.go @@ -0,0 +1,72 @@ +package upgrade + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/upgrade/types" + ibctypes "github.com/cosmos/ibc-go/v6/modules/core/02-client/types" +) + +// We need compatibility with the way that IBC uses the upgrade module. This file +// ensures that we comply to the interface that IBC expects +var _ ibctypes.UpgradeKeeper = (*Keeper)(nil) + +// ScheduleUpgrade implements the ibc upgrade keeper interface. This is a noop as +// no other process is allowed to schedule an upgrade but the upgrade keeper itself. +// This is kept around to support the interface. +func (k Keeper) ScheduleUpgrade(_ sdk.Context, _ types.Plan) error { + return nil +} + +// GetUpgradePlan implements the ibc upgrade keeper interface. This is used in BeginBlock +// to know when to write the upgraded consensus state. The IBC module needs to sign over +// the next consensus state to ensure a smooth transition for counterparty chains. This +// is implemented as a noop. Any IBC breaking change would be invoked by this upgrade module +// in end blocker. +func (k Keeper) GetUpgradePlan(_ sdk.Context) (plan types.Plan, havePlan bool) { + return types.Plan{}, false +} + +// SetUpgradedClient sets the expected upgraded client for the next version of this chain at the last height the current chain will commit. +func (k Keeper) SetUpgradedClient(ctx sdk.Context, planHeight int64, bz []byte) error { + store := ctx.KVStore(k.storeKey) + store.Set(types.UpgradedClientKey(planHeight), bz) + return nil +} + +// GetUpgradedClient gets the expected upgraded client for the next version of this chain +func (k Keeper) GetUpgradedClient(ctx sdk.Context, height int64) ([]byte, bool) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.UpgradedClientKey(height)) + if len(bz) == 0 { + return nil, false + } + + return bz, true +} + +// SetUpgradedConsensusState set the expected upgraded consensus state for the next version of this chain +// using the last height committed on this chain. +func (k Keeper) SetUpgradedConsensusState(ctx sdk.Context, planHeight int64, bz []byte) error { + store := ctx.KVStore(k.storeKey) + store.Set(types.UpgradedConsStateKey(planHeight), bz) + return nil +} + +// GetUpgradedConsensusState get the expected upgraded consensus state for the next version of this chain +func (k Keeper) GetUpgradedConsensusState(ctx sdk.Context, lastHeight int64) ([]byte, bool) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.UpgradedConsStateKey(lastHeight)) + if len(bz) == 0 { + return nil, false + } + + return bz, true +} + +// ClearIBCState clears any planned IBC state +func (k Keeper) ClearIBCState(ctx sdk.Context, lastHeight int64) { + // delete IBC client and consensus state from store if this is IBC plan + store := ctx.KVStore(k.storeKey) + store.Delete(types.UpgradedClientKey(lastHeight)) + store.Delete(types.UpgradedConsStateKey(lastHeight)) +} diff --git a/x/upgrade/interfaces.go b/x/upgrade/interfaces.go new file mode 100644 index 0000000000..ae745bb655 --- /dev/null +++ b/x/upgrade/interfaces.go @@ -0,0 +1,13 @@ +package upgrade + +import ( + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +type StakingKeeper interface { + GetLastValidatorPower(ctx sdk.Context, addr sdk.ValAddress) int64 + GetLastTotalPower(ctx sdk.Context) math.Int + GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) +} diff --git a/x/upgrade/keeper.go b/x/upgrade/keeper.go index 54b03dd7d9..483f68ee66 100644 --- a/x/upgrade/keeper.go +++ b/x/upgrade/keeper.go @@ -1,13 +1,40 @@ package upgrade import ( + "context" + "encoding/binary" + + sdkmath "cosmossdk.io/math" + "github.com/celestiaorg/celestia-app/x/upgrade/types" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/upgrade/types" - ibctypes "github.com/cosmos/ibc-go/v6/modules/core/02-client/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +// Keeper implements the MsgServer and QueryServer interfaces +var ( + _ types.MsgServer = Keeper{} + _ types.QueryServer = Keeper{} + + defaultSignalTheshold = Fraction{Numerator: 5, Denominator: 6} ) -var _ ibctypes.UpgradeKeeper = (*Keeper)(nil) +type Fraction struct { + Numerator int64 + Denominator int64 +} + +// SignalThreshold is the fraction of voting power that is required +// to signal for a version change. It is set to 5/6 as the middle point +// between 2/3 and 3/3 providing 1/6 fault tolerance to halting the +// network during an upgrade period. It can be modified through a +// hard fork change that modified the app version +func SignalThreshold(version uint64) Fraction { + switch version { + default: + return defaultSignalTheshold + } +} type Keeper struct { // we use the same upgrade store key so existing IBC client state can @@ -15,83 +42,166 @@ type Keeper struct { storeKey storetypes.StoreKey // in memory copy of the upgrade height if any. This is local per node - // and configured from the config. + // and configured from the config. Used just for V2 upgradeHeight int64 -} -type VersionSetter func(version uint64) + // quorumVersion is the version that has received a quorum of validators + // to signal for it. This variable is relevant just for the scope of the + // lifetime of the block + quorumVersion uint64 + + // staking keeper is used to fetch validators to calculate the total power + // signalled to a version + stakingKeeper StakingKeeper +} // NewKeeper constructs an upgrade keeper -func NewKeeper(storeKey storetypes.StoreKey, upgradeHeight int64) Keeper { +func NewKeeper( + storeKey storetypes.StoreKey, + upgradeHeight int64, + stakingKeeper StakingKeeper, +) Keeper { return Keeper{ storeKey: storeKey, upgradeHeight: upgradeHeight, + stakingKeeper: stakingKeeper, } } -// ScheduleUpgrade implements the ibc upgrade keeper interface. This is a noop as -// no other process is allowed to schedule an upgrade but the upgrade keeper itself. -// This is kept around to support the interface. -func (k Keeper) ScheduleUpgrade(_ sdk.Context, _ types.Plan) error { - return nil -} +// SignalVersion is a method required by the MsgServer interface +func (k Keeper) SignalVersion(ctx context.Context, req *types.MsgSignalVersion) (*types.MsgSignalVersionResponse, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) + if err != nil { + return nil, err + } -// GetUpgradePlan implements the ibc upgrade keeper interface. This is used in BeginBlock -// to know when to write the upgraded consensus state. The IBC module needs to sign over -// the next consensus state to ensure a smooth transition for counterparty chains. This -// is implemented as a noop. Any IBC breaking change would be invoked by this upgrade module -// in end blocker. -func (k Keeper) GetUpgradePlan(_ sdk.Context) (plan types.Plan, havePlan bool) { - return types.Plan{}, false -} + // check that the validator exists + _, found := k.stakingKeeper.GetValidator(sdkCtx, valAddr) + if !found { + return nil, stakingtypes.ErrNoValidatorFound + } -// SetUpgradedClient sets the expected upgraded client for the next version of this chain at the last height the current chain will commit. -func (k Keeper) SetUpgradedClient(ctx sdk.Context, planHeight int64, bz []byte) error { - store := ctx.KVStore(k.storeKey) - store.Set(types.UpgradedClientKey(planHeight), bz) - return nil + // the signalled version must be either the current version (for cancelling an upgrade) + // or the very next version (for accepting an upgrade) + currentVersion := sdkCtx.BlockHeader().Version.App + if req.Version != currentVersion && req.Version != currentVersion+1 { + return nil, types.ErrInvalidVersion + } + + k.SetValidatorVersion(sdkCtx, valAddr, req.Version) + return &types.MsgSignalVersionResponse{}, nil } -// GetUpgradedClient gets the expected upgraded client for the next version of this chain -func (k Keeper) GetUpgradedClient(ctx sdk.Context, height int64) ([]byte, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.UpgradedClientKey(height)) - if len(bz) == 0 { - return nil, false +// VersionTally is a method required by the QueryServer interface +func (k Keeper) VersionTally(ctx context.Context, req *types.QueryVersionTallyRequest) (*types.QueryVersionTallyResponse, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + totalVotingPower := k.stakingKeeper.GetLastTotalPower(sdkCtx) + currentVotingPower := sdk.NewInt(0) + store := sdkCtx.KVStore(k.storeKey) + iterator := store.Iterator(nil, nil) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + valAddress := sdk.ValAddress(iterator.Key()) + power := k.stakingKeeper.GetLastValidatorPower(sdkCtx, valAddress) + version := VersionFromBytes(iterator.Value()) + if version == req.Version { + currentVotingPower = currentVotingPower.AddRaw(power) + } } - return bz, true + threshold := k.GetVotingPowerThreshold(sdkCtx) + return &types.QueryVersionTallyResponse{ + VotingPower: currentVotingPower.Uint64(), + ThresholdPower: threshold.Uint64(), + TotalVotingPower: totalVotingPower.Uint64(), + }, nil } -// SetUpgradedConsensusState set the expected upgraded consensus state for the next version of this chain -// using the last height committed on this chain. -func (k Keeper) SetUpgradedConsensusState(ctx sdk.Context, planHeight int64, bz []byte) error { +// SetValidatorVersion saves a signalled version for a validator using the keeper's store key +func (k Keeper) SetValidatorVersion(ctx sdk.Context, valAddress sdk.ValAddress, version uint64) { store := ctx.KVStore(k.storeKey) - store.Set(types.UpgradedConsStateKey(planHeight), bz) - return nil + store.Set(valAddress, VersionToBytes(version)) } -// GetUpgradedConsensusState get the expected upgraded consensus state for the next version of this chain -func (k Keeper) GetUpgradedConsensusState(ctx sdk.Context, lastHeight int64) ([]byte, bool) { +// DeleteValidatorVersion deletes a signalled version for a validator using the keeper's store key +func (k Keeper) DeleteValidatorVersion(ctx sdk.Context, valAddress sdk.ValAddress) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.UpgradedConsStateKey(lastHeight)) - if len(bz) == 0 { - return nil, false - } + store.Delete(valAddress) +} - return bz, true +// EndBlock is called at the end of every block. It tallies the voting power that has +// voted on each version. If one version has quorum, it is set as the quorum version +// which the application can use as signal to upgrade to that version. +func (k *Keeper) EndBlock(ctx sdk.Context) { + threshold := k.GetVotingPowerThreshold(ctx) + hasQuorum, version := k.TallyVotingPower(ctx, threshold.Int64()) + if hasQuorum { + k.quorumVersion = version + } } -// ClearIBCState clears any planned IBC state -func (k Keeper) ClearIBCState(ctx sdk.Context, lastHeight int64) { - // delete IBC client and consensus state from store if this is IBC plan +// TallyVotingPower tallies the voting power for each version and returns true if +// any version has reached the quorum in voting power +func (k Keeper) TallyVotingPower(ctx sdk.Context, threshold int64) (bool, uint64) { + output := make(map[uint64]int64) store := ctx.KVStore(k.storeKey) - store.Delete(types.UpgradedClientKey(lastHeight)) - store.Delete(types.UpgradedConsStateKey(lastHeight)) + iterator := store.Iterator(nil, nil) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + valAddress := sdk.ValAddress(iterator.Key()) + // check that the validator is still part of the bonded set + val, found := k.stakingKeeper.GetValidator(ctx, valAddress) + if !found { + // if it no longer exists, delete the version + k.DeleteValidatorVersion(ctx, valAddress) + } + // if the validator is not bonded, skip it's voting power + if !found || !val.IsBonded() { + continue + } + power := k.stakingKeeper.GetLastValidatorPower(ctx, valAddress) + version := VersionFromBytes(iterator.Value()) + if _, ok := output[version]; !ok { + output[version] = power + } else { + output[version] += power + } + if output[version] > threshold { + return true, version + } + } + return false, 0 } -// ShouldUpgrade returns true if the current height is one before +// GetVotingPowerThreshold returns the voting power threshold required to +// upgrade to a new version. +func (k Keeper) GetVotingPowerThreshold(ctx sdk.Context) sdkmath.Int { + // contract: totalVotingPower should not exceed MaxUit64 + totalVotingPower := k.stakingKeeper.GetLastTotalPower(ctx) + thresholdFraction := SignalThreshold(ctx.BlockHeader().Version.App) + return totalVotingPower.MulRaw(thresholdFraction.Numerator).QuoRaw(thresholdFraction.Denominator) +} + +// ShouldUpgradeToV2 returns true if the current height is one before // the locally provided upgrade height that is passed as a flag -func (k Keeper) ShouldUpgrade(height int64) bool { +// NOTE: This is only used to upgrade to v2 and should be deprecated +// in v3 +func (k Keeper) ShouldUpgradeToV2(height int64) bool { return k.upgradeHeight == height+1 } + +// ShouldUpgrade returns true if the signalling mechanism has concluded +// that the network is ready to upgrade. It also returns the version +// that the node should upgrade to. +func (k *Keeper) ShouldUpgrade() (bool, uint64) { + return k.quorumVersion != 0, k.quorumVersion +} + +func VersionToBytes(version uint64) []byte { + return binary.BigEndian.AppendUint64(nil, version) +} + +func VersionFromBytes(version []byte) uint64 { + return binary.BigEndian.Uint64(version) +} diff --git a/x/upgrade/module.go b/x/upgrade/module.go new file mode 100644 index 0000000000..a69c54dd24 --- /dev/null +++ b/x/upgrade/module.go @@ -0,0 +1,129 @@ +package upgrade + +import ( + "context" + "encoding/json" + + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/celestiaorg/celestia-app/x/upgrade/types" + "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/cosmos/cosmos-sdk/x/upgrade/client/cli" +) + +func init() { + types.RegisterLegacyAminoCodec(codec.NewLegacyAmino()) +} + +const ( + consensusVersion uint64 = 3 +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// AppModuleBasic implements the sdk.AppModuleBasic interface +type AppModuleBasic struct{} + +// Name returns the ModuleName +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the upgrade types on the LegacyAmino codec +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the upgrade module. +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } +} + +// GetQueryCmd returns the cli query commands for this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// GetTxCmd returns the transaction commands for this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} + +// AppModule implements the sdk.AppModule interface +type AppModule struct { + AppModuleBasic + keeper Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(keeper Keeper) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + } +} + +// RegisterInvariants does nothing, there are no invariants to enforce +func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// Deprecated: Route returns the message routing key for the upgrade module. +func (AppModule) Route() sdk.Route { + return sdk.Route{} +} + +// QuerierRoute returns the route we respond to for abci queries +func (AppModule) QuerierRoute() string { return types.QuerierRoute } + +// LegacyQuerierHandler registers a query handler to respond to the module-specific queries +func (am AppModule) LegacyQuerierHandler(_ *codec.LegacyAmino) sdk.Querier { + return nil +} + +// RegisterServices registers module services. +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), am.keeper) + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) +} + +// InitGenesis is ignored, no sense in serializing future upgrades +func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +// DefaultGenesis is an empty object +func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { + return []byte("{}") +} + +// ValidateGenesis is always successful, as we ignore the value +func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ json.RawMessage) error { + return nil +} + +// ExportGenesis is always empty, as InitGenesis does nothing either +func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMessage { + return am.DefaultGenesis(cdc) +} + +// ConsensusVersion implements AppModule/ConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return consensusVersion } + +// EndBlock is used by the Endblocker +func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) { + am.keeper.EndBlock(ctx) +} diff --git a/x/upgrade/tally_test.go b/x/upgrade/tally_test.go new file mode 100644 index 0000000000..994e74043f --- /dev/null +++ b/x/upgrade/tally_test.go @@ -0,0 +1,209 @@ +package upgrade_test + +import ( + "testing" + + "cosmossdk.io/math" + "github.com/celestiaorg/celestia-app/x/upgrade" + "github.com/celestiaorg/celestia-app/x/upgrade/types" + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/stretchr/testify/require" + + testutil "github.com/celestiaorg/celestia-app/test/util" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + "github.com/tendermint/tendermint/libs/log" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + tmversion "github.com/tendermint/tendermint/proto/tendermint/version" + tmdb "github.com/tendermint/tm-db" +) + +func TestSignalVersion(t *testing.T) { + upgradeKeeper, ctx, _ := setup(t) + goCtx := sdk.WrapSDKContext(ctx) + _, err := upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[0].String(), + Version: 0, + }) + require.Error(t, err) + _, err = upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[0].String(), + Version: 3, + }) + require.Error(t, err) + + _, err = upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[4].String(), + Version: 2, + }) + require.Error(t, err) + + _, err = upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[0].String(), + Version: 2, + }) + require.NoError(t, err) + + res, err := upgradeKeeper.VersionTally(goCtx, &types.QueryVersionTallyRequest{ + Version: 2, + }) + require.NoError(t, err) + require.EqualValues(t, 40, res.VotingPower) + require.EqualValues(t, 100, res.ThresholdPower) + require.EqualValues(t, 120, res.TotalVotingPower) +} + +func TestTallyingLogic(t *testing.T) { + upgradeKeeper, ctx, mockStakingKeeper := setup(t) + goCtx := sdk.WrapSDKContext(ctx) + _, err := upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[0].String(), + Version: 0, + }) + require.Error(t, err) + _, err = upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[0].String(), + Version: 3, + }) + require.Error(t, err) + + _, err = upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[0].String(), + Version: 2, + }) + require.NoError(t, err) + + res, err := upgradeKeeper.VersionTally(goCtx, &types.QueryVersionTallyRequest{ + Version: 2, + }) + require.NoError(t, err) + require.EqualValues(t, 40, res.VotingPower) + require.EqualValues(t, 100, res.ThresholdPower) + require.EqualValues(t, 120, res.TotalVotingPower) + + _, err = upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[2].String(), + Version: 2, + }) + require.NoError(t, err) + + res, err = upgradeKeeper.VersionTally(goCtx, &types.QueryVersionTallyRequest{ + Version: 2, + }) + require.NoError(t, err) + require.EqualValues(t, 100, res.VotingPower) + require.EqualValues(t, 100, res.ThresholdPower) + require.EqualValues(t, 120, res.TotalVotingPower) + + upgradeKeeper.EndBlock(ctx) + shouldUpgrade, version := upgradeKeeper.ShouldUpgrade() + require.False(t, shouldUpgrade) + require.Equal(t, uint64(0), version) + + // we now have 101/120 + _, err = upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[1].String(), + Version: 2, + }) + require.NoError(t, err) + + upgradeKeeper.EndBlock(ctx) + shouldUpgrade, version = upgradeKeeper.ShouldUpgrade() + require.True(t, shouldUpgrade) + require.Equal(t, uint64(2), version) + // update the version to 2 + ctx = ctx.WithBlockHeader(tmproto.Header{ + Version: tmversion.Consensus{ + Block: 1, + App: 2, + }, + }) + goCtx = sdk.WrapSDKContext(ctx) + + _, err = upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[0].String(), + Version: 3, + }) + require.NoError(t, err) + + res, err = upgradeKeeper.VersionTally(goCtx, &types.QueryVersionTallyRequest{ + Version: 2, + }) + require.NoError(t, err) + require.EqualValues(t, 61, res.VotingPower) + require.EqualValues(t, 100, res.ThresholdPower) + require.EqualValues(t, 120, res.TotalVotingPower) + + // remove one of the validators from the set + delete(mockStakingKeeper.validators, testutil.ValAddrs[1].String()) + mockStakingKeeper.totalVotingPower-- + + res, err = upgradeKeeper.VersionTally(goCtx, &types.QueryVersionTallyRequest{ + Version: 2, + }) + require.NoError(t, err) + require.EqualValues(t, 60, res.VotingPower) + require.EqualValues(t, 99, res.ThresholdPower) + require.EqualValues(t, 119, res.TotalVotingPower) + + // That validator should not be able to signal a version + _, err = upgradeKeeper.SignalVersion(goCtx, &types.MsgSignalVersion{ + ValidatorAddress: testutil.ValAddrs[1].String(), + Version: 2, + }) + require.Error(t, err) +} + +func setup(t *testing.T) (upgrade.Keeper, sdk.Context, *mockStakingKeeper) { + upgradeStore := sdk.NewKVStoreKey(types.StoreKey) + db := tmdb.NewMemDB() + stateStore := store.NewCommitMultiStore(db) + stateStore.MountStoreWithDB(upgradeStore, storetypes.StoreTypeIAVL, nil) + require.NoError(t, stateStore.LoadLatestVersion()) + mockCtx := sdk.NewContext(stateStore, tmproto.Header{ + Version: tmversion.Consensus{ + Block: 1, + App: 1, + }, + }, false, log.NewNopLogger()) + mockStakingKeeper := &mockStakingKeeper{ + totalVotingPower: 120, + validators: map[string]int64{ + testutil.ValAddrs[0].String(): 40, + testutil.ValAddrs[1].String(): 1, + testutil.ValAddrs[2].String(): 60, + testutil.ValAddrs[3].String(): 19, + }, + } + + upgradeKeeper := upgrade.NewKeeper(upgradeStore, 0, mockStakingKeeper) + return upgradeKeeper, mockCtx, mockStakingKeeper +} + +var _ upgrade.StakingKeeper = (*mockStakingKeeper)(nil) + +type mockStakingKeeper struct { + totalVotingPower int64 + validators map[string]int64 +} + +func (m *mockStakingKeeper) GetLastTotalPower(_ sdk.Context) math.Int { + return math.NewInt(m.totalVotingPower) +} + +func (m *mockStakingKeeper) GetLastValidatorPower(_ sdk.Context, addr sdk.ValAddress) int64 { + addrStr := addr.String() + if power, ok := m.validators[addrStr]; ok { + return power + } + return 0 +} + +func (m *mockStakingKeeper) GetValidator(_ sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) { + addrStr := addr.String() + if _, ok := m.validators[addrStr]; ok { + return stakingtypes.Validator{Status: stakingtypes.Bonded}, true + } + return stakingtypes.Validator{}, false +} diff --git a/x/upgrade/types.go b/x/upgrade/types.go deleted file mode 100644 index ba3270a9c0..0000000000 --- a/x/upgrade/types.go +++ /dev/null @@ -1,65 +0,0 @@ -package upgrade - -import ( - "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" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" -) - -const ( - StoreKey = upgradetypes.StoreKey - ModuleName = upgradetypes.ModuleName -) - -var _ sdk.Msg = &MsgVersionChange{} - -// TypeRegister is used to register the upgrade module's types in the encoding -// config without defining an entire module. -type TypeRegister struct{} - -// RegisterLegacyAminoCodec registers the upgrade types on the LegacyAmino codec. -func (TypeRegister) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(upgradetypes.Plan{}, "cosmos-sdk/Plan", nil) - cdc.RegisterConcrete(MsgVersionChange{}, "celestia/MsgVersionChange", nil) -} - -// RegisterInterfaces registers the upgrade module types. -func (TypeRegister) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgVersionChange{}, - ) -} - -func (msg *MsgVersionChange) GetSigners() []sdk.AccAddress { - return nil -} - -func (msg *MsgVersionChange) ValidateBasic() error { - return nil -} - -// NewMsgVersionChange creates a tx in byte form used to signal to validators -// to change to a new version -func NewMsgVersionChange(txConfig client.TxConfig, version uint64) ([]byte, error) { - builder := txConfig.NewTxBuilder() - msg := &MsgVersionChange{ - Version: version, - } - if err := builder.SetMsgs(msg); err != nil { - return nil, err - } - return txConfig.TxEncoder()(builder.GetTx()) -} - -func IsUpgradeMsg(msg []sdk.Msg) (uint64, bool) { - if len(msg) != 1 { - return 0, false - } - msgVersionChange, ok := msg[0].(*MsgVersionChange) - if !ok { - return 0, false - } - return msgVersionChange.Version, true -} diff --git a/x/upgrade/types.pb.go b/x/upgrade/types.pb.go deleted file mode 100644 index 3e5eb9271e..0000000000 --- a/x/upgrade/types.pb.go +++ /dev/null @@ -1,301 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: celestia/upgrade/v1/types.proto - -package upgrade - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/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 - -// MsgVersionChange is a message that signals an app version change -type MsgVersionChange struct { - // the app version this message proposes upgrading to - Version uint64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` -} - -func (m *MsgVersionChange) Reset() { *m = MsgVersionChange{} } -func (m *MsgVersionChange) String() string { return proto.CompactTextString(m) } -func (*MsgVersionChange) ProtoMessage() {} -func (*MsgVersionChange) Descriptor() ([]byte, []int) { - return fileDescriptor_0195354c266f07b3, []int{0} -} -func (m *MsgVersionChange) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgVersionChange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgVersionChange.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 *MsgVersionChange) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgVersionChange.Merge(m, src) -} -func (m *MsgVersionChange) XXX_Size() int { - return m.Size() -} -func (m *MsgVersionChange) XXX_DiscardUnknown() { - xxx_messageInfo_MsgVersionChange.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgVersionChange proto.InternalMessageInfo - -func (m *MsgVersionChange) GetVersion() uint64 { - if m != nil { - return m.Version - } - return 0 -} - -func init() { - proto.RegisterType((*MsgVersionChange)(nil), "celestia.upgrade.v1.MsgVersionChange") -} - -func init() { proto.RegisterFile("celestia/upgrade/v1/types.proto", fileDescriptor_0195354c266f07b3) } - -var fileDescriptor_0195354c266f07b3 = []byte{ - // 164 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0x4e, 0xcd, 0x49, - 0x2d, 0x2e, 0xc9, 0x4c, 0xd4, 0x2f, 0x2d, 0x48, 0x2f, 0x4a, 0x4c, 0x49, 0xd5, 0x2f, 0x33, 0xd4, - 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x86, 0x29, 0xd0, - 0x83, 0x2a, 0xd0, 0x2b, 0x33, 0x54, 0xd2, 0xe1, 0x12, 0xf0, 0x2d, 0x4e, 0x0f, 0x4b, 0x2d, 0x2a, - 0xce, 0xcc, 0xcf, 0x73, 0xce, 0x48, 0xcc, 0x4b, 0x4f, 0x15, 0x92, 0xe0, 0x62, 0x2f, 0x83, 0x08, - 0x48, 0x30, 0x2a, 0x30, 0x6a, 0xb0, 0x04, 0xc1, 0xb8, 0x4e, 0xee, 0x27, 0x1e, 0xc9, 0x31, 0x5e, - 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, - 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0xa5, 0x9b, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, - 0xab, 0x0f, 0xb3, 0x27, 0xbf, 0x28, 0x1d, 0xce, 0xd6, 0x4d, 0x2c, 0x28, 0xd0, 0xaf, 0x80, 0x39, - 0x2d, 0x89, 0x0d, 0xec, 0x24, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x04, 0x7a, 0xde, 0x74, - 0xb5, 0x00, 0x00, 0x00, -} - -func (m *MsgVersionChange) 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 *MsgVersionChange) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgVersionChange) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Version != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.Version)) - i-- - dAtA[i] = 0x8 - } - 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 *MsgVersionChange) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Version != 0 { - n += 1 + sovTypes(uint64(m.Version)) - } - 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 *MsgVersionChange) 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: MsgVersionChange: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgVersionChange: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) - } - m.Version = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Version |= 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 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/upgrade/types/codec.go b/x/upgrade/types/codec.go new file mode 100644 index 0000000000..7cf5a81e89 --- /dev/null +++ b/x/upgrade/types/codec.go @@ -0,0 +1,18 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" +) + +// RegisterLegacyAminoCodec registers the upgrade types on the LegacyAmino codec. +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(upgradetypes.Plan{}, "cosmos-sdk/Plan", nil) +} + +// RegisterInterfaces registers the upgrade module types. +func RegisterInterfaces(registry codectypes.InterfaceRegistry) { + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} diff --git a/x/upgrade/types/errors.go b/x/upgrade/types/errors.go new file mode 100644 index 0000000000..1ff6064d9b --- /dev/null +++ b/x/upgrade/types/errors.go @@ -0,0 +1,7 @@ +package types + +import ( + "cosmossdk.io/errors" +) + +var ErrInvalidVersion = errors.Register(ModuleName, 1, "signalled version must be either the current version or one greater") diff --git a/x/upgrade/types/msgs.go b/x/upgrade/types/msgs.go new file mode 100644 index 0000000000..d308ab9f74 --- /dev/null +++ b/x/upgrade/types/msgs.go @@ -0,0 +1,38 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" +) + +const ( + StoreKey = upgradetypes.StoreKey + + // Copied from cosmos/cosmos-sdk/x/upgrade/types/keys.go: + ModuleName = upgradetypes.ModuleName + + // QuerierRoute defines the module's query routing key + QuerierRoute = ModuleName +) + +var _ sdk.Msg = &MsgSignalVersion{} + +func NewMsgSignalVersion(valAddress sdk.ValAddress, version uint64) *MsgSignalVersion { + return &MsgSignalVersion{ + ValidatorAddress: valAddress.String(), + Version: version, + } +} + +func (msg *MsgSignalVersion) GetSigners() []sdk.AccAddress { + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + if err != nil { + panic(err) + } + return []sdk.AccAddress{sdk.AccAddress(valAddr)} +} + +func (msg *MsgSignalVersion) ValidateBasic() error { + _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + return err +} diff --git a/x/upgrade/types/query.pb.go b/x/upgrade/types/query.pb.go new file mode 100644 index 0000000000..ed6653ac17 --- /dev/null +++ b/x/upgrade/types/query.pb.go @@ -0,0 +1,627 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: celestia/upgrade/v1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + grpc1 "github.com/gogo/protobuf/grpc" + proto "github.com/gogo/protobuf/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 + +// QueryVersionTallyRequest is the request type for the UpgradeStatus RPC +// method. +type QueryVersionTallyRequest struct { + Version uint64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` +} + +func (m *QueryVersionTallyRequest) Reset() { *m = QueryVersionTallyRequest{} } +func (m *QueryVersionTallyRequest) String() string { return proto.CompactTextString(m) } +func (*QueryVersionTallyRequest) ProtoMessage() {} +func (*QueryVersionTallyRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_7dd2290b21d03efa, []int{0} +} +func (m *QueryVersionTallyRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryVersionTallyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryVersionTallyRequest.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 *QueryVersionTallyRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryVersionTallyRequest.Merge(m, src) +} +func (m *QueryVersionTallyRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryVersionTallyRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryVersionTallyRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryVersionTallyRequest proto.InternalMessageInfo + +func (m *QueryVersionTallyRequest) GetVersion() uint64 { + if m != nil { + return m.Version + } + return 0 +} + +// QueryVersionTallyResponse is the response type for the UpgradeStatus RPC +// method. +type QueryVersionTallyResponse struct { + VotingPower uint64 `protobuf:"varint,1,opt,name=voting_power,json=votingPower,proto3" json:"voting_power,omitempty"` + ThresholdPower uint64 `protobuf:"varint,2,opt,name=threshold_power,json=thresholdPower,proto3" json:"threshold_power,omitempty"` + TotalVotingPower uint64 `protobuf:"varint,3,opt,name=total_voting_power,json=totalVotingPower,proto3" json:"total_voting_power,omitempty"` +} + +func (m *QueryVersionTallyResponse) Reset() { *m = QueryVersionTallyResponse{} } +func (m *QueryVersionTallyResponse) String() string { return proto.CompactTextString(m) } +func (*QueryVersionTallyResponse) ProtoMessage() {} +func (*QueryVersionTallyResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_7dd2290b21d03efa, []int{1} +} +func (m *QueryVersionTallyResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryVersionTallyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryVersionTallyResponse.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 *QueryVersionTallyResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryVersionTallyResponse.Merge(m, src) +} +func (m *QueryVersionTallyResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryVersionTallyResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryVersionTallyResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryVersionTallyResponse proto.InternalMessageInfo + +func (m *QueryVersionTallyResponse) GetVotingPower() uint64 { + if m != nil { + return m.VotingPower + } + return 0 +} + +func (m *QueryVersionTallyResponse) GetThresholdPower() uint64 { + if m != nil { + return m.ThresholdPower + } + return 0 +} + +func (m *QueryVersionTallyResponse) GetTotalVotingPower() uint64 { + if m != nil { + return m.TotalVotingPower + } + return 0 +} + +func init() { + proto.RegisterType((*QueryVersionTallyRequest)(nil), "celestia.upgrade.v1.QueryVersionTallyRequest") + proto.RegisterType((*QueryVersionTallyResponse)(nil), "celestia.upgrade.v1.QueryVersionTallyResponse") +} + +func init() { proto.RegisterFile("celestia/upgrade/v1/query.proto", fileDescriptor_7dd2290b21d03efa) } + +var fileDescriptor_7dd2290b21d03efa = []byte{ + // 331 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x91, 0xcd, 0x4e, 0x02, 0x31, + 0x14, 0x85, 0x29, 0xfe, 0x25, 0x95, 0xa8, 0xa9, 0x1b, 0x44, 0x1d, 0x15, 0x17, 0xba, 0x90, 0x36, + 0x88, 0x4f, 0xe0, 0xde, 0x44, 0x89, 0x61, 0xe1, 0x86, 0x14, 0x68, 0x86, 0x49, 0xc6, 0xb9, 0xa5, + 0xbd, 0x33, 0x4a, 0x8c, 0x1b, 0x9f, 0xc0, 0x68, 0xdc, 0xf9, 0x40, 0x2e, 0x49, 0xdc, 0xb8, 0x34, + 0xe0, 0x83, 0x18, 0x66, 0x86, 0x11, 0x13, 0x4c, 0xdc, 0xb5, 0xa7, 0xdf, 0x39, 0xbd, 0x3f, 0x74, + 0xa7, 0xad, 0x7c, 0x65, 0xd1, 0x93, 0x22, 0xd4, 0xae, 0x91, 0x1d, 0x25, 0xa2, 0xaa, 0xe8, 0x85, + 0xca, 0xf4, 0xb9, 0x36, 0x80, 0xc0, 0xd6, 0x27, 0x00, 0x4f, 0x01, 0x1e, 0x55, 0x4b, 0x5b, 0x2e, + 0x80, 0xeb, 0x2b, 0x21, 0xb5, 0x27, 0x64, 0x10, 0x00, 0x4a, 0xf4, 0x20, 0xb0, 0x89, 0xa5, 0x7c, + 0x42, 0x8b, 0x17, 0xe3, 0x84, 0x86, 0x32, 0xd6, 0x83, 0xe0, 0x52, 0xfa, 0x7e, 0xbf, 0xae, 0x7a, + 0xa1, 0xb2, 0xc8, 0x8a, 0x74, 0x29, 0x4a, 0xe4, 0x22, 0xd9, 0x25, 0x87, 0xf3, 0xf5, 0xc9, 0xb5, + 0xfc, 0x42, 0xe8, 0xc6, 0x0c, 0x9b, 0xd5, 0x10, 0x58, 0xc5, 0xf6, 0x68, 0x21, 0x02, 0xf4, 0x02, + 0xb7, 0xa9, 0xe1, 0x46, 0x99, 0xd4, 0xbc, 0x9c, 0x68, 0xe7, 0x63, 0x89, 0x1d, 0xd0, 0x55, 0xec, + 0x1a, 0x65, 0xbb, 0xe0, 0x77, 0x52, 0x2a, 0x1f, 0x53, 0x2b, 0x99, 0x9c, 0x80, 0x47, 0x94, 0x21, + 0xa0, 0xf4, 0x9b, 0xbf, 0x12, 0xe7, 0x62, 0x76, 0x2d, 0x7e, 0x69, 0xfc, 0xc4, 0x1e, 0xbf, 0x12, + 0xba, 0x10, 0xd7, 0xc5, 0x9e, 0x08, 0x2d, 0x4c, 0x17, 0xc7, 0x2a, 0x7c, 0xc6, 0x70, 0xf8, 0x5f, + 0xbd, 0x97, 0xf8, 0x7f, 0xf1, 0xa4, 0xe7, 0xf2, 0xfe, 0xc3, 0xfb, 0xd7, 0x73, 0x7e, 0x9b, 0x6d, + 0x4e, 0xef, 0x06, 0xc7, 0x88, 0xb8, 0x4b, 0xa7, 0x76, 0x7f, 0x7a, 0xf6, 0x36, 0x74, 0xc8, 0x60, + 0xe8, 0x90, 0xcf, 0xa1, 0x43, 0x1e, 0x47, 0x4e, 0x6e, 0x30, 0x72, 0x72, 0x1f, 0x23, 0x27, 0x77, + 0x55, 0x73, 0x3d, 0xec, 0x86, 0x2d, 0xde, 0x86, 0x6b, 0x31, 0xf9, 0x18, 0x8c, 0x9b, 0x9d, 0x2b, + 0x52, 0x6b, 0x71, 0x9b, 0x65, 0x63, 0x5f, 0x2b, 0xdb, 0x5a, 0x8c, 0x57, 0x58, 0xfb, 0x0e, 0x00, + 0x00, 0xff, 0xff, 0xa9, 0x02, 0x48, 0x0f, 0x18, 0x02, 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 { + // VersionTally allows the querying of the tally of voting power by all + // validators that have signalled for each version + VersionTally(ctx context.Context, in *QueryVersionTallyRequest, opts ...grpc.CallOption) (*QueryVersionTallyResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) VersionTally(ctx context.Context, in *QueryVersionTallyRequest, opts ...grpc.CallOption) (*QueryVersionTallyResponse, error) { + out := new(QueryVersionTallyResponse) + err := c.cc.Invoke(ctx, "/celestia.upgrade.v1.Query/VersionTally", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // VersionTally allows the querying of the tally of voting power by all + // validators that have signalled for each version + VersionTally(context.Context, *QueryVersionTallyRequest) (*QueryVersionTallyResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) VersionTally(ctx context.Context, req *QueryVersionTallyRequest) (*QueryVersionTallyResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method VersionTally not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_VersionTally_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryVersionTallyRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).VersionTally(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/celestia.upgrade.v1.Query/VersionTally", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).VersionTally(ctx, req.(*QueryVersionTallyRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "celestia.upgrade.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "VersionTally", + Handler: _Query_VersionTally_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "celestia/upgrade/v1/query.proto", +} + +func (m *QueryVersionTallyRequest) 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 *QueryVersionTallyRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryVersionTallyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Version != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Version)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryVersionTallyResponse) 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 *QueryVersionTallyResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryVersionTallyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.TotalVotingPower != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.TotalVotingPower)) + i-- + dAtA[i] = 0x18 + } + if m.ThresholdPower != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.ThresholdPower)) + i-- + dAtA[i] = 0x10 + } + if m.VotingPower != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.VotingPower)) + i-- + dAtA[i] = 0x8 + } + 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 *QueryVersionTallyRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Version != 0 { + n += 1 + sovQuery(uint64(m.Version)) + } + return n +} + +func (m *QueryVersionTallyResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.VotingPower != 0 { + n += 1 + sovQuery(uint64(m.VotingPower)) + } + if m.ThresholdPower != 0 { + n += 1 + sovQuery(uint64(m.ThresholdPower)) + } + if m.TotalVotingPower != 0 { + n += 1 + sovQuery(uint64(m.TotalVotingPower)) + } + 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 *QueryVersionTallyRequest) 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: QueryVersionTallyRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryVersionTallyRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + m.Version = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Version |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 *QueryVersionTallyResponse) 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: QueryVersionTallyResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryVersionTallyResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field VotingPower", wireType) + } + m.VotingPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.VotingPower |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ThresholdPower", wireType) + } + m.ThresholdPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ThresholdPower |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TotalVotingPower", wireType) + } + m.TotalVotingPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TotalVotingPower |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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/upgrade/types/query.pb.gw.go b/x/upgrade/types/query.pb.gw.go new file mode 100644 index 0000000000..03b777ca29 --- /dev/null +++ b/x/upgrade/types/query.pb.gw.go @@ -0,0 +1,189 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: celestia/upgrade/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_VersionTally_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryVersionTallyRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["version"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "version") + } + + protoReq.Version, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "version", err) + } + + msg, err := client.VersionTally(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_VersionTally_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryVersionTallyRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["version"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "version") + } + + protoReq.Version, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "version", err) + } + + msg, err := server.VersionTally(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_VersionTally_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_VersionTally_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_VersionTally_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_VersionTally_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_VersionTally_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_VersionTally_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_VersionTally_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"upgrade", "v1", "tally", "version"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_VersionTally_0 = runtime.ForwardResponseMessage +) diff --git a/x/upgrade/types/tx.pb.go b/x/upgrade/types/tx.pb.go new file mode 100644 index 0000000000..fd15cd30ee --- /dev/null +++ b/x/upgrade/types/tx.pb.go @@ -0,0 +1,567 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: celestia/upgrade/v1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + grpc1 "github.com/gogo/protobuf/grpc" + proto "github.com/gogo/protobuf/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 + +// MsgSignalVersion signals for an upgrade +type MsgSignalVersion struct { + ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` + Version uint64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` +} + +func (m *MsgSignalVersion) Reset() { *m = MsgSignalVersion{} } +func (m *MsgSignalVersion) String() string { return proto.CompactTextString(m) } +func (*MsgSignalVersion) ProtoMessage() {} +func (*MsgSignalVersion) Descriptor() ([]byte, []int) { + return fileDescriptor_ee2a0c754324bd13, []int{0} +} +func (m *MsgSignalVersion) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSignalVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSignalVersion.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 *MsgSignalVersion) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSignalVersion.Merge(m, src) +} +func (m *MsgSignalVersion) XXX_Size() int { + return m.Size() +} +func (m *MsgSignalVersion) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSignalVersion.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSignalVersion proto.InternalMessageInfo + +func (m *MsgSignalVersion) GetValidatorAddress() string { + if m != nil { + return m.ValidatorAddress + } + return "" +} + +func (m *MsgSignalVersion) GetVersion() uint64 { + if m != nil { + return m.Version + } + return 0 +} + +// MsgSignalVersionResponse describes the response returned after the submission +// of a SignalVersion +type MsgSignalVersionResponse struct { +} + +func (m *MsgSignalVersionResponse) Reset() { *m = MsgSignalVersionResponse{} } +func (m *MsgSignalVersionResponse) String() string { return proto.CompactTextString(m) } +func (*MsgSignalVersionResponse) ProtoMessage() {} +func (*MsgSignalVersionResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_ee2a0c754324bd13, []int{1} +} +func (m *MsgSignalVersionResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSignalVersionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSignalVersionResponse.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 *MsgSignalVersionResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSignalVersionResponse.Merge(m, src) +} +func (m *MsgSignalVersionResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgSignalVersionResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSignalVersionResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSignalVersionResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgSignalVersion)(nil), "celestia.upgrade.v1.MsgSignalVersion") + proto.RegisterType((*MsgSignalVersionResponse)(nil), "celestia.upgrade.v1.MsgSignalVersionResponse") +} + +func init() { proto.RegisterFile("celestia/upgrade/v1/tx.proto", fileDescriptor_ee2a0c754324bd13) } + +var fileDescriptor_ee2a0c754324bd13 = []byte{ + // 283 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x50, 0x4f, 0x4b, 0xc3, 0x30, + 0x14, 0x6f, 0xa6, 0x28, 0x06, 0x84, 0x59, 0x3d, 0x94, 0x32, 0xc2, 0x28, 0x08, 0x03, 0x59, 0xc2, + 0xdc, 0x27, 0xd0, 0x7b, 0x2f, 0x15, 0x04, 0xbd, 0x48, 0xb6, 0x86, 0x18, 0xa8, 0x49, 0xc8, 0xcb, + 0xca, 0x3c, 0xea, 0xcd, 0x9b, 0xe0, 0x97, 0xf2, 0x38, 0xf0, 0xe2, 0x51, 0x5a, 0x3f, 0x88, 0xb0, + 0xda, 0xa2, 0xc3, 0x83, 0xb7, 0xf7, 0xde, 0xef, 0x1f, 0xef, 0x87, 0x07, 0x73, 0x51, 0x08, 0xf0, + 0x8a, 0xb3, 0x85, 0x95, 0x8e, 0xe7, 0x82, 0x95, 0x13, 0xe6, 0x97, 0xd4, 0x3a, 0xe3, 0x4d, 0x78, + 0xd8, 0xa2, 0xf4, 0x1b, 0xa5, 0xe5, 0x24, 0x1e, 0x48, 0x63, 0x64, 0x21, 0x18, 0xb7, 0x8a, 0x71, + 0xad, 0x8d, 0xe7, 0x5e, 0x19, 0x0d, 0x8d, 0x24, 0xb9, 0xc2, 0xfd, 0x14, 0xe4, 0x85, 0x92, 0x9a, + 0x17, 0x97, 0xc2, 0x81, 0x32, 0x3a, 0x3c, 0xc1, 0x07, 0x25, 0x2f, 0x54, 0xce, 0xbd, 0x71, 0x37, + 0x3c, 0xcf, 0x9d, 0x00, 0x88, 0xd0, 0x10, 0x8d, 0xf6, 0xb2, 0x7e, 0x07, 0x9c, 0x35, 0xf7, 0x30, + 0xc2, 0xbb, 0x65, 0xa3, 0x8b, 0x7a, 0x43, 0x34, 0xda, 0xce, 0xda, 0x35, 0x89, 0x71, 0xb4, 0x69, + 0x9d, 0x09, 0xb0, 0x46, 0x83, 0x38, 0x7d, 0x42, 0x78, 0x2b, 0x05, 0x19, 0x3e, 0x20, 0xbc, 0xff, + 0x3b, 0xfc, 0x98, 0xfe, 0xf1, 0x04, 0xdd, 0x34, 0x8a, 0xc7, 0xff, 0xa2, 0xb5, 0x79, 0x49, 0xfc, + 0xf8, 0xf6, 0xf9, 0xd2, 0x3b, 0x4a, 0xc2, 0x9f, 0xbd, 0xc1, 0x9a, 0x7a, 0x9e, 0xbe, 0x56, 0x04, + 0xad, 0x2a, 0x82, 0x3e, 0x2a, 0x82, 0x9e, 0x6b, 0x12, 0xac, 0x6a, 0x12, 0xbc, 0xd7, 0x24, 0xb8, + 0x9e, 0x4a, 0xe5, 0x6f, 0x17, 0x33, 0x3a, 0x37, 0x77, 0xac, 0x8d, 0x33, 0x4e, 0x76, 0xf3, 0x98, + 0x5b, 0xcb, 0x96, 0x9d, 0xa5, 0xbf, 0xb7, 0x02, 0x66, 0x3b, 0xeb, 0x62, 0xa7, 0x5f, 0x01, 0x00, + 0x00, 0xff, 0xff, 0x7d, 0x45, 0x22, 0x3c, 0xab, 0x01, 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 { + // SignalVersion allows the validator to signal for an upgrade + SignalVersion(ctx context.Context, in *MsgSignalVersion, opts ...grpc.CallOption) (*MsgSignalVersionResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) SignalVersion(ctx context.Context, in *MsgSignalVersion, opts ...grpc.CallOption) (*MsgSignalVersionResponse, error) { + out := new(MsgSignalVersionResponse) + err := c.cc.Invoke(ctx, "/celestia.upgrade.v1.Msg/SignalVersion", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + // SignalVersion allows the validator to signal for an upgrade + SignalVersion(context.Context, *MsgSignalVersion) (*MsgSignalVersionResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) SignalVersion(ctx context.Context, req *MsgSignalVersion) (*MsgSignalVersionResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SignalVersion not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_SignalVersion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgSignalVersion) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).SignalVersion(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/celestia.upgrade.v1.Msg/SignalVersion", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).SignalVersion(ctx, req.(*MsgSignalVersion)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "celestia.upgrade.v1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "SignalVersion", + Handler: _Msg_SignalVersion_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "celestia/upgrade/v1/tx.proto", +} + +func (m *MsgSignalVersion) 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 *MsgSignalVersion) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSignalVersion) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Version != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.Version)) + i-- + dAtA[i] = 0x10 + } + if len(m.ValidatorAddress) > 0 { + i -= len(m.ValidatorAddress) + copy(dAtA[i:], m.ValidatorAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.ValidatorAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgSignalVersionResponse) 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 *MsgSignalVersionResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSignalVersionResponse) 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 *MsgSignalVersion) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ValidatorAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.Version != 0 { + n += 1 + sovTx(uint64(m.Version)) + } + return n +} + +func (m *MsgSignalVersionResponse) 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 *MsgSignalVersion) 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: MsgSignalVersion: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSignalVersion: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", 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.ValidatorAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + m.Version = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Version |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 *MsgSignalVersionResponse) 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: MsgSignalVersionResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSignalVersionResponse: 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/upgrade/types/tx.pb.gw.go b/x/upgrade/types/tx.pb.gw.go new file mode 100644 index 0000000000..429e98cf87 --- /dev/null +++ b/x/upgrade/types/tx.pb.gw.go @@ -0,0 +1,171 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: celestia/upgrade/v1/tx.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 + +var ( + filter_Msg_SignalVersion_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Msg_SignalVersion_0(ctx context.Context, marshaler runtime.Marshaler, client MsgClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq MsgSignalVersion + 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_Msg_SignalVersion_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.SignalVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Msg_SignalVersion_0(ctx context.Context, marshaler runtime.Marshaler, server MsgServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq MsgSignalVersion + 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_Msg_SignalVersion_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.SignalVersion(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterMsgHandlerServer registers the http handlers for service Msg to "mux". +// UnaryRPC :call MsgServer 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 RegisterMsgHandlerFromEndpoint instead. +func RegisterMsgHandlerServer(ctx context.Context, mux *runtime.ServeMux, server MsgServer) error { + + mux.Handle("POST", pattern_Msg_SignalVersion_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_Msg_SignalVersion_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_Msg_SignalVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterMsgHandlerFromEndpoint is same as RegisterMsgHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterMsgHandlerFromEndpoint(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 RegisterMsgHandler(ctx, mux, conn) +} + +// RegisterMsgHandler registers the http handlers for service Msg to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterMsgHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterMsgHandlerClient(ctx, mux, NewMsgClient(conn)) +} + +// RegisterMsgHandlerClient registers the http handlers for service Msg +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "MsgClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "MsgClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "MsgClient" to call the correct interceptors. +func RegisterMsgHandlerClient(ctx context.Context, mux *runtime.ServeMux, client MsgClient) error { + + mux.Handle("POST", pattern_Msg_SignalVersion_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_Msg_SignalVersion_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Msg_SignalVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Msg_SignalVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"upgrade", "v1", "signal"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Msg_SignalVersion_0 = runtime.ForwardResponseMessage +)