diff --git a/app/app.go b/app/app.go index 95f1f8b9a..f8716ffd6 100644 --- a/app/app.go +++ b/app/app.go @@ -6,7 +6,10 @@ import ( "os" "path/filepath" + "github.com/cheqd/cheqd-node/x/resource" + cheqdtypes "github.com/cheqd/cheqd-node/x/cheqd/types" + resourcetypes "github.com/cheqd/cheqd-node/x/resource/types" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/authz" authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" @@ -37,6 +40,7 @@ import ( appparams "github.com/cheqd/cheqd-node/app/params" "github.com/cheqd/cheqd-node/x/cheqd" cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + resourcekeeper "github.com/cheqd/cheqd-node/x/resource/keeper" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" "github.com/cosmos/cosmos-sdk/client/rpc" @@ -147,6 +151,7 @@ var ( feegrantmodule.AppModuleBasic{}, authzmodule.AppModuleBasic{}, cheqd.AppModuleBasic{}, + resource.AppModuleBasic{}, ) // module account permissions @@ -214,7 +219,8 @@ type App struct { ScopedIBCKeeper capabilitykeeper.ScopedKeeper ScopedTransferKeeper capabilitykeeper.ScopedKeeper - cheqdKeeper cheqdkeeper.Keeper + cheqdKeeper cheqdkeeper.Keeper + resourceKeeper resourcekeeper.Keeper // the module manager mm *module.Manager @@ -243,7 +249,7 @@ func New( govtypes.StoreKey, paramstypes.StoreKey, upgradetypes.StoreKey, evidencetypes.StoreKey, capabilitytypes.StoreKey, feegrant.StoreKey, ibchost.StoreKey, ibctransfertypes.StoreKey, authzkeeper.StoreKey, - cheqdtypes.StoreKey, + cheqdtypes.StoreKey, resourcetypes.StoreKey, ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) @@ -378,6 +384,10 @@ func New( appCodec, keys[cheqdtypes.StoreKey], ) + app.resourceKeeper = *resourcekeeper.NewKeeper( + appCodec, keys[resourcetypes.StoreKey], + ) + app.GovKeeper = govkeeper.NewKeeper( appCodec, keys[govtypes.StoreKey], app.GetSubspace(govtypes.ModuleName), app.AccountKeeper, app.BankKeeper, &stakingKeeper, govRouter, @@ -418,6 +428,7 @@ func New( feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeegrantKeeper, app.interfaceRegistry), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), cheqd.NewAppModule(appCodec, app.cheqdKeeper), + resource.NewAppModule(appCodec, app.resourceKeeper, app.cheqdKeeper), ibc.NewAppModule(app.IBCKeeper), transferModule, ) @@ -437,6 +448,7 @@ func New( stakingtypes.ModuleName, ibchost.ModuleName, cheqdtypes.ModuleName, + resourcetypes.ModuleName, genutiltypes.ModuleName, banktypes.ModuleName, crisistypes.ModuleName, @@ -461,6 +473,7 @@ func New( evidencetypes.ModuleName, ibchost.ModuleName, cheqdtypes.ModuleName, + resourcetypes.ModuleName, genutiltypes.ModuleName, banktypes.ModuleName, ibctransfertypes.ModuleName, @@ -493,6 +506,7 @@ func New( feegrant.ModuleName, authz.ModuleName, cheqdtypes.ModuleName, + resourcetypes.ModuleName, vestingtypes.ModuleName, upgradetypes.ModuleName, paramstypes.ModuleName, @@ -515,6 +529,7 @@ func New( feegrant.ModuleName, authz.ModuleName, cheqdtypes.ModuleName, + resourcetypes.ModuleName, paramstypes.ModuleName, vestingtypes.ModuleName, upgradetypes.ModuleName, @@ -573,7 +588,7 @@ func (app *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.Respo func (app *App) TestNetMigration(ctx sdk.Context) { if ctx.ChainID() == "cheqd-testnet-2" { - app.cheqdKeeper.SetDidNamespace(ctx, "testnet") + app.cheqdKeeper.SetDidNamespace(&ctx, "testnet") } } diff --git a/app/migration_v_0_5.go b/app/migration_v_0_5.go index e3db7601c..204381581 100644 --- a/app/migration_v_0_5.go +++ b/app/migration_v_0_5.go @@ -6,7 +6,7 @@ import ( func (app *App) Migration05(ctx sdk.Context) { oldKey := "testnettestnet" - namespase := app.cheqdKeeper.GetFromState(ctx, oldKey) - app.cheqdKeeper.DeteteFromState(ctx, oldKey) - app.cheqdKeeper.SetDidNamespace(ctx, namespase) + namespase := app.cheqdKeeper.GetFromState(&ctx, oldKey) + app.cheqdKeeper.DeleteFromState(&ctx, oldKey) + app.cheqdKeeper.SetDidNamespace(&ctx, namespase) } diff --git a/go.mod b/go.mod index 7f2d48a10..ac059b06c 100644 --- a/go.mod +++ b/go.mod @@ -5,25 +5,27 @@ go 1.17 require ( filippo.io/edwards25519 v1.0.0-beta.2 github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce - github.com/cosmos/cosmos-sdk v0.45.4 + github.com/cosmos/cosmos-sdk v0.45.6 github.com/cosmos/ibc-go v1.4.0 + github.com/gabriel-vasile/mimetype v1.4.0 github.com/go-ozzo/ozzo-validation/v4 v4.3.0 github.com/gogo/protobuf v1.3.3 github.com/golang/protobuf v1.5.2 + github.com/google/uuid v1.3.0 github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/lestrrat-go/jwx v1.2.20 github.com/multiformats/go-multibase v0.0.3 github.com/rakyll/statik v0.1.7 github.com/spf13/cast v1.4.1 - github.com/spf13/cobra v1.4.0 + github.com/spf13/cobra v1.5.0 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.10.1 github.com/stretchr/testify v1.7.1 github.com/tendermint/tendermint v0.34.19 github.com/tendermint/tm-db v0.6.6 - google.golang.org/genproto v0.0.0-20211223182754-3ac035c7e7cb - google.golang.org/grpc v1.45.0 + google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd + google.golang.org/grpc v1.46.2 ) require ( @@ -65,6 +67,7 @@ require ( github.com/gogo/gateway v1.1.0 // indirect github.com/golang/snappy v0.0.3 // indirect github.com/google/btree v1.0.0 // indirect + github.com/google/go-cmp v0.5.8 // indirect github.com/google/orderedcode v0.0.1 // indirect github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect @@ -124,14 +127,14 @@ require ( github.com/zondax/hid v0.9.0 // indirect go.etcd.io/bbolt v1.3.6 // indirect golang.org/x/crypto v0.0.0-20220214200702-86341886e292 // indirect - golang.org/x/net v0.0.0-20211208012354-db4efeb81f4b // indirect + golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect - golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect + golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect golang.org/x/text v0.3.7 // indirect - google.golang.org/protobuf v1.27.1 // indirect + google.golang.org/protobuf v1.28.0 // indirect gopkg.in/ini.v1 v1.66.2 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect nhooyr.io/websocket v1.8.6 // indirect ) diff --git a/go.sum b/go.sum index 91df4ebd6..07046cfc7 100644 --- a/go.sum +++ b/go.sum @@ -237,6 +237,7 @@ github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwc github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cyphar/filepath-securejoin v0.2.2/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4= @@ -316,6 +317,8 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= +github.com/gabriel-vasile/mimetype v1.4.0 h1:Cn9dkdYsMIu56tGho+fqzh7XmvY2YyGU0FnbhiOsEro= +github.com/gabriel-vasile/mimetype v1.4.0/go.mod h1:fA8fi6KUiG7MgQQ+mEWotXoEOvmxRtOJlERCzSmRvr8= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= @@ -427,8 +430,9 @@ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.1.1-0.20200604201612-c04b05f3adfa h1:Q75Upo5UN4JbPFURXZ8nLKYUvF85dyFRop/vQ0Rv+64= @@ -457,6 +461,8 @@ github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm4 github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= @@ -920,8 +926,9 @@ github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tL github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= -github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q= github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= +github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU= +github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -1170,6 +1177,7 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= @@ -1177,8 +1185,9 @@ golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20210903162142-ad29c8ab022f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210917221730-978cfadd31cf/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211208012354-db4efeb81f4b h1:MWaHNqZy3KTpuTMAGvv+Kw+ylsEpmyJZizz1dqxnu28= golang.org/x/net v0.0.0-20211208012354-db4efeb81f4b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk= +golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1304,11 +1313,13 @@ golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 h1:XfKQ4OlFl8okEOr5UvAqFRVj8pY/4yfcXrddB8qAbU0= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1393,7 +1404,6 @@ golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0= @@ -1508,8 +1518,9 @@ google.golang.org/genproto v0.0.0-20211028162531-8db9c33dc351/go.mod h1:5CzLGKJ6 google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20211223182754-3ac035c7e7cb h1:ZrsicilzPCS/Xr8qtBZZLpy4P9TYXAfl49ctG1/5tgw= google.golang.org/genproto v0.0.0-20211223182754-3ac035c7e7cb/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd h1:e0TwkXOdbnH/1x5rc5MZ/VYyiZ4v+RdVfrGMqEwT68I= +google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= google.golang.org/grpc v1.33.2 h1:EQyQC3sa8M+p6Ulc8yy9SWSS2GVwyRc83gAbG8lrl4o= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= @@ -1526,8 +1537,9 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba google.golang.org/protobuf v1.25.1-0.20200805231151-a709e31e5d12/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -1562,8 +1574,9 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/proto/cheqd/v1/stateValue.proto b/proto/cheqd/v1/stateValue.proto index b5fde6f94..3edd74b0d 100644 --- a/proto/cheqd/v1/stateValue.proto +++ b/proto/cheqd/v1/stateValue.proto @@ -15,4 +15,5 @@ message Metadata { string updated = 2; bool deactivated = 3; string version_id = 4; + repeated string resources = 5; } diff --git a/proto/resource/v1/genesis.proto b/proto/resource/v1/genesis.proto new file mode 100644 index 000000000..0bb62e1de --- /dev/null +++ b/proto/resource/v1/genesis.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +package cheqdid.cheqdnode.resource.v1; + +option go_package = "github.com/cheqd/cheqd-node/x/resource/types"; + +import "resource/v1/resource.proto"; + +// GenesisState defines the cheqd module's genesis state. +message GenesisState { + repeated Resource resourceList = 1; +} + diff --git a/proto/resource/v1/query.proto b/proto/resource/v1/query.proto new file mode 100644 index 000000000..ba341e9cc --- /dev/null +++ b/proto/resource/v1/query.proto @@ -0,0 +1,47 @@ +syntax = "proto3"; +package cheqdid.cheqdnode.resource.v1; + +option go_package = "github.com/cheqd/cheqd-node/x/resource/types"; + +import "google/api/annotations.proto"; +import "resource/v1/resource.proto"; + + +// Query defines the gRPC querier service. +service Query { + rpc Resource(QueryGetResourceRequest) returns (QueryGetResourceResponse) { + option (google.api.http).get = "/1.0/identifiers/{collection_id}/resources/{id}"; + } + rpc CollectionResources(QueryGetCollectionResourcesRequest) returns (QueryGetCollectionResourcesResponse) { + option (google.api.http).get = "/1.0/identifiers/{collection_id}/resources/all"; + } + rpc AllResourceVersions(QueryGetAllResourceVersionsRequest) returns (QueryGetAllResourceVersionsResponse) { + option (google.api.http).get = "/1.0/identifiers/{collection_id}/resources/versions/{name}"; + } +} + +message QueryGetResourceRequest { + string collection_id = 1; + string id = 2; +} + +message QueryGetResourceResponse { + Resource resource = 1; +} + +message QueryGetCollectionResourcesRequest { + string collection_id = 1; +} + +message QueryGetCollectionResourcesResponse { + repeated ResourceHeader resources = 1; +} + +message QueryGetAllResourceVersionsRequest { + string collection_id = 1; + string name = 2; +} + +message QueryGetAllResourceVersionsResponse { + repeated ResourceHeader resources = 1; +} diff --git a/proto/resource/v1/resource.proto b/proto/resource/v1/resource.proto new file mode 100644 index 000000000..b92d4488c --- /dev/null +++ b/proto/resource/v1/resource.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; +package cheqdid.cheqdnode.resource.v1; + +option go_package = "github.com/cheqd/cheqd-node/x/resource/types"; + + +message Resource { + ResourceHeader header = 1; + bytes data = 2; +} + +message ResourceHeader { + string collection_id = 1; + string id = 2; + string name = 3; + string resource_type = 4; + string media_type = 5; + string created = 6; + bytes checksum = 7; + string previous_version_id = 8; + string next_version_id = 9; +} diff --git a/proto/resource/v1/tx.proto b/proto/resource/v1/tx.proto new file mode 100644 index 000000000..118c6736b --- /dev/null +++ b/proto/resource/v1/tx.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; +package cheqdid.cheqdnode.resource.v1; + +option go_package = "github.com/cheqd/cheqd-node/x/resource/types"; + +import "cheqd/v1/tx.proto"; +import "resource/v1/resource.proto"; + +// Msg defines the Msg service. +service Msg { + rpc CreateResource(MsgCreateResource) returns (MsgCreateResourceResponse); +} + +// this line is used by starport scaffolding # proto/tx/message +message MsgCreateResource { + MsgCreateResourcePayload payload = 1; + repeated cheqdid.cheqdnode.cheqd.v1.SignInfo signatures = 2; +} + +message MsgCreateResourcePayload { + string collection_id = 1; + string id = 2; + string name = 3; + string resource_type = 4; + bytes data = 6; +} + +message MsgCreateResourceResponse { + Resource resource = 1; // Not necessary +} diff --git a/tests/e2e-bash/resource.dat b/tests/e2e-bash/resource.dat new file mode 100644 index 000000000..2f8e9776b Binary files /dev/null and b/tests/e2e-bash/resource.dat differ diff --git a/tests/e2e-bash/tests/test_create_resource.sh b/tests/e2e-bash/tests/test_create_resource.sh new file mode 100644 index 000000000..024555882 --- /dev/null +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -0,0 +1,75 @@ +#!/bin/bash + +set -euox pipefail + +SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" +# shellcheck source=/dev/null +source "$SCRIPT_DIR/common.sh" + + +# Generate Alice identity key +ALICE_VER_KEY="$(cheqd-noded debug ed25519 random)" +ALICE_VER_PUB_BASE_64=$(echo "${ALICE_VER_KEY}" | jq -r ".pub_key_base_64") +ALICE_VER_PRIV_BASE_64=$(echo "${ALICE_VER_KEY}" | jq -r ".priv_key_base_64") +ALICE_VER_PUB_MULTIBASE_58=$(cheqd-noded debug encoding base64-multibase58 "${ALICE_VER_PUB_BASE_64}") + + +########## Creating DID ########## + +ID="$(random_string)" +DID="did:cheqd:testnet:$ID" +KEY_ID="${DID}#key1" + +MSG_CREATE_DID='{ + "id": "'${DID}'", + "verification_method": [{ + "id": "'${KEY_ID}'", + "type": "Ed25519VerificationKey2020", + "controller": "'${DID}'", + "public_key_multibase": "'${ALICE_VER_PUB_MULTIBASE_58}'" + }], + "authentication": [ + "'${KEY_ID}'" + ] +}'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx cheqd create-did "${MSG_CREATE_DID}" "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + + +########## Creating Resource ########## + +RESOURCE_ID=$(uuidgen) +RESOURCE_NAME="Resource 1" +RESOURCE_MEDIA_TYPE="application/json" +RESOURCE_RESOURCE_TYPE="CL-Schema" +RESOURCE_DATA='{ "content": "test data" }'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource \ + --collection-id ${ID} \ + --resource-id ${RESOURCE_ID} \ + --resource-name "${RESOURCE_NAME}" \ + --resource-type ${RESOURCE_RESOURCE_TYPE} \ + --resource-file <(echo "${RESOURCE_DATA}") \ + "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + +########## Querying Resource ########## + +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded query resource resource "${ID}" ${RESOURCE_ID} ${QUERY_PARAMS}) + +assert_eq "$(echo "$RESULT" | jq -r ".resource.header.collection_id")" "${ID}" +assert_eq "$(echo "$RESULT" | jq -r ".resource.header.id")" "${RESOURCE_ID}" +assert_eq "$(echo "$RESULT" | jq -r ".resource.header.name")" "${RESOURCE_NAME}" +assert_eq "$(echo "$RESULT" | jq -r ".resource.header.resource_type")" "${RESOURCE_RESOURCE_TYPE}" +assert_eq "$(echo "$RESULT" | jq -r ".resource.header.media_type")" "${RESOURCE_MEDIA_TYPE}" +assert_eq "$(echo "$RESULT" | jq -r ".resource.data")" "$(echo "${RESOURCE_DATA}" | base64 -w 0)" diff --git a/tests/e2e-bash/tests/test_query_all_resource_versions.sh b/tests/e2e-bash/tests/test_query_all_resource_versions.sh new file mode 100644 index 000000000..d901d0655 --- /dev/null +++ b/tests/e2e-bash/tests/test_query_all_resource_versions.sh @@ -0,0 +1,139 @@ +#!/bin/bash + +set -euox pipefail + +SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" +# shellcheck source=/dev/null +source "$SCRIPT_DIR/common.sh" + + +# Generate Alice identity key +ALICE_VER_KEY="$(cheqd-noded debug ed25519 random)" +ALICE_VER_PUB_BASE_64=$(echo "${ALICE_VER_KEY}" | jq -r ".pub_key_base_64") +ALICE_VER_PRIV_BASE_64=$(echo "${ALICE_VER_KEY}" | jq -r ".priv_key_base_64") +ALICE_VER_PUB_MULTIBASE_58=$(cheqd-noded debug encoding base64-multibase58 "${ALICE_VER_PUB_BASE_64}") + + +########## Creating DID 1 ########## + +ID1="$(random_string)" +DID1="did:cheqd:testnet:$ID1" +KEY1_ID="${DID1}#key1" + +MSG_CREATE_DID_1='{ + "id": "'${DID1}'", + "verification_method": [{ + "id": "'${KEY1_ID}'", + "type": "Ed25519VerificationKey2020", + "controller": "'${DID1}'", + "public_key_multibase": "'${ALICE_VER_PUB_MULTIBASE_58}'" + }], + "authentication": [ + "'${KEY1_ID}'" + ] +}'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx cheqd create-did "${MSG_CREATE_DID_1}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + + +########## Creating Resource 1 ########## + +RESOURCE1_V1_ID=$(uuidgen) +RESOURCE1_NAME="Resource 1" +RESOURCE1_MEDIA_TYPE="application/json" +RESOURCE1_RESOURCE_TYPE="CL-Schema" +RESOURCE1_V1_DATA='{ "content": "resource 1 v1" }'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource \ + --collection-id "${ID1}" \ + --resource-id "${RESOURCE1_V1_ID}" \ + --resource-name "${RESOURCE1_NAME}" \ + --resource-type "${RESOURCE1_RESOURCE_TYPE}" \ + --resource-file <(echo "${RESOURCE1_V1_DATA}") \ + "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + +########## Querying Resource 1 ########## + +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded query resource resource "${ID1}" ${RESOURCE1_V1_ID} ${QUERY_PARAMS}) + +EXPECTED_RES1_V1_HEADER='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V1_ID}'", + "name": "'${RESOURCE1_NAME}'", + "media_type": "'${RESOURCE1_MEDIA_TYPE}'", + "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'" +}' + +DEL_FILTER='del(.checksum, .created, .next_version_id, .previous_version_id)' +assert_json_eq "$(echo "$RESULT" | jq -r ".resource.header | ${DEL_FILTER}")" "${EXPECTED_RES1_V1_HEADER}" +assert_json_eq "$(echo "$RESULT" | jq -r ".resource.data")" "$(echo "${RESOURCE1_V1_DATA}" | base64 -w 0)" + + +########## Creating Resource 1 v2 ########## + +RESOURCE1_V2_ID=$(uuidgen) +RESOURCE1_V2_DATA='{ "content": "resource 1 v2" }'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource \ + --collection-id "${ID1}" \ + --resource-id "${RESOURCE1_V2_ID}" \ + --resource-name "${RESOURCE1_NAME}" \ + --resource-type "${RESOURCE1_RESOURCE_TYPE}" \ + --resource-file <(echo "${RESOURCE1_V2_DATA}") \ + "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + + +########## Creating Resource 2 ########## + +RESOURCE2_ID=$(uuidgen) +RESOURCE2_DATA=$(echo '{ "content": "resource 2" }'| base64 -w 0); +RESOURCE2_NAME="Resource 2" +RESOURCE2_RESOURCE_TYPE="CL-Schema" + + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource \ + --collection-id "${ID1}" \ + --resource-id "${RESOURCE2_ID}" \ + --resource-name "${RESOURCE2_NAME}" \ + --resource-type "${RESOURCE2_RESOURCE_TYPE}" \ + --resource-file <(echo "${RESOURCE2_DATA}") \ + "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + + +########## Querying All Resource 1 versions ########## + +EXPECTED_RES1_V2_HEADER='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V2_ID}'", + "name": "'${RESOURCE1_NAME}'", + "media_type": "'${RESOURCE1_MEDIA_TYPE}'", + "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'" +}' + +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded query resource all-resource-versions "${ID1}" "${RESOURCE1_NAME}" ${QUERY_PARAMS}) + +assert_eq "$(echo "$RESULT" | jq -r ".resources | length")" "2" +assert_json_eq "$(echo "$RESULT" | jq -r '.resources[] | select(.id == "'"${RESOURCE1_V1_ID}"'") | '"${DEL_FILTER}"'')" "${EXPECTED_RES1_V1_HEADER}" +assert_json_eq "$(echo "$RESULT" | jq -r '.resources[] | select(.id == "'"${RESOURCE1_V2_ID}"'") | '"${DEL_FILTER}"'')" "${EXPECTED_RES1_V2_HEADER}" diff --git a/tests/e2e-bash/tests/test_query_collection_resources.sh b/tests/e2e-bash/tests/test_query_collection_resources.sh new file mode 100644 index 000000000..c88acb24d --- /dev/null +++ b/tests/e2e-bash/tests/test_query_collection_resources.sh @@ -0,0 +1,166 @@ +#!/bin/bash + +set -euox pipefail + +SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" +# shellcheck source=/dev/null +source "$SCRIPT_DIR/common.sh" + + +# Generate Alice identity key +ALICE_VER_KEY="$(cheqd-noded debug ed25519 random)" +ALICE_VER_PUB_BASE_64=$(echo "${ALICE_VER_KEY}" | jq -r ".pub_key_base_64") +ALICE_VER_PRIV_BASE_64=$(echo "${ALICE_VER_KEY}" | jq -r ".priv_key_base_64") +ALICE_VER_PUB_MULTIBASE_58=$(cheqd-noded debug encoding base64-multibase58 "${ALICE_VER_PUB_BASE_64}") + + +########## Creating DID 1 ########## + +ID1="$(random_string)" +DID1="did:cheqd:testnet:$ID1" +KEY1_ID="${DID1}#key1" + +MSG_CREATE_DID_1='{ + "id": "'${DID1}'", + "verification_method": [{ + "id": "'${KEY1_ID}'", + "type": "Ed25519VerificationKey2020", + "controller": "'${DID1}'", + "public_key_multibase": "'${ALICE_VER_PUB_MULTIBASE_58}'" + }], + "authentication": [ + "'${KEY1_ID}'" + ] +}'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx cheqd create-did "${MSG_CREATE_DID_1}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + + +########## Creating Resource 1 ########## + +RESOURCE1_V1_ID=$(uuidgen) +RESOURCE1_V1_NAME="Resource 1" +RESOURCE1_V1_MEDIA_TYPE="application/json" +RESOURCE1_V1_RESOURCE_TYPE="CL-Schema" +RESOURCE1_V1_DATA='{ "content": "resource 1 v1" }'; + + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource \ + --collection-id "${ID1}" \ + --resource-id "${RESOURCE1_V1_ID}" \ + --resource-name "${RESOURCE1_V1_NAME}" \ + --resource-type "${RESOURCE1_V1_RESOURCE_TYPE}" \ + --resource-file <(echo "${RESOURCE1_V1_DATA}") \ + "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + +########## Querying Resource 1 ########## + +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded query resource resource "${ID1}" ${RESOURCE1_V1_ID} ${QUERY_PARAMS}) + +EXPECTED_RES1_V1_HEADER='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V1_ID}'", + "name": "'${RESOURCE1_V1_NAME}'", + "media_type": "'${RESOURCE1_V1_MEDIA_TYPE}'", + "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'" +}' + +DEL_FILTER='del(.checksum, .created, .next_version_id, .previous_version_id)' +assert_json_eq "$(echo "$RESULT" | jq -r ".resource.header | ${DEL_FILTER}")" "${EXPECTED_RES1_V1_HEADER}" +assert_json_eq "$(echo "$RESULT" | jq -r ".resource.data")" "$(echo "${RESOURCE1_V1_DATA}" | base64 -w 0)" + + +########## Creating Resource 1 v2 ########## + +RESOURCE1_V2_ID=$(uuidgen) +RESOURCE1_V2_DATA='{ "content": "resource 1 v2" }' + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource \ + --collection-id "${ID1}" \ + --resource-id "${RESOURCE1_V2_ID}" \ + --resource-name "${RESOURCE1_V1_NAME}" \ + --resource-type "${RESOURCE1_V1_RESOURCE_TYPE}" \ + --resource-file <(echo "${RESOURCE1_V2_DATA}") \ + "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + + +########## Creating DID 2 ########## + +ID2="$(random_string)" +DID2="did:cheqd:testnet:$ID2" +KEY2_ID="${DID2}#key1" + +MSG_CREATE_DID_2='{ + "id": "'${DID2}'", + "verification_method": [{ + "id": "'${KEY2_ID}'", + "type": "Ed25519VerificationKey2020", + "controller": "'${DID2}'", + "public_key_multibase": "'${ALICE_VER_PUB_MULTIBASE_58}'" + }], + "authentication": [ + "'${KEY2_ID}'" + ] +}'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx cheqd create-did "${MSG_CREATE_DID_2}" "${KEY2_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + + +########## Creating Resource 2 ########## + +RESOURCE2_ID=$(uuidgen) +RESOURCE2_DATA='{ "content": "resource 2" }' +RESOURCE2_NAME="Resource 2" +RESOURCE2_RESOURCE_TYPE="CL-Schema" + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource \ + --collection-id "${ID2}" \ + --resource-id "${RESOURCE2_ID}" \ + --resource-name "${RESOURCE2_NAME}" \ + --resource-type "${RESOURCE2_RESOURCE_TYPE}" \ + --resource-file <(echo "${RESOURCE2_DATA}") \ + "${KEY2_ID}" "${ALICE_VER_PRIV_BASE_64}" \ + --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) + +assert_tx_successful "$RESULT" + + +########## Querying All Resource 1 versions ########## + +EXPECTED_RES1_V2_HEADER='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V2_ID}'", + "name": "'${RESOURCE1_V1_NAME}'", + "media_type": "'${RESOURCE1_V1_MEDIA_TYPE}'", + "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'" +}' + +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded query resource collection-resources "${ID1}" ${QUERY_PARAMS}) + +assert_eq "$(echo "$RESULT" | jq -r ".resources | length")" "2" +assert_json_eq "$(echo "$RESULT" | jq -r '.resources[] | select(.id == "'"${RESOURCE1_V1_ID}"'") | '"${DEL_FILTER}"'')" "${EXPECTED_RES1_V1_HEADER}" +assert_json_eq "$(echo "$RESULT" | jq -r '.resources[] | select(.id == "'"${RESOURCE1_V2_ID}"'") | '"${DEL_FILTER}"'')" "${EXPECTED_RES1_V2_HEADER}" diff --git a/tests/e2e-pytest/test_identity.py b/tests/e2e-pytest/test_identity.py index cddbd458e..f0e8ef4c9 100644 --- a/tests/e2e-pytest/test_identity.py +++ b/tests/e2e-pytest/test_identity.py @@ -5,7 +5,7 @@ from helpers import run, LOCAL_SENDER_ADDRESS, LOCAL_RECEIVER_ADDRESS, LOCAL_NET_DESTINATION, GAS_PRICE, YES_FLAG, \ KEYRING_BACKEND_TEST, get_gas_extimation, CODE_0, TEST_NET_GAS_X_GAS_PRICES, generate_ed25519_key, random_string, \ build_create_did_msg, json_loads, build_update_did_msg, CODE_1101, CODE_1203, get_balance, GAS_AMOUNT, CODE_5, \ - CODE_11, generate_public_multibase, generate_did + CODE_11, generate_public_multibase, generate_did, CODE_1100 @pytest.mark.parametrize("magic_number_positive", [1.3, 2, 3, 10]) @@ -229,4 +229,4 @@ def test_did_wrong_verkey_update(): "cheqd-noded tx", "cheqd update-did", f" '{json.dumps(msg_update_did)}' {key_id} {new_priv_key_base_64} --from {LOCAL_SENDER_ADDRESS} {LOCAL_NET_DESTINATION} {TEST_NET_GAS_X_GAS_PRICES} {YES_FLAG} {KEYRING_BACKEND_TEST}", - fr"{CODE_1101}(.*?)\"raw_log\":\"(.*?)signature is required but not found") + fr"{CODE_1100}(.*?)\"raw_log\":\"(.*?)there should be at least one valid signature by") diff --git a/x/cheqd/client/cli/tx.go b/x/cheqd/client/cli/tx.go index b659be114..885ad1ad1 100644 --- a/x/cheqd/client/cli/tx.go +++ b/x/cheqd/client/cli/tx.go @@ -45,10 +45,25 @@ func GetPayloadAndSignInputs(clientCtx client.Context, args []string) (string, [ // Get payload json payloadJson := args[0] + // Get signInputs + signInputs, err := GetSignInputs(clientCtx, args[1:]) + if err != nil { + return "", []SignInput{}, err + } + + return payloadJson, signInputs, nil +} + +func GetSignInputs(clientCtx client.Context, args []string) ([]SignInput, error) { + // Check for args count + if len(args)%2 != 0 { + return []SignInput{}, fmt.Errorf("can't read sign inputs. invalid number of arguments: %d", len(args)) + } + // Get signInputs var signInputs []SignInput - for i := 1; i < len(args); i += 2 { + for i := 0; i < len(args); i += 2 { vmId := args[i] privKey := args[i+1] @@ -59,13 +74,13 @@ func GetPayloadAndSignInputs(clientCtx client.Context, args []string) (string, [ privKey, err = input.GetString("Enter base64 encoded verification key", inBuf) if err != nil { - return "", nil, err + return nil, err } } privKeyBytes, err := base64.StdEncoding.DecodeString(privKey) if err != nil { - return "", nil, fmt.Errorf("unable to decode private key: %s", err.Error()) + return nil, fmt.Errorf("unable to decode private key: %s", err.Error()) } signInput := SignInput{ @@ -76,7 +91,7 @@ func GetPayloadAndSignInputs(clientCtx client.Context, args []string) (string, [ signInputs = append(signInputs, signInput) } - return payloadJson, signInputs, nil + return signInputs, nil } func SignWithSignInputs(signBytes []byte, signInputs []SignInput) []*types.SignInfo { diff --git a/x/cheqd/genesis.go b/x/cheqd/genesis.go index 413028501..50024476a 100644 --- a/x/cheqd/genesis.go +++ b/x/cheqd/genesis.go @@ -12,12 +12,7 @@ import ( // state. func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { for _, elem := range genState.DidList { - did, err := elem.UnpackDataAsDid() - if err != nil { - panic(fmt.Sprintf("Cannot import geneses case: %s", err.Error())) - } - - if err = k.SetDid(&ctx, did, elem.Metadata); err != nil { + if err := k.SetDid(&ctx, elem); err != nil { panic(fmt.Sprintf("Cannot set did case: %s", err.Error())) } } @@ -25,7 +20,7 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) // Set nym count k.SetDidCount(&ctx, uint64(len(genState.DidList))) - k.SetDidNamespace(ctx, genState.DidNamespace) + k.SetDidNamespace(&ctx, genState.DidNamespace) } // ExportGenesis returns the cheqd module's exported genesis. @@ -40,7 +35,7 @@ func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { genesis.DidList = append(genesis.DidList, &elem) } - genesis.DidNamespace = k.GetDidNamespace(ctx) + genesis.DidNamespace = k.GetDidNamespace(&ctx) return genesis } diff --git a/x/cheqd/keeper/keeper_config.go b/x/cheqd/keeper/keeper_config.go index f13db9c99..7e2c80e26 100644 --- a/x/cheqd/keeper/keeper_config.go +++ b/x/cheqd/keeper/keeper_config.go @@ -6,17 +6,17 @@ import ( ) // GetDidNamespace get did namespace -func (k Keeper) GetDidNamespace(ctx sdk.Context) string { +func (k Keeper) GetDidNamespace(ctx *sdk.Context) string { return k.GetFromState(ctx, types.DidNamespaceKey) } // SetDidNamespace set did namespace -func (k Keeper) SetDidNamespace(ctx sdk.Context, namespace string) { +func (k Keeper) SetDidNamespace(ctx *sdk.Context, namespace string) { k.SetToState(ctx, types.DidNamespaceKey, []byte(namespace)) } -// GetDidNamespace - get State value -func (k Keeper) GetFromState(ctx sdk.Context, stateKey string) string { +// GetFromState - get State value +func (k Keeper) GetFromState(ctx *sdk.Context, stateKey string) string { store := ctx.KVStore(k.storeKey) byteKey := types.KeyPrefix(stateKey) bz := store.Get(byteKey) @@ -27,15 +27,15 @@ func (k Keeper) GetFromState(ctx sdk.Context, stateKey string) string { } // SetToState - set State value -func (k Keeper) SetToState(ctx sdk.Context, stateKey string, stateValue []byte) { +func (k Keeper) SetToState(ctx *sdk.Context, stateKey string, stateValue []byte) { store := ctx.KVStore(k.storeKey) - byteKey := types.KeyPrefix(types.DidNamespaceKey) + byteKey := types.KeyPrefix(stateKey) store.Set(byteKey, stateValue) } -// DeteteFromState - remove value from State by key -func (k Keeper) DeteteFromState(ctx sdk.Context, stateKey string) { +// DeleteFromState - remove value from State by key +func (k Keeper) DeleteFromState(ctx *sdk.Context, stateKey string) { store := ctx.KVStore(k.storeKey) - byteKey := types.KeyPrefix(types.DidNamespaceKey) + byteKey := types.KeyPrefix(stateKey) store.Delete(byteKey) } diff --git a/x/cheqd/keeper/keeper_did.go b/x/cheqd/keeper/keeper_did.go index a71ca3d0f..f44448ef5 100644 --- a/x/cheqd/keeper/keeper_did.go +++ b/x/cheqd/keeper/keeper_did.go @@ -38,34 +38,23 @@ func (k Keeper) SetDidCount(ctx *sdk.Context, count uint64) { store.Set(byteKey, bz) } -// AppendDid appends a did in the store with a new id and updates the count -func (k Keeper) AppendDid(ctx *sdk.Context, did *types.Did, metadata *types.Metadata) error { - // Check that did doesn't exist - if k.HasDid(ctx, did.Id) { - return types.ErrDidDocExists.Wrapf(did.Id) - } - - // Create the did - count := k.GetDidCount(ctx) - err := k.SetDid(ctx, did, metadata) +// SetDid set a specific did in the store. Updates DID counter if the DID is new. +func (k Keeper) SetDid(ctx *sdk.Context, stateValue *types.StateValue) error { + // Unpack + did, err := stateValue.UnpackDataAsDid() if err != nil { return err } - // Update did count - k.SetDidCount(ctx, count+1) - return nil -} - -// SetDid set a specific did in the store -func (k Keeper) SetDid(ctx *sdk.Context, did *types.Did, metadata *types.Metadata) error { - stateValue, err := types.NewStateValue(did, metadata) - if err != nil { - return err + // Update counter + if !k.HasDid(ctx, did.Id) { + count := k.GetDidCount(ctx) + k.SetDidCount(ctx, count+1) } + // Create the did store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidKey)) - b := k.cdc.MustMarshal(&stateValue) + b := k.cdc.MustMarshal(stateValue) store.Set(GetDidIDBytes(did.Id), b) return nil } @@ -99,6 +88,7 @@ func GetDidIDBytes(id string) []byte { } // GetAllDid returns all did +// Loads all DIDs in memory. Use only for genesis export. func (k Keeper) GetAllDid(ctx *sdk.Context) (list []types.StateValue) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidKey)) iterator := sdk.KVStorePrefixIterator(store, []byte{}) diff --git a/x/cheqd/keeper/msg_server.go b/x/cheqd/keeper/msg_server.go index 56f00e4b0..ee41b5468 100644 --- a/x/cheqd/keeper/msg_server.go +++ b/x/cheqd/keeper/msg_server.go @@ -105,3 +105,52 @@ func VerifySignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types. return nil } + +func VerifyAllSignersHaveAllValidSignatures(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, message []byte, signers []string, signatures []*types.SignInfo) error { + for _, signer := range signers { + signatures := types.FindSignInfosBySigner(signatures, signer) + + if len(signatures) == 0 { + return types.ErrSignatureNotFound.Wrapf("signer: %s", signer) + } + + for _, signature := range signatures { + err := VerifySignature(k, ctx, inMemoryDIDs, message, signature) + if err != nil { + return err + } + } + } + + return nil +} + +// VerifyAllSignersHaveAtLeastOneValidSignature verifies that all signers have at least one valid signature. +// Omit DIDtoBeUpdated and updatedDID if not updating a DID. Otherwise those values will be used to better format error messages. +func VerifyAllSignersHaveAtLeastOneValidSignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, + message []byte, signers []string, signatures []*types.SignInfo, DIDToBeUpdated string, updatedDID string, +) error { + for _, signer := range signers { + signaturesBySigner := types.FindSignInfosBySigner(signatures, signer) + signerForErrorMessage := GetSignerIdForErrorMessage(signer, DIDToBeUpdated, updatedDID) + + if len(signaturesBySigner) == 0 { + return types.ErrSignatureNotFound.Wrapf("there should be at least one signature by %s", signerForErrorMessage) + } + + found := false + for _, signature := range signaturesBySigner { + err := VerifySignature(k, ctx, inMemoryDIDs, message, signature) + if err == nil { + found = true + break + } + } + + if !found { + return types.ErrInvalidSignature.Wrapf("there should be at least one valid signature by %s", signerForErrorMessage) + } + } + + return nil +} diff --git a/x/cheqd/keeper/msg_server_create_did.go b/x/cheqd/keeper/msg_server_create_did.go index e2ecc76fd..2ba9df228 100644 --- a/x/cheqd/keeper/msg_server_create_did.go +++ b/x/cheqd/keeper/msg_server_create_did.go @@ -17,7 +17,7 @@ func (k msgServer) CreateDid(goCtx context.Context, msg *types.MsgCreateDid) (*t } // Validate namespaces - namespace := k.GetDidNamespace(ctx) + namespace := k.GetDidNamespace(&ctx) err := msg.Validate([]string{namespace}) if err != nil { return nil, types.ErrNamespaceValidation.Wrap(err.Error()) @@ -45,21 +45,18 @@ func (k msgServer) CreateDid(goCtx context.Context, msg *types.MsgCreateDid) (*t // Verify signatures signers := GetSignerDIDsForDIDCreation(did) - for _, signer := range signers { - signature, found := types.FindSignInfoBySigner(msg.Signatures, signer) - - if !found { - return nil, types.ErrSignatureNotFound.Wrapf("signer: %s", signer) - } + err = VerifyAllSignersHaveAllValidSignatures(&k.Keeper, &ctx, inMemoryDids, msg.Payload.GetSignBytes(), signers, msg.Signatures) + if err != nil { + return nil, err + } - err := VerifySignature(&k.Keeper, &ctx, inMemoryDids, msg.Payload.GetSignBytes(), signature) - if err != nil { - return nil, err - } + // Build state value + value, err := types.NewStateValue(&did, &metadata) + if err != nil { + return nil, err } - // Apply changes - err = k.AppendDid(&ctx, &did, &metadata) + err = k.SetDid(&ctx, &value) if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } diff --git a/x/cheqd/keeper/msg_server_update_did.go b/x/cheqd/keeper/msg_server_update_did.go index 4bc22e264..d19e6a66f 100644 --- a/x/cheqd/keeper/msg_server_update_did.go +++ b/x/cheqd/keeper/msg_server_update_did.go @@ -19,7 +19,7 @@ func (k msgServer) UpdateDid(goCtx context.Context, msg *types.MsgUpdateDid) (*t } // Validate namespaces - namespace := k.GetDidNamespace(ctx) + namespace := k.GetDidNamespace(&ctx) err := msg.Validate([]string{namespace}) if err != nil { return nil, types.ErrNamespaceValidation.Wrap(err.Error()) @@ -71,33 +71,26 @@ func (k msgServer) UpdateDid(goCtx context.Context, msg *types.MsgUpdateDid) (*t // Verify signatures // Duplicate signatures that reference the old version, make them reference a new (in memory) version + // We can't use VerifySignatures because we can't uniquely identify a verification method corresponding to a given signInfo. + // In other words if a signature belongs to the did being updated, there is no way to know which did version it belongs to: old or new. + // To eliminate this problem we have to add pubkey to the signInfo in future. signers := GetSignerDIDsForDIDUpdate(*existingDid, updatedDid) extendedSignatures := DuplicateSignatures(msg.Signatures, existingDid.Id, updatedDid.Id) - for _, signer := range signers { - signaturesBySigner := types.FindSignInfosBySigner(extendedSignatures, signer) - signerForErrorMessage := GetSignerIdForErrorMessage(signer, existingDid.Id, updatedDid.Id) - - if len(signaturesBySigner) == 0 { - return nil, types.ErrSignatureNotFound.Wrapf("there should be at least one signature by %s", signerForErrorMessage) - } + err = VerifyAllSignersHaveAtLeastOneValidSignature(&k.Keeper, &ctx, inMemoryDids, signBytes, signers, extendedSignatures, existingDid.Id, updatedDid.Id) + if err != nil { + return nil, err + } - found := false - for _, signature := range signaturesBySigner { - err := VerifySignature(&k.Keeper, &ctx, inMemoryDids, signBytes, signature) - if err == nil { - found = true - break - } - } + // Return original id + updatedDid.ReplaceIds(updatedDid.Id, existingDid.Id) - if !found { - return nil, types.ErrSignatureNotFound.Wrapf("there should be at least one valid signature by %s", signerForErrorMessage) - } + // Modify state + updatedStateValue, err = types.NewStateValue(&updatedDid, &updatedMetadata) + if err != nil { + return nil, err } - // Apply changes: return original id and modify state - updatedDid.ReplaceIds(updatedDid.Id, existingDid.Id) - err = k.SetDid(&ctx, &updatedDid, &updatedMetadata) + err = k.SetDid(&ctx, &updatedStateValue) if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } diff --git a/x/cheqd/module.go b/x/cheqd/module.go index 9c59efdaa..e905ac7ae 100644 --- a/x/cheqd/module.go +++ b/x/cheqd/module.go @@ -33,7 +33,7 @@ var ( // AppModuleBasic // ---------------------------------------------------------------------------- -// AppModuleBasic implements the AppModuleBasic interface for the capability module. +// AppModuleBasic implements the AppModuleBasic interface for the cheqd module. type AppModuleBasic struct { cdc codec.Codec } @@ -42,7 +42,7 @@ func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { return AppModuleBasic{cdc: cdc} } -// Name returns the capability module's name. +// Name returns the cheqd module's name. func (AppModuleBasic) Name() string { return types.ModuleName } @@ -60,12 +60,12 @@ func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { types.RegisterInterfaces(reg) } -// DefaultGenesis returns the capability module's default genesis state. +// DefaultGenesis returns the cheqd module's default genesis state. func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesis()) } -// ValidateGenesis performs genesis state validation for the capability module. +// ValidateGenesis performs genesis state validation for the cheqd module. func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var genState types.GenesisState if err := cdc.UnmarshalJSON(bz, &genState); err != nil { @@ -74,7 +74,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod return genState.Validate() } -// RegisterRESTRoutes registers the capability module's REST service handlers. +// RegisterRESTRoutes registers the cheqd module's REST service handlers. func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { // rest.RegisterRoutes(clientCtx, rtr) } @@ -87,12 +87,12 @@ func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *r } } -// GetTxCmd returns the capability module's root tx command. +// GetTxCmd returns the cheqd module's root tx command. func (a AppModuleBasic) GetTxCmd() *cobra.Command { return cli.GetTxCmd() } -// GetQueryCmd returns the capability module's root query command. +// GetQueryCmd returns the cheqd module's root query command. func (AppModuleBasic) GetQueryCmd() *cobra.Command { return cli.GetQueryCmd() } @@ -101,7 +101,7 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { // AppModule // ---------------------------------------------------------------------------- -// AppModule implements the AppModule interface for the capability module. +// AppModule implements the AppModule interface for the cheqd module. type AppModule struct { AppModuleBasic @@ -123,20 +123,20 @@ func (am AppModule) ConsensusVersion() uint64 { return 3 } -// Name returns the capability module's name. +// Name returns the cheqd module's name. func (am AppModule) Name() string { return am.AppModuleBasic.Name() } -// Route returns the capability module's message routing key. +// Route returns the cheqd module's message routing key. func (am AppModule) Route() sdk.Route { return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper)) } -// QuerierRoute returns the capability module's query routing key. +// QuerierRoute returns the cheqd module's query routing key. func (AppModule) QuerierRoute() string { return types.QuerierRoute } -// LegacyQuerierHandler returns the capability module's Querier. +// LegacyQuerierHandler returns the cheqd module's Querier. func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } @@ -147,10 +147,10 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterQueryServer(cfg.QueryServer(), am.keeper) } -// RegisterInvariants registers the capability module's invariants. +// RegisterInvariants registers the cheqd module's invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// InitGenesis performs the capability module's genesis initialization It returns +// InitGenesis performs the cheqd module's genesis initialization It returns // no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { var genState types.GenesisState @@ -162,16 +162,16 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.Ra return []abci.ValidatorUpdate{} } -// ExportGenesis returns the capability module's exported genesis state as raw JSON bytes. +// ExportGenesis returns the cheqd module's exported genesis state as raw JSON bytes. func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { genState := ExportGenesis(ctx, am.keeper) return cdc.MustMarshalJSON(genState) } -// BeginBlock executes all ABCI BeginBlock logic respective to the capability module. +// BeginBlock executes all ABCI BeginBlock logic respective to the cheqd module. func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// EndBlock executes all ABCI EndBlock logic respective to the capability module. It +// EndBlock executes all ABCI EndBlock logic respective to the cheqd module. It // returns no validator updates. func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} diff --git a/x/cheqd/tests/constants.go b/x/cheqd/tests/constants.go index a1d4cc243..47d292149 100644 --- a/x/cheqd/tests/constants.go +++ b/x/cheqd/tests/constants.go @@ -1,9 +1,9 @@ package tests const ( - AliceDID = "did:cheqd:test:aaaaaaaaaaaaaaaa" - BobDID = "did:cheqd:test:bbbbbbbbbbbbbbbb" - CharlieDID = "did:cheqd:test:cccccccccccccccc" + AliceDID = "did:cheqd:test:aaaaaaaaaaaaaaaa" // 16 chars base58 + BobDID = "did:cheqd:test:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" // 32 chars base58 + CharlieDID = "did:cheqd:test:babbba14-f294-458a-9b9c-474d188680fd" // UUID ImposterDID = "did:cheqd:test:nananananananana" NotFounDID = "did:cheqd:test:nfdnfdnfdnfdnfdd" AliceKey1 = AliceDID + "#key-1" diff --git a/x/cheqd/tests/create_did_test.go b/x/cheqd/tests/create_did_test.go index c9415fc99..32b510d17 100644 --- a/x/cheqd/tests/create_did_test.go +++ b/x/cheqd/tests/create_did_test.go @@ -144,11 +144,11 @@ func TestCreateDID(t *testing.T) { valid: true, name: "Valid: Full message works", keys: map[string]KeyPair{ - "did:cheqd:test:1111111111111111#key-1": GenerateKeyPair(), - "did:cheqd:test:1111111111111111#key-2": GenerateKeyPair(), - "did:cheqd:test:1111111111111111#key-3": GenerateKeyPair(), - "did:cheqd:test:1111111111111111#key-4": GenerateKeyPair(), - "did:cheqd:test:1111111111111111#key-5": GenerateKeyPair(), + "did:cheqd:test:yyyyyyyyyyyyyyyy#key-1": GenerateKeyPair(), + "did:cheqd:test:yyyyyyyyyyyyyyyy#key-2": GenerateKeyPair(), + "did:cheqd:test:yyyyyyyyyyyyyyyy#key-3": GenerateKeyPair(), + "did:cheqd:test:yyyyyyyyyyyyyyyy#key-4": GenerateKeyPair(), + "did:cheqd:test:yyyyyyyyyyyyyyyy#key-5": GenerateKeyPair(), AliceKey1: keys[AliceKey1], BobKey1: keys[BobKey1], BobKey2: keys[BobKey2], @@ -158,8 +158,8 @@ func TestCreateDID(t *testing.T) { CharlieKey3: keys[CharlieKey3], }, signers: []string{ - "did:cheqd:test:1111111111111111#key-1", - "did:cheqd:test:1111111111111111#key-5", + "did:cheqd:test:yyyyyyyyyyyyyyyy#key-1", + "did:cheqd:test:yyyyyyyyyyyyyyyy#key-5", AliceKey1, BobKey1, BobKey2, @@ -169,49 +169,49 @@ func TestCreateDID(t *testing.T) { CharlieKey3, }, msg: &types.MsgCreateDidPayload{ - Id: "did:cheqd:test:1111111111111111", + Id: "did:cheqd:test:yyyyyyyyyyyyyyyy", Authentication: []string{ - "did:cheqd:test:1111111111111111#key-1", - "did:cheqd:test:1111111111111111#key-5", + "did:cheqd:test:yyyyyyyyyyyyyyyy#key-1", + "did:cheqd:test:yyyyyyyyyyyyyyyy#key-5", }, Context: []string{"abc", "de"}, - CapabilityInvocation: []string{"did:cheqd:test:1111111111111111#key-2"}, - CapabilityDelegation: []string{"did:cheqd:test:1111111111111111#key-3"}, - KeyAgreement: []string{"did:cheqd:test:1111111111111111#key-4"}, + CapabilityInvocation: []string{"did:cheqd:test:yyyyyyyyyyyyyyyy#key-2"}, + CapabilityDelegation: []string{"did:cheqd:test:yyyyyyyyyyyyyyyy#key-3"}, + KeyAgreement: []string{"did:cheqd:test:yyyyyyyyyyyyyyyy#key-4"}, AlsoKnownAs: []string{"SomeUri"}, Service: []*types.Service{ { - Id: "did:cheqd:test:1111111111111111#service-1", + Id: "did:cheqd:test:yyyyyyyyyyyyyyyy#service-1", Type: "DIDCommMessaging", ServiceEndpoint: "ServiceEndpoint", }, }, - Controller: []string{"did:cheqd:test:1111111111111111", AliceDID, BobDID, CharlieDID}, + Controller: []string{"did:cheqd:test:yyyyyyyyyyyyyyyy", AliceDID, BobDID, CharlieDID}, VerificationMethod: []*types.VerificationMethod{ { - Id: "did:cheqd:test:1111111111111111#key-1", + Id: "did:cheqd:test:yyyyyyyyyyyyyyyy#key-1", Type: Ed25519VerificationKey2020, - Controller: "did:cheqd:test:1111111111111111", + Controller: "did:cheqd:test:yyyyyyyyyyyyyyyy", }, { - Id: "did:cheqd:test:1111111111111111#key-2", + Id: "did:cheqd:test:yyyyyyyyyyyyyyyy#key-2", Type: Ed25519VerificationKey2020, - Controller: "did:cheqd:test:1111111111111111", + Controller: "did:cheqd:test:yyyyyyyyyyyyyyyy", }, { - Id: "did:cheqd:test:1111111111111111#key-3", + Id: "did:cheqd:test:yyyyyyyyyyyyyyyy#key-3", Type: Ed25519VerificationKey2020, - Controller: "did:cheqd:test:1111111111111111", + Controller: "did:cheqd:test:yyyyyyyyyyyyyyyy", }, { - Id: "did:cheqd:test:1111111111111111#key-4", + Id: "did:cheqd:test:yyyyyyyyyyyyyyyy#key-4", Type: "Ed25519VerificationKey2020", - Controller: "did:cheqd:test:1111111111111111", + Controller: "did:cheqd:test:yyyyyyyyyyyyyyyy", }, { - Id: "did:cheqd:test:1111111111111111#key-5", + Id: "did:cheqd:test:yyyyyyyyyyyyyyyy#key-5", Type: "Ed25519VerificationKey2020", - Controller: "did:cheqd:test:1111111111111111", + Controller: "did:cheqd:test:yyyyyyyyyyyyyyyy", }, }, }, diff --git a/x/cheqd/tests/setup.go b/x/cheqd/tests/setup.go index f15bc96f2..b5fdf30f3 100644 --- a/x/cheqd/tests/setup.go +++ b/x/cheqd/tests/setup.go @@ -78,7 +78,7 @@ func Setup() TestSetup { Handler: handler, } - setup.Keeper.SetDidNamespace(ctx, "test") + setup.Keeper.SetDidNamespace(&ctx, "test") return setup } diff --git a/x/cheqd/tests/update_did_test.go b/x/cheqd/tests/update_did_test.go index b47eb5233..e4371f6c7 100644 --- a/x/cheqd/tests/update_did_test.go +++ b/x/cheqd/tests/update_did_test.go @@ -150,7 +150,7 @@ func TestUpdateDid(t *testing.T) { }, }, }, - errMsg: fmt.Sprintf("there should be at least one valid signature by %s (new version): signature is required but not found", AliceDID), + errMsg: fmt.Sprintf("there should be at least one valid signature by %s (new version): invalid signature detected", AliceDID), }, { valid: false, @@ -166,7 +166,7 @@ func TestUpdateDid(t *testing.T) { }, }, }, - errMsg: fmt.Sprintf("there should be at least one valid signature by %s (old version): signature is required but not found", AliceDID), + errMsg: fmt.Sprintf("there should be at least one valid signature by %s (old version): invalid signature detected", AliceDID), }, { valid: true, @@ -247,7 +247,7 @@ func TestUpdateDid(t *testing.T) { }, }, }, - errMsg: fmt.Sprintf("there should be at least one valid signature by %s (old version): signature is required but not found", AliceDID), + errMsg: fmt.Sprintf("there should be at least one valid signature by %s (old version): invalid signature detected", AliceDID), }, // Controller's tests diff --git a/x/cheqd/types/did_service.go b/x/cheqd/types/did_service.go index 0c9f775b5..9763c0812 100644 --- a/x/cheqd/types/did_service.go +++ b/x/cheqd/types/did_service.go @@ -7,11 +7,6 @@ import ( validation "github.com/go-ozzo/ozzo-validation/v4" ) -var SupportedServiceTypes = []string{ - "LinkedDomains", - "DIDCommMessaging", -} - func NewService(id string, type_ string, serviceEndpoint string) *Service { return &Service{ Id: id, @@ -37,7 +32,7 @@ func GetServiceIds(vms []*Service) []string { func (s Service) Validate(baseDid string, allowedNamespaces []string) error { return validation.ValidateStruct(&s, validation.Field(&s.Id, validation.Required, IsDIDUrl(allowedNamespaces, Empty, Empty, Required), HasPrefix(baseDid)), - validation.Field(&s.Type, validation.Required, validation.In(utils.ToInterfaces(SupportedServiceTypes)...)), + validation.Field(&s.Type, validation.Required, validation.Length(1, 255)), validation.Field(&s.ServiceEndpoint, validation.Required), ) } diff --git a/x/cheqd/types/stateValue.pb.go b/x/cheqd/types/stateValue.pb.go index 0822e6dd8..944ed6284 100644 --- a/x/cheqd/types/stateValue.pb.go +++ b/x/cheqd/types/stateValue.pb.go @@ -77,10 +77,11 @@ func (m *StateValue) GetMetadata() *Metadata { // metadata type Metadata struct { - Created string `protobuf:"bytes,1,opt,name=created,proto3" json:"created,omitempty"` - Updated string `protobuf:"bytes,2,opt,name=updated,proto3" json:"updated,omitempty"` - Deactivated bool `protobuf:"varint,3,opt,name=deactivated,proto3" json:"deactivated,omitempty"` - VersionId string `protobuf:"bytes,4,opt,name=version_id,json=versionId,proto3" json:"version_id,omitempty"` + Created string `protobuf:"bytes,1,opt,name=created,proto3" json:"created,omitempty"` + Updated string `protobuf:"bytes,2,opt,name=updated,proto3" json:"updated,omitempty"` + Deactivated bool `protobuf:"varint,3,opt,name=deactivated,proto3" json:"deactivated,omitempty"` + VersionId string `protobuf:"bytes,4,opt,name=version_id,json=versionId,proto3" json:"version_id,omitempty"` + Resources []string `protobuf:"bytes,5,rep,name=resources,proto3" json:"resources,omitempty"` } func (m *Metadata) Reset() { *m = Metadata{} } @@ -144,6 +145,13 @@ func (m *Metadata) GetVersionId() string { return "" } +func (m *Metadata) GetResources() []string { + if m != nil { + return m.Resources + } + return nil +} + func init() { proto.RegisterType((*StateValue)(nil), "cheqdid.cheqdnode.cheqd.v1.StateValue") proto.RegisterType((*Metadata)(nil), "cheqdid.cheqdnode.cheqd.v1.Metadata") @@ -152,25 +160,27 @@ func init() { func init() { proto.RegisterFile("cheqd/v1/stateValue.proto", fileDescriptor_7d27f952e1e87cef) } var fileDescriptor_7d27f952e1e87cef = []byte{ - // 288 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x90, 0xbf, 0x4e, 0xc3, 0x30, - 0x10, 0xc6, 0xeb, 0x52, 0x41, 0xeb, 0x6e, 0x16, 0x43, 0x5a, 0x09, 0x2b, 0xaa, 0x18, 0xc2, 0x80, - 0xad, 0xc2, 0x0b, 0xf0, 0x67, 0x62, 0x60, 0x09, 0x12, 0x03, 0x0b, 0x72, 0xe2, 0x23, 0x8d, 0xd4, - 0xc6, 0x21, 0x71, 0xa2, 0x66, 0xe2, 0x15, 0x78, 0x2c, 0xc6, 0x8e, 0x8c, 0x28, 0x79, 0x11, 0xd4, - 0x4b, 0x52, 0xb1, 0xb0, 0xd8, 0xbe, 0xef, 0xfb, 0x7e, 0xb6, 0xef, 0xe8, 0x2c, 0x5c, 0xc1, 0xbb, - 0x96, 0xe5, 0x52, 0xe6, 0x56, 0x59, 0x78, 0x56, 0xeb, 0x02, 0x44, 0x9a, 0x19, 0x6b, 0xd8, 0x1c, - 0xad, 0x58, 0x0b, 0xdc, 0x13, 0xa3, 0xa1, 0x3d, 0x89, 0x72, 0x39, 0x9f, 0x45, 0xc6, 0x44, 0x6b, - 0x90, 0x98, 0x0c, 0x8a, 0x37, 0xa9, 0x92, 0xaa, 0xc5, 0x16, 0x5b, 0x4a, 0x9f, 0x0e, 0x57, 0x31, - 0x8f, 0x8e, 0xb4, 0xb2, 0xca, 0x21, 0x2e, 0xf1, 0xa6, 0x57, 0xa7, 0xa2, 0xe5, 0x44, 0xcf, 0x89, - 0xdb, 0xa4, 0xf2, 0x31, 0xc1, 0x6e, 0xe8, 0x78, 0x03, 0x56, 0x61, 0x7a, 0x88, 0xe9, 0x73, 0xf1, - 0xff, 0x0f, 0xc4, 0x63, 0x97, 0xf5, 0x0f, 0xd4, 0xe2, 0x83, 0x8e, 0x7b, 0x95, 0x39, 0xf4, 0x24, - 0xcc, 0x40, 0x59, 0xd0, 0xf8, 0xf4, 0xc4, 0xef, 0xcb, 0xbd, 0x53, 0xa4, 0x1a, 0x9d, 0x61, 0xeb, - 0x74, 0x25, 0x73, 0xe9, 0x54, 0x83, 0x0a, 0x6d, 0x5c, 0xa2, 0x7b, 0xe4, 0x12, 0x6f, 0xec, 0xff, - 0x95, 0xd8, 0x19, 0xa5, 0x25, 0x64, 0x79, 0x6c, 0x92, 0xd7, 0x58, 0x3b, 0x23, 0xc4, 0x27, 0x9d, - 0xf2, 0xa0, 0xef, 0xee, 0xbf, 0x6a, 0x4e, 0x76, 0x35, 0x27, 0x3f, 0x35, 0x27, 0x9f, 0x0d, 0x1f, - 0xec, 0x1a, 0x3e, 0xf8, 0x6e, 0xf8, 0xe0, 0xe5, 0x22, 0x8a, 0xed, 0xaa, 0x08, 0x44, 0x68, 0x36, - 0xb2, 0x9d, 0x38, 0xae, 0x97, 0xfb, 0x9e, 0xe4, 0xb6, 0x93, 0x6c, 0x95, 0x42, 0x1e, 0x1c, 0xe3, - 0x6c, 0xae, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x5f, 0x10, 0xb8, 0x1e, 0x9a, 0x01, 0x00, 0x00, + // 307 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0xbb, 0x4e, 0xfb, 0x30, + 0x14, 0xc6, 0xeb, 0xb6, 0xff, 0x3f, 0xad, 0xbb, 0x59, 0x0c, 0x69, 0x05, 0x56, 0x54, 0x31, 0x94, + 0x01, 0x5b, 0x85, 0x17, 0xe0, 0x32, 0x31, 0xb0, 0x04, 0x89, 0x81, 0x05, 0xb9, 0xf1, 0xa1, 0x8d, + 0xd4, 0xc6, 0x21, 0x71, 0xa2, 0xe6, 0x2d, 0x78, 0x01, 0xde, 0x87, 0xb1, 0x23, 0x23, 0x4a, 0x5e, + 0x04, 0xe5, 0xe4, 0x22, 0x16, 0x16, 0xdb, 0xe7, 0xfb, 0x7d, 0x9f, 0x6f, 0x87, 0x4e, 0xfd, 0x0d, + 0xbc, 0x69, 0x99, 0x2d, 0x65, 0x62, 0x95, 0x85, 0x27, 0xb5, 0x4d, 0x41, 0x44, 0xb1, 0xb1, 0x86, + 0xcd, 0x10, 0x05, 0x5a, 0xe0, 0x1c, 0x1a, 0x0d, 0xf5, 0x4a, 0x64, 0xcb, 0xd9, 0x74, 0x6d, 0xcc, + 0x7a, 0x0b, 0x12, 0x9d, 0xab, 0xf4, 0x55, 0xaa, 0x30, 0xaf, 0x63, 0xf3, 0x3d, 0xa5, 0x8f, 0xdd, + 0x56, 0x6c, 0x41, 0x87, 0x5a, 0x59, 0xe5, 0x10, 0x97, 0x2c, 0x26, 0x97, 0xc7, 0xa2, 0xce, 0x89, + 0x36, 0x27, 0x6e, 0xc2, 0xdc, 0x43, 0x07, 0xbb, 0xa6, 0xa3, 0x1d, 0x58, 0x85, 0xee, 0x3e, 0xba, + 0xcf, 0xc4, 0xdf, 0x37, 0x10, 0x0f, 0x8d, 0xd7, 0xeb, 0x52, 0xf3, 0x0f, 0x42, 0x47, 0xad, 0xcc, + 0x1c, 0x7a, 0xe4, 0xc7, 0xa0, 0x2c, 0x68, 0x3c, 0x7b, 0xec, 0xb5, 0x65, 0x45, 0xd2, 0x48, 0x23, + 0xe9, 0xd7, 0xa4, 0x29, 0x99, 0x4b, 0x27, 0x1a, 0x94, 0x6f, 0x83, 0x0c, 0xe9, 0xc0, 0x25, 0x8b, + 0x91, 0xf7, 0x5b, 0x62, 0xa7, 0x94, 0x66, 0x10, 0x27, 0x81, 0x09, 0x5f, 0x02, 0xed, 0x0c, 0x31, + 0x3e, 0x6e, 0x94, 0x7b, 0xcd, 0x4e, 0xe8, 0x38, 0x86, 0xc4, 0xa4, 0xb1, 0x0f, 0x89, 0xf3, 0xcf, + 0x1d, 0x54, 0xb4, 0x13, 0x6e, 0xef, 0x3e, 0x0b, 0x4e, 0x0e, 0x05, 0x27, 0xdf, 0x05, 0x27, 0xef, + 0x25, 0xef, 0x1d, 0x4a, 0xde, 0xfb, 0x2a, 0x79, 0xef, 0xf9, 0x7c, 0x1d, 0xd8, 0x4d, 0xba, 0x12, + 0xbe, 0xd9, 0xc9, 0xba, 0x21, 0x38, 0x5e, 0x54, 0x4f, 0x96, 0xfb, 0x46, 0xb2, 0x79, 0x04, 0xc9, + 0xea, 0x3f, 0x7e, 0xdd, 0xd5, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xd3, 0x49, 0x91, 0xa9, 0xb9, + 0x01, 0x00, 0x00, } func (m *StateValue) Marshal() (dAtA []byte, err error) { @@ -240,6 +250,15 @@ func (m *Metadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.Resources) > 0 { + for iNdEx := len(m.Resources) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Resources[iNdEx]) + copy(dAtA[i:], m.Resources[iNdEx]) + i = encodeVarintStateValue(dAtA, i, uint64(len(m.Resources[iNdEx]))) + i-- + dAtA[i] = 0x2a + } + } if len(m.VersionId) > 0 { i -= len(m.VersionId) copy(dAtA[i:], m.VersionId) @@ -323,6 +342,12 @@ func (m *Metadata) Size() (n int) { if l > 0 { n += 1 + l + sovStateValue(uint64(l)) } + if len(m.Resources) > 0 { + for _, s := range m.Resources { + l = len(s) + n += 1 + l + sovStateValue(uint64(l)) + } + } return n } @@ -599,6 +624,38 @@ func (m *Metadata) Unmarshal(dAtA []byte) error { } m.VersionId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Resources", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStateValue + } + 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 ErrInvalidLengthStateValue + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthStateValue + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Resources = append(m.Resources, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipStateValue(dAtA[iNdEx:]) diff --git a/x/cheqd/types/validate.go b/x/cheqd/types/validate.go index 68d0410e7..b691d1d92 100644 --- a/x/cheqd/types/validate.go +++ b/x/cheqd/types/validate.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/cheqd/cheqd-node/x/cheqd/utils" "github.com/multiformats/go-multibase" ) @@ -21,6 +23,8 @@ const ( // Custom error rule +var _ validation.Rule = &CustomErrorRule{} + type CustomErrorRule struct { fn func(value interface{}) error } @@ -35,6 +39,17 @@ func (c CustomErrorRule) Validate(value interface{}) error { // Validation helpers +func IsID() *CustomErrorRule { + return NewCustomErrorRule(func(value interface{}) error { + casted, ok := value.(string) + if !ok { + panic("IsID must be only applied on string properties") + } + + return utils.ValidateID(casted) + }) +} + func IsDID(allowedNamespaces []string) *CustomErrorRule { return NewCustomErrorRule(func(value interface{}) error { casted, ok := value.(string) @@ -178,3 +193,14 @@ func IsUniqueStrList() *CustomErrorRule { return nil }) } + +func IsUUID() *CustomErrorRule { + return NewCustomErrorRule(func(value interface{}) error { + casted, ok := value.(string) + if !ok { + panic("IsDID must be only applied on string properties") + } + + return utils.ValidateUUID(casted) + }) +} diff --git a/x/cheqd/utils/did.go b/x/cheqd/utils/did.go index d33528a1c..876581430 100644 --- a/x/cheqd/utils/did.go +++ b/x/cheqd/utils/did.go @@ -70,7 +70,7 @@ func ValidateDID(did string, method string, allowedNamespaces []string) error { } // check unique-id - err = ValidateUniqueId(sUniqueId) + err = ValidateID(sUniqueId) if err != nil { return err } @@ -78,21 +78,24 @@ func ValidateDID(did string, method string, allowedNamespaces []string) error { return err } -func ValidateUniqueId(uniqueId string) error { - // Length should be 16 or 32 symbols - if len(uniqueId) != 16 && len(uniqueId) != 32 { - return fmt.Errorf("unique id length should be 16 or 32 symbols") - } +func IsValidDID(did string, method string, allowedNamespaces []string) bool { + err := ValidateDID(did, method, allowedNamespaces) + return err == nil +} + +func ValidateID(id string) error { + isValidId := len(id) == 16 && IsValidBase58(id) || + len(id) == 32 && IsValidBase58(id) || + IsValidUUID(id) - // Base58 check - if err := ValidateBase58(uniqueId); err != nil { - return fmt.Errorf("unique id must be valid base58 string: %s", err) + if !isValidId { + return errors.New("unique id should be one of: 16 symbols base58 string, 32 symbols base58 string, or UUID") } return nil } -func IsValidDID(did string, method string, allowedNamespaces []string) bool { - err := ValidateDID(did, method, allowedNamespaces) +func IsValidID(id string) bool { + err := ValidateID(id) return err == nil } diff --git a/x/cheqd/utils/did_test.go b/x/cheqd/utils/did_test.go index 9902a9915..39bad227a 100644 --- a/x/cheqd/utils/did_test.go +++ b/x/cheqd/utils/did_test.go @@ -6,6 +6,32 @@ import ( "github.com/stretchr/testify/require" ) +func TestIsId(t *testing.T) { + cases := []struct { + valid bool + id string + }{ + {true, "123456789abcdefg"}, + {true, "123456789abcdefg123456789abcdefg"}, + {true, "3b9b8eec-5b5d-4382-86d8-9185126ff130"}, + {false, "sdf"}, + {false, "sdf:sdf"}, + {false, "12345"}, + } + + for _, tc := range cases { + t.Run(tc.id, func(t *testing.T) { + isDid := IsValidID(tc.id) + + if tc.valid { + require.True(t, isDid) + } else { + require.False(t, isDid) + } + }) + } +} + func TestIsDid(t *testing.T) { cases := []struct { name string diff --git a/x/cheqd/utils/encoding.go b/x/cheqd/utils/encoding.go index 080f883d4..571870026 100644 --- a/x/cheqd/utils/encoding.go +++ b/x/cheqd/utils/encoding.go @@ -28,3 +28,7 @@ func ValidateMultibaseEncoding(data string, expectedEncoding multibase.Encoding) func ValidateBase58(data string) error { return ValidateMultibaseEncoding(string(multibase.Base58BTC)+data, multibase.Base58BTC) } + +func IsValidBase58(data string) bool { + return ValidateBase58(data) == nil +} diff --git a/x/cheqd/utils/uuid.go b/x/cheqd/utils/uuid.go new file mode 100644 index 000000000..be86de9af --- /dev/null +++ b/x/cheqd/utils/uuid.go @@ -0,0 +1,23 @@ +package utils + +import ( + "errors" + "strconv" + + "github.com/google/uuid" +) + +const StandardUuidLength = 36 + +func ValidateUUID(u string) error { + if len(u) != StandardUuidLength { + return errors.New("uuid must be of length " + strconv.Itoa(StandardUuidLength) + " (in form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)") + } + + _, err := uuid.Parse(u) + return err +} + +func IsValidUUID(u string) bool { + return ValidateUUID(u) == nil +} diff --git a/x/cheqd/utils/uuid_test.go b/x/cheqd/utils/uuid_test.go new file mode 100644 index 000000000..0b7ff983f --- /dev/null +++ b/x/cheqd/utils/uuid_test.go @@ -0,0 +1,33 @@ +package utils + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestValidateUUID(t *testing.T) { + cases := []struct { + uuid string + valid bool + }{ + {"42d9c704-ecb0-11ec-8ea0-0242ac120002", true}, + {"not uuid", false}, + {"e1cdbc10-858c-4d7d-8a4b-5d45e90a81b3", true}, + {"{42d9c704-ecb0-11ec-8ea0-0242ac120002}", false}, + {"urn:uuid:42d9c704-ecb0-11ec-8ea0-0242ac120002", false}, + {"42d9c704ecb011ec8ea00242ac120002", false}, + } + + for _, tc := range cases { + t.Run(tc.uuid, func(t *testing.T) { + err_ := ValidateUUID(tc.uuid) + + if tc.valid { + require.NoError(t, err_) + } else { + require.Error(t, err_) + } + }) + } +} diff --git a/x/resource/client/cli/query.go b/x/resource/client/cli/query.go new file mode 100644 index 000000000..16ee30e90 --- /dev/null +++ b/x/resource/client/cli/query.go @@ -0,0 +1,27 @@ +package cli + +import ( + "fmt" + + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/spf13/cobra" +) + +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd() *cobra.Command { + // Group cheqd queries under a subcommand + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand(CmdGetResource(), + CmdGetAllResourceVersions(), + CmdGetCollectionResources()) + + return cmd +} diff --git a/x/resource/client/cli/query_all_resource_versions.go b/x/resource/client/cli/query_all_resource_versions.go new file mode 100644 index 000000000..79c60392c --- /dev/null +++ b/x/resource/client/cli/query_all_resource_versions.go @@ -0,0 +1,42 @@ +package cli + +import ( + "context" + + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" +) + +func CmdGetAllResourceVersions() *cobra.Command { + cmd := &cobra.Command{ + Use: "all-resource-versions [collectionId] [name] [resourceType] [mediaType]", + Short: "Query all resource versions", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + + queryClient := types.NewQueryClient(clientCtx) + + collectionId := args[0] + name := args[1] + + params := &types.QueryGetAllResourceVersionsRequest{ + CollectionId: collectionId, + Name: name, + } + + resp, err := queryClient.AllResourceVersions(context.Background(), params) + if err != nil { + return err + } + + return clientCtx.PrintProto(resp) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/resource/client/cli/query_collection_resources.go b/x/resource/client/cli/query_collection_resources.go new file mode 100644 index 000000000..e10c098c8 --- /dev/null +++ b/x/resource/client/cli/query_collection_resources.go @@ -0,0 +1,40 @@ +package cli + +import ( + "context" + + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" +) + +func CmdGetCollectionResources() *cobra.Command { + cmd := &cobra.Command{ + Use: "collection-resources [collectionId]", + Short: "Query all resource of a specific collection", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + + queryClient := types.NewQueryClient(clientCtx) + + collectionId := args[0] + + params := &types.QueryGetCollectionResourcesRequest{ + CollectionId: collectionId, + } + + resp, err := queryClient.CollectionResources(context.Background(), params) + if err != nil { + return err + } + + return clientCtx.PrintProto(resp) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/resource/client/cli/query_resource.go b/x/resource/client/cli/query_resource.go new file mode 100644 index 000000000..01536df7a --- /dev/null +++ b/x/resource/client/cli/query_resource.go @@ -0,0 +1,42 @@ +package cli + +import ( + "context" + + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" +) + +func CmdGetResource() *cobra.Command { + cmd := &cobra.Command{ + Use: "resource [collectionId] [id]", + Short: "Query a resource", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + + queryClient := types.NewQueryClient(clientCtx) + + collectionId := args[0] + id := args[1] + + params := &types.QueryGetResourceRequest{ + CollectionId: collectionId, + Id: id, + } + + resp, err := queryClient.Resource(context.Background(), params) + if err != nil { + return err + } + + return clientCtx.PrintProto(resp) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/resource/client/cli/tx.go b/x/resource/client/cli/tx.go new file mode 100644 index 000000000..36fdfa128 --- /dev/null +++ b/x/resource/client/cli/tx.go @@ -0,0 +1,30 @@ +package cli + +import ( + "fmt" + + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/spf13/cobra" +) + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("%s transaction subcommands", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand(CmdCreateResource()) + + return cmd +} + +func panicIfErr(err error) { + if err != nil { + panic(err) + } +} diff --git a/x/resource/client/cli/tx_create_resource.go b/x/resource/client/cli/tx_create_resource.go new file mode 100644 index 000000000..470e15fc4 --- /dev/null +++ b/x/resource/client/cli/tx_create_resource.go @@ -0,0 +1,125 @@ +package cli + +import ( + "io/ioutil" + + cheqdcli "github.com/cheqd/cheqd-node/x/cheqd/client/cli" + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/spf13/cobra" +) + +const ( + FlagCollectionId = "collection-id" + FlagResourceId = "resource-id" + FlagResourceName = "resource-name" + FlagResourceType = "resource-type" + FlagResourceFile = "resource-file" +) + +func CmdCreateResource() *cobra.Command { + cmd := &cobra.Command{ + Use: "create-resource --collection-id [collection-id] --resource-id [resource-id] --resource-name [resource-name]--resource-type [resource-type] --resource-file [path/to/resource/file] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", + Short: "Creates a new Resource.", + Long: "Creates a new Resource. " + + "[ver-method-id-N] is the DID fragment that points to the public part of the key in the ledger for the signature N." + + "[priv-key-N] is base Base64 encoded ed25519 private key for signature N." + + "If 'interactive' value is used for a key, the key will be read interactively. " + + "Prefer interactive mode, use inline mode only for tests.", + Args: cobra.MinimumNArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + collectionId, err := cmd.Flags().GetString(FlagCollectionId) + if err != nil { + return err + } + + resourceId, err := cmd.Flags().GetString(FlagResourceId) + if err != nil { + return err + } + + resourceName, err := cmd.Flags().GetString(FlagResourceName) + if err != nil { + return err + } + + resourceType, err := cmd.Flags().GetString(FlagResourceType) + if err != nil { + return err + } + + resourceFile, err := cmd.Flags().GetString(FlagResourceFile) + if err != nil { + return err + } + + data, err := ioutil.ReadFile(resourceFile) + if err != nil { + return err + } + + // Prepare payload + payload := types.MsgCreateResourcePayload{ + CollectionId: collectionId, + Id: resourceId, + Name: resourceName, + ResourceType: resourceType, + Data: data, + } + + // Read signatures + signInputs, err := cheqdcli.GetSignInputs(clientCtx, args) + if err != nil { + return err + } + + // Build identity message + signBytes := payload.GetSignBytes() + identitySignatures := cheqdcli.SignWithSignInputs(signBytes, signInputs) + + msg := types.MsgCreateResource{ + Payload: &payload, + Signatures: identitySignatures, + } + + // Set fee-payer if not set + err = cheqdcli.SetFeePayerFromSigner(&clientCtx) + if err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + cmd.Flags().String(FlagCollectionId, "", "Collection ID (same as unique identifier portion of an existing DID)") + err := cobra.MarkFlagRequired(cmd.Flags(), FlagCollectionId) + panicIfErr(err) + + cmd.Flags().String(FlagResourceId, "", "Resource ID (must be a UUID)") + err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceId) + panicIfErr(err) + + cmd.Flags().String(FlagResourceName, "", "Resource Name (a distinct DID fragment in `service` block, e.g., did:cheqd:mainnet:...#SchemaName where resource name will be 'SchemaName'") + err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceName) + panicIfErr(err) + + cmd.Flags().String(FlagResourceType, "", "Resource Type (same as `type` within a DID Document `service` block)") + err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceType) + panicIfErr(err) + + cmd.Flags().String(FlagResourceFile, "", "Resource File (path to file to be stored as a resource)") + err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceFile) + panicIfErr(err) + + return cmd +} diff --git a/x/resource/genesis.go b/x/resource/genesis.go new file mode 100644 index 000000000..5ea0ed74f --- /dev/null +++ b/x/resource/genesis.go @@ -0,0 +1,33 @@ +package resource + +import ( + "fmt" + + "github.com/cheqd/cheqd-node/x/resource/keeper" + "github.com/cheqd/cheqd-node/x/resource/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// InitGenesis initializes the resource module's state from a provided genesis +// state. +func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { + for _, resource := range genState.ResourceList { + if err := k.SetResource(&ctx, resource); err != nil { + panic(fmt.Sprintf("Cannot set resource case: %s", err.Error())) + } + } +} + +// ExportGenesis returns the cheqd module's exported genesis. +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { + genesis := types.GenesisState{} + + // Get all resource + resourceList := k.GetAllResources(&ctx) + for _, elem := range resourceList { + elem := elem + genesis.ResourceList = append(genesis.ResourceList, &elem) + } + + return &genesis +} diff --git a/x/resource/handler.go b/x/resource/handler.go new file mode 100644 index 000000000..d3d6aa181 --- /dev/null +++ b/x/resource/handler.go @@ -0,0 +1,30 @@ +package resource + +import ( + "fmt" + + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + + "github.com/cheqd/cheqd-node/x/resource/keeper" + "github.com/cheqd/cheqd-node/x/resource/types" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +func NewHandler(k keeper.Keeper, cheqdKeeper cheqdkeeper.Keeper) sdk.Handler { + msgServer := keeper.NewMsgServer(k, cheqdKeeper) + + return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { + ctx = ctx.WithEventManager(sdk.NewEventManager()) + + switch msg := msg.(type) { + case *types.MsgCreateResource: + res, err := msgServer.CreateResource(sdk.WrapSDKContext(ctx), msg) + return sdk.WrapServiceResult(ctx, res, err) + + default: + errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) + return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) + } + } +} diff --git a/x/resource/keeper/keeper.go b/x/resource/keeper/keeper.go new file mode 100644 index 000000000..cba9a9ad6 --- /dev/null +++ b/x/resource/keeper/keeper.go @@ -0,0 +1,27 @@ +package keeper + +import ( + "fmt" + + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type Keeper struct { + cdc codec.BinaryCodec + storeKey sdk.StoreKey +} + +func NewKeeper(cdc codec.BinaryCodec, storeKey sdk.StoreKey) *Keeper { + return &Keeper{ + cdc: cdc, + storeKey: storeKey, + } +} + +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go new file mode 100644 index 000000000..1d957b56d --- /dev/null +++ b/x/resource/keeper/keeper_resource.go @@ -0,0 +1,211 @@ +package keeper + +import ( + "strconv" + + "github.com/cheqd/cheqd-node/x/resource/types" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// GetResourceCount get the total number of resource +func (k Keeper) GetResourceCount(ctx *sdk.Context) uint64 { + store := ctx.KVStore(k.storeKey) + byteKey := types.KeyPrefix(types.ResourceCountKey) + bz := store.Get(byteKey) + + // Count doesn't exist: no element + if bz == nil { + return 0 + } + + // Parse bytes + count, err := strconv.ParseUint(string(bz), 10, 64) + if err != nil { + // Panic because the count should be always formattable to int64 + panic("cannot decode count") + } + + return count +} + +// SetResourceCount set the total number of resource +func (k Keeper) SetResourceCount(ctx *sdk.Context, count uint64) { + store := ctx.KVStore(k.storeKey) + byteKey := types.KeyPrefix(types.ResourceCountKey) + + // Set bytes + bz := []byte(strconv.FormatUint(count, 10)) + store.Set(byteKey, bz) +} + +// SetResource create or update a specific resource in the store +func (k Keeper) SetResource(ctx *sdk.Context, resource *types.Resource) error { + if !k.HasResource(ctx, resource.Header.CollectionId, resource.Header.Id) { + count := k.GetResourceCount(ctx) + k.SetResourceCount(ctx, count+1) + } + + store := ctx.KVStore(k.storeKey) + + // Set header + headerKey := GetResourceHeaderKeyBytes(resource.Header.CollectionId, resource.Header.Id) + headerBytes := k.cdc.MustMarshal(resource.Header) + store.Set(headerKey, headerBytes) + + // Set data + dataKey := GetResourceDataKeyBytes(resource.Header.CollectionId, resource.Header.Id) + store.Set(dataKey, resource.Data) + + return nil +} + +// GetResource returns a resource from its id +func (k Keeper) GetResource(ctx *sdk.Context, collectionId string, id string) (types.Resource, error) { + if !k.HasResource(ctx, collectionId, id) { + return types.Resource{}, sdkerrors.ErrNotFound.Wrap("resource " + collectionId + ":" + id) + } + + store := ctx.KVStore(k.storeKey) + + headerBytes := store.Get(GetResourceHeaderKeyBytes(collectionId, id)) + var header types.ResourceHeader + if err := k.cdc.Unmarshal(headerBytes, &header); err != nil { + return types.Resource{}, sdkerrors.ErrInvalidType.Wrap(err.Error()) + } + + dataBytes := store.Get(GetResourceDataKeyBytes(collectionId, id)) + + return types.Resource{ + Header: &header, + Data: dataBytes, + }, nil +} + +// HasResource checks if the resource exists in the store +func (k Keeper) HasResource(ctx *sdk.Context, collectionId string, id string) bool { + store := ctx.KVStore(k.storeKey) + return store.Has(GetResourceHeaderKeyBytes(collectionId, id)) +} + +func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name string) []*types.ResourceHeader { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, GetResourceHeaderCollectionPrefixBytes(collectionId)) + + defer closeIteratorOrPanic(iterator) + + var result []*types.ResourceHeader + + for ; iterator.Valid(); iterator.Next() { + var val types.ResourceHeader + k.cdc.MustUnmarshal(iterator.Value(), &val) + + if val.Name == name { + result = append(result, &val) + } + } + + return result +} + +func (k Keeper) GetResourceCollection(ctx *sdk.Context, collectionId string) []*types.ResourceHeader { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, GetResourceHeaderCollectionPrefixBytes(collectionId)) + + var resources []*types.ResourceHeader + + defer closeIteratorOrPanic(iterator) + + for ; iterator.Valid(); iterator.Next() { + var val types.ResourceHeader + k.cdc.MustUnmarshal(iterator.Value(), &val) + resources = append(resources, &val) + + } + + return resources +} + +func (k Keeper) GetLastResourceVersionHeader(ctx *sdk.Context, collectionId, name, resourceType, mediaType string) (types.ResourceHeader, bool) { + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), GetResourceHeaderCollectionPrefixBytes(collectionId)) + + defer closeIteratorOrPanic(iterator) + + for ; iterator.Valid(); iterator.Next() { + var val types.ResourceHeader + k.cdc.MustUnmarshal(iterator.Value(), &val) + + if val.Name == name && val.NextVersionId == "" { + return val, true + } + } + + return types.ResourceHeader{}, false +} + +// UpdateResourceHeader update the header of a resource. Returns an error if the resource doesn't exist +func (k Keeper) UpdateResourceHeader(ctx *sdk.Context, header *types.ResourceHeader) error { + if !k.HasResource(ctx, header.CollectionId, header.Id) { + return sdkerrors.ErrNotFound.Wrap("resource " + header.CollectionId + ":" + header.Id) + } + + store := ctx.KVStore(k.storeKey) + + // Set header + headerKey := GetResourceHeaderKeyBytes(header.CollectionId, header.Id) + headerBytes := k.cdc.MustMarshal(header) + store.Set(headerKey, headerBytes) + + return nil +} + +// GetAllResources returns all resources as a list +// Loads everything in memory. Use only for genesis export! +func (k Keeper) GetAllResources(ctx *sdk.Context) (list []types.Resource) { + headerIterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceHeaderKey)) + dataIterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceDataKey)) + + defer closeIteratorOrPanic(headerIterator) + defer closeIteratorOrPanic(dataIterator) + + for headerIterator.Valid() { + if !dataIterator.Valid() { + panic("number of headers and data don't match") + } + + var val types.ResourceHeader + k.cdc.MustUnmarshal(headerIterator.Value(), &val) + + list = append(list, types.Resource{ + Header: &val, + Data: dataIterator.Value(), + }) + + headerIterator.Next() + dataIterator.Next() + } + + return +} + +// GetResourceHeaderKeyBytes returns the byte representation of resource key +func GetResourceHeaderKeyBytes(collectionId string, id string) []byte { + return []byte(types.ResourceHeaderKey + collectionId + ":" + id) +} + +// GetResourceHeaderCollectionPrefixBytes used to iterate over all resource headers in a collection +func GetResourceHeaderCollectionPrefixBytes(collectionId string) []byte { + return []byte(types.ResourceHeaderKey + collectionId + ":") +} + +// GetResourceDataKeyBytes returns the byte representation of resource key +func GetResourceDataKeyBytes(collectionId string, id string) []byte { + return []byte(types.ResourceDataKey + collectionId + ":" + id) +} + +func closeIteratorOrPanic(iterator sdk.Iterator) { + err := iterator.Close() + if err != nil { + panic(err.Error()) + } +} diff --git a/x/resource/keeper/msg_server.go b/x/resource/keeper/msg_server.go new file mode 100644 index 000000000..7a95e5cf7 --- /dev/null +++ b/x/resource/keeper/msg_server.go @@ -0,0 +1,21 @@ +package keeper + +import ( + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + "github.com/cheqd/cheqd-node/x/resource/types" +) + +type msgServer struct { + Keeper + cheqdKeeper cheqdkeeper.Keeper +} + +// NewMsgServer returns an implementation of the MsgServer interface for the provided Keeper. +func NewMsgServer(keeper Keeper, cheqdKeeper cheqdkeeper.Keeper) types.MsgServer { + return &msgServer{ + Keeper: keeper, + cheqdKeeper: cheqdKeeper, + } +} + +var _ types.MsgServer = msgServer{} diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go new file mode 100644 index 000000000..aea4be33c --- /dev/null +++ b/x/resource/keeper/msg_server_create_resource.go @@ -0,0 +1,85 @@ +package keeper + +import ( + "context" + "crypto/sha256" + "time" + + "github.com/cheqd/cheqd-node/x/resource/utils" + + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + cheqdtypes "github.com/cheqd/cheqd-node/x/cheqd/types" + cheqdutils "github.com/cheqd/cheqd-node/x/cheqd/utils" + "github.com/cheqd/cheqd-node/x/resource/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateResource) (*types.MsgCreateResourceResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + // Validate corresponding DIDDoc exists + namespace := k.cheqdKeeper.GetDidNamespace(&ctx) + did := cheqdutils.JoinDID(cheqdtypes.DidMethod, namespace, msg.Payload.CollectionId) + didDocStateValue, err := k.cheqdKeeper.GetDid(&ctx, did) + if err != nil { + return nil, err + } + + // Validate Resource doesn't exist + if k.HasResource(&ctx, msg.Payload.CollectionId, msg.Payload.Id) { + return nil, types.ErrResourceExists.Wrap(msg.Payload.Id) + } + + // Validate signatures + didDoc, err := didDocStateValue.UnpackDataAsDid() + if err != nil { + return nil, err + } + + // We can use the same signers as for DID creation because didDoc stays the same + signers := cheqdkeeper.GetSignerDIDsForDIDCreation(*didDoc) + err = cheqdkeeper.VerifyAllSignersHaveAllValidSignatures(&k.cheqdKeeper, &ctx, map[string]cheqdtypes.StateValue{}, + msg.Payload.GetSignBytes(), signers, msg.Signatures) + if err != nil { + return nil, err + } + + // Build Resource + resource := msg.Payload.ToResource() + + resource.Header.Checksum = sha256.New().Sum(resource.Data) + resource.Header.Created = time.Now().UTC().Format(time.RFC3339) + resource.Header.MediaType = utils.DetectMediaType(resource.Data) + + // Find previous version and upgrade backward and forward version links + previousResourceVersionHeader, found := k.GetLastResourceVersionHeader(&ctx, resource.Header.CollectionId, resource.Header.Name, resource.Header.ResourceType, resource.Header.MediaType) + if found { + // Set links + previousResourceVersionHeader.NextVersionId = resource.Header.Id + resource.Header.PreviousVersionId = previousResourceVersionHeader.Id + + // Update previous version + err := k.UpdateResourceHeader(&ctx, &previousResourceVersionHeader) + if err != nil { + return nil, err + } + } + + // Append backlink to didDoc + didDocStateValue.Metadata.Resources = append(didDocStateValue.Metadata.Resources, resource.Header.Id) + err = k.cheqdKeeper.SetDid(&ctx, &didDocStateValue) + if err != nil { + return nil, types.ErrInternal.Wrapf(err.Error()) + } + + // Persist resource + err = k.SetResource(&ctx, &resource) + if err != nil { + return nil, types.ErrInternal.Wrapf(err.Error()) + } + + // Build and return response + return &types.MsgCreateResourceResponse{ + Resource: &resource, + }, nil +} diff --git a/x/resource/keeper/query.go b/x/resource/keeper/query.go new file mode 100644 index 000000000..bb3ff6131 --- /dev/null +++ b/x/resource/keeper/query.go @@ -0,0 +1,34 @@ +package keeper + +import ( + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + abci "github.com/tendermint/tendermint/abci/types" +) + +func NewQuerier(k Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { + var ( + res []byte + err error + ) + + switch path[0] { + case types.QueryGetResource: + return resource(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2]) + case types.QueryGetCollectionResources: + return collectionResources(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1]) + case types.QueryGetAllResourceVersions: + return allResourceVersions(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2]) + + default: + err = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) + } + + return res, err + } +} diff --git a/x/resource/keeper/query_all_resource_versions.go b/x/resource/keeper/query_all_resource_versions.go new file mode 100644 index 000000000..6059feba9 --- /dev/null +++ b/x/resource/keeper/query_all_resource_versions.go @@ -0,0 +1,28 @@ +package keeper + +import ( + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +func allResourceVersions(ctx sdk.Context, keeper Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *codec.LegacyAmino, collectionId, name string) ([]byte, error) { + queryServer := NewQueryServer(keeper, cheqdKeeper) + + resp, err := queryServer.AllResourceVersions(sdk.WrapSDKContext(ctx), &types.QueryGetAllResourceVersionsRequest{ + CollectionId: collectionId, + Name: name, + }) + if err != nil { + return nil, err + } + + bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, resp) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + } + + return bz, nil +} diff --git a/x/resource/keeper/query_collection_resources.go b/x/resource/keeper/query_collection_resources.go new file mode 100644 index 000000000..9da01a2d3 --- /dev/null +++ b/x/resource/keeper/query_collection_resources.go @@ -0,0 +1,27 @@ +package keeper + +import ( + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +func collectionResources(ctx sdk.Context, keeper Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *codec.LegacyAmino, collectionId string) ([]byte, error) { + queryServer := NewQueryServer(keeper, cheqdKeeper) + + resp, err := queryServer.CollectionResources(sdk.WrapSDKContext(ctx), &types.QueryGetCollectionResourcesRequest{ + CollectionId: collectionId, + }) + if err != nil { + return nil, err + } + + bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, resp) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + } + + return bz, nil +} diff --git a/x/resource/keeper/query_resource.go b/x/resource/keeper/query_resource.go new file mode 100644 index 000000000..1d881d984 --- /dev/null +++ b/x/resource/keeper/query_resource.go @@ -0,0 +1,25 @@ +package keeper + +import ( + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +func resource(ctx sdk.Context, keeper Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *codec.LegacyAmino, collectionId, id string) ([]byte, error) { + queryServer := NewQueryServer(keeper, cheqdKeeper) + + resp, err := queryServer.Resource(sdk.WrapSDKContext(ctx), &types.QueryGetResourceRequest{CollectionId: collectionId, Id: id}) + if err != nil { + return nil, err + } + + bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, resp) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + } + + return bz, nil +} diff --git a/x/resource/keeper/query_server.go b/x/resource/keeper/query_server.go new file mode 100644 index 000000000..a701ec50e --- /dev/null +++ b/x/resource/keeper/query_server.go @@ -0,0 +1,21 @@ +package keeper + +import ( + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + "github.com/cheqd/cheqd-node/x/resource/types" +) + +type queryServer struct { + Keeper + cheqdKeeper cheqdkeeper.Keeper +} + +// NewQueryServer returns an implementation of the MsgServer interface for the provided Keeper. +func NewQueryServer(keeper Keeper, cheqdKeeper cheqdkeeper.Keeper) types.QueryServer { + return &queryServer{ + Keeper: keeper, + cheqdKeeper: cheqdKeeper, + } +} + +var _ types.QueryServer = queryServer{} diff --git a/x/resource/keeper/query_server_all_resource_versions.go b/x/resource/keeper/query_server_all_resource_versions.go new file mode 100644 index 000000000..bdc07294b --- /dev/null +++ b/x/resource/keeper/query_server_all_resource_versions.go @@ -0,0 +1,34 @@ +package keeper + +import ( + "context" + + cheqdtypes "github.com/cheqd/cheqd-node/x/cheqd/types" + cheqdutils "github.com/cheqd/cheqd-node/x/cheqd/utils" + "github.com/cheqd/cheqd-node/x/resource/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (m queryServer) AllResourceVersions(c context.Context, req *types.QueryGetAllResourceVersionsRequest) (*types.QueryGetAllResourceVersionsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + ctx := sdk.UnwrapSDKContext(c) + + // Validate corresponding DIDDoc exists + namespace := m.cheqdKeeper.GetDidNamespace(&ctx) + did := cheqdutils.JoinDID(cheqdtypes.DidMethod, namespace, req.CollectionId) + if !m.cheqdKeeper.HasDid(&ctx, did) { + return nil, cheqdtypes.ErrDidDocNotFound.Wrap(did) + } + + // Get all versions + versions := m.GetAllResourceVersions(&ctx, req.CollectionId, req.Name) + + return &types.QueryGetAllResourceVersionsResponse{ + Resources: versions, + }, nil +} diff --git a/x/resource/keeper/query_server_collection_resources.go b/x/resource/keeper/query_server_collection_resources.go new file mode 100644 index 000000000..59eb9d7fe --- /dev/null +++ b/x/resource/keeper/query_server_collection_resources.go @@ -0,0 +1,34 @@ +package keeper + +import ( + "context" + + cheqdtypes "github.com/cheqd/cheqd-node/x/cheqd/types" + cheqdutils "github.com/cheqd/cheqd-node/x/cheqd/utils" + "github.com/cheqd/cheqd-node/x/resource/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (m queryServer) CollectionResources(c context.Context, request *types.QueryGetCollectionResourcesRequest) (*types.QueryGetCollectionResourcesResponse, error) { + if request == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + ctx := sdk.UnwrapSDKContext(c) + + // Validate corresponding DIDDoc exists + namespace := m.cheqdKeeper.GetDidNamespace(&ctx) + did := cheqdutils.JoinDID(cheqdtypes.DidMethod, namespace, request.CollectionId) + if !m.cheqdKeeper.HasDid(&ctx, did) { + return nil, cheqdtypes.ErrDidDocNotFound.Wrap(did) + } + + // Get all resources + resources := m.GetResourceCollection(&ctx, request.CollectionId) + + return &types.QueryGetCollectionResourcesResponse{ + Resources: resources, + }, nil +} diff --git a/x/resource/keeper/query_server_resource.go b/x/resource/keeper/query_server_resource.go new file mode 100644 index 000000000..03125168a --- /dev/null +++ b/x/resource/keeper/query_server_resource.go @@ -0,0 +1,37 @@ +package keeper + +import ( + "context" + + cheqdtypes "github.com/cheqd/cheqd-node/x/cheqd/types" + cheqdutils "github.com/cheqd/cheqd-node/x/cheqd/utils" + sdk "github.com/cosmos/cosmos-sdk/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/cheqd/cheqd-node/x/resource/types" +) + +func (q queryServer) Resource(c context.Context, req *types.QueryGetResourceRequest) (*types.QueryGetResourceResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + ctx := sdk.UnwrapSDKContext(c) + + // Validate corresponding DIDDoc exists + namespace := q.cheqdKeeper.GetDidNamespace(&ctx) + did := cheqdutils.JoinDID(cheqdtypes.DidMethod, namespace, req.CollectionId) + if !q.cheqdKeeper.HasDid(&ctx, did) { + return nil, cheqdtypes.ErrDidDocNotFound.Wrap(did) + } + + resource, err := q.GetResource(&ctx, req.CollectionId, req.Id) + if err != nil { + return nil, err + } + + return &types.QueryGetResourceResponse{ + Resource: &resource, + }, nil +} diff --git a/x/resource/module.go b/x/resource/module.go new file mode 100644 index 000000000..fdf653642 --- /dev/null +++ b/x/resource/module.go @@ -0,0 +1,181 @@ +package resource + +import ( + "context" + "encoding/json" + "fmt" + "log" + + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + + "github.com/cheqd/cheqd-node/x/resource/client/cli" + "github.com/cheqd/cheqd-node/x/resource/types" + + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cheqd/cheqd-node/x/resource/keeper" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// ---------------------------------------------------------------------------- +// AppModuleBasic +// ---------------------------------------------------------------------------- + +// AppModuleBasic implements the AppModuleBasic interface for the resource module. +type AppModuleBasic struct { + cdc codec.Codec +} + +func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { + return AppModuleBasic{cdc: cdc} +} + +// Name returns the resource module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +func (AppModuleBasic) RegisterCodec(cdc *codec.LegacyAmino) { + types.RegisterCodec(cdc) +} + +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterCodec(cdc) +} + +// RegisterInterfaces registers the module's interface types +func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(reg) +} + +// DefaultGenesis returns the resource module's default genesis state. +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesis()) +} + +// ValidateGenesis performs genesis state validation for the resource module. +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var genState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + return genState.Validate() +} + +// RegisterRESTRoutes registers the resource module's REST service handlers. +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { + // rest.RegisterRoutes(clientCtx, rtr) +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) + if err != nil { + log.Fatal(err) + } +} + +// GetTxCmd returns the resource module's root tx command. +func (a AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// GetQueryCmd returns the resource module's root query command. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// ---------------------------------------------------------------------------- +// AppModule +// ---------------------------------------------------------------------------- + +// AppModule implements the AppModule interface for the resource module. +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper + cheqdKeeper cheqdkeeper.Keeper +} + +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, cheqdKeeper cheqdkeeper.Keeper) AppModule { + return AppModule{ + AppModuleBasic: NewAppModuleBasic(cdc), + keeper: keeper, + cheqdKeeper: cheqdKeeper, + } +} + +// ConsensusVersion is a sequence number for state-breaking change of the +// module. It should be incremented on each consensus-breaking change +// introduced by the module. To avoid wrong/empty versions, the initial version +// should be set to 1. +func (am AppModule) ConsensusVersion() uint64 { + return 1 +} + +// Name returns the resource module's name. +func (am AppModule) Name() string { + return am.AppModuleBasic.Name() +} + +// Route returns the resource module's message routing key. +func (am AppModule) Route() sdk.Route { + return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper, am.cheqdKeeper)) +} + +// QuerierRoute returns the resource module's query routing key. +func (AppModule) QuerierRoute() string { return types.QuerierRoute } + +// LegacyQuerierHandler returns the resource module's Querier. +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return keeper.NewQuerier(am.keeper, am.cheqdKeeper, legacyQuerierCdc) +} + +// RegisterServices registers a GRPC query service to respond to the +// module-specific GRPC queries. +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServer(am.keeper, am.cheqdKeeper)) +} + +// RegisterInvariants registers the resource module's invariants. +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs the resource module's genesis initialization It returns +// no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { + var genState types.GenesisState + // Initialize global index to index in genesis state + cdc.MustUnmarshalJSON(gs, &genState) + + InitGenesis(ctx, am.keeper, genState) + + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the resource module's exported genesis state as raw JSON bytes. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + genState := ExportGenesis(ctx, am.keeper) + return cdc.MustMarshalJSON(genState) +} + +// BeginBlock executes all ABCI BeginBlock logic respective to the resource module. +func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} + +// EndBlock executes all ABCI EndBlock logic respective to the resource module. It +// returns no validator updates. +func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} diff --git a/x/resource/tests/constants.go b/x/resource/tests/constants.go new file mode 100644 index 000000000..6f2befe27 --- /dev/null +++ b/x/resource/tests/constants.go @@ -0,0 +1,38 @@ +package tests + +import ( + "crypto/sha256" + + "github.com/cheqd/cheqd-node/x/resource/types" +) + +const ( + CLSchemaType = "CL-Schema" + SchemaData = "{\"attr\":[\"name\",\"age\"]}" + TestResourceName = "Test Resource Name" + JsonResourceType = "application/json" + ResourceId = "988b0ab3-6a39-4598-83ec-b84c6cf8da15" + AnotherResourceId = "71583c78-f16f-11ec-9dd4-cba0f34eb177" + IncorrectResourceId = "1234" + + NotFoundDIDIdentifier = "nfdnfdnfdnfdnfdd" + ExistingDIDIdentifier = "eeeeeeeeeeeeeeee" + ExistingDID = "did:cheqd:test:" + ExistingDIDIdentifier + ExistingDIDKey = ExistingDID + "#key-1" +) + +func ExistingResource() types.Resource { + data := []byte(SchemaData) + checksum := sha256.New().Sum(data) + return types.Resource{ + Header: &types.ResourceHeader{ + CollectionId: ExistingDIDIdentifier, + Id: "a09abea0-22e0-4b35-8f70-9cc3a6d0b5fd", + Name: "Existing Resource Name", + ResourceType: CLSchemaType, + MediaType: JsonResourceType, + Checksum: checksum, + }, + Data: data, + } +} diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go new file mode 100644 index 000000000..ce4b95b9d --- /dev/null +++ b/x/resource/tests/create_resource_test.go @@ -0,0 +1,133 @@ +package tests + +import ( + "crypto/ed25519" + "crypto/sha256" + "fmt" + "testing" + + "github.com/cheqd/cheqd-node/x/cheqd/utils" + + // "crypto/sha256" + + "github.com/cheqd/cheqd-node/x/resource/types" + + "github.com/stretchr/testify/require" +) + +func TestCreateResource(t *testing.T) { + keys := GenerateTestKeys() + cases := []struct { + valid bool + name string + signerKeys map[string]ed25519.PrivateKey + msg *types.MsgCreateResourcePayload + mediaType string + previousVersionId string + errMsg string + }{ + { + valid: true, + name: "Valid: Works", + signerKeys: map[string]ed25519.PrivateKey{ + ExistingDIDKey: keys[ExistingDIDKey].PrivateKey, + }, + msg: &types.MsgCreateResourcePayload{ + CollectionId: ExistingDIDIdentifier, + Id: ResourceId, + Name: "Test Resource Name", + ResourceType: CLSchemaType, + Data: []byte(SchemaData), + }, + mediaType: JsonResourceType, + previousVersionId: "", + }, + { + valid: true, + name: "Valid: Add new resource version", + signerKeys: map[string]ed25519.PrivateKey{ + ExistingDIDKey: keys[ExistingDIDKey].PrivateKey, + }, + msg: &types.MsgCreateResourcePayload{ + CollectionId: ExistingResource().Header.CollectionId, + Id: ResourceId, + Name: ExistingResource().Header.Name, + ResourceType: ExistingResource().Header.ResourceType, + Data: ExistingResource().Data, + }, + mediaType: ExistingResource().Header.MediaType, + previousVersionId: ExistingResource().Header.Id, + }, + { + valid: false, + name: "Not Valid: No signature", + signerKeys: map[string]ed25519.PrivateKey{}, + msg: &types.MsgCreateResourcePayload{ + CollectionId: ExistingDIDIdentifier, + Id: ResourceId, + Name: "Test Resource Name", + ResourceType: CLSchemaType, + Data: []byte(SchemaData), + }, + mediaType: JsonResourceType, + errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), + }, + { + valid: false, + name: "Not Valid: Invalid Resource Id", + signerKeys: map[string]ed25519.PrivateKey{}, + msg: &types.MsgCreateResourcePayload{ + CollectionId: ExistingDIDIdentifier, + Id: IncorrectResourceId, + Name: "Test Resource Name", + ResourceType: CLSchemaType, + Data: []byte(SchemaData), + }, + mediaType: JsonResourceType, + errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), + }, + { + valid: false, + name: "Not Valid: DID Doc is not found", + signerKeys: map[string]ed25519.PrivateKey{}, + msg: &types.MsgCreateResourcePayload{ + CollectionId: NotFoundDIDIdentifier, + Id: IncorrectResourceId, + Name: "Test Resource Name", + ResourceType: CLSchemaType, + Data: []byte(SchemaData), + }, + mediaType: JsonResourceType, + errMsg: fmt.Sprintf("did:cheqd:test:%s: not found", NotFoundDIDIdentifier), + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + msg := tc.msg + resourceSetup := InitEnv(t, keys[ExistingDIDKey].PublicKey, keys[ExistingDIDKey].PrivateKey) + + resource, err := resourceSetup.SendCreateResource(msg, tc.signerKeys) + if tc.valid { + require.Nil(t, err) + + did := utils.JoinDID("cheqd", "test", resource.Header.CollectionId) + didStateValue, err := resourceSetup.Keeper.GetDid(&resourceSetup.Ctx, did) + require.Nil(t, err) + require.Contains(t, didStateValue.Metadata.Resources, resource.Header.Id) + + require.Equal(t, tc.msg.CollectionId, resource.Header.CollectionId) + require.Equal(t, tc.msg.Id, resource.Header.Id) + require.Equal(t, tc.mediaType, resource.Header.MediaType) + require.Equal(t, tc.msg.ResourceType, resource.Header.ResourceType) + require.Equal(t, tc.msg.Data, resource.Data) + require.Equal(t, tc.msg.Name, resource.Header.Name) + require.Equal(t, sha256.New().Sum(resource.Data), resource.Header.Checksum) + require.Equal(t, tc.previousVersionId, resource.Header.PreviousVersionId) + } else { + require.Error(t, err) + require.Equal(t, tc.errMsg, err.Error()) + } + }) + } +} diff --git a/x/resource/tests/query_all_resource_versions_test.go b/x/resource/tests/query_all_resource_versions_test.go new file mode 100644 index 000000000..fd90c72da --- /dev/null +++ b/x/resource/tests/query_all_resource_versions_test.go @@ -0,0 +1,99 @@ +package tests + +import ( + "crypto/ed25519" + "fmt" + "testing" + + cheqdtests "github.com/cheqd/cheqd-node/x/cheqd/tests" + "github.com/cheqd/cheqd-node/x/resource/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" +) + +func SendAnotherResourceVersion(t require.TestingT, resourceSetup TestSetup, keys map[string]cheqdtests.KeyPair) types.Resource { + newResourcePayload := GenerateCreateResourcePayload(ExistingResource()) + newResourcePayload.Id = AnotherResourceId + didKey := map[string]ed25519.PrivateKey{ + ExistingDIDKey: keys[ExistingDIDKey].PrivateKey, + } + newResourcePayload.Name = "AnotherResourceVersion" + createdResource, err := resourceSetup.SendCreateResource(newResourcePayload, didKey) + require.Nil(t, err) + + return *createdResource +} + +func TestQueryGetAllResourceVersions(t *testing.T) { + keys := GenerateTestKeys() + existingResource := ExistingResource() + cases := []struct { + valid bool + name string + msg *types.QueryGetAllResourceVersionsRequest + response *types.QueryGetAllResourceVersionsResponse + errMsg string + }{ + { + valid: true, + name: "Valid: Works", + msg: &types.QueryGetAllResourceVersionsRequest{ + CollectionId: ExistingDIDIdentifier, + Name: existingResource.Header.Name, + }, + response: &types.QueryGetAllResourceVersionsResponse{ + Resources: []*types.ResourceHeader{existingResource.Header}, + }, + errMsg: "", + }, + { + valid: false, + name: "Not Valid: DID Doc is not found", + msg: &types.QueryGetAllResourceVersionsRequest{ + CollectionId: NotFoundDIDIdentifier, + Name: existingResource.Header.Name, + }, + response: nil, + errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + msg := tc.msg + resourceSetup := InitEnv(t, keys[ExistingDIDKey].PublicKey, keys[ExistingDIDKey].PrivateKey) + + newResourcePayload := GenerateCreateResourcePayload(ExistingResource()) + newResourcePayload.Id = ResourceId + didKey := map[string]ed25519.PrivateKey{ + ExistingDIDKey: keys[ExistingDIDKey].PrivateKey, + } + // Resource with the same version but another Id + createdResource, err := resourceSetup.SendCreateResource(newResourcePayload, didKey) + require.Nil(t, err) + + // Send another Resource but with another Name (should affect the version choosing) + SendAnotherResourceVersion(t, resourceSetup, keys) + + queryResponse, err := resourceSetup.QueryServer.AllResourceVersions(sdk.WrapSDKContext(resourceSetup.Ctx), msg) + + if tc.valid { + resources := queryResponse.Resources + existingResource.Header.NextVersionId = createdResource.Header.Id + expectedResources := map[string]types.Resource{ + existingResource.Header.Id: existingResource, + createdResource.Header.Id: *createdResource, + } + require.Nil(t, err) + require.Equal(t, len(expectedResources), len(resources)) + for _, r := range resources { + r.Created = expectedResources[r.Id].Header.Created + require.Equal(t, r, expectedResources[r.Id].Header) + } + } else { + require.Error(t, err) + require.Equal(t, tc.errMsg, err.Error()) + } + }) + } +} diff --git a/x/resource/tests/query_collection_resources_test.go b/x/resource/tests/query_collection_resources_test.go new file mode 100644 index 000000000..a8f643f0c --- /dev/null +++ b/x/resource/tests/query_collection_resources_test.go @@ -0,0 +1,66 @@ +package tests + +import ( + "fmt" + "testing" + + "github.com/cheqd/cheqd-node/x/resource/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" +) + +func TestQueryGetCollectionResources(t *testing.T) { + keys := GenerateTestKeys() + existingResource := ExistingResource() + cases := []struct { + valid bool + name string + msg *types.QueryGetCollectionResourcesRequest + response *types.QueryGetCollectionResourcesResponse + errMsg string + }{ + { + valid: true, + name: "Valid: Works", + msg: &types.QueryGetCollectionResourcesRequest{ + CollectionId: ExistingDIDIdentifier, + }, + response: &types.QueryGetCollectionResourcesResponse{ + Resources: []*types.ResourceHeader{existingResource.Header}, + }, + errMsg: "", + }, + { + valid: false, + name: "Not Valid: DID Doc is not found", + msg: &types.QueryGetCollectionResourcesRequest{ + CollectionId: NotFoundDIDIdentifier, + }, + response: nil, + errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + msg := tc.msg + resourceSetup := InitEnv(t, keys[ExistingDIDKey].PublicKey, keys[ExistingDIDKey].PrivateKey) + + queryResponse, err := resourceSetup.QueryServer.CollectionResources(sdk.WrapSDKContext(resourceSetup.Ctx), msg) + + if tc.valid { + resources := queryResponse.Resources + expectedResources := tc.response.Resources + require.Nil(t, err) + require.Equal(t, len(expectedResources), len(resources)) + for i, r := range resources { + r.Created = expectedResources[i].Created + require.Equal(t, expectedResources[i], r) + } + } else { + require.Error(t, err) + require.Equal(t, tc.errMsg, err.Error()) + } + }) + } +} diff --git a/x/resource/tests/query_resource_test.go b/x/resource/tests/query_resource_test.go new file mode 100644 index 000000000..1cfd044f4 --- /dev/null +++ b/x/resource/tests/query_resource_test.go @@ -0,0 +1,84 @@ +package tests + +import ( + + // "crypto/sha256" + "crypto/sha256" + "fmt" + "testing" + + "github.com/cheqd/cheqd-node/x/resource/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" +) + +func TestQueryGetResource(t *testing.T) { + keys := GenerateTestKeys() + existingResource := ExistingResource() + cases := []struct { + valid bool + name string + msg *types.QueryGetResourceRequest + response *types.QueryGetResourceResponse + errMsg string + }{ + { + valid: true, + name: "Valid: Works", + msg: &types.QueryGetResourceRequest{ + CollectionId: ExistingDIDIdentifier, + Id: existingResource.Header.Id, + }, + response: &types.QueryGetResourceResponse{ + Resource: &existingResource, + }, + errMsg: "", + }, + { + valid: false, + name: "Not Valid: Resource is not found", + msg: &types.QueryGetResourceRequest{ + CollectionId: ExistingDIDIdentifier, + Id: ResourceId, + }, + response: nil, + errMsg: fmt.Sprintf("resource %s:%s: not found", ExistingDIDIdentifier, ResourceId), + }, + { + valid: false, + name: "Not Valid: DID Doc is not found", + msg: &types.QueryGetResourceRequest{ + CollectionId: NotFoundDIDIdentifier, + Id: existingResource.Header.Id, + }, + response: nil, + errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + msg := tc.msg + resourceSetup := InitEnv(t, keys[ExistingDIDKey].PublicKey, keys[ExistingDIDKey].PrivateKey) + + queryResponse, err := resourceSetup.QueryServer.Resource(sdk.WrapSDKContext(resourceSetup.Ctx), msg) + + if tc.valid { + resource := queryResponse.Resource + require.Nil(t, err) + require.Equal(t, tc.response.Resource.Header.CollectionId, resource.Header.CollectionId) + require.Equal(t, tc.response.Resource.Header.Id, resource.Header.Id) + require.Equal(t, tc.response.Resource.Header.MediaType, resource.Header.MediaType) + require.Equal(t, tc.response.Resource.Header.ResourceType, resource.Header.ResourceType) + require.Equal(t, tc.response.Resource.Data, resource.Data) + require.Equal(t, tc.response.Resource.Header.Name, resource.Header.Name) + require.Equal(t, sha256.New().Sum(tc.response.Resource.Data), resource.Header.Checksum) + require.Equal(t, tc.response.Resource.Header.PreviousVersionId, resource.Header.PreviousVersionId) + require.Equal(t, tc.response.Resource.Header.NextVersionId, resource.Header.NextVersionId) + } else { + require.Error(t, err) + require.Equal(t, tc.errMsg, err.Error()) + } + }) + } +} diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go new file mode 100644 index 000000000..1709e37f2 --- /dev/null +++ b/x/resource/tests/setup.go @@ -0,0 +1,148 @@ +package tests + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "testing" + "time" + + "github.com/cheqd/cheqd-node/x/cheqd" + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + + cheqdtests "github.com/cheqd/cheqd-node/x/cheqd/tests" + cheqdtypes "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/resource" + "github.com/cheqd/cheqd-node/x/resource/types" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + "github.com/tendermint/tendermint/libs/log" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + dbm "github.com/tendermint/tm-db" + + "github.com/cheqd/cheqd-node/x/resource/keeper" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type TestSetup struct { + cheqdtests.TestSetup + + ResourceKeeper keeper.Keeper + ResourceHandler sdk.Handler + QueryServer types.QueryServer +} + +func Setup() TestSetup { + // Init Codec + ir := codectypes.NewInterfaceRegistry() + types.RegisterInterfaces(ir) + cheqdtypes.RegisterInterfaces(ir) + cdc := codec.NewProtoCodec(ir) + + // Init KVSore + db := dbm.NewMemDB() + + dbStore := store.NewCommitMultiStore(db) + + cheqdStoreKey := sdk.NewKVStoreKey(cheqdtypes.StoreKey) + resourceStoreKey := sdk.NewKVStoreKey(types.StoreKey) + + dbStore.MountStoreWithDB(cheqdStoreKey, sdk.StoreTypeIAVL, nil) + dbStore.MountStoreWithDB(resourceStoreKey, sdk.StoreTypeIAVL, nil) + + _ = dbStore.LoadLatestVersion() + + // Init Keepers + cheqdKeeper := cheqdkeeper.NewKeeper(cdc, cheqdStoreKey) + resourceKeeper := keeper.NewKeeper(cdc, resourceStoreKey) + queryServer := keeper.NewQueryServer(*resourceKeeper, *cheqdKeeper) + + // Create Tx + txBytes := make([]byte, 28) + _, _ = rand.Read(txBytes) + + // Create context + blockTime, _ := time.Parse(time.RFC3339, "2021-01-01T00:00:00.000Z") + ctx := sdk.NewContext(dbStore, + tmproto.Header{ChainID: "test", Time: blockTime}, + false, log.NewNopLogger()).WithTxBytes(txBytes) + + cheqdHandler := cheqd.NewHandler(*cheqdKeeper) + resourceHandler := resource.NewHandler(*resourceKeeper, *cheqdKeeper) + + setup := TestSetup{ + TestSetup: cheqdtests.TestSetup{ + Cdc: cdc, + Ctx: ctx, + Keeper: *cheqdKeeper, + Handler: cheqdHandler, + }, + ResourceKeeper: *resourceKeeper, + ResourceHandler: resourceHandler, + QueryServer: queryServer, + } + + setup.Keeper.SetDidNamespace(&ctx, "test") + return setup +} + +func GenerateCreateResourcePayload(resource types.Resource) *types.MsgCreateResourcePayload { + return &types.MsgCreateResourcePayload{ + CollectionId: resource.Header.CollectionId, + Id: resource.Header.Id, + Name: resource.Header.Name, + ResourceType: resource.Header.ResourceType, + Data: resource.Data, + } +} + +func (s *TestSetup) WrapCreateRequest(payload *types.MsgCreateResourcePayload, keys map[string]ed25519.PrivateKey) *types.MsgCreateResource { + var signatures []*cheqdtypes.SignInfo + signingInput := payload.GetSignBytes() + + for privKeyId, privKey := range keys { + signature := base64.StdEncoding.EncodeToString(ed25519.Sign(privKey, signingInput)) + signatures = append(signatures, &cheqdtypes.SignInfo{ + VerificationMethodId: privKeyId, + Signature: signature, + }) + } + + return &types.MsgCreateResource{ + Payload: payload, + Signatures: signatures, + } +} + +func (s *TestSetup) SendCreateResource(msg *types.MsgCreateResourcePayload, keys map[string]ed25519.PrivateKey) (*types.Resource, error) { + _, err := s.ResourceHandler(s.Ctx, s.WrapCreateRequest(msg, keys)) + if err != nil { + return nil, err + } + + created, _ := s.ResourceKeeper.GetResource(&s.Ctx, msg.CollectionId, msg.Id) + return &created, nil +} + +func InitEnv(t *testing.T, publicKey ed25519.PublicKey, privateKey ed25519.PrivateKey) TestSetup { + resourceSetup := Setup() + + didDoc := resourceSetup.CreateDid(publicKey, ExistingDID) + _, err := resourceSetup.SendCreateDid(didDoc, map[string]ed25519.PrivateKey{ExistingDIDKey: privateKey}) + require.NoError(t, err) + + resourcePayload := GenerateCreateResourcePayload(ExistingResource()) + _, err = resourceSetup.SendCreateResource(resourcePayload, map[string]ed25519.PrivateKey{ExistingDIDKey: privateKey}) + require.NoError(t, err) + + return resourceSetup +} + +func GenerateTestKeys() map[string]cheqdtests.KeyPair { + return map[string]cheqdtests.KeyPair{ + ExistingDIDKey: cheqdtests.GenerateKeyPair(), + } +} diff --git a/x/resource/types/codec.go b/x/resource/types/codec.go new file mode 100644 index 000000000..766f753cd --- /dev/null +++ b/x/resource/types/codec.go @@ -0,0 +1,27 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" +) + +func RegisterCodec(cdc *codec.LegacyAmino) { + // Sdk messages + cdc.RegisterConcrete(&MsgCreateResource{}, "resource/CreateResource", nil) +} + +func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + // Sdk messages + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgCreateResource{}, + ) + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} + +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) diff --git a/x/resource/types/error.go b/x/resource/types/error.go new file mode 100644 index 000000000..f8786359d --- /dev/null +++ b/x/resource/types/error.go @@ -0,0 +1,15 @@ +package types + +// DONTCOVER + +import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// x/resource module sentinel errors +var ( + ErrBadRequest = sdkerrors.Register(ModuleName, 2000, "bad request") + ErrResourceExists = sdkerrors.Register(ModuleName, 2200, "Resoure exists") + ErrBasicValidation = sdkerrors.Register(ModuleName, 2205, "basic validation failed") + ErrInternal = sdkerrors.Register(ModuleName, 2500, "internal error") +) diff --git a/x/resource/types/genesis.go b/x/resource/types/genesis.go new file mode 100644 index 000000000..b877466fd --- /dev/null +++ b/x/resource/types/genesis.go @@ -0,0 +1,30 @@ +package types + +import ( + "fmt" +) + +// DefaultGenesis returns the default Capability genesis state +func DefaultGenesis() *GenesisState { + return &GenesisState{ + ResourceList: []*Resource{}, + } +} + +// Validate performs basic genesis state validation returning an error upon any +// failure. +func (gs GenesisState) Validate() error { + resourceIdMap := make(map[string]bool) + + for _, resource := range gs.ResourceList { + collectionResourceId := resource.Header.CollectionId + ":" + resource.Header.Id + + if _, ok := resourceIdMap[collectionResourceId]; ok { + return fmt.Errorf("duplicated id for resource within the same collection: %s", collectionResourceId) + } + + resourceIdMap[collectionResourceId] = true + } + + return nil +} diff --git a/x/resource/types/genesis.pb.go b/x/resource/types/genesis.pb.go new file mode 100644 index 000000000..8cc9fb6a2 --- /dev/null +++ b/x/resource/types/genesis.pb.go @@ -0,0 +1,328 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: resource/v1/genesis.proto + +package types + +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 + +// GenesisState defines the cheqd module's genesis state. +type GenesisState struct { + ResourceList []*Resource `protobuf:"bytes,1,rep,name=resourceList,proto3" json:"resourceList,omitempty"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_3e70cb64fdfc8574, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetResourceList() []*Resource { + if m != nil { + return m.ResourceList + } + return nil +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "cheqdid.cheqdnode.resource.v1.GenesisState") +} + +func init() { proto.RegisterFile("resource/v1/genesis.proto", fileDescriptor_3e70cb64fdfc8574) } + +var fileDescriptor_3e70cb64fdfc8574 = []byte{ + // 184 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2c, 0x4a, 0x2d, 0xce, + 0x2f, 0x2d, 0x4a, 0x4e, 0xd5, 0x2f, 0x33, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, + 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x4d, 0xce, 0x48, 0x2d, 0x4c, 0xc9, 0x4c, 0xd1, 0x03, + 0xd3, 0x79, 0xf9, 0x29, 0xa9, 0x7a, 0x30, 0xc5, 0x7a, 0x65, 0x86, 0x52, 0x52, 0xc8, 0x3a, 0xe1, + 0x12, 0x60, 0xad, 0x4a, 0xd1, 0x5c, 0x3c, 0xee, 0x10, 0xb3, 0x82, 0x4b, 0x12, 0x4b, 0x52, 0x85, + 0xbc, 0xb9, 0x78, 0x60, 0x2a, 0x7c, 0x32, 0x8b, 0x4b, 0x24, 0x18, 0x15, 0x98, 0x35, 0xb8, 0x8d, + 0xd4, 0xf5, 0xf0, 0xda, 0xa0, 0x17, 0x04, 0x65, 0x07, 0xa1, 0x68, 0x76, 0x72, 0x3b, 0xf1, 0x48, + 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, + 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0x9d, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, + 0xe4, 0xfc, 0x5c, 0x7d, 0xb0, 0x91, 0x10, 0x52, 0x17, 0x64, 0xb2, 0x7e, 0x05, 0xdc, 0x91, 0xfa, + 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0xb7, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, + 0x63, 0x1d, 0x9b, 0xdf, 0x03, 0x01, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ResourceList) > 0 { + for iNdEx := len(m.ResourceList) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ResourceList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.ResourceList) > 0 { + for _, e := range m.ResourceList { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceList", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceList = append(m.ResourceList, &Resource{}) + if err := m.ResourceList[len(m.ResourceList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/resource/types/keys.go b/x/resource/types/keys.go new file mode 100644 index 000000000..10cc9300a --- /dev/null +++ b/x/resource/types/keys.go @@ -0,0 +1,25 @@ +package types + +const ( + // ModuleName defines the module name + ModuleName = "resource" + + // StoreKey defines the primary module store key + StoreKey = ModuleName + + // RouterKey is the message route for slashing + RouterKey = ModuleName + + // QuerierRoute defines the module's query routing key + QuerierRoute = ModuleName +) + +func KeyPrefix(p string) []byte { + return []byte(p) +} + +const ( + ResourceHeaderKey = "resource-header:" + ResourceDataKey = "resource-data:" + ResourceCountKey = "resource-count:" +) diff --git a/x/resource/types/query.go b/x/resource/types/query.go new file mode 100644 index 000000000..6321965eb --- /dev/null +++ b/x/resource/types/query.go @@ -0,0 +1,7 @@ +package types + +const ( + QueryGetResource = "get-resource" + QueryGetCollectionResources = "get-collection-resources" + QueryGetAllResourceVersions = "get-all-resource-versions" +) diff --git a/x/resource/types/query.pb.go b/x/resource/types/query.pb.go new file mode 100644 index 000000000..a54d8ac82 --- /dev/null +++ b/x/resource/types/query.pb.go @@ -0,0 +1,1476 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: resource/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 + +type QueryGetResourceRequest struct { + CollectionId string `protobuf:"bytes,1,opt,name=collection_id,json=collectionId,proto3" json:"collection_id,omitempty"` + Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` +} + +func (m *QueryGetResourceRequest) Reset() { *m = QueryGetResourceRequest{} } +func (m *QueryGetResourceRequest) String() string { return proto.CompactTextString(m) } +func (*QueryGetResourceRequest) ProtoMessage() {} +func (*QueryGetResourceRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_10aac3b48339734d, []int{0} +} +func (m *QueryGetResourceRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetResourceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetResourceRequest.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 *QueryGetResourceRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetResourceRequest.Merge(m, src) +} +func (m *QueryGetResourceRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryGetResourceRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetResourceRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetResourceRequest proto.InternalMessageInfo + +func (m *QueryGetResourceRequest) GetCollectionId() string { + if m != nil { + return m.CollectionId + } + return "" +} + +func (m *QueryGetResourceRequest) GetId() string { + if m != nil { + return m.Id + } + return "" +} + +type QueryGetResourceResponse struct { + Resource *Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` +} + +func (m *QueryGetResourceResponse) Reset() { *m = QueryGetResourceResponse{} } +func (m *QueryGetResourceResponse) String() string { return proto.CompactTextString(m) } +func (*QueryGetResourceResponse) ProtoMessage() {} +func (*QueryGetResourceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_10aac3b48339734d, []int{1} +} +func (m *QueryGetResourceResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetResourceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetResourceResponse.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 *QueryGetResourceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetResourceResponse.Merge(m, src) +} +func (m *QueryGetResourceResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryGetResourceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetResourceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetResourceResponse proto.InternalMessageInfo + +func (m *QueryGetResourceResponse) GetResource() *Resource { + if m != nil { + return m.Resource + } + return nil +} + +type QueryGetCollectionResourcesRequest struct { + CollectionId string `protobuf:"bytes,1,opt,name=collection_id,json=collectionId,proto3" json:"collection_id,omitempty"` +} + +func (m *QueryGetCollectionResourcesRequest) Reset() { *m = QueryGetCollectionResourcesRequest{} } +func (m *QueryGetCollectionResourcesRequest) String() string { return proto.CompactTextString(m) } +func (*QueryGetCollectionResourcesRequest) ProtoMessage() {} +func (*QueryGetCollectionResourcesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_10aac3b48339734d, []int{2} +} +func (m *QueryGetCollectionResourcesRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetCollectionResourcesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetCollectionResourcesRequest.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 *QueryGetCollectionResourcesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetCollectionResourcesRequest.Merge(m, src) +} +func (m *QueryGetCollectionResourcesRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryGetCollectionResourcesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetCollectionResourcesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetCollectionResourcesRequest proto.InternalMessageInfo + +func (m *QueryGetCollectionResourcesRequest) GetCollectionId() string { + if m != nil { + return m.CollectionId + } + return "" +} + +type QueryGetCollectionResourcesResponse struct { + Resources []*ResourceHeader `protobuf:"bytes,1,rep,name=resources,proto3" json:"resources,omitempty"` +} + +func (m *QueryGetCollectionResourcesResponse) Reset() { *m = QueryGetCollectionResourcesResponse{} } +func (m *QueryGetCollectionResourcesResponse) String() string { return proto.CompactTextString(m) } +func (*QueryGetCollectionResourcesResponse) ProtoMessage() {} +func (*QueryGetCollectionResourcesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_10aac3b48339734d, []int{3} +} +func (m *QueryGetCollectionResourcesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetCollectionResourcesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetCollectionResourcesResponse.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 *QueryGetCollectionResourcesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetCollectionResourcesResponse.Merge(m, src) +} +func (m *QueryGetCollectionResourcesResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryGetCollectionResourcesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetCollectionResourcesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetCollectionResourcesResponse proto.InternalMessageInfo + +func (m *QueryGetCollectionResourcesResponse) GetResources() []*ResourceHeader { + if m != nil { + return m.Resources + } + return nil +} + +type QueryGetAllResourceVersionsRequest struct { + CollectionId string `protobuf:"bytes,1,opt,name=collection_id,json=collectionId,proto3" json:"collection_id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` +} + +func (m *QueryGetAllResourceVersionsRequest) Reset() { *m = QueryGetAllResourceVersionsRequest{} } +func (m *QueryGetAllResourceVersionsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryGetAllResourceVersionsRequest) ProtoMessage() {} +func (*QueryGetAllResourceVersionsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_10aac3b48339734d, []int{4} +} +func (m *QueryGetAllResourceVersionsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetAllResourceVersionsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetAllResourceVersionsRequest.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 *QueryGetAllResourceVersionsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetAllResourceVersionsRequest.Merge(m, src) +} +func (m *QueryGetAllResourceVersionsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryGetAllResourceVersionsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetAllResourceVersionsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetAllResourceVersionsRequest proto.InternalMessageInfo + +func (m *QueryGetAllResourceVersionsRequest) GetCollectionId() string { + if m != nil { + return m.CollectionId + } + return "" +} + +func (m *QueryGetAllResourceVersionsRequest) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +type QueryGetAllResourceVersionsResponse struct { + Resources []*ResourceHeader `protobuf:"bytes,1,rep,name=resources,proto3" json:"resources,omitempty"` +} + +func (m *QueryGetAllResourceVersionsResponse) Reset() { *m = QueryGetAllResourceVersionsResponse{} } +func (m *QueryGetAllResourceVersionsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryGetAllResourceVersionsResponse) ProtoMessage() {} +func (*QueryGetAllResourceVersionsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_10aac3b48339734d, []int{5} +} +func (m *QueryGetAllResourceVersionsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetAllResourceVersionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetAllResourceVersionsResponse.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 *QueryGetAllResourceVersionsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetAllResourceVersionsResponse.Merge(m, src) +} +func (m *QueryGetAllResourceVersionsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryGetAllResourceVersionsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetAllResourceVersionsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetAllResourceVersionsResponse proto.InternalMessageInfo + +func (m *QueryGetAllResourceVersionsResponse) GetResources() []*ResourceHeader { + if m != nil { + return m.Resources + } + return nil +} + +func init() { + proto.RegisterType((*QueryGetResourceRequest)(nil), "cheqdid.cheqdnode.resource.v1.QueryGetResourceRequest") + proto.RegisterType((*QueryGetResourceResponse)(nil), "cheqdid.cheqdnode.resource.v1.QueryGetResourceResponse") + proto.RegisterType((*QueryGetCollectionResourcesRequest)(nil), "cheqdid.cheqdnode.resource.v1.QueryGetCollectionResourcesRequest") + proto.RegisterType((*QueryGetCollectionResourcesResponse)(nil), "cheqdid.cheqdnode.resource.v1.QueryGetCollectionResourcesResponse") + proto.RegisterType((*QueryGetAllResourceVersionsRequest)(nil), "cheqdid.cheqdnode.resource.v1.QueryGetAllResourceVersionsRequest") + proto.RegisterType((*QueryGetAllResourceVersionsResponse)(nil), "cheqdid.cheqdnode.resource.v1.QueryGetAllResourceVersionsResponse") +} + +func init() { proto.RegisterFile("resource/v1/query.proto", fileDescriptor_10aac3b48339734d) } + +var fileDescriptor_10aac3b48339734d = []byte{ + // 484 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x94, 0x41, 0x6b, 0x13, 0x41, + 0x14, 0xc7, 0x33, 0xb1, 0x4a, 0x3b, 0x55, 0x0f, 0xd3, 0x43, 0xc3, 0xa2, 0x4b, 0x99, 0x1e, 0xec, + 0xc1, 0xce, 0x34, 0x11, 0x5a, 0x10, 0x2f, 0x4d, 0x41, 0x2d, 0x82, 0x60, 0x0e, 0x1e, 0x04, 0x29, + 0xdb, 0x9d, 0x67, 0x3a, 0xb0, 0xdd, 0x49, 0x66, 0x66, 0x83, 0x25, 0xe4, 0xe2, 0x27, 0x10, 0xfc, + 0x2a, 0x7e, 0x08, 0x8f, 0x05, 0x3d, 0x78, 0x2c, 0x89, 0x1f, 0xc2, 0xa3, 0xec, 0x64, 0x77, 0x53, + 0x31, 0x89, 0xbb, 0x88, 0x97, 0x64, 0xd9, 0x79, 0xef, 0xff, 0xfe, 0xbf, 0xb7, 0xff, 0x5d, 0xbc, + 0xa9, 0xc1, 0xa8, 0x44, 0x87, 0xc0, 0x07, 0x4d, 0xde, 0x4f, 0x40, 0x5f, 0xb0, 0x9e, 0x56, 0x56, + 0x91, 0xfb, 0xe1, 0x19, 0xf4, 0x85, 0x14, 0xcc, 0xfd, 0xc7, 0x4a, 0x00, 0xcb, 0x4b, 0xd9, 0xa0, + 0xe9, 0xdd, 0xeb, 0x2a, 0xd5, 0x8d, 0x80, 0x07, 0x3d, 0xc9, 0x83, 0x38, 0x56, 0x36, 0xb0, 0x52, + 0xc5, 0x66, 0xda, 0xec, 0x79, 0xd7, 0x55, 0x8b, 0x36, 0x77, 0x46, 0x5f, 0xe2, 0xcd, 0x57, 0xe9, + 0x9c, 0x67, 0x60, 0x3b, 0xd9, 0x49, 0x07, 0xfa, 0x09, 0x18, 0x4b, 0xb6, 0xf1, 0x9d, 0x50, 0x45, + 0x11, 0x84, 0xa9, 0xd6, 0x89, 0x14, 0x0d, 0xb4, 0x85, 0x76, 0xd6, 0x3a, 0xb7, 0x67, 0x37, 0x8f, + 0x05, 0xb9, 0x8b, 0xeb, 0x52, 0x34, 0xea, 0xee, 0xa4, 0x2e, 0x05, 0x3d, 0xc1, 0x8d, 0x3f, 0xf5, + 0x4c, 0x4f, 0xc5, 0x06, 0xc8, 0x11, 0x5e, 0xcd, 0xa7, 0x3b, 0xad, 0xf5, 0xd6, 0x03, 0xb6, 0x94, + 0x8b, 0x15, 0x12, 0x45, 0x23, 0x3d, 0xc6, 0x34, 0x1f, 0x70, 0x54, 0x18, 0xc9, 0xeb, 0x4c, 0x15, + 0xef, 0x54, 0xe3, 0xed, 0xa5, 0x52, 0x99, 0xed, 0x17, 0x78, 0x2d, 0x9f, 0x6e, 0x1a, 0x68, 0xeb, + 0xc6, 0xce, 0x7a, 0x6b, 0xb7, 0xa4, 0xef, 0xe7, 0x10, 0x08, 0xd0, 0x9d, 0x59, 0x3f, 0x7d, 0x3b, + 0xb3, 0x7f, 0x18, 0x45, 0x79, 0xdd, 0x6b, 0xd0, 0x26, 0x7d, 0x60, 0x95, 0x56, 0x4f, 0xf0, 0x4a, + 0x1c, 0x9c, 0x43, 0xb6, 0x7c, 0x77, 0x7d, 0x1d, 0x69, 0xae, 0xfc, 0x7f, 0x40, 0x6a, 0xfd, 0x5c, + 0xc1, 0x37, 0xdd, 0x50, 0xf2, 0x19, 0xe1, 0xd5, 0xbc, 0x8e, 0xec, 0xff, 0x45, 0x70, 0x41, 0xec, + 0xbc, 0x83, 0xca, 0x7d, 0x53, 0x28, 0x7a, 0xf0, 0xe1, 0xeb, 0x8f, 0x4f, 0xf5, 0x26, 0xe1, 0xbc, + 0xc9, 0xf6, 0xb8, 0x14, 0x10, 0x5b, 0xf9, 0x4e, 0x82, 0x36, 0x7c, 0xf8, 0xdb, 0x32, 0x47, 0xc5, + 0x3b, 0x60, 0xf8, 0x50, 0x8a, 0x11, 0xf9, 0x86, 0xf0, 0xc6, 0x9c, 0x00, 0x90, 0xc3, 0x92, 0x4e, + 0x16, 0xe7, 0xd0, 0x6b, 0xff, 0x8b, 0x44, 0xc6, 0xb5, 0xef, 0xb8, 0xf6, 0x08, 0xab, 0xc0, 0x15, + 0x44, 0x11, 0xb9, 0x42, 0x78, 0x63, 0x4e, 0x08, 0x4a, 0x63, 0x2d, 0xce, 0x67, 0x69, 0xac, 0x25, + 0x19, 0xa4, 0x6d, 0x87, 0xf5, 0x84, 0x3c, 0xae, 0x80, 0x35, 0xc8, 0x44, 0xf8, 0x30, 0x4d, 0xfb, + 0xa8, 0xfd, 0xf4, 0xcb, 0xd8, 0x47, 0x97, 0x63, 0x1f, 0x5d, 0x8d, 0x7d, 0xf4, 0x71, 0xe2, 0xd7, + 0x2e, 0x27, 0x7e, 0xed, 0xfb, 0xc4, 0xaf, 0xbd, 0x79, 0xd8, 0x95, 0xf6, 0x2c, 0x39, 0x65, 0xa1, + 0x3a, 0xe7, 0xce, 0xe3, 0xf4, 0x77, 0x37, 0xb5, 0xca, 0xdf, 0x17, 0x92, 0xdc, 0x5e, 0xf4, 0xc0, + 0x9c, 0xde, 0x72, 0x1f, 0xc3, 0x47, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0xf7, 0x66, 0xec, 0xcb, + 0x80, 0x05, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + Resource(ctx context.Context, in *QueryGetResourceRequest, opts ...grpc.CallOption) (*QueryGetResourceResponse, error) + CollectionResources(ctx context.Context, in *QueryGetCollectionResourcesRequest, opts ...grpc.CallOption) (*QueryGetCollectionResourcesResponse, error) + AllResourceVersions(ctx context.Context, in *QueryGetAllResourceVersionsRequest, opts ...grpc.CallOption) (*QueryGetAllResourceVersionsResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Resource(ctx context.Context, in *QueryGetResourceRequest, opts ...grpc.CallOption) (*QueryGetResourceResponse, error) { + out := new(QueryGetResourceResponse) + err := c.cc.Invoke(ctx, "/cheqdid.cheqdnode.resource.v1.Query/Resource", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) CollectionResources(ctx context.Context, in *QueryGetCollectionResourcesRequest, opts ...grpc.CallOption) (*QueryGetCollectionResourcesResponse, error) { + out := new(QueryGetCollectionResourcesResponse) + err := c.cc.Invoke(ctx, "/cheqdid.cheqdnode.resource.v1.Query/CollectionResources", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) AllResourceVersions(ctx context.Context, in *QueryGetAllResourceVersionsRequest, opts ...grpc.CallOption) (*QueryGetAllResourceVersionsResponse, error) { + out := new(QueryGetAllResourceVersionsResponse) + err := c.cc.Invoke(ctx, "/cheqdid.cheqdnode.resource.v1.Query/AllResourceVersions", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + Resource(context.Context, *QueryGetResourceRequest) (*QueryGetResourceResponse, error) + CollectionResources(context.Context, *QueryGetCollectionResourcesRequest) (*QueryGetCollectionResourcesResponse, error) + AllResourceVersions(context.Context, *QueryGetAllResourceVersionsRequest) (*QueryGetAllResourceVersionsResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Resource(ctx context.Context, req *QueryGetResourceRequest) (*QueryGetResourceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Resource not implemented") +} +func (*UnimplementedQueryServer) CollectionResources(ctx context.Context, req *QueryGetCollectionResourcesRequest) (*QueryGetCollectionResourcesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CollectionResources not implemented") +} +func (*UnimplementedQueryServer) AllResourceVersions(ctx context.Context, req *QueryGetAllResourceVersionsRequest) (*QueryGetAllResourceVersionsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method AllResourceVersions not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Resource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryGetResourceRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Resource(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cheqdid.cheqdnode.resource.v1.Query/Resource", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Resource(ctx, req.(*QueryGetResourceRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_CollectionResources_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryGetCollectionResourcesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).CollectionResources(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cheqdid.cheqdnode.resource.v1.Query/CollectionResources", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).CollectionResources(ctx, req.(*QueryGetCollectionResourcesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_AllResourceVersions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryGetAllResourceVersionsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).AllResourceVersions(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cheqdid.cheqdnode.resource.v1.Query/AllResourceVersions", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).AllResourceVersions(ctx, req.(*QueryGetAllResourceVersionsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cheqdid.cheqdnode.resource.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Resource", + Handler: _Query_Resource_Handler, + }, + { + MethodName: "CollectionResources", + Handler: _Query_CollectionResources_Handler, + }, + { + MethodName: "AllResourceVersions", + Handler: _Query_AllResourceVersions_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "resource/v1/query.proto", +} + +func (m *QueryGetResourceRequest) 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 *QueryGetResourceRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetResourceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Id) > 0 { + i -= len(m.Id) + copy(dAtA[i:], m.Id) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Id))) + i-- + dAtA[i] = 0x12 + } + if len(m.CollectionId) > 0 { + i -= len(m.CollectionId) + copy(dAtA[i:], m.CollectionId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.CollectionId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryGetResourceResponse) 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 *QueryGetResourceResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetResourceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Resource != nil { + { + size, err := m.Resource.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryGetCollectionResourcesRequest) 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 *QueryGetCollectionResourcesRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetCollectionResourcesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.CollectionId) > 0 { + i -= len(m.CollectionId) + copy(dAtA[i:], m.CollectionId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.CollectionId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryGetCollectionResourcesResponse) 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 *QueryGetCollectionResourcesResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetCollectionResourcesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Resources) > 0 { + for iNdEx := len(m.Resources) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Resources[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryGetAllResourceVersionsRequest) 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 *QueryGetAllResourceVersionsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetAllResourceVersionsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0x12 + } + if len(m.CollectionId) > 0 { + i -= len(m.CollectionId) + copy(dAtA[i:], m.CollectionId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.CollectionId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryGetAllResourceVersionsResponse) 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 *QueryGetAllResourceVersionsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetAllResourceVersionsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Resources) > 0 { + for iNdEx := len(m.Resources) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Resources[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func 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 *QueryGetResourceRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.CollectionId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.Id) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryGetResourceResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Resource != nil { + l = m.Resource.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryGetCollectionResourcesRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.CollectionId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryGetCollectionResourcesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Resources) > 0 { + for _, e := range m.Resources { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func (m *QueryGetAllResourceVersionsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.CollectionId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryGetAllResourceVersionsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Resources) > 0 { + for _, e := range m.Resources { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryGetResourceRequest) 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: QueryGetResourceRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetResourceRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CollectionId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CollectionId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Id = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryGetResourceResponse) 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: QueryGetResourceResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetResourceResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Resource == nil { + m.Resource = &Resource{} + } + if err := m.Resource.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryGetCollectionResourcesRequest) 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: QueryGetCollectionResourcesRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetCollectionResourcesRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CollectionId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CollectionId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryGetCollectionResourcesResponse) 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: QueryGetCollectionResourcesResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetCollectionResourcesResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Resources", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Resources = append(m.Resources, &ResourceHeader{}) + if err := m.Resources[len(m.Resources)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryGetAllResourceVersionsRequest) 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: QueryGetAllResourceVersionsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetAllResourceVersionsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CollectionId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CollectionId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryGetAllResourceVersionsResponse) 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: QueryGetAllResourceVersionsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetAllResourceVersionsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Resources", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Resources = append(m.Resources, &ResourceHeader{}) + if err := m.Resources[len(m.Resources)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/resource/types/query.pb.gw.go b/x/resource/types/query.pb.gw.go new file mode 100644 index 000000000..6186e0bda --- /dev/null +++ b/x/resource/types/query.pb.gw.go @@ -0,0 +1,435 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: resource/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_Resource_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetResourceRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["collection_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collection_id") + } + + protoReq.CollectionId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collection_id", err) + } + + val, ok = pathParams["id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") + } + + protoReq.Id, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) + } + + msg, err := client.Resource(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Resource_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetResourceRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["collection_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collection_id") + } + + protoReq.CollectionId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collection_id", err) + } + + val, ok = pathParams["id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") + } + + protoReq.Id, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) + } + + msg, err := server.Resource(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_CollectionResources_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetCollectionResourcesRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["collection_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collection_id") + } + + protoReq.CollectionId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collection_id", err) + } + + msg, err := client.CollectionResources(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_CollectionResources_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetCollectionResourcesRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["collection_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collection_id") + } + + protoReq.CollectionId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collection_id", err) + } + + msg, err := server.CollectionResources(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_AllResourceVersions_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetAllResourceVersionsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["collection_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collection_id") + } + + protoReq.CollectionId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collection_id", err) + } + + val, ok = pathParams["name"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name") + } + + protoReq.Name, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err) + } + + msg, err := client.AllResourceVersions(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_AllResourceVersions_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetAllResourceVersionsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["collection_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collection_id") + } + + protoReq.CollectionId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collection_id", err) + } + + val, ok = pathParams["name"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name") + } + + protoReq.Name, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err) + } + + msg, err := server.AllResourceVersions(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_Resource_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_Resource_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_Resource_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_CollectionResources_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_CollectionResources_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_CollectionResources_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_AllResourceVersions_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_AllResourceVersions_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_AllResourceVersions_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_Resource_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_Resource_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_Resource_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_CollectionResources_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_CollectionResources_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_CollectionResources_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_AllResourceVersions_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_AllResourceVersions_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_AllResourceVersions_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Resource_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"1.0", "identifiers", "collection_id", "resources", "id"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_CollectionResources_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4}, []string{"1.0", "identifiers", "collection_id", "resources", "all"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_AllResourceVersions_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"1.0", "identifiers", "collection_id", "resources", "versions", "name"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_Resource_0 = runtime.ForwardResponseMessage + + forward_Query_CollectionResources_0 = runtime.ForwardResponseMessage + + forward_Query_AllResourceVersions_0 = runtime.ForwardResponseMessage +) diff --git a/x/resource/types/resource.pb.go b/x/resource/types/resource.pb.go new file mode 100644 index 000000000..bfd0792f7 --- /dev/null +++ b/x/resource/types/resource.pb.go @@ -0,0 +1,968 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: resource/v1/resource.proto + +package types + +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 + +type Resource struct { + Header *ResourceHeader `protobuf:"bytes,1,opt,name=header,proto3" json:"header,omitempty"` + Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` +} + +func (m *Resource) Reset() { *m = Resource{} } +func (m *Resource) String() string { return proto.CompactTextString(m) } +func (*Resource) ProtoMessage() {} +func (*Resource) Descriptor() ([]byte, []int) { + return fileDescriptor_cebae6241f1ea243, []int{0} +} +func (m *Resource) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Resource) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Resource.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 *Resource) XXX_Merge(src proto.Message) { + xxx_messageInfo_Resource.Merge(m, src) +} +func (m *Resource) XXX_Size() int { + return m.Size() +} +func (m *Resource) XXX_DiscardUnknown() { + xxx_messageInfo_Resource.DiscardUnknown(m) +} + +var xxx_messageInfo_Resource proto.InternalMessageInfo + +func (m *Resource) GetHeader() *ResourceHeader { + if m != nil { + return m.Header + } + return nil +} + +func (m *Resource) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +type ResourceHeader struct { + CollectionId string `protobuf:"bytes,1,opt,name=collection_id,json=collectionId,proto3" json:"collection_id,omitempty"` + Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` + ResourceType string `protobuf:"bytes,4,opt,name=resource_type,json=resourceType,proto3" json:"resource_type,omitempty"` + MediaType string `protobuf:"bytes,5,opt,name=media_type,json=mediaType,proto3" json:"media_type,omitempty"` + Created string `protobuf:"bytes,6,opt,name=created,proto3" json:"created,omitempty"` + Checksum []byte `protobuf:"bytes,7,opt,name=checksum,proto3" json:"checksum,omitempty"` + PreviousVersionId string `protobuf:"bytes,8,opt,name=previous_version_id,json=previousVersionId,proto3" json:"previous_version_id,omitempty"` + NextVersionId string `protobuf:"bytes,9,opt,name=next_version_id,json=nextVersionId,proto3" json:"next_version_id,omitempty"` +} + +func (m *ResourceHeader) Reset() { *m = ResourceHeader{} } +func (m *ResourceHeader) String() string { return proto.CompactTextString(m) } +func (*ResourceHeader) ProtoMessage() {} +func (*ResourceHeader) Descriptor() ([]byte, []int) { + return fileDescriptor_cebae6241f1ea243, []int{1} +} +func (m *ResourceHeader) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ResourceHeader) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ResourceHeader.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 *ResourceHeader) XXX_Merge(src proto.Message) { + xxx_messageInfo_ResourceHeader.Merge(m, src) +} +func (m *ResourceHeader) XXX_Size() int { + return m.Size() +} +func (m *ResourceHeader) XXX_DiscardUnknown() { + xxx_messageInfo_ResourceHeader.DiscardUnknown(m) +} + +var xxx_messageInfo_ResourceHeader proto.InternalMessageInfo + +func (m *ResourceHeader) GetCollectionId() string { + if m != nil { + return m.CollectionId + } + return "" +} + +func (m *ResourceHeader) GetId() string { + if m != nil { + return m.Id + } + return "" +} + +func (m *ResourceHeader) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *ResourceHeader) GetResourceType() string { + if m != nil { + return m.ResourceType + } + return "" +} + +func (m *ResourceHeader) GetMediaType() string { + if m != nil { + return m.MediaType + } + return "" +} + +func (m *ResourceHeader) GetCreated() string { + if m != nil { + return m.Created + } + return "" +} + +func (m *ResourceHeader) GetChecksum() []byte { + if m != nil { + return m.Checksum + } + return nil +} + +func (m *ResourceHeader) GetPreviousVersionId() string { + if m != nil { + return m.PreviousVersionId + } + return "" +} + +func (m *ResourceHeader) GetNextVersionId() string { + if m != nil { + return m.NextVersionId + } + return "" +} + +func init() { + proto.RegisterType((*Resource)(nil), "cheqdid.cheqdnode.resource.v1.Resource") + proto.RegisterType((*ResourceHeader)(nil), "cheqdid.cheqdnode.resource.v1.ResourceHeader") +} + +func init() { proto.RegisterFile("resource/v1/resource.proto", fileDescriptor_cebae6241f1ea243) } + +var fileDescriptor_cebae6241f1ea243 = []byte{ + // 346 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x52, 0xcf, 0x4e, 0xf2, 0x40, + 0x10, 0xa7, 0xfd, 0xf8, 0x80, 0xae, 0x80, 0x71, 0xbd, 0x34, 0x24, 0x34, 0x04, 0x13, 0xc3, 0x41, + 0xda, 0xa0, 0x6f, 0x60, 0xa2, 0x91, 0x6b, 0x63, 0x3c, 0x78, 0x21, 0x65, 0x77, 0x62, 0x37, 0xd2, + 0x6e, 0xdd, 0x6e, 0x1b, 0x78, 0x0b, 0xdf, 0xc3, 0x17, 0xf1, 0xc8, 0xd1, 0xa3, 0x81, 0x17, 0x31, + 0x9d, 0xd2, 0xaa, 0x17, 0x2f, 0xed, 0xcc, 0xef, 0xdf, 0xee, 0x64, 0x96, 0x0c, 0x14, 0xa4, 0x32, + 0x53, 0x0c, 0xbc, 0x7c, 0xe6, 0x55, 0xb5, 0x9b, 0x28, 0xa9, 0x25, 0x1d, 0xb2, 0x10, 0x5e, 0xb8, + 0xe0, 0x2e, 0xfe, 0x63, 0xc9, 0xc1, 0xad, 0x15, 0xf9, 0x6c, 0x0c, 0xa4, 0xe3, 0x1f, 0x5a, 0x7a, + 0x43, 0x5a, 0x21, 0x04, 0x1c, 0x94, 0x6d, 0x8c, 0x8c, 0xc9, 0xd1, 0xe5, 0xd4, 0xfd, 0xd3, 0xeb, + 0x56, 0xc6, 0x3b, 0x34, 0xf9, 0x07, 0x33, 0xa5, 0xa4, 0xc9, 0x03, 0x1d, 0xd8, 0xe6, 0xc8, 0x98, + 0x74, 0x7d, 0xac, 0xc7, 0x6f, 0x26, 0xe9, 0xff, 0x96, 0xd3, 0x33, 0xd2, 0x63, 0x72, 0xb5, 0x02, + 0xa6, 0x85, 0x8c, 0x17, 0x82, 0xe3, 0xa1, 0x96, 0xdf, 0xfd, 0x06, 0xe7, 0x9c, 0xf6, 0x89, 0x29, + 0x38, 0x26, 0x59, 0xbe, 0x29, 0x78, 0x91, 0x1d, 0x07, 0x11, 0xd8, 0xff, 0x10, 0xc1, 0xba, 0x08, + 0xaa, 0x6e, 0xb5, 0xd0, 0x9b, 0x04, 0xec, 0x66, 0x19, 0x54, 0x81, 0xf7, 0x9b, 0x04, 0xe8, 0x90, + 0x90, 0x08, 0xb8, 0x08, 0x4a, 0xc5, 0x7f, 0x54, 0x58, 0x88, 0x20, 0x6d, 0x93, 0x36, 0x53, 0x10, + 0x68, 0xe0, 0x76, 0x0b, 0xb9, 0xaa, 0xa5, 0x03, 0xd2, 0x61, 0x21, 0xb0, 0xe7, 0x34, 0x8b, 0xec, + 0x36, 0x4e, 0x54, 0xf7, 0xd4, 0x25, 0xa7, 0x89, 0x82, 0x5c, 0xc8, 0x2c, 0x5d, 0xe4, 0xa0, 0xd2, + 0xc3, 0x20, 0x1d, 0x4c, 0x38, 0xa9, 0xa8, 0x87, 0x92, 0x99, 0x73, 0x7a, 0x4e, 0x8e, 0x63, 0x58, + 0xeb, 0x9f, 0x5a, 0x0b, 0xb5, 0xbd, 0x02, 0xae, 0x75, 0xd7, 0xb7, 0xef, 0x3b, 0xc7, 0xd8, 0xee, + 0x1c, 0xe3, 0x73, 0xe7, 0x18, 0xaf, 0x7b, 0xa7, 0xb1, 0xdd, 0x3b, 0x8d, 0x8f, 0xbd, 0xd3, 0x78, + 0xbc, 0x78, 0x12, 0x3a, 0xcc, 0x96, 0x2e, 0x93, 0x91, 0x87, 0x4b, 0x29, 0xbf, 0xd3, 0x62, 0x37, + 0xde, 0xba, 0xde, 0xbd, 0x57, 0x4c, 0x99, 0x2e, 0x5b, 0xf8, 0x04, 0xae, 0xbe, 0x02, 0x00, 0x00, + 0xff, 0xff, 0xb6, 0x9e, 0x0d, 0x64, 0x20, 0x02, 0x00, 0x00, +} + +func (m *Resource) 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 *Resource) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Resource) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintResource(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0x12 + } + if m.Header != nil { + { + size, err := m.Header.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintResource(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ResourceHeader) 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 *ResourceHeader) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResourceHeader) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.NextVersionId) > 0 { + i -= len(m.NextVersionId) + copy(dAtA[i:], m.NextVersionId) + i = encodeVarintResource(dAtA, i, uint64(len(m.NextVersionId))) + i-- + dAtA[i] = 0x4a + } + if len(m.PreviousVersionId) > 0 { + i -= len(m.PreviousVersionId) + copy(dAtA[i:], m.PreviousVersionId) + i = encodeVarintResource(dAtA, i, uint64(len(m.PreviousVersionId))) + i-- + dAtA[i] = 0x42 + } + if len(m.Checksum) > 0 { + i -= len(m.Checksum) + copy(dAtA[i:], m.Checksum) + i = encodeVarintResource(dAtA, i, uint64(len(m.Checksum))) + i-- + dAtA[i] = 0x3a + } + if len(m.Created) > 0 { + i -= len(m.Created) + copy(dAtA[i:], m.Created) + i = encodeVarintResource(dAtA, i, uint64(len(m.Created))) + i-- + dAtA[i] = 0x32 + } + if len(m.MediaType) > 0 { + i -= len(m.MediaType) + copy(dAtA[i:], m.MediaType) + i = encodeVarintResource(dAtA, i, uint64(len(m.MediaType))) + i-- + dAtA[i] = 0x2a + } + if len(m.ResourceType) > 0 { + i -= len(m.ResourceType) + copy(dAtA[i:], m.ResourceType) + i = encodeVarintResource(dAtA, i, uint64(len(m.ResourceType))) + i-- + dAtA[i] = 0x22 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintResource(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0x1a + } + if len(m.Id) > 0 { + i -= len(m.Id) + copy(dAtA[i:], m.Id) + i = encodeVarintResource(dAtA, i, uint64(len(m.Id))) + i-- + dAtA[i] = 0x12 + } + if len(m.CollectionId) > 0 { + i -= len(m.CollectionId) + copy(dAtA[i:], m.CollectionId) + i = encodeVarintResource(dAtA, i, uint64(len(m.CollectionId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintResource(dAtA []byte, offset int, v uint64) int { + offset -= sovResource(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Resource) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Header != nil { + l = m.Header.Size() + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + return n +} + +func (m *ResourceHeader) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.CollectionId) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.Id) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.ResourceType) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.MediaType) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.Created) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.Checksum) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.PreviousVersionId) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.NextVersionId) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + return n +} + +func sovResource(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozResource(x uint64) (n int) { + return sovResource(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Resource) 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 ErrIntOverflowResource + } + 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: Resource: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Resource: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthResource + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Header == nil { + m.Header = &ResourceHeader{} + } + if err := m.Header.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthResource + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipResource(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthResource + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ResourceHeader) 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 ErrIntOverflowResource + } + 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: ResourceHeader: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResourceHeader: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CollectionId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + 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 ErrInvalidLengthResource + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CollectionId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + 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 ErrInvalidLengthResource + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Id = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + 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 ErrInvalidLengthResource + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + 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 ErrInvalidLengthResource + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MediaType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + 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 ErrInvalidLengthResource + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.MediaType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Created", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + 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 ErrInvalidLengthResource + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Created = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Checksum", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthResource + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Checksum = append(m.Checksum[:0], dAtA[iNdEx:postIndex]...) + if m.Checksum == nil { + m.Checksum = []byte{} + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PreviousVersionId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + 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 ErrInvalidLengthResource + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PreviousVersionId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NextVersionId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowResource + } + 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 ErrInvalidLengthResource + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthResource + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.NextVersionId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipResource(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthResource + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipResource(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, ErrIntOverflowResource + } + 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, ErrIntOverflowResource + } + 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, ErrIntOverflowResource + } + 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, ErrInvalidLengthResource + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupResource + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthResource + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthResource = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowResource = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupResource = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/resource/types/tx.pb.go b/x/resource/types/tx.pb.go new file mode 100644 index 000000000..ce64040de --- /dev/null +++ b/x/resource/types/tx.pb.go @@ -0,0 +1,1041 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: resource/v1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + types "github.com/cheqd/cheqd-node/x/cheqd/types" + grpc1 "github.com/gogo/protobuf/grpc" + proto "github.com/gogo/protobuf/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// this line is used by starport scaffolding # proto/tx/message +type MsgCreateResource struct { + Payload *MsgCreateResourcePayload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` + Signatures []*types.SignInfo `protobuf:"bytes,2,rep,name=signatures,proto3" json:"signatures,omitempty"` +} + +func (m *MsgCreateResource) Reset() { *m = MsgCreateResource{} } +func (m *MsgCreateResource) String() string { return proto.CompactTextString(m) } +func (*MsgCreateResource) ProtoMessage() {} +func (*MsgCreateResource) Descriptor() ([]byte, []int) { + return fileDescriptor_f5b76d41c4c62339, []int{0} +} +func (m *MsgCreateResource) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgCreateResource) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgCreateResource.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 *MsgCreateResource) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgCreateResource.Merge(m, src) +} +func (m *MsgCreateResource) XXX_Size() int { + return m.Size() +} +func (m *MsgCreateResource) XXX_DiscardUnknown() { + xxx_messageInfo_MsgCreateResource.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgCreateResource proto.InternalMessageInfo + +func (m *MsgCreateResource) GetPayload() *MsgCreateResourcePayload { + if m != nil { + return m.Payload + } + return nil +} + +func (m *MsgCreateResource) GetSignatures() []*types.SignInfo { + if m != nil { + return m.Signatures + } + return nil +} + +type MsgCreateResourcePayload struct { + CollectionId string `protobuf:"bytes,1,opt,name=collection_id,json=collectionId,proto3" json:"collection_id,omitempty"` + Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` + ResourceType string `protobuf:"bytes,4,opt,name=resource_type,json=resourceType,proto3" json:"resource_type,omitempty"` + Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` +} + +func (m *MsgCreateResourcePayload) Reset() { *m = MsgCreateResourcePayload{} } +func (m *MsgCreateResourcePayload) String() string { return proto.CompactTextString(m) } +func (*MsgCreateResourcePayload) ProtoMessage() {} +func (*MsgCreateResourcePayload) Descriptor() ([]byte, []int) { + return fileDescriptor_f5b76d41c4c62339, []int{1} +} +func (m *MsgCreateResourcePayload) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgCreateResourcePayload) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgCreateResourcePayload.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 *MsgCreateResourcePayload) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgCreateResourcePayload.Merge(m, src) +} +func (m *MsgCreateResourcePayload) XXX_Size() int { + return m.Size() +} +func (m *MsgCreateResourcePayload) XXX_DiscardUnknown() { + xxx_messageInfo_MsgCreateResourcePayload.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgCreateResourcePayload proto.InternalMessageInfo + +func (m *MsgCreateResourcePayload) GetCollectionId() string { + if m != nil { + return m.CollectionId + } + return "" +} + +func (m *MsgCreateResourcePayload) GetId() string { + if m != nil { + return m.Id + } + return "" +} + +func (m *MsgCreateResourcePayload) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *MsgCreateResourcePayload) GetResourceType() string { + if m != nil { + return m.ResourceType + } + return "" +} + +func (m *MsgCreateResourcePayload) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +type MsgCreateResourceResponse struct { + Resource *Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` +} + +func (m *MsgCreateResourceResponse) Reset() { *m = MsgCreateResourceResponse{} } +func (m *MsgCreateResourceResponse) String() string { return proto.CompactTextString(m) } +func (*MsgCreateResourceResponse) ProtoMessage() {} +func (*MsgCreateResourceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_f5b76d41c4c62339, []int{2} +} +func (m *MsgCreateResourceResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgCreateResourceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgCreateResourceResponse.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 *MsgCreateResourceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgCreateResourceResponse.Merge(m, src) +} +func (m *MsgCreateResourceResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgCreateResourceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgCreateResourceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgCreateResourceResponse proto.InternalMessageInfo + +func (m *MsgCreateResourceResponse) GetResource() *Resource { + if m != nil { + return m.Resource + } + return nil +} + +func init() { + proto.RegisterType((*MsgCreateResource)(nil), "cheqdid.cheqdnode.resource.v1.MsgCreateResource") + proto.RegisterType((*MsgCreateResourcePayload)(nil), "cheqdid.cheqdnode.resource.v1.MsgCreateResourcePayload") + proto.RegisterType((*MsgCreateResourceResponse)(nil), "cheqdid.cheqdnode.resource.v1.MsgCreateResourceResponse") +} + +func init() { proto.RegisterFile("resource/v1/tx.proto", fileDescriptor_f5b76d41c4c62339) } + +var fileDescriptor_f5b76d41c4c62339 = []byte{ + // 381 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x29, 0x4a, 0x2d, 0xce, + 0x2f, 0x2d, 0x4a, 0x4e, 0xd5, 0x2f, 0x33, 0xd4, 0x2f, 0xa9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, + 0x17, 0x92, 0x4d, 0xce, 0x48, 0x2d, 0x4c, 0xc9, 0x4c, 0xd1, 0x03, 0xd3, 0x79, 0xf9, 0x29, 0xa9, + 0x7a, 0x30, 0x75, 0x7a, 0x65, 0x86, 0x52, 0x82, 0x60, 0x61, 0x64, 0x1d, 0x52, 0x52, 0xc8, 0xe6, + 0xc0, 0xd5, 0x82, 0xe5, 0x94, 0xd6, 0x30, 0x72, 0x09, 0xfa, 0x16, 0xa7, 0x3b, 0x17, 0xa5, 0x26, + 0x96, 0xa4, 0x06, 0x41, 0xe5, 0x84, 0x02, 0xb9, 0xd8, 0x0b, 0x12, 0x2b, 0x73, 0xf2, 0x13, 0x53, + 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0xcc, 0xf5, 0xf0, 0xda, 0xaa, 0x87, 0x61, 0x44, 0x00, + 0x44, 0x7b, 0x10, 0xcc, 0x1c, 0x21, 0x17, 0x2e, 0xae, 0xe2, 0xcc, 0xf4, 0xbc, 0xc4, 0x92, 0xd2, + 0xa2, 0xd4, 0x62, 0x09, 0x26, 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x15, 0x2c, 0xa6, 0x82, 0x59, 0x20, + 0x23, 0x83, 0x33, 0xd3, 0xf3, 0x3c, 0xf3, 0xd2, 0xf2, 0x83, 0x90, 0xf4, 0x29, 0xcd, 0x61, 0xe4, + 0x92, 0xc0, 0x65, 0x97, 0x90, 0x32, 0x17, 0x6f, 0x72, 0x7e, 0x4e, 0x4e, 0x6a, 0x72, 0x49, 0x66, + 0x7e, 0x5e, 0x7c, 0x26, 0xc4, 0xed, 0x9c, 0x41, 0x3c, 0x08, 0x41, 0xcf, 0x14, 0x21, 0x3e, 0x2e, + 0xa6, 0xcc, 0x14, 0x09, 0x26, 0xb0, 0x0c, 0x53, 0x66, 0x8a, 0x90, 0x10, 0x17, 0x4b, 0x5e, 0x62, + 0x6e, 0xaa, 0x04, 0x33, 0x58, 0x04, 0xcc, 0x06, 0x19, 0x04, 0xf3, 0x5c, 0x7c, 0x49, 0x65, 0x41, + 0xaa, 0x04, 0x0b, 0xc4, 0x20, 0x98, 0x60, 0x48, 0x65, 0x41, 0x2a, 0x48, 0x63, 0x4a, 0x62, 0x49, + 0xa2, 0x04, 0x9b, 0x02, 0xa3, 0x06, 0x4f, 0x10, 0x98, 0xad, 0x94, 0xc0, 0x25, 0x89, 0xe1, 0xba, + 0xa0, 0xd4, 0xe2, 0x82, 0xfc, 0xbc, 0xe2, 0x54, 0x21, 0x67, 0x2e, 0x0e, 0x98, 0x01, 0xd0, 0x50, + 0x55, 0x27, 0x10, 0xaa, 0x70, 0x23, 0xe0, 0x1a, 0x8d, 0x9a, 0x19, 0xb9, 0x98, 0x7d, 0x8b, 0xd3, + 0x85, 0x6a, 0xb8, 0xf8, 0xd0, 0xe2, 0xcc, 0x80, 0xd4, 0x28, 0x92, 0xb2, 0x20, 0x55, 0x07, 0xcc, + 0x2b, 0x4e, 0x6e, 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, 0x93, 0x9e, + 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x0f, 0x49, 0x89, 0x60, 0x52, 0x17, 0x64, + 0xb8, 0x7e, 0x05, 0x3c, 0xf5, 0xe9, 0x83, 0x82, 0xb5, 0x38, 0x89, 0x0d, 0x9c, 0x08, 0x8d, 0x01, + 0x01, 0x00, 0x00, 0xff, 0xff, 0x83, 0x8d, 0x25, 0xe3, 0xea, 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 + +// 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 { + CreateResource(ctx context.Context, in *MsgCreateResource, opts ...grpc.CallOption) (*MsgCreateResourceResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) CreateResource(ctx context.Context, in *MsgCreateResource, opts ...grpc.CallOption) (*MsgCreateResourceResponse, error) { + out := new(MsgCreateResourceResponse) + err := c.cc.Invoke(ctx, "/cheqdid.cheqdnode.resource.v1.Msg/CreateResource", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + CreateResource(context.Context, *MsgCreateResource) (*MsgCreateResourceResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) CreateResource(ctx context.Context, req *MsgCreateResource) (*MsgCreateResourceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CreateResource not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_CreateResource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgCreateResource) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).CreateResource(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cheqdid.cheqdnode.resource.v1.Msg/CreateResource", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).CreateResource(ctx, req.(*MsgCreateResource)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cheqdid.cheqdnode.resource.v1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "CreateResource", + Handler: _Msg_CreateResource_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "resource/v1/tx.proto", +} + +func (m *MsgCreateResource) 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 *MsgCreateResource) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCreateResource) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Signatures) > 0 { + for iNdEx := len(m.Signatures) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Signatures[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if m.Payload != nil { + { + size, err := m.Payload.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgCreateResourcePayload) 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 *MsgCreateResourcePayload) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCreateResourcePayload) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0x32 + } + if len(m.ResourceType) > 0 { + i -= len(m.ResourceType) + copy(dAtA[i:], m.ResourceType) + i = encodeVarintTx(dAtA, i, uint64(len(m.ResourceType))) + i-- + dAtA[i] = 0x22 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintTx(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0x1a + } + if len(m.Id) > 0 { + i -= len(m.Id) + copy(dAtA[i:], m.Id) + i = encodeVarintTx(dAtA, i, uint64(len(m.Id))) + i-- + dAtA[i] = 0x12 + } + if len(m.CollectionId) > 0 { + i -= len(m.CollectionId) + copy(dAtA[i:], m.CollectionId) + i = encodeVarintTx(dAtA, i, uint64(len(m.CollectionId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgCreateResourceResponse) 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 *MsgCreateResourceResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCreateResourceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Resource != nil { + { + size, err := m.Resource.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + 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 *MsgCreateResource) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Payload != nil { + l = m.Payload.Size() + n += 1 + l + sovTx(uint64(l)) + } + if len(m.Signatures) > 0 { + for _, e := range m.Signatures { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } + return n +} + +func (m *MsgCreateResourcePayload) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.CollectionId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.Id) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ResourceType) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgCreateResourceResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Resource != nil { + l = m.Resource.Size() + n += 1 + l + sovTx(uint64(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 *MsgCreateResource) 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: MsgCreateResource: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgCreateResource: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Payload == nil { + m.Payload = &MsgCreateResourcePayload{} + } + if err := m.Payload.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signatures", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signatures = append(m.Signatures, &types.SignInfo{}) + if err := m.Signatures[len(m.Signatures)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgCreateResourcePayload) 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: MsgCreateResourcePayload: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgCreateResourcePayload: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CollectionId", 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.CollectionId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Id", 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.Id = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", 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.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceType", 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.ResourceType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgCreateResourceResponse) 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: MsgCreateResourceResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgCreateResourceResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Resource == nil { + m.Resource = &Resource{} + } + if err := m.Resource.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func 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/resource/types/tx_msg_create_resource.go b/x/resource/types/tx_msg_create_resource.go new file mode 100644 index 000000000..ccfe9bfef --- /dev/null +++ b/x/resource/types/tx_msg_create_resource.go @@ -0,0 +1,51 @@ +package types + +import ( + cheqd_types "github.com/cheqd/cheqd-node/x/cheqd/types" + sdk "github.com/cosmos/cosmos-sdk/types" + validation "github.com/go-ozzo/ozzo-validation/v4" +) + +var _ sdk.Msg = &MsgCreateResource{} + +func NewMsgCreateResource(payload *MsgCreateResourcePayload, signatures []*cheqd_types.SignInfo) *MsgCreateResource { + return &MsgCreateResource{ + Payload: payload, + Signatures: signatures, + } +} + +func (msg *MsgCreateResource) Route() string { + return RouterKey +} + +func (msg *MsgCreateResource) Type() string { + return "MsgCreateResource" +} + +func (msg *MsgCreateResource) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{} +} + +func (msg *MsgCreateResource) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshal(msg) + return sdk.MustSortJSON(bz) +} + +func (msg *MsgCreateResource) ValidateBasic() error { + err := msg.Validate([]string{}) + if err != nil { + return ErrBasicValidation.Wrap(err.Error()) + } + + return nil +} + +// Validate + +func (msg MsgCreateResource) Validate(allowedNamespaces []string) error { + return validation.ValidateStruct(&msg, + validation.Field(&msg.Payload, validation.Required, ValidMsgCreateResourcePayload()), + validation.Field(&msg.Signatures, cheqd_types.IsUniqueSignInfoListRule(), validation.Each(cheqd_types.ValidSignInfoRule(allowedNamespaces))), + ) +} diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go new file mode 100644 index 000000000..f521f5088 --- /dev/null +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -0,0 +1,47 @@ +package types + +import ( + cheqdtypes "github.com/cheqd/cheqd-node/x/cheqd/types" + validation "github.com/go-ozzo/ozzo-validation/v4" +) + +var _ cheqdtypes.IdentityMsg = &MsgCreateResourcePayload{} + +func (msg *MsgCreateResourcePayload) GetSignBytes() []byte { + return ModuleCdc.MustMarshal(msg) +} + +func (msg *MsgCreateResourcePayload) ToResource() Resource { + return Resource{ + Header: &ResourceHeader{ + CollectionId: msg.CollectionId, + Id: msg.Id, + Name: msg.Name, + ResourceType: msg.ResourceType, + }, + Data: msg.Data, + } +} + +// Validation + +func (msg MsgCreateResourcePayload) Validate() error { + return validation.ValidateStruct(&msg, + validation.Field(&msg.CollectionId, validation.Required, cheqdtypes.IsID()), + validation.Field(&msg.Id, validation.Required, cheqdtypes.IsUUID()), + validation.Field(&msg.Name, validation.Required, validation.Length(1, 64)), + validation.Field(&msg.ResourceType, validation.Required, validation.Length(1, 64)), + validation.Field(&msg.Data, validation.Required, validation.Length(1, 200*1024)), // 200KB + ) +} + +func ValidMsgCreateResourcePayload() *cheqdtypes.CustomErrorRule { + return cheqdtypes.NewCustomErrorRule(func(value interface{}) error { + casted, ok := value.(*MsgCreateResourcePayload) + if !ok { + panic("ValidMsgCreateResourcePayload must be only applied on MsgCreateDidPayload properties") + } + + return casted.Validate() + }) +} diff --git a/x/resource/types/tx_msg_create_resource_payload_test.go b/x/resource/types/tx_msg_create_resource_payload_test.go new file mode 100644 index 000000000..26fb75ab6 --- /dev/null +++ b/x/resource/types/tx_msg_create_resource_payload_test.go @@ -0,0 +1,53 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMsgCreateResourcePayloadValidation(t *testing.T) { + cases := []struct { + name string + struct_ *MsgCreateResourcePayload + isValid bool + errorMsg string + }{ + { + name: "positive", + struct_: &MsgCreateResourcePayload{ + CollectionId: "123456789abcdefg", + Id: "ba62c728-cb15-498b-8e9e-9259cc242186", + Name: "Test Resource", + ResourceType: "CL-Schema", + Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + }, + isValid: true, + }, + { + name: "negative resource type", + struct_: &MsgCreateResourcePayload{ + CollectionId: "123456789abcdefg", + Id: "ba62c728-cb15-498b-8e9e-9259cc242186", + Name: "Test Resource", + ResourceType: "", + Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + }, + isValid: false, + errorMsg: "resource_type: cannot be blank.", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := tc.struct_.Validate() + + if tc.isValid { + require.NoError(t, err) + } else { + require.Error(t, err) + require.Equal(t, err.Error(), tc.errorMsg) + } + }) + } +} diff --git a/x/resource/utils/media_type.go b/x/resource/utils/media_type.go new file mode 100644 index 000000000..443912515 --- /dev/null +++ b/x/resource/utils/media_type.go @@ -0,0 +1,13 @@ +package utils + +import ( + "github.com/gabriel-vasile/mimetype" +) + +func DetectMediaType(data []byte) string { + mimetype.SetLimit(0) // No limit, whole file content used. + + // The result is always a valid MIME type, with application/octet-stream + // returned when identification failed. + return mimetype.Detect(data).String() +} diff --git a/x/resource/utils/media_type_test.go b/x/resource/utils/media_type_test.go new file mode 100644 index 000000000..becbc3578 --- /dev/null +++ b/x/resource/utils/media_type_test.go @@ -0,0 +1,32 @@ +package utils + +import ( + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestValidateMediaType(t *testing.T) { + cases := []struct { + path string + mt string + }{ + {"testdata/resource.txt", "text/plain; charset=utf-8"}, + {"testdata/resource.csv", "text/csv"}, + {"testdata/resource.dat", "application/octet-stream"}, + {"testdata/resource.json", "application/json"}, + {"testdata/resource.pdf", "application/pdf"}, + } + + for _, tc := range cases { + t.Run(tc.mt, func(t *testing.T) { + data, err := os.ReadFile(tc.path) + require.NoError(t, err) + + detected := DetectMediaType(data) + + require.Equal(t, tc.mt, detected) + }) + } +} diff --git a/x/resource/utils/testdata/resource.csv b/x/resource/utils/testdata/resource.csv new file mode 100644 index 000000000..b9783dae1 --- /dev/null +++ b/x/resource/utils/testdata/resource.csv @@ -0,0 +1,23 @@ +"Sell", "List", "Living", "Rooms", "Beds", "Baths", "Age", "Acres", "Taxes" +142, 160, 28, 10, 5, 3, 60, 0.28, 3167 +175, 180, 18, 8, 4, 1, 12, 0.43, 4033 +129, 132, 13, 6, 3, 1, 41, 0.33, 1471 +138, 140, 17, 7, 3, 1, 22, 0.46, 3204 +232, 240, 25, 8, 4, 3, 5, 2.05, 3613 +135, 140, 18, 7, 4, 3, 9, 0.57, 3028 +150, 160, 20, 8, 4, 3, 18, 4.00, 3131 +207, 225, 22, 8, 4, 2, 16, 2.22, 5158 +271, 285, 30, 10, 5, 2, 30, 0.53, 5702 + 89, 90, 10, 5, 3, 1, 43, 0.30, 2054 +153, 157, 22, 8, 3, 3, 18, 0.38, 4127 + 87, 90, 16, 7, 3, 1, 50, 0.65, 1445 +234, 238, 25, 8, 4, 2, 2, 1.61, 2087 +106, 116, 20, 8, 4, 1, 13, 0.22, 2818 +175, 180, 22, 8, 4, 2, 15, 2.06, 3917 +165, 170, 17, 8, 4, 2, 33, 0.46, 2220 +166, 170, 23, 9, 4, 2, 37, 0.27, 3498 +136, 140, 19, 7, 3, 1, 22, 0.63, 3607 +148, 160, 17, 7, 3, 2, 13, 0.36, 3648 +151, 153, 19, 8, 4, 2, 24, 0.34, 3561 +180, 190, 24, 9, 4, 2, 10, 1.55, 4681 +293, 305, 26, 8, 4, 3, 6, 0.46, 7088 diff --git a/x/resource/utils/testdata/resource.dat b/x/resource/utils/testdata/resource.dat new file mode 100644 index 000000000..55d85b198 --- /dev/null +++ b/x/resource/utils/testdata/resource.dat @@ -0,0 +1,3 @@ +á`9U5³Õ2q@h× ;Ü<Eø iÓQ›PC™šRÜÜéh`÷H£·6«q]n˜ö>9Rè%ÜH¿›FÒU 7–hQcŸb™b¡jŒ­iûŒJRüºæºúÏ炾X¶©ïsڑL\šç¦‹gP tG¸Ê·ó5;B¬à.—ٍáXþ ++–pà Xîã]ayD۞ WsÔÝ`;UW³/*ŠPؖ™]ð¤÷¥iI$ì$àÞ +V$_-IXdƒ­½Ò¸Ç„¾ÑÎ,üŸÕܛ#Aœ³ Ý«a†À‹aÖª´VõB¶?FC~–xm öäâ·öQQtƒêN¾šˆ·t \ No newline at end of file diff --git a/x/resource/utils/testdata/resource.json b/x/resource/utils/testdata/resource.json new file mode 100644 index 000000000..2c0bb135c --- /dev/null +++ b/x/resource/utils/testdata/resource.json @@ -0,0 +1,13 @@ +{ + "menu": { + "id": "file", + "value": "File", + "popup": { + "menuitem": [ + { "value": "New", "onclick": "CreateNewDoc()" }, + { "value": "Open", "onclick": "OpenDoc()" }, + { "value": "Close", "onclick": "CloseDoc()" } + ] + } + } +} diff --git a/x/resource/utils/testdata/resource.pdf b/x/resource/utils/testdata/resource.pdf new file mode 100644 index 000000000..774c2ea70 Binary files /dev/null and b/x/resource/utils/testdata/resource.pdf differ diff --git a/x/resource/utils/testdata/resource.txt b/x/resource/utils/testdata/resource.txt new file mode 100644 index 000000000..08e00ed29 --- /dev/null +++ b/x/resource/utils/testdata/resource.txt @@ -0,0 +1 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \ No newline at end of file