From fab0baba04452d30093f9514b26ca7287e9150f4 Mon Sep 17 00:00:00 2001 From: toktar Date: Fri, 3 Jun 2022 12:05:48 +0300 Subject: [PATCH 01/65] dev-1281: add `resource` module --- go.mod | 15 +- go.sum | 14 + proto/resource/v1/genesis.proto | 13 + proto/resource/v1/query.proto | 49 ++ proto/resource/v1/resource.proto | 18 + proto/resource/v1/tx.proto | 28 + x/resource/client/cli/query.go | 25 + x/resource/client/cli/query_resource.go | 39 ++ x/resource/client/cli/tx.go | 128 +++++ x/resource/client/cli/tx_create_resource.go | 62 +++ x/resource/client/cli/tx_update_resource.go | 62 +++ x/resource/genesis.go | 46 ++ x/resource/handler.go | 32 ++ x/resource/keeper/keeper.go | 29 ++ x/resource/keeper/keeper_config.go | 31 ++ x/resource/keeper/keeper_resource.go | 120 +++++ x/resource/keeper/msg_server.go | 107 ++++ .../keeper/msg_server_create_resource.go | 78 +++ x/resource/keeper/query.go | 29 ++ x/resource/keeper/query_resource.go | 24 + x/resource/keeper/query_server.go | 16 + x/resource/keeper/query_server_resource.go | 30 ++ x/resource/module.go | 177 +++++++ x/resource/tests/constants.go | 22 + x/resource/tests/create_did_test.go | 403 +++++++++++++++ x/resource/tests/setup.go | 346 +++++++++++++ .../tests/signature_verification_test.go | 142 +++++ x/resource/tests/update_did_test.go | 483 ++++++++++++++++++ x/resource/tests/utils.go | 48 ++ x/resource/types/codec.go | 37 ++ x/resource/types/error.go | 22 + x/resource/types/genesis.go | 36 ++ x/resource/types/keys.go | 27 + x/resource/types/query.go | 5 + x/resource/utils/crypto.go | 86 ++++ x/resource/utils/crypto_test.go | 60 +++ x/resource/utils/did.go | 98 ++++ x/resource/utils/did_test.go | 97 ++++ x/resource/utils/did_url.go | 118 +++++ x/resource/utils/did_url_test.go | 93 ++++ x/resource/utils/encoding.go | 30 ++ x/resource/utils/encoding_test.go | 115 +++++ x/resource/utils/proto.go | 8 + x/resource/utils/proto_test.go | 12 + x/resource/utils/str.go | 98 ++++ x/resource/utils/str_test.go | 122 +++++ x/resource/utils/tx.go | 12 + x/resource/utils/uri.go | 18 + x/resource/utils/uri_test.go | 32 ++ 49 files changed, 3736 insertions(+), 6 deletions(-) create mode 100644 proto/resource/v1/genesis.proto create mode 100644 proto/resource/v1/query.proto create mode 100644 proto/resource/v1/resource.proto create mode 100644 proto/resource/v1/tx.proto create mode 100644 x/resource/client/cli/query.go create mode 100644 x/resource/client/cli/query_resource.go create mode 100644 x/resource/client/cli/tx.go create mode 100644 x/resource/client/cli/tx_create_resource.go create mode 100644 x/resource/client/cli/tx_update_resource.go create mode 100644 x/resource/genesis.go create mode 100644 x/resource/handler.go create mode 100644 x/resource/keeper/keeper.go create mode 100644 x/resource/keeper/keeper_config.go create mode 100644 x/resource/keeper/keeper_resource.go create mode 100644 x/resource/keeper/msg_server.go create mode 100644 x/resource/keeper/msg_server_create_resource.go create mode 100644 x/resource/keeper/query.go create mode 100644 x/resource/keeper/query_resource.go create mode 100644 x/resource/keeper/query_server.go create mode 100644 x/resource/keeper/query_server_resource.go create mode 100644 x/resource/module.go create mode 100644 x/resource/tests/constants.go create mode 100644 x/resource/tests/create_did_test.go create mode 100644 x/resource/tests/setup.go create mode 100644 x/resource/tests/signature_verification_test.go create mode 100644 x/resource/tests/update_did_test.go create mode 100644 x/resource/tests/utils.go create mode 100644 x/resource/types/codec.go create mode 100644 x/resource/types/error.go create mode 100644 x/resource/types/genesis.go create mode 100644 x/resource/types/keys.go create mode 100644 x/resource/types/query.go create mode 100644 x/resource/utils/crypto.go create mode 100644 x/resource/utils/crypto_test.go create mode 100644 x/resource/utils/did.go create mode 100644 x/resource/utils/did_test.go create mode 100644 x/resource/utils/did_url.go create mode 100644 x/resource/utils/did_url_test.go create mode 100644 x/resource/utils/encoding.go create mode 100644 x/resource/utils/encoding_test.go create mode 100644 x/resource/utils/proto.go create mode 100644 x/resource/utils/proto_test.go create mode 100644 x/resource/utils/str.go create mode 100644 x/resource/utils/str_test.go create mode 100644 x/resource/utils/tx.go create mode 100644 x/resource/utils/uri.go create mode 100644 x/resource/utils/uri_test.go diff --git a/go.mod b/go.mod index 7f2d48a10..ac516630a 100644 --- a/go.mod +++ b/go.mod @@ -22,8 +22,8 @@ require ( 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 ( @@ -56,6 +56,7 @@ require ( github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect github.com/felixge/httpsnoop v1.0.1 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect + github.com/ghodss/yaml v1.0.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.0 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect @@ -63,12 +64,14 @@ require ( github.com/goccy/go-json v0.9.4 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/gateway v1.1.0 // indirect + github.com/golang/glog v1.0.0 // indirect github.com/golang/snappy v0.0.3 // indirect github.com/google/btree v1.0.0 // 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 github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/gtank/merlin v0.1.1 // indirect github.com/gtank/ristretto255 v0.1.2 // 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..1d45cd0d4 100644 --- a/go.sum +++ b/go.sum @@ -317,6 +317,7 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -374,6 +375,8 @@ github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2V github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= +github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -429,6 +432,7 @@ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ 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/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= @@ -490,6 +494,8 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 h1:BGNSrTRW4rwfhJiFwvwF4XQ0Y72Jj9YEgxVrtovbD5o= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3/go.mod h1:VHn7KgNsRriXa4mcgtkpR00OXyQY6g67JWMvn+R27A4= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= @@ -1179,6 +1185,7 @@ golang.org/x/net v0.0.0-20210917221730-978cfadd31cf/go.mod h1:9nx3DQGgdP8bBQD5qx 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/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= @@ -1309,6 +1316,7 @@ golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBc 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/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= @@ -1510,6 +1518,8 @@ google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ6 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= @@ -1528,6 +1538,8 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0 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= @@ -1564,6 +1576,8 @@ 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/resource/v1/genesis.proto b/proto/resource/v1/genesis.proto new file mode 100644 index 000000000..656bfc576 --- /dev/null +++ b/proto/resource/v1/genesis.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; +package cheqdid.cheqdnode.cheqd.v1; + +option go_package = "github.com/cheqd/cheqd-node/x/cheqd/types"; + +import "cheqd/v1/stateValue.proto"; + +// GenesisState defines the cheqd module's genesis state. +message GenesisState { + string did_namespace = 1; + repeated StateValue didList = 2; +} + diff --git a/proto/resource/v1/query.proto b/proto/resource/v1/query.proto new file mode 100644 index 000000000..b6ebb0b64 --- /dev/null +++ b/proto/resource/v1/query.proto @@ -0,0 +1,49 @@ +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/{did}/resources/{id}"; + } + rpc CollectionResources(QueryGetCollectionResourcesRequest) returns (QueryGetCollectionResourcesResponse) { + option (google.api.http).get = "/1.0/identifiers/{did}/resources"; + } + rpc AllResourceVersions(QueryGetAllResourceVersionsRequest) returns (QueryGetAllResourceVersionsResponse) { + option (google.api.http).get = "/1.0/identifiers/{did}/resources"; + } +} + +message QueryGetResourceRequest { + string collection_id = 1; + string id = 2; +} + +message QueryGetResourceResponse { + Resource resource = 1; +} + +message QueryGetCollectionResourcesRequest { + string collection_id = 1; +} + +message QueryGetCollectionResourcesResponse { + repeated Resource resource = 1; +} + +message QueryGetAllResourceVersionsRequest { + string collection_id = 1; + string name = 2; + string resource_type = 3; + string mime_type = 4; +} + +message QueryGetAllResourceVersionsResponse { + repeated Resource resource = 1; +} diff --git a/proto/resource/v1/resource.proto b/proto/resource/v1/resource.proto new file mode 100644 index 000000000..0c6e1354b --- /dev/null +++ b/proto/resource/v1/resource.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; +package cheqdid.cheqdnode.resource.v1; + +option go_package = "github.com/cheqd/cheqd-node/x/resource/types"; + + +message Resource { + string collection_id = 1; + string id = 2; + string name = 3; + string resource_type = 4; + string mime_type = 5; + bytes data = 6; + string created = 7; + string checksum = 8; + string previous_version_id = 9; + string next_version_id = 10; +} \ No newline at end of file diff --git a/proto/resource/v1/tx.proto b/proto/resource/v1/tx.proto new file mode 100644 index 000000000..3ccafd3a7 --- /dev/null +++ b/proto/resource/v1/tx.proto @@ -0,0 +1,28 @@ +syntax = "proto3"; +package cheqdid.cheqdnode.resource.v1; + +option go_package = "github.com/cheqd/cheqd-node/x/resource/types"; + +import "google/protobuf/any.proto"; +import "cheqd/v1/tx.proto"; +import "resource/v1/tx.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 { + string collection_id = 1; + string id = 2; + string name = 3; + string resource_type = 4; + string mime_type = 5; + repeated byte data = 6; + repeated SignInfo signatures = 7; +} + +message MsgCreateDidResponse { + Resource resource = 1; // Not necessary +} diff --git a/x/resource/client/cli/query.go b/x/resource/client/cli/query.go new file mode 100644 index 000000000..dfca90ea9 --- /dev/null +++ b/x/resource/client/cli/query.go @@ -0,0 +1,25 @@ +package cli + +import ( + "fmt" + + "github.com/cheqd/cheqd-node/x/cheqd/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(CmdGetDid()) + + 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..3c8777d69 --- /dev/null +++ b/x/resource/client/cli/query_resource.go @@ -0,0 +1,39 @@ +package cli + +import ( + "context" + + "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" +) + +func CmdGetDid() *cobra.Command { + cmd := &cobra.Command{ + Use: "did [id]", + Short: "Query a did", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + + queryClient := types.NewQueryClient(clientCtx) + + did := args[0] + params := &types.QueryGetDidRequest{ + Id: did, + } + + resp, err := queryClient.Did(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..b659be114 --- /dev/null +++ b/x/resource/client/cli/tx.go @@ -0,0 +1,128 @@ +package cli + +import ( + "bufio" + "crypto/ed25519" + "encoding/base64" + "fmt" + + "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/input" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/spf13/cobra" +) + +type SignInput struct { + verificationMethodId string + privKey ed25519.PrivateKey +} + +// 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(CmdCreateDid()) + cmd.AddCommand(CmdUpdateDid()) + + return cmd +} + +func GetPayloadAndSignInputs(clientCtx client.Context, args []string) (string, []SignInput, error) { + // Check for args count + if len(args)%2 != 1 { + return "", []SignInput{}, fmt.Errorf("invalid number of arguments: %d. must be an odd number", len(args)) + } + + // Get payload json + payloadJson := args[0] + + // Get signInputs + var signInputs []SignInput + + for i := 1; i < len(args); i += 2 { + vmId := args[i] + privKey := args[i+1] + + if privKey == "interactive" { + inBuf := bufio.NewReader(clientCtx.Input) + + var err error + privKey, err = input.GetString("Enter base64 encoded verification key", inBuf) + + if err != nil { + return "", nil, err + } + } + + privKeyBytes, err := base64.StdEncoding.DecodeString(privKey) + if err != nil { + return "", nil, fmt.Errorf("unable to decode private key: %s", err.Error()) + } + + signInput := SignInput{ + verificationMethodId: vmId, + privKey: privKeyBytes, + } + + signInputs = append(signInputs, signInput) + } + + return payloadJson, signInputs, nil +} + +func SignWithSignInputs(signBytes []byte, signInputs []SignInput) []*types.SignInfo { + var signatures []*types.SignInfo + + for _, signInput := range signInputs { + signatureBytes := ed25519.Sign(signInput.privKey, signBytes) + + signInfo := types.SignInfo{ + VerificationMethodId: signInput.verificationMethodId, + Signature: base64.StdEncoding.EncodeToString(signatureBytes), + } + + signatures = append(signatures, &signInfo) + } + + return signatures +} + +func SetFeePayerFromSigner(ctx *client.Context) error { + if ctx.FromAddress != nil { + ctx.FeePayer = ctx.FromAddress + return nil + } + + signerAccAddr, err := AccAddrByKeyRef(ctx.Keyring, ctx.From) + if err != nil { + return err + } + + ctx.FeePayer = signerAccAddr + return nil +} + +func AccAddrByKeyRef(keyring keyring.Keyring, keyRef string) (sdk.AccAddress, error) { + // Firstly check if the keyref is a key name of a key registered in a keyring + info, err := keyring.Key(keyRef) + + if err == nil { + return info.GetAddress(), nil + } + + if !sdkerrors.IsOf(err, sdkerrors.ErrIO, sdkerrors.ErrKeyNotFound) { + return nil, err + } + + // Fallback: convert keyref to address + return sdk.AccAddressFromBech32(keyRef) +} 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..e5498a53b --- /dev/null +++ b/x/resource/client/cli/tx_create_resource.go @@ -0,0 +1,62 @@ +package cli + +import ( + "github.com/cheqd/cheqd-node/x/cheqd/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" +) + +func CmdCreateDid() *cobra.Command { + cmd := &cobra.Command{ + Use: "create-did [payload-json] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", + Short: "Creates a new DID.", + Long: "Creates a new DID. " + + "[payload-json] is JSON encoded MsgCreateDidPayload. " + + "[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-1] 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(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + payloadJson, signInputs, err := GetPayloadAndSignInputs(clientCtx, args) + if err != nil { + return err + } + + // Unmarshal payload + var payload types.MsgCreateDidPayload + err = clientCtx.Codec.UnmarshalJSON([]byte(payloadJson), &payload) + if err != nil { + return err + } + + // Build identity message + signBytes := payload.GetSignBytes() + identitySignatures := SignWithSignInputs(signBytes, signInputs) + + msg := types.MsgCreateDid{ + Payload: &payload, + Signatures: identitySignatures, + } + + // Set fee-payer if not set + err = SetFeePayerFromSigner(&clientCtx) + if err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/resource/client/cli/tx_update_resource.go b/x/resource/client/cli/tx_update_resource.go new file mode 100644 index 000000000..6c2437da2 --- /dev/null +++ b/x/resource/client/cli/tx_update_resource.go @@ -0,0 +1,62 @@ +package cli + +import ( + "github.com/cheqd/cheqd-node/x/cheqd/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" +) + +func CmdUpdateDid() *cobra.Command { + cmd := &cobra.Command{ + Use: "update-did [payload-json] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", + Short: "Update a DID.", + Long: "Updates a DID. " + + "[payload-json] is JSON encoded MsgUpdateDidPayload. " + + "[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-1] 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(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + payloadJson, signInputs, err := GetPayloadAndSignInputs(clientCtx, args) + if err != nil { + return err + } + + // Unmarshal payload + var payload types.MsgUpdateDidPayload + err = clientCtx.Codec.UnmarshalJSON([]byte(payloadJson), &payload) + if err != nil { + return err + } + + // Build identity message + signBytes := payload.GetSignBytes() + identitySignatures := SignWithSignInputs(signBytes, signInputs) + + msg := types.MsgUpdateDid{ + Payload: &payload, + Signatures: identitySignatures, + } + + // Set fee-payer if not set + err = SetFeePayerFromSigner(&clientCtx) + if err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/resource/genesis.go b/x/resource/genesis.go new file mode 100644 index 000000000..413028501 --- /dev/null +++ b/x/resource/genesis.go @@ -0,0 +1,46 @@ +package cheqd + +import ( + "fmt" + + "github.com/cheqd/cheqd-node/x/cheqd/keeper" + "github.com/cheqd/cheqd-node/x/cheqd/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// InitGenesis initializes the cheqd module's state from a provided genesis +// 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 { + panic(fmt.Sprintf("Cannot set did case: %s", err.Error())) + } + } + + // Set nym count + k.SetDidCount(&ctx, uint64(len(genState.DidList))) + + k.SetDidNamespace(ctx, genState.DidNamespace) +} + +// ExportGenesis returns the cheqd module's exported genesis. +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { + genesis := types.DefaultGenesis() + + // this line is used by starport scaffolding # genesis/module/export + // Get all did + didList := k.GetAllDid(&ctx) + for _, elem := range didList { + elem := elem + genesis.DidList = append(genesis.DidList, &elem) + } + + genesis.DidNamespace = k.GetDidNamespace(ctx) + + return genesis +} diff --git a/x/resource/handler.go b/x/resource/handler.go new file mode 100644 index 000000000..23d43d077 --- /dev/null +++ b/x/resource/handler.go @@ -0,0 +1,32 @@ +package cheqd + +import ( + "fmt" + + "github.com/cheqd/cheqd-node/x/cheqd/keeper" + "github.com/cheqd/cheqd-node/x/cheqd/types" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +func NewHandler(k keeper.Keeper) sdk.Handler { + msgServer := keeper.NewMsgServer(k) + + return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { + ctx = ctx.WithEventManager(sdk.NewEventManager()) + + switch msg := msg.(type) { + case *types.MsgCreateDid: + res, err := msgServer.CreateDid(sdk.WrapSDKContext(ctx), msg) + return sdk.WrapServiceResult(ctx, res, err) + + case *types.MsgUpdateDid: + res, err := msgServer.UpdateDid(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..8802339a7 --- /dev/null +++ b/x/resource/keeper/keeper.go @@ -0,0 +1,29 @@ +package keeper + +import ( + "fmt" + + "github.com/cheqd/cheqd-node/x/cheqd/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_config.go b/x/resource/keeper/keeper_config.go new file mode 100644 index 000000000..eb67b6704 --- /dev/null +++ b/x/resource/keeper/keeper_config.go @@ -0,0 +1,31 @@ +package keeper + +import ( + "github.com/cheqd/cheqd-node/x/cheqd/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GetDidNamespace - 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) + + // Parse bytes + namespace := string(bz) + return namespace +} + +// SetToState - set State value +func (k Keeper) SetToState(ctx sdk.Context, stateKey string, stateValue []byte) { + store := ctx.KVStore(k.storeKey) + byteKey := types.KeyPrefix(types.DidNamespaceKey) + store.Set(byteKey, stateValue) +} + +// DeteteFromState - remove value from State by key +func (k Keeper) DeteteFromState(ctx sdk.Context, stateKey string) { + store := ctx.KVStore(k.storeKey) + byteKey := types.KeyPrefix(types.DidNamespaceKey) + store.Delete(byteKey) +} diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go new file mode 100644 index 000000000..a71ca3d0f --- /dev/null +++ b/x/resource/keeper/keeper_resource.go @@ -0,0 +1,120 @@ +package keeper + +import ( + "strconv" + + "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// GetDidCount get the total number of did +func (k Keeper) GetDidCount(ctx *sdk.Context) uint64 { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidCountKey)) + byteKey := types.KeyPrefix(types.DidCountKey) + 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 iint64 + panic("cannot decode count") + } + + return count +} + +// SetDidCount set the total number of did +func (k Keeper) SetDidCount(ctx *sdk.Context, count uint64) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidCountKey)) + byteKey := types.KeyPrefix(types.DidCountKey) + bz := []byte(strconv.FormatUint(count, 10)) + 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) + 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 + } + + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidKey)) + b := k.cdc.MustMarshal(&stateValue) + store.Set(GetDidIDBytes(did.Id), b) + return nil +} + +// GetDid returns a did from its id +func (k Keeper) GetDid(ctx *sdk.Context, id string) (types.StateValue, error) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidKey)) + + if !k.HasDid(ctx, id) { + return types.StateValue{}, sdkerrors.ErrNotFound.Wrap(id) + } + + var value types.StateValue + bytes := store.Get(GetDidIDBytes(id)) + if err := k.cdc.Unmarshal(bytes, &value); err != nil { + return types.StateValue{}, sdkerrors.Wrap(sdkerrors.ErrInvalidType, err.Error()) + } + + return value, nil +} + +// HasDid checks if the did exists in the store +func (k Keeper) HasDid(ctx *sdk.Context, id string) bool { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidKey)) + return store.Has(GetDidIDBytes(id)) +} + +// GetDidIDBytes returns the byte representation of the ID +func GetDidIDBytes(id string) []byte { + return []byte(id) +} + +// GetAllDid returns all did +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{}) + + defer func(iterator sdk.Iterator) { + err := iterator.Close() + if err != nil { + panic(err.Error()) + } + }(iterator) + + for ; iterator.Valid(); iterator.Next() { + var val types.StateValue + k.cdc.MustUnmarshal(iterator.Value(), &val) + list = append(list, val) + } + + return +} diff --git a/x/resource/keeper/msg_server.go b/x/resource/keeper/msg_server.go new file mode 100644 index 000000000..56f00e4b0 --- /dev/null +++ b/x/resource/keeper/msg_server.go @@ -0,0 +1,107 @@ +package keeper + +import ( + "encoding/base64" + + "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/cheqd/utils" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type msgServer struct { + Keeper +} + +// NewMsgServer returns an implementation of the MsgServer interface for the provided Keeper. +func NewMsgServer(keeper Keeper) types.MsgServer { + return &msgServer{Keeper: keeper} +} + +var _ types.MsgServer = msgServer{} + +func FindDid(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, did string) (res types.StateValue, found bool, err error) { + // Look in inMemory dict + value, found := inMemoryDIDs[did] + if found { + return value, true, nil + } + + // Look in state + if k.HasDid(ctx, did) { + value, err := k.GetDid(ctx, did) + if err != nil { + return types.StateValue{}, false, err + } + + return value, true, nil + } + + return types.StateValue{}, false, nil +} + +func MustFindDid(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, did string) (res types.StateValue, err error) { + res, found, err := FindDid(k, ctx, inMemoryDIDs, did) + if err != nil { + return types.StateValue{}, err + } + + if !found { + return types.StateValue{}, types.ErrDidDocNotFound.Wrap(did) + } + + return res, nil +} + +func FindVerificationMethod(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, didUrl string) (res types.VerificationMethod, found bool, err error) { + did, _, _, _ := utils.MustSplitDIDUrl(didUrl) + + stateValue, found, err := FindDid(k, ctx, inMemoryDIDs, did) + if err != nil || !found { + return types.VerificationMethod{}, found, err + } + + didDoc, err := stateValue.UnpackDataAsDid() + if err != nil { + return types.VerificationMethod{}, false, err + } + + for _, vm := range didDoc.VerificationMethod { + if vm.Id == didUrl { + return *vm, true, nil + } + } + + return types.VerificationMethod{}, false, nil +} + +func MustFindVerificationMethod(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, didUrl string) (res types.VerificationMethod, err error) { + res, found, err := FindVerificationMethod(k, ctx, inMemoryDIDs, didUrl) + if err != nil { + return types.VerificationMethod{}, err + } + + if !found { + return types.VerificationMethod{}, types.ErrVerificationMethodNotFound.Wrap(didUrl) + } + + return res, nil +} + +func VerifySignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, message []byte, signature types.SignInfo) error { + verificationMethod, err := MustFindVerificationMethod(k, ctx, inMemoryDIDs, signature.VerificationMethodId) + if err != nil { + return err + } + + signatureBytes, err := base64.StdEncoding.DecodeString(signature.Signature) + if err != nil { + return err + } + + err = types.VerifySignature(verificationMethod, message, signatureBytes) + if err != nil { + return types.ErrInvalidSignature.Wrapf("method id: %s", signature.VerificationMethodId) + } + + return nil +} 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..e2ecc76fd --- /dev/null +++ b/x/resource/keeper/msg_server_create_resource.go @@ -0,0 +1,78 @@ +package keeper + +import ( + "context" + + "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/cheqd/utils" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (k msgServer) CreateDid(goCtx context.Context, msg *types.MsgCreateDid) (*types.MsgCreateDidResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + // Validate DID doesn't exist + if k.HasDid(&ctx, msg.Payload.Id) { + return nil, types.ErrDidDocExists.Wrap(msg.Payload.Id) + } + + // Validate namespaces + namespace := k.GetDidNamespace(ctx) + err := msg.Validate([]string{namespace}) + if err != nil { + return nil, types.ErrNamespaceValidation.Wrap(err.Error()) + } + + // Build metadata and stateValue + did := msg.Payload.ToDid() + metadata := types.NewMetadataFromContext(ctx) + stateValue, err := types.NewStateValue(&did, &metadata) + if err != nil { + return nil, err + } + + // Consider did that we are going to create during did resolutions + inMemoryDids := map[string]types.StateValue{did.Id: stateValue} + + // Check controllers' existence + controllers := did.AllControllerDids() + for _, controller := range controllers { + _, err := MustFindDid(&k.Keeper, &ctx, inMemoryDids, controller) + if err != nil { + return nil, err + } + } + + // 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 := VerifySignature(&k.Keeper, &ctx, inMemoryDids, msg.Payload.GetSignBytes(), signature) + if err != nil { + return nil, err + } + } + + // Apply changes + err = k.AppendDid(&ctx, &did, &metadata) + if err != nil { + return nil, types.ErrInternal.Wrapf(err.Error()) + } + + // Build and return response + return &types.MsgCreateDidResponse{ + Id: did.Id, + }, nil +} + +func GetSignerDIDsForDIDCreation(did types.Did) []string { + res := did.GetControllersOrSubject() + res = append(res, did.GetVerificationMethodControllers()...) + + return utils.UniqueSorted(res) +} diff --git a/x/resource/keeper/query.go b/x/resource/keeper/query.go new file mode 100644 index 000000000..927292558 --- /dev/null +++ b/x/resource/keeper/query.go @@ -0,0 +1,29 @@ +package keeper + +import ( + "github.com/cheqd/cheqd-node/x/cheqd/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, 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.QueryGetResourceRequest: + return getResourceRequest(ctx, path[1], k, legacyQuerierCdc) + + 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_resource.go b/x/resource/keeper/query_resource.go new file mode 100644 index 000000000..54e331d8c --- /dev/null +++ b/x/resource/keeper/query_resource.go @@ -0,0 +1,24 @@ +package keeper + +import ( + "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +func getDid(ctx sdk.Context, id string, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { + queryServer := NewQueryServer(keeper) + + resp, err := queryServer.Did(sdk.WrapSDKContext(ctx), &types.QueryGetDidRequest{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..966633539 --- /dev/null +++ b/x/resource/keeper/query_server.go @@ -0,0 +1,16 @@ +package keeper + +import ( + "github.com/cheqd/cheqd-node/x/cheqd/types" +) + +type queryServer struct { + Keeper +} + +// NewQueryServer returns an implementation of the MsgServer interface for the provided Keeper. +func NewQueryServer(keeper Keeper) types.QueryServer { + return &queryServer{Keeper: keeper} +} + +var _ types.QueryServer = queryServer{} diff --git a/x/resource/keeper/query_server_resource.go b/x/resource/keeper/query_server_resource.go new file mode 100644 index 000000000..970c017e9 --- /dev/null +++ b/x/resource/keeper/query_server_resource.go @@ -0,0 +1,30 @@ +package keeper + +import ( + "context" + + "github.com/cheqd/cheqd-node/x/cheqd/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (k Keeper) Did(c context.Context, req *types.QueryGetDidRequest) (*types.QueryGetDidResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + ctx := sdk.UnwrapSDKContext(c) + + stateValue, err := k.GetDid(&ctx, req.Id) + if err != nil { + return nil, err + } + + did, err := stateValue.UnpackDataAsDid() + if err != nil { + return nil, err + } + + return &types.QueryGetDidResponse{Did: did, Metadata: stateValue.Metadata}, nil +} diff --git a/x/resource/module.go b/x/resource/module.go new file mode 100644 index 000000000..5d0a49f9b --- /dev/null +++ b/x/resource/module.go @@ -0,0 +1,177 @@ +package recource + +import ( + "context" + "encoding/json" + "fmt" + "log" + + "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 capability module. +type AppModuleBasic struct { + cdc codec.Codec +} + +func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { + return AppModuleBasic{cdc: cdc} +} + +// Name returns the capability 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 capability 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. +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 capability 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 capability module's root tx command. +func (a AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// GetQueryCmd returns the capability module's root query command. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// ---------------------------------------------------------------------------- +// AppModule +// ---------------------------------------------------------------------------- + +// AppModule implements the AppModule interface for the capability module. +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper +} + +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { + return AppModule{ + AppModuleBasic: NewAppModuleBasic(cdc), + keeper: keeper, + } +} + +// 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 3 +} + +// Name returns the capability module's name. +func (am AppModule) Name() string { + return am.AppModuleBasic.Name() +} + +// Route returns the capability 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. +func (AppModule) QuerierRoute() string { return types.QuerierRoute } + +// LegacyQuerierHandler returns the capability module's Querier. +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return keeper.NewQuerier(am.keeper, 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(), am.keeper) +} + +// RegisterInvariants registers the capability module's invariants. +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs the capability 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 capability 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. +func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} + +// EndBlock executes all ABCI EndBlock logic respective to the capability 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..a1d4cc243 --- /dev/null +++ b/x/resource/tests/constants.go @@ -0,0 +1,22 @@ +package tests + +const ( + AliceDID = "did:cheqd:test:aaaaaaaaaaaaaaaa" + BobDID = "did:cheqd:test:bbbbbbbbbbbbbbbb" + CharlieDID = "did:cheqd:test:cccccccccccccccc" + ImposterDID = "did:cheqd:test:nananananananana" + NotFounDID = "did:cheqd:test:nfdnfdnfdnfdnfdd" + AliceKey1 = AliceDID + "#key-1" + AliceKey2 = AliceDID + "#key-2" + BobKey1 = BobDID + "#key-1" + BobKey2 = BobDID + "#key-2" + BobKey3 = BobDID + "#key-3" + BobKey4 = BobDID + "#key-4" + ImposterKey1 = ImposterDID + "#key-1" + ImposterKey2 = ImposterDID + "#key-2" + NotFoundKey1 = NotFounDID + "#key-1" + CharlieKey1 = CharlieDID + "#key-1" + CharlieKey2 = CharlieDID + "#key-2" + CharlieKey3 = CharlieDID + "#key-3" + CharlieKey4 = CharlieDID + "#key-4" +) diff --git a/x/resource/tests/create_did_test.go b/x/resource/tests/create_did_test.go new file mode 100644 index 000000000..c9415fc99 --- /dev/null +++ b/x/resource/tests/create_did_test.go @@ -0,0 +1,403 @@ +package tests + +import ( + "crypto/ed25519" + "fmt" + "testing" + + "github.com/btcsuite/btcutil/base58" + + "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/multiformats/go-multibase" + + "github.com/stretchr/testify/require" +) + +func TestCreateDID(t *testing.T) { + var err error + keys := GenerateTestKeys() + cases := []struct { + valid bool + name string + keys map[string]KeyPair + signers []string + msg *types.MsgCreateDidPayload + errMsg string + }{ + { + valid: true, + name: "Valid: Works", + keys: map[string]KeyPair{ + ImposterKey1: GenerateKeyPair(), + }, + signers: []string{ImposterKey1}, + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + Authentication: []string{ImposterKey1}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: ImposterKey1, + Type: Ed25519VerificationKey2020, + Controller: ImposterDID, + }, + }, + }, + }, + { + valid: true, + name: "Valid: Works with Key Agreement", + keys: map[string]KeyPair{ + ImposterKey1: GenerateKeyPair(), + AliceKey1: keys[AliceKey1], + }, + signers: []string{ImposterKey1, AliceKey1}, + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + KeyAgreement: []string{ImposterKey1}, + Controller: []string{AliceDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: ImposterKey1, + Type: Ed25519VerificationKey2020, + Controller: ImposterDID, + }, + }, + }, + }, + { + valid: true, + name: "Valid: Works with Assertion Method", + keys: map[string]KeyPair{ + ImposterKey1: GenerateKeyPair(), + AliceKey1: keys[AliceKey1], + }, + signers: []string{AliceKey1, ImposterKey1}, + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + AssertionMethod: []string{ImposterKey1}, + Controller: []string{AliceDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: ImposterKey1, + Type: Ed25519VerificationKey2020, + Controller: ImposterDID, + }, + }, + }, + }, + { + valid: true, + name: "Valid: Works with Capability Delegation", + keys: map[string]KeyPair{ + ImposterKey1: GenerateKeyPair(), + AliceKey1: keys[AliceKey1], + }, + signers: []string{AliceKey1, ImposterKey1}, + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + CapabilityDelegation: []string{ImposterKey1}, + Controller: []string{AliceDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: ImposterKey1, + Type: Ed25519VerificationKey2020, + Controller: ImposterDID, + }, + }, + }, + }, + { + valid: true, + name: "Valid: Works with Capability Invocation", + keys: map[string]KeyPair{ + ImposterKey1: GenerateKeyPair(), + AliceKey1: keys[AliceKey1], + }, + signers: []string{AliceKey1, ImposterKey1}, + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + CapabilityInvocation: []string{ImposterKey1}, + Controller: []string{AliceDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: ImposterKey1, + Type: Ed25519VerificationKey2020, + Controller: ImposterDID, + }, + }, + }, + }, + { + valid: true, + name: "Valid: With controller works", + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + Controller: []string{AliceDID, BobDID}, + }, + signers: []string{AliceKey1, BobKey3}, + keys: map[string]KeyPair{ + AliceKey1: keys[AliceKey1], + BobKey3: keys[BobKey3], + }, + }, + { + 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(), + AliceKey1: keys[AliceKey1], + BobKey1: keys[BobKey1], + BobKey2: keys[BobKey2], + BobKey3: keys[BobKey3], + CharlieKey1: keys[CharlieKey1], + CharlieKey2: keys[CharlieKey2], + CharlieKey3: keys[CharlieKey3], + }, + signers: []string{ + "did:cheqd:test:1111111111111111#key-1", + "did:cheqd:test:1111111111111111#key-5", + AliceKey1, + BobKey1, + BobKey2, + BobKey3, + CharlieKey1, + CharlieKey2, + CharlieKey3, + }, + msg: &types.MsgCreateDidPayload{ + Id: "did:cheqd:test:1111111111111111", + Authentication: []string{ + "did:cheqd:test:1111111111111111#key-1", + "did:cheqd:test:1111111111111111#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"}, + AlsoKnownAs: []string{"SomeUri"}, + Service: []*types.Service{ + { + Id: "did:cheqd:test:1111111111111111#service-1", + Type: "DIDCommMessaging", + ServiceEndpoint: "ServiceEndpoint", + }, + }, + Controller: []string{"did:cheqd:test:1111111111111111", AliceDID, BobDID, CharlieDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: "did:cheqd:test:1111111111111111#key-1", + Type: Ed25519VerificationKey2020, + Controller: "did:cheqd:test:1111111111111111", + }, + { + Id: "did:cheqd:test:1111111111111111#key-2", + Type: Ed25519VerificationKey2020, + Controller: "did:cheqd:test:1111111111111111", + }, + { + Id: "did:cheqd:test:1111111111111111#key-3", + Type: Ed25519VerificationKey2020, + Controller: "did:cheqd:test:1111111111111111", + }, + { + Id: "did:cheqd:test:1111111111111111#key-4", + Type: "Ed25519VerificationKey2020", + Controller: "did:cheqd:test:1111111111111111", + }, + { + Id: "did:cheqd:test:1111111111111111#key-5", + Type: "Ed25519VerificationKey2020", + Controller: "did:cheqd:test:1111111111111111", + }, + }, + }, + }, + { + valid: false, + name: "Not Valid: Second controller did not sign request", + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + Controller: []string{AliceDID, BobDID}, + }, + signers: []string{AliceKey1}, + keys: map[string]KeyPair{ + AliceKey1: keys[AliceKey1], + }, + errMsg: fmt.Sprintf("signer: %s: signature is required but not found", BobDID), + }, + { + valid: false, + name: "Not Valid: No signature", + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + Controller: []string{AliceDID, BobDID}, + }, + errMsg: fmt.Sprintf("signer: %s: signature is required but not found", AliceDID), + }, + { + valid: false, + name: "Not Valid: Controller not found", + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + Controller: []string{AliceDID, NotFounDID}, + }, + signers: []string{AliceKey1, ImposterKey1}, + keys: map[string]KeyPair{ + AliceKey1: keys[AliceKey1], + ImposterKey1: GenerateKeyPair(), + }, + errMsg: fmt.Sprintf("%s: DID Doc not found", NotFounDID), + }, + { + valid: false, + name: "Not Valid: Wrong signature", + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + Controller: []string{AliceDID}, + }, + signers: []string{AliceKey1}, + keys: map[string]KeyPair{ + AliceKey1: keys[BobKey1], + }, + errMsg: fmt.Sprintf("method id: %s: invalid signature detected", AliceKey1), + }, + { + valid: false, + name: "Not Valid: DID signed by wrong controller", + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + Authentication: []string{ImposterKey1}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: ImposterKey1, + Type: Ed25519VerificationKey2020, + Controller: ImposterDID, + PublicKeyMultibase: "z" + base58.Encode(keys[ImposterKey1].PublicKey), + }, + }, + }, + signers: []string{AliceKey1}, + keys: map[string]KeyPair{ + AliceKey1: keys[AliceKey1], + }, + errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ImposterDID), + }, + { + valid: false, + name: "Not Valid: DID self-signed by not existing verification method", + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + Authentication: []string{ImposterKey1}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: ImposterKey1, + Type: Ed25519VerificationKey2020, + Controller: ImposterDID, + PublicKeyMultibase: "z" + base58.Encode(keys[ImposterKey1].PublicKey), + }, + }, + }, + signers: []string{ImposterKey2}, + keys: map[string]KeyPair{ + ImposterKey2: GenerateKeyPair(), + }, + errMsg: fmt.Sprintf("%s: verification method not found", ImposterKey2), + }, + { + valid: false, + name: "Not Valid: Self-signature not found", + msg: &types.MsgCreateDidPayload{ + Id: ImposterDID, + Controller: []string{AliceDID, ImposterDID}, + Authentication: []string{ImposterKey1}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: ImposterKey1, + Type: Ed25519VerificationKey2020, + Controller: ImposterDID, + PublicKeyMultibase: "z" + base58.Encode(keys[ImposterKey1].PublicKey), + }, + }, + }, + signers: []string{AliceKey1, ImposterKey2}, + keys: map[string]KeyPair{ + AliceKey1: keys[AliceKey1], + ImposterKey2: GenerateKeyPair(), + }, + errMsg: fmt.Sprintf("%s: verification method not found", ImposterKey2), + }, + { + valid: false, + name: "Not Valid: DID Doc already exists", + keys: map[string]KeyPair{ + CharlieKey1: GenerateKeyPair(), + }, + signers: []string{CharlieKey1}, + msg: &types.MsgCreateDidPayload{ + Id: CharlieDID, + Authentication: []string{CharlieKey1}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: CharlieKey1, + Type: Ed25519VerificationKey2020, + Controller: CharlieDID, + }, + }, + }, + errMsg: fmt.Sprintf("%s: DID Doc exists", CharlieDID), + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + msg := tc.msg + setup := InitEnv(t, keys) + + for _, vm := range msg.VerificationMethod { + if vm.PublicKeyMultibase == "" { + vm.PublicKeyMultibase, err = multibase.Encode(multibase.Base58BTC, tc.keys[vm.Id].PublicKey) + } + require.NoError(t, err) + } + + signerKeys := map[string]ed25519.PrivateKey{} + for _, signer := range tc.signers { + signerKeys[signer] = tc.keys[signer].PrivateKey + } + + did, err := setup.SendCreateDid(msg, signerKeys) + + if tc.valid { + require.Nil(t, err) + require.Equal(t, tc.msg.Id, did.Id) + require.Equal(t, tc.msg.Controller, did.Controller) + require.Equal(t, tc.msg.VerificationMethod, did.VerificationMethod) + require.Equal(t, tc.msg.Authentication, did.Authentication) + require.Equal(t, tc.msg.AssertionMethod, did.AssertionMethod) + require.Equal(t, tc.msg.CapabilityInvocation, did.CapabilityInvocation) + require.Equal(t, tc.msg.CapabilityDelegation, did.CapabilityDelegation) + require.Equal(t, tc.msg.KeyAgreement, did.KeyAgreement) + require.Equal(t, tc.msg.AlsoKnownAs, did.AlsoKnownAs) + require.Equal(t, tc.msg.Service, did.Service) + require.Equal(t, tc.msg.Context, did.Context) + } else { + require.Error(t, err) + require.Equal(t, tc.errMsg, err.Error()) + } + }) + } +} + +func TestHandler_DidDocAlreadyExists(t *testing.T) { + setup := Setup() + + _, _, _ = setup.InitDid(AliceDID) + _, _, err := setup.InitDid(AliceDID) + + require.Error(t, err) + require.Equal(t, fmt.Sprintf("%s: DID Doc exists", AliceDID), err.Error()) +} diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go new file mode 100644 index 000000000..573d7756b --- /dev/null +++ b/x/resource/tests/setup.go @@ -0,0 +1,346 @@ +package tests + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "time" + + "github.com/btcsuite/btcutil/base58" + "github.com/cheqd/cheqd-node/x/cheqd" + "github.com/cheqd/cheqd-node/x/cheqd/types" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/multiformats/go-multibase" + + "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/cheqd/keeper" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const Ed25519VerificationKey2020 = "Ed25519VerificationKey2020" + +type KeyPair struct { + PrivateKey ed25519.PrivateKey + PublicKey ed25519.PublicKey +} + +type TestSetup struct { + Cdc codec.Codec + Ctx sdk.Context + Keeper keeper.Keeper + Handler sdk.Handler +} + +type SignerKey struct { + signer string + key ed25519.PrivateKey +} + +func Setup() TestSetup { + // Init Codec + ir := codectypes.NewInterfaceRegistry() + types.RegisterInterfaces(ir) + cdc := codec.NewProtoCodec(ir) + + // Init KVSore + db := dbm.NewMemDB() + + dbStore := store.NewCommitMultiStore(db) + storeKey := sdk.NewKVStoreKey(types.StoreKey) + dbStore.MountStoreWithDB(storeKey, sdk.StoreTypeIAVL, nil) + + _ = dbStore.LoadLatestVersion() + + // Init Keepers + newKeeper := keeper.NewKeeper(cdc, storeKey) + + // 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) + + handler := cheqd.NewHandler(*newKeeper) + + setup := TestSetup{ + Cdc: cdc, + Ctx: ctx, + Keeper: *newKeeper, + Handler: handler, + } + return setup +} + +func (s *TestSetup) CreateDid(pubKey ed25519.PublicKey, did string) *types.MsgCreateDidPayload { + PublicKeyMultibase := "z" + base58.Encode(pubKey) + + VerificationMethod := types.VerificationMethod{ + Id: did + "#key-1", + Type: Ed25519VerificationKey2020, + Controller: did, + PublicKeyMultibase: PublicKeyMultibase, + } + + Service := types.Service{ + Id: did + "#service-2", + Type: "DIDCommMessaging", + ServiceEndpoint: "endpoint", + } + + return &types.MsgCreateDidPayload{ + Id: did, + Controller: nil, + VerificationMethod: []*types.VerificationMethod{&VerificationMethod}, + Authentication: []string{did + "#key-1"}, + AssertionMethod: []string{did + "#key-1"}, + CapabilityInvocation: []string{did + "#key-1"}, + CapabilityDelegation: []string{did + "#key-1"}, + KeyAgreement: []string{did + "#key-1"}, + AlsoKnownAs: []string{did + "#key-1"}, + Context: []string{"Context"}, + Service: []*types.Service{&Service}, + } +} + +func (s *TestSetup) CreateToUpdateDid(did *types.MsgCreateDidPayload) *types.MsgUpdateDidPayload { + return &types.MsgUpdateDidPayload{ + Id: did.Id, + Controller: did.Controller, + VerificationMethod: did.VerificationMethod, + Authentication: did.Authentication, + AssertionMethod: did.AssertionMethod, + CapabilityInvocation: did.CapabilityInvocation, + CapabilityDelegation: did.CapabilityDelegation, + KeyAgreement: did.KeyAgreement, + AlsoKnownAs: did.AlsoKnownAs, + Service: did.Service, + Context: did.Context, + } +} + +func (s *TestSetup) WrapCreateRequest(payload *types.MsgCreateDidPayload, keys map[string]ed25519.PrivateKey) *types.MsgCreateDid { + var signatures []*types.SignInfo + signingInput := payload.GetSignBytes() + + for privKeyId, privKey := range keys { + signature := base64.StdEncoding.EncodeToString(ed25519.Sign(privKey, signingInput)) + signatures = append(signatures, &types.SignInfo{ + VerificationMethodId: privKeyId, + Signature: signature, + }) + } + + return &types.MsgCreateDid{ + Payload: payload, + Signatures: signatures, + } +} + +func (s *TestSetup) WrapUpdateRequest(payload *types.MsgUpdateDidPayload, keys []SignerKey) *types.MsgUpdateDid { + var signatures []*types.SignInfo + signingInput := payload.GetSignBytes() + + for _, skey := range keys { + signature := base64.StdEncoding.EncodeToString(ed25519.Sign(skey.key, signingInput)) + signatures = append(signatures, &types.SignInfo{ + VerificationMethodId: skey.signer, + Signature: signature, + }) + } + + return &types.MsgUpdateDid{ + Payload: payload, + Signatures: signatures, + } +} + +func GenerateKeyPair() KeyPair { + PublicKey, PrivateKey, _ := ed25519.GenerateKey(rand.Reader) + return KeyPair{PrivateKey, PublicKey} +} + +func (s *TestSetup) InitDid(did string) (map[string]ed25519.PrivateKey, *types.MsgCreateDidPayload, error) { + pubKey, privKey, _ := ed25519.GenerateKey(rand.Reader) + + // add new Did + didMsg := s.CreateDid(pubKey, did) + + keyId := did + "#key-1" + keys := map[string]ed25519.PrivateKey{keyId: privKey} + + result, err := s.Handler(s.Ctx, s.WrapCreateRequest(didMsg, keys)) + if err != nil { + return nil, nil, err + } + + didResponse := types.MsgCreateDidResponse{} + if err := didResponse.Unmarshal(result.Data); err != nil { + return nil, nil, err + } + + return keys, didMsg, nil +} + +func (s *TestSetup) SendUpdateDid(msg *types.MsgUpdateDidPayload, keys []SignerKey) (*types.Did, error) { + // query Did + state, _ := s.Keeper.GetDid(&s.Ctx, msg.Id) + if len(msg.VersionId) == 0 { + msg.VersionId = state.Metadata.VersionId + } + + _, err := s.Handler(s.Ctx, s.WrapUpdateRequest(msg, keys)) + if err != nil { + return nil, err + } + + updated, _ := s.Keeper.GetDid(&s.Ctx, msg.Id) + return updated.UnpackDataAsDid() +} + +func (s *TestSetup) SendCreateDid(msg *types.MsgCreateDidPayload, keys map[string]ed25519.PrivateKey) (*types.Did, error) { + _, err := s.Handler(s.Ctx, s.WrapCreateRequest(msg, keys)) + if err != nil { + return nil, err + } + + created, _ := s.Keeper.GetDid(&s.Ctx, msg.Id) + return created.UnpackDataAsDid() +} + +func ConcatKeys(dst map[string]ed25519.PrivateKey, src map[string]ed25519.PrivateKey) map[string]ed25519.PrivateKey { + for k, v := range src { + dst[k] = v + } + + return dst +} + +func MapToListOfSignerKeys(mp map[string]ed25519.PrivateKey) []SignerKey { + rlist := []SignerKey{} + for k, v := range mp { + rlist = append(rlist, SignerKey{ + signer: k, + key: v, + }) + } + return rlist +} + +func (s TestSetup) CreateTestDIDs(keys map[string]KeyPair) error { + testDIDs := []struct { + signers []string + msg *types.MsgCreateDidPayload + }{ + { + signers: []string{AliceKey1}, + msg: &types.MsgCreateDidPayload{ + Id: AliceDID, + Authentication: []string{AliceKey1}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + }, + { + signers: []string{BobKey2}, + msg: &types.MsgCreateDidPayload{ + Id: BobDID, + Authentication: []string{ + BobKey1, + BobKey2, + BobKey3, + }, + CapabilityDelegation: []string{ + BobKey4, + }, + VerificationMethod: []*types.VerificationMethod{ + { + Id: BobKey1, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + { + Id: BobKey2, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + { + Id: BobKey3, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + { + Id: BobKey4, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + }, + }, + }, + { + signers: []string{CharlieKey2, BobKey2}, + msg: &types.MsgCreateDidPayload{ + Id: CharlieDID, + Authentication: []string{ + CharlieKey1, + CharlieKey2, + CharlieKey3, + }, + VerificationMethod: []*types.VerificationMethod{ + { + Id: CharlieKey1, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + { + Id: CharlieKey2, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + { + Id: CharlieKey3, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + }, + }, + }, + } + + for _, prefilled := range testDIDs { + msg := prefilled.msg + + for _, vm := range msg.VerificationMethod { + encoded, err := multibase.Encode(multibase.Base58BTC, keys[vm.Id].PublicKey) + if err != nil { + return err + } + vm.PublicKeyMultibase = encoded + } + + signerKeys := map[string]ed25519.PrivateKey{} + for _, signer := range prefilled.signers { + signerKeys[signer] = keys[signer].PrivateKey + } + + _, err := s.SendCreateDid(msg, signerKeys) + if err != nil { + return err + } + } + + return nil +} diff --git a/x/resource/tests/signature_verification_test.go b/x/resource/tests/signature_verification_test.go new file mode 100644 index 000000000..88a8c9bea --- /dev/null +++ b/x/resource/tests/signature_verification_test.go @@ -0,0 +1,142 @@ +package tests + +import ( + "crypto/ed25519" + "crypto/rand" + "fmt" + "reflect" + "testing" + + "github.com/btcsuite/btcutil/base58" + "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/stretchr/testify/require" +) + +func TestDIDDocControllerChanged(t *testing.T) { + setup := Setup() + + // Init did + aliceKeys, aliceDid, _ := setup.InitDid(AliceDID) + bobKeys, _, _ := setup.InitDid(BobDID) + + updatedDidDoc := setup.CreateToUpdateDid(aliceDid) + updatedDidDoc.Controller = append(updatedDidDoc.Controller, BobDID) + receivedDid, _ := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(ConcatKeys(aliceKeys, bobKeys))) + + // check + require.NotEqual(t, aliceDid.Controller, receivedDid.Controller) + require.NotEqual(t, []string{AliceDID, BobDID}, receivedDid.Controller) + require.Equal(t, []string{BobDID}, receivedDid.Controller) +} + +func TestDIDDocVerificationMethodChangedWithoutOldSignature(t *testing.T) { + setup := Setup() + + // Init did + _, aliceDid, _ := setup.InitDid(AliceDID) + bobKeys, _, _ := setup.InitDid(BobDID) + + updatedDidDoc := setup.CreateToUpdateDid(aliceDid) + updatedDidDoc.VerificationMethod[0].Type = Ed25519VerificationKey2020 + _, err := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(bobKeys)) + + // check + require.Error(t, err) + require.Equal(t, fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), err.Error()) +} + +func TestDIDDocVerificationMethodControllerChangedWithoutOldSignature(t *testing.T) { + setup := Setup() + + // Init did + _, aliceDid, _ := setup.InitDid(AliceDID) + bobKeys, _, _ := setup.InitDid(BobDID) + + updatedDidDoc := setup.CreateToUpdateDid(aliceDid) + updatedDidDoc.VerificationMethod[0].Controller = BobDID + _, err := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(bobKeys)) + + // check + require.Error(t, err) + require.Equal(t, fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), err.Error()) +} + +func TestDIDDocControllerChangedWithoutOldSignature(t *testing.T) { + setup := Setup() + + // Init did + _, aliceDid, _ := setup.InitDid(AliceDID) + bobKeys, _, _ := setup.InitDid(BobDID) + + updatedDidDoc := setup.CreateToUpdateDid(aliceDid) + updatedDidDoc.Controller = append(updatedDidDoc.Controller, BobDID) + _, err := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(bobKeys)) + + // check + require.Error(t, err) + require.Equal(t, fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), err.Error()) +} + +func TestDIDDocVerificationMethodDeletedWithoutOldSignature(t *testing.T) { + setup := Setup() + + // Init did + + ApubKey, AprivKey, _ := ed25519.GenerateKey(rand.Reader) + BpubKey, BprivKey, _ := ed25519.GenerateKey(rand.Reader) + aliceDid := setup.CreateDid(ApubKey, AliceDID) + bobDid := setup.CreateDid(BpubKey, BobDID) + + aliceDid.VerificationMethod = append(aliceDid.VerificationMethod, &types.VerificationMethod{ + Id: AliceKey2, + Controller: BobDID, + Type: Ed25519VerificationKey2020, + PublicKeyMultibase: "z" + base58.Encode(BpubKey), + }) + + aliceKeys := map[string]ed25519.PrivateKey{AliceKey1: AprivKey, BobKey1: BprivKey} + bobKeys := map[string]ed25519.PrivateKey{BobKey1: BprivKey} + _, _ = setup.SendCreateDid(bobDid, bobKeys) + _, _ = setup.SendCreateDid(aliceDid, aliceKeys) + + updatedDidDoc := setup.CreateToUpdateDid(aliceDid) + updatedDidDoc.VerificationMethod = []*types.VerificationMethod{aliceDid.VerificationMethod[0]} + updatedDidDoc.Authentication = []string{aliceDid.Authentication[0]} + _, err := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(bobKeys)) + + // check + require.Error(t, err) + require.Equal(t, fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), err.Error()) +} + +func TestDIDDocVerificationMethodDeleted(t *testing.T) { + setup := Setup() + + ApubKey, AprivKey, _ := ed25519.GenerateKey(rand.Reader) + BpubKey, BprivKey, _ := ed25519.GenerateKey(rand.Reader) + + aliceDid := setup.CreateDid(ApubKey, AliceDID) + bobDid := setup.CreateDid(BpubKey, BobDID) + + aliceDid.Authentication = append(aliceDid.Authentication, AliceKey2) + aliceDid.VerificationMethod = append(aliceDid.VerificationMethod, &types.VerificationMethod{ + Id: AliceKey2, + Controller: BobDID, + Type: Ed25519VerificationKey2020, + PublicKeyMultibase: "z" + base58.Encode(BpubKey), + }) + + aliceKeys := map[string]ed25519.PrivateKey{AliceKey1: AprivKey, BobKey1: BprivKey} + bobKeys := map[string]ed25519.PrivateKey{BobKey1: BprivKey} + _, _ = setup.SendCreateDid(bobDid, bobKeys) + _, _ = setup.SendCreateDid(aliceDid, aliceKeys) + + updatedDidDoc := setup.CreateToUpdateDid(aliceDid) + updatedDidDoc.Authentication = []string{aliceDid.Authentication[0]} + updatedDidDoc.VerificationMethod = []*types.VerificationMethod{aliceDid.VerificationMethod[0]} + receivedDid, _ := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(ConcatKeys(aliceKeys, bobKeys))) + + // check + require.NotEqual(t, len(aliceDid.VerificationMethod), len(receivedDid.VerificationMethod)) + require.True(t, reflect.DeepEqual(aliceDid.VerificationMethod[0], receivedDid.VerificationMethod[0])) +} diff --git a/x/resource/tests/update_did_test.go b/x/resource/tests/update_did_test.go new file mode 100644 index 000000000..b47eb5233 --- /dev/null +++ b/x/resource/tests/update_did_test.go @@ -0,0 +1,483 @@ +package tests + +import ( + "fmt" + "testing" + + "github.com/btcsuite/btcutil/base58" + "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/multiformats/go-multibase" + "github.com/stretchr/testify/require" +) + +func TestUpdateDid(t *testing.T) { + var err error + keys := map[string]KeyPair{ + AliceKey1: GenerateKeyPair(), + AliceKey2: GenerateKeyPair(), + BobKey1: GenerateKeyPair(), + BobKey2: GenerateKeyPair(), + BobKey3: GenerateKeyPair(), + BobKey4: GenerateKeyPair(), + CharlieKey1: GenerateKeyPair(), + CharlieKey2: GenerateKeyPair(), + CharlieKey3: GenerateKeyPair(), + CharlieKey4: GenerateKeyPair(), + ImposterKey1: GenerateKeyPair(), + } + + cases := []struct { + valid bool + name string + signerKeys []SignerKey + signers []string + msg *types.MsgUpdateDidPayload + errMsg string + }{ + { + valid: true, + name: "Valid: Key rotation works", + signerKeys: []SignerKey{ + { + signer: AliceKey1, + key: keys[AliceKey1].PrivateKey, + }, + { + signer: AliceKey1, + key: keys[AliceKey2].PrivateKey, + }, + }, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + PublicKeyMultibase: "z" + base58.Encode(keys[AliceKey2].PublicKey), + }, + }, + }, + }, + // VM and Controller replacing tests + { + valid: false, + name: "Not Valid: replacing controller and Verification method ID does not work without new sign", + signers: []string{AliceKey2, BobKey1, AliceKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{CharlieDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey2, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", CharlieDID), + }, + { + valid: true, + name: "Valid: replacing controller and Verification method ID works with all signatures", + signers: []string{AliceKey1, CharlieKey1, AliceKey2}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{CharlieDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey2, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", CharlieDID), + }, + // Verification method's tests + // cases: + // - replacing VM controller works + // - replacing VM controller does not work without new signature + // - replacing VM controller does not work without old signature ?????? + // - replacing VM doesn't work without new signature + // - replacing VM doesn't work without old signature + // - replacing VM works with all signatures + // --- adding new VM works + // --- adding new VM without new signature + // --- adding new VM without old signature + { + valid: true, + name: "Valid: Replacing VM controller works with one signature", + signers: []string{AliceKey1, BobKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + }, + }, + }, + { + valid: false, + name: "Not Valid: Replacing VM controller does not work without new signature", + signers: []string{AliceKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", BobDID), + }, + { + valid: false, + name: "Not Valid: Replacing VM does not work without new signature", + signers: []string{AliceKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey2, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one valid signature by %s (new version): signature is required but not found", AliceDID), + }, + { + valid: false, + name: "Not Valid: Replacing VM does not work without old signature", + signers: []string{AliceKey2}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey2, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one valid signature by %s (old version): signature is required but not found", AliceDID), + }, + { + valid: true, + name: "Not Valid: Replacing VM works with all signatures", + signers: []string{AliceKey1, AliceKey2}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey2, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + }, + // Adding VM + { + valid: true, + name: "Valid: Adding another verification method", + signers: []string{AliceKey1, BobKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{AliceDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + { + Id: AliceKey2, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + }, + }, + }, + { + valid: false, + name: "Not Valid: Adding another verification method without new sign", + signers: []string{AliceKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{AliceDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + { + Id: AliceKey2, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", BobDID), + }, + { + valid: false, + name: "Not Valid: Adding another verification method without old sign", + signers: []string{AliceKey2}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{AliceDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + { + Id: AliceKey2, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one valid signature by %s (old version): signature is required but not found", AliceDID), + }, + + // Controller's tests + // cases: + // - replacing Controller works with all signatures + // - replacing Controller doesn't work without old signature + // - replacing Controller doesn't work without new signature + // --- adding Controller works with all signatures + // --- adding Controller doesn't work without old signature + // --- adding Controller doesn't work without new signature + { + valid: true, + name: "Valid: Replace controller works with all signatures", + signers: []string{BobKey1, AliceKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{BobDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + }, + { + valid: false, + name: "Not Valid: Replace controller doesn't work without old signatures", + signers: []string{BobKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{BobDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), + }, + { + valid: false, + name: "Not Valid: Replace controller doesn't work without new signatures", + signers: []string{AliceKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{BobDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", BobDID), + }, + // add Controller + { + valid: true, + name: "Valid: Adding second controller works", + signers: []string{AliceKey1, CharlieKey3}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{AliceDID, CharlieDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + }, + { + valid: false, + name: "Not Valid: Adding controller without old signature", + signers: []string{BobKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{AliceDID, BobDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), + }, + { + valid: false, + name: "Not Valid: Add controller without new signature doesn't work", + signers: []string{AliceKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{AliceDID, BobDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", BobDID), + }, + + { + valid: true, + name: "Valid: Adding verification method with the same controller works", + signers: []string{AliceKey1, AliceKey2}, + msg: &types.MsgUpdateDidPayload{ + Id: AliceDID, + Controller: []string{AliceDID}, + VerificationMethod: []*types.VerificationMethod{ + { + Id: AliceKey2, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + { + Id: AliceKey1, + Type: Ed25519VerificationKey2020, + Controller: AliceDID, + }, + }, + }, + }, + { + valid: true, + name: "Valid: Keeping VM with controller different then subject untouched during update should not require Bob signature", + signers: []string{CharlieKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: CharlieDID, + Authentication: []string{ + CharlieKey1, + CharlieKey2, + CharlieKey3, + }, + + VerificationMethod: []*types.VerificationMethod{ + { + Id: CharlieKey1, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + { + Id: CharlieKey2, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + { + Id: CharlieKey3, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + { + Id: CharlieKey4, + Type: Ed25519VerificationKey2020, + Controller: CharlieDID, + }, + }, + }, + }, + { + valid: true, + name: "Valid: Removing verification method is possible with any kind of valid Bob's key", + signers: []string{BobKey1}, + msg: &types.MsgUpdateDidPayload{ + Id: BobDID, + VerificationMethod: []*types.VerificationMethod{ + { + Id: BobKey1, + Type: Ed25519VerificationKey2020, + Controller: BobDID, + }, + }, + }, + errMsg: fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", BobDID), + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + setup := InitEnv(t, keys) + msg := tc.msg + + for _, vm := range msg.VerificationMethod { + if vm.PublicKeyMultibase == "" { + vm.PublicKeyMultibase, err = multibase.Encode(multibase.Base58BTC, keys[vm.Id].PublicKey) + } + require.NoError(t, err) + } + + signerKeys := []SignerKey{} + if tc.signerKeys != nil { + signerKeys = tc.signerKeys + } else { + for _, signer := range tc.signers { + signerKeys = append(signerKeys, SignerKey{ + signer: signer, + key: keys[signer].PrivateKey, + }) + } + } + + did, err := setup.SendUpdateDid(msg, signerKeys) + + if tc.valid { + require.Nil(t, err) + require.Equal(t, tc.msg.Id, did.Id) + require.Equal(t, tc.msg.Controller, did.Controller) + require.Equal(t, tc.msg.VerificationMethod, did.VerificationMethod) + require.Equal(t, tc.msg.Authentication, did.Authentication) + require.Equal(t, tc.msg.AssertionMethod, did.AssertionMethod) + require.Equal(t, tc.msg.CapabilityInvocation, did.CapabilityInvocation) + require.Equal(t, tc.msg.CapabilityDelegation, did.CapabilityDelegation) + require.Equal(t, tc.msg.KeyAgreement, did.KeyAgreement) + require.Equal(t, tc.msg.AlsoKnownAs, did.AlsoKnownAs) + require.Equal(t, tc.msg.Service, did.Service) + require.Equal(t, tc.msg.Context, did.Context) + } else { + require.Error(t, err) + require.Equal(t, tc.errMsg, err.Error()) + } + }) + } +} diff --git a/x/resource/tests/utils.go b/x/resource/tests/utils.go new file mode 100644 index 000000000..5ba9b0b97 --- /dev/null +++ b/x/resource/tests/utils.go @@ -0,0 +1,48 @@ +package tests + +import ( + "math/rand" + "testing" + + "github.com/stretchr/testify/require" +) + +var letters = []rune("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") + +func randSeq(n int) string { + b := make([]rune, n) + for i := range b { + b[i] = letters[rand.Intn(len(letters))] + } + return string(b) +} + +func GenerateDID() string { + return "did:cheqd:test:" + randSeq(16) +} + +func GenerateFragment(did string) string { + return did + "#key-1" +} + +func GenerateTestKeys() map[string]KeyPair { + return map[string]KeyPair{ + AliceKey1: GenerateKeyPair(), + AliceKey2: GenerateKeyPair(), + BobKey1: GenerateKeyPair(), + BobKey2: GenerateKeyPair(), + BobKey3: GenerateKeyPair(), + BobKey4: GenerateKeyPair(), + CharlieKey1: GenerateKeyPair(), + CharlieKey2: GenerateKeyPair(), + CharlieKey3: GenerateKeyPair(), + ImposterKey1: GenerateKeyPair(), + } +} + +func InitEnv(t *testing.T, keys map[string]KeyPair) TestSetup { + setup := Setup() + err := setup.CreateTestDIDs(keys) + require.NoError(t, err) + return setup +} diff --git a/x/resource/types/codec.go b/x/resource/types/codec.go new file mode 100644 index 000000000..21d800df5 --- /dev/null +++ b/x/resource/types/codec.go @@ -0,0 +1,37 @@ +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(&MsgCreateDid{}, "cheqd/CreateDid", nil) + cdc.RegisterConcrete(&MsgUpdateDid{}, "cheqd/UpdateDid", nil) + + // State value data + cdc.RegisterInterface((*StateValueData)(nil), nil) + cdc.RegisterConcrete(&Did{}, "cheqd/Did", nil) +} + +func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + // Sdk messages + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgCreateDid{}, + &MsgUpdateDid{}, + ) + + // State value data + registry.RegisterInterface("StateValueData", (*StateValueData)(nil)) + registry.RegisterImplementations((*StateValueData)(nil), &Did{}) + + 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..48bb7fc60 --- /dev/null +++ b/x/resource/types/error.go @@ -0,0 +1,22 @@ +package types + +// DONTCOVER + +import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// x/cheqd module sentinel errors +var ( + ErrBadRequest = sdkerrors.Register(ModuleName, 1000, "bad request") + ErrInvalidSignature = sdkerrors.Register(ModuleName, 1100, "invalid signature detected") + ErrSignatureNotFound = sdkerrors.Register(ModuleName, 1101, "signature is required but not found") + ErrDidDocExists = sdkerrors.Register(ModuleName, 1200, "DID Doc exists") + ErrDidDocNotFound = sdkerrors.Register(ModuleName, 1201, "DID Doc not found") + ErrVerificationMethodNotFound = sdkerrors.Register(ModuleName, 1202, "verification method not found") + ErrUnexpectedDidVersion = sdkerrors.Register(ModuleName, 1203, "unexpected DID version") + ErrBasicValidation = sdkerrors.Register(ModuleName, 1205, "basic validation failed") + ErrNamespaceValidation = sdkerrors.Register(ModuleName, 1206, "DID namespace validation failed") + ErrUnpackStateValue = sdkerrors.Register(ModuleName, 1300, "invalid did state value") + ErrInternal = sdkerrors.Register(ModuleName, 1500, "internal error") +) diff --git a/x/resource/types/genesis.go b/x/resource/types/genesis.go new file mode 100644 index 000000000..e6a9b11df --- /dev/null +++ b/x/resource/types/genesis.go @@ -0,0 +1,36 @@ +package types + +import ( + "fmt" +) + +const DefaultDidNamespace = "testnet" + +// DefaultGenesis returns the default Capability genesis state +func DefaultGenesis() *GenesisState { + return &GenesisState{ + DidList: []*StateValue{}, + DidNamespace: DefaultDidNamespace, + } +} + +// Validate performs basic genesis state validation returning an error upon any +// failure. +func (gs GenesisState) Validate() error { + didIdMap := make(map[string]bool) + + for _, elem := range gs.DidList { + did, err := elem.UnpackDataAsDid() + if err != nil { + return err + } + + if _, ok := didIdMap[did.Id]; ok { + return fmt.Errorf("duplicated id for did") + } + + didIdMap[did.Id] = true + } + + return nil +} diff --git a/x/resource/types/keys.go b/x/resource/types/keys.go new file mode 100644 index 000000000..502b02cae --- /dev/null +++ b/x/resource/types/keys.go @@ -0,0 +1,27 @@ +package types + +const ( + // ModuleName defines the module name + ModuleName = "cheqd" + + // 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 + + DidMethod = ModuleName +) + +func KeyPrefix(p string) []byte { + return []byte(p) +} + +const ( + DidKey = "did:" + DidCountKey = "did-count:" + DidNamespaceKey = "did-namespace:" +) diff --git a/x/resource/types/query.go b/x/resource/types/query.go new file mode 100644 index 000000000..8a6cb7eb4 --- /dev/null +++ b/x/resource/types/query.go @@ -0,0 +1,5 @@ +package types + +const ( + QueryGetDid = "get-did" +) diff --git a/x/resource/utils/crypto.go b/x/resource/utils/crypto.go new file mode 100644 index 000000000..0294f3bc3 --- /dev/null +++ b/x/resource/utils/crypto.go @@ -0,0 +1,86 @@ +package utils + +import ( + "crypto" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/rsa" + "errors" + "fmt" + "reflect" + + "filippo.io/edwards25519" + + "github.com/lestrrat-go/jwx/jwk" +) + +func ValidateJWK(jwk_string string) error { + var raw interface{} + err := jwk.ParseRawKey([]byte(jwk_string), &raw) + if err != nil { + return fmt.Errorf("can't parse jwk: %s", err.Error()) + } + + switch key := raw.(type) { + case *rsa.PublicKey: + break + case *ecdsa.PublicKey: + break + case ed25519.PublicKey: + err := ValidateEd25519PubKey(key) + if err != nil { + return err + } + default: + return fmt.Errorf("unsupported jwk type: %s. supported types are: rsa/pub, ecdsa/pub, ed25519/pub", reflect.TypeOf(raw).Name()) + } + + return nil +} + +func ValidateEd25519PubKey(keyBytes []byte) error { + if l := len(keyBytes); l != ed25519.PublicKeySize { + return fmt.Errorf("ed25519: bad public key length: %d", l) + } + _, err := (&edwards25519.Point{}).SetBytes(keyBytes) + if err != nil { + return err + } + return nil +} + +func VerifyED25519Signature(pubKey ed25519.PublicKey, message []byte, signature []byte) error { + valid := ed25519.Verify(pubKey, message, signature) + if !valid { + return errors.New("invalid ed25519 signature") + } + + return nil +} + +// VerifyRSASignature uses PSS padding and SHA256 digest +// A good explanation of different paddings: https://security.stackexchange.com/questions/183179/what-is-rsa-oaep-rsa-pss-in-simple-terms +func VerifyRSASignature(pubKey rsa.PublicKey, message []byte, signature []byte) error { + hasher := crypto.SHA256.New() + hasher.Write(message) + digest := hasher.Sum(nil) + + err := rsa.VerifyPSS(&pubKey, crypto.SHA256, digest, signature, nil) + if err != nil { + return err + } + return nil +} + +// VerifyECDSASignature uses ASN1 to decode r and s, SHA265 to calculate message digest +func VerifyECDSASignature(pubKey ecdsa.PublicKey, message []byte, signature []byte) error { + hasher := crypto.SHA256.New() + hasher.Write(message) + digest := hasher.Sum(nil) + + ok := ecdsa.VerifyASN1(&pubKey, digest, signature) + if !ok { + return errors.New("invalid ecdsa signature") + } + return nil +} diff --git a/x/resource/utils/crypto_test.go b/x/resource/utils/crypto_test.go new file mode 100644 index 000000000..c8feb4f08 --- /dev/null +++ b/x/resource/utils/crypto_test.go @@ -0,0 +1,60 @@ +package utils + +import ( + "testing" + + "github.com/multiformats/go-multibase" + "github.com/stretchr/testify/require" +) + +func TestValidateEd25519PubKey(t *testing.T) { + cases := []struct { + name string + key string + valid bool + errorMsg string + }{ + {"Valid: General Ed25519 public key", "zF1hVGXXK9rmx5HhMTpGnGQJiab9qrFJbQXBRhSmYjQWX", true, ""}, + {"Valid: General Ed25519 public key", "zF1hVGXXK9rmx5HhMTpGnGQJiab9qr1111111111111", false, "ed25519: bad public key length: 31"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, keyBytes, _ := multibase.Decode(tc.key) + err := ValidateEd25519PubKey(keyBytes) + + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + require.Contains(t, err.Error(), tc.errorMsg) + } + }) + } +} + +func TestValidateJwk(t *testing.T) { + cases := []struct { + name string + key string + valid bool + errorMsg string + }{ + {"positive ed25519", "{\"crv\":\"Ed25519\",\"kty\":\"OKP\",\"x\":\"9Ov80OqMlNrILAUG8DBBlYQ1rUhp7wDomr2I5muzpTc\"}", true, ""}, + {"positive ecdsa", "{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"tcEgxIPyYMiyR2_Vh_YMYG6Grg7axhK2N8JjWta5C0g\",\"y\":\"imiXD9ahVA_MKY066TrNA9r6l35lRrerP6JRey5SryQ\"}", true, ""}, + {"positive rsa", "{\"e\":\"AQAB\",\"kty\":\"RSA\",\"n\":\"skKXRn44WN2DpXDwm4Ip25kIAGRA8y3iXlaoAhPmFiuSDkx97lXcJYrjxX0wSfehgCiSoZOBv6mFzgSVv0_pXQ6zI35xi2dsbexrc87m7Q24q2chpG33ttnVwQkoXrrm0zDzSX32EVxYQyTu9aWp-zxUdAWcrWUarT24RmgjU78v8JmUzkLmwbzsEImnIZ8Hce2ruisAmuAQBVVA4bWwQm_x1KPoQW-TP5_UR3gGugvf0XrQfMJaVpcxcJ9tduMUw6ffZOsqgbvAiZYnrezxSIjnd5lFTFBIEYdGR6ZgjYZoWvQB7U72o_TJoka-zfSODOUbxNBvxvFhA3uhoo3ZKw\"}", true, ""}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := ValidateJWK(tc.key) + + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + require.Contains(t, err.Error(), tc.errorMsg) + } + }) + } +} diff --git a/x/resource/utils/did.go b/x/resource/utils/did.go new file mode 100644 index 000000000..d33528a1c --- /dev/null +++ b/x/resource/utils/did.go @@ -0,0 +1,98 @@ +package utils + +import ( + "errors" + "fmt" + "regexp" + "strings" +) + +var ( + SplitDIDRegexp, _ = regexp.Compile(`^did:([^:]+?)(:([^:]+?))?:([^:]+)$`) + DidNamespaceRegexp, _ = regexp.Compile(`^[a-zA-Z0-9]*$`) +) + +// TrySplitDID Validates generic format of DID. It doesn't validate method, name and id content. +// Call ValidateDID for further validation. +func TrySplitDID(did string) (method string, namespace string, id string, err error) { + // Example: did:cheqd:testnet:base58str1ng1111 + // match [0] - the whole string + // match [1] - cheqd - method + // match [2] - :testnet + // match [3] - testnet - namespace + // match [4] - base58str1ng1111 - id + matches := SplitDIDRegexp.FindAllStringSubmatch(did, -1) + if len(matches) != 1 { + return "", "", "", errors.New("unable to split did into method, namespace and id") + } + + match := matches[0] + return match[1], match[3], match[4], nil +} + +func MustSplitDID(did string) (method string, namespace string, id string) { + method, namespace, id, err := TrySplitDID(did) + if err != nil { + panic(err.Error()) + } + return +} + +func JoinDID(method, namespace, id string) string { + res := "did:" + method + + if namespace != "" { + res = res + ":" + namespace + } + + return res + ":" + id +} + +// ValidateDID checks method and allowed namespaces only when the corresponding parameters are specified. +func ValidateDID(did string, method string, allowedNamespaces []string) error { + sMethod, sNamespace, sUniqueId, err := TrySplitDID(did) + if err != nil { + return err + } + + // check method + if method != "" && method != sMethod { + return fmt.Errorf("did method must be: %s", method) + } + + // check namespaces + if !DidNamespaceRegexp.MatchString(sNamespace) { + return errors.New("invalid did namespace") + } + + if len(allowedNamespaces) > 0 && !Contains(allowedNamespaces, sNamespace) { + return fmt.Errorf("did namespace must be one of: %s", strings.Join(allowedNamespaces[:], ", ")) + } + + // check unique-id + err = ValidateUniqueId(sUniqueId) + if err != nil { + return err + } + + 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") + } + + // Base58 check + if err := ValidateBase58(uniqueId); err != nil { + return fmt.Errorf("unique id must be valid base58 string: %s", err) + } + + return nil +} + +func IsValidDID(did string, method string, allowedNamespaces []string) bool { + err := ValidateDID(did, method, allowedNamespaces) + return err == nil +} diff --git a/x/resource/utils/did_test.go b/x/resource/utils/did_test.go new file mode 100644 index 000000000..9902a9915 --- /dev/null +++ b/x/resource/utils/did_test.go @@ -0,0 +1,97 @@ +package utils + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIsDid(t *testing.T) { + cases := []struct { + name string + valid bool + did string + method string + allowedNS []string + }{ + {"Valid: Inputs: Method and namespace are set", true, "did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"testnet"}}, + {"Valid: Inputs: Method and namespaces are set", true, "did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"testnet", "mainnet"}}, + {"Valid: Inputs: Method not set", true, "did:cheqd:testnet:123456789abcdefg", "", []string{"testnet"}}, + {"Valid: Inputs: Method and namespaces are empty", true, "did:cheqd:testnet:123456789abcdefg", "", []string{}}, + {"Valid: Namespace is absent in DID", true, "did:cheqd:123456789abcdefg", "", []string{}}, + // Generic method validation + {"Valid: Inputs: Method is not set and passed for NOTcheqd", true, "did:NOTcheqd:123456789abcdefg", "", []string{}}, + {"Valid: Inputs: Method and Namespaces are not set and passed for NOTcheqd", true, "did:NOTcheqd:123456789abcdefg123456789abcdefg", "", []string{}}, + + {"Valid: Inputs: Order of namespaces changed", true, "did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"mainnet", "testnet"}}, + // Wrong splitting (^did:([^:]+?)(:([^:]+?))?:([^:]+)$) + {"Not valid: DID is not started from 'did'", false, "did123:cheqd:::123456789abcdefg", "cheqd", []string{"testnet"}}, + {"Not valid: empty namespace", false, "did:cheqd::123456789abcdefg", "cheqd", []string{"testnet"}}, + {"Not valid: a lot of ':'", false, "did:cheqd:::123456789abcdefg", "cheqd", []string{"testnet"}}, + {"Not valid: several DIDs in one string", false, "did:cheqd:testnet:123456789abcdefg:did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"testnet"}}, + // Wrong method + {"Not valid: method in DID is not the same as from Inputs", false, "did:NOTcheqd:testnet:123456789abcdefg", "cheqd", []string{"mainnet", "testnet"}}, + {"Not valid: method in Inputs is not the same as from DID", false, "did:cheqd:testnet:123456789abcdefg", "NOTcheqd", []string{"mainnet", "testnet"}}, + // Wrong namespace (^[a-zA-Z0-9]*) + {"Not valid: / is not allowed for namespace", false, "did:cheqd:testnet/:123456789abcdefg", "cheqd", []string{}}, + {"Not valid: _ is not allowed for namespace", false, "did:cheqd:testnet_:123456789abcdefg", "cheqd", []string{}}, + {"Not valid: % is not allowed for namespace", false, "did:cheqd:testnet%:123456789abcdefg", "cheqd", []string{}}, + {"Not valid: * is not allowed for namespace", false, "did:cheqd:testnet*:123456789abcdefg", "cheqd", []string{}}, + {"Not valid: & is not allowed for namespace", false, "did:cheqd:testnet&:123456789abcdefg", "cheqd", []string{}}, + {"Not valid: @ is not allowed for namespace", false, "did:cheqd:testnet@:123456789abcdefg", "cheqd", []string{}}, + {"Not valid: namespace from Inputs is not the same as from DID", false, "did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"not_testnet"}}, + // Base58 checks (^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]*$) + {"Not valid: O - is not allowed for UniqueID", false, "did:cheqd:testnet:123456789abcdefO", "cheqd", []string{}}, + {"Not valid: I - is not allowed for UniqueID", false, "did:cheqd:testnet:123456789abcdefI", "cheqd", []string{}}, + {"Not valid: l - is not allowed for UniqueID", false, "did:cheqd:testnet:123456789abcdefl", "cheqd", []string{}}, + {"Not valid: 0 - is not allowed for UniqueID", false, "did:cheqd:testnet:123456789abcdef0", "cheqd", []string{}}, + // Length checks (should be exactly 16 or 32) + {"Not valid: UniqueID less then 16 symbols", false, "did:cheqd:testnet:123", "cheqd", []string{}}, + {"Not valid: UniqueID more then 16 symbols but less then 32", false, "did:cheqd:testnet:123456789abcdefgABCDEF", "cheqd", []string{}}, + {"Not valid: UniqueID more then 32 symbols", false, "did:cheqd:testnet:123456789abcdefg123456789abcdefgABCDEF", "cheqd", []string{}}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + isDid := IsValidDID(tc.did, tc.method, tc.allowedNS) + + if tc.valid { + require.True(t, isDid) + } else { + require.False(t, isDid) + } + }) + } +} + +func TestSplitJoin(t *testing.T) { + cases := []string{ + "did:cheqd:testnet:123456789abcdefg", + "did:cheqd:testnet:123456789abcdefg", + "did:cheqd:testnet:123456789abcdefg", + "did:cheqd:testnet:123456789abcdefg", + "did:cheqd:123456789abcdefg", + "did:NOTcheqd:123456789abcdefg", + "did:NOTcheqd:123456789abcdefg123456789abcdefg", + "did:cheqd:testnet:123456789abcdefg", + } + + for _, tc := range cases { + // Test split/join + t.Run("split/join "+tc, func(t *testing.T) { + method, namespace, id := MustSplitDID(tc) + require.Equal(t, tc, JoinDID(method, namespace, id)) + }) + } +} + +func TestMustSplitDID(t *testing.T) { + require.Panicsf(t, func() { + MustSplitDID("not did") + }, "must panic") + + method, namespace, id := MustSplitDID("did:cheqd:mainnet:qqqqqqqqqqqqqqqq") + require.Equal(t, "cheqd", method) + require.Equal(t, "mainnet", namespace) + require.Equal(t, "qqqqqqqqqqqqqqqq", id) +} diff --git a/x/resource/utils/did_url.go b/x/resource/utils/did_url.go new file mode 100644 index 000000000..a46527f10 --- /dev/null +++ b/x/resource/utils/did_url.go @@ -0,0 +1,118 @@ +package utils + +import ( + "errors" + "fmt" + "regexp" +) + +// That for groups: +// Example: did:cheqd:testnet:fafdsffq11213343/path-to-s/ome-external-resource?query#key1??? +// 1 - [^/?#]* - all the symbols except / and ? and # . This is the DID part (did:cheqd:testnet:fafdsffq11213343) +// 2 - [^?#]* - all the symbols except ? and #. it means te section started from /, path-abempty (/path-to-s/ome-external-resource) +// 3 - \?([^#]*) - group for `query` part but with ? symbol (?query) +// 4 - [^#]* - group inside query string, match only exact query (query) +// 5 - #([^#]+[\$]?) - group for fragment, starts with #, includes # (#key1???) +// 6 - [^#]+[\$]? - fragment only (key1???) +// Number of queries is not limited. +var SplitDIDURLRegexp, _ = regexp.Compile(`([^/?#]*)?([^?#]*)(\?([^#]*))?(#([^#]+$))?$`) + +var ( + DIDPathAbemptyRegexp, _ = regexp.Compile(`^([/a-zA-Z0-9\-\.\_\~\!\$\&\'\(\)\*\+\,\;\=\:\@]*|(%[0-9A-Fa-f]{2})*)*$`) + DIDQueryRegexp, _ = regexp.Compile(`^([/a-zA-Z0-9\-\.\_\~\!\$\&\'\(\)\*\+\,\;\=\:\@\/\?]*|(%[0-9A-Fa-f]{2})*)*$`) + DIDFragmentRegexp, _ = regexp.Compile(`^([/a-zA-Z0-9\-\.\_\~\!\$\&\'\(\)\*\+\,\;\=\:\@\/\?]*|(%[0-9A-Fa-f]{2})*)*$`) +) + +// TrySplitDIDUrl Validates generic format of DIDUrl. It doesn't validate path, query and fragment content. +// Call ValidateDIDUrl for further validation. +func TrySplitDIDUrl(didUrl string) (did string, path string, query string, fragment string, err error) { + matches := SplitDIDURLRegexp.FindAllStringSubmatch(didUrl, -1) + + if len(matches) != 1 { + return "", "", "", "", errors.New("unable to split did url into did, path, query and fragment") + } + + match := matches[0] + + return match[1], match[2], match[4], match[6], nil +} + +func MustSplitDIDUrl(didUrl string) (did string, path string, query string, fragment string) { + did, path, query, fragment, err := TrySplitDIDUrl(didUrl) + if err != nil { + panic(err.Error()) + } + return +} + +func JoinDIDUrl(did string, path string, query string, fragment string) string { + res := did + path + + if query != "" { + res = res + "?" + query + } + + if fragment != "" { + res = res + "#" + fragment + } + + return res +} + +// ValidateDIDUrl checks method and allowed namespaces only when the corresponding parameters are specified. +func ValidateDIDUrl(didUrl string, method string, allowedNamespaces []string) error { + did, path, query, fragment, err := TrySplitDIDUrl(didUrl) + if err != nil { + return err + } + + // Validate DID + err = ValidateDID(did, method, allowedNamespaces) + if err != nil { + return err + } + // Validate path + err = ValidatePath(path) + if err != nil { + return err + } + // Validate query + err = ValidateQuery(query) + if err != nil { + return err + } + // Validate fragment + err = ValidateFragment(fragment) + if err != nil { + return err + } + + return nil +} + +func ValidateFragment(fragment string) error { + if !DIDFragmentRegexp.MatchString(fragment) { + return fmt.Errorf("did url fragmnt must match the following regexp: %s", DIDFragmentRegexp) + } + return nil +} + +func ValidateQuery(query string) error { + if !DIDQueryRegexp.MatchString(query) { + return fmt.Errorf("did url query must match the following regexp: %s", DIDQueryRegexp) + } + return nil +} + +func ValidatePath(path string) error { + if !DIDPathAbemptyRegexp.MatchString(path) { + return fmt.Errorf("did url path abempty must match the following regexp: %s", DIDPathAbemptyRegexp) + } + return nil +} + +func IsValidDIDUrl(didUrl string, method string, allowedNamespaces []string) bool { + err := ValidateDIDUrl(didUrl, method, allowedNamespaces) + + return nil == err +} diff --git a/x/resource/utils/did_url_test.go b/x/resource/utils/did_url_test.go new file mode 100644 index 000000000..0d1f1e4df --- /dev/null +++ b/x/resource/utils/did_url_test.go @@ -0,0 +1,93 @@ +package utils + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIsDidURL(t *testing.T) { + cases := []struct { + name string + valid bool + didUrl string + }{ + // Path: all the possible symbols + {"Valid: the whole alphabet for path", true, "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff"}, + {"Valid: several paths", true, "did:cheqd:testnet:123456789abcdefg/path/to/some/other/place/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff/"}, + {"Valid: the whole alphabet with query", true, "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query"}, + {"Valid: the whole alphabet with query and fragment", true, "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query#fragment"}, + {"Valid: each possible symbols as a path", true, "did:cheqd:testnet:123456789abcdefg/12/ab/AB/-/./_/~/!/$/&/'/(/)/*/+/,/;/=/:/@/%20/%ff"}, + {"Valid: empty path", true, "did:cheqd:testnet:123456789abcdefg/"}, + // Query: all the possible variants + {"Valid: the whole alphabet for query", true, "did:cheqd:testnet:123456789abcdefg/path?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?"}, + {"Valid: the whole alphabet for query and another query", true, "did:cheqd:testnet:123456789abcdefg/path?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query=2?query=3/query=%A4"}, + // Fragment: + {"Valid: the whole alphabet for fragment", true, "did:cheqd:testnet:123456789abcdefg/path?query#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff"}, + {"Valid: the whole alphabet with query and apth", true, "did:cheqd:testnet:123456789abcdefg/path?query#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?"}, + {"Valid: only fragment", true, "did:cheqd:testnet:123456789abcdefg#fragment"}, + {"Valid: only query", true, "did:cheqd:testnet:123456789abcdefg?query"}, + // Wrong cases + {"Not valid: wrong HEXDIG for path (pct-encoded phrase)", false, "did:cheqd:testnet:123456789abcdefg/path%20%zz"}, + {"Not valid: wrong HEXDIG for query (pct-encoded phrase)", false, "did:cheqd:testnet:123456789abcdefg/path?query%20%zz"}, + {"Not valid: wrong HEXDIG for fragment (pct-encoded phrase)", false, "did:cheqd:testnet:123456789abcdefg/path?query#fragment%20%zz"}, + // Wrong splitting (^did:([^:]+?)(:([^:]+?))?:([^:]+)$) + {"Not valid: starts with not 'did'", false, "did123:cheqd:::123456789abcdefg/path?query#fragment"}, + {"Not valid: empty namespace", false, "did:cheqd::123456789abcdefg/path?query#fragment"}, + {"Not valid: a lot of ':'", false, "did:cheqd:::123456789abcdefg/path?query#fragment"}, + {"Not valid: two DIDs in one", false, "did:cheqd:testnet:123456789abcdefg:did:cheqd:testnet:123456789abcdefg/path?query#fragment"}, + // Wrong namespace (^[a-zA-Z0-9]*) + {"Not valid: / - is not allowed for namespace", false, "did:cheqd:testnet/:123456789abcdefg/path?query#fragment"}, + {"Not valid: _ - is not allowed for namespace", false, "did:cheqd:testnet_:123456789abcdefg/path?query#fragment"}, + {"Not valid: % - is not allowed for namespace", false, "did:cheqd:testnet%:123456789abcdefg/path?query#fragment"}, + {"Not valid: * - is not allowed for namespace", false, "did:cheqd:testnet*:123456789abcdefg/path?query#fragment"}, + {"Not valid: & - is not allowed for namespace", false, "did:cheqd:testnet&:123456789abcdefg/path?query#fragment"}, + {"Not valid: @ - is not allowed for namespace", false, "did:cheqd:testnet@/:123456789abcdefg/path?query#fragment"}, + // Base58 checks (^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]*$) + {"Not valid: O - is not allowed for base58", false, "did:cheqd:testnet:123456789abcdefO/path?query#fragment"}, + {"Not valid: I - is not allowed for base58", false, "did:cheqd:testnet:123456789abcdefI/path?query#fragment"}, + {"Not valid: l - is not allowed for base58", false, "did:cheqd:testnet:123456789abcdefl/path?query#fragment"}, + {"Not valid: 0 - is not allowed for base58", false, "did:cheqd:testnet:123456789abcdef0/path?query#fragment"}, + // Length checks (should be exactly 16 or 32) + {"Not valid: UniqueID less then 16 symbols", false, "did:cheqd:testnet:123/path?query#fragment"}, + {"Not valid: UniqueID more then 16 symbols but less then 32", false, "did:cheqd:testnet:123456789abcdefgABCDEF/path?query#fragment"}, + {"Not valid: UniqueID more then 32 symbols", false, "did:cheqd:testnet:123456789abcdefg123456789abcdefgABCDEF/path?query#fragment"}, + {"Not valid: Split should return error", false, "qwerty"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + isDid := IsValidDIDUrl(tc.didUrl, "", []string{}) + + if tc.valid { + require.True(t, isDid) + } else { + require.False(t, isDid) + } + }) + } +} + +func TestDidURLJoin(t *testing.T) { + cases := []string{ + "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff", + "did:cheqd:testnet:123456789abcdefg/path/to/some/other/place/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff/", + "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query", + "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query#fragment", + "did:cheqd:testnet:123456789abcdefg/12/ab/AB/-/./_/~/!/$/&/'/(/)/*/+/,/;/=/:/@/%20/%ff", + "did:cheqd:testnet:123456789abcdefg/", + "did:cheqd:testnet:123456789abcdefg/path?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?", + "did:cheqd:testnet:123456789abcdefg/path?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query=2?query=3/query=%A4", + "did:cheqd:testnet:123456789abcdefg/path?query#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff", + "did:cheqd:testnet:123456789abcdefg/path?query#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?", + "did:cheqd:testnet:123456789abcdefg#fragment", + "did:cheqd:testnet:123456789abcdefg?query", + } + + for _, tc := range cases { + t.Run("split/join"+tc, func(t *testing.T) { + did, path, query, fragment := MustSplitDIDUrl(tc) + require.Equal(t, tc, JoinDIDUrl(did, path, query, fragment)) + }) + } +} diff --git a/x/resource/utils/encoding.go b/x/resource/utils/encoding.go new file mode 100644 index 000000000..080f883d4 --- /dev/null +++ b/x/resource/utils/encoding.go @@ -0,0 +1,30 @@ +package utils + +import ( + "fmt" + + "github.com/multiformats/go-multibase" +) + +func ValidateMultibase(data string) error { + _, _, err := multibase.Decode(data) + return err +} + +func ValidateMultibaseEncoding(data string, expectedEncoding multibase.Encoding) error { + actualEncoding, _, err := multibase.Decode(data) + if err != nil { + return err + } + + if actualEncoding != expectedEncoding { + return fmt.Errorf("invalid actualEncoding. expected: %s actual: %s", + multibase.EncodingToStr[expectedEncoding], multibase.EncodingToStr[actualEncoding]) + } + + return nil +} + +func ValidateBase58(data string) error { + return ValidateMultibaseEncoding(string(multibase.Base58BTC)+data, multibase.Base58BTC) +} diff --git a/x/resource/utils/encoding_test.go b/x/resource/utils/encoding_test.go new file mode 100644 index 000000000..d06f74dda --- /dev/null +++ b/x/resource/utils/encoding_test.go @@ -0,0 +1,115 @@ +package utils + +import ( + "encoding/json" + "testing" + + "github.com/multiformats/go-multibase" + "github.com/stretchr/testify/require" +) + +type TestJWKKey struct { + Kty string `json:"kty"` + N string `json:"n"` + Use string `json:"use"` + Alg string `json:"alg"` + E string `json:"e"` + Kid string `json:"kid"` +} + +var ValidJWKKey = TestJWKKey{ + Kty: "RSA", + N: "o76AudS2rsCvlz_3D47sFkpuz3NJxgLbXr1cHdmbo9xOMttPMJI97f0rHiSl9stltMi87KIOEEVQWUgMLaWQNaIZThgI1seWDAGRw59AO5sctgM1wPVZYt40fj2Qw4KT7m4RLMsZV1M5NYyXSd1lAAywM4FT25N0RLhkm3u8Hehw2Szj_2lm-rmcbDXzvjeXkodOUszFiOqzqBIS0Bv3c2zj2sytnozaG7aXa14OiUMSwJb4gmBC7I0BjPv5T85CH88VOcFDV51sO9zPJaBQnNBRUWNLh1vQUbkmspIANTzj2sN62cTSoxRhSdnjZQ9E_jraKYEW5oizE9Dtow4EvQ", + Use: "sig", + Alg: "RS256", + E: "AQAB", + Kid: "6a8ba5652a7044121d4fedac8f14d14c54e4895b", +} + +var NotValidJWKKey = TestJWKKey{ + Kty: "SomeOtherKeyType", + N: "o76AudS2rsCvlz_3D47sFkpuz3NJxgLbXr1cHdmbo9xOMttPMJI97f0rHiSl9stltMi87KIOEEVQWUgMLaWQNaIZThgI1seWDAGRw59AO5sctgM1wPVZYt40fj2Qw4KT7m4RLMsZV1M5NYyXSd1lAAywM4FT25N0RLhkm3u8Hehw2Szj_2lm-rmcbDXzvjeXkodOUszFiOqzqBIS0Bv3c2zj2sytnozaG7aXa14OiUMSwJb4gmBC7I0BjPv5T85CH88VOcFDV51sO9zPJaBQnNBRUWNLh1vQUbkmspIANTzj2sN62cTSoxRhSdnjZQ9E_jraKYEW5oizE9Dtow4EvQ", + Use: "sig", + Alg: "RS256", + E: "AQAB", + Kid: "6a8ba5652a7044121d4fedac8f14d14c54e4895b", +} + +var ( + ValidJWKByte, _ = json.Marshal(ValidJWKKey) + NotValidJWKByte, _ = json.Marshal(NotValidJWKKey) +) + +func TestValidateMultibase(t *testing.T) { + cases := []struct { + name string + data string + encoding multibase.Encoding + valid bool + }{ + {"Valid: General pmbkey", "zABCDEFG123456789", multibase.Base58BTC, true}, + {"Not Valid: cannot be empty", "", multibase.Base58BTC, false}, + {"Not Valid: without z but base58", "ABCDEFG123456789", multibase.Base58BTC, false}, + {"Not Valid: without z and not base58", "OIl0ABCDEFG123456789", multibase.Base58BTC, false}, + {"Not Valid: with z but not base58", "zOIl0ABCDEFG123456789", multibase.Base58BTC, false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := ValidateMultibase(tc.data) + + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} + +func TestValidateBase58(t *testing.T) { + cases := []struct { + name string + data string + valid bool + }{ + {"Valid: General pmbkey", "ABCDEFG123456789", true}, + {"Not Valid: cannot be empty", "", false}, + {"Not Valid: not base58", "OIl0ABCDEFG123456789", false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := ValidateBase58(tc.data) + + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} + +func TestValidateJWK(t *testing.T) { + cases := []struct { + name string + data string + valid bool + }{ + {"Valid: General jwk", string(ValidJWKByte), true}, + {"Not Valid: Bad jwk", string(NotValidJWKByte), false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := ValidateJWK(tc.data) + + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} diff --git a/x/resource/utils/proto.go b/x/resource/utils/proto.go new file mode 100644 index 000000000..e25f37e8a --- /dev/null +++ b/x/resource/utils/proto.go @@ -0,0 +1,8 @@ +package utils + +import "github.com/gogo/protobuf/proto" + +// MsgTypeURL returns the TypeURL of a `proto.Message`. +func MsgTypeURL(msg proto.Message) string { + return "/" + proto.MessageName(msg) +} diff --git a/x/resource/utils/proto_test.go b/x/resource/utils/proto_test.go new file mode 100644 index 000000000..d62252a9b --- /dev/null +++ b/x/resource/utils/proto_test.go @@ -0,0 +1,12 @@ +package utils + +import ( + "testing" + + bank_types "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/stretchr/testify/assert" +) + +func Test_MsgTypeUrl(t *testing.T) { + assert.Equal(t, "/cosmos.bank.v1beta1.DenomUnit", MsgTypeURL(&bank_types.DenomUnit{})) +} diff --git a/x/resource/utils/str.go b/x/resource/utils/str.go new file mode 100644 index 000000000..723d539f4 --- /dev/null +++ b/x/resource/utils/str.go @@ -0,0 +1,98 @@ +package utils + +import "sort" + +func IndexOf(array []string, searchElement string, fromIndex int) int { + for i, v := range array[fromIndex:] { + if v == searchElement { + return fromIndex + i + } + } + + return -1 +} + +func Contains(vs []string, t string) bool { + return IndexOf(vs, t, 0) >= 0 +} + +func Filter(vs []string, f func(string) bool) []string { + vsf := make([]string, 0) + for _, v := range vs { + if f(v) { + vsf = append(vsf, v) + } + } + return vsf +} + +func Subtract(minuend []string, subtrahend []string) []string { + m := map[string]bool{} + + for _, v := range minuend { + m[v] = true + } + + for _, v := range subtrahend { + delete(m, v) + } + + result := make([]string, 0, len(m)) + + for k := range m { + result = append(result, k) + } + + return result +} + +// Unique returns a copy of the passed array with duplicates removed +func Unique(array []string) []string { + m := map[string]bool{} + + for _, v := range array { + m[v] = true + } + + result := make([]string, 0, len(m)) + + for k := range m { + result = append(result, k) + } + + return result +} + +func IsUnique(list []string) bool { + set := map[string]bool{} + + for _, did := range list { + set[did] = true + } + + return len(list) == len(set) +} + +func ToInterfaces(list []string) []interface{} { + res := make([]interface{}, len(list)) + + for i := range list { + res[i] = list[i] + } + + return res +} + +func ReplaceInSlice(list []string, old, new string) { + for i := range list { + if list[i] == old { + list[i] = new + } + } +} + +func UniqueSorted(ls []string) []string { + tmp_ := Unique(ls) + sort.Strings(tmp_) + return tmp_ +} diff --git a/x/resource/utils/str_test.go b/x/resource/utils/str_test.go new file mode 100644 index 000000000..80a91eb4f --- /dev/null +++ b/x/resource/utils/str_test.go @@ -0,0 +1,122 @@ +package utils + +import ( + "sort" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIndexOf(t *testing.T) { + cases := []struct { + array []string + searchElement string + fromIndex int + expectedResult int + }{ + {[]string{}, "", 0, -1}, + {nil, "", 0, -1}, + {[]string{"1", "2"}, "1", 0, 0}, + {[]string{"1", "2", "3"}, "3", 0, 2}, + {[]string{"1", "2", "3"}, "4", 0, -1}, + {[]string{"4", "1", "6", "2", "3", "4"}, "4", 0, 0}, + {[]string{"4", "1", "6", "2", "3", "4"}, "4", 1, 5}, + {[]string{"4", "1", "6", "2", "3", "4"}, "4", 3, 5}, + } + + for _, tc := range cases { + actual := IndexOf(tc.array, tc.searchElement, tc.fromIndex) + require.Equal(t, tc.expectedResult, actual) + } +} + +func TestContains(t *testing.T) { + cases := []struct { + array []string + searchElement string + expectedResult bool + }{ + {[]string{}, "", false}, + {nil, "", false}, + {[]string{"1", "2"}, "1", true}, + {[]string{"1", "2", "3"}, "2", true}, + {[]string{"1", "2", "3"}, "3", true}, + {[]string{"1", "2", "3"}, "123", false}, + } + + for _, tc := range cases { + actual := Contains(tc.array, tc.searchElement) + require.Equal(t, tc.expectedResult, actual) + } +} + +func TestSubtract(t *testing.T) { + cases := []struct { + first []string + second []string + expected []string + }{ + {[]string{}, []string{}, []string{}}, + {nil, []string{}, []string{}}, + {nil, nil, []string{}}, + {[]string{"1", "2"}, []string{"1", "2"}, []string{}}, + {[]string{"1", "2", "3"}, []string{}, []string{"1", "2", "3"}}, + {[]string{"1", "2", "3"}, nil, []string{"1", "2", "3"}}, + {[]string{"1", "2", "3"}, []string{"4", "5", "6"}, []string{"1", "2", "3"}}, + {[]string{"1", "2", "3"}, []string{"1", "5", "2"}, []string{"3"}}, + {[]string{"4", "1", "6", "2", "3"}, []string{"1", "5", "2"}, []string{"3", "4", "6"}}, + } + + for _, tc := range cases { + actual := Subtract(tc.first, tc.second) + // We can't compare arrays directly cause result of `subtract` is not deterministic + sort.Strings(actual) + require.Equal(t, tc.expected, actual) + } +} + +func TestUnique(t *testing.T) { + cases := []struct { + array []string + expected []string + }{ + {[]string{}, []string{}}, + {nil, []string{}}, + {[]string{"1", "2"}, []string{"1", "2"}}, + {[]string{"1", "3", "2"}, []string{"1", "2", "3"}}, + {[]string{"4", "1", "6", "2", "3", "1", "3", "1"}, []string{"1", "2", "3", "4", "6"}}, + } + + for _, tc := range cases { + actual := Unique(tc.array) + // We can't compare arrays directly cause result of `unique` is not deterministic + sort.Strings(actual) + require.Equal(t, tc.expected, actual) + } +} + +func TestReplaceInList(t *testing.T) { + list := []string{"1", "2", "3", "2"} + ReplaceInSlice(list, "2", "3") + + require.Equal(t, []string{"1", "3", "3", "3"}, list) +} + +func TestUniqueSorted(t *testing.T) { + cases := []struct { + name string + input []string + output []string + }{ + {"General alphabet list", []string{"aa", "bb"}, []string{"aa", "bb"}}, + {"General alphabet reverse list", []string{"bb", "aa"}, []string{"aa", "bb"}}, + {"General number list", []string{"22", "11"}, []string{"11", "22"}}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + res := UniqueSorted(tc.input) + require.Equal(t, res, tc.output) + }) + } +} diff --git a/x/resource/utils/tx.go b/x/resource/utils/tx.go new file mode 100644 index 000000000..525846155 --- /dev/null +++ b/x/resource/utils/tx.go @@ -0,0 +1,12 @@ +package utils + +import ( + "fmt" + + "github.com/tendermint/tendermint/types" +) + +func GetTxHash(txBytes []byte) string { + // return base64.StdEncoding.EncodeToString(tmhash.Sum(txBytes)) + return fmt.Sprintf("%X", types.Tx(txBytes).Hash()) +} diff --git a/x/resource/utils/uri.go b/x/resource/utils/uri.go new file mode 100644 index 000000000..b8f5fcc1c --- /dev/null +++ b/x/resource/utils/uri.go @@ -0,0 +1,18 @@ +package utils + +import ( + "fmt" + "regexp" +) + +// Goes from RFC: https://www.rfc-editor.org/rfc/rfc3986#appendix-B +var ValidURIRegexp, _ = regexp.Compile(`^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?`) + +func ValidateURI(uri string) error { + // Match with Regexp from RFC + if !ValidURIRegexp.MatchString(uri) { + return fmt.Errorf("URI: %s does not match regexp: %s", uri, ValidURIRegexp) + } + + return nil +} diff --git a/x/resource/utils/uri_test.go b/x/resource/utils/uri_test.go new file mode 100644 index 000000000..9e7de26bc --- /dev/null +++ b/x/resource/utils/uri_test.go @@ -0,0 +1,32 @@ +package utils + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestValidateURI(t *testing.T) { + cases := []struct { + name string + valid bool + URI string + }{ + // Path: all the possible symbols + {"Valid: General http URI path", true, "http://a.com/a/b/c/d/?query=123#fragment=another_part"}, + {"Valid: General https URI path", true, "https://a.com/a/b/c/d/?query=123#fragment=another_part"}, + {"Valid: only alphabet symbols", true, "SomeAnotherPath"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err_ := ValidateURI(tc.URI) + + if tc.valid { + require.NoError(t, err_) + } else { + require.Error(t, err_) + } + }) + } +} From a18b4ff0f8286b419dc5e1b046781157c36cdc7c Mon Sep 17 00:00:00 2001 From: toktar Date: Fri, 3 Jun 2022 16:23:36 +0300 Subject: [PATCH 02/65] dev-1281: update keeper ant types in `resource` module --- go.sum | 2 + proto/resource/v1/genesis.proto | 9 +- proto/resource/v1/query.proto | 18 +- proto/resource/v1/tx.proto | 13 +- x/resource/keeper/keeper.go | 2 +- x/resource/keeper/keeper_config.go | 31 - x/resource/keeper/keeper_resource.go | 91 +- x/resource/keeper/msg_server.go | 84 +- .../keeper/msg_server_create_resource.go | 63 +- x/resource/types/codec.go | 14 +- x/resource/types/error.go | 24 +- x/resource/types/genesis.go | 17 +- x/resource/types/genesis.pb.go | 328 ++++ x/resource/types/keys.go | 10 +- x/resource/types/query.go | 4 +- x/resource/types/query.pb.go | 1579 +++++++++++++++++ x/resource/types/query.pb.gw.go | 431 +++++ x/resource/types/resource.pb.go | 785 ++++++++ x/resource/types/tx.pb.go | 1093 ++++++++++++ x/resource/types/tx_msg_create_resource.go | 48 + .../types/tx_msg_create_resource_payload.go | 27 + 21 files changed, 4424 insertions(+), 249 deletions(-) delete mode 100644 x/resource/keeper/keeper_config.go create mode 100644 x/resource/types/genesis.pb.go create mode 100644 x/resource/types/query.pb.go create mode 100644 x/resource/types/query.pb.gw.go create mode 100644 x/resource/types/resource.pb.go create mode 100644 x/resource/types/tx.pb.go create mode 100644 x/resource/types/tx_msg_create_resource.go create mode 100644 x/resource/types/tx_msg_create_resource_payload.go diff --git a/go.sum b/go.sum index 1d45cd0d4..d973a4ae1 100644 --- a/go.sum +++ b/go.sum @@ -1185,6 +1185,7 @@ golang.org/x/net v0.0.0-20210917221730-978cfadd31cf/go.mod h1:9nx3DQGgdP8bBQD5qx 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= @@ -1316,6 +1317,7 @@ golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBc 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= diff --git a/proto/resource/v1/genesis.proto b/proto/resource/v1/genesis.proto index 656bfc576..0bb62e1de 100644 --- a/proto/resource/v1/genesis.proto +++ b/proto/resource/v1/genesis.proto @@ -1,13 +1,12 @@ syntax = "proto3"; -package cheqdid.cheqdnode.cheqd.v1; +package cheqdid.cheqdnode.resource.v1; -option go_package = "github.com/cheqd/cheqd-node/x/cheqd/types"; +option go_package = "github.com/cheqd/cheqd-node/x/resource/types"; -import "cheqd/v1/stateValue.proto"; +import "resource/v1/resource.proto"; // GenesisState defines the cheqd module's genesis state. message GenesisState { - string did_namespace = 1; - repeated StateValue didList = 2; + repeated Resource resourceList = 1; } diff --git a/proto/resource/v1/query.proto b/proto/resource/v1/query.proto index b6ebb0b64..ac74923c6 100644 --- a/proto/resource/v1/query.proto +++ b/proto/resource/v1/query.proto @@ -10,13 +10,13 @@ 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/{did}/resources/{id}"; + 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/{did}/resources"; + option (google.api.http).get = "/1.0/identifiers/{collection_id}/resources"; } rpc AllResourceVersions(QueryGetAllResourceVersionsRequest) returns (QueryGetAllResourceVersionsResponse) { - option (google.api.http).get = "/1.0/identifiers/{did}/resources"; + option (google.api.http).get = "/1.0/identifiers/{collection_id}/resources/versions"; } } @@ -34,16 +34,16 @@ message QueryGetCollectionResourcesRequest { } message QueryGetCollectionResourcesResponse { - repeated Resource resource = 1; + repeated Resource resources = 1; } message QueryGetAllResourceVersionsRequest { - string collection_id = 1; - string name = 2; - string resource_type = 3; - string mime_type = 4; + string collection_id = 1; // Mapped to URL path + string name = 2; // Mapped to URL parameter `name` + string resource_type = 3; // Mapped to URL parameter `resource_type` + string mime_type = 4; // Mapped to URL parameter `mime_type` } message QueryGetAllResourceVersionsResponse { - repeated Resource resource = 1; + repeated Resource resources = 1; } diff --git a/proto/resource/v1/tx.proto b/proto/resource/v1/tx.proto index 3ccafd3a7..036db8ea1 100644 --- a/proto/resource/v1/tx.proto +++ b/proto/resource/v1/tx.proto @@ -3,9 +3,8 @@ package cheqdid.cheqdnode.resource.v1; option go_package = "github.com/cheqd/cheqd-node/x/resource/types"; -import "google/protobuf/any.proto"; import "cheqd/v1/tx.proto"; -import "resource/v1/tx.proto"; +import "resource/v1/resource.proto"; // Msg defines the Msg service. service Msg { @@ -14,15 +13,19 @@ service Msg { // 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; string mime_type = 5; - repeated byte data = 6; - repeated SignInfo signatures = 7; + bytes data = 6; } -message MsgCreateDidResponse { +message MsgCreateResourceResponse { Resource resource = 1; // Not necessary } diff --git a/x/resource/keeper/keeper.go b/x/resource/keeper/keeper.go index 8802339a7..2f6297b09 100644 --- a/x/resource/keeper/keeper.go +++ b/x/resource/keeper/keeper.go @@ -3,7 +3,7 @@ package keeper import ( "fmt" - "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/resource/types" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/resource/keeper/keeper_config.go b/x/resource/keeper/keeper_config.go deleted file mode 100644 index eb67b6704..000000000 --- a/x/resource/keeper/keeper_config.go +++ /dev/null @@ -1,31 +0,0 @@ -package keeper - -import ( - "github.com/cheqd/cheqd-node/x/cheqd/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// GetDidNamespace - 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) - - // Parse bytes - namespace := string(bz) - return namespace -} - -// SetToState - set State value -func (k Keeper) SetToState(ctx sdk.Context, stateKey string, stateValue []byte) { - store := ctx.KVStore(k.storeKey) - byteKey := types.KeyPrefix(types.DidNamespaceKey) - store.Set(byteKey, stateValue) -} - -// DeteteFromState - remove value from State by key -func (k Keeper) DeteteFromState(ctx sdk.Context, stateKey string) { - store := ctx.KVStore(k.storeKey) - byteKey := types.KeyPrefix(types.DidNamespaceKey) - store.Delete(byteKey) -} diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index a71ca3d0f..4b2c84cf3 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -3,16 +3,16 @@ package keeper import ( "strconv" - "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/resource/types" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// GetDidCount get the total number of did -func (k Keeper) GetDidCount(ctx *sdk.Context) uint64 { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidCountKey)) - byteKey := types.KeyPrefix(types.DidCountKey) +// GetResourceCount get the total number of resource +func (k Keeper) GetResourceCount(ctx *sdk.Context) uint64 { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceCountKey)) + byteKey := types.KeyPrefix(types.ResourceCountKey) bz := store.Get(byteKey) // Count doesn't exist: no element @@ -30,77 +30,72 @@ func (k Keeper) GetDidCount(ctx *sdk.Context) uint64 { return count } -// SetDidCount set the total number of did -func (k Keeper) SetDidCount(ctx *sdk.Context, count uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidCountKey)) - byteKey := types.KeyPrefix(types.DidCountKey) +// SetResourceCount set the total number of resource +func (k Keeper) SetResourceCount(ctx *sdk.Context, count uint64) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceCountKey)) + byteKey := types.KeyPrefix(types.ResourceCountKey) bz := []byte(strconv.FormatUint(count, 10)) 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) +// AppendResource appends a resource in the store with a new id and updates the count +func (k Keeper) AppendResource(ctx *sdk.Context, resource *types.Resource) error { + // Check that resource doesn't exist + if k.HasResource(ctx, resource.CollectionId, resource.Id) { + return types.ErrResourceExists.Wrapf(resource.Id) } - // Create the did - count := k.GetDidCount(ctx) - err := k.SetDid(ctx, did, metadata) + // Create the resource + count := k.GetResourceCount(ctx) + err := k.SetResource(ctx, resource) if err != nil { return err } - // Update did count - k.SetDidCount(ctx, count+1) + // Update resource count + k.SetResourceCount(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 - } - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidKey)) - b := k.cdc.MustMarshal(&stateValue) - store.Set(GetDidIDBytes(did.Id), b) +// SetResource set a specific resource in the store +func (k Keeper) SetResource(ctx *sdk.Context, resource *types.Resource) error { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) + b := k.cdc.MustMarshal(&resource) + store.Set(GetResourceKeyBytes(resource.CollectionId, resource.Id), b) return nil } -// GetDid returns a did from its id -func (k Keeper) GetDid(ctx *sdk.Context, id string) (types.StateValue, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidKey)) +// GetResource returns a resource from its id +func (k Keeper) GetResource(ctx *sdk.Context, collectionId string, id string) (types.Resource, error) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - if !k.HasDid(ctx, id) { - return types.StateValue{}, sdkerrors.ErrNotFound.Wrap(id) + if !k.HasResource(ctx, collectionId, id) { + return types.Resource{}, sdkerrors.ErrNotFound.Wrap(id) } - var value types.StateValue - bytes := store.Get(GetDidIDBytes(id)) + var value types.Resource + bytes := store.Get(GetResourceKeyBytes(collectionId, id)) if err := k.cdc.Unmarshal(bytes, &value); err != nil { - return types.StateValue{}, sdkerrors.Wrap(sdkerrors.ErrInvalidType, err.Error()) + return types.Resource{}, sdkerrors.Wrap(sdkerrors.ErrInvalidType, err.Error()) } return value, nil } -// HasDid checks if the did exists in the store -func (k Keeper) HasDid(ctx *sdk.Context, id string) bool { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidKey)) - return store.Has(GetDidIDBytes(id)) +// HasResource checks if the resource exists in the store +func (k Keeper) HasResource(ctx *sdk.Context, collectionId string, id string) bool { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) + return store.Has(GetResourceKeyBytes(collectionId, id)) } -// GetDidIDBytes returns the byte representation of the ID -func GetDidIDBytes(id string) []byte { - return []byte(id) +// GetResourceKeyBytes returns the byte representation of resource key +func GetResourceKeyBytes(collectionId string, id string) []byte { + return []byte(collectionId + ":" + id) } -// GetAllDid returns all did -func (k Keeper) GetAllDid(ctx *sdk.Context) (list []types.StateValue) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.DidKey)) +// GetAllResource returns all resource +func (k Keeper) GetAllResource(ctx *sdk.Context) (list []types.Resource) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) iterator := sdk.KVStorePrefixIterator(store, []byte{}) defer func(iterator sdk.Iterator) { @@ -111,7 +106,7 @@ func (k Keeper) GetAllDid(ctx *sdk.Context) (list []types.StateValue) { }(iterator) for ; iterator.Valid(); iterator.Next() { - var val types.StateValue + var val types.Resource k.cdc.MustUnmarshal(iterator.Value(), &val) list = append(list, val) } diff --git a/x/resource/keeper/msg_server.go b/x/resource/keeper/msg_server.go index 56f00e4b0..699c0521d 100644 --- a/x/resource/keeper/msg_server.go +++ b/x/resource/keeper/msg_server.go @@ -1,10 +1,8 @@ package keeper import ( - "encoding/base64" - - "github.com/cheqd/cheqd-node/x/cheqd/types" - "github.com/cheqd/cheqd-node/x/cheqd/utils" + "github.com/cheqd/cheqd-node/x/resource/types" + cheqd_types "github.com/cheqd/cheqd-node/x/resource/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -19,89 +17,27 @@ func NewMsgServer(keeper Keeper) types.MsgServer { var _ types.MsgServer = msgServer{} -func FindDid(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, did string) (res types.StateValue, found bool, err error) { +func FindResource(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.Resource, collectionId string, id string) (res types.Resource, found bool, err error) { // Look in inMemory dict - value, found := inMemoryDIDs[did] + value, found := inMemoryDIDs[collectionId+id] if found { return value, true, nil } // Look in state - if k.HasDid(ctx, did) { - value, err := k.GetDid(ctx, did) + if k.HasResource(ctx, collectionId, id) { + value, err := k.GetResource(ctx, collectionId, id) if err != nil { - return types.StateValue{}, false, err + return types.Resource{}, false, err } return value, true, nil } - return types.StateValue{}, false, nil -} - -func MustFindDid(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, did string) (res types.StateValue, err error) { - res, found, err := FindDid(k, ctx, inMemoryDIDs, did) - if err != nil { - return types.StateValue{}, err - } - - if !found { - return types.StateValue{}, types.ErrDidDocNotFound.Wrap(did) - } - - return res, nil + return types.Resource{}, false, nil } -func FindVerificationMethod(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, didUrl string) (res types.VerificationMethod, found bool, err error) { - did, _, _, _ := utils.MustSplitDIDUrl(didUrl) - - stateValue, found, err := FindDid(k, ctx, inMemoryDIDs, did) - if err != nil || !found { - return types.VerificationMethod{}, found, err - } - - didDoc, err := stateValue.UnpackDataAsDid() - if err != nil { - return types.VerificationMethod{}, false, err - } - - for _, vm := range didDoc.VerificationMethod { - if vm.Id == didUrl { - return *vm, true, nil - } - } - - return types.VerificationMethod{}, false, nil -} - -func MustFindVerificationMethod(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, didUrl string) (res types.VerificationMethod, err error) { - res, found, err := FindVerificationMethod(k, ctx, inMemoryDIDs, didUrl) - if err != nil { - return types.VerificationMethod{}, err - } - - if !found { - return types.VerificationMethod{}, types.ErrVerificationMethodNotFound.Wrap(didUrl) - } - - return res, nil -} - -func VerifySignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, message []byte, signature types.SignInfo) error { - verificationMethod, err := MustFindVerificationMethod(k, ctx, inMemoryDIDs, signature.VerificationMethodId) - if err != nil { - return err - } - - signatureBytes, err := base64.StdEncoding.DecodeString(signature.Signature) - if err != nil { - return err - } - - err = types.VerifySignature(verificationMethod, message, signatureBytes) - if err != nil { - return types.ErrInvalidSignature.Wrapf("method id: %s", signature.VerificationMethodId) - } - +func VerifySignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.Resource, message []byte, signature cheqd_types.SignInfo) error { + //TODO: implement return nil } diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index e2ecc76fd..c4341058e 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -3,76 +3,57 @@ package keeper import ( "context" - "github.com/cheqd/cheqd-node/x/cheqd/types" - "github.com/cheqd/cheqd-node/x/cheqd/utils" + "github.com/Workiva/go-datastructures/threadsafe/err" + cheqd_types "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/cheqd/cheqd-node/x/resource/utils" sdk "github.com/cosmos/cosmos-sdk/types" ) -func (k msgServer) CreateDid(goCtx context.Context, msg *types.MsgCreateDid) (*types.MsgCreateDidResponse, error) { +func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateResource) (*types.MsgCreateResourceResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - // Validate DID doesn't exist - if k.HasDid(&ctx, msg.Payload.Id) { - return nil, types.ErrDidDocExists.Wrap(msg.Payload.Id) + // Validate Resource doesn't exist + if k.HasResource(&ctx, msg.Payload.CollectionId, msg.Payload.Id) { + return nil, types.ErrResourceExists.Wrap(msg.Payload.Id) } - // Validate namespaces - namespace := k.GetDidNamespace(ctx) - err := msg.Validate([]string{namespace}) - if err != nil { - return nil, types.ErrNamespaceValidation.Wrap(err.Error()) - } - - // Build metadata and stateValue - did := msg.Payload.ToDid() - metadata := types.NewMetadataFromContext(ctx) - stateValue, err := types.NewStateValue(&did, &metadata) - if err != nil { - return nil, err - } + // Build Resource + resource := msg.Payload.ToResource() - // Consider did that we are going to create during did resolutions - inMemoryDids := map[string]types.StateValue{did.Id: stateValue} - - // Check controllers' existence - controllers := did.AllControllerDids() - for _, controller := range controllers { - _, err := MustFindDid(&k.Keeper, &ctx, inMemoryDids, controller) - if err != nil { - return nil, err - } - } + // Consider resource that we are going to create during resource resolutions + inMemoryResources := map[string]types.Resource{resource.Id: resource} // Verify signatures - signers := GetSignerDIDsForDIDCreation(did) + signers := GetSignerDIDsForDIDCreation(resource) for _, signer := range signers { - signature, found := types.FindSignInfoBySigner(msg.Signatures, signer) + signature, found := cheqd_types.FindSignInfoBySigner(msg.Signatures, signer) if !found { - return nil, types.ErrSignatureNotFound.Wrapf("signer: %s", signer) + return nil, cheqd_types.ErrSignatureNotFound.Wrapf("signer: %s", signer) } - err := VerifySignature(&k.Keeper, &ctx, inMemoryDids, msg.Payload.GetSignBytes(), signature) + err := VerifySignature(&k.Keeper, &ctx, inMemoryResources, msg.Payload.GetSignBytes(), signature) if err != nil { return nil, err } } // Apply changes - err = k.AppendDid(&ctx, &did, &metadata) + err = k.AppendResource(&ctx, &resource) if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } // Build and return response - return &types.MsgCreateDidResponse{ - Id: did.Id, + return &types.MsgCreateResourceResponse{ + Id: resource.Id, }, nil } -func GetSignerDIDsForDIDCreation(did types.Did) []string { - res := did.GetControllersOrSubject() - res = append(res, did.GetVerificationMethodControllers()...) +func GetSignerDIDsForDIDCreation(resource types.Resource) []string { + res := resource.GetControllersOrSubject() + res = append(res, resource.GetVerificationMethodControllers()...) return utils.UniqueSorted(res) } diff --git a/x/resource/types/codec.go b/x/resource/types/codec.go index 21d800df5..954998942 100644 --- a/x/resource/types/codec.go +++ b/x/resource/types/codec.go @@ -9,24 +9,22 @@ import ( func RegisterCodec(cdc *codec.LegacyAmino) { // Sdk messages - cdc.RegisterConcrete(&MsgCreateDid{}, "cheqd/CreateDid", nil) - cdc.RegisterConcrete(&MsgUpdateDid{}, "cheqd/UpdateDid", nil) + cdc.RegisterConcrete(&MsgCreateResource{}, "resource/CreateResource", nil) // State value data - cdc.RegisterInterface((*StateValueData)(nil), nil) - cdc.RegisterConcrete(&Did{}, "cheqd/Did", nil) + // cdc.RegisterInterface((*StateValueData)(nil), nil) + cdc.RegisterConcrete(&Resource{}, "resource/Resource", nil) } func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { // Sdk messages registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgCreateDid{}, - &MsgUpdateDid{}, + &MsgCreateResource{}, ) // State value data - registry.RegisterInterface("StateValueData", (*StateValueData)(nil)) - registry.RegisterImplementations((*StateValueData)(nil), &Did{}) + // registry.RegisterInterface("StateValueData", (*StateValueData)(nil)) + // registry.RegisterImplementations((*StateValueData)(nil), &Resource{}) msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } diff --git a/x/resource/types/error.go b/x/resource/types/error.go index 48bb7fc60..9b316db8e 100644 --- a/x/resource/types/error.go +++ b/x/resource/types/error.go @@ -6,17 +6,17 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// x/cheqd module sentinel errors +// x/resource module sentinel errors var ( - ErrBadRequest = sdkerrors.Register(ModuleName, 1000, "bad request") - ErrInvalidSignature = sdkerrors.Register(ModuleName, 1100, "invalid signature detected") - ErrSignatureNotFound = sdkerrors.Register(ModuleName, 1101, "signature is required but not found") - ErrDidDocExists = sdkerrors.Register(ModuleName, 1200, "DID Doc exists") - ErrDidDocNotFound = sdkerrors.Register(ModuleName, 1201, "DID Doc not found") - ErrVerificationMethodNotFound = sdkerrors.Register(ModuleName, 1202, "verification method not found") - ErrUnexpectedDidVersion = sdkerrors.Register(ModuleName, 1203, "unexpected DID version") - ErrBasicValidation = sdkerrors.Register(ModuleName, 1205, "basic validation failed") - ErrNamespaceValidation = sdkerrors.Register(ModuleName, 1206, "DID namespace validation failed") - ErrUnpackStateValue = sdkerrors.Register(ModuleName, 1300, "invalid did state value") - ErrInternal = sdkerrors.Register(ModuleName, 1500, "internal error") + ErrBadRequest = sdkerrors.Register(ModuleName, 2000, "bad request") + ErrInvalidSignature = sdkerrors.Register(ModuleName, 2100, "invalid signature detected") + ErrSignatureNotFound = sdkerrors.Register(ModuleName, 2101, "signature is required but not found") + ErrResourceExists = sdkerrors.Register(ModuleName, 2200, "Resoure exists") + ErrDidDocNotFound = sdkerrors.Register(ModuleName, 2201, "DID Doc not found") + ErrVerificationMethodNotFound = sdkerrors.Register(ModuleName, 2202, "verification method not found") + ErrUnexpectedDidVersion = sdkerrors.Register(ModuleName, 2203, "unexpected DID version") + ErrBasicValidation = sdkerrors.Register(ModuleName, 2205, "basic validation failed") + ErrNamespaceValidation = sdkerrors.Register(ModuleName, 2206, "DID namespace validation failed") + ErrUnpackStateValue = sdkerrors.Register(ModuleName, 2300, "invalid did state value") + ErrInternal = sdkerrors.Register(ModuleName, 2500, "internal error") ) diff --git a/x/resource/types/genesis.go b/x/resource/types/genesis.go index e6a9b11df..9f1a7277d 100644 --- a/x/resource/types/genesis.go +++ b/x/resource/types/genesis.go @@ -4,32 +4,31 @@ import ( "fmt" ) -const DefaultDidNamespace = "testnet" +const DefaultResourceNamespace = "testnet" // DefaultGenesis returns the default Capability genesis state func DefaultGenesis() *GenesisState { return &GenesisState{ - DidList: []*StateValue{}, - DidNamespace: DefaultDidNamespace, + ResourceList: []*Resource{}, } } // Validate performs basic genesis state validation returning an error upon any // failure. func (gs GenesisState) Validate() error { - didIdMap := make(map[string]bool) + resourceIdMap := make(map[string]bool) - for _, elem := range gs.DidList { - did, err := elem.UnpackDataAsDid() + for _, elem := range gs.ResourceList { + resource, err := elem.UnpackDataAsResource() if err != nil { return err } - if _, ok := didIdMap[did.Id]; ok { - return fmt.Errorf("duplicated id for did") + if _, ok := resourceIdMap[resource.Id]; ok { + return fmt.Errorf("duplicated id for resource") } - didIdMap[did.Id] = true + resourceIdMap[resource.Id] = 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 index 502b02cae..0e83c3959 100644 --- a/x/resource/types/keys.go +++ b/x/resource/types/keys.go @@ -2,7 +2,7 @@ package types const ( // ModuleName defines the module name - ModuleName = "cheqd" + ModuleName = "resource" // StoreKey defines the primary module store key StoreKey = ModuleName @@ -13,7 +13,7 @@ const ( // QuerierRoute defines the module's query routing key QuerierRoute = ModuleName - DidMethod = ModuleName + ResourceMethod = ModuleName ) func KeyPrefix(p string) []byte { @@ -21,7 +21,7 @@ func KeyPrefix(p string) []byte { } const ( - DidKey = "did:" - DidCountKey = "did-count:" - DidNamespaceKey = "did-namespace:" + ResourceKey = "resource:" + ResourceCountKey = "resource-count:" + ResourceNamespaceKey = "resource-namespace:" ) diff --git a/x/resource/types/query.go b/x/resource/types/query.go index 8a6cb7eb4..6321965eb 100644 --- a/x/resource/types/query.go +++ b/x/resource/types/query.go @@ -1,5 +1,7 @@ package types const ( - QueryGetDid = "get-did" + 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..07893d52e --- /dev/null +++ b/x/resource/types/query.pb.go @@ -0,0 +1,1579 @@ +// 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 []*Resource `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() []*Resource { + 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"` + ResourceType string `protobuf:"bytes,3,opt,name=resource_type,json=resourceType,proto3" json:"resource_type,omitempty"` + MimeType string `protobuf:"bytes,4,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,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 "" +} + +func (m *QueryGetAllResourceVersionsRequest) GetResourceType() string { + if m != nil { + return m.ResourceType + } + return "" +} + +func (m *QueryGetAllResourceVersionsRequest) GetMimeType() string { + if m != nil { + return m.MimeType + } + return "" +} + +type QueryGetAllResourceVersionsResponse struct { + Resources []*Resource `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() []*Resource { + 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{ + // 500 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0xcd, 0x6e, 0xd3, 0x40, + 0x10, 0xce, 0xa6, 0x01, 0x25, 0xcb, 0xcf, 0x61, 0x7b, 0xa8, 0x65, 0xc0, 0xaa, 0xdc, 0x03, 0x08, + 0x15, 0x2f, 0x49, 0x05, 0x3d, 0x70, 0x6a, 0x2b, 0x40, 0xbd, 0x20, 0x11, 0x21, 0x0e, 0x5c, 0xa2, + 0xd4, 0x3b, 0xa4, 0x2b, 0x39, 0x5e, 0xc7, 0xbb, 0x89, 0x88, 0xaa, 0x5e, 0x78, 0x02, 0x24, 0x1e, + 0x80, 0x97, 0xe0, 0x21, 0x38, 0x46, 0xe2, 0x02, 0x37, 0x94, 0x70, 0xe5, 0x1d, 0xd0, 0x6e, 0xbc, + 0x4e, 0x11, 0x49, 0xb0, 0x45, 0x2f, 0xb6, 0xb5, 0x33, 0xdf, 0x37, 0xdf, 0x37, 0x33, 0x6b, 0xbc, + 0x95, 0x82, 0x14, 0xc3, 0x34, 0x04, 0x3a, 0x6a, 0xd2, 0xc1, 0x10, 0xd2, 0x71, 0x90, 0xa4, 0x42, + 0x09, 0x72, 0x27, 0x3c, 0x85, 0x01, 0xe3, 0x2c, 0x30, 0xef, 0x58, 0x30, 0x08, 0x6c, 0x6a, 0x30, + 0x6a, 0xba, 0xb7, 0x7b, 0x42, 0xf4, 0x22, 0xa0, 0xdd, 0x84, 0xd3, 0x6e, 0x1c, 0x0b, 0xd5, 0x55, + 0x5c, 0xc4, 0x72, 0x0e, 0x76, 0xdd, 0x8b, 0xac, 0x39, 0xcc, 0xc4, 0xfc, 0x17, 0x78, 0xeb, 0xa5, + 0xae, 0xf3, 0x1c, 0x54, 0x3b, 0x8b, 0xb4, 0x61, 0x30, 0x04, 0xa9, 0xc8, 0x0e, 0xbe, 0x11, 0x8a, + 0x28, 0x82, 0x50, 0x73, 0x75, 0x38, 0x73, 0xd0, 0x36, 0xba, 0xd7, 0x68, 0x5f, 0x5f, 0x1c, 0x1e, + 0x33, 0x72, 0x13, 0x57, 0x39, 0x73, 0xaa, 0x26, 0x52, 0xe5, 0xcc, 0xef, 0x60, 0xe7, 0x6f, 0x3e, + 0x99, 0x88, 0x58, 0x02, 0x39, 0xc2, 0x75, 0x5b, 0xdd, 0x70, 0x5d, 0x6b, 0xdd, 0x0d, 0xd6, 0xfa, + 0x0a, 0x72, 0x8a, 0x1c, 0xe8, 0x1f, 0x63, 0xdf, 0x16, 0x38, 0xca, 0x85, 0xd8, 0x3c, 0x59, 0x46, + 0xbb, 0x1f, 0xe1, 0x9d, 0xb5, 0x54, 0x99, 0xec, 0xa7, 0xb8, 0x61, 0xab, 0x4b, 0x07, 0x6d, 0x6f, + 0x94, 0xd1, 0xbd, 0x40, 0xfa, 0x9f, 0xd0, 0x42, 0xf9, 0x41, 0x14, 0xd9, 0x94, 0xd7, 0x90, 0x4a, + 0x3d, 0xab, 0x52, 0x5d, 0x27, 0xb8, 0x16, 0x77, 0xfb, 0x90, 0xf5, 0xdd, 0x7c, 0x6b, 0xa0, 0x2d, + 0xd6, 0x51, 0xe3, 0x04, 0x9c, 0x8d, 0x39, 0xd0, 0x1e, 0xbe, 0x1a, 0x27, 0x40, 0x6e, 0xe1, 0x46, + 0x9f, 0xf7, 0xb3, 0x84, 0x9a, 0x49, 0xa8, 0xeb, 0x03, 0x1d, 0xbc, 0xd8, 0x8f, 0xa5, 0x02, 0x2f, + 0xb5, 0x1f, 0xad, 0x5f, 0x35, 0x7c, 0xc5, 0x94, 0x23, 0x9f, 0x11, 0xae, 0xdb, 0x0c, 0xf2, 0xf8, + 0x1f, 0x54, 0x2b, 0xb6, 0xd5, 0xdd, 0x2f, 0x8d, 0x9b, 0xdb, 0xf1, 0xf7, 0xdf, 0x7f, 0xfd, 0xf9, + 0xb1, 0xda, 0x24, 0x94, 0x36, 0x83, 0x87, 0x94, 0x33, 0x88, 0x15, 0x7f, 0xcb, 0x21, 0x95, 0xf4, + 0xec, 0x8f, 0x41, 0x9c, 0xe7, 0x57, 0x47, 0xd2, 0x33, 0xce, 0xce, 0xc9, 0x04, 0xe1, 0xcd, 0x25, + 0x7b, 0x43, 0x0e, 0x0a, 0x2a, 0x59, 0xbd, 0xbe, 0xee, 0xe1, 0xff, 0x50, 0x64, 0xbe, 0x5a, 0xc6, + 0xd7, 0x2e, 0xb9, 0x5f, 0xdc, 0x17, 0xf9, 0x8e, 0xf0, 0xe6, 0x92, 0xd1, 0x17, 0xb6, 0xb4, 0x7a, + 0xaf, 0x0b, 0x5b, 0x5a, 0xb3, 0x79, 0xfe, 0x13, 0x63, 0xe9, 0x11, 0xd9, 0x2b, 0x31, 0xaa, 0x51, + 0x46, 0x72, 0xf8, 0xec, 0xcb, 0xd4, 0x43, 0x93, 0xa9, 0x87, 0x7e, 0x4c, 0x3d, 0xf4, 0x61, 0xe6, + 0x55, 0x26, 0x33, 0xaf, 0xf2, 0x6d, 0xe6, 0x55, 0xde, 0xec, 0xf6, 0xb8, 0x3a, 0x1d, 0x9e, 0x04, + 0xa1, 0xe8, 0x53, 0x23, 0x6e, 0xfe, 0x7c, 0xa0, 0x35, 0xd2, 0x77, 0x39, 0x17, 0xd5, 0x97, 0x46, + 0x9e, 0x5c, 0x35, 0x3f, 0xce, 0xbd, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xf4, 0xef, 0x1e, 0x9a, + 0xac, 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.MimeType) > 0 { + i -= len(m.MimeType) + copy(dAtA[i:], m.MimeType) + i = encodeVarintQuery(dAtA, i, uint64(len(m.MimeType))) + i-- + dAtA[i] = 0x22 + } + if len(m.ResourceType) > 0 { + i -= len(m.ResourceType) + copy(dAtA[i:], m.ResourceType) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ResourceType))) + i-- + dAtA[i] = 0x1a + } + 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)) + } + l = len(m.ResourceType) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.MimeType) + 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, &Resource{}) + 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 + case 3: + 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 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.ResourceType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MimeType", 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.MimeType = 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, &Resource{}) + 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..63883e35f --- /dev/null +++ b/x/resource/types/query.pb.gw.go @@ -0,0 +1,431 @@ +// 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 + +} + +var ( + filter_Query_AllResourceVersions_0 = &utilities.DoubleArray{Encoding: map[string]int{"collection_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} +) + +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) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AllResourceVersions_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", 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) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AllResourceVersions_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", 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(true))) + + pattern_Query_CollectionResources_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"1.0", "identifiers", "collection_id", "resources"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_AllResourceVersions_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", "versions"}, "", runtime.AssumeColonVerbOpt(true))) +) + +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..c054342a8 --- /dev/null +++ b/x/resource/types/resource.pb.go @@ -0,0 +1,785 @@ +// 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 { + 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"` + MimeType string `protobuf:"bytes,5,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"` + Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` + Created string `protobuf:"bytes,7,opt,name=created,proto3" json:"created,omitempty"` + Checksum string `protobuf:"bytes,8,opt,name=checksum,proto3" json:"checksum,omitempty"` + PreviousVersionId string `protobuf:"bytes,9,opt,name=previous_version_id,json=previousVersionId,proto3" json:"previous_version_id,omitempty"` + NextVersionId string `protobuf:"bytes,10,opt,name=next_version_id,json=nextVersionId,proto3" json:"next_version_id,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) GetCollectionId() string { + if m != nil { + return m.CollectionId + } + return "" +} + +func (m *Resource) GetId() string { + if m != nil { + return m.Id + } + return "" +} + +func (m *Resource) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Resource) GetResourceType() string { + if m != nil { + return m.ResourceType + } + return "" +} + +func (m *Resource) GetMimeType() string { + if m != nil { + return m.MimeType + } + return "" +} + +func (m *Resource) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +func (m *Resource) GetCreated() string { + if m != nil { + return m.Created + } + return "" +} + +func (m *Resource) GetChecksum() string { + if m != nil { + return m.Checksum + } + return "" +} + +func (m *Resource) GetPreviousVersionId() string { + if m != nil { + return m.PreviousVersionId + } + return "" +} + +func (m *Resource) GetNextVersionId() string { + if m != nil { + return m.NextVersionId + } + return "" +} + +func init() { + proto.RegisterType((*Resource)(nil), "cheqdid.cheqdnode.resource.v1.Resource") +} + +func init() { proto.RegisterFile("resource/v1/resource.proto", fileDescriptor_cebae6241f1ea243) } + +var fileDescriptor_cebae6241f1ea243 = []byte{ + // 316 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0xc1, 0x4e, 0xc2, 0x40, + 0x10, 0x86, 0x69, 0x45, 0x28, 0x13, 0xd0, 0xb8, 0x5e, 0x36, 0x18, 0x1b, 0xa2, 0x89, 0xe1, 0xa0, + 0x6d, 0x88, 0x6f, 0xe0, 0xc1, 0x84, 0x2b, 0x31, 0x1e, 0xbc, 0x90, 0xb2, 0x3b, 0x91, 0x8d, 0xb4, + 0x5b, 0xdb, 0x6d, 0x03, 0x6f, 0xe1, 0xdb, 0xf8, 0x0a, 0x1e, 0x39, 0x7a, 0x34, 0xf0, 0x22, 0xa6, + 0x53, 0xb6, 0x7a, 0x69, 0x67, 0xfe, 0xff, 0xcb, 0xbf, 0x99, 0x19, 0x18, 0x66, 0x98, 0xeb, 0x22, + 0x13, 0x18, 0x96, 0x93, 0xd0, 0xd6, 0x41, 0x9a, 0x69, 0xa3, 0xd9, 0xa5, 0x58, 0xe2, 0xbb, 0x54, + 0x32, 0xa0, 0x7f, 0xa2, 0x25, 0x06, 0x0d, 0x51, 0x4e, 0xae, 0x3e, 0x5d, 0xf0, 0x66, 0x87, 0x9e, + 0x5d, 0xc3, 0x40, 0xe8, 0xd5, 0x0a, 0x85, 0x51, 0x3a, 0x99, 0x2b, 0xc9, 0x9d, 0x91, 0x33, 0xee, + 0xcd, 0xfa, 0x7f, 0xe2, 0x54, 0xb2, 0x13, 0x70, 0x95, 0xe4, 0x2e, 0x39, 0xae, 0x92, 0x8c, 0x41, + 0x3b, 0x89, 0x62, 0xe4, 0x47, 0xa4, 0x50, 0x5d, 0x05, 0xd9, 0x47, 0xe6, 0x66, 0x93, 0x22, 0x6f, + 0xd7, 0x41, 0x56, 0x7c, 0xda, 0xa4, 0xc8, 0x2e, 0xa0, 0x17, 0xab, 0xf8, 0x00, 0x1c, 0x13, 0xe0, + 0x55, 0x02, 0x99, 0x0c, 0xda, 0x32, 0x32, 0x11, 0xef, 0x8c, 0x9c, 0x71, 0x7f, 0x46, 0x35, 0xe3, + 0xd0, 0x15, 0x19, 0x46, 0x06, 0x25, 0xef, 0x12, 0x6e, 0x5b, 0x36, 0x04, 0x4f, 0x2c, 0x51, 0xbc, + 0xe5, 0x45, 0xcc, 0xbd, 0x3a, 0xc9, 0xf6, 0x2c, 0x80, 0xf3, 0x34, 0xc3, 0x52, 0xe9, 0x22, 0x9f, + 0x97, 0x98, 0xe5, 0x87, 0xd1, 0x7a, 0x84, 0x9d, 0x59, 0xeb, 0xb9, 0x76, 0xa6, 0x92, 0xdd, 0xc0, + 0x69, 0x82, 0x6b, 0xf3, 0x9f, 0x05, 0x62, 0x07, 0x95, 0xdc, 0x70, 0x0f, 0x8f, 0x5f, 0x3b, 0xdf, + 0xd9, 0xee, 0x7c, 0xe7, 0x67, 0xe7, 0x3b, 0x1f, 0x7b, 0xbf, 0xb5, 0xdd, 0xfb, 0xad, 0xef, 0xbd, + 0xdf, 0x7a, 0xb9, 0x7d, 0x55, 0x66, 0x59, 0x2c, 0x02, 0xa1, 0xe3, 0x90, 0xb6, 0x5e, 0x7f, 0xef, + 0xaa, 0xe5, 0x87, 0xeb, 0xe6, 0x40, 0x61, 0x35, 0x78, 0xbe, 0xe8, 0xd0, 0x9d, 0xee, 0x7f, 0x03, + 0x00, 0x00, 0xff, 0xff, 0x68, 0x81, 0x26, 0x95, 0xc5, 0x01, 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.NextVersionId) > 0 { + i -= len(m.NextVersionId) + copy(dAtA[i:], m.NextVersionId) + i = encodeVarintResource(dAtA, i, uint64(len(m.NextVersionId))) + i-- + dAtA[i] = 0x52 + } + 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] = 0x4a + } + 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] = 0x42 + } + 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] = 0x3a + } + 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] = 0x32 + } + if len(m.MimeType) > 0 { + i -= len(m.MimeType) + copy(dAtA[i:], m.MimeType) + i = encodeVarintResource(dAtA, i, uint64(len(m.MimeType))) + 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 + 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.MimeType) + if l > 0 { + n += 1 + l + sovResource(uint64(l)) + } + l = len(m.Data) + 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 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 MimeType", 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.MimeType = 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 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 + case 7: + 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 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Checksum", 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.Checksum = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 9: + 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 10: + 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..c5b5ebca8 --- /dev/null +++ b/x/resource/types/tx.pb.go @@ -0,0 +1,1093 @@ +// 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"` + MimeType string `protobuf:"bytes,5,opt,name=mime_type,json=mimeType,proto3" json:"mime_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) GetMimeType() string { + if m != nil { + return m.MimeType + } + 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{ + // 399 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, 0xed, 0x64, 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, 0xaa, 0x90, 0x34, 0x17, 0x67, 0x6e, + 0x66, 0x2e, 0x54, 0x01, 0x2b, 0x58, 0x01, 0x07, 0x48, 0x00, 0x2c, 0x29, 0xc4, 0xc5, 0x92, 0x92, + 0x58, 0x92, 0x28, 0xc1, 0xa6, 0xc0, 0xa8, 0xc1, 0x13, 0x04, 0x66, 0x2b, 0x25, 0x70, 0x49, 0x62, + 0x38, 0x3d, 0x28, 0xb5, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, 0xc8, 0x99, 0x8b, 0x03, 0x66, 0x3a, + 0x34, 0xc8, 0xd5, 0x09, 0x04, 0x39, 0xdc, 0x08, 0xb8, 0x46, 0xa3, 0x66, 0x46, 0x2e, 0x66, 0xdf, + 0xe2, 0x74, 0xa1, 0x1a, 0x2e, 0x3e, 0xb4, 0x08, 0x35, 0x20, 0x35, 0xfe, 0xa4, 0x2c, 0x48, 0xd5, + 0x01, 0xf3, 0x8a, 0x93, 0xdb, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, + 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0xe9, + 0xa4, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x43, 0x92, 0x29, 0x98, 0xd4, + 0x05, 0x19, 0xae, 0x5f, 0x01, 0x4f, 0x9a, 0xfa, 0xa0, 0x20, 0x2d, 0x4e, 0x62, 0x03, 0xa7, 0x50, + 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x30, 0x46, 0xdb, 0xa5, 0x07, 0x03, 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.MimeType) > 0 { + i -= len(m.MimeType) + copy(dAtA[i:], m.MimeType) + i = encodeVarintTx(dAtA, i, uint64(len(m.MimeType))) + i-- + dAtA[i] = 0x2a + } + 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.MimeType) + 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 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MimeType", 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.MimeType = 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..e208dd085 --- /dev/null +++ b/x/resource/types/tx_msg_create_resource.go @@ -0,0 +1,48 @@ +package types + +import ( + cheqd_types "github.com/cheqd/cheqd-node/x/cheqd/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +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() + if err != nil { + return ErrBasicValidation.Wrap(err.Error()) + } + + return nil +} + +// Validate + +func (msg MsgCreateResource) Validate() error { + //TODO: implement + return nil +} 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..94219e30b --- /dev/null +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -0,0 +1,27 @@ +package types + +func (msg *MsgCreateResourcePayload) GetSignBytes() []byte { + return ModuleCdc.MustMarshal(msg) +} + +func (msg *MsgCreateResourcePayload) ToResource() Resource { + created := "" + checksum := "" + return Resource{ + CollectionId: msg.CollectionId, + Id: msg.Id, + Name: msg.Name, + ResourceType: msg.ResourceType, + MimeType: msg.MimeType, + Data: msg.Data, + Created: created, + Checksum: checksum, + } +} + +// Validation + +func (msg MsgCreateResourcePayload) Validate() error { + //TODO: implementation + return nil +} From e0309494d8a9b5b7a41c66c39c292d275db49be2 Mon Sep 17 00:00:00 2001 From: toktar Date: Mon, 6 Jun 2022 20:20:33 +0300 Subject: [PATCH 03/65] dev-1281: update query implementation for `resource` module --- x/resource/keeper/keeper_resource.go | 2 +- x/resource/keeper/msg_server.go | 6 +-- .../keeper/msg_server_create_resource.go | 18 +++---- x/resource/keeper/query.go | 10 ++-- x/resource/keeper/query_resource.go | 6 +-- x/resource/keeper/query_server.go | 2 +- x/resource/keeper/query_server_resource.go | 49 ++++++++++++++++--- x/resource/types/codec.go | 6 +-- 8 files changed, 67 insertions(+), 32 deletions(-) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index 4b2c84cf3..c70b50f14 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -94,7 +94,7 @@ func GetResourceKeyBytes(collectionId string, id string) []byte { } // GetAllResource returns all resource -func (k Keeper) GetAllResource(ctx *sdk.Context) (list []types.Resource) { +func (k Keeper) GetAllResources(ctx *sdk.Context) (list []types.Resource) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) iterator := sdk.KVStorePrefixIterator(store, []byte{}) diff --git a/x/resource/keeper/msg_server.go b/x/resource/keeper/msg_server.go index 699c0521d..f0705d4b8 100644 --- a/x/resource/keeper/msg_server.go +++ b/x/resource/keeper/msg_server.go @@ -17,9 +17,9 @@ func NewMsgServer(keeper Keeper) types.MsgServer { var _ types.MsgServer = msgServer{} -func FindResource(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.Resource, collectionId string, id string) (res types.Resource, found bool, err error) { +func FindResource(k *Keeper, ctx *sdk.Context, inMemoryResources map[string]types.Resource, collectionId string, id string) (res types.Resource, found bool, err error) { // Look in inMemory dict - value, found := inMemoryDIDs[collectionId+id] + value, found := inMemoryResources[collectionId+id] if found { return value, true, nil } @@ -37,7 +37,7 @@ func FindResource(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.Res return types.Resource{}, false, nil } -func VerifySignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.Resource, message []byte, signature cheqd_types.SignInfo) error { +func VerifySignature(k *Keeper, ctx *sdk.Context, inMemoryResources map[string]types.Resource, message []byte, signature cheqd_types.SignInfo) error { //TODO: implement return nil } diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index c4341058e..a482e3baf 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -3,10 +3,8 @@ package keeper import ( "context" - "github.com/Workiva/go-datastructures/threadsafe/err" cheqd_types "github.com/cheqd/cheqd-node/x/cheqd/types" "github.com/cheqd/cheqd-node/x/resource/types" - "github.com/cheqd/cheqd-node/x/resource/utils" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -22,10 +20,10 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes resource := msg.Payload.ToResource() // Consider resource that we are going to create during resource resolutions - inMemoryResources := map[string]types.Resource{resource.Id: resource} + inMemoryResources := map[string]types.Resource{resource.CollectionId + resource.Id: resource} // Verify signatures - signers := GetSignerDIDsForDIDCreation(resource) + signers := GetSignerDIDsForResourceCreation(resource) for _, signer := range signers { signature, found := cheqd_types.FindSignInfoBySigner(msg.Signatures, signer) @@ -40,20 +38,18 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes } // Apply changes - err = k.AppendResource(&ctx, &resource) + err := k.AppendResource(&ctx, &resource) if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } // Build and return response return &types.MsgCreateResourceResponse{ - Id: resource.Id, + Resource: &resource, }, nil } -func GetSignerDIDsForDIDCreation(resource types.Resource) []string { - res := resource.GetControllersOrSubject() - res = append(res, resource.GetVerificationMethodControllers()...) - - return utils.UniqueSorted(res) +func GetSignerDIDsForResourceCreation(resource types.Resource) []string { + //TODO: implement + return []string{} } diff --git a/x/resource/keeper/query.go b/x/resource/keeper/query.go index 927292558..9559824f0 100644 --- a/x/resource/keeper/query.go +++ b/x/resource/keeper/query.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/cheqd/cheqd-node/x/cheqd/types" + "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" @@ -17,8 +17,12 @@ func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { ) switch path[0] { - case types.QueryGetResourceRequest: - return getResourceRequest(ctx, path[1], k, legacyQuerierCdc) + case types.QueryGetResource: + return getResource(ctx, path[1], path[2], k, legacyQuerierCdc) + // case types.QueryGetCollectionResources: + // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) + // case types.QueryGetAllResourceVersions: + // return getAllResourceVersions(ctx, path[1], k, legacyQuerierCdc) default: err = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) diff --git a/x/resource/keeper/query_resource.go b/x/resource/keeper/query_resource.go index 54e331d8c..652f812be 100644 --- a/x/resource/keeper/query_resource.go +++ b/x/resource/keeper/query_resource.go @@ -1,16 +1,16 @@ package keeper import ( - "github.com/cheqd/cheqd-node/x/cheqd/types" + "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 getDid(ctx sdk.Context, id string, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { +func getResource(ctx sdk.Context, collectionId string, id string, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { queryServer := NewQueryServer(keeper) - resp, err := queryServer.Did(sdk.WrapSDKContext(ctx), &types.QueryGetDidRequest{Id: id}) + resp, err := queryServer.Resource(sdk.WrapSDKContext(ctx), &types.QueryGetResourceRequest{CollectionId: collectionId, Id: id}) if err != nil { return nil, err } diff --git a/x/resource/keeper/query_server.go b/x/resource/keeper/query_server.go index 966633539..5d474dab2 100644 --- a/x/resource/keeper/query_server.go +++ b/x/resource/keeper/query_server.go @@ -1,7 +1,7 @@ package keeper import ( - "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/resource/types" ) type queryServer struct { diff --git a/x/resource/keeper/query_server_resource.go b/x/resource/keeper/query_server_resource.go index 970c017e9..53c6467ed 100644 --- a/x/resource/keeper/query_server_resource.go +++ b/x/resource/keeper/query_server_resource.go @@ -3,28 +3,63 @@ package keeper import ( "context" - "github.com/cheqd/cheqd-node/x/cheqd/types" + "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 (k Keeper) Did(c context.Context, req *types.QueryGetDidRequest) (*types.QueryGetDidResponse, error) { +func (k Keeper) 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) - stateValue, err := k.GetDid(&ctx, req.Id) + resource, err := k.GetResource(&ctx, req.CollectionId, req.Id) if err != nil { return nil, err } - did, err := stateValue.UnpackDataAsDid() - if err != nil { - return nil, err + return &types.QueryGetResourceResponse{Resource: &resource}, nil +} + +func (k Keeper) CollectionResources(c context.Context, req *types.QueryGetCollectionResourcesRequest) (*types.QueryGetCollectionResourcesResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + // ctx := sdk.UnwrapSDKContext(c) + + // stateResource, err := k.GetAllResource(&ctx, req.CollectionId) + // if err != nil { + // return nil, err + // } + + // resource, err := stateResource.UnpackDataAsResource() + // if err != nil { + // return nil, err + // } + + return &types.QueryGetCollectionResourcesResponse{Resources: []*types.Resource{}}, nil +} + +func (k Keeper) AllResourceVersions(c context.Context, req *types.QueryGetAllResourceVersionsRequest) (*types.QueryGetAllResourceVersionsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") } - return &types.QueryGetDidResponse{Did: did, Metadata: stateValue.Metadata}, nil + // ctx := sdk.UnwrapSDKContext(c) + + // stateResource, err := k.GetResource(&ctx, req.CollectionId, req.Id) + // if err != nil { + // return nil, err + // } + + // resource, err := stateResource.UnpackDataAsResource() + // if err != nil { + // return nil, err + // } + + return &types.QueryGetAllResourceVersionsResponse{Resources: []*types.Resource{}}, nil } diff --git a/x/resource/types/codec.go b/x/resource/types/codec.go index 954998942..34ac68a55 100644 --- a/x/resource/types/codec.go +++ b/x/resource/types/codec.go @@ -12,7 +12,7 @@ func RegisterCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(&MsgCreateResource{}, "resource/CreateResource", nil) // State value data - // cdc.RegisterInterface((*StateValueData)(nil), nil) + cdc.RegisterInterface((*Resource)(nil), nil) cdc.RegisterConcrete(&Resource{}, "resource/Resource", nil) } @@ -23,8 +23,8 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { ) // State value data - // registry.RegisterInterface("StateValueData", (*StateValueData)(nil)) - // registry.RegisterImplementations((*StateValueData)(nil), &Resource{}) + registry.RegisterInterface("Resource", (*Resource)(nil)) + registry.RegisterImplementations((*Resource)(nil), &Resource{}) msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } From 48e93e185753bce3e4abbd89165403268e653502 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Thu, 9 Jun 2022 07:10:31 +0300 Subject: [PATCH 04/65] Various --- go.mod | 4 +--- go.sum | 14 ++------------ x/resource/genesis.go | 2 +- x/resource/handler.go | 2 +- x/resource/types/query.pb.gw.go | 6 +++--- 5 files changed, 8 insertions(+), 20 deletions(-) diff --git a/go.mod b/go.mod index ac516630a..70a054965 100644 --- a/go.mod +++ b/go.mod @@ -56,7 +56,6 @@ require ( github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect github.com/felixge/httpsnoop v1.0.1 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect - github.com/ghodss/yaml v1.0.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.0 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect @@ -64,14 +63,13 @@ require ( github.com/goccy/go-json v0.9.4 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/gateway v1.1.0 // indirect - github.com/golang/glog v1.0.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 github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/gtank/merlin v0.1.1 // indirect github.com/gtank/ristretto255 v0.1.2 // indirect diff --git a/go.sum b/go.sum index d973a4ae1..75cdeb113 100644 --- a/go.sum +++ b/go.sum @@ -317,7 +317,6 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= -github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -375,8 +374,6 @@ github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2V github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= -github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -430,9 +427,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= @@ -494,8 +491,6 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 h1:BGNSrTRW4rwfhJiFwvwF4XQ0Y72Jj9YEgxVrtovbD5o= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3/go.mod h1:VHn7KgNsRriXa4mcgtkpR00OXyQY6g67JWMvn+R27A4= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= @@ -1183,7 +1178,6 @@ 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= @@ -1312,10 +1306,10 @@ 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= @@ -1403,7 +1397,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= @@ -1518,7 +1511,6 @@ 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= @@ -1538,7 +1530,6 @@ 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= @@ -1576,7 +1567,6 @@ 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= diff --git a/x/resource/genesis.go b/x/resource/genesis.go index 413028501..24be07579 100644 --- a/x/resource/genesis.go +++ b/x/resource/genesis.go @@ -1,4 +1,4 @@ -package cheqd +package recource import ( "fmt" diff --git a/x/resource/handler.go b/x/resource/handler.go index 23d43d077..cacd218e7 100644 --- a/x/resource/handler.go +++ b/x/resource/handler.go @@ -1,4 +1,4 @@ -package cheqd +package recource import ( "fmt" diff --git a/x/resource/types/query.pb.gw.go b/x/resource/types/query.pb.gw.go index 63883e35f..274eb0b51 100644 --- a/x/resource/types/query.pb.gw.go +++ b/x/resource/types/query.pb.gw.go @@ -415,11 +415,11 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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(true))) + 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}, []string{"1.0", "identifiers", "collection_id", "resources"}, "", runtime.AssumeColonVerbOpt(true))) + pattern_Query_CollectionResources_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"1.0", "identifiers", "collection_id", "resources"}, "", 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}, []string{"1.0", "identifiers", "collection_id", "resources", "versions"}, "", runtime.AssumeColonVerbOpt(true))) + pattern_Query_AllResourceVersions_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", "versions"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( From b0424e5de5edc1fe7a6d015766f7eaa15495e09b Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Tue, 14 Jun 2022 11:45:24 +0300 Subject: [PATCH 05/65] Make it compilable Signed-off-by: Andrew Nikitin --- go.mod | 3 +++ go.sum | 5 ++++ x/cheqd/types/query.pb.gw.go | 2 +- x/resource/genesis.go | 36 +++++++++++++--------------- x/resource/handler.go | 18 +++++++------- x/resource/keeper/keeper_resource.go | 2 +- x/resource/keeper/msg_server.go | 2 +- x/resource/module.go | 2 +- x/resource/types/genesis.go | 6 +---- x/resource/types/query.pb.gw.go | 6 ++--- 10 files changed, 41 insertions(+), 41 deletions(-) diff --git a/go.mod b/go.mod index 70a054965..085e6c02e 100644 --- a/go.mod +++ b/go.mod @@ -56,6 +56,7 @@ require ( github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect github.com/felixge/httpsnoop v1.0.1 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect + github.com/ghodss/yaml v1.0.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.0 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect @@ -63,6 +64,7 @@ require ( github.com/goccy/go-json v0.9.4 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/gateway v1.1.0 // indirect + github.com/golang/glog v1.0.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 @@ -70,6 +72,7 @@ require ( github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/gtank/merlin v0.1.1 // indirect github.com/gtank/ristretto255 v0.1.2 // indirect diff --git a/go.sum b/go.sum index 75cdeb113..66ac7a0ae 100644 --- a/go.sum +++ b/go.sum @@ -317,6 +317,7 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -374,6 +375,8 @@ github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2V github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= +github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -491,6 +494,8 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 h1:BGNSrTRW4rwfhJiFwvwF4XQ0Y72Jj9YEgxVrtovbD5o= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3/go.mod h1:VHn7KgNsRriXa4mcgtkpR00OXyQY6g67JWMvn+R27A4= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= diff --git a/x/cheqd/types/query.pb.gw.go b/x/cheqd/types/query.pb.gw.go index 7a537fc1b..bb740e001 100644 --- a/x/cheqd/types/query.pb.gw.go +++ b/x/cheqd/types/query.pb.gw.go @@ -181,7 +181,7 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } var ( - pattern_Query_Did_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"cheqd", "v1", "did", "id"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_Did_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"cheqd", "v1", "did", "id"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( diff --git a/x/resource/genesis.go b/x/resource/genesis.go index 24be07579..b2f1a216b 100644 --- a/x/resource/genesis.go +++ b/x/resource/genesis.go @@ -1,31 +1,27 @@ -package recource +package resource import ( "fmt" - "github.com/cheqd/cheqd-node/x/cheqd/keeper" - "github.com/cheqd/cheqd-node/x/cheqd/types" + "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 cheqd module's state from a provided genesis // 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())) - } + for _, resource := range genState.ResourceList { - if err = k.SetDid(&ctx, did, elem.Metadata); err != nil { - panic(fmt.Sprintf("Cannot set did case: %s", err.Error())) + if err := k.SetResource(&ctx, resource); err != nil { + panic(fmt.Sprintf("Cannot set resource case: %s", err.Error())) } } // Set nym count - k.SetDidCount(&ctx, uint64(len(genState.DidList))) + k.SetResourceCount(&ctx, uint64(len(genState.ResourceList))) - k.SetDidNamespace(ctx, genState.DidNamespace) + //k.SetResourceNamespace(ctx, genState.ResourceNamespace) } // ExportGenesis returns the cheqd module's exported genesis. @@ -33,14 +29,14 @@ func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { genesis := types.DefaultGenesis() // this line is used by starport scaffolding # genesis/module/export - // Get all did - didList := k.GetAllDid(&ctx) - for _, elem := range didList { - elem := elem - genesis.DidList = append(genesis.DidList, &elem) - } - - genesis.DidNamespace = k.GetDidNamespace(ctx) + // Get all resource + //resourceList := k.GetAllResource(&ctx) + //for _, elem := range resourceList { + // elem := elem + // genesis.ResourceList = append(genesis.ResourceList, &elem) + //} + // + //genesis.ResourceNamespace = k.GetResourceNamespace(ctx) return genesis } diff --git a/x/resource/handler.go b/x/resource/handler.go index cacd218e7..4cd84365c 100644 --- a/x/resource/handler.go +++ b/x/resource/handler.go @@ -1,10 +1,10 @@ -package recource +package resource import ( "fmt" - "github.com/cheqd/cheqd-node/x/cheqd/keeper" - "github.com/cheqd/cheqd-node/x/cheqd/types" + "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" ) @@ -16,13 +16,13 @@ func NewHandler(k keeper.Keeper) sdk.Handler { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { - case *types.MsgCreateDid: - res, err := msgServer.CreateDid(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgUpdateDid: - res, err := msgServer.UpdateDid(sdk.WrapSDKContext(ctx), msg) + case *types.MsgCreateResource: + res, err := msgServer.CreateResource(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) + // + //case *types.Msg: + // res, err := msgServer.UpdateDid(sdk.WrapSDKContext(ctx), msg) + // return sdk.WrapServiceResult(ctx, res, err) default: errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index c70b50f14..7023d55f6 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -60,7 +60,7 @@ func (k Keeper) AppendResource(ctx *sdk.Context, resource *types.Resource) error // SetResource set a specific resource in the store func (k Keeper) SetResource(ctx *sdk.Context, resource *types.Resource) error { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - b := k.cdc.MustMarshal(&resource) + b := k.cdc.MustMarshal(resource) store.Set(GetResourceKeyBytes(resource.CollectionId, resource.Id), b) return nil } diff --git a/x/resource/keeper/msg_server.go b/x/resource/keeper/msg_server.go index f0705d4b8..0af835351 100644 --- a/x/resource/keeper/msg_server.go +++ b/x/resource/keeper/msg_server.go @@ -1,8 +1,8 @@ package keeper import ( + cheqd_types "github.com/cheqd/cheqd-node/x/cheqd/types" "github.com/cheqd/cheqd-node/x/resource/types" - cheqd_types "github.com/cheqd/cheqd-node/x/resource/types" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/resource/module.go b/x/resource/module.go index 5d0a49f9b..19899ad88 100644 --- a/x/resource/module.go +++ b/x/resource/module.go @@ -1,4 +1,4 @@ -package recource +package resource import ( "context" diff --git a/x/resource/types/genesis.go b/x/resource/types/genesis.go index 9f1a7277d..3e597b96e 100644 --- a/x/resource/types/genesis.go +++ b/x/resource/types/genesis.go @@ -18,11 +18,7 @@ func DefaultGenesis() *GenesisState { func (gs GenesisState) Validate() error { resourceIdMap := make(map[string]bool) - for _, elem := range gs.ResourceList { - resource, err := elem.UnpackDataAsResource() - if err != nil { - return err - } + for _, resource := range gs.ResourceList { if _, ok := resourceIdMap[resource.Id]; ok { return fmt.Errorf("duplicated id for resource") diff --git a/x/resource/types/query.pb.gw.go b/x/resource/types/query.pb.gw.go index 274eb0b51..63883e35f 100644 --- a/x/resource/types/query.pb.gw.go +++ b/x/resource/types/query.pb.gw.go @@ -415,11 +415,11 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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_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(true))) - pattern_Query_CollectionResources_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"1.0", "identifiers", "collection_id", "resources"}, "", 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}, []string{"1.0", "identifiers", "collection_id", "resources"}, "", runtime.AssumeColonVerbOpt(true))) - pattern_Query_AllResourceVersions_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", "versions"}, "", 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}, []string{"1.0", "identifiers", "collection_id", "resources", "versions"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( From 846aa7da2c7b3ef090ad159176ea02da749b88b0 Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Tue, 14 Jun 2022 17:41:51 +0300 Subject: [PATCH 06/65] Make it compilable Signed-off-by: Andrew Nikitin --- go.mod | 1 + go.sum | 2 + x/resource/types/tx_msg_create_resource.go | 6 ++- .../types/tx_msg_create_resource_payload.go | 24 ++++++++++- x/resource/types/validate.go | 42 +++++++++++++++++++ x/resource/utils/tx.go | 7 +++- 6 files changed, 77 insertions(+), 5 deletions(-) create mode 100644 x/resource/types/validate.go diff --git a/go.mod b/go.mod index 085e6c02e..11529f77e 100644 --- a/go.mod +++ b/go.mod @@ -69,6 +69,7 @@ require ( 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/google/uuid v1.3.0 // indirect github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect diff --git a/go.sum b/go.sum index 66ac7a0ae..b276c407b 100644 --- a/go.sum +++ b/go.sum @@ -461,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= diff --git a/x/resource/types/tx_msg_create_resource.go b/x/resource/types/tx_msg_create_resource.go index e208dd085..61d3cfd98 100644 --- a/x/resource/types/tx_msg_create_resource.go +++ b/x/resource/types/tx_msg_create_resource.go @@ -3,6 +3,7 @@ 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{} @@ -43,6 +44,7 @@ func (msg *MsgCreateResource) ValidateBasic() error { // Validate func (msg MsgCreateResource) Validate() error { - //TODO: implement - return nil + return validation.ValidateStruct(&msg, + validation.Field(&msg.Payload, validation.Required, ValidMsgCreateResourcePayload()), + ) } diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go index 94219e30b..6c734f063 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -1,5 +1,9 @@ package types +import ( + validation "github.com/go-ozzo/ozzo-validation/v4" +) + func (msg *MsgCreateResourcePayload) GetSignBytes() []byte { return ModuleCdc.MustMarshal(msg) } @@ -22,6 +26,22 @@ func (msg *MsgCreateResourcePayload) ToResource() Resource { // Validation func (msg MsgCreateResourcePayload) Validate() error { - //TODO: implementation - return nil + //return validation.ValidateStruct(&msg, + // validation.Field(&msg.Payload, validation.Required, ValidMsgCreateDidPayloadRule(allowedNamespaces)), + // validation.Field(&msg.Signatures, IsUniqueSignInfoListByIdRule(), validation.Each(ValidSignInfoRule(allowedNamespaces))), + //) + return validation.ValidateStruct(&msg, + validation.Field(&msg.CollectionId, validation.Required, IsUUID()), + ) +} + +func ValidMsgCreateResourcePayload() *CustomErrorRule { + return 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/validate.go b/x/resource/types/validate.go new file mode 100644 index 000000000..afc938472 --- /dev/null +++ b/x/resource/types/validate.go @@ -0,0 +1,42 @@ +package types + +import ( + utils "github.com/cheqd/cheqd-node/x/resource/utils" +) + +// Helper enums + +type ValidationType int + +const ( + Optional ValidationType = iota + Required ValidationType = iota + Empty ValidationType = iota +) + +// Custom error rule + +type CustomErrorRule struct { + fn func(value interface{}) error +} + +func NewCustomErrorRule(fn func(value interface{}) error) *CustomErrorRule { + return &CustomErrorRule{fn: fn} +} + +func (c CustomErrorRule) Validate(value interface{}) error { + return c.fn(value) +} + +// Validate URL + +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/resource/utils/tx.go b/x/resource/utils/tx.go index 525846155..7a4c95e4e 100644 --- a/x/resource/utils/tx.go +++ b/x/resource/utils/tx.go @@ -2,7 +2,7 @@ package utils import ( "fmt" - + "github.com/google/uuid" "github.com/tendermint/tendermint/types" ) @@ -10,3 +10,8 @@ func GetTxHash(txBytes []byte) string { // return base64.StdEncoding.EncodeToString(tmhash.Sum(txBytes)) return fmt.Sprintf("%X", types.Tx(txBytes).Hash()) } + +func ValidateUUID(u string) error { + _, err := uuid.Parse(u) + return err +} From 6e85cf1fd54aefb818c5cd28395bfec18304767b Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Thu, 16 Jun 2022 10:41:01 +0300 Subject: [PATCH 07/65] Fixing validation / build --- go.mod | 5 +- go.sum | 5 - x/cheqd/types/validate.go | 3 + x/resource/handler.go | 4 - x/resource/types/codec.go | 8 -- x/resource/types/error.go | 1 + x/resource/types/genesis.go | 4 +- x/resource/types/keys.go | 8 +- .../types/tx_msg_create_resource_payload.go | 13 +- x/resource/types/validate.go | 33 +---- x/resource/utils/crypto.go | 86 ------------ x/resource/utils/crypto_test.go | 60 --------- x/resource/utils/did.go | 98 -------------- x/resource/utils/did_test.go | 97 -------------- x/resource/utils/did_url.go | 118 ----------------- x/resource/utils/did_url_test.go | 93 ------------- x/resource/utils/encoding.go | 30 ----- x/resource/utils/encoding_test.go | 115 ----------------- x/resource/utils/proto.go | 8 -- x/resource/utils/proto_test.go | 12 -- x/resource/utils/str.go | 98 -------------- x/resource/utils/str_test.go | 122 ------------------ x/resource/utils/tx.go | 17 --- x/resource/utils/uri.go | 18 --- x/resource/utils/uri_test.go | 32 ----- x/resource/utils/uuid.go | 18 +++ x/resource/utils/uuid_test.go | 32 +++++ 27 files changed, 71 insertions(+), 1067 deletions(-) delete mode 100644 x/resource/utils/crypto.go delete mode 100644 x/resource/utils/crypto_test.go delete mode 100644 x/resource/utils/did.go delete mode 100644 x/resource/utils/did_test.go delete mode 100644 x/resource/utils/did_url.go delete mode 100644 x/resource/utils/did_url_test.go delete mode 100644 x/resource/utils/encoding.go delete mode 100644 x/resource/utils/encoding_test.go delete mode 100644 x/resource/utils/proto.go delete mode 100644 x/resource/utils/proto_test.go delete mode 100644 x/resource/utils/str.go delete mode 100644 x/resource/utils/str_test.go delete mode 100644 x/resource/utils/tx.go delete mode 100644 x/resource/utils/uri.go delete mode 100644 x/resource/utils/uri_test.go create mode 100644 x/resource/utils/uuid.go create mode 100644 x/resource/utils/uuid_test.go diff --git a/go.mod b/go.mod index 11529f77e..dc6737ee4 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( 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 @@ -56,7 +57,6 @@ require ( github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect github.com/felixge/httpsnoop v1.0.1 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect - github.com/ghodss/yaml v1.0.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.0 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect @@ -64,16 +64,13 @@ require ( github.com/goccy/go-json v0.9.4 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/gateway v1.1.0 // indirect - github.com/golang/glog v1.0.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/google/uuid v1.3.0 // indirect github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/gtank/merlin v0.1.1 // indirect github.com/gtank/ristretto255 v0.1.2 // indirect diff --git a/go.sum b/go.sum index b276c407b..398ea4bb4 100644 --- a/go.sum +++ b/go.sum @@ -317,7 +317,6 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= -github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -375,8 +374,6 @@ github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2V github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= -github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -496,8 +493,6 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 h1:BGNSrTRW4rwfhJiFwvwF4XQ0Y72Jj9YEgxVrtovbD5o= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3/go.mod h1:VHn7KgNsRriXa4mcgtkpR00OXyQY6g67JWMvn+R27A4= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= diff --git a/x/cheqd/types/validate.go b/x/cheqd/types/validate.go index 68d0410e7..f91a658bc 100644 --- a/x/cheqd/types/validate.go +++ b/x/cheqd/types/validate.go @@ -3,6 +3,7 @@ package types import ( "errors" "fmt" + validation "github.com/go-ozzo/ozzo-validation/v4" "strings" "github.com/cheqd/cheqd-node/x/cheqd/utils" @@ -21,6 +22,8 @@ const ( // Custom error rule +var _ validation.Rule = &CustomErrorRule{} + type CustomErrorRule struct { fn func(value interface{}) error } diff --git a/x/resource/handler.go b/x/resource/handler.go index 4cd84365c..e7c80ff35 100644 --- a/x/resource/handler.go +++ b/x/resource/handler.go @@ -19,10 +19,6 @@ func NewHandler(k keeper.Keeper) sdk.Handler { case *types.MsgCreateResource: res, err := msgServer.CreateResource(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) - // - //case *types.Msg: - // res, err := msgServer.UpdateDid(sdk.WrapSDKContext(ctx), msg) - // return sdk.WrapServiceResult(ctx, res, err) default: errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) diff --git a/x/resource/types/codec.go b/x/resource/types/codec.go index 34ac68a55..766f753cd 100644 --- a/x/resource/types/codec.go +++ b/x/resource/types/codec.go @@ -10,10 +10,6 @@ import ( func RegisterCodec(cdc *codec.LegacyAmino) { // Sdk messages cdc.RegisterConcrete(&MsgCreateResource{}, "resource/CreateResource", nil) - - // State value data - cdc.RegisterInterface((*Resource)(nil), nil) - cdc.RegisterConcrete(&Resource{}, "resource/Resource", nil) } func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { @@ -22,10 +18,6 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { &MsgCreateResource{}, ) - // State value data - registry.RegisterInterface("Resource", (*Resource)(nil)) - registry.RegisterImplementations((*Resource)(nil), &Resource{}) - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } diff --git a/x/resource/types/error.go b/x/resource/types/error.go index 9b316db8e..8901fd77f 100644 --- a/x/resource/types/error.go +++ b/x/resource/types/error.go @@ -7,6 +7,7 @@ import ( ) // x/resource module sentinel errors +// TODO: Rework these errors to be used in the module var ( ErrBadRequest = sdkerrors.Register(ModuleName, 2000, "bad request") ErrInvalidSignature = sdkerrors.Register(ModuleName, 2100, "invalid signature detected") diff --git a/x/resource/types/genesis.go b/x/resource/types/genesis.go index 3e597b96e..91c9c7036 100644 --- a/x/resource/types/genesis.go +++ b/x/resource/types/genesis.go @@ -1,11 +1,10 @@ +// TODO: package types import ( "fmt" ) -const DefaultResourceNamespace = "testnet" - // DefaultGenesis returns the default Capability genesis state func DefaultGenesis() *GenesisState { return &GenesisState{ @@ -16,6 +15,7 @@ func DefaultGenesis() *GenesisState { // Validate performs basic genesis state validation returning an error upon any // failure. func (gs GenesisState) Validate() error { + // TODO: Are resource ids unique within a collection or globally? resourceIdMap := make(map[string]bool) for _, resource := range gs.ResourceList { diff --git a/x/resource/types/keys.go b/x/resource/types/keys.go index 0e83c3959..3325ced54 100644 --- a/x/resource/types/keys.go +++ b/x/resource/types/keys.go @@ -12,8 +12,6 @@ const ( // QuerierRoute defines the module's query routing key QuerierRoute = ModuleName - - ResourceMethod = ModuleName ) func KeyPrefix(p string) []byte { @@ -21,7 +19,7 @@ func KeyPrefix(p string) []byte { } const ( - ResourceKey = "resource:" - ResourceCountKey = "resource-count:" - ResourceNamespaceKey = "resource-namespace:" + CollectionKey = "collection:" + ResourceKey = "resource:" + ResourceCountKey = "resource-count:" ) diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go index 6c734f063..a0128b95b 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -1,9 +1,12 @@ 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) } @@ -26,17 +29,13 @@ func (msg *MsgCreateResourcePayload) ToResource() Resource { // Validation func (msg MsgCreateResourcePayload) Validate() error { - //return validation.ValidateStruct(&msg, - // validation.Field(&msg.Payload, validation.Required, ValidMsgCreateDidPayloadRule(allowedNamespaces)), - // validation.Field(&msg.Signatures, IsUniqueSignInfoListByIdRule(), validation.Each(ValidSignInfoRule(allowedNamespaces))), - //) return validation.ValidateStruct(&msg, - validation.Field(&msg.CollectionId, validation.Required, IsUUID()), + validation.Field(&msg.CollectionId, validation.Required, IsUUID()), // TODO: Wrong ) } -func ValidMsgCreateResourcePayload() *CustomErrorRule { - return NewCustomErrorRule(func(value interface{}) error { +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") diff --git a/x/resource/types/validate.go b/x/resource/types/validate.go index afc938472..4736169ca 100644 --- a/x/resource/types/validate.go +++ b/x/resource/types/validate.go @@ -1,37 +1,14 @@ package types import ( - utils "github.com/cheqd/cheqd-node/x/resource/utils" + cheqdTypes "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/resource/utils" ) -// Helper enums +// Validation helpers -type ValidationType int - -const ( - Optional ValidationType = iota - Required ValidationType = iota - Empty ValidationType = iota -) - -// Custom error rule - -type CustomErrorRule struct { - fn func(value interface{}) error -} - -func NewCustomErrorRule(fn func(value interface{}) error) *CustomErrorRule { - return &CustomErrorRule{fn: fn} -} - -func (c CustomErrorRule) Validate(value interface{}) error { - return c.fn(value) -} - -// Validate URL - -func IsUUID() *CustomErrorRule { - return NewCustomErrorRule(func(value interface{}) error { +func IsUUID() *cheqdTypes.CustomErrorRule { + return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { casted, ok := value.(string) if !ok { panic("IsDID must be only applied on string properties") diff --git a/x/resource/utils/crypto.go b/x/resource/utils/crypto.go deleted file mode 100644 index 0294f3bc3..000000000 --- a/x/resource/utils/crypto.go +++ /dev/null @@ -1,86 +0,0 @@ -package utils - -import ( - "crypto" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/rsa" - "errors" - "fmt" - "reflect" - - "filippo.io/edwards25519" - - "github.com/lestrrat-go/jwx/jwk" -) - -func ValidateJWK(jwk_string string) error { - var raw interface{} - err := jwk.ParseRawKey([]byte(jwk_string), &raw) - if err != nil { - return fmt.Errorf("can't parse jwk: %s", err.Error()) - } - - switch key := raw.(type) { - case *rsa.PublicKey: - break - case *ecdsa.PublicKey: - break - case ed25519.PublicKey: - err := ValidateEd25519PubKey(key) - if err != nil { - return err - } - default: - return fmt.Errorf("unsupported jwk type: %s. supported types are: rsa/pub, ecdsa/pub, ed25519/pub", reflect.TypeOf(raw).Name()) - } - - return nil -} - -func ValidateEd25519PubKey(keyBytes []byte) error { - if l := len(keyBytes); l != ed25519.PublicKeySize { - return fmt.Errorf("ed25519: bad public key length: %d", l) - } - _, err := (&edwards25519.Point{}).SetBytes(keyBytes) - if err != nil { - return err - } - return nil -} - -func VerifyED25519Signature(pubKey ed25519.PublicKey, message []byte, signature []byte) error { - valid := ed25519.Verify(pubKey, message, signature) - if !valid { - return errors.New("invalid ed25519 signature") - } - - return nil -} - -// VerifyRSASignature uses PSS padding and SHA256 digest -// A good explanation of different paddings: https://security.stackexchange.com/questions/183179/what-is-rsa-oaep-rsa-pss-in-simple-terms -func VerifyRSASignature(pubKey rsa.PublicKey, message []byte, signature []byte) error { - hasher := crypto.SHA256.New() - hasher.Write(message) - digest := hasher.Sum(nil) - - err := rsa.VerifyPSS(&pubKey, crypto.SHA256, digest, signature, nil) - if err != nil { - return err - } - return nil -} - -// VerifyECDSASignature uses ASN1 to decode r and s, SHA265 to calculate message digest -func VerifyECDSASignature(pubKey ecdsa.PublicKey, message []byte, signature []byte) error { - hasher := crypto.SHA256.New() - hasher.Write(message) - digest := hasher.Sum(nil) - - ok := ecdsa.VerifyASN1(&pubKey, digest, signature) - if !ok { - return errors.New("invalid ecdsa signature") - } - return nil -} diff --git a/x/resource/utils/crypto_test.go b/x/resource/utils/crypto_test.go deleted file mode 100644 index c8feb4f08..000000000 --- a/x/resource/utils/crypto_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package utils - -import ( - "testing" - - "github.com/multiformats/go-multibase" - "github.com/stretchr/testify/require" -) - -func TestValidateEd25519PubKey(t *testing.T) { - cases := []struct { - name string - key string - valid bool - errorMsg string - }{ - {"Valid: General Ed25519 public key", "zF1hVGXXK9rmx5HhMTpGnGQJiab9qrFJbQXBRhSmYjQWX", true, ""}, - {"Valid: General Ed25519 public key", "zF1hVGXXK9rmx5HhMTpGnGQJiab9qr1111111111111", false, "ed25519: bad public key length: 31"}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - _, keyBytes, _ := multibase.Decode(tc.key) - err := ValidateEd25519PubKey(keyBytes) - - if tc.valid { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errorMsg) - } - }) - } -} - -func TestValidateJwk(t *testing.T) { - cases := []struct { - name string - key string - valid bool - errorMsg string - }{ - {"positive ed25519", "{\"crv\":\"Ed25519\",\"kty\":\"OKP\",\"x\":\"9Ov80OqMlNrILAUG8DBBlYQ1rUhp7wDomr2I5muzpTc\"}", true, ""}, - {"positive ecdsa", "{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"tcEgxIPyYMiyR2_Vh_YMYG6Grg7axhK2N8JjWta5C0g\",\"y\":\"imiXD9ahVA_MKY066TrNA9r6l35lRrerP6JRey5SryQ\"}", true, ""}, - {"positive rsa", "{\"e\":\"AQAB\",\"kty\":\"RSA\",\"n\":\"skKXRn44WN2DpXDwm4Ip25kIAGRA8y3iXlaoAhPmFiuSDkx97lXcJYrjxX0wSfehgCiSoZOBv6mFzgSVv0_pXQ6zI35xi2dsbexrc87m7Q24q2chpG33ttnVwQkoXrrm0zDzSX32EVxYQyTu9aWp-zxUdAWcrWUarT24RmgjU78v8JmUzkLmwbzsEImnIZ8Hce2ruisAmuAQBVVA4bWwQm_x1KPoQW-TP5_UR3gGugvf0XrQfMJaVpcxcJ9tduMUw6ffZOsqgbvAiZYnrezxSIjnd5lFTFBIEYdGR6ZgjYZoWvQB7U72o_TJoka-zfSODOUbxNBvxvFhA3uhoo3ZKw\"}", true, ""}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - err := ValidateJWK(tc.key) - - if tc.valid { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errorMsg) - } - }) - } -} diff --git a/x/resource/utils/did.go b/x/resource/utils/did.go deleted file mode 100644 index d33528a1c..000000000 --- a/x/resource/utils/did.go +++ /dev/null @@ -1,98 +0,0 @@ -package utils - -import ( - "errors" - "fmt" - "regexp" - "strings" -) - -var ( - SplitDIDRegexp, _ = regexp.Compile(`^did:([^:]+?)(:([^:]+?))?:([^:]+)$`) - DidNamespaceRegexp, _ = regexp.Compile(`^[a-zA-Z0-9]*$`) -) - -// TrySplitDID Validates generic format of DID. It doesn't validate method, name and id content. -// Call ValidateDID for further validation. -func TrySplitDID(did string) (method string, namespace string, id string, err error) { - // Example: did:cheqd:testnet:base58str1ng1111 - // match [0] - the whole string - // match [1] - cheqd - method - // match [2] - :testnet - // match [3] - testnet - namespace - // match [4] - base58str1ng1111 - id - matches := SplitDIDRegexp.FindAllStringSubmatch(did, -1) - if len(matches) != 1 { - return "", "", "", errors.New("unable to split did into method, namespace and id") - } - - match := matches[0] - return match[1], match[3], match[4], nil -} - -func MustSplitDID(did string) (method string, namespace string, id string) { - method, namespace, id, err := TrySplitDID(did) - if err != nil { - panic(err.Error()) - } - return -} - -func JoinDID(method, namespace, id string) string { - res := "did:" + method - - if namespace != "" { - res = res + ":" + namespace - } - - return res + ":" + id -} - -// ValidateDID checks method and allowed namespaces only when the corresponding parameters are specified. -func ValidateDID(did string, method string, allowedNamespaces []string) error { - sMethod, sNamespace, sUniqueId, err := TrySplitDID(did) - if err != nil { - return err - } - - // check method - if method != "" && method != sMethod { - return fmt.Errorf("did method must be: %s", method) - } - - // check namespaces - if !DidNamespaceRegexp.MatchString(sNamespace) { - return errors.New("invalid did namespace") - } - - if len(allowedNamespaces) > 0 && !Contains(allowedNamespaces, sNamespace) { - return fmt.Errorf("did namespace must be one of: %s", strings.Join(allowedNamespaces[:], ", ")) - } - - // check unique-id - err = ValidateUniqueId(sUniqueId) - if err != nil { - return err - } - - 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") - } - - // Base58 check - if err := ValidateBase58(uniqueId); err != nil { - return fmt.Errorf("unique id must be valid base58 string: %s", err) - } - - return nil -} - -func IsValidDID(did string, method string, allowedNamespaces []string) bool { - err := ValidateDID(did, method, allowedNamespaces) - return err == nil -} diff --git a/x/resource/utils/did_test.go b/x/resource/utils/did_test.go deleted file mode 100644 index 9902a9915..000000000 --- a/x/resource/utils/did_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package utils - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestIsDid(t *testing.T) { - cases := []struct { - name string - valid bool - did string - method string - allowedNS []string - }{ - {"Valid: Inputs: Method and namespace are set", true, "did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"testnet"}}, - {"Valid: Inputs: Method and namespaces are set", true, "did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"testnet", "mainnet"}}, - {"Valid: Inputs: Method not set", true, "did:cheqd:testnet:123456789abcdefg", "", []string{"testnet"}}, - {"Valid: Inputs: Method and namespaces are empty", true, "did:cheqd:testnet:123456789abcdefg", "", []string{}}, - {"Valid: Namespace is absent in DID", true, "did:cheqd:123456789abcdefg", "", []string{}}, - // Generic method validation - {"Valid: Inputs: Method is not set and passed for NOTcheqd", true, "did:NOTcheqd:123456789abcdefg", "", []string{}}, - {"Valid: Inputs: Method and Namespaces are not set and passed for NOTcheqd", true, "did:NOTcheqd:123456789abcdefg123456789abcdefg", "", []string{}}, - - {"Valid: Inputs: Order of namespaces changed", true, "did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"mainnet", "testnet"}}, - // Wrong splitting (^did:([^:]+?)(:([^:]+?))?:([^:]+)$) - {"Not valid: DID is not started from 'did'", false, "did123:cheqd:::123456789abcdefg", "cheqd", []string{"testnet"}}, - {"Not valid: empty namespace", false, "did:cheqd::123456789abcdefg", "cheqd", []string{"testnet"}}, - {"Not valid: a lot of ':'", false, "did:cheqd:::123456789abcdefg", "cheqd", []string{"testnet"}}, - {"Not valid: several DIDs in one string", false, "did:cheqd:testnet:123456789abcdefg:did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"testnet"}}, - // Wrong method - {"Not valid: method in DID is not the same as from Inputs", false, "did:NOTcheqd:testnet:123456789abcdefg", "cheqd", []string{"mainnet", "testnet"}}, - {"Not valid: method in Inputs is not the same as from DID", false, "did:cheqd:testnet:123456789abcdefg", "NOTcheqd", []string{"mainnet", "testnet"}}, - // Wrong namespace (^[a-zA-Z0-9]*) - {"Not valid: / is not allowed for namespace", false, "did:cheqd:testnet/:123456789abcdefg", "cheqd", []string{}}, - {"Not valid: _ is not allowed for namespace", false, "did:cheqd:testnet_:123456789abcdefg", "cheqd", []string{}}, - {"Not valid: % is not allowed for namespace", false, "did:cheqd:testnet%:123456789abcdefg", "cheqd", []string{}}, - {"Not valid: * is not allowed for namespace", false, "did:cheqd:testnet*:123456789abcdefg", "cheqd", []string{}}, - {"Not valid: & is not allowed for namespace", false, "did:cheqd:testnet&:123456789abcdefg", "cheqd", []string{}}, - {"Not valid: @ is not allowed for namespace", false, "did:cheqd:testnet@:123456789abcdefg", "cheqd", []string{}}, - {"Not valid: namespace from Inputs is not the same as from DID", false, "did:cheqd:testnet:123456789abcdefg", "cheqd", []string{"not_testnet"}}, - // Base58 checks (^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]*$) - {"Not valid: O - is not allowed for UniqueID", false, "did:cheqd:testnet:123456789abcdefO", "cheqd", []string{}}, - {"Not valid: I - is not allowed for UniqueID", false, "did:cheqd:testnet:123456789abcdefI", "cheqd", []string{}}, - {"Not valid: l - is not allowed for UniqueID", false, "did:cheqd:testnet:123456789abcdefl", "cheqd", []string{}}, - {"Not valid: 0 - is not allowed for UniqueID", false, "did:cheqd:testnet:123456789abcdef0", "cheqd", []string{}}, - // Length checks (should be exactly 16 or 32) - {"Not valid: UniqueID less then 16 symbols", false, "did:cheqd:testnet:123", "cheqd", []string{}}, - {"Not valid: UniqueID more then 16 symbols but less then 32", false, "did:cheqd:testnet:123456789abcdefgABCDEF", "cheqd", []string{}}, - {"Not valid: UniqueID more then 32 symbols", false, "did:cheqd:testnet:123456789abcdefg123456789abcdefgABCDEF", "cheqd", []string{}}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - isDid := IsValidDID(tc.did, tc.method, tc.allowedNS) - - if tc.valid { - require.True(t, isDid) - } else { - require.False(t, isDid) - } - }) - } -} - -func TestSplitJoin(t *testing.T) { - cases := []string{ - "did:cheqd:testnet:123456789abcdefg", - "did:cheqd:testnet:123456789abcdefg", - "did:cheqd:testnet:123456789abcdefg", - "did:cheqd:testnet:123456789abcdefg", - "did:cheqd:123456789abcdefg", - "did:NOTcheqd:123456789abcdefg", - "did:NOTcheqd:123456789abcdefg123456789abcdefg", - "did:cheqd:testnet:123456789abcdefg", - } - - for _, tc := range cases { - // Test split/join - t.Run("split/join "+tc, func(t *testing.T) { - method, namespace, id := MustSplitDID(tc) - require.Equal(t, tc, JoinDID(method, namespace, id)) - }) - } -} - -func TestMustSplitDID(t *testing.T) { - require.Panicsf(t, func() { - MustSplitDID("not did") - }, "must panic") - - method, namespace, id := MustSplitDID("did:cheqd:mainnet:qqqqqqqqqqqqqqqq") - require.Equal(t, "cheqd", method) - require.Equal(t, "mainnet", namespace) - require.Equal(t, "qqqqqqqqqqqqqqqq", id) -} diff --git a/x/resource/utils/did_url.go b/x/resource/utils/did_url.go deleted file mode 100644 index a46527f10..000000000 --- a/x/resource/utils/did_url.go +++ /dev/null @@ -1,118 +0,0 @@ -package utils - -import ( - "errors" - "fmt" - "regexp" -) - -// That for groups: -// Example: did:cheqd:testnet:fafdsffq11213343/path-to-s/ome-external-resource?query#key1??? -// 1 - [^/?#]* - all the symbols except / and ? and # . This is the DID part (did:cheqd:testnet:fafdsffq11213343) -// 2 - [^?#]* - all the symbols except ? and #. it means te section started from /, path-abempty (/path-to-s/ome-external-resource) -// 3 - \?([^#]*) - group for `query` part but with ? symbol (?query) -// 4 - [^#]* - group inside query string, match only exact query (query) -// 5 - #([^#]+[\$]?) - group for fragment, starts with #, includes # (#key1???) -// 6 - [^#]+[\$]? - fragment only (key1???) -// Number of queries is not limited. -var SplitDIDURLRegexp, _ = regexp.Compile(`([^/?#]*)?([^?#]*)(\?([^#]*))?(#([^#]+$))?$`) - -var ( - DIDPathAbemptyRegexp, _ = regexp.Compile(`^([/a-zA-Z0-9\-\.\_\~\!\$\&\'\(\)\*\+\,\;\=\:\@]*|(%[0-9A-Fa-f]{2})*)*$`) - DIDQueryRegexp, _ = regexp.Compile(`^([/a-zA-Z0-9\-\.\_\~\!\$\&\'\(\)\*\+\,\;\=\:\@\/\?]*|(%[0-9A-Fa-f]{2})*)*$`) - DIDFragmentRegexp, _ = regexp.Compile(`^([/a-zA-Z0-9\-\.\_\~\!\$\&\'\(\)\*\+\,\;\=\:\@\/\?]*|(%[0-9A-Fa-f]{2})*)*$`) -) - -// TrySplitDIDUrl Validates generic format of DIDUrl. It doesn't validate path, query and fragment content. -// Call ValidateDIDUrl for further validation. -func TrySplitDIDUrl(didUrl string) (did string, path string, query string, fragment string, err error) { - matches := SplitDIDURLRegexp.FindAllStringSubmatch(didUrl, -1) - - if len(matches) != 1 { - return "", "", "", "", errors.New("unable to split did url into did, path, query and fragment") - } - - match := matches[0] - - return match[1], match[2], match[4], match[6], nil -} - -func MustSplitDIDUrl(didUrl string) (did string, path string, query string, fragment string) { - did, path, query, fragment, err := TrySplitDIDUrl(didUrl) - if err != nil { - panic(err.Error()) - } - return -} - -func JoinDIDUrl(did string, path string, query string, fragment string) string { - res := did + path - - if query != "" { - res = res + "?" + query - } - - if fragment != "" { - res = res + "#" + fragment - } - - return res -} - -// ValidateDIDUrl checks method and allowed namespaces only when the corresponding parameters are specified. -func ValidateDIDUrl(didUrl string, method string, allowedNamespaces []string) error { - did, path, query, fragment, err := TrySplitDIDUrl(didUrl) - if err != nil { - return err - } - - // Validate DID - err = ValidateDID(did, method, allowedNamespaces) - if err != nil { - return err - } - // Validate path - err = ValidatePath(path) - if err != nil { - return err - } - // Validate query - err = ValidateQuery(query) - if err != nil { - return err - } - // Validate fragment - err = ValidateFragment(fragment) - if err != nil { - return err - } - - return nil -} - -func ValidateFragment(fragment string) error { - if !DIDFragmentRegexp.MatchString(fragment) { - return fmt.Errorf("did url fragmnt must match the following regexp: %s", DIDFragmentRegexp) - } - return nil -} - -func ValidateQuery(query string) error { - if !DIDQueryRegexp.MatchString(query) { - return fmt.Errorf("did url query must match the following regexp: %s", DIDQueryRegexp) - } - return nil -} - -func ValidatePath(path string) error { - if !DIDPathAbemptyRegexp.MatchString(path) { - return fmt.Errorf("did url path abempty must match the following regexp: %s", DIDPathAbemptyRegexp) - } - return nil -} - -func IsValidDIDUrl(didUrl string, method string, allowedNamespaces []string) bool { - err := ValidateDIDUrl(didUrl, method, allowedNamespaces) - - return nil == err -} diff --git a/x/resource/utils/did_url_test.go b/x/resource/utils/did_url_test.go deleted file mode 100644 index 0d1f1e4df..000000000 --- a/x/resource/utils/did_url_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package utils - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestIsDidURL(t *testing.T) { - cases := []struct { - name string - valid bool - didUrl string - }{ - // Path: all the possible symbols - {"Valid: the whole alphabet for path", true, "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff"}, - {"Valid: several paths", true, "did:cheqd:testnet:123456789abcdefg/path/to/some/other/place/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff/"}, - {"Valid: the whole alphabet with query", true, "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query"}, - {"Valid: the whole alphabet with query and fragment", true, "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query#fragment"}, - {"Valid: each possible symbols as a path", true, "did:cheqd:testnet:123456789abcdefg/12/ab/AB/-/./_/~/!/$/&/'/(/)/*/+/,/;/=/:/@/%20/%ff"}, - {"Valid: empty path", true, "did:cheqd:testnet:123456789abcdefg/"}, - // Query: all the possible variants - {"Valid: the whole alphabet for query", true, "did:cheqd:testnet:123456789abcdefg/path?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?"}, - {"Valid: the whole alphabet for query and another query", true, "did:cheqd:testnet:123456789abcdefg/path?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query=2?query=3/query=%A4"}, - // Fragment: - {"Valid: the whole alphabet for fragment", true, "did:cheqd:testnet:123456789abcdefg/path?query#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff"}, - {"Valid: the whole alphabet with query and apth", true, "did:cheqd:testnet:123456789abcdefg/path?query#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?"}, - {"Valid: only fragment", true, "did:cheqd:testnet:123456789abcdefg#fragment"}, - {"Valid: only query", true, "did:cheqd:testnet:123456789abcdefg?query"}, - // Wrong cases - {"Not valid: wrong HEXDIG for path (pct-encoded phrase)", false, "did:cheqd:testnet:123456789abcdefg/path%20%zz"}, - {"Not valid: wrong HEXDIG for query (pct-encoded phrase)", false, "did:cheqd:testnet:123456789abcdefg/path?query%20%zz"}, - {"Not valid: wrong HEXDIG for fragment (pct-encoded phrase)", false, "did:cheqd:testnet:123456789abcdefg/path?query#fragment%20%zz"}, - // Wrong splitting (^did:([^:]+?)(:([^:]+?))?:([^:]+)$) - {"Not valid: starts with not 'did'", false, "did123:cheqd:::123456789abcdefg/path?query#fragment"}, - {"Not valid: empty namespace", false, "did:cheqd::123456789abcdefg/path?query#fragment"}, - {"Not valid: a lot of ':'", false, "did:cheqd:::123456789abcdefg/path?query#fragment"}, - {"Not valid: two DIDs in one", false, "did:cheqd:testnet:123456789abcdefg:did:cheqd:testnet:123456789abcdefg/path?query#fragment"}, - // Wrong namespace (^[a-zA-Z0-9]*) - {"Not valid: / - is not allowed for namespace", false, "did:cheqd:testnet/:123456789abcdefg/path?query#fragment"}, - {"Not valid: _ - is not allowed for namespace", false, "did:cheqd:testnet_:123456789abcdefg/path?query#fragment"}, - {"Not valid: % - is not allowed for namespace", false, "did:cheqd:testnet%:123456789abcdefg/path?query#fragment"}, - {"Not valid: * - is not allowed for namespace", false, "did:cheqd:testnet*:123456789abcdefg/path?query#fragment"}, - {"Not valid: & - is not allowed for namespace", false, "did:cheqd:testnet&:123456789abcdefg/path?query#fragment"}, - {"Not valid: @ - is not allowed for namespace", false, "did:cheqd:testnet@/:123456789abcdefg/path?query#fragment"}, - // Base58 checks (^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]*$) - {"Not valid: O - is not allowed for base58", false, "did:cheqd:testnet:123456789abcdefO/path?query#fragment"}, - {"Not valid: I - is not allowed for base58", false, "did:cheqd:testnet:123456789abcdefI/path?query#fragment"}, - {"Not valid: l - is not allowed for base58", false, "did:cheqd:testnet:123456789abcdefl/path?query#fragment"}, - {"Not valid: 0 - is not allowed for base58", false, "did:cheqd:testnet:123456789abcdef0/path?query#fragment"}, - // Length checks (should be exactly 16 or 32) - {"Not valid: UniqueID less then 16 symbols", false, "did:cheqd:testnet:123/path?query#fragment"}, - {"Not valid: UniqueID more then 16 symbols but less then 32", false, "did:cheqd:testnet:123456789abcdefgABCDEF/path?query#fragment"}, - {"Not valid: UniqueID more then 32 symbols", false, "did:cheqd:testnet:123456789abcdefg123456789abcdefgABCDEF/path?query#fragment"}, - {"Not valid: Split should return error", false, "qwerty"}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - isDid := IsValidDIDUrl(tc.didUrl, "", []string{}) - - if tc.valid { - require.True(t, isDid) - } else { - require.False(t, isDid) - } - }) - } -} - -func TestDidURLJoin(t *testing.T) { - cases := []string{ - "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff", - "did:cheqd:testnet:123456789abcdefg/path/to/some/other/place/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff/", - "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query", - "did:cheqd:testnet:123456789abcdefg/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query#fragment", - "did:cheqd:testnet:123456789abcdefg/12/ab/AB/-/./_/~/!/$/&/'/(/)/*/+/,/;/=/:/@/%20/%ff", - "did:cheqd:testnet:123456789abcdefg/", - "did:cheqd:testnet:123456789abcdefg/path?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?", - "did:cheqd:testnet:123456789abcdefg/path?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?query=2?query=3/query=%A4", - "did:cheqd:testnet:123456789abcdefg/path?query#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff", - "did:cheqd:testnet:123456789abcdefg/path?query#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@%20%ff?", - "did:cheqd:testnet:123456789abcdefg#fragment", - "did:cheqd:testnet:123456789abcdefg?query", - } - - for _, tc := range cases { - t.Run("split/join"+tc, func(t *testing.T) { - did, path, query, fragment := MustSplitDIDUrl(tc) - require.Equal(t, tc, JoinDIDUrl(did, path, query, fragment)) - }) - } -} diff --git a/x/resource/utils/encoding.go b/x/resource/utils/encoding.go deleted file mode 100644 index 080f883d4..000000000 --- a/x/resource/utils/encoding.go +++ /dev/null @@ -1,30 +0,0 @@ -package utils - -import ( - "fmt" - - "github.com/multiformats/go-multibase" -) - -func ValidateMultibase(data string) error { - _, _, err := multibase.Decode(data) - return err -} - -func ValidateMultibaseEncoding(data string, expectedEncoding multibase.Encoding) error { - actualEncoding, _, err := multibase.Decode(data) - if err != nil { - return err - } - - if actualEncoding != expectedEncoding { - return fmt.Errorf("invalid actualEncoding. expected: %s actual: %s", - multibase.EncodingToStr[expectedEncoding], multibase.EncodingToStr[actualEncoding]) - } - - return nil -} - -func ValidateBase58(data string) error { - return ValidateMultibaseEncoding(string(multibase.Base58BTC)+data, multibase.Base58BTC) -} diff --git a/x/resource/utils/encoding_test.go b/x/resource/utils/encoding_test.go deleted file mode 100644 index d06f74dda..000000000 --- a/x/resource/utils/encoding_test.go +++ /dev/null @@ -1,115 +0,0 @@ -package utils - -import ( - "encoding/json" - "testing" - - "github.com/multiformats/go-multibase" - "github.com/stretchr/testify/require" -) - -type TestJWKKey struct { - Kty string `json:"kty"` - N string `json:"n"` - Use string `json:"use"` - Alg string `json:"alg"` - E string `json:"e"` - Kid string `json:"kid"` -} - -var ValidJWKKey = TestJWKKey{ - Kty: "RSA", - N: "o76AudS2rsCvlz_3D47sFkpuz3NJxgLbXr1cHdmbo9xOMttPMJI97f0rHiSl9stltMi87KIOEEVQWUgMLaWQNaIZThgI1seWDAGRw59AO5sctgM1wPVZYt40fj2Qw4KT7m4RLMsZV1M5NYyXSd1lAAywM4FT25N0RLhkm3u8Hehw2Szj_2lm-rmcbDXzvjeXkodOUszFiOqzqBIS0Bv3c2zj2sytnozaG7aXa14OiUMSwJb4gmBC7I0BjPv5T85CH88VOcFDV51sO9zPJaBQnNBRUWNLh1vQUbkmspIANTzj2sN62cTSoxRhSdnjZQ9E_jraKYEW5oizE9Dtow4EvQ", - Use: "sig", - Alg: "RS256", - E: "AQAB", - Kid: "6a8ba5652a7044121d4fedac8f14d14c54e4895b", -} - -var NotValidJWKKey = TestJWKKey{ - Kty: "SomeOtherKeyType", - N: "o76AudS2rsCvlz_3D47sFkpuz3NJxgLbXr1cHdmbo9xOMttPMJI97f0rHiSl9stltMi87KIOEEVQWUgMLaWQNaIZThgI1seWDAGRw59AO5sctgM1wPVZYt40fj2Qw4KT7m4RLMsZV1M5NYyXSd1lAAywM4FT25N0RLhkm3u8Hehw2Szj_2lm-rmcbDXzvjeXkodOUszFiOqzqBIS0Bv3c2zj2sytnozaG7aXa14OiUMSwJb4gmBC7I0BjPv5T85CH88VOcFDV51sO9zPJaBQnNBRUWNLh1vQUbkmspIANTzj2sN62cTSoxRhSdnjZQ9E_jraKYEW5oizE9Dtow4EvQ", - Use: "sig", - Alg: "RS256", - E: "AQAB", - Kid: "6a8ba5652a7044121d4fedac8f14d14c54e4895b", -} - -var ( - ValidJWKByte, _ = json.Marshal(ValidJWKKey) - NotValidJWKByte, _ = json.Marshal(NotValidJWKKey) -) - -func TestValidateMultibase(t *testing.T) { - cases := []struct { - name string - data string - encoding multibase.Encoding - valid bool - }{ - {"Valid: General pmbkey", "zABCDEFG123456789", multibase.Base58BTC, true}, - {"Not Valid: cannot be empty", "", multibase.Base58BTC, false}, - {"Not Valid: without z but base58", "ABCDEFG123456789", multibase.Base58BTC, false}, - {"Not Valid: without z and not base58", "OIl0ABCDEFG123456789", multibase.Base58BTC, false}, - {"Not Valid: with z but not base58", "zOIl0ABCDEFG123456789", multibase.Base58BTC, false}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - err := ValidateMultibase(tc.data) - - if tc.valid { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -func TestValidateBase58(t *testing.T) { - cases := []struct { - name string - data string - valid bool - }{ - {"Valid: General pmbkey", "ABCDEFG123456789", true}, - {"Not Valid: cannot be empty", "", false}, - {"Not Valid: not base58", "OIl0ABCDEFG123456789", false}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - err := ValidateBase58(tc.data) - - if tc.valid { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -func TestValidateJWK(t *testing.T) { - cases := []struct { - name string - data string - valid bool - }{ - {"Valid: General jwk", string(ValidJWKByte), true}, - {"Not Valid: Bad jwk", string(NotValidJWKByte), false}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - err := ValidateJWK(tc.data) - - if tc.valid { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} diff --git a/x/resource/utils/proto.go b/x/resource/utils/proto.go deleted file mode 100644 index e25f37e8a..000000000 --- a/x/resource/utils/proto.go +++ /dev/null @@ -1,8 +0,0 @@ -package utils - -import "github.com/gogo/protobuf/proto" - -// MsgTypeURL returns the TypeURL of a `proto.Message`. -func MsgTypeURL(msg proto.Message) string { - return "/" + proto.MessageName(msg) -} diff --git a/x/resource/utils/proto_test.go b/x/resource/utils/proto_test.go deleted file mode 100644 index d62252a9b..000000000 --- a/x/resource/utils/proto_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package utils - -import ( - "testing" - - bank_types "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/stretchr/testify/assert" -) - -func Test_MsgTypeUrl(t *testing.T) { - assert.Equal(t, "/cosmos.bank.v1beta1.DenomUnit", MsgTypeURL(&bank_types.DenomUnit{})) -} diff --git a/x/resource/utils/str.go b/x/resource/utils/str.go deleted file mode 100644 index 723d539f4..000000000 --- a/x/resource/utils/str.go +++ /dev/null @@ -1,98 +0,0 @@ -package utils - -import "sort" - -func IndexOf(array []string, searchElement string, fromIndex int) int { - for i, v := range array[fromIndex:] { - if v == searchElement { - return fromIndex + i - } - } - - return -1 -} - -func Contains(vs []string, t string) bool { - return IndexOf(vs, t, 0) >= 0 -} - -func Filter(vs []string, f func(string) bool) []string { - vsf := make([]string, 0) - for _, v := range vs { - if f(v) { - vsf = append(vsf, v) - } - } - return vsf -} - -func Subtract(minuend []string, subtrahend []string) []string { - m := map[string]bool{} - - for _, v := range minuend { - m[v] = true - } - - for _, v := range subtrahend { - delete(m, v) - } - - result := make([]string, 0, len(m)) - - for k := range m { - result = append(result, k) - } - - return result -} - -// Unique returns a copy of the passed array with duplicates removed -func Unique(array []string) []string { - m := map[string]bool{} - - for _, v := range array { - m[v] = true - } - - result := make([]string, 0, len(m)) - - for k := range m { - result = append(result, k) - } - - return result -} - -func IsUnique(list []string) bool { - set := map[string]bool{} - - for _, did := range list { - set[did] = true - } - - return len(list) == len(set) -} - -func ToInterfaces(list []string) []interface{} { - res := make([]interface{}, len(list)) - - for i := range list { - res[i] = list[i] - } - - return res -} - -func ReplaceInSlice(list []string, old, new string) { - for i := range list { - if list[i] == old { - list[i] = new - } - } -} - -func UniqueSorted(ls []string) []string { - tmp_ := Unique(ls) - sort.Strings(tmp_) - return tmp_ -} diff --git a/x/resource/utils/str_test.go b/x/resource/utils/str_test.go deleted file mode 100644 index 80a91eb4f..000000000 --- a/x/resource/utils/str_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package utils - -import ( - "sort" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestIndexOf(t *testing.T) { - cases := []struct { - array []string - searchElement string - fromIndex int - expectedResult int - }{ - {[]string{}, "", 0, -1}, - {nil, "", 0, -1}, - {[]string{"1", "2"}, "1", 0, 0}, - {[]string{"1", "2", "3"}, "3", 0, 2}, - {[]string{"1", "2", "3"}, "4", 0, -1}, - {[]string{"4", "1", "6", "2", "3", "4"}, "4", 0, 0}, - {[]string{"4", "1", "6", "2", "3", "4"}, "4", 1, 5}, - {[]string{"4", "1", "6", "2", "3", "4"}, "4", 3, 5}, - } - - for _, tc := range cases { - actual := IndexOf(tc.array, tc.searchElement, tc.fromIndex) - require.Equal(t, tc.expectedResult, actual) - } -} - -func TestContains(t *testing.T) { - cases := []struct { - array []string - searchElement string - expectedResult bool - }{ - {[]string{}, "", false}, - {nil, "", false}, - {[]string{"1", "2"}, "1", true}, - {[]string{"1", "2", "3"}, "2", true}, - {[]string{"1", "2", "3"}, "3", true}, - {[]string{"1", "2", "3"}, "123", false}, - } - - for _, tc := range cases { - actual := Contains(tc.array, tc.searchElement) - require.Equal(t, tc.expectedResult, actual) - } -} - -func TestSubtract(t *testing.T) { - cases := []struct { - first []string - second []string - expected []string - }{ - {[]string{}, []string{}, []string{}}, - {nil, []string{}, []string{}}, - {nil, nil, []string{}}, - {[]string{"1", "2"}, []string{"1", "2"}, []string{}}, - {[]string{"1", "2", "3"}, []string{}, []string{"1", "2", "3"}}, - {[]string{"1", "2", "3"}, nil, []string{"1", "2", "3"}}, - {[]string{"1", "2", "3"}, []string{"4", "5", "6"}, []string{"1", "2", "3"}}, - {[]string{"1", "2", "3"}, []string{"1", "5", "2"}, []string{"3"}}, - {[]string{"4", "1", "6", "2", "3"}, []string{"1", "5", "2"}, []string{"3", "4", "6"}}, - } - - for _, tc := range cases { - actual := Subtract(tc.first, tc.second) - // We can't compare arrays directly cause result of `subtract` is not deterministic - sort.Strings(actual) - require.Equal(t, tc.expected, actual) - } -} - -func TestUnique(t *testing.T) { - cases := []struct { - array []string - expected []string - }{ - {[]string{}, []string{}}, - {nil, []string{}}, - {[]string{"1", "2"}, []string{"1", "2"}}, - {[]string{"1", "3", "2"}, []string{"1", "2", "3"}}, - {[]string{"4", "1", "6", "2", "3", "1", "3", "1"}, []string{"1", "2", "3", "4", "6"}}, - } - - for _, tc := range cases { - actual := Unique(tc.array) - // We can't compare arrays directly cause result of `unique` is not deterministic - sort.Strings(actual) - require.Equal(t, tc.expected, actual) - } -} - -func TestReplaceInList(t *testing.T) { - list := []string{"1", "2", "3", "2"} - ReplaceInSlice(list, "2", "3") - - require.Equal(t, []string{"1", "3", "3", "3"}, list) -} - -func TestUniqueSorted(t *testing.T) { - cases := []struct { - name string - input []string - output []string - }{ - {"General alphabet list", []string{"aa", "bb"}, []string{"aa", "bb"}}, - {"General alphabet reverse list", []string{"bb", "aa"}, []string{"aa", "bb"}}, - {"General number list", []string{"22", "11"}, []string{"11", "22"}}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - res := UniqueSorted(tc.input) - require.Equal(t, res, tc.output) - }) - } -} diff --git a/x/resource/utils/tx.go b/x/resource/utils/tx.go deleted file mode 100644 index 7a4c95e4e..000000000 --- a/x/resource/utils/tx.go +++ /dev/null @@ -1,17 +0,0 @@ -package utils - -import ( - "fmt" - "github.com/google/uuid" - "github.com/tendermint/tendermint/types" -) - -func GetTxHash(txBytes []byte) string { - // return base64.StdEncoding.EncodeToString(tmhash.Sum(txBytes)) - return fmt.Sprintf("%X", types.Tx(txBytes).Hash()) -} - -func ValidateUUID(u string) error { - _, err := uuid.Parse(u) - return err -} diff --git a/x/resource/utils/uri.go b/x/resource/utils/uri.go deleted file mode 100644 index b8f5fcc1c..000000000 --- a/x/resource/utils/uri.go +++ /dev/null @@ -1,18 +0,0 @@ -package utils - -import ( - "fmt" - "regexp" -) - -// Goes from RFC: https://www.rfc-editor.org/rfc/rfc3986#appendix-B -var ValidURIRegexp, _ = regexp.Compile(`^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?`) - -func ValidateURI(uri string) error { - // Match with Regexp from RFC - if !ValidURIRegexp.MatchString(uri) { - return fmt.Errorf("URI: %s does not match regexp: %s", uri, ValidURIRegexp) - } - - return nil -} diff --git a/x/resource/utils/uri_test.go b/x/resource/utils/uri_test.go deleted file mode 100644 index 9e7de26bc..000000000 --- a/x/resource/utils/uri_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package utils - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestValidateURI(t *testing.T) { - cases := []struct { - name string - valid bool - URI string - }{ - // Path: all the possible symbols - {"Valid: General http URI path", true, "http://a.com/a/b/c/d/?query=123#fragment=another_part"}, - {"Valid: General https URI path", true, "https://a.com/a/b/c/d/?query=123#fragment=another_part"}, - {"Valid: only alphabet symbols", true, "SomeAnotherPath"}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - err_ := ValidateURI(tc.URI) - - if tc.valid { - require.NoError(t, err_) - } else { - require.Error(t, err_) - } - }) - } -} diff --git a/x/resource/utils/uuid.go b/x/resource/utils/uuid.go new file mode 100644 index 000000000..d6c19ebb4 --- /dev/null +++ b/x/resource/utils/uuid.go @@ -0,0 +1,18 @@ +package utils + +import ( + "errors" + "github.com/google/uuid" + "strconv" +) + +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 +} diff --git a/x/resource/utils/uuid_test.go b/x/resource/utils/uuid_test.go new file mode 100644 index 000000000..38fde6de6 --- /dev/null +++ b/x/resource/utils/uuid_test.go @@ -0,0 +1,32 @@ +package utils + +import ( + "github.com/stretchr/testify/require" + "testing" +) + +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_) + } + }) + } +} From 7a8c739d3de2113b03b47fec8bb8b172fe3d7e97 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Thu, 16 Jun 2022 16:45:14 +0300 Subject: [PATCH 08/65] Implementing resources creation --- app/app.go | 16 ++++- x/cheqd/keeper/keeper_did.go | 1 + x/cheqd/keeper/msg_server.go | 52 ++++++++++++++++ x/cheqd/keeper/msg_server_create_did.go | 14 +---- x/cheqd/keeper/msg_server_update_did.go | 26 ++------ x/cheqd/module.go | 2 +- x/cheqd/types/error.go | 1 + x/cheqd/types/validate.go | 11 ++++ x/cheqd/utils/did.go | 17 ++++-- x/resource/handler.go | 5 +- x/resource/keeper/keeper_resource.go | 59 +++++++++---------- x/resource/keeper/msg_server.go | 36 +++-------- .../keeper/msg_server_create_resource.go | 32 +++++++--- x/resource/module.go | 11 ++-- x/resource/types/genesis.go | 1 - x/resource/types/keys.go | 1 - x/resource/types/tx_msg_create_resource.go | 5 +- .../types/tx_msg_create_resource_payload.go | 13 ++-- .../tx_msg_create_resource_payload_test.go | 41 +++++++++++++ 19 files changed, 222 insertions(+), 122 deletions(-) create mode 100644 x/resource/types/tx_msg_create_resource_payload_test.go diff --git a/app/app.go b/app/app.go index 95f1f8b9a..c850233ad 100644 --- a/app/app.go +++ b/app/app.go @@ -1,12 +1,14 @@ package app import ( + "github.com/cheqd/cheqd-node/x/resource" "io" "net/http" "os" "path/filepath" 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 +39,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 +150,7 @@ var ( feegrantmodule.AppModuleBasic{}, authzmodule.AppModuleBasic{}, cheqd.AppModuleBasic{}, + resource.AppModuleBasic{}, ) // module account permissions @@ -215,6 +219,7 @@ type App struct { ScopedTransferKeeper capabilitykeeper.ScopedKeeper cheqdKeeper cheqdkeeper.Keeper + resourceKeeper resourcekeeper.Keeper // the module manager mm *module.Manager @@ -243,7 +248,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 +383,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 +427,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 +447,7 @@ func New( stakingtypes.ModuleName, ibchost.ModuleName, cheqdtypes.ModuleName, + resourcetypes.ModuleName, genutiltypes.ModuleName, banktypes.ModuleName, crisistypes.ModuleName, @@ -461,6 +472,7 @@ func New( evidencetypes.ModuleName, ibchost.ModuleName, cheqdtypes.ModuleName, + resourcetypes.ModuleName, genutiltypes.ModuleName, banktypes.ModuleName, ibctransfertypes.ModuleName, @@ -493,6 +505,7 @@ func New( feegrant.ModuleName, authz.ModuleName, cheqdtypes.ModuleName, + resourcetypes.ModuleName, vestingtypes.ModuleName, upgradetypes.ModuleName, paramstypes.ModuleName, @@ -515,6 +528,7 @@ func New( feegrant.ModuleName, authz.ModuleName, cheqdtypes.ModuleName, + resourcetypes.ModuleName, paramstypes.ModuleName, vestingtypes.ModuleName, upgradetypes.ModuleName, diff --git a/x/cheqd/keeper/keeper_did.go b/x/cheqd/keeper/keeper_did.go index a71ca3d0f..f694923df 100644 --- a/x/cheqd/keeper/keeper_did.go +++ b/x/cheqd/keeper/keeper_did.go @@ -99,6 +99,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..4855981f7 100644 --- a/x/cheqd/keeper/msg_server.go +++ b/x/cheqd/keeper/msg_server.go @@ -105,3 +105,55 @@ func VerifySignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types. return nil } + +func VerifyAllSignersHaveExactlyOneValidSignature(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) + } + + if len(signatures) > 1 { + return types.ErrMultipleSignatures.Wrapf("signer: %s", signer) + } + + signature := signatures[0] + + 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 +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..43d6d6b22 100644 --- a/x/cheqd/keeper/msg_server_create_did.go +++ b/x/cheqd/keeper/msg_server_create_did.go @@ -45,17 +45,9 @@ 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 := VerifySignature(&k.Keeper, &ctx, inMemoryDids, msg.Payload.GetSignBytes(), signature) - if err != nil { - return nil, err - } + err = VerifyAllSignersHaveExactlyOneValidSignature(&k.Keeper, &ctx, inMemoryDids, msg.GetSignBytes(), signers, msg.GetSignatures()) + if err != nil { + return nil, err } // Apply changes diff --git a/x/cheqd/keeper/msg_server_update_did.go b/x/cheqd/keeper/msg_server_update_did.go index 4bc22e264..65f63fa3c 100644 --- a/x/cheqd/keeper/msg_server_update_did.go +++ b/x/cheqd/keeper/msg_server_update_did.go @@ -71,28 +71,14 @@ 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) - } - - found := false - for _, signature := range signaturesBySigner { - err := VerifySignature(&k.Keeper, &ctx, inMemoryDids, signBytes, signature) - if err == nil { - found = true - break - } - } - - if !found { - return nil, types.ErrSignatureNotFound.Wrapf("there should be at least one valid signature by %s", signerForErrorMessage) - } + err = VerifyAllSignersHaveAtLeastOneValidSignature(&k.Keeper, &ctx, inMemoryDids, signBytes, signers, extendedSignatures, existingDid.Id, updatedDid.Id) + if err != nil { + return nil, err } // Apply changes: return original id and modify state diff --git a/x/cheqd/module.go b/x/cheqd/module.go index 9c59efdaa..022fe3b96 100644 --- a/x/cheqd/module.go +++ b/x/cheqd/module.go @@ -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 diff --git a/x/cheqd/types/error.go b/x/cheqd/types/error.go index 48bb7fc60..ce1a000bc 100644 --- a/x/cheqd/types/error.go +++ b/x/cheqd/types/error.go @@ -11,6 +11,7 @@ var ( ErrBadRequest = sdkerrors.Register(ModuleName, 1000, "bad request") ErrInvalidSignature = sdkerrors.Register(ModuleName, 1100, "invalid signature detected") ErrSignatureNotFound = sdkerrors.Register(ModuleName, 1101, "signature is required but not found") + ErrMultipleSignatures = sdkerrors.Register(ModuleName, 1102, "signature is required but not found") ErrDidDocExists = sdkerrors.Register(ModuleName, 1200, "DID Doc exists") ErrDidDocNotFound = sdkerrors.Register(ModuleName, 1201, "DID Doc not found") ErrVerificationMethodNotFound = sdkerrors.Register(ModuleName, 1202, "verification method not found") diff --git a/x/cheqd/types/validate.go b/x/cheqd/types/validate.go index f91a658bc..b3c699a84 100644 --- a/x/cheqd/types/validate.go +++ b/x/cheqd/types/validate.go @@ -38,6 +38,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) diff --git a/x/cheqd/utils/did.go b/x/cheqd/utils/did.go index d33528a1c..cb3b005b5 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,26 @@ func ValidateDID(did string, method string, allowedNamespaces []string) error { return err } -func ValidateUniqueId(uniqueId string) error { +func IsValidDID(did string, method string, allowedNamespaces []string) bool { + err := ValidateDID(did, method, allowedNamespaces) + return err == nil +} + +func ValidateID(id string) error { // Length should be 16 or 32 symbols - if len(uniqueId) != 16 && len(uniqueId) != 32 { + if len(id) != 16 && len(id) != 32 { return fmt.Errorf("unique id length should be 16 or 32 symbols") } // Base58 check - if err := ValidateBase58(uniqueId); err != nil { + if err := ValidateBase58(id); err != nil { return fmt.Errorf("unique id must be valid base58 string: %s", err) } 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/resource/handler.go b/x/resource/handler.go index e7c80ff35..5526de917 100644 --- a/x/resource/handler.go +++ b/x/resource/handler.go @@ -2,6 +2,7 @@ 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" @@ -9,8 +10,8 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -func NewHandler(k keeper.Keeper) sdk.Handler { - msgServer := keeper.NewMsgServer(k) +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()) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index 7023d55f6..ceb24efd9 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -11,7 +11,7 @@ import ( // GetResourceCount get the total number of resource func (k Keeper) GetResourceCount(ctx *sdk.Context) uint64 { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceCountKey)) + store := ctx.KVStore(k.storeKey) byteKey := types.KeyPrefix(types.ResourceCountKey) bz := store.Get(byteKey) @@ -23,7 +23,7 @@ func (k Keeper) GetResourceCount(ctx *sdk.Context) uint64 { // Parse bytes count, err := strconv.ParseUint(string(bz), 10, 64) if err != nil { - // Panic because the count should be always formattable to iint64 + // Panic because the count should be always formattable to int64 panic("cannot decode count") } @@ -32,51 +32,41 @@ func (k Keeper) GetResourceCount(ctx *sdk.Context) uint64 { // SetResourceCount set the total number of resource func (k Keeper) SetResourceCount(ctx *sdk.Context, count uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceCountKey)) + store := ctx.KVStore(k.storeKey) byteKey := types.KeyPrefix(types.ResourceCountKey) + + // Set bytes bz := []byte(strconv.FormatUint(count, 10)) store.Set(byteKey, bz) } -// AppendResource appends a resource in the store with a new id and updates the count -func (k Keeper) AppendResource(ctx *sdk.Context, resource *types.Resource) error { - // Check that resource doesn't exist - if k.HasResource(ctx, resource.CollectionId, resource.Id) { - return types.ErrResourceExists.Wrapf(resource.Id) - } - - // Create the resource - count := k.GetResourceCount(ctx) - err := k.SetResource(ctx, resource) - if err != nil { - return err - } - - // Update resource count - k.SetResourceCount(ctx, count+1) - return nil -} - // SetResource set a specific resource in the store func (k Keeper) SetResource(ctx *sdk.Context, resource *types.Resource) error { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - b := k.cdc.MustMarshal(resource) - store.Set(GetResourceKeyBytes(resource.CollectionId, resource.Id), b) + key := GetResourceKeyBytes(resource.CollectionId, resource.Id) + bytes := k.cdc.MustMarshal(resource) + + if !store.Has(key) { + count := k.GetResourceCount(ctx) + k.SetResourceCount(ctx, count+1) + } + + store.Set(key, bytes) return nil } // GetResource returns a resource from its id func (k Keeper) GetResource(ctx *sdk.Context, collectionId string, id string) (types.Resource, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - if !k.HasResource(ctx, collectionId, id) { return types.Resource{}, sdkerrors.ErrNotFound.Wrap(id) } - var value types.Resource + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) bytes := store.Get(GetResourceKeyBytes(collectionId, id)) + + var value types.Resource if err := k.cdc.Unmarshal(bytes, &value); err != nil { - return types.Resource{}, sdkerrors.Wrap(sdkerrors.ErrInvalidType, err.Error()) + return types.Resource{}, sdkerrors.ErrInvalidType.Wrap(err.Error()) } return value, nil @@ -93,10 +83,17 @@ func GetResourceKeyBytes(collectionId string, id string) []byte { return []byte(collectionId + ":" + id) } -// GetAllResource returns all resource +// GetAllCollectionResourceIterator returns an iterator over all resources of a collection +// It's up to the caller to close the iterator +func (k Keeper) GetAllCollectionResourceIterator(ctx *sdk.Context, collectionId string) (iterator sdk.Iterator) { + collectionPrefix := types.KeyPrefix(types.ResourceKey + collectionId + ":") + return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), collectionPrefix) +} + +// 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) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) defer func(iterator sdk.Iterator) { err := iterator.Close() diff --git a/x/resource/keeper/msg_server.go b/x/resource/keeper/msg_server.go index 0af835351..a86b4bd49 100644 --- a/x/resource/keeper/msg_server.go +++ b/x/resource/keeper/msg_server.go @@ -1,43 +1,21 @@ package keeper import ( - cheqd_types "github.com/cheqd/cheqd-node/x/cheqd/types" + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" "github.com/cheqd/cheqd-node/x/resource/types" - sdk "github.com/cosmos/cosmos-sdk/types" ) type msgServer struct { Keeper + cheqdKeeper cheqdkeeper.Keeper } // NewMsgServer returns an implementation of the MsgServer interface for the provided Keeper. -func NewMsgServer(keeper Keeper) types.MsgServer { - return &msgServer{Keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func FindResource(k *Keeper, ctx *sdk.Context, inMemoryResources map[string]types.Resource, collectionId string, id string) (res types.Resource, found bool, err error) { - // Look in inMemory dict - value, found := inMemoryResources[collectionId+id] - if found { - return value, true, nil - } - - // Look in state - if k.HasResource(ctx, collectionId, id) { - value, err := k.GetResource(ctx, collectionId, id) - if err != nil { - return types.Resource{}, false, err - } - - return value, true, nil +func NewMsgServer(keeper Keeper, cheqdKeeper cheqdkeeper.Keeper) types.MsgServer { + return &msgServer{ + Keeper: keeper, + cheqdKeeper: cheqdKeeper, } - - return types.Resource{}, false, nil } -func VerifySignature(k *Keeper, ctx *sdk.Context, inMemoryResources map[string]types.Resource, message []byte, signature cheqd_types.SignInfo) error { - //TODO: implement - return nil -} +var _ types.MsgServer = msgServer{} diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index a482e3baf..958f8bce5 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -2,8 +2,8 @@ package keeper import ( "context" - - cheqd_types "github.com/cheqd/cheqd-node/x/cheqd/types" + 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" ) @@ -11,24 +11,36 @@ import ( 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) + if !k.cheqdKeeper.HasDid(&ctx, did) { + return nil, cheqdtypes.ErrDidDocNotFound.Wrapf(did) + } + // Validate Resource doesn't exist if k.HasResource(&ctx, msg.Payload.CollectionId, msg.Payload.Id) { return nil, types.ErrResourceExists.Wrap(msg.Payload.Id) } - // Build Resource - resource := msg.Payload.ToResource() - // Consider resource that we are going to create during resource resolutions - inMemoryResources := map[string]types.Resource{resource.CollectionId + resource.Id: resource} + + + + + + + // getDid + // get signatures for did modification + // // Verify signatures signers := GetSignerDIDsForResourceCreation(resource) for _, signer := range signers { - signature, found := cheqd_types.FindSignInfoBySigner(msg.Signatures, signer) + signature, found := cheqdtypes.FindSignInfoBySigner(msg.Signatures, signer) if !found { - return nil, cheqd_types.ErrSignatureNotFound.Wrapf("signer: %s", signer) + return nil, cheqdtypes.ErrSignatureNotFound.Wrapf("signer: %s", signer) } err := VerifySignature(&k.Keeper, &ctx, inMemoryResources, msg.Payload.GetSignBytes(), signature) @@ -37,6 +49,10 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes } } + // Build Resource + resource := msg.Payload.ToResource() + // set created, checksum + // Apply changes err := k.AppendResource(&ctx, &resource) if err != nil { diff --git a/x/resource/module.go b/x/resource/module.go index 19899ad88..c44409b4f 100644 --- a/x/resource/module.go +++ b/x/resource/module.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" "log" "github.com/cheqd/cheqd-node/x/resource/client/cli" @@ -100,17 +101,19 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { // AppModule // ---------------------------------------------------------------------------- -// AppModule implements the AppModule interface for the capability module. +// 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) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, cheqdKeeper cheqdkeeper.Keeper) AppModule { return AppModule{ AppModuleBasic: NewAppModuleBasic(cdc), keeper: keeper, + cheqdKeeper: cheqdKeeper, } } @@ -119,7 +122,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { // introduced by the module. To avoid wrong/empty versions, the initial version // should be set to 1. func (am AppModule) ConsensusVersion() uint64 { - return 3 + return 1 } // Name returns the capability module's name. @@ -129,7 +132,7 @@ func (am AppModule) Name() string { // Route returns the capability module's message routing key. func (am AppModule) Route() sdk.Route { - return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper)) + return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper, am.cheqdKeeper)) } // QuerierRoute returns the capability module's query routing key. diff --git a/x/resource/types/genesis.go b/x/resource/types/genesis.go index 91c9c7036..4c7234e3d 100644 --- a/x/resource/types/genesis.go +++ b/x/resource/types/genesis.go @@ -1,4 +1,3 @@ -// TODO: package types import ( diff --git a/x/resource/types/keys.go b/x/resource/types/keys.go index 3325ced54..7fe501c82 100644 --- a/x/resource/types/keys.go +++ b/x/resource/types/keys.go @@ -19,7 +19,6 @@ func KeyPrefix(p string) []byte { } const ( - CollectionKey = "collection:" ResourceKey = "resource:" ResourceCountKey = "resource-count:" ) diff --git a/x/resource/types/tx_msg_create_resource.go b/x/resource/types/tx_msg_create_resource.go index 61d3cfd98..ccfe9bfef 100644 --- a/x/resource/types/tx_msg_create_resource.go +++ b/x/resource/types/tx_msg_create_resource.go @@ -33,7 +33,7 @@ func (msg *MsgCreateResource) GetSignBytes() []byte { } func (msg *MsgCreateResource) ValidateBasic() error { - err := msg.Validate() + err := msg.Validate([]string{}) if err != nil { return ErrBasicValidation.Wrap(err.Error()) } @@ -43,8 +43,9 @@ func (msg *MsgCreateResource) ValidateBasic() error { // Validate -func (msg MsgCreateResource) Validate() error { +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 index a0128b95b..547d5d048 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -12,8 +12,6 @@ func (msg *MsgCreateResourcePayload) GetSignBytes() []byte { } func (msg *MsgCreateResourcePayload) ToResource() Resource { - created := "" - checksum := "" return Resource{ CollectionId: msg.CollectionId, Id: msg.Id, @@ -21,8 +19,8 @@ func (msg *MsgCreateResourcePayload) ToResource() Resource { ResourceType: msg.ResourceType, MimeType: msg.MimeType, Data: msg.Data, - Created: created, - Checksum: checksum, + Created: "", + Checksum: "", } } @@ -30,7 +28,12 @@ func (msg *MsgCreateResourcePayload) ToResource() Resource { func (msg MsgCreateResourcePayload) Validate() error { return validation.ValidateStruct(&msg, - validation.Field(&msg.CollectionId, validation.Required, IsUUID()), // TODO: Wrong + validation.Field(&msg.CollectionId, validation.Required, cheqdTypes.IsID()), + validation.Field(&msg.Id, validation.Required, IsUUID()), + validation.Field(&msg.Name, validation.Required, validation.Length(1, 64)), + // TODO: add validation for resource type + // TODO: add validation for mime type + validation.Field(&msg.Data, validation.Required, validation.Length(1, 1024*1024)), // 1MB ) } 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..1c716c1c1 --- /dev/null +++ b/x/resource/types/tx_msg_create_resource_payload_test.go @@ -0,0 +1,41 @@ +package types + +import ( + "github.com/stretchr/testify/require" + "testing" +) + +func TestMsgUpdateDidValidation(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", + MimeType: "text/plain", + Data: []byte {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + }, + isValid: true, + }, + } + + 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) + } + }) + } +} From a9085089b666242f88794c7f00778437a750a125 Mon Sep 17 00:00:00 2001 From: toktar Date: Thu, 16 Jun 2022 16:47:48 +0300 Subject: [PATCH 09/65] dev-1281: add resource unit tests --- x/resource/tests/constants.go | 48 +- x/resource/tests/create_did_test.go | 403 --------------- x/resource/tests/create_resource_test.go | 103 ++++ x/resource/tests/setup.go | 293 ++--------- .../tests/signature_verification_test.go | 142 ----- x/resource/tests/update_did_test.go | 483 ------------------ x/resource/tests/utils.go | 48 -- 7 files changed, 176 insertions(+), 1344 deletions(-) delete mode 100644 x/resource/tests/create_did_test.go create mode 100644 x/resource/tests/create_resource_test.go delete mode 100644 x/resource/tests/signature_verification_test.go delete mode 100644 x/resource/tests/update_did_test.go delete mode 100644 x/resource/tests/utils.go diff --git a/x/resource/tests/constants.go b/x/resource/tests/constants.go index a1d4cc243..d95ea04f7 100644 --- a/x/resource/tests/constants.go +++ b/x/resource/tests/constants.go @@ -1,22 +1,34 @@ package tests +import ( + "crypto/sha256" + + "github.com/cheqd/cheqd-node/x/resource/types" +) + const ( - AliceDID = "did:cheqd:test:aaaaaaaaaaaaaaaa" - BobDID = "did:cheqd:test:bbbbbbbbbbbbbbbb" - CharlieDID = "did:cheqd:test:cccccccccccccccc" - ImposterDID = "did:cheqd:test:nananananananana" - NotFounDID = "did:cheqd:test:nfdnfdnfdnfdnfdd" - AliceKey1 = AliceDID + "#key-1" - AliceKey2 = AliceDID + "#key-2" - BobKey1 = BobDID + "#key-1" - BobKey2 = BobDID + "#key-2" - BobKey3 = BobDID + "#key-3" - BobKey4 = BobDID + "#key-4" - ImposterKey1 = ImposterDID + "#key-1" - ImposterKey2 = ImposterDID + "#key-2" - NotFoundKey1 = NotFounDID + "#key-1" - CharlieKey1 = CharlieDID + "#key-1" - CharlieKey2 = CharlieDID + "#key-2" - CharlieKey3 = CharlieDID + "#key-3" - CharlieKey4 = CharlieDID + "#key-4" + CLSchemaType = "CL-Schema" + SchemaData = "{\"attr\":[\"name\",\"age\"]}" + TestResourceName = "Test Resource Name" + JsonResourceType = "application/json" + ResourceId = "988b0ab3-6a39-4598-83ec-b84c6cf8da15" + IncorrectResourceId = "1234" + + NotFounDID = "did:cheqd:test:nfdnfdnfdnfdnfdd" + ExistingDID = "did:cheqd:test:aaaaaaaaaaaaaaaa" + ExistingDIDKey = ExistingDID + "#key-1" ) + +func ExistingResource() types.Resource { + data := []byte(SchemaData) + checksum := string(sha256.New().Sum(data)) + return types.Resource{ + CollectionId: ExistingDID, + Id: "a09abea0-22e0-4b35-8f70-9cc3a6d0b5fd", + Name: "Existing Resource Name", + ResourceType: CLSchemaType, + MimeType: JsonResourceType, + Data: data, + Checksum: checksum, + } +} diff --git a/x/resource/tests/create_did_test.go b/x/resource/tests/create_did_test.go deleted file mode 100644 index c9415fc99..000000000 --- a/x/resource/tests/create_did_test.go +++ /dev/null @@ -1,403 +0,0 @@ -package tests - -import ( - "crypto/ed25519" - "fmt" - "testing" - - "github.com/btcsuite/btcutil/base58" - - "github.com/cheqd/cheqd-node/x/cheqd/types" - "github.com/multiformats/go-multibase" - - "github.com/stretchr/testify/require" -) - -func TestCreateDID(t *testing.T) { - var err error - keys := GenerateTestKeys() - cases := []struct { - valid bool - name string - keys map[string]KeyPair - signers []string - msg *types.MsgCreateDidPayload - errMsg string - }{ - { - valid: true, - name: "Valid: Works", - keys: map[string]KeyPair{ - ImposterKey1: GenerateKeyPair(), - }, - signers: []string{ImposterKey1}, - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - Authentication: []string{ImposterKey1}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: ImposterKey1, - Type: Ed25519VerificationKey2020, - Controller: ImposterDID, - }, - }, - }, - }, - { - valid: true, - name: "Valid: Works with Key Agreement", - keys: map[string]KeyPair{ - ImposterKey1: GenerateKeyPair(), - AliceKey1: keys[AliceKey1], - }, - signers: []string{ImposterKey1, AliceKey1}, - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - KeyAgreement: []string{ImposterKey1}, - Controller: []string{AliceDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: ImposterKey1, - Type: Ed25519VerificationKey2020, - Controller: ImposterDID, - }, - }, - }, - }, - { - valid: true, - name: "Valid: Works with Assertion Method", - keys: map[string]KeyPair{ - ImposterKey1: GenerateKeyPair(), - AliceKey1: keys[AliceKey1], - }, - signers: []string{AliceKey1, ImposterKey1}, - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - AssertionMethod: []string{ImposterKey1}, - Controller: []string{AliceDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: ImposterKey1, - Type: Ed25519VerificationKey2020, - Controller: ImposterDID, - }, - }, - }, - }, - { - valid: true, - name: "Valid: Works with Capability Delegation", - keys: map[string]KeyPair{ - ImposterKey1: GenerateKeyPair(), - AliceKey1: keys[AliceKey1], - }, - signers: []string{AliceKey1, ImposterKey1}, - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - CapabilityDelegation: []string{ImposterKey1}, - Controller: []string{AliceDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: ImposterKey1, - Type: Ed25519VerificationKey2020, - Controller: ImposterDID, - }, - }, - }, - }, - { - valid: true, - name: "Valid: Works with Capability Invocation", - keys: map[string]KeyPair{ - ImposterKey1: GenerateKeyPair(), - AliceKey1: keys[AliceKey1], - }, - signers: []string{AliceKey1, ImposterKey1}, - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - CapabilityInvocation: []string{ImposterKey1}, - Controller: []string{AliceDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: ImposterKey1, - Type: Ed25519VerificationKey2020, - Controller: ImposterDID, - }, - }, - }, - }, - { - valid: true, - name: "Valid: With controller works", - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - Controller: []string{AliceDID, BobDID}, - }, - signers: []string{AliceKey1, BobKey3}, - keys: map[string]KeyPair{ - AliceKey1: keys[AliceKey1], - BobKey3: keys[BobKey3], - }, - }, - { - 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(), - AliceKey1: keys[AliceKey1], - BobKey1: keys[BobKey1], - BobKey2: keys[BobKey2], - BobKey3: keys[BobKey3], - CharlieKey1: keys[CharlieKey1], - CharlieKey2: keys[CharlieKey2], - CharlieKey3: keys[CharlieKey3], - }, - signers: []string{ - "did:cheqd:test:1111111111111111#key-1", - "did:cheqd:test:1111111111111111#key-5", - AliceKey1, - BobKey1, - BobKey2, - BobKey3, - CharlieKey1, - CharlieKey2, - CharlieKey3, - }, - msg: &types.MsgCreateDidPayload{ - Id: "did:cheqd:test:1111111111111111", - Authentication: []string{ - "did:cheqd:test:1111111111111111#key-1", - "did:cheqd:test:1111111111111111#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"}, - AlsoKnownAs: []string{"SomeUri"}, - Service: []*types.Service{ - { - Id: "did:cheqd:test:1111111111111111#service-1", - Type: "DIDCommMessaging", - ServiceEndpoint: "ServiceEndpoint", - }, - }, - Controller: []string{"did:cheqd:test:1111111111111111", AliceDID, BobDID, CharlieDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: "did:cheqd:test:1111111111111111#key-1", - Type: Ed25519VerificationKey2020, - Controller: "did:cheqd:test:1111111111111111", - }, - { - Id: "did:cheqd:test:1111111111111111#key-2", - Type: Ed25519VerificationKey2020, - Controller: "did:cheqd:test:1111111111111111", - }, - { - Id: "did:cheqd:test:1111111111111111#key-3", - Type: Ed25519VerificationKey2020, - Controller: "did:cheqd:test:1111111111111111", - }, - { - Id: "did:cheqd:test:1111111111111111#key-4", - Type: "Ed25519VerificationKey2020", - Controller: "did:cheqd:test:1111111111111111", - }, - { - Id: "did:cheqd:test:1111111111111111#key-5", - Type: "Ed25519VerificationKey2020", - Controller: "did:cheqd:test:1111111111111111", - }, - }, - }, - }, - { - valid: false, - name: "Not Valid: Second controller did not sign request", - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - Controller: []string{AliceDID, BobDID}, - }, - signers: []string{AliceKey1}, - keys: map[string]KeyPair{ - AliceKey1: keys[AliceKey1], - }, - errMsg: fmt.Sprintf("signer: %s: signature is required but not found", BobDID), - }, - { - valid: false, - name: "Not Valid: No signature", - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - Controller: []string{AliceDID, BobDID}, - }, - errMsg: fmt.Sprintf("signer: %s: signature is required but not found", AliceDID), - }, - { - valid: false, - name: "Not Valid: Controller not found", - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - Controller: []string{AliceDID, NotFounDID}, - }, - signers: []string{AliceKey1, ImposterKey1}, - keys: map[string]KeyPair{ - AliceKey1: keys[AliceKey1], - ImposterKey1: GenerateKeyPair(), - }, - errMsg: fmt.Sprintf("%s: DID Doc not found", NotFounDID), - }, - { - valid: false, - name: "Not Valid: Wrong signature", - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - Controller: []string{AliceDID}, - }, - signers: []string{AliceKey1}, - keys: map[string]KeyPair{ - AliceKey1: keys[BobKey1], - }, - errMsg: fmt.Sprintf("method id: %s: invalid signature detected", AliceKey1), - }, - { - valid: false, - name: "Not Valid: DID signed by wrong controller", - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - Authentication: []string{ImposterKey1}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: ImposterKey1, - Type: Ed25519VerificationKey2020, - Controller: ImposterDID, - PublicKeyMultibase: "z" + base58.Encode(keys[ImposterKey1].PublicKey), - }, - }, - }, - signers: []string{AliceKey1}, - keys: map[string]KeyPair{ - AliceKey1: keys[AliceKey1], - }, - errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ImposterDID), - }, - { - valid: false, - name: "Not Valid: DID self-signed by not existing verification method", - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - Authentication: []string{ImposterKey1}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: ImposterKey1, - Type: Ed25519VerificationKey2020, - Controller: ImposterDID, - PublicKeyMultibase: "z" + base58.Encode(keys[ImposterKey1].PublicKey), - }, - }, - }, - signers: []string{ImposterKey2}, - keys: map[string]KeyPair{ - ImposterKey2: GenerateKeyPair(), - }, - errMsg: fmt.Sprintf("%s: verification method not found", ImposterKey2), - }, - { - valid: false, - name: "Not Valid: Self-signature not found", - msg: &types.MsgCreateDidPayload{ - Id: ImposterDID, - Controller: []string{AliceDID, ImposterDID}, - Authentication: []string{ImposterKey1}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: ImposterKey1, - Type: Ed25519VerificationKey2020, - Controller: ImposterDID, - PublicKeyMultibase: "z" + base58.Encode(keys[ImposterKey1].PublicKey), - }, - }, - }, - signers: []string{AliceKey1, ImposterKey2}, - keys: map[string]KeyPair{ - AliceKey1: keys[AliceKey1], - ImposterKey2: GenerateKeyPair(), - }, - errMsg: fmt.Sprintf("%s: verification method not found", ImposterKey2), - }, - { - valid: false, - name: "Not Valid: DID Doc already exists", - keys: map[string]KeyPair{ - CharlieKey1: GenerateKeyPair(), - }, - signers: []string{CharlieKey1}, - msg: &types.MsgCreateDidPayload{ - Id: CharlieDID, - Authentication: []string{CharlieKey1}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: CharlieKey1, - Type: Ed25519VerificationKey2020, - Controller: CharlieDID, - }, - }, - }, - errMsg: fmt.Sprintf("%s: DID Doc exists", CharlieDID), - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg - setup := InitEnv(t, keys) - - for _, vm := range msg.VerificationMethod { - if vm.PublicKeyMultibase == "" { - vm.PublicKeyMultibase, err = multibase.Encode(multibase.Base58BTC, tc.keys[vm.Id].PublicKey) - } - require.NoError(t, err) - } - - signerKeys := map[string]ed25519.PrivateKey{} - for _, signer := range tc.signers { - signerKeys[signer] = tc.keys[signer].PrivateKey - } - - did, err := setup.SendCreateDid(msg, signerKeys) - - if tc.valid { - require.Nil(t, err) - require.Equal(t, tc.msg.Id, did.Id) - require.Equal(t, tc.msg.Controller, did.Controller) - require.Equal(t, tc.msg.VerificationMethod, did.VerificationMethod) - require.Equal(t, tc.msg.Authentication, did.Authentication) - require.Equal(t, tc.msg.AssertionMethod, did.AssertionMethod) - require.Equal(t, tc.msg.CapabilityInvocation, did.CapabilityInvocation) - require.Equal(t, tc.msg.CapabilityDelegation, did.CapabilityDelegation) - require.Equal(t, tc.msg.KeyAgreement, did.KeyAgreement) - require.Equal(t, tc.msg.AlsoKnownAs, did.AlsoKnownAs) - require.Equal(t, tc.msg.Service, did.Service) - require.Equal(t, tc.msg.Context, did.Context) - } else { - require.Error(t, err) - require.Equal(t, tc.errMsg, err.Error()) - } - }) - } -} - -func TestHandler_DidDocAlreadyExists(t *testing.T) { - setup := Setup() - - _, _, _ = setup.InitDid(AliceDID) - _, _, err := setup.InitDid(AliceDID) - - require.Error(t, err) - require.Equal(t, fmt.Sprintf("%s: DID Doc exists", AliceDID), err.Error()) -} diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go new file mode 100644 index 000000000..211daa74f --- /dev/null +++ b/x/resource/tests/create_resource_test.go @@ -0,0 +1,103 @@ +package tests + +import ( + "crypto/ed25519" + "crypto/sha256" + "fmt" + "testing" + + "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 + errMsg string + }{ + { + valid: true, + name: "Valid: Works", + signerKeys: map[string]ed25519.PrivateKey{ + ExistingDIDKey: keys[ExistingDIDKey].PrivateKey, + }, + msg: &types.MsgCreateResourcePayload{ + CollectionId: ExistingDID, + Id: ResourceId, + Name: "Test Resource Name", + ResourceType: CLSchemaType, + MimeType: JsonResourceType, + Data: []byte(SchemaData), + }, + errMsg: "", + }, + { + valid: true, + name: "Valid: Add new resource version", + signerKeys: map[string]ed25519.PrivateKey{ + ExistingDIDKey: keys[ExistingDIDKey].PrivateKey, + }, + msg: &types.MsgCreateResourcePayload{ + CollectionId: ExistingResource().Id, + Id: ResourceId, + Name: ExistingResource().Name, + ResourceType: ExistingResource().ResourceType, + MimeType: ExistingResource().MimeType, + Data: ExistingResource().Data, + }, + errMsg: "", + }, + { + valid: false, + name: "Not Valid: No signature", + signerKeys: map[string]ed25519.PrivateKey{ + }, + msg: &types.MsgCreateResourcePayload{ + CollectionId: ExistingDID, + Id: ResourceId, + Name: "Test Resource Name", + ResourceType: CLSchemaType, + MimeType: JsonResourceType, + Data: []byte(SchemaData), + }, + errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), + }, + } + + 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) + require.Equal(t, tc.msg.CollectionId, resource.CollectionId) + require.Equal(t, tc.msg.Id, resource.Id) + require.Equal(t, tc.msg.MimeType, resource.MimeType) + require.Equal(t, tc.msg.ResourceType, resource.ResourceType) + require.Equal(t, tc.msg.Data, resource.Data) + require.Equal(t, tc.msg.Name, resource.Name) + require.Equal(t, string(sha256.New().Sum(resource.Data)), resource.Checksum) + } else { + require.Error(t, err) + require.Equal(t, tc.errMsg, err.Error()) + } + }) + } +} + +// func TestHandler_ResourceDocAlreadyExists(t *testing.T) { +// setup := Setup() + +// _, _, _ = setup.InitDid(AliceDID) +// _, _, err := setup.InitDid(AliceDID) + +// require.Error(t, err) +// require.Equal(t, fmt.Sprintf("%s: DID Doc exists", AliceDID), err.Error()) +// } diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go index 573d7756b..2505652f7 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -4,13 +4,18 @@ import ( "crypto/ed25519" "crypto/rand" "encoding/base64" + "testing" "time" - "github.com/btcsuite/btcutil/base58" - "github.com/cheqd/cheqd-node/x/cheqd" - "github.com/cheqd/cheqd-node/x/cheqd/types" + // "github.com/btcsuite/btcutil/base58" + 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/multiformats/go-multibase" + "github.com/stretchr/testify/require" + + // "github.com/multiformats/go-multibase" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" @@ -18,17 +23,10 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/cheqd/cheqd-node/x/cheqd/keeper" + "github.com/cheqd/cheqd-node/x/resource/keeper" sdk "github.com/cosmos/cosmos-sdk/types" ) -const Ed25519VerificationKey2020 = "Ed25519VerificationKey2020" - -type KeyPair struct { - PrivateKey ed25519.PrivateKey - PublicKey ed25519.PublicKey -} - type TestSetup struct { Cdc codec.Codec Ctx sdk.Context @@ -36,12 +34,11 @@ type TestSetup struct { Handler sdk.Handler } -type SignerKey struct { - signer string - key ed25519.PrivateKey -} func Setup() TestSetup { + + cheqdtests.Setup() + // Init Codec ir := codectypes.NewInterfaceRegistry() types.RegisterInterfaces(ir) @@ -69,7 +66,7 @@ func Setup() TestSetup { tmproto.Header{ChainID: "test", Time: blockTime}, false, log.NewNopLogger()).WithTxBytes(txBytes) - handler := cheqd.NewHandler(*newKeeper) + handler := resource.NewHandler(*newKeeper) setup := TestSetup{ Cdc: cdc, @@ -80,267 +77,63 @@ func Setup() TestSetup { return setup } -func (s *TestSetup) CreateDid(pubKey ed25519.PublicKey, did string) *types.MsgCreateDidPayload { - PublicKeyMultibase := "z" + base58.Encode(pubKey) - - VerificationMethod := types.VerificationMethod{ - Id: did + "#key-1", - Type: Ed25519VerificationKey2020, - Controller: did, - PublicKeyMultibase: PublicKeyMultibase, - } - - Service := types.Service{ - Id: did + "#service-2", - Type: "DIDCommMessaging", - ServiceEndpoint: "endpoint", - } - - return &types.MsgCreateDidPayload{ - Id: did, - Controller: nil, - VerificationMethod: []*types.VerificationMethod{&VerificationMethod}, - Authentication: []string{did + "#key-1"}, - AssertionMethod: []string{did + "#key-1"}, - CapabilityInvocation: []string{did + "#key-1"}, - CapabilityDelegation: []string{did + "#key-1"}, - KeyAgreement: []string{did + "#key-1"}, - AlsoKnownAs: []string{did + "#key-1"}, - Context: []string{"Context"}, - Service: []*types.Service{&Service}, - } -} - -func (s *TestSetup) CreateToUpdateDid(did *types.MsgCreateDidPayload) *types.MsgUpdateDidPayload { - return &types.MsgUpdateDidPayload{ - Id: did.Id, - Controller: did.Controller, - VerificationMethod: did.VerificationMethod, - Authentication: did.Authentication, - AssertionMethod: did.AssertionMethod, - CapabilityInvocation: did.CapabilityInvocation, - CapabilityDelegation: did.CapabilityDelegation, - KeyAgreement: did.KeyAgreement, - AlsoKnownAs: did.AlsoKnownAs, - Service: did.Service, - Context: did.Context, +func GenerateCreateResourcePayload(resource types.Resource) *types.MsgCreateResourcePayload { + return &types.MsgCreateResourcePayload{ + CollectionId: resource.CollectionId, + Id: resource.Id, + Name: resource.Name, + ResourceType: resource.ResourceType, + MimeType: resource.MimeType, + Data: resource.Data, } } -func (s *TestSetup) WrapCreateRequest(payload *types.MsgCreateDidPayload, keys map[string]ed25519.PrivateKey) *types.MsgCreateDid { - var signatures []*types.SignInfo +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, &types.SignInfo{ + signatures = append(signatures, &cheqdtypes.SignInfo{ VerificationMethodId: privKeyId, Signature: signature, }) } - return &types.MsgCreateDid{ - Payload: payload, - Signatures: signatures, - } -} - -func (s *TestSetup) WrapUpdateRequest(payload *types.MsgUpdateDidPayload, keys []SignerKey) *types.MsgUpdateDid { - var signatures []*types.SignInfo - signingInput := payload.GetSignBytes() - - for _, skey := range keys { - signature := base64.StdEncoding.EncodeToString(ed25519.Sign(skey.key, signingInput)) - signatures = append(signatures, &types.SignInfo{ - VerificationMethodId: skey.signer, - Signature: signature, - }) - } - - return &types.MsgUpdateDid{ + return &types.MsgCreateResource{ Payload: payload, Signatures: signatures, } } -func GenerateKeyPair() KeyPair { - PublicKey, PrivateKey, _ := ed25519.GenerateKey(rand.Reader) - return KeyPair{PrivateKey, PublicKey} -} - -func (s *TestSetup) InitDid(did string) (map[string]ed25519.PrivateKey, *types.MsgCreateDidPayload, error) { - pubKey, privKey, _ := ed25519.GenerateKey(rand.Reader) - - // add new Did - didMsg := s.CreateDid(pubKey, did) - - keyId := did + "#key-1" - keys := map[string]ed25519.PrivateKey{keyId: privKey} - - result, err := s.Handler(s.Ctx, s.WrapCreateRequest(didMsg, keys)) - if err != nil { - return nil, nil, err - } - - didResponse := types.MsgCreateDidResponse{} - if err := didResponse.Unmarshal(result.Data); err != nil { - return nil, nil, err - } - - return keys, didMsg, nil -} - -func (s *TestSetup) SendUpdateDid(msg *types.MsgUpdateDidPayload, keys []SignerKey) (*types.Did, error) { - // query Did - state, _ := s.Keeper.GetDid(&s.Ctx, msg.Id) - if len(msg.VersionId) == 0 { - msg.VersionId = state.Metadata.VersionId - } - - _, err := s.Handler(s.Ctx, s.WrapUpdateRequest(msg, keys)) - if err != nil { - return nil, err - } - - updated, _ := s.Keeper.GetDid(&s.Ctx, msg.Id) - return updated.UnpackDataAsDid() -} - -func (s *TestSetup) SendCreateDid(msg *types.MsgCreateDidPayload, keys map[string]ed25519.PrivateKey) (*types.Did, error) { +func (s *TestSetup) SendCreateResource(msg *types.MsgCreateResourcePayload, keys map[string]ed25519.PrivateKey) (*types.Resource, error) { _, err := s.Handler(s.Ctx, s.WrapCreateRequest(msg, keys)) if err != nil { return nil, err } - created, _ := s.Keeper.GetDid(&s.Ctx, msg.Id) - return created.UnpackDataAsDid() -} - -func ConcatKeys(dst map[string]ed25519.PrivateKey, src map[string]ed25519.PrivateKey) map[string]ed25519.PrivateKey { - for k, v := range src { - dst[k] = v - } - - return dst + created, _ := s.Keeper.GetResource(&s.Ctx, msg.CollectionId, msg.Id) + return &created, nil } -func MapToListOfSignerKeys(mp map[string]ed25519.PrivateKey) []SignerKey { - rlist := []SignerKey{} - for k, v := range mp { - rlist = append(rlist, SignerKey{ - signer: k, - key: v, - }) - } - return rlist -} -func (s TestSetup) CreateTestDIDs(keys map[string]KeyPair) error { - testDIDs := []struct { - signers []string - msg *types.MsgCreateDidPayload - }{ - { - signers: []string{AliceKey1}, - msg: &types.MsgCreateDidPayload{ - Id: AliceDID, - Authentication: []string{AliceKey1}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - }, - { - signers: []string{BobKey2}, - msg: &types.MsgCreateDidPayload{ - Id: BobDID, - Authentication: []string{ - BobKey1, - BobKey2, - BobKey3, - }, - CapabilityDelegation: []string{ - BobKey4, - }, - VerificationMethod: []*types.VerificationMethod{ - { - Id: BobKey1, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - { - Id: BobKey2, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - { - Id: BobKey3, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - { - Id: BobKey4, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - }, - }, - }, - { - signers: []string{CharlieKey2, BobKey2}, - msg: &types.MsgCreateDidPayload{ - Id: CharlieDID, - Authentication: []string{ - CharlieKey1, - CharlieKey2, - CharlieKey3, - }, - VerificationMethod: []*types.VerificationMethod{ - { - Id: CharlieKey1, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - { - Id: CharlieKey2, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - { - Id: CharlieKey3, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - }, - }, - }, - } +func InitEnv(t *testing.T, publicKey ed25519.PublicKey, privateKey ed25519.PrivateKey) (TestSetup, cheqdtests.TestSetup) { + resourceSetup := Setup() + didSetup := cheqdtests.Setup() - for _, prefilled := range testDIDs { - msg := prefilled.msg + didDoc := didSetup.CreateDid(publicKey, ExistingDID) + _, err := didSetup.SendCreateDid(didDoc, map[string]ed25519.PrivateKey{ExistingDIDKey: privateKey}) + require.NoError(t, err) - for _, vm := range msg.VerificationMethod { - encoded, err := multibase.Encode(multibase.Base58BTC, keys[vm.Id].PublicKey) - if err != nil { - return err - } - vm.PublicKeyMultibase = encoded - } + resourcePayload := GenerateCreateResourcePayload(ExistingResource()) + _, err = resourceSetup.SendCreateResource(resourcePayload, map[string]ed25519.PrivateKey{ExistingDIDKey: privateKey}) + require.NoError(t, err) - signerKeys := map[string]ed25519.PrivateKey{} - for _, signer := range prefilled.signers { - signerKeys[signer] = keys[signer].PrivateKey - } + return resourceSetup, didSetup +} - _, err := s.SendCreateDid(msg, signerKeys) - if err != nil { - return err - } +func GenerateTestKeys() map[string]cheqdtests.KeyPair { + return map[string]cheqdtests.KeyPair{ + ExistingDIDKey: cheqdtests.GenerateKeyPair(), } - - return nil } diff --git a/x/resource/tests/signature_verification_test.go b/x/resource/tests/signature_verification_test.go deleted file mode 100644 index 88a8c9bea..000000000 --- a/x/resource/tests/signature_verification_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package tests - -import ( - "crypto/ed25519" - "crypto/rand" - "fmt" - "reflect" - "testing" - - "github.com/btcsuite/btcutil/base58" - "github.com/cheqd/cheqd-node/x/cheqd/types" - "github.com/stretchr/testify/require" -) - -func TestDIDDocControllerChanged(t *testing.T) { - setup := Setup() - - // Init did - aliceKeys, aliceDid, _ := setup.InitDid(AliceDID) - bobKeys, _, _ := setup.InitDid(BobDID) - - updatedDidDoc := setup.CreateToUpdateDid(aliceDid) - updatedDidDoc.Controller = append(updatedDidDoc.Controller, BobDID) - receivedDid, _ := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(ConcatKeys(aliceKeys, bobKeys))) - - // check - require.NotEqual(t, aliceDid.Controller, receivedDid.Controller) - require.NotEqual(t, []string{AliceDID, BobDID}, receivedDid.Controller) - require.Equal(t, []string{BobDID}, receivedDid.Controller) -} - -func TestDIDDocVerificationMethodChangedWithoutOldSignature(t *testing.T) { - setup := Setup() - - // Init did - _, aliceDid, _ := setup.InitDid(AliceDID) - bobKeys, _, _ := setup.InitDid(BobDID) - - updatedDidDoc := setup.CreateToUpdateDid(aliceDid) - updatedDidDoc.VerificationMethod[0].Type = Ed25519VerificationKey2020 - _, err := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(bobKeys)) - - // check - require.Error(t, err) - require.Equal(t, fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), err.Error()) -} - -func TestDIDDocVerificationMethodControllerChangedWithoutOldSignature(t *testing.T) { - setup := Setup() - - // Init did - _, aliceDid, _ := setup.InitDid(AliceDID) - bobKeys, _, _ := setup.InitDid(BobDID) - - updatedDidDoc := setup.CreateToUpdateDid(aliceDid) - updatedDidDoc.VerificationMethod[0].Controller = BobDID - _, err := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(bobKeys)) - - // check - require.Error(t, err) - require.Equal(t, fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), err.Error()) -} - -func TestDIDDocControllerChangedWithoutOldSignature(t *testing.T) { - setup := Setup() - - // Init did - _, aliceDid, _ := setup.InitDid(AliceDID) - bobKeys, _, _ := setup.InitDid(BobDID) - - updatedDidDoc := setup.CreateToUpdateDid(aliceDid) - updatedDidDoc.Controller = append(updatedDidDoc.Controller, BobDID) - _, err := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(bobKeys)) - - // check - require.Error(t, err) - require.Equal(t, fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), err.Error()) -} - -func TestDIDDocVerificationMethodDeletedWithoutOldSignature(t *testing.T) { - setup := Setup() - - // Init did - - ApubKey, AprivKey, _ := ed25519.GenerateKey(rand.Reader) - BpubKey, BprivKey, _ := ed25519.GenerateKey(rand.Reader) - aliceDid := setup.CreateDid(ApubKey, AliceDID) - bobDid := setup.CreateDid(BpubKey, BobDID) - - aliceDid.VerificationMethod = append(aliceDid.VerificationMethod, &types.VerificationMethod{ - Id: AliceKey2, - Controller: BobDID, - Type: Ed25519VerificationKey2020, - PublicKeyMultibase: "z" + base58.Encode(BpubKey), - }) - - aliceKeys := map[string]ed25519.PrivateKey{AliceKey1: AprivKey, BobKey1: BprivKey} - bobKeys := map[string]ed25519.PrivateKey{BobKey1: BprivKey} - _, _ = setup.SendCreateDid(bobDid, bobKeys) - _, _ = setup.SendCreateDid(aliceDid, aliceKeys) - - updatedDidDoc := setup.CreateToUpdateDid(aliceDid) - updatedDidDoc.VerificationMethod = []*types.VerificationMethod{aliceDid.VerificationMethod[0]} - updatedDidDoc.Authentication = []string{aliceDid.Authentication[0]} - _, err := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(bobKeys)) - - // check - require.Error(t, err) - require.Equal(t, fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), err.Error()) -} - -func TestDIDDocVerificationMethodDeleted(t *testing.T) { - setup := Setup() - - ApubKey, AprivKey, _ := ed25519.GenerateKey(rand.Reader) - BpubKey, BprivKey, _ := ed25519.GenerateKey(rand.Reader) - - aliceDid := setup.CreateDid(ApubKey, AliceDID) - bobDid := setup.CreateDid(BpubKey, BobDID) - - aliceDid.Authentication = append(aliceDid.Authentication, AliceKey2) - aliceDid.VerificationMethod = append(aliceDid.VerificationMethod, &types.VerificationMethod{ - Id: AliceKey2, - Controller: BobDID, - Type: Ed25519VerificationKey2020, - PublicKeyMultibase: "z" + base58.Encode(BpubKey), - }) - - aliceKeys := map[string]ed25519.PrivateKey{AliceKey1: AprivKey, BobKey1: BprivKey} - bobKeys := map[string]ed25519.PrivateKey{BobKey1: BprivKey} - _, _ = setup.SendCreateDid(bobDid, bobKeys) - _, _ = setup.SendCreateDid(aliceDid, aliceKeys) - - updatedDidDoc := setup.CreateToUpdateDid(aliceDid) - updatedDidDoc.Authentication = []string{aliceDid.Authentication[0]} - updatedDidDoc.VerificationMethod = []*types.VerificationMethod{aliceDid.VerificationMethod[0]} - receivedDid, _ := setup.SendUpdateDid(updatedDidDoc, MapToListOfSignerKeys(ConcatKeys(aliceKeys, bobKeys))) - - // check - require.NotEqual(t, len(aliceDid.VerificationMethod), len(receivedDid.VerificationMethod)) - require.True(t, reflect.DeepEqual(aliceDid.VerificationMethod[0], receivedDid.VerificationMethod[0])) -} diff --git a/x/resource/tests/update_did_test.go b/x/resource/tests/update_did_test.go deleted file mode 100644 index b47eb5233..000000000 --- a/x/resource/tests/update_did_test.go +++ /dev/null @@ -1,483 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/btcsuite/btcutil/base58" - "github.com/cheqd/cheqd-node/x/cheqd/types" - "github.com/multiformats/go-multibase" - "github.com/stretchr/testify/require" -) - -func TestUpdateDid(t *testing.T) { - var err error - keys := map[string]KeyPair{ - AliceKey1: GenerateKeyPair(), - AliceKey2: GenerateKeyPair(), - BobKey1: GenerateKeyPair(), - BobKey2: GenerateKeyPair(), - BobKey3: GenerateKeyPair(), - BobKey4: GenerateKeyPair(), - CharlieKey1: GenerateKeyPair(), - CharlieKey2: GenerateKeyPair(), - CharlieKey3: GenerateKeyPair(), - CharlieKey4: GenerateKeyPair(), - ImposterKey1: GenerateKeyPair(), - } - - cases := []struct { - valid bool - name string - signerKeys []SignerKey - signers []string - msg *types.MsgUpdateDidPayload - errMsg string - }{ - { - valid: true, - name: "Valid: Key rotation works", - signerKeys: []SignerKey{ - { - signer: AliceKey1, - key: keys[AliceKey1].PrivateKey, - }, - { - signer: AliceKey1, - key: keys[AliceKey2].PrivateKey, - }, - }, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - PublicKeyMultibase: "z" + base58.Encode(keys[AliceKey2].PublicKey), - }, - }, - }, - }, - // VM and Controller replacing tests - { - valid: false, - name: "Not Valid: replacing controller and Verification method ID does not work without new sign", - signers: []string{AliceKey2, BobKey1, AliceKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{CharlieDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey2, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", CharlieDID), - }, - { - valid: true, - name: "Valid: replacing controller and Verification method ID works with all signatures", - signers: []string{AliceKey1, CharlieKey1, AliceKey2}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{CharlieDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey2, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", CharlieDID), - }, - // Verification method's tests - // cases: - // - replacing VM controller works - // - replacing VM controller does not work without new signature - // - replacing VM controller does not work without old signature ?????? - // - replacing VM doesn't work without new signature - // - replacing VM doesn't work without old signature - // - replacing VM works with all signatures - // --- adding new VM works - // --- adding new VM without new signature - // --- adding new VM without old signature - { - valid: true, - name: "Valid: Replacing VM controller works with one signature", - signers: []string{AliceKey1, BobKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - }, - }, - }, - { - valid: false, - name: "Not Valid: Replacing VM controller does not work without new signature", - signers: []string{AliceKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", BobDID), - }, - { - valid: false, - name: "Not Valid: Replacing VM does not work without new signature", - signers: []string{AliceKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey2, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one valid signature by %s (new version): signature is required but not found", AliceDID), - }, - { - valid: false, - name: "Not Valid: Replacing VM does not work without old signature", - signers: []string{AliceKey2}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey2, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one valid signature by %s (old version): signature is required but not found", AliceDID), - }, - { - valid: true, - name: "Not Valid: Replacing VM works with all signatures", - signers: []string{AliceKey1, AliceKey2}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey2, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - }, - // Adding VM - { - valid: true, - name: "Valid: Adding another verification method", - signers: []string{AliceKey1, BobKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{AliceDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - { - Id: AliceKey2, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - }, - }, - }, - { - valid: false, - name: "Not Valid: Adding another verification method without new sign", - signers: []string{AliceKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{AliceDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - { - Id: AliceKey2, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", BobDID), - }, - { - valid: false, - name: "Not Valid: Adding another verification method without old sign", - signers: []string{AliceKey2}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{AliceDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - { - Id: AliceKey2, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one valid signature by %s (old version): signature is required but not found", AliceDID), - }, - - // Controller's tests - // cases: - // - replacing Controller works with all signatures - // - replacing Controller doesn't work without old signature - // - replacing Controller doesn't work without new signature - // --- adding Controller works with all signatures - // --- adding Controller doesn't work without old signature - // --- adding Controller doesn't work without new signature - { - valid: true, - name: "Valid: Replace controller works with all signatures", - signers: []string{BobKey1, AliceKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{BobDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - }, - { - valid: false, - name: "Not Valid: Replace controller doesn't work without old signatures", - signers: []string{BobKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{BobDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), - }, - { - valid: false, - name: "Not Valid: Replace controller doesn't work without new signatures", - signers: []string{AliceKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{BobDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", BobDID), - }, - // add Controller - { - valid: true, - name: "Valid: Adding second controller works", - signers: []string{AliceKey1, CharlieKey3}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{AliceDID, CharlieDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - }, - { - valid: false, - name: "Not Valid: Adding controller without old signature", - signers: []string{BobKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{AliceDID, BobDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", AliceDID), - }, - { - valid: false, - name: "Not Valid: Add controller without new signature doesn't work", - signers: []string{AliceKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{AliceDID, BobDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one signature by %s: signature is required but not found", BobDID), - }, - - { - valid: true, - name: "Valid: Adding verification method with the same controller works", - signers: []string{AliceKey1, AliceKey2}, - msg: &types.MsgUpdateDidPayload{ - Id: AliceDID, - Controller: []string{AliceDID}, - VerificationMethod: []*types.VerificationMethod{ - { - Id: AliceKey2, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - { - Id: AliceKey1, - Type: Ed25519VerificationKey2020, - Controller: AliceDID, - }, - }, - }, - }, - { - valid: true, - name: "Valid: Keeping VM with controller different then subject untouched during update should not require Bob signature", - signers: []string{CharlieKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: CharlieDID, - Authentication: []string{ - CharlieKey1, - CharlieKey2, - CharlieKey3, - }, - - VerificationMethod: []*types.VerificationMethod{ - { - Id: CharlieKey1, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - { - Id: CharlieKey2, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - { - Id: CharlieKey3, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - { - Id: CharlieKey4, - Type: Ed25519VerificationKey2020, - Controller: CharlieDID, - }, - }, - }, - }, - { - valid: true, - name: "Valid: Removing verification method is possible with any kind of valid Bob's key", - signers: []string{BobKey1}, - msg: &types.MsgUpdateDidPayload{ - Id: BobDID, - VerificationMethod: []*types.VerificationMethod{ - { - Id: BobKey1, - Type: Ed25519VerificationKey2020, - Controller: BobDID, - }, - }, - }, - errMsg: fmt.Sprintf("there should be at least one signature by %s (old version): signature is required but not found", BobDID), - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - setup := InitEnv(t, keys) - msg := tc.msg - - for _, vm := range msg.VerificationMethod { - if vm.PublicKeyMultibase == "" { - vm.PublicKeyMultibase, err = multibase.Encode(multibase.Base58BTC, keys[vm.Id].PublicKey) - } - require.NoError(t, err) - } - - signerKeys := []SignerKey{} - if tc.signerKeys != nil { - signerKeys = tc.signerKeys - } else { - for _, signer := range tc.signers { - signerKeys = append(signerKeys, SignerKey{ - signer: signer, - key: keys[signer].PrivateKey, - }) - } - } - - did, err := setup.SendUpdateDid(msg, signerKeys) - - if tc.valid { - require.Nil(t, err) - require.Equal(t, tc.msg.Id, did.Id) - require.Equal(t, tc.msg.Controller, did.Controller) - require.Equal(t, tc.msg.VerificationMethod, did.VerificationMethod) - require.Equal(t, tc.msg.Authentication, did.Authentication) - require.Equal(t, tc.msg.AssertionMethod, did.AssertionMethod) - require.Equal(t, tc.msg.CapabilityInvocation, did.CapabilityInvocation) - require.Equal(t, tc.msg.CapabilityDelegation, did.CapabilityDelegation) - require.Equal(t, tc.msg.KeyAgreement, did.KeyAgreement) - require.Equal(t, tc.msg.AlsoKnownAs, did.AlsoKnownAs) - require.Equal(t, tc.msg.Service, did.Service) - require.Equal(t, tc.msg.Context, did.Context) - } else { - require.Error(t, err) - require.Equal(t, tc.errMsg, err.Error()) - } - }) - } -} diff --git a/x/resource/tests/utils.go b/x/resource/tests/utils.go deleted file mode 100644 index 5ba9b0b97..000000000 --- a/x/resource/tests/utils.go +++ /dev/null @@ -1,48 +0,0 @@ -package tests - -import ( - "math/rand" - "testing" - - "github.com/stretchr/testify/require" -) - -var letters = []rune("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") - -func randSeq(n int) string { - b := make([]rune, n) - for i := range b { - b[i] = letters[rand.Intn(len(letters))] - } - return string(b) -} - -func GenerateDID() string { - return "did:cheqd:test:" + randSeq(16) -} - -func GenerateFragment(did string) string { - return did + "#key-1" -} - -func GenerateTestKeys() map[string]KeyPair { - return map[string]KeyPair{ - AliceKey1: GenerateKeyPair(), - AliceKey2: GenerateKeyPair(), - BobKey1: GenerateKeyPair(), - BobKey2: GenerateKeyPair(), - BobKey3: GenerateKeyPair(), - BobKey4: GenerateKeyPair(), - CharlieKey1: GenerateKeyPair(), - CharlieKey2: GenerateKeyPair(), - CharlieKey3: GenerateKeyPair(), - ImposterKey1: GenerateKeyPair(), - } -} - -func InitEnv(t *testing.T, keys map[string]KeyPair) TestSetup { - setup := Setup() - err := setup.CreateTestDIDs(keys) - require.NoError(t, err) - return setup -} From 0bc8a814e0499d190978b8586ca1b38ed5264324 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Thu, 16 Jun 2022 17:36:00 +0300 Subject: [PATCH 10/65] Fixing tests --- x/cheqd/keeper/msg_server.go | 16 ++---- x/cheqd/keeper/msg_server_create_did.go | 2 +- x/cheqd/tests/create_did_test.go | 50 ++++++++-------- x/cheqd/tests/update_did_test.go | 6 +- x/cheqd/types/error.go | 1 - .../keeper/msg_server_create_resource.go | 44 +++++++------- x/resource/tests/create_resource_test.go | 2 +- x/resource/tests/setup.go | 57 +++++++++++-------- 8 files changed, 91 insertions(+), 87 deletions(-) diff --git a/x/cheqd/keeper/msg_server.go b/x/cheqd/keeper/msg_server.go index 4855981f7..336310b30 100644 --- a/x/cheqd/keeper/msg_server.go +++ b/x/cheqd/keeper/msg_server.go @@ -106,7 +106,7 @@ func VerifySignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types. return nil } -func VerifyAllSignersHaveExactlyOneValidSignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, message []byte, signers []string, signatures []*types.SignInfo) error { +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) @@ -114,15 +114,11 @@ func VerifyAllSignersHaveExactlyOneValidSignature(k *Keeper, ctx *sdk.Context, i return types.ErrSignatureNotFound.Wrapf("signer: %s", signer) } - if len(signatures) > 1 { - return types.ErrMultipleSignatures.Wrapf("signer: %s", signer) - } - - signature := signatures[0] - - err := VerifySignature(k, ctx, inMemoryDIDs, message, signature) - if err != nil { - return err + for _, signature := range signatures { + err := VerifySignature(k, ctx, inMemoryDIDs, message, signature) + if err != nil { + return err + } } } diff --git a/x/cheqd/keeper/msg_server_create_did.go b/x/cheqd/keeper/msg_server_create_did.go index 43d6d6b22..1e5cde0a9 100644 --- a/x/cheqd/keeper/msg_server_create_did.go +++ b/x/cheqd/keeper/msg_server_create_did.go @@ -45,7 +45,7 @@ func (k msgServer) CreateDid(goCtx context.Context, msg *types.MsgCreateDid) (*t // Verify signatures signers := GetSignerDIDsForDIDCreation(did) - err = VerifyAllSignersHaveExactlyOneValidSignature(&k.Keeper, &ctx, inMemoryDids, msg.GetSignBytes(), signers, msg.GetSignatures()) + err = VerifyAllSignersHaveAllValidSignatures(&k.Keeper, &ctx, inMemoryDids, msg.Payload.GetSignBytes(), signers, msg.Signatures) if err != nil { return nil, err } 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/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/error.go b/x/cheqd/types/error.go index ce1a000bc..48bb7fc60 100644 --- a/x/cheqd/types/error.go +++ b/x/cheqd/types/error.go @@ -11,7 +11,6 @@ var ( ErrBadRequest = sdkerrors.Register(ModuleName, 1000, "bad request") ErrInvalidSignature = sdkerrors.Register(ModuleName, 1100, "invalid signature detected") ErrSignatureNotFound = sdkerrors.Register(ModuleName, 1101, "signature is required but not found") - ErrMultipleSignatures = sdkerrors.Register(ModuleName, 1102, "signature is required but not found") ErrDidDocExists = sdkerrors.Register(ModuleName, 1200, "DID Doc exists") ErrDidDocNotFound = sdkerrors.Register(ModuleName, 1201, "DID Doc not found") ErrVerificationMethodNotFound = sdkerrors.Register(ModuleName, 1202, "verification method not found") diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 958f8bce5..efe118355 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -24,37 +24,37 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes } + // TODO: validation - - - - - // getDid - // get signatures for did modification // + //// getDid + //// get signatures for did modification + //// + // + //// Verify signatures + //signers := GetSignerDIDsForResourceCreation(resource) + //for _, signer := range signers { + // signature, found := cheqdtypes.FindSignInfoBySigner(msg.Signatures, signer) + // + // if !found { + // return nil, cheqdtypes.ErrSignatureNotFound.Wrapf("signer: %s", signer) + // } + // + // err := VerifySignature(&k.Keeper, &ctx, inMemoryResources, msg.Payload.GetSignBytes(), signature) + // if err != nil { + // return nil, err + // } + //} - // Verify signatures - signers := GetSignerDIDsForResourceCreation(resource) - for _, signer := range signers { - signature, found := cheqdtypes.FindSignInfoBySigner(msg.Signatures, signer) - - if !found { - return nil, cheqdtypes.ErrSignatureNotFound.Wrapf("signer: %s", signer) - } - - err := VerifySignature(&k.Keeper, &ctx, inMemoryResources, msg.Payload.GetSignBytes(), signature) - if err != nil { - return nil, err - } - } // Build Resource resource := msg.Payload.ToResource() - // set created, checksum + + // TODO: set created, checksum // Apply changes - err := k.AppendResource(&ctx, &resource) + err := k.SetResource(&ctx, &resource) if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index 211daa74f..c44083c21 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -72,7 +72,7 @@ func TestCreateResource(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { msg := tc.msg - resourceSetup, _ := InitEnv(t, keys[ExistingDIDKey].PublicKey, keys[ExistingDIDKey].PrivateKey) + resourceSetup := InitEnv(t, keys[ExistingDIDKey].PublicKey, keys[ExistingDIDKey].PrivateKey) resource, err := resourceSetup.SendCreateResource(msg, tc.signerKeys) if tc.valid { diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go index 2505652f7..8d996a73f 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -7,6 +7,9 @@ import ( "testing" "time" + "github.com/cheqd/cheqd-node/x/cheqd" + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" + // "github.com/btcsuite/btcutil/base58" cheqdtests "github.com/cheqd/cheqd-node/x/cheqd/tests" cheqdtypes "github.com/cheqd/cheqd-node/x/cheqd/types" @@ -28,33 +31,35 @@ import ( ) type TestSetup struct { - Cdc codec.Codec - Ctx sdk.Context - Keeper keeper.Keeper - Handler sdk.Handler -} + cheqdtests.TestSetup + resourceKeeper keeper.Keeper + resourceHandler sdk.Handler +} func Setup() TestSetup { - - cheqdtests.Setup() - // Init Codec ir := codectypes.NewInterfaceRegistry() types.RegisterInterfaces(ir) + cheqdtypes.RegisterInterfaces(ir) cdc := codec.NewProtoCodec(ir) // Init KVSore db := dbm.NewMemDB() dbStore := store.NewCommitMultiStore(db) - storeKey := sdk.NewKVStoreKey(types.StoreKey) - dbStore.MountStoreWithDB(storeKey, sdk.StoreTypeIAVL, nil) + + 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 - newKeeper := keeper.NewKeeper(cdc, storeKey) + cheqdKeeper := cheqdkeeper.NewKeeper(cdc, cheqdStoreKey) + resourceKeeper := keeper.NewKeeper(cdc, resourceStoreKey) // Create Tx txBytes := make([]byte, 28) @@ -66,14 +71,20 @@ func Setup() TestSetup { tmproto.Header{ChainID: "test", Time: blockTime}, false, log.NewNopLogger()).WithTxBytes(txBytes) - handler := resource.NewHandler(*newKeeper) + cheqdHandler := cheqd.NewHandler(*cheqdKeeper) + resourceHandler := resource.NewHandler(*resourceKeeper, *cheqdKeeper) setup := TestSetup{ - Cdc: cdc, - Ctx: ctx, - Keeper: *newKeeper, - Handler: handler, + TestSetup: cheqdtests.TestSetup{ + Cdc: cdc, + Ctx: ctx, + Keeper: *cheqdKeeper, + Handler: cheqdHandler, + }, + resourceKeeper: *resourceKeeper, + resourceHandler: resourceHandler, } + return setup } @@ -112,28 +123,26 @@ func (s *TestSetup) SendCreateResource(msg *types.MsgCreateResourcePayload, keys return nil, err } - created, _ := s.Keeper.GetResource(&s.Ctx, msg.CollectionId, msg.Id) + 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, cheqdtests.TestSetup) { +func InitEnv(t *testing.T, publicKey ed25519.PublicKey, privateKey ed25519.PrivateKey) TestSetup { resourceSetup := Setup() - didSetup := cheqdtests.Setup() - didDoc := didSetup.CreateDid(publicKey, ExistingDID) - _, err := didSetup.SendCreateDid(didDoc, map[string]ed25519.PrivateKey{ExistingDIDKey: privateKey}) + 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, didSetup + return resourceSetup } func GenerateTestKeys() map[string]cheqdtests.KeyPair { return map[string]cheqdtests.KeyPair{ - ExistingDIDKey: cheqdtests.GenerateKeyPair(), + ExistingDIDKey: cheqdtests.GenerateKeyPair(), } } From 5125db75fb93897336e91faaebffd92c8faa56d4 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Thu, 16 Jun 2022 17:49:31 +0300 Subject: [PATCH 11/65] Minimal resource creation --- .../keeper/msg_server_create_resource.go | 46 +++++++------------ 1 file changed, 17 insertions(+), 29 deletions(-) diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index efe118355..ddb9db33c 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -2,6 +2,7 @@ package keeper import ( "context" + 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" @@ -23,38 +24,30 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes return nil, types.ErrResourceExists.Wrap(msg.Payload.Id) } + // Validate signatures + didDocStateValue, err := k.cheqdKeeper.GetDid(&ctx, did) + didDoc, err := didDocStateValue.UnpackDataAsDid() + if err != nil { + return nil, err + } - // TODO: validation - - - // - //// getDid - //// get signatures for did modification - //// - // - //// Verify signatures - //signers := GetSignerDIDsForResourceCreation(resource) - //for _, signer := range signers { - // signature, found := cheqdtypes.FindSignInfoBySigner(msg.Signatures, signer) - // - // if !found { - // return nil, cheqdtypes.ErrSignatureNotFound.Wrapf("signer: %s", signer) - // } - // - // err := VerifySignature(&k.Keeper, &ctx, inMemoryResources, msg.Payload.GetSignBytes(), signature) - // 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() // TODO: set created, checksum + // TODO: set backlink to didDoc + // TODO: set version + update forward and backward links // Apply changes - err := k.SetResource(&ctx, &resource) + err = k.SetResource(&ctx, &resource) if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } @@ -64,8 +57,3 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes Resource: &resource, }, nil } - -func GetSignerDIDsForResourceCreation(resource types.Resource) []string { - //TODO: implement - return []string{} -} From 5b0524f935e62bdafaff8fc394c6dc0835cc3e29 Mon Sep 17 00:00:00 2001 From: toktar Date: Thu, 16 Jun 2022 18:39:47 +0300 Subject: [PATCH 12/65] dev-1281: update resource unit tests --- x/resource/tests/constants.go | 9 ++-- x/resource/tests/create_resource_test.go | 67 +++++++++++++++++++----- x/resource/tests/setup.go | 13 ++--- 3 files changed, 65 insertions(+), 24 deletions(-) diff --git a/x/resource/tests/constants.go b/x/resource/tests/constants.go index d95ea04f7..c2b21ae53 100644 --- a/x/resource/tests/constants.go +++ b/x/resource/tests/constants.go @@ -14,16 +14,17 @@ const ( ResourceId = "988b0ab3-6a39-4598-83ec-b84c6cf8da15" IncorrectResourceId = "1234" - NotFounDID = "did:cheqd:test:nfdnfdnfdnfdnfdd" - ExistingDID = "did:cheqd:test:aaaaaaaaaaaaaaaa" - ExistingDIDKey = ExistingDID + "#key-1" + NotFoundDIDIdentifier = "nfdnfdnfdnfdnfdd" + ExistingDIDIdentifier = "eeeeeeeeeeeeeeee" + ExistingDID = "did:cheqd:test:" + ExistingDIDIdentifier + ExistingDIDKey = ExistingDID + "#key-1" ) func ExistingResource() types.Resource { data := []byte(SchemaData) checksum := string(sha256.New().Sum(data)) return types.Resource{ - CollectionId: ExistingDID, + CollectionId: ExistingDIDIdentifier, Id: "a09abea0-22e0-4b35-8f70-9cc3a6d0b5fd", Name: "Existing Resource Name", ResourceType: CLSchemaType, diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index c44083c21..df511b42f 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -2,7 +2,7 @@ package tests import ( "crypto/ed25519" - "crypto/sha256" + // "crypto/sha256" "fmt" "testing" @@ -14,11 +14,12 @@ import ( func TestCreateResource(t *testing.T) { keys := GenerateTestKeys() cases := []struct { - valid bool - name string - signerKeys map[string]ed25519.PrivateKey - msg *types.MsgCreateResourcePayload - errMsg string + valid bool + name string + signerKeys map[string]ed25519.PrivateKey + msg *types.MsgCreateResourcePayload + previousVersionId string + errMsg string }{ { valid: true, @@ -27,13 +28,14 @@ func TestCreateResource(t *testing.T) { ExistingDIDKey: keys[ExistingDIDKey].PrivateKey, }, msg: &types.MsgCreateResourcePayload{ - CollectionId: ExistingDID, + CollectionId: ExistingDIDIdentifier, Id: ResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, MimeType: JsonResourceType, Data: []byte(SchemaData), }, + previousVersionId: "", errMsg: "", }, { @@ -43,22 +45,22 @@ func TestCreateResource(t *testing.T) { ExistingDIDKey: keys[ExistingDIDKey].PrivateKey, }, msg: &types.MsgCreateResourcePayload{ - CollectionId: ExistingResource().Id, + CollectionId: ExistingResource().CollectionId, Id: ResourceId, Name: ExistingResource().Name, ResourceType: ExistingResource().ResourceType, MimeType: ExistingResource().MimeType, Data: ExistingResource().Data, }, + previousVersionId: ExistingResource().Id, errMsg: "", }, { - valid: false, - name: "Not Valid: No signature", - signerKeys: map[string]ed25519.PrivateKey{ - }, + valid: false, + name: "Not Valid: No signature", + signerKeys: map[string]ed25519.PrivateKey{}, msg: &types.MsgCreateResourcePayload{ - CollectionId: ExistingDID, + CollectionId: ExistingDIDIdentifier, Id: ResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, @@ -67,6 +69,34 @@ func TestCreateResource(t *testing.T) { }, 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, + MimeType: JsonResourceType, + Data: []byte(SchemaData), + }, + 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, + MimeType: JsonResourceType, + Data: []byte(SchemaData), + }, + errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), + }, } for _, tc := range cases { @@ -77,13 +107,22 @@ func TestCreateResource(t *testing.T) { resource, err := resourceSetup.SendCreateResource(msg, tc.signerKeys) if tc.valid { require.Nil(t, err) + + // didStateValue, err := resourceSetup.Keeper.GetDid(&resourceSetup.Ctx, resource.CollectionId) + // require.Nil(t, err) + // require.Contains(t, didStateValue.Metadata.Resources, resource.Id) + require.Equal(t, tc.msg.CollectionId, resource.CollectionId) require.Equal(t, tc.msg.Id, resource.Id) require.Equal(t, tc.msg.MimeType, resource.MimeType) require.Equal(t, tc.msg.ResourceType, resource.ResourceType) require.Equal(t, tc.msg.Data, resource.Data) require.Equal(t, tc.msg.Name, resource.Name) - require.Equal(t, string(sha256.New().Sum(resource.Data)), resource.Checksum) + // require.Equal(t, string(sha256.New().Sum(resource.Data)), resource.Checksum) + require.Equal(t, tc.previousVersionId, resource.PreviousVersionId) + // if tc.previousVersionId != "" { + // require.Equal(t, resource.Id, resource.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 index 8d996a73f..ff2770164 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -33,8 +33,8 @@ import ( type TestSetup struct { cheqdtests.TestSetup - resourceKeeper keeper.Keeper - resourceHandler sdk.Handler + ResourceKeeper keeper.Keeper + ResourceHandler sdk.Handler } func Setup() TestSetup { @@ -81,10 +81,11 @@ func Setup() TestSetup { Keeper: *cheqdKeeper, Handler: cheqdHandler, }, - resourceKeeper: *resourceKeeper, - resourceHandler: resourceHandler, + ResourceKeeper: *resourceKeeper, + ResourceHandler: resourceHandler, } + setup.Keeper.SetDidNamespace(ctx, "test") return setup } @@ -118,12 +119,12 @@ func (s *TestSetup) WrapCreateRequest(payload *types.MsgCreateResourcePayload, k } func (s *TestSetup) SendCreateResource(msg *types.MsgCreateResourcePayload, keys map[string]ed25519.PrivateKey) (*types.Resource, error) { - _, err := s.Handler(s.Ctx, s.WrapCreateRequest(msg, keys)) + _, 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) + created, _ := s.ResourceKeeper.GetResource(&s.Ctx, msg.CollectionId, msg.Id) return &created, nil } From b0f45bb9f7f94609bb950dd2a8d48b8f7692edad Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Fri, 17 Jun 2022 13:19:47 +0300 Subject: [PATCH 13/65] Implementation of createResource cli command --- tests/e2e-bash/tests/test_create_resource.sh | 69 ++++++++++++ x/resource/client/cli/query.go | 4 +- x/resource/client/cli/query_resource.go | 65 +++++------- x/resource/client/cli/tx.go | 106 +------------------ x/resource/client/cli/tx_create_resource.go | 21 ++-- x/resource/client/cli/tx_update_resource.go | 62 ----------- 6 files changed, 111 insertions(+), 216 deletions(-) create mode 100644 tests/e2e-bash/tests/test_create_resource.sh delete mode 100644 x/resource/client/cli/tx_update_resource.go 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..d8614667c --- /dev/null +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -0,0 +1,69 @@ +#!/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}") + +# Build CreateDid message +DID="did:cheqd:testnet:$(random_string)" +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" + + + + + + + + +# Build CreateResource message +DID="did:cheqd:testnet:$(random_string)" +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" diff --git a/x/resource/client/cli/query.go b/x/resource/client/cli/query.go index dfca90ea9..be0642e5d 100644 --- a/x/resource/client/cli/query.go +++ b/x/resource/client/cli/query.go @@ -3,7 +3,7 @@ package cli import ( "fmt" - "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/resource/types" "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" ) @@ -19,7 +19,7 @@ func GetQueryCmd() *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdGetDid()) + //cmd.AddCommand(CmdGetDid()) return cmd } diff --git a/x/resource/client/cli/query_resource.go b/x/resource/client/cli/query_resource.go index 3c8777d69..2ffada1d3 100644 --- a/x/resource/client/cli/query_resource.go +++ b/x/resource/client/cli/query_resource.go @@ -1,39 +1,30 @@ package cli -import ( - "context" - - "github.com/cheqd/cheqd-node/x/cheqd/types" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/spf13/cobra" -) - -func CmdGetDid() *cobra.Command { - cmd := &cobra.Command{ - Use: "did [id]", - Short: "Query a did", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - queryClient := types.NewQueryClient(clientCtx) - - did := args[0] - params := &types.QueryGetDidRequest{ - Id: did, - } - - resp, err := queryClient.Did(context.Background(), params) - if err != nil { - return err - } - - return clientCtx.PrintProto(resp) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} +//func CmdGetDid() *cobra.Command { +// cmd := &cobra.Command{ +// Use: "did [id]", +// Short: "Query a did", +// Args: cobra.ExactArgs(1), +// RunE: func(cmd *cobra.Command, args []string) error { +// clientCtx := client.GetClientContextFromCmd(cmd) +// +// queryClient := types.NewQueryClient(clientCtx) +// +// did := args[0] +// params := &types.QueryGetDidRequest{ +// Id: did, +// } +// +// resp, err := queryClient.Did(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 index b659be114..3cc5eded9 100644 --- a/x/resource/client/cli/tx.go +++ b/x/resource/client/cli/tx.go @@ -1,25 +1,13 @@ package cli import ( - "bufio" - "crypto/ed25519" - "encoding/base64" "fmt" - "github.com/cheqd/cheqd-node/x/cheqd/types" + "github.com/cheqd/cheqd-node/x/resource/types" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/input" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/spf13/cobra" ) -type SignInput struct { - verificationMethodId string - privKey ed25519.PrivateKey -} - // GetTxCmd returns the transaction commands for this module func GetTxCmd() *cobra.Command { cmd := &cobra.Command{ @@ -31,98 +19,6 @@ func GetTxCmd() *cobra.Command { } cmd.AddCommand(CmdCreateDid()) - cmd.AddCommand(CmdUpdateDid()) return cmd } - -func GetPayloadAndSignInputs(clientCtx client.Context, args []string) (string, []SignInput, error) { - // Check for args count - if len(args)%2 != 1 { - return "", []SignInput{}, fmt.Errorf("invalid number of arguments: %d. must be an odd number", len(args)) - } - - // Get payload json - payloadJson := args[0] - - // Get signInputs - var signInputs []SignInput - - for i := 1; i < len(args); i += 2 { - vmId := args[i] - privKey := args[i+1] - - if privKey == "interactive" { - inBuf := bufio.NewReader(clientCtx.Input) - - var err error - privKey, err = input.GetString("Enter base64 encoded verification key", inBuf) - - if err != nil { - return "", nil, err - } - } - - privKeyBytes, err := base64.StdEncoding.DecodeString(privKey) - if err != nil { - return "", nil, fmt.Errorf("unable to decode private key: %s", err.Error()) - } - - signInput := SignInput{ - verificationMethodId: vmId, - privKey: privKeyBytes, - } - - signInputs = append(signInputs, signInput) - } - - return payloadJson, signInputs, nil -} - -func SignWithSignInputs(signBytes []byte, signInputs []SignInput) []*types.SignInfo { - var signatures []*types.SignInfo - - for _, signInput := range signInputs { - signatureBytes := ed25519.Sign(signInput.privKey, signBytes) - - signInfo := types.SignInfo{ - VerificationMethodId: signInput.verificationMethodId, - Signature: base64.StdEncoding.EncodeToString(signatureBytes), - } - - signatures = append(signatures, &signInfo) - } - - return signatures -} - -func SetFeePayerFromSigner(ctx *client.Context) error { - if ctx.FromAddress != nil { - ctx.FeePayer = ctx.FromAddress - return nil - } - - signerAccAddr, err := AccAddrByKeyRef(ctx.Keyring, ctx.From) - if err != nil { - return err - } - - ctx.FeePayer = signerAccAddr - return nil -} - -func AccAddrByKeyRef(keyring keyring.Keyring, keyRef string) (sdk.AccAddress, error) { - // Firstly check if the keyref is a key name of a key registered in a keyring - info, err := keyring.Key(keyRef) - - if err == nil { - return info.GetAddress(), nil - } - - if !sdkerrors.IsOf(err, sdkerrors.ErrIO, sdkerrors.ErrKeyNotFound) { - return nil, err - } - - // Fallback: convert keyref to address - return sdk.AccAddressFromBech32(keyRef) -} diff --git a/x/resource/client/cli/tx_create_resource.go b/x/resource/client/cli/tx_create_resource.go index e5498a53b..8a337c7ea 100644 --- a/x/resource/client/cli/tx_create_resource.go +++ b/x/resource/client/cli/tx_create_resource.go @@ -1,7 +1,8 @@ package cli import ( - "github.com/cheqd/cheqd-node/x/cheqd/types" + 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" @@ -10,10 +11,10 @@ import ( func CmdCreateDid() *cobra.Command { cmd := &cobra.Command{ - Use: "create-did [payload-json] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", - Short: "Creates a new DID.", - Long: "Creates a new DID. " + - "[payload-json] is JSON encoded MsgCreateDidPayload. " + + Use: "create-resource [payload-json] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", + Short: "Creates a new Resource.", + Long: "Creates a new Resource. " + + "[payload-json] is JSON encoded MsgCreateResourcePayload. " + "[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-1] is base base64 encoded ed25519 private key for signature N." + "If 'interactive' value is used for a key, the key will be read interactively. " + @@ -25,13 +26,13 @@ func CmdCreateDid() *cobra.Command { return err } - payloadJson, signInputs, err := GetPayloadAndSignInputs(clientCtx, args) + payloadJson, signInputs, err := cheqdcli.GetPayloadAndSignInputs(clientCtx, args) if err != nil { return err } // Unmarshal payload - var payload types.MsgCreateDidPayload + var payload types.MsgCreateResourcePayload err = clientCtx.Codec.UnmarshalJSON([]byte(payloadJson), &payload) if err != nil { return err @@ -39,15 +40,15 @@ func CmdCreateDid() *cobra.Command { // Build identity message signBytes := payload.GetSignBytes() - identitySignatures := SignWithSignInputs(signBytes, signInputs) + identitySignatures := cheqdcli.SignWithSignInputs(signBytes, signInputs) - msg := types.MsgCreateDid{ + msg := types.MsgCreateResource{ Payload: &payload, Signatures: identitySignatures, } // Set fee-payer if not set - err = SetFeePayerFromSigner(&clientCtx) + err = cheqdcli.SetFeePayerFromSigner(&clientCtx) if err != nil { return err } diff --git a/x/resource/client/cli/tx_update_resource.go b/x/resource/client/cli/tx_update_resource.go deleted file mode 100644 index 6c2437da2..000000000 --- a/x/resource/client/cli/tx_update_resource.go +++ /dev/null @@ -1,62 +0,0 @@ -package cli - -import ( - "github.com/cheqd/cheqd-node/x/cheqd/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" -) - -func CmdUpdateDid() *cobra.Command { - cmd := &cobra.Command{ - Use: "update-did [payload-json] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", - Short: "Update a DID.", - Long: "Updates a DID. " + - "[payload-json] is JSON encoded MsgUpdateDidPayload. " + - "[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-1] 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(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - payloadJson, signInputs, err := GetPayloadAndSignInputs(clientCtx, args) - if err != nil { - return err - } - - // Unmarshal payload - var payload types.MsgUpdateDidPayload - err = clientCtx.Codec.UnmarshalJSON([]byte(payloadJson), &payload) - if err != nil { - return err - } - - // Build identity message - signBytes := payload.GetSignBytes() - identitySignatures := SignWithSignInputs(signBytes, signInputs) - - msg := types.MsgUpdateDid{ - Payload: &payload, - Signatures: identitySignatures, - } - - // Set fee-payer if not set - err = SetFeePayerFromSigner(&clientCtx) - if err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} From f7a5bda457b2274019aa436ab0f6041821caeeb4 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Fri, 17 Jun 2022 14:40:57 +0300 Subject: [PATCH 14/65] Fix createResource bash test --- tests/e2e-bash/tests/test_create_resource.sh | 34 +++++++------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/tests/e2e-bash/tests/test_create_resource.sh b/tests/e2e-bash/tests/test_create_resource.sh index d8614667c..24c42b809 100644 --- a/tests/e2e-bash/tests/test_create_resource.sh +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -14,7 +14,8 @@ 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}") # Build CreateDid message -DID="did:cheqd:testnet:$(random_string)" +ID="$(random_string)" +DID="did:cheqd:testnet:$ID" KEY_ID="${DID}#key1" MSG_CREATE_DID='{ @@ -38,32 +39,21 @@ RESULT=$(cheqd-noded tx cheqd create-did "${MSG_CREATE_DID}" "${KEY_ID}" "${ALIC assert_tx_successful "$RESULT" - - - - - - # Build CreateResource message -DID="did:cheqd:testnet:$(random_string)" -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}'" - ] +RESOURCE_ID=$(uuidgen) +RESOURCE_NAME="Test resource" +RESOURCE_DATA="dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh" + +MSG_CREATE_RESOURCE='{ + "collection_id": "'${ID}'", + "id": "'${RESOURCE_ID}'", + "name": "'${RESOURCE_NAME}'", + "data": "'${RESOURCE_DATA}'" }'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx cheqd create-did "${MSG_CREATE_DID}" "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE}" "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" From 6669a4a7ad184ae6918019219804466376a7bb46 Mon Sep 17 00:00:00 2001 From: toktar Date: Fri, 17 Jun 2022 15:45:51 +0300 Subject: [PATCH 15/65] dev-1281: add resource query --- proto/cheqd/v1/stateValue.proto | 1 + x/cheqd/types/stateValue.pb.go | 103 ++++++++++++++---- x/resource/keeper/keeper_resource.go | 2 +- .../keeper/msg_server_create_resource.go | 9 +- x/resource/tests/create_resource_test.go | 6 +- .../tests/query_collection_resources_test.go | 91 ++++++++++++++++ x/resource/tests/query_resource_test.go | 83 ++++++++++++++ 7 files changed, 267 insertions(+), 28 deletions(-) create mode 100644 x/resource/tests/query_collection_resources_test.go create mode 100644 x/resource/tests/query_resource_test.go 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/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/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index ceb24efd9..ca714cc69 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -58,7 +58,7 @@ func (k Keeper) SetResource(ctx *sdk.Context, resource *types.Resource) error { // 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(id) + return types.Resource{}, sdkerrors.ErrNotFound.Wrap("resource " + collectionId + ":" + id) } store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index efe118355..c9045b05d 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -14,7 +14,8 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes // Validate corresponding DIDDoc exists namespace := k.cheqdKeeper.GetDidNamespace(ctx) did := cheqdutils.JoinDID(cheqdtypes.DidMethod, namespace, msg.Payload.CollectionId) - if !k.cheqdKeeper.HasDid(&ctx, did) { + didDoc, err := k.cheqdKeeper.GetDid(&ctx, did) + if err != nil { return nil, cheqdtypes.ErrDidDocNotFound.Wrapf(did) } @@ -58,6 +59,12 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } + updatedMetadata := didDoc.Metadata + updatedMetadata.Resources = append(updatedMetadata.Resources, ) + err = k.cheqdKeeper.SetDid(&ctx, didDoc.Data, &updatedMetadata) + if err != nil { + return nil, types.ErrInternal.Wrapf(err.Error()) + } // Build and return response return &types.MsgCreateResourceResponse{ diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index df511b42f..1ed0d57d8 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -108,9 +108,9 @@ func TestCreateResource(t *testing.T) { if tc.valid { require.Nil(t, err) - // didStateValue, err := resourceSetup.Keeper.GetDid(&resourceSetup.Ctx, resource.CollectionId) - // require.Nil(t, err) - // require.Contains(t, didStateValue.Metadata.Resources, resource.Id) + didStateValue, err := resourceSetup.Keeper.GetDid(&resourceSetup.Ctx, resource.CollectionId) + require.Nil(t, err) + require.Contains(t, didStateValue.Metadata.Resources, resource.Id) require.Equal(t, tc.msg.CollectionId, resource.CollectionId) require.Equal(t, tc.msg.Id, resource.Id) 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..6cc6ed834 --- /dev/null +++ b/x/resource/tests/query_collection_resources_test.go @@ -0,0 +1,91 @@ +package tests + +import ( + + // "crypto/sha256" + "crypto/ed25519" + "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.QueryGetResourceRequest + response *types.QueryGetResourceResponse + errMsg string + }{ + { + valid: true, + name: "Valid: Works", + msg: &types.QueryGetResourceRequest{ + CollectionId: ExistingDIDIdentifier, + Id: existingResource.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.Id, + }, + response: nil, + errMsg: fmt.Sprintf("resource %s:%s: not found", NotFoundDIDIdentifier, existingResource.Id), + }, + } + + 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, + } + createdResource, err := resourceSetup.SendCreateResource(newResourcePayload, didKey) + require.Nil(t, err) + + queryResponse, err := resourceSetup.ResourceKeeper.CollectionResources(sdk.WrapSDKContext(resourceSetup.Ctx), msg) + + if tc.valid { + resources := queryResponse.Resources + expectedResources := map[string]types.Resource { + existingResource.Id: existingResource, + createdResource.Id: *createdResource, + } + require.Nil(t, err) + require.Equal(t, len(expectedResources), len(resources)) + for _, r := range resources { + CompareResources(t, expectedResources[r.Id], *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..c5cc47fbc --- /dev/null +++ b/x/resource/tests/query_resource_test.go @@ -0,0 +1,83 @@ +package tests + +import ( + + // "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.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.Id, + }, + response: nil, + errMsg: fmt.Sprintf("resource %s:%s: not found", NotFoundDIDIdentifier, existingResource.Id), + }, + } + + 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.ResourceKeeper.Resource(sdk.WrapSDKContext(resourceSetup.Ctx), msg) + + if tc.valid { + resource := queryResponse.Resource + require.Nil(t, err) + require.Equal(t, tc.response.Resource.CollectionId, resource.CollectionId) + require.Equal(t, tc.response.Resource.Id, resource.Id) + require.Equal(t, tc.response.Resource.MimeType, resource.MimeType) + require.Equal(t, tc.response.Resource.ResourceType, resource.ResourceType) + require.Equal(t, tc.response.Resource.Data, resource.Data) + require.Equal(t, tc.response.Resource.Name, resource.Name) + // require.Equal(t, string(sha256.New().Sum(response.Resource.Data)), resource.Checksum) + require.Equal(t, tc.response.Resource.PreviousVersionId, resource.PreviousVersionId) + require.Equal(t, tc.response.Resource.NextVersionId, resource.NextVersionId) + } else { + require.Error(t, err) + require.Equal(t, tc.errMsg, err.Error()) + } + }) + } +} From e1522bad146cef751cec352d56ef52888e34e252 Mon Sep 17 00:00:00 2001 From: toktar Date: Fri, 17 Jun 2022 15:50:39 +0300 Subject: [PATCH 16/65] dev-1281: update tests --- x/resource/tests/create_resource_test.go | 3 ++- x/resource/tests/utils.go | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 x/resource/tests/utils.go diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index 1ed0d57d8..a6a9580eb 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -2,6 +2,7 @@ package tests import ( "crypto/ed25519" + "crypto/sha256" // "crypto/sha256" "fmt" "testing" @@ -118,7 +119,7 @@ func TestCreateResource(t *testing.T) { require.Equal(t, tc.msg.ResourceType, resource.ResourceType) require.Equal(t, tc.msg.Data, resource.Data) require.Equal(t, tc.msg.Name, resource.Name) - // require.Equal(t, string(sha256.New().Sum(resource.Data)), resource.Checksum) + require.Equal(t, string(sha256.New().Sum(resource.Data)), resource.Checksum) require.Equal(t, tc.previousVersionId, resource.PreviousVersionId) // if tc.previousVersionId != "" { // require.Equal(t, resource.Id, resource.NextVersionId) diff --git a/x/resource/tests/utils.go b/x/resource/tests/utils.go new file mode 100644 index 000000000..515251853 --- /dev/null +++ b/x/resource/tests/utils.go @@ -0,0 +1,20 @@ +package tests + +import ( + "crypto/sha256" + + "github.com/cheqd/cheqd-node/x/resource/types" + "github.com/stretchr/testify/require" +) + +func CompareResources(t require.TestingT, expectedResource types.Resource, resource types.Resource) { + require.Equal(t, expectedResource.CollectionId, resource.CollectionId) + require.Equal(t, expectedResource.Id, resource.Id) + require.Equal(t, expectedResource.MimeType, resource.MimeType) + require.Equal(t, expectedResource.ResourceType, resource.ResourceType) + require.Equal(t, expectedResource.Data, resource.Data) + require.Equal(t, expectedResource, resource.Name) + require.Equal(t, string(sha256.New().Sum(expectedResource.Data)), resource.Checksum) + require.Equal(t, expectedResource.PreviousVersionId, resource.PreviousVersionId) + require.Equal(t, expectedResource.NextVersionId, resource.NextVersionId) +} From 28d4ab20db1b14502317d76d521e1d232138b6f1 Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Fri, 17 Jun 2022 16:11:33 +0300 Subject: [PATCH 17/65] Add validation for resourceType and MimeType --- .../types/tx_msg_create_resource_payload.go | 4 +-- x/resource/types/validate.go | 22 ++++++++++++++ x/resource/utils/mime_type.go | 18 +++++++++++ x/resource/utils/mime_type_test.go | 30 +++++++++++++++++++ x/resource/utils/resource_type.go | 18 +++++++++++ x/resource/utils/resource_type_test.go | 30 +++++++++++++++++++ 6 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 x/resource/utils/mime_type.go create mode 100644 x/resource/utils/mime_type_test.go create mode 100644 x/resource/utils/resource_type.go create mode 100644 x/resource/utils/resource_type_test.go diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go index 547d5d048..2d66fc0a5 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -31,8 +31,8 @@ func (msg MsgCreateResourcePayload) Validate() error { validation.Field(&msg.CollectionId, validation.Required, cheqdTypes.IsID()), validation.Field(&msg.Id, validation.Required, IsUUID()), validation.Field(&msg.Name, validation.Required, validation.Length(1, 64)), - // TODO: add validation for resource type - // TODO: add validation for mime type + validation.Field(&msg.ResourceType, validation.Required, isResourceTypeAllowed()), + validation.Field(&msg.ResourceType, validation.Required, isMimeTypeAllowed()), validation.Field(&msg.Data, validation.Required, validation.Length(1, 1024*1024)), // 1MB ) } diff --git a/x/resource/types/validate.go b/x/resource/types/validate.go index 4736169ca..a22db7ef3 100644 --- a/x/resource/types/validate.go +++ b/x/resource/types/validate.go @@ -17,3 +17,25 @@ func IsUUID() *cheqdTypes.CustomErrorRule { return utils.ValidateUUID(casted) }) } + +func isResourceTypeAllowed()*cheqdTypes.CustomErrorRule { + return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { + casted, ok := value.(string) + if !ok { + panic("IsDID must be only applied on string properties") + } + + return utils.ValidateResourceType(casted) + }) +} + +func isMimeTypeAllowed()*cheqdTypes.CustomErrorRule { + return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { + casted, ok := value.(string) + if !ok { + panic("IsDID must be only applied on string properties") + } + + return utils.ValidateMimeType(casted) + }) +} diff --git a/x/resource/utils/mime_type.go b/x/resource/utils/mime_type.go new file mode 100644 index 000000000..805575d2f --- /dev/null +++ b/x/resource/utils/mime_type.go @@ -0,0 +1,18 @@ +package utils + +import ( + "errors" + "strings" + + cheqdUtils "github.com/cheqd/cheqd-node/x/cheqd/utils" +) + +var AllowedMimeTypes = []string {"application/json", "image/png"} + +func ValidateMimeType(rt string) error { + if ! cheqdUtils.Contains(AllowedMimeTypes, rt) { + return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedResourceTypes, ",") + " .") + } + + return nil +} \ No newline at end of file diff --git a/x/resource/utils/mime_type_test.go b/x/resource/utils/mime_type_test.go new file mode 100644 index 000000000..4c4114ff8 --- /dev/null +++ b/x/resource/utils/mime_type_test.go @@ -0,0 +1,30 @@ +package utils + +import ( + "github.com/stretchr/testify/require" + "testing" +) + +func TestValidateMimeType(t *testing.T) { + cases := []struct { + mt string + valid bool + }{ + {"application/json", true}, + {"image/png", true}, + {"my/mime", false}, + {"notMine/type", false}, + } + + for _, tc := range cases { + t.Run(tc.mt, func(t *testing.T) { + err_ := ValidateMimeType(tc.mt) + + if tc.valid { + require.NoError(t, err_) + } else { + require.Error(t, err_) + } + }) + } +} diff --git a/x/resource/utils/resource_type.go b/x/resource/utils/resource_type.go new file mode 100644 index 000000000..d059dd93d --- /dev/null +++ b/x/resource/utils/resource_type.go @@ -0,0 +1,18 @@ +package utils + +import ( + "errors" + "strings" + + cheqdUtils "github.com/cheqd/cheqd-node/x/cheqd/utils" +) + +var AllowedResourceTypes = []string {"CL-Schema", "JSONSchema2020"} + +func ValidateResourceType(rt string) error { + if ! cheqdUtils.Contains(AllowedResourceTypes, rt) { + return errors.New(rt + " resource type is not allowed. Only " + strings.Join(AllowedResourceTypes, ",") + " .") + } + + return nil +} \ No newline at end of file diff --git a/x/resource/utils/resource_type_test.go b/x/resource/utils/resource_type_test.go new file mode 100644 index 000000000..780144368 --- /dev/null +++ b/x/resource/utils/resource_type_test.go @@ -0,0 +1,30 @@ +package utils + +import ( + "github.com/stretchr/testify/require" + "testing" +) + +func TestValidateResourceType(t *testing.T) { + cases := []struct { + rt string + valid bool + }{ + {"CL-Schema", true}, + {"JSONSchema2020", true}, + {"My-Schema", false}, + {"Not schema", false}, + } + + for _, tc := range cases { + t.Run(tc.rt, func(t *testing.T) { + err_ := ValidateResourceType(tc.rt) + + if tc.valid { + require.NoError(t, err_) + } else { + require.Error(t, err_) + } + }) + } +} From cbdbe4aa2175800f07a955e9b039db6e0e13df0b Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Fri, 17 Jun 2022 16:27:35 +0300 Subject: [PATCH 18/65] Add created and checksum for Resource --- x/resource/keeper/msg_server_create_resource.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 5762be75d..83d04a45a 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -2,6 +2,9 @@ package keeper import ( "context" + "crypto/sha256" + "time" + 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" @@ -43,7 +46,8 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes // Build Resource resource := msg.Payload.ToResource() - // TODO: set created, checksum + resource.Checksum = string(sha256.New().Sum(resource.Data)) + resource.Created = time.Now().UTC().Format(time.RFC3339) // TODO: set backlink to didDoc // TODO: set version + update forward and backward links From 1006313b2c6f86efb90fa85088b34c85baf12ee1 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Fri, 17 Jun 2022 16:33:00 +0300 Subject: [PATCH 19/65] Fixing backlinks from diddocx to resources --- x/cheqd/genesis.go | 8 +---- x/cheqd/keeper/keeper_did.go | 31 ++++++------------- x/cheqd/keeper/msg_server_create_did.go | 9 ++++-- x/cheqd/keeper/msg_server_update_did.go | 11 +++++-- .../keeper/msg_server_create_resource.go | 15 ++++----- 5 files changed, 33 insertions(+), 41 deletions(-) diff --git a/x/cheqd/genesis.go b/x/cheqd/genesis.go index 413028501..c437858fb 100644 --- a/x/cheqd/genesis.go +++ b/x/cheqd/genesis.go @@ -2,7 +2,6 @@ package cheqd import ( "fmt" - "github.com/cheqd/cheqd-node/x/cheqd/keeper" "github.com/cheqd/cheqd-node/x/cheqd/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -12,12 +11,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())) } } diff --git a/x/cheqd/keeper/keeper_did.go b/x/cheqd/keeper/keeper_did.go index f694923df..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 } diff --git a/x/cheqd/keeper/msg_server_create_did.go b/x/cheqd/keeper/msg_server_create_did.go index 1e5cde0a9..588d07782 100644 --- a/x/cheqd/keeper/msg_server_create_did.go +++ b/x/cheqd/keeper/msg_server_create_did.go @@ -50,8 +50,13 @@ func (k msgServer) CreateDid(goCtx context.Context, msg *types.MsgCreateDid) (*t return nil, err } - // Apply changes - err = k.AppendDid(&ctx, &did, &metadata) + // Build state value + value, err := types.NewStateValue(&did, &metadata) + if err != nil { + return nil, err + } + + 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 65f63fa3c..691899f44 100644 --- a/x/cheqd/keeper/msg_server_update_did.go +++ b/x/cheqd/keeper/msg_server_update_did.go @@ -81,9 +81,16 @@ func (k msgServer) UpdateDid(goCtx context.Context, msg *types.MsgUpdateDid) (*t return nil, err } - // Apply changes: return original id and modify state + // Return original id updatedDid.ReplaceIds(updatedDid.Id, existingDid.Id) - err = k.SetDid(&ctx, &updatedDid, &updatedMetadata) + + // Modify state + updatedStateValue, err = types.NewStateValue(&updatedDid, &updatedMetadata) + if err != nil { + return nil, err + } + + err = k.SetDid(&ctx, &updatedStateValue) if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 5762be75d..3aed1df14 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -15,10 +15,6 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes // Validate corresponding DIDDoc exists namespace := k.cheqdKeeper.GetDidNamespace(ctx) did := cheqdutils.JoinDID(cheqdtypes.DidMethod, namespace, msg.Payload.CollectionId) - didDoc, err := k.cheqdKeeper.GetDid(&ctx, did) - if err != nil { - return nil, cheqdtypes.ErrDidDocNotFound.Wrapf(did) - } // Validate Resource doesn't exist if k.HasResource(&ctx, msg.Payload.CollectionId, msg.Payload.Id) { @@ -47,14 +43,15 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes // TODO: set backlink to didDoc // TODO: set version + update forward and backward links - // Apply changes - err = k.SetResource(&ctx, &resource) + // Append backlink to didDoc + didDocStateValue.Metadata.Resources = append(didDocStateValue.Metadata.Resources, resource.Id) + err = k.cheqdKeeper.SetDid(&ctx, &didDocStateValue) if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } - updatedMetadata := didDoc.Metadata - updatedMetadata.Resources = append(updatedMetadata.Resources, ) - err = k.cheqdKeeper.SetDid(&ctx, didDoc.Data, &updatedMetadata) + + // Persist resource + err = k.SetResource(&ctx, &resource) if err != nil { return nil, types.ErrInternal.Wrapf(err.Error()) } From c69dd23ec2cd76688bb457d8a586877e9581adbf Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Fri, 17 Jun 2022 16:45:35 +0300 Subject: [PATCH 20/65] Add files for queries --- .../keeper/msg_server_create_resource.go | 1 - .../query_server_all_resource_versions.go | 17 ++ ...o => query_server_collection_resources.go} | 0 .../tests/query_collection_resources_test.go | 178 +++++++++--------- 4 files changed, 106 insertions(+), 90 deletions(-) create mode 100644 x/resource/keeper/query_server_all_resource_versions.go rename x/resource/keeper/{query_resource.go => query_server_collection_resources.go} (100%) diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index df3cdc80e..3d7a6f89a 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -44,7 +44,6 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes resource.Checksum = string(sha256.New().Sum(resource.Data)) resource.Created = time.Now().UTC().Format(time.RFC3339) - // TODO: set backlink to didDoc // TODO: set version + update forward and backward links // Append backlink to didDoc 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..b1d561ad5 --- /dev/null +++ b/x/resource/keeper/query_server_all_resource_versions.go @@ -0,0 +1,17 @@ +package keeper + +//func getResource(ctx sdk.Context, collectionId string, id string, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { +// queryServer := NewQueryServer(keeper) +// +// 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_resource.go b/x/resource/keeper/query_server_collection_resources.go similarity index 100% rename from x/resource/keeper/query_resource.go rename to x/resource/keeper/query_server_collection_resources.go diff --git a/x/resource/tests/query_collection_resources_test.go b/x/resource/tests/query_collection_resources_test.go index 6cc6ed834..77869f984 100644 --- a/x/resource/tests/query_collection_resources_test.go +++ b/x/resource/tests/query_collection_resources_test.go @@ -1,91 +1,91 @@ package tests -import ( - - // "crypto/sha256" - "crypto/ed25519" - "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.QueryGetResourceRequest - response *types.QueryGetResourceResponse - errMsg string - }{ - { - valid: true, - name: "Valid: Works", - msg: &types.QueryGetResourceRequest{ - CollectionId: ExistingDIDIdentifier, - Id: existingResource.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.Id, - }, - response: nil, - errMsg: fmt.Sprintf("resource %s:%s: not found", NotFoundDIDIdentifier, existingResource.Id), - }, - } - - 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, - } - createdResource, err := resourceSetup.SendCreateResource(newResourcePayload, didKey) - require.Nil(t, err) - - queryResponse, err := resourceSetup.ResourceKeeper.CollectionResources(sdk.WrapSDKContext(resourceSetup.Ctx), msg) - - if tc.valid { - resources := queryResponse.Resources - expectedResources := map[string]types.Resource { - existingResource.Id: existingResource, - createdResource.Id: *createdResource, - } - require.Nil(t, err) - require.Equal(t, len(expectedResources), len(resources)) - for _, r := range resources { - CompareResources(t, expectedResources[r.Id], *r) - } - } else { - require.Error(t, err) - require.Equal(t, tc.errMsg, err.Error()) - } - }) - } -} +//import ( +// +// // "crypto/sha256" +// "crypto/ed25519" +// "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.QueryGetResourceRequest +// response *types.QueryGetResourceResponse +// errMsg string +// }{ +// { +// valid: true, +// name: "Valid: Works", +// msg: &types.QueryGetResourceRequest{ +// CollectionId: ExistingDIDIdentifier, +// Id: existingResource.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.Id, +// }, +// response: nil, +// errMsg: fmt.Sprintf("resource %s:%s: not found", NotFoundDIDIdentifier, existingResource.Id), +// }, +// } +// +// 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, +// } +// createdResource, err := resourceSetup.SendCreateResource(newResourcePayload, didKey) +// require.Nil(t, err) +// +// queryResponse, err := resourceSetup.ResourceKeeper.CollectionResources(sdk.WrapSDKContext(resourceSetup.Ctx), msg) +// +// if tc.valid { +// resources := queryResponse.Resources +// expectedResources := map[string]types.Resource { +// existingResource.Id: existingResource, +// createdResource.Id: *createdResource, +// } +// require.Nil(t, err) +// require.Equal(t, len(expectedResources), len(resources)) +// for _, r := range resources { +// CompareResources(t, expectedResources[r.Id], *r) +// } +// } else { +// require.Error(t, err) +// require.Equal(t, tc.errMsg, err.Error()) +// } +// }) +// } +//} From 2eb9da74ef75b74dc81654effbffb1395338e8e0 Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Fri, 17 Jun 2022 17:03:52 +0300 Subject: [PATCH 21/65] Move cheqcksum to bytes --- go.mod | 3 ++ go.sum | 5 ++ proto/resource/v1/resource.proto | 2 +- .../keeper/msg_server_create_resource.go | 2 +- x/resource/types/resource.pb.go | 54 ++++++++++--------- 5 files changed, 38 insertions(+), 28 deletions(-) diff --git a/go.mod b/go.mod index dc6737ee4..11823b275 100644 --- a/go.mod +++ b/go.mod @@ -57,6 +57,7 @@ require ( github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect github.com/felixge/httpsnoop v1.0.1 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect + github.com/ghodss/yaml v1.0.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.0 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect @@ -64,6 +65,7 @@ require ( github.com/goccy/go-json v0.9.4 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/gateway v1.1.0 // indirect + github.com/golang/glog v1.0.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 @@ -71,6 +73,7 @@ require ( github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/gtank/merlin v0.1.1 // indirect github.com/gtank/ristretto255 v0.1.2 // indirect diff --git a/go.sum b/go.sum index 398ea4bb4..b276c407b 100644 --- a/go.sum +++ b/go.sum @@ -317,6 +317,7 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -374,6 +375,8 @@ github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2V github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= +github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -493,6 +496,8 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 h1:BGNSrTRW4rwfhJiFwvwF4XQ0Y72Jj9YEgxVrtovbD5o= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3/go.mod h1:VHn7KgNsRriXa4mcgtkpR00OXyQY6g67JWMvn+R27A4= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= diff --git a/proto/resource/v1/resource.proto b/proto/resource/v1/resource.proto index 0c6e1354b..b4b0b4209 100644 --- a/proto/resource/v1/resource.proto +++ b/proto/resource/v1/resource.proto @@ -12,7 +12,7 @@ message Resource { string mime_type = 5; bytes data = 6; string created = 7; - string checksum = 8; + bytes checksum = 8; string previous_version_id = 9; string next_version_id = 10; } \ No newline at end of file diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 83d04a45a..8baa27116 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -46,7 +46,7 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes // Build Resource resource := msg.Payload.ToResource() - resource.Checksum = string(sha256.New().Sum(resource.Data)) + resource.Checksum = sha256.New().Sum(resource.Data) resource.Created = time.Now().UTC().Format(time.RFC3339) // TODO: set backlink to didDoc // TODO: set version + update forward and backward links diff --git a/x/resource/types/resource.pb.go b/x/resource/types/resource.pb.go index c054342a8..5e9e24211 100644 --- a/x/resource/types/resource.pb.go +++ b/x/resource/types/resource.pb.go @@ -30,7 +30,7 @@ type Resource struct { MimeType string `protobuf:"bytes,5,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"` Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` Created string `protobuf:"bytes,7,opt,name=created,proto3" json:"created,omitempty"` - Checksum string `protobuf:"bytes,8,opt,name=checksum,proto3" json:"checksum,omitempty"` + Checksum []byte `protobuf:"bytes,8,opt,name=checksum,proto3" json:"checksum,omitempty"` PreviousVersionId string `protobuf:"bytes,9,opt,name=previous_version_id,json=previousVersionId,proto3" json:"previous_version_id,omitempty"` NextVersionId string `protobuf:"bytes,10,opt,name=next_version_id,json=nextVersionId,proto3" json:"next_version_id,omitempty"` } @@ -117,11 +117,11 @@ func (m *Resource) GetCreated() string { return "" } -func (m *Resource) GetChecksum() string { +func (m *Resource) GetChecksum() []byte { if m != nil { return m.Checksum } - return "" + return nil } func (m *Resource) GetPreviousVersionId() string { @@ -149,23 +149,23 @@ var fileDescriptor_cebae6241f1ea243 = []byte{ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0xc1, 0x4e, 0xc2, 0x40, 0x10, 0x86, 0x69, 0x45, 0x28, 0x13, 0xd0, 0xb8, 0x5e, 0x36, 0x18, 0x1b, 0xa2, 0x89, 0xe1, 0xa0, 0x6d, 0x88, 0x6f, 0xe0, 0xc1, 0x84, 0x2b, 0x31, 0x1e, 0xbc, 0x90, 0xb2, 0x3b, 0x91, 0x8d, 0xb4, - 0x5b, 0xdb, 0x6d, 0x03, 0x6f, 0xe1, 0xdb, 0xf8, 0x0a, 0x1e, 0x39, 0x7a, 0x34, 0xf0, 0x22, 0xa6, - 0x53, 0xb6, 0x7a, 0x69, 0x67, 0xfe, 0xff, 0xcb, 0xbf, 0x99, 0x19, 0x18, 0x66, 0x98, 0xeb, 0x22, - 0x13, 0x18, 0x96, 0x93, 0xd0, 0xd6, 0x41, 0x9a, 0x69, 0xa3, 0xd9, 0xa5, 0x58, 0xe2, 0xbb, 0x54, - 0x32, 0xa0, 0x7f, 0xa2, 0x25, 0x06, 0x0d, 0x51, 0x4e, 0xae, 0x3e, 0x5d, 0xf0, 0x66, 0x87, 0x9e, - 0x5d, 0xc3, 0x40, 0xe8, 0xd5, 0x0a, 0x85, 0x51, 0x3a, 0x99, 0x2b, 0xc9, 0x9d, 0x91, 0x33, 0xee, - 0xcd, 0xfa, 0x7f, 0xe2, 0x54, 0xb2, 0x13, 0x70, 0x95, 0xe4, 0x2e, 0x39, 0xae, 0x92, 0x8c, 0x41, - 0x3b, 0x89, 0x62, 0xe4, 0x47, 0xa4, 0x50, 0x5d, 0x05, 0xd9, 0x47, 0xe6, 0x66, 0x93, 0x22, 0x6f, - 0xd7, 0x41, 0x56, 0x7c, 0xda, 0xa4, 0xc8, 0x2e, 0xa0, 0x17, 0xab, 0xf8, 0x00, 0x1c, 0x13, 0xe0, - 0x55, 0x02, 0x99, 0x0c, 0xda, 0x32, 0x32, 0x11, 0xef, 0x8c, 0x9c, 0x71, 0x7f, 0x46, 0x35, 0xe3, - 0xd0, 0x15, 0x19, 0x46, 0x06, 0x25, 0xef, 0x12, 0x6e, 0x5b, 0x36, 0x04, 0x4f, 0x2c, 0x51, 0xbc, - 0xe5, 0x45, 0xcc, 0xbd, 0x3a, 0xc9, 0xf6, 0x2c, 0x80, 0xf3, 0x34, 0xc3, 0x52, 0xe9, 0x22, 0x9f, - 0x97, 0x98, 0xe5, 0x87, 0xd1, 0x7a, 0x84, 0x9d, 0x59, 0xeb, 0xb9, 0x76, 0xa6, 0x92, 0xdd, 0xc0, - 0x69, 0x82, 0x6b, 0xf3, 0x9f, 0x05, 0x62, 0x07, 0x95, 0xdc, 0x70, 0x0f, 0x8f, 0x5f, 0x3b, 0xdf, - 0xd9, 0xee, 0x7c, 0xe7, 0x67, 0xe7, 0x3b, 0x1f, 0x7b, 0xbf, 0xb5, 0xdd, 0xfb, 0xad, 0xef, 0xbd, - 0xdf, 0x7a, 0xb9, 0x7d, 0x55, 0x66, 0x59, 0x2c, 0x02, 0xa1, 0xe3, 0x90, 0xb6, 0x5e, 0x7f, 0xef, - 0xaa, 0xe5, 0x87, 0xeb, 0xe6, 0x40, 0x61, 0x35, 0x78, 0xbe, 0xe8, 0xd0, 0x9d, 0xee, 0x7f, 0x03, - 0x00, 0x00, 0xff, 0xff, 0x68, 0x81, 0x26, 0x95, 0xc5, 0x01, 0x00, 0x00, + 0x5b, 0xb7, 0xdb, 0x06, 0xde, 0xc2, 0xb7, 0xf1, 0x15, 0x3c, 0x72, 0xf4, 0x68, 0xe0, 0x45, 0x4c, + 0x87, 0xb6, 0x7a, 0xd9, 0x9d, 0xf9, 0xff, 0x6f, 0x67, 0x33, 0x33, 0x30, 0x34, 0x98, 0xe9, 0xdc, + 0x08, 0x0c, 0x8b, 0x49, 0x58, 0xc7, 0x41, 0x6a, 0xb4, 0xd5, 0xec, 0x52, 0x2c, 0xf1, 0x5d, 0x2a, + 0x19, 0xd0, 0x9d, 0x68, 0x89, 0x41, 0x43, 0x14, 0x93, 0xab, 0x4f, 0x17, 0xbc, 0x59, 0x95, 0xb3, + 0x6b, 0x18, 0x08, 0xbd, 0x5a, 0xa1, 0xb0, 0x4a, 0x27, 0x73, 0x25, 0xb9, 0x33, 0x72, 0xc6, 0xbd, + 0x59, 0xff, 0x4f, 0x9c, 0x4a, 0x76, 0x02, 0xae, 0x92, 0xdc, 0x25, 0xc7, 0x55, 0x92, 0x31, 0x68, + 0x27, 0x51, 0x8c, 0xfc, 0x88, 0x14, 0x8a, 0xcb, 0x42, 0xf5, 0x27, 0x73, 0xbb, 0x49, 0x91, 0xb7, + 0x0f, 0x85, 0x6a, 0xf1, 0x69, 0x93, 0x22, 0xbb, 0x80, 0x5e, 0xac, 0xe2, 0x0a, 0x38, 0x26, 0xc0, + 0x2b, 0x05, 0x32, 0x19, 0xb4, 0x65, 0x64, 0x23, 0xde, 0x19, 0x39, 0xe3, 0xfe, 0x8c, 0x62, 0xc6, + 0xa1, 0x2b, 0x0c, 0x46, 0x16, 0x25, 0xef, 0x12, 0x5e, 0xa7, 0x6c, 0x08, 0x9e, 0x58, 0xa2, 0x78, + 0xcb, 0xf2, 0x98, 0x7b, 0xf4, 0xa2, 0xc9, 0x59, 0x00, 0xe7, 0xa9, 0xc1, 0x42, 0xe9, 0x3c, 0x9b, + 0x17, 0x68, 0xb2, 0xaa, 0xb5, 0x1e, 0x55, 0x38, 0xab, 0xad, 0xe7, 0x83, 0x33, 0x95, 0xec, 0x06, + 0x4e, 0x13, 0x5c, 0xdb, 0xff, 0x2c, 0x10, 0x3b, 0x28, 0xe5, 0x86, 0x7b, 0x78, 0xfc, 0xda, 0xf9, + 0xce, 0x76, 0xe7, 0x3b, 0x3f, 0x3b, 0xdf, 0xf9, 0xd8, 0xfb, 0xad, 0xed, 0xde, 0x6f, 0x7d, 0xef, + 0xfd, 0xd6, 0xcb, 0xed, 0xab, 0xb2, 0xcb, 0x7c, 0x11, 0x08, 0x1d, 0x87, 0x34, 0xf5, 0xc3, 0x79, + 0x57, 0x0e, 0x3f, 0x5c, 0x37, 0x0b, 0x0a, 0xcb, 0xc6, 0xb3, 0x45, 0x87, 0xf6, 0x74, 0xff, 0x1b, + 0x00, 0x00, 0xff, 0xff, 0x31, 0x30, 0xf1, 0xb4, 0xc5, 0x01, 0x00, 0x00, } func (m *Resource) Marshal() (dAtA []byte, err error) { @@ -586,7 +586,7 @@ func (m *Resource) Unmarshal(dAtA []byte) error { if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Checksum", wireType) } - var stringLen uint64 + var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowResource @@ -596,23 +596,25 @@ func (m *Resource) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if byteLen < 0 { return ErrInvalidLengthResource } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthResource } if postIndex > l { return io.ErrUnexpectedEOF } - m.Checksum = string(dAtA[iNdEx:postIndex]) + m.Checksum = append(m.Checksum[:0], dAtA[iNdEx:postIndex]...) + if m.Checksum == nil { + m.Checksum = []byte{} + } iNdEx = postIndex case 9: if wireType != 2 { From abc825385697dd2abf59cb4bba9b42e69aff6f4c Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Fri, 17 Jun 2022 17:30:05 +0300 Subject: [PATCH 22/65] Implementation --- x/resource/keeper/keeper_resource.go | 9 +++----- .../keeper/msg_server_create_resource.go | 10 +++++++-- x/resource/tests/create_resource_test.go | 22 +++++-------------- .../types/tx_msg_create_resource_payload.go | 4 ++-- .../tx_msg_create_resource_payload_test.go | 2 +- x/resource/types/validate.go | 8 +++---- x/resource/utils/mime_type.go | 8 +++++-- x/resource/utils/resource_type.go | 6 ++++- 8 files changed, 34 insertions(+), 35 deletions(-) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index ca714cc69..d4d40a91e 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -83,12 +83,9 @@ func GetResourceKeyBytes(collectionId string, id string) []byte { return []byte(collectionId + ":" + id) } -// GetAllCollectionResourceIterator returns an iterator over all resources of a collection -// It's up to the caller to close the iterator -func (k Keeper) GetAllCollectionResourceIterator(ctx *sdk.Context, collectionId string) (iterator sdk.Iterator) { - collectionPrefix := types.KeyPrefix(types.ResourceKey + collectionId + ":") - return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), collectionPrefix) -} +func (k Keeper) GetLastResourceVersion(collectionId, id, name, resourceType, mimeType string) (uint64, error) { + store := prefix.NewStore(k.ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) + // GetAllResources returns all resources as a list // Loads everything in memory. Use only for genesis export! diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 3d7a6f89a..c38ebf662 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -18,6 +18,10 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes // 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) { @@ -25,7 +29,6 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes } // Validate signatures - didDocStateValue, err := k.cheqdKeeper.GetDid(&ctx, did) didDoc, err := didDocStateValue.UnpackDataAsDid() if err != nil { return nil, err @@ -44,7 +47,10 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes resource.Checksum = string(sha256.New().Sum(resource.Data)) resource.Created = time.Now().UTC().Format(time.RFC3339) - // TODO: set version + update forward and backward links + + // Find previous version and upgrade backward and forward version links + + // Append backlink to didDoc didDocStateValue.Metadata.Resources = append(didDocStateValue.Metadata.Resources, resource.Id) diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index a6a9580eb..2468242c9 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -3,6 +3,8 @@ package tests import ( "crypto/ed25519" "crypto/sha256" + "github.com/cheqd/cheqd-node/x/cheqd/utils" + // "crypto/sha256" "fmt" "testing" @@ -37,7 +39,6 @@ func TestCreateResource(t *testing.T) { Data: []byte(SchemaData), }, previousVersionId: "", - errMsg: "", }, { valid: true, @@ -54,7 +55,6 @@ func TestCreateResource(t *testing.T) { Data: ExistingResource().Data, }, previousVersionId: ExistingResource().Id, - errMsg: "", }, { valid: false, @@ -96,7 +96,7 @@ func TestCreateResource(t *testing.T) { MimeType: JsonResourceType, Data: []byte(SchemaData), }, - errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), + errMsg: fmt.Sprintf("did:cheqd:test:%s: not found", NotFoundDIDIdentifier), }, } @@ -109,7 +109,8 @@ func TestCreateResource(t *testing.T) { if tc.valid { require.Nil(t, err) - didStateValue, err := resourceSetup.Keeper.GetDid(&resourceSetup.Ctx, resource.CollectionId) + did := utils.JoinDID("cheqd", "test", resource.CollectionId) + didStateValue, err := resourceSetup.Keeper.GetDid(&resourceSetup.Ctx, did) require.Nil(t, err) require.Contains(t, didStateValue.Metadata.Resources, resource.Id) @@ -121,9 +122,6 @@ func TestCreateResource(t *testing.T) { require.Equal(t, tc.msg.Name, resource.Name) require.Equal(t, string(sha256.New().Sum(resource.Data)), resource.Checksum) require.Equal(t, tc.previousVersionId, resource.PreviousVersionId) - // if tc.previousVersionId != "" { - // require.Equal(t, resource.Id, resource.NextVersionId) - // } } else { require.Error(t, err) require.Equal(t, tc.errMsg, err.Error()) @@ -131,13 +129,3 @@ func TestCreateResource(t *testing.T) { }) } } - -// func TestHandler_ResourceDocAlreadyExists(t *testing.T) { -// setup := Setup() - -// _, _, _ = setup.InitDid(AliceDID) -// _, _, err := setup.InitDid(AliceDID) - -// require.Error(t, err) -// require.Equal(t, fmt.Sprintf("%s: DID Doc exists", AliceDID), err.Error()) -// } diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go index 2d66fc0a5..c1abec8bf 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -31,8 +31,8 @@ func (msg MsgCreateResourcePayload) Validate() error { validation.Field(&msg.CollectionId, validation.Required, cheqdTypes.IsID()), validation.Field(&msg.Id, validation.Required, IsUUID()), validation.Field(&msg.Name, validation.Required, validation.Length(1, 64)), - validation.Field(&msg.ResourceType, validation.Required, isResourceTypeAllowed()), - validation.Field(&msg.ResourceType, validation.Required, isMimeTypeAllowed()), + validation.Field(&msg.ResourceType, validation.Required, IsAllowedResourceType()), + validation.Field(&msg.MimeType, validation.Required, IsAllowedMimeType()), validation.Field(&msg.Data, validation.Required, validation.Length(1, 1024*1024)), // 1MB ) } diff --git a/x/resource/types/tx_msg_create_resource_payload_test.go b/x/resource/types/tx_msg_create_resource_payload_test.go index 1c716c1c1..1f1adf33a 100644 --- a/x/resource/types/tx_msg_create_resource_payload_test.go +++ b/x/resource/types/tx_msg_create_resource_payload_test.go @@ -19,7 +19,7 @@ func TestMsgUpdateDidValidation(t *testing.T) { Id: "ba62c728-cb15-498b-8e9e-9259cc242186", Name: "Test Resource", ResourceType: "CL-Schema", - MimeType: "text/plain", + MimeType: "application/json", Data: []byte {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, }, isValid: true, diff --git a/x/resource/types/validate.go b/x/resource/types/validate.go index a22db7ef3..939d072d9 100644 --- a/x/resource/types/validate.go +++ b/x/resource/types/validate.go @@ -18,22 +18,22 @@ func IsUUID() *cheqdTypes.CustomErrorRule { }) } -func isResourceTypeAllowed()*cheqdTypes.CustomErrorRule { +func IsAllowedResourceType()*cheqdTypes.CustomErrorRule { return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { casted, ok := value.(string) if !ok { - panic("IsDID must be only applied on string properties") + panic("IsAllowedResourceType must be only applied on string properties") } return utils.ValidateResourceType(casted) }) } -func isMimeTypeAllowed()*cheqdTypes.CustomErrorRule { +func IsAllowedMimeType()*cheqdTypes.CustomErrorRule { return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { casted, ok := value.(string) if !ok { - panic("IsDID must be only applied on string properties") + panic("IsAllowedMimeType must be only applied on string properties") } return utils.ValidateMimeType(casted) diff --git a/x/resource/utils/mime_type.go b/x/resource/utils/mime_type.go index 805575d2f..43e218736 100644 --- a/x/resource/utils/mime_type.go +++ b/x/resource/utils/mime_type.go @@ -9,9 +9,13 @@ import ( var AllowedMimeTypes = []string {"application/json", "image/png"} +func IsValidMimeType(rt string) bool { + return cheqdUtils.Contains(AllowedMimeTypes, rt) +} + func ValidateMimeType(rt string) error { - if ! cheqdUtils.Contains(AllowedMimeTypes, rt) { - return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedResourceTypes, ",") + " .") + if ! IsValidMimeType(rt) { + return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedMimeTypes, ",") + " .") } return nil diff --git a/x/resource/utils/resource_type.go b/x/resource/utils/resource_type.go index d059dd93d..2822fdfa1 100644 --- a/x/resource/utils/resource_type.go +++ b/x/resource/utils/resource_type.go @@ -9,8 +9,12 @@ import ( var AllowedResourceTypes = []string {"CL-Schema", "JSONSchema2020"} +func IsValidResourceType(rt string) bool { + return cheqdUtils.Contains(AllowedResourceTypes, rt) +} + func ValidateResourceType(rt string) error { - if ! cheqdUtils.Contains(AllowedResourceTypes, rt) { + if !IsValidResourceType(rt) { return errors.New(rt + " resource type is not allowed. Only " + strings.Join(AllowedResourceTypes, ",") + " .") } From 6d171574d41c0002202fc666122df60db5d9b136 Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Fri, 17 Jun 2022 17:32:24 +0300 Subject: [PATCH 23/65] Fixes and tests for resourceType and MimeTYpe --- .../types/tx_msg_create_resource_payload.go | 4 +-- .../tx_msg_create_resource_payload_test.go | 30 +++++++++++++++++-- x/resource/types/validate.go | 4 +-- x/resource/utils/mime_type.go | 2 +- x/resource/utils/resource_type.go | 2 +- 5 files changed, 34 insertions(+), 8 deletions(-) diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go index 2d66fc0a5..c73ef3880 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -20,7 +20,7 @@ func (msg *MsgCreateResourcePayload) ToResource() Resource { MimeType: msg.MimeType, Data: msg.Data, Created: "", - Checksum: "", + Checksum: []byte {}, } } @@ -32,7 +32,7 @@ func (msg MsgCreateResourcePayload) Validate() error { validation.Field(&msg.Id, validation.Required, IsUUID()), validation.Field(&msg.Name, validation.Required, validation.Length(1, 64)), validation.Field(&msg.ResourceType, validation.Required, isResourceTypeAllowed()), - validation.Field(&msg.ResourceType, validation.Required, isMimeTypeAllowed()), + validation.Field(&msg.MimeType, validation.Required, isMimeTypeAllowed()), validation.Field(&msg.Data, validation.Required, validation.Length(1, 1024*1024)), // 1MB ) } diff --git a/x/resource/types/tx_msg_create_resource_payload_test.go b/x/resource/types/tx_msg_create_resource_payload_test.go index 1c716c1c1..dfbd6afc7 100644 --- a/x/resource/types/tx_msg_create_resource_payload_test.go +++ b/x/resource/types/tx_msg_create_resource_payload_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -func TestMsgUpdateDidValidation(t *testing.T) { +func TestMsgCreateResourcePayloadValidation(t *testing.T) { cases := []struct { name string struct_ *MsgCreateResourcePayload @@ -19,11 +19,37 @@ func TestMsgUpdateDidValidation(t *testing.T) { Id: "ba62c728-cb15-498b-8e9e-9259cc242186", Name: "Test Resource", ResourceType: "CL-Schema", - MimeType: "text/plain", + MimeType: "image/png", 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: "Not-CL-Schema", + MimeType: "image/png", + Data: []byte {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + }, + isValid: false, + errorMsg: "resource_type: Not-CL-Schema resource type is not allowed. Only CL-Schema,JSONSchema2020.", + }, + { + name: "negative mime type", + struct_: &MsgCreateResourcePayload{ + CollectionId: "123456789abcdefg", + Id: "ba62c728-cb15-498b-8e9e-9259cc242186", + Name: "Test Resource", + ResourceType: "CL-Schema", + MimeType: "text/data", + Data: []byte {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + }, + isValid: false, + errorMsg: "mime_type: text/data mime type is not allowed. Only application/json,image/png.", + }, } for _, tc := range cases { diff --git a/x/resource/types/validate.go b/x/resource/types/validate.go index a22db7ef3..6c1216bd4 100644 --- a/x/resource/types/validate.go +++ b/x/resource/types/validate.go @@ -22,7 +22,7 @@ func isResourceTypeAllowed()*cheqdTypes.CustomErrorRule { return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { casted, ok := value.(string) if !ok { - panic("IsDID must be only applied on string properties") + panic("isResourceTypeAllowed must be only applied on string properties") } return utils.ValidateResourceType(casted) @@ -33,7 +33,7 @@ func isMimeTypeAllowed()*cheqdTypes.CustomErrorRule { return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { casted, ok := value.(string) if !ok { - panic("IsDID must be only applied on string properties") + panic("isMimeTypeAllowed must be only applied on string properties") } return utils.ValidateMimeType(casted) diff --git a/x/resource/utils/mime_type.go b/x/resource/utils/mime_type.go index 805575d2f..8cda87acf 100644 --- a/x/resource/utils/mime_type.go +++ b/x/resource/utils/mime_type.go @@ -11,7 +11,7 @@ var AllowedMimeTypes = []string {"application/json", "image/png"} func ValidateMimeType(rt string) error { if ! cheqdUtils.Contains(AllowedMimeTypes, rt) { - return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedResourceTypes, ",") + " .") + return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedMimeTypes, ",")) } return nil diff --git a/x/resource/utils/resource_type.go b/x/resource/utils/resource_type.go index d059dd93d..73b28d612 100644 --- a/x/resource/utils/resource_type.go +++ b/x/resource/utils/resource_type.go @@ -11,7 +11,7 @@ var AllowedResourceTypes = []string {"CL-Schema", "JSONSchema2020"} func ValidateResourceType(rt string) error { if ! cheqdUtils.Contains(AllowedResourceTypes, rt) { - return errors.New(rt + " resource type is not allowed. Only " + strings.Join(AllowedResourceTypes, ",") + " .") + return errors.New(rt + " resource type is not allowed. Only " + strings.Join(AllowedResourceTypes, ",")) } return nil From 7f2dbb42d5f9ad833a9becb3ffcd5f1d28556370 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Fri, 17 Jun 2022 17:47:49 +0300 Subject: [PATCH 24/65] Fix merge conflivts --- x/resource/keeper/keeper_resource.go | 4 ++-- x/resource/tests/constants.go | 2 +- x/resource/tests/create_resource_test.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index d4d40a91e..a3d12380e 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -83,8 +83,8 @@ func GetResourceKeyBytes(collectionId string, id string) []byte { return []byte(collectionId + ":" + id) } -func (k Keeper) GetLastResourceVersion(collectionId, id, name, resourceType, mimeType string) (uint64, error) { - store := prefix.NewStore(k.ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) +//func (k Keeper) GetLastResourceVersion(collectionId, id, name, resourceType, mimeType string) (uint64, error) { +// store := prefix.NewStore(k.ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) // GetAllResources returns all resources as a list diff --git a/x/resource/tests/constants.go b/x/resource/tests/constants.go index c2b21ae53..3a7399ac5 100644 --- a/x/resource/tests/constants.go +++ b/x/resource/tests/constants.go @@ -22,7 +22,7 @@ const ( func ExistingResource() types.Resource { data := []byte(SchemaData) - checksum := string(sha256.New().Sum(data)) + checksum := sha256.New().Sum(data) return types.Resource{ CollectionId: ExistingDIDIdentifier, Id: "a09abea0-22e0-4b35-8f70-9cc3a6d0b5fd", diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index 2468242c9..02a86b571 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -120,7 +120,7 @@ func TestCreateResource(t *testing.T) { require.Equal(t, tc.msg.ResourceType, resource.ResourceType) require.Equal(t, tc.msg.Data, resource.Data) require.Equal(t, tc.msg.Name, resource.Name) - require.Equal(t, string(sha256.New().Sum(resource.Data)), resource.Checksum) + require.Equal(t, sha256.New().Sum(resource.Data), resource.Checksum) require.Equal(t, tc.previousVersionId, resource.PreviousVersionId) } else { require.Error(t, err) From 1f2946100c12940618455186370ff8f352b4eb86 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Fri, 17 Jun 2022 18:07:42 +0300 Subject: [PATCH 25/65] Finish resource creation --- x/resource/keeper/keeper_resource.go | 31 +++++++++++++++++-- .../keeper/msg_server_create_resource.go | 12 ++++++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index a3d12380e..5314027c6 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -83,8 +83,35 @@ func GetResourceKeyBytes(collectionId string, id string) []byte { return []byte(collectionId + ":" + id) } -//func (k Keeper) GetLastResourceVersion(collectionId, id, name, resourceType, mimeType string) (uint64, error) { -// store := prefix.NewStore(k.ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) +func GetResourceCollectionPrefixBytes(collectionId string) []byte { + return []byte(collectionId + ":") +} + +func (k Keeper) GetLastResourceVersion(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) (types.Resource, bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) + iterator := sdk.KVStorePrefixIterator(store, GetResourceCollectionPrefixBytes(collectionId)) + + defer func(iterator sdk.Iterator) { + err := iterator.Close() + if err != nil { + panic(err.Error()) + } + }(iterator) + + for ; iterator.Valid(); iterator.Next() { + var val types.Resource + k.cdc.MustUnmarshal(iterator.Value(), &val) + + if val.Name == name && + val.ResourceType == resourceType && + val.MimeType == mimeType && + val.NextVersionId == "" { + return val, true + } + } + + return types.Resource{}, false +} // GetAllResources returns all resources as a list diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 3ac65704b..150c21b10 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -49,8 +49,18 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes resource.Created = time.Now().UTC().Format(time.RFC3339) // Find previous version and upgrade backward and forward version links + previousResourceVersion, found := k.GetLastResourceVersion(&ctx, resource.CollectionId, resource.Name, resource.ResourceType, resource.MimeType) + if found { + // Set links + previousResourceVersion.NextVersionId = resource.Id + resource.PreviousVersionId = previousResourceVersion.Id - + // Update previous version + err := k.SetResource(&ctx, &previousResourceVersion) + if err != nil { + return nil, err + } + } // Append backlink to didDoc didDocStateValue.Metadata.Resources = append(didDocStateValue.Metadata.Resources, resource.Id) From 30003c4147f8f7f75ad32048ec7f998b86228816 Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Fri, 17 Jun 2022 18:42:21 +0300 Subject: [PATCH 26/65] fix tests --- x/resource/tests/constants.go | 2 +- x/resource/tests/query_resource_test.go | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/x/resource/tests/constants.go b/x/resource/tests/constants.go index c2b21ae53..3a7399ac5 100644 --- a/x/resource/tests/constants.go +++ b/x/resource/tests/constants.go @@ -22,7 +22,7 @@ const ( func ExistingResource() types.Resource { data := []byte(SchemaData) - checksum := string(sha256.New().Sum(data)) + checksum := sha256.New().Sum(data) return types.Resource{ CollectionId: ExistingDIDIdentifier, Id: "a09abea0-22e0-4b35-8f70-9cc3a6d0b5fd", diff --git a/x/resource/tests/query_resource_test.go b/x/resource/tests/query_resource_test.go index c5cc47fbc..4673fdba3 100644 --- a/x/resource/tests/query_resource_test.go +++ b/x/resource/tests/query_resource_test.go @@ -3,6 +3,7 @@ package tests import ( // "crypto/sha256" + "crypto/sha256" "fmt" "testing" @@ -71,7 +72,7 @@ func TestQueryGetResource(t *testing.T) { require.Equal(t, tc.response.Resource.ResourceType, resource.ResourceType) require.Equal(t, tc.response.Resource.Data, resource.Data) require.Equal(t, tc.response.Resource.Name, resource.Name) - // require.Equal(t, string(sha256.New().Sum(response.Resource.Data)), resource.Checksum) + require.Equal(t, sha256.New().Sum(tc.response.Resource.Data), resource.Checksum) require.Equal(t, tc.response.Resource.PreviousVersionId, resource.PreviousVersionId) require.Equal(t, tc.response.Resource.NextVersionId, resource.NextVersionId) } else { From d8b0bdfc080f57ac686f1e6c6b4193307d7041bc Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Mon, 20 Jun 2022 10:11:43 +0300 Subject: [PATCH 27/65] for moving to another machine --- x/resource/keeper/keeper_resource.go | 15 +++++++++++++++ x/resource/keeper/query_server_resource.go | 18 +++++++++--------- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index 5314027c6..52c0ee8d1 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -72,6 +72,21 @@ func (k Keeper) GetResource(ctx *sdk.Context, collectionId string, id string) (t return value, nil } +// GetAllResource return a list of resources for corresponded DID +func (ms msgServer) GetResourceCollection(ctx *sdk.Context, didId string) (types.Resource, error) { + didDocStateValue, err := ms.cheqdKeeper.GetDid(ctx, didId) + if err != nil { + return nil, err + } + + value := []types.Resource + for rId := range didDocStateValue.Metadata.Resources { + + } + + return nil, err +} + // HasResource checks if the resource exists in the store func (k Keeper) HasResource(ctx *sdk.Context, collectionId string, id string) bool { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) diff --git a/x/resource/keeper/query_server_resource.go b/x/resource/keeper/query_server_resource.go index 53c6467ed..5f73e0e40 100644 --- a/x/resource/keeper/query_server_resource.go +++ b/x/resource/keeper/query_server_resource.go @@ -9,14 +9,14 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) Resource(c context.Context, req *types.QueryGetResourceRequest) (*types.QueryGetResourceResponse, error) { +func (ms msgServer) 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) - resource, err := k.GetResource(&ctx, req.CollectionId, req.Id) + resource, err := ms.GetResource(&ctx, req.CollectionId, req.Id) if err != nil { return nil, err } @@ -24,17 +24,17 @@ func (k Keeper) Resource(c context.Context, req *types.QueryGetResourceRequest) return &types.QueryGetResourceResponse{Resource: &resource}, nil } -func (k Keeper) CollectionResources(c context.Context, req *types.QueryGetCollectionResourcesRequest) (*types.QueryGetCollectionResourcesResponse, error) { +func (ms msgServer) CollectionResources(c context.Context, req *types.QueryGetCollectionResourcesRequest) (*types.QueryGetCollectionResourcesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } - // ctx := sdk.UnwrapSDKContext(c) + ctx := sdk.UnwrapSDKContext(c) - // stateResource, err := k.GetAllResource(&ctx, req.CollectionId) - // if err != nil { - // return nil, err - // } + stateResource, err := ms.GetResourceCollection(&ctx, req.CollectionId) + if err != nil { + return nil, err + } // resource, err := stateResource.UnpackDataAsResource() // if err != nil { @@ -44,7 +44,7 @@ func (k Keeper) CollectionResources(c context.Context, req *types.QueryGetCollec return &types.QueryGetCollectionResourcesResponse{Resources: []*types.Resource{}}, nil } -func (k Keeper) AllResourceVersions(c context.Context, req *types.QueryGetAllResourceVersionsRequest) (*types.QueryGetAllResourceVersionsResponse, error) { +func (m msgServer) AllResourceVersions(c context.Context, req *types.QueryGetAllResourceVersionsRequest) (*types.QueryGetAllResourceVersionsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } From 0b32565e3b18d48afe336df81d7df77065e33860 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Mon, 20 Jun 2022 17:33:29 +0300 Subject: [PATCH 28/65] Implement query all versions query --- x/resource/keeper/keeper_resource.go | 27 ++++++++++++++ .../query_server_all_resource_versions.go | 36 +++++++++++-------- 2 files changed, 48 insertions(+), 15 deletions(-) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index 52c0ee8d1..e67c46d2c 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -102,6 +102,33 @@ func GetResourceCollectionPrefixBytes(collectionId string) []byte { return []byte(collectionId + ":") } +func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) []*types.Resource { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) + iterator := sdk.KVStorePrefixIterator(store, GetResourceCollectionPrefixBytes(collectionId)) + + defer func(iterator sdk.Iterator) { + err := iterator.Close() + if err != nil { + panic(err.Error()) + } + }(iterator) + + var result []*types.Resource + + for ; iterator.Valid(); iterator.Next() { + var val types.Resource + k.cdc.MustUnmarshal(iterator.Value(), &val) + + if val.Name == name && + val.ResourceType == resourceType && + val.MimeType == mimeType { + result = append(result, &val) + } + } + + return result +} + func (k Keeper) GetLastResourceVersion(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) (types.Resource, bool) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) iterator := sdk.KVStorePrefixIterator(store, GetResourceCollectionPrefixBytes(collectionId)) diff --git a/x/resource/keeper/query_server_all_resource_versions.go b/x/resource/keeper/query_server_all_resource_versions.go index b1d561ad5..b234be3a3 100644 --- a/x/resource/keeper/query_server_all_resource_versions.go +++ b/x/resource/keeper/query_server_all_resource_versions.go @@ -1,17 +1,23 @@ package keeper -//func getResource(ctx sdk.Context, collectionId string, id string, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { -// queryServer := NewQueryServer(keeper) -// -// 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 -//} +import ( + "context" + "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) + + versions := m.GetAllResourceVersions(&ctx, req.CollectionId, req.Name, req.ResourceType, req.MimeType) + + return &types.QueryGetAllResourceVersionsResponse{ + Resources: versions, + }, nil +} From 44f14086dafcfc935053826afdad0bd7cdf5b712 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Mon, 20 Jun 2022 18:13:58 +0300 Subject: [PATCH 29/65] Implementation --- x/resource/keeper/keeper.go | 10 ++-- x/resource/keeper/keeper_resource.go | 16 ------ x/resource/keeper/query.go | 2 +- .../keeper/query_all_resource_versions.go | 35 +++++++++++++ .../keeper/query_collection_resource.go | 35 +++++++++++++ x/resource/keeper/query_resource.go | 24 +++++++++ .../query_server_collection_resources.go | 20 ++----- x/resource/keeper/query_server_resource.go | 52 +++---------------- x/resource/module.go | 34 ++++++------ 9 files changed, 126 insertions(+), 102 deletions(-) create mode 100644 x/resource/keeper/query_all_resource_versions.go create mode 100644 x/resource/keeper/query_collection_resource.go create mode 100644 x/resource/keeper/query_resource.go diff --git a/x/resource/keeper/keeper.go b/x/resource/keeper/keeper.go index 2f6297b09..cba9a9ad6 100644 --- a/x/resource/keeper/keeper.go +++ b/x/resource/keeper/keeper.go @@ -10,12 +10,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -type ( - Keeper struct { - cdc codec.BinaryCodec - storeKey sdk.StoreKey - } -) +type Keeper struct { + cdc codec.BinaryCodec + storeKey sdk.StoreKey +} func NewKeeper(cdc codec.BinaryCodec, storeKey sdk.StoreKey) *Keeper { return &Keeper{ diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index e67c46d2c..8af0768dc 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -72,21 +72,6 @@ func (k Keeper) GetResource(ctx *sdk.Context, collectionId string, id string) (t return value, nil } -// GetAllResource return a list of resources for corresponded DID -func (ms msgServer) GetResourceCollection(ctx *sdk.Context, didId string) (types.Resource, error) { - didDocStateValue, err := ms.cheqdKeeper.GetDid(ctx, didId) - if err != nil { - return nil, err - } - - value := []types.Resource - for rId := range didDocStateValue.Metadata.Resources { - - } - - return nil, err -} - // HasResource checks if the resource exists in the store func (k Keeper) HasResource(ctx *sdk.Context, collectionId string, id string) bool { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) @@ -155,7 +140,6 @@ func (k Keeper) GetLastResourceVersion(ctx *sdk.Context, collectionId, name, res return types.Resource{}, false } - // 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) { diff --git a/x/resource/keeper/query.go b/x/resource/keeper/query.go index 9559824f0..a3247ad05 100644 --- a/x/resource/keeper/query.go +++ b/x/resource/keeper/query.go @@ -18,7 +18,7 @@ func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { switch path[0] { case types.QueryGetResource: - return getResource(ctx, path[1], path[2], k, legacyQuerierCdc) + return resource(ctx, k, legacyQuerierCdc, path[1], path[2]) // case types.QueryGetCollectionResources: // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) // case types.QueryGetAllResourceVersions: 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..479203986 --- /dev/null +++ b/x/resource/keeper/query_all_resource_versions.go @@ -0,0 +1,35 @@ +package keeper + +//import ( +// "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, 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 k.Res(ctx, path[1], path[2], k, legacyQuerierCdc) +// // case types.QueryGetCollectionResources: +// // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) +// // case types.QueryGetAllResourceVersions: +// // return getAllResourceVersions(ctx, path[1], k, legacyQuerierCdc) +// +// 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_collection_resource.go b/x/resource/keeper/query_collection_resource.go new file mode 100644 index 000000000..479203986 --- /dev/null +++ b/x/resource/keeper/query_collection_resource.go @@ -0,0 +1,35 @@ +package keeper + +//import ( +// "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, 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 k.Res(ctx, path[1], path[2], k, legacyQuerierCdc) +// // case types.QueryGetCollectionResources: +// // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) +// // case types.QueryGetAllResourceVersions: +// // return getAllResourceVersions(ctx, path[1], k, legacyQuerierCdc) +// +// 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_resource.go b/x/resource/keeper/query_resource.go new file mode 100644 index 000000000..bcaa4888f --- /dev/null +++ b/x/resource/keeper/query_resource.go @@ -0,0 +1,24 @@ +package keeper + +import ( + "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, legacyQuerierCdc *codec.LegacyAmino, collectionId, id string) ([]byte, error) { + queryServer := NewQueryServer(keeper) + + 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_collection_resources.go b/x/resource/keeper/query_server_collection_resources.go index 652f812be..3abc312cb 100644 --- a/x/resource/keeper/query_server_collection_resources.go +++ b/x/resource/keeper/query_server_collection_resources.go @@ -1,24 +1,10 @@ package keeper import ( + "context" "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 getResource(ctx sdk.Context, collectionId string, id string, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - queryServer := NewQueryServer(keeper) - - 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 +func (q queryServer) CollectionResources(ctx context.Context, request *types.QueryGetCollectionResourcesRequest) (*types.QueryGetCollectionResourcesResponse, error) { + panic("implement me") } diff --git a/x/resource/keeper/query_server_resource.go b/x/resource/keeper/query_server_resource.go index 5f73e0e40..86b1012eb 100644 --- a/x/resource/keeper/query_server_resource.go +++ b/x/resource/keeper/query_server_resource.go @@ -2,64 +2,26 @@ package keeper import ( "context" - - "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 (ms msgServer) 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) - - resource, err := ms.GetResource(&ctx, req.CollectionId, req.Id) - if err != nil { - return nil, err - } - return &types.QueryGetResourceResponse{Resource: &resource}, nil -} + "github.com/cheqd/cheqd-node/x/resource/types" +) -func (ms msgServer) CollectionResources(c context.Context, req *types.QueryGetCollectionResourcesRequest) (*types.QueryGetCollectionResourcesResponse, error) { +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) - stateResource, err := ms.GetResourceCollection(&ctx, req.CollectionId) + resource, err := q.GetResource(&ctx, req.CollectionId, req.Id) if err != nil { return nil, err } - // resource, err := stateResource.UnpackDataAsResource() - // if err != nil { - // return nil, err - // } - - return &types.QueryGetCollectionResourcesResponse{Resources: []*types.Resource{}}, nil -} - -func (m msgServer) 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) - - // stateResource, err := k.GetResource(&ctx, req.CollectionId, req.Id) - // if err != nil { - // return nil, err - // } - - // resource, err := stateResource.UnpackDataAsResource() - // if err != nil { - // return nil, err - // } - - return &types.QueryGetAllResourceVersionsResponse{Resources: []*types.Resource{}}, nil + return &types.QueryGetResourceResponse{ + Resource: &resource, + }, nil } diff --git a/x/resource/module.go b/x/resource/module.go index c44409b4f..ab84dc427 100644 --- a/x/resource/module.go +++ b/x/resource/module.go @@ -33,7 +33,7 @@ var ( // AppModuleBasic // ---------------------------------------------------------------------------- -// AppModuleBasic implements the AppModuleBasic interface for the capability module. +// AppModuleBasic implements the AppModuleBasic interface for the resource 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 resource 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 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 capability module. +// 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 { @@ -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 resource 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 resource 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 resource module's root query command. func (AppModuleBasic) GetQueryCmd() *cobra.Command { return cli.GetQueryCmd() } @@ -125,20 +125,20 @@ func (am AppModule) ConsensusVersion() uint64 { return 1 } -// Name returns the capability module's name. +// Name returns the resource module's name. func (am AppModule) Name() string { return am.AppModuleBasic.Name() } -// Route returns the capability module's message routing key. +// 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 capability module's query routing key. +// QuerierRoute returns the resource module's query routing key. func (AppModule) QuerierRoute() string { return types.QuerierRoute } -// LegacyQuerierHandler returns the capability module's Querier. +// LegacyQuerierHandler returns the resource module's Querier. func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } @@ -146,13 +146,13 @@ func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sd // 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(), am.keeper) + types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServer(am.keeper)) } -// RegisterInvariants registers the capability module's invariants. +// RegisterInvariants registers the resource module's invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// InitGenesis performs the capability module's genesis initialization It returns +// 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 @@ -164,16 +164,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 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 capability module. +// 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 capability module. It +// 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{} From abc9e3379d07a09aa688decd4b3b84f468f95bdf Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Mon, 20 Jun 2022 18:46:44 +0300 Subject: [PATCH 30/65] Add cli command and bash test for query resource --- tests/e2e-bash/tests/test_create_resource.sh | 23 +++++-- x/resource/client/cli/query.go | 2 +- x/resource/client/cli/query_resource.go | 67 ++++++++++++-------- 3 files changed, 59 insertions(+), 33 deletions(-) diff --git a/tests/e2e-bash/tests/test_create_resource.sh b/tests/e2e-bash/tests/test_create_resource.sh index 24c42b809..3966b8f82 100644 --- a/tests/e2e-bash/tests/test_create_resource.sh +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -41,14 +41,14 @@ assert_tx_successful "$RESULT" # Build CreateResource message RESOURCE_ID=$(uuidgen) -RESOURCE_NAME="Test resource" -RESOURCE_DATA="dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh" MSG_CREATE_RESOURCE='{ "collection_id": "'${ID}'", "id": "'${RESOURCE_ID}'", - "name": "'${RESOURCE_NAME}'", - "data": "'${RESOURCE_DATA}'" + "name": "Test resource", + "mime_type": "application/json", + "resource_type": "CL-Schema", + "data": "dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh" }'; # Post the message @@ -57,3 +57,18 @@ RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE}" "${KEY --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" + +# Query Resource +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded query resource resource "${ID}" ${RESOURCE_ID} ${QUERY_PARAMS}) + +EXPECTED='{ + "collection_id": "'${ID}'", + "id": "'${RESOURCE_ID}'", + "name": "Test resource", + "mime_type": "application/json", + "resource_type": "CL-Schema", + "data": "dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh" +}' + +assert_json_eq "$(echo "$RESULT" | jq -r ".resource | del(.checksum, .created, .next_version_id, .previous_version_id)")" "${EXPECTED}" diff --git a/x/resource/client/cli/query.go b/x/resource/client/cli/query.go index be0642e5d..aaa08ab4d 100644 --- a/x/resource/client/cli/query.go +++ b/x/resource/client/cli/query.go @@ -19,7 +19,7 @@ func GetQueryCmd() *cobra.Command { RunE: client.ValidateCmd, } - //cmd.AddCommand(CmdGetDid()) + cmd.AddCommand(CmdGetResource()) return cmd } diff --git a/x/resource/client/cli/query_resource.go b/x/resource/client/cli/query_resource.go index 2ffada1d3..b36bee753 100644 --- a/x/resource/client/cli/query_resource.go +++ b/x/resource/client/cli/query_resource.go @@ -1,30 +1,41 @@ package cli -//func CmdGetDid() *cobra.Command { -// cmd := &cobra.Command{ -// Use: "did [id]", -// Short: "Query a did", -// Args: cobra.ExactArgs(1), -// RunE: func(cmd *cobra.Command, args []string) error { -// clientCtx := client.GetClientContextFromCmd(cmd) -// -// queryClient := types.NewQueryClient(clientCtx) -// -// did := args[0] -// params := &types.QueryGetDidRequest{ -// Id: did, -// } -// -// resp, err := queryClient.Did(context.Background(), params) -// if err != nil { -// return err -// } -// -// return clientCtx.PrintProto(resp) -// }, -// } -// -// flags.AddQueryFlagsToCmd(cmd) -// -// return cmd -//} +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 +} From 9de750d352261466c49e2ea55222bdd39c502960 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Mon, 20 Jun 2022 19:26:10 +0300 Subject: [PATCH 31/65] Finish get allresource versions query and tests --- tests/e2e-bash/tests/test_create_resource.sh | 112 +++++++++++++----- x/resource/client/cli/query.go | 3 +- .../client/cli/query_all_resource_versions.go | 45 +++++++ x/resource/keeper/query.go | 8 +- .../keeper/query_all_resource_versions.go | 60 +++++----- 5 files changed, 159 insertions(+), 69 deletions(-) create mode 100644 x/resource/client/cli/query_all_resource_versions.go diff --git a/tests/e2e-bash/tests/test_create_resource.sh b/tests/e2e-bash/tests/test_create_resource.sh index 3966b8f82..08380082e 100644 --- a/tests/e2e-bash/tests/test_create_resource.sh +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -13,62 +13,112 @@ 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}") -# Build CreateDid message -ID="$(random_string)" -DID="did:cheqd:testnet:$ID" -KEY_ID="${DID}#key1" -MSG_CREATE_DID='{ - "id": "'${DID}'", +########## Creating DID 1 ########## + +ID1="$(random_string)" +DID1="did:cheqd:testnet:$ID1" +KEY1_ID="${DID1}#key1" + +MSG_CREATE_DID_1='{ + "id": "'${DID1}'", "verification_method": [{ - "id": "'${KEY_ID}'", + "id": "'${KEY1_ID}'", "type": "Ed25519VerificationKey2020", - "controller": "'${DID}'", + "controller": "'${DID1}'", "public_key_multibase": "'${ALICE_VER_PUB_MULTIBASE_58}'" }], "authentication": [ - "'${KEY_ID}'" + "'${KEY1_ID}'" ] }'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx cheqd create-did "${MSG_CREATE_DID}" "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +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" -# Build CreateResource message -RESOURCE_ID=$(uuidgen) +########## Creating Resource 1 ########## + +RESOURCE1_V1_ID=$(uuidgen) +RESOURCE1_V1_NAME="Resource 1" +RESOURCE1_V1_MIME_TYPE="application/json" +RESOURCE1_V1_RESOURCE_TYPE="CL-Schema" +RESOURCE1_V1_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; -MSG_CREATE_RESOURCE='{ - "collection_id": "'${ID}'", - "id": "'${RESOURCE_ID}'", - "name": "Test resource", - "mime_type": "application/json", - "resource_type": "CL-Schema", - "data": "dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh" +MSG_CREATE_RESOURCE1='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V1_ID}'", + "name": "'${RESOURCE1_V1_NAME}'", + "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", + "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", + "data": "'${RESOURCE1_V1_DATA}'" }'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE}" "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE1}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" -# Query Resource +########## Querying Resource 1 ########## + +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded query resource resource "${ID1}" ${RESOURCE1_V1_ID} ${QUERY_PARAMS}) + +EXPECTED_RES1_V1='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V1_ID}'", + "name": "'${RESOURCE1_V1_NAME}'", + "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", + "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", + "data": "'${RESOURCE1_V1_DATA}'" +}' + +DEL_FILTER='del(.checksum, .created, .next_version_id, .previous_version_id)' +assert_json_eq "$(echo "$RESULT" | jq -r ".resource | ${DEL_FILTER}")" "${EXPECTED_RES1_V1}" + + +########## Creating Resource 1 v2 ########## + +RESOURCE1_V2_ID=$(uuidgen) +RESOURCE1_V2_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhLg=='; + +MSG_CREATE_RESOURCE1_V2='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V2_ID}'", + "name": "'${RESOURCE1_V1_NAME}'", + "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", + "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", + "data": "'${RESOURCE1_V2_DATA}'" +}'; + +# Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded query resource resource "${ID}" ${RESOURCE_ID} ${QUERY_PARAMS}) - -EXPECTED='{ - "collection_id": "'${ID}'", - "id": "'${RESOURCE_ID}'", - "name": "Test resource", - "mime_type": "application/json", - "resource_type": "CL-Schema", - "data": "dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh" +RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE1_V2}" "${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='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V2_ID}'", + "name": "'${RESOURCE1_V1_NAME}'", + "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", + "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", + "data": "'${RESOURCE1_V2_DATA}'" }' -assert_json_eq "$(echo "$RESULT" | jq -r ".resource | del(.checksum, .created, .next_version_id, .previous_version_id)")" "${EXPECTED}" +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded query resource all-resource-versions "${ID1}" "${RESOURCE1_V1_NAME}" ${RESOURCE1_V1_RESOURCE_TYPE} ${RESOURCE1_V1_MIME_TYPE} ${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}" +assert_json_eq "$(echo "$RESULT" | jq -r '.resources[] | select(.id == "'"${RESOURCE1_V2_ID}"'") | '"${DEL_FILTER}"'')" "${EXPECTED_RES1_V2}" diff --git a/x/resource/client/cli/query.go b/x/resource/client/cli/query.go index aaa08ab4d..3ea176235 100644 --- a/x/resource/client/cli/query.go +++ b/x/resource/client/cli/query.go @@ -19,7 +19,8 @@ func GetQueryCmd() *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdGetResource()) + cmd.AddCommand(CmdGetResource(), + CmdGetAllResourceVersions()) 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..814ae6156 --- /dev/null +++ b/x/resource/client/cli/query_all_resource_versions.go @@ -0,0 +1,45 @@ +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] [mimeType]", + Short: "Query a resource", + Args: cobra.ExactArgs(4), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + + queryClient := types.NewQueryClient(clientCtx) + + collectionId := args[0] + name := args[1] + resourceType := args[2] + mimeType := args[3] + + params := &types.QueryGetAllResourceVersionsRequest{ + CollectionId: collectionId, + Name: name, + ResourceType: resourceType, + MimeType: mimeType, + } + + 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/keeper/query.go b/x/resource/keeper/query.go index a3247ad05..bebc7fd6d 100644 --- a/x/resource/keeper/query.go +++ b/x/resource/keeper/query.go @@ -19,10 +19,10 @@ func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { switch path[0] { case types.QueryGetResource: return resource(ctx, k, legacyQuerierCdc, path[1], path[2]) - // case types.QueryGetCollectionResources: - // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) - // case types.QueryGetAllResourceVersions: - // return getAllResourceVersions(ctx, path[1], k, legacyQuerierCdc) + //case types.QueryGetCollectionResources: + // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) + case types.QueryGetAllResourceVersions: + return allResourceVersions(ctx, k, legacyQuerierCdc, path[1], path[2], path[3], path[4]) default: err = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) diff --git a/x/resource/keeper/query_all_resource_versions.go b/x/resource/keeper/query_all_resource_versions.go index 479203986..e5d9b7137 100644 --- a/x/resource/keeper/query_all_resource_versions.go +++ b/x/resource/keeper/query_all_resource_versions.go @@ -1,35 +1,29 @@ package keeper -//import ( -// "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, 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 k.Res(ctx, path[1], path[2], k, legacyQuerierCdc) -// // case types.QueryGetCollectionResources: -// // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) -// // case types.QueryGetAllResourceVersions: -// // return getAllResourceVersions(ctx, path[1], k, legacyQuerierCdc) -// -// default: -// err = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) -// } -// -// return res, err -// } -//} +import ( + "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, legacyQuerierCdc *codec.LegacyAmino, collectionId, name, resourceType, mimeType string) ([]byte, error) { + queryServer := NewQueryServer(keeper) + + resp, err := queryServer.AllResourceVersions(sdk.WrapSDKContext(ctx), &types.QueryGetAllResourceVersionsRequest{ + CollectionId: collectionId, + Name: name, + ResourceType: resourceType, + MimeType: mimeType, + }) + 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 +} From 07053ea06c149f0eff318305ff780c77ca982a90 Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Mon, 20 Jun 2022 21:11:42 +0300 Subject: [PATCH 32/65] Finish implementation --- x/resource/keeper/keeper_resource.go | 23 +++ .../query_server_collection_resources.go | 17 +- .../tests/query_collection_resources_test.go | 177 +++++++++--------- x/resource/tests/query_resource_test.go | 2 +- x/resource/tests/setup.go | 3 + x/resource/tests/utils.go | 6 +- 6 files changed, 133 insertions(+), 95 deletions(-) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index 8af0768dc..c9af1c40d 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -114,6 +114,29 @@ func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, res return result } +func (k Keeper) GetResourceCollection(ctx *sdk.Context, collectionId string) []*types.Resource { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) + iterator := sdk.KVStorePrefixIterator(store, GetResourceCollectionPrefixBytes(collectionId)) + + resources := []*types.Resource{} + + defer func(iterator sdk.Iterator) { + err := iterator.Close() + if err != nil { + panic(err.Error()) + } + }(iterator) + + for ; iterator.Valid(); iterator.Next() { + var val types.Resource + k.cdc.MustUnmarshal(iterator.Value(), &val) + resources = append(resources, &val) + + } + + return resources +} + func (k Keeper) GetLastResourceVersion(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) (types.Resource, bool) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) iterator := sdk.KVStorePrefixIterator(store, GetResourceCollectionPrefixBytes(collectionId)) diff --git a/x/resource/keeper/query_server_collection_resources.go b/x/resource/keeper/query_server_collection_resources.go index 3abc312cb..38c6ec80a 100644 --- a/x/resource/keeper/query_server_collection_resources.go +++ b/x/resource/keeper/query_server_collection_resources.go @@ -3,8 +3,21 @@ package keeper import ( "context" "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 (q queryServer) CollectionResources(ctx context.Context, request *types.QueryGetCollectionResourcesRequest) (*types.QueryGetCollectionResourcesResponse, error) { - panic("implement me") +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) + + resources := m.GetResourceCollection(&ctx, request.CollectionId) + + return &types.QueryGetCollectionResourcesResponse{ + Resources: resources, + }, nil } diff --git a/x/resource/tests/query_collection_resources_test.go b/x/resource/tests/query_collection_resources_test.go index 77869f984..7f88393e8 100644 --- a/x/resource/tests/query_collection_resources_test.go +++ b/x/resource/tests/query_collection_resources_test.go @@ -1,91 +1,90 @@ package tests -//import ( -// -// // "crypto/sha256" -// "crypto/ed25519" -// "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.QueryGetResourceRequest -// response *types.QueryGetResourceResponse -// errMsg string -// }{ -// { -// valid: true, -// name: "Valid: Works", -// msg: &types.QueryGetResourceRequest{ -// CollectionId: ExistingDIDIdentifier, -// Id: existingResource.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.Id, -// }, -// response: nil, -// errMsg: fmt.Sprintf("resource %s:%s: not found", NotFoundDIDIdentifier, existingResource.Id), -// }, -// } -// -// 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, -// } -// createdResource, err := resourceSetup.SendCreateResource(newResourcePayload, didKey) -// require.Nil(t, err) -// -// queryResponse, err := resourceSetup.ResourceKeeper.CollectionResources(sdk.WrapSDKContext(resourceSetup.Ctx), msg) -// -// if tc.valid { -// resources := queryResponse.Resources -// expectedResources := map[string]types.Resource { -// existingResource.Id: existingResource, -// createdResource.Id: *createdResource, -// } -// require.Nil(t, err) -// require.Equal(t, len(expectedResources), len(resources)) -// for _, r := range resources { -// CompareResources(t, expectedResources[r.Id], *r) -// } -// } else { -// require.Error(t, err) -// require.Equal(t, tc.errMsg, err.Error()) -// } -// }) -// } -//} +import ( + + // "crypto/sha256" + // "crypto/ed25519" + "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.Resource{&existingResource}, + // }, + // errMsg: "", + // }, + // { + // valid: false, + // name: "Not Valid: Resource is not found", + // msg: &types.QueryGetCollectionResources{ + // 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.QueryGetCollectionResourcesRequest{ + CollectionId: NotFoundDIDIdentifier, + }, + response: nil, + errMsg: fmt.Sprintf("resource %s:%s: not found", NotFoundDIDIdentifier, existingResource.Id), + }, + } + + 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, + // } + // createdResource, err := resourceSetup.SendCreateResource(newResourcePayload, didKey) + // require.Nil(t, err) + + queryResponse, err := resourceSetup.QueryServer.CollectionResources(sdk.WrapSDKContext(resourceSetup.Ctx), msg) + + if tc.valid { + resources := queryResponse.Resources + expectedResources := tc.response.Resources + // expectedResources := map[string]types.Resource { + // existingResource.Id: existingResource, + // createdResource.Id: *createdResource, + // } + require.Nil(t, err) + require.Equal(t, len(expectedResources), len(resources)) + for i, r := range resources { + CompareResources(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 index 4673fdba3..fd1e27f11 100644 --- a/x/resource/tests/query_resource_test.go +++ b/x/resource/tests/query_resource_test.go @@ -61,7 +61,7 @@ func TestQueryGetResource(t *testing.T) { msg := tc.msg resourceSetup := InitEnv(t, keys[ExistingDIDKey].PublicKey, keys[ExistingDIDKey].PrivateKey) - queryResponse, err := resourceSetup.ResourceKeeper.Resource(sdk.WrapSDKContext(resourceSetup.Ctx), msg) + queryResponse, err := resourceSetup.QueryServer.Resource(sdk.WrapSDKContext(resourceSetup.Ctx), msg) if tc.valid { resource := queryResponse.Resource diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go index ff2770164..d1af42a19 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -35,6 +35,7 @@ type TestSetup struct { ResourceKeeper keeper.Keeper ResourceHandler sdk.Handler + QueryServer types.QueryServer } func Setup() TestSetup { @@ -60,6 +61,7 @@ func Setup() TestSetup { // Init Keepers cheqdKeeper := cheqdkeeper.NewKeeper(cdc, cheqdStoreKey) resourceKeeper := keeper.NewKeeper(cdc, resourceStoreKey) + queryServer := keeper.NewQueryServer(*resourceKeeper) // Create Tx txBytes := make([]byte, 28) @@ -83,6 +85,7 @@ func Setup() TestSetup { }, ResourceKeeper: *resourceKeeper, ResourceHandler: resourceHandler, + QueryServer: queryServer, } setup.Keeper.SetDidNamespace(ctx, "test") diff --git a/x/resource/tests/utils.go b/x/resource/tests/utils.go index 515251853..9065e7292 100644 --- a/x/resource/tests/utils.go +++ b/x/resource/tests/utils.go @@ -7,14 +7,14 @@ import ( "github.com/stretchr/testify/require" ) -func CompareResources(t require.TestingT, expectedResource types.Resource, resource types.Resource) { +func CompareResources(t require.TestingT, expectedResource *types.Resource, resource types.Resource) { require.Equal(t, expectedResource.CollectionId, resource.CollectionId) require.Equal(t, expectedResource.Id, resource.Id) require.Equal(t, expectedResource.MimeType, resource.MimeType) require.Equal(t, expectedResource.ResourceType, resource.ResourceType) require.Equal(t, expectedResource.Data, resource.Data) - require.Equal(t, expectedResource, resource.Name) - require.Equal(t, string(sha256.New().Sum(expectedResource.Data)), resource.Checksum) + require.Equal(t, expectedResource.Name, resource.Name) + require.Equal(t, sha256.New().Sum(expectedResource.Data), resource.Checksum) require.Equal(t, expectedResource.PreviousVersionId, resource.PreviousVersionId) require.Equal(t, expectedResource.NextVersionId, resource.NextVersionId) } From 47e8866a82cefa6f75071484d81316c3f1706f45 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 11:55:50 +0300 Subject: [PATCH 33/65] Add check for did doc existing in queries --- app/app.go | 2 +- app/migration_v_0_5.go | 6 +++--- x/cheqd/genesis.go | 4 ++-- x/cheqd/keeper/keeper_config.go | 18 +++++++++--------- x/cheqd/keeper/msg_server_create_did.go | 2 +- x/cheqd/keeper/msg_server_update_did.go | 2 +- x/cheqd/tests/setup.go | 2 +- x/resource/keeper/keeper_resource.go | 2 +- .../keeper/msg_server_create_resource.go | 2 +- x/resource/keeper/query.go | 7 ++++--- .../keeper/query_all_resource_versions.go | 5 +++-- x/resource/keeper/query_resource.go | 5 +++-- x/resource/keeper/query_server.go | 9 +++++++-- .../query_server_all_resource_versions.go | 10 ++++++++++ .../query_server_collection_resources.go | 10 ++++++++++ x/resource/keeper/query_server_resource.go | 9 +++++++++ x/resource/module.go | 4 ++-- .../tests/query_collection_resources_test.go | 4 ++-- x/resource/tests/setup.go | 4 ++-- x/resource/types/error.go | 1 - 20 files changed, 72 insertions(+), 36 deletions(-) diff --git a/app/app.go b/app/app.go index c850233ad..ad862a72e 100644 --- a/app/app.go +++ b/app/app.go @@ -587,7 +587,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/x/cheqd/genesis.go b/x/cheqd/genesis.go index c437858fb..e21e2269c 100644 --- a/x/cheqd/genesis.go +++ b/x/cheqd/genesis.go @@ -19,7 +19,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. @@ -34,7 +34,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/msg_server_create_did.go b/x/cheqd/keeper/msg_server_create_did.go index 588d07782..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()) diff --git a/x/cheqd/keeper/msg_server_update_did.go b/x/cheqd/keeper/msg_server_update_did.go index 691899f44..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()) 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/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index c9af1c40d..244e377aa 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -118,7 +118,7 @@ func (k Keeper) GetResourceCollection(ctx *sdk.Context, collectionId string) []* store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) iterator := sdk.KVStorePrefixIterator(store, GetResourceCollectionPrefixBytes(collectionId)) - resources := []*types.Resource{} + var resources []*types.Resource defer func(iterator sdk.Iterator) { err := iterator.Close() diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 150c21b10..86388d0b6 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -16,7 +16,7 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes ctx := sdk.UnwrapSDKContext(goCtx) // Validate corresponding DIDDoc exists - namespace := k.cheqdKeeper.GetDidNamespace(ctx) + namespace := k.cheqdKeeper.GetDidNamespace(&ctx) did := cheqdutils.JoinDID(cheqdtypes.DidMethod, namespace, msg.Payload.CollectionId) didDocStateValue, err := k.cheqdKeeper.GetDid(&ctx, did) if err != nil { diff --git a/x/resource/keeper/query.go b/x/resource/keeper/query.go index bebc7fd6d..d3cbfdb82 100644 --- a/x/resource/keeper/query.go +++ b/x/resource/keeper/query.go @@ -1,6 +1,7 @@ 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" @@ -9,7 +10,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) -func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { +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 @@ -18,11 +19,11 @@ func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { switch path[0] { case types.QueryGetResource: - return resource(ctx, k, legacyQuerierCdc, path[1], path[2]) + return resource(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2]) //case types.QueryGetCollectionResources: // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) case types.QueryGetAllResourceVersions: - return allResourceVersions(ctx, k, legacyQuerierCdc, path[1], path[2], path[3], path[4]) + return allResourceVersions(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2], path[3], path[4]) default: err = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) diff --git a/x/resource/keeper/query_all_resource_versions.go b/x/resource/keeper/query_all_resource_versions.go index e5d9b7137..b7860f918 100644 --- a/x/resource/keeper/query_all_resource_versions.go +++ b/x/resource/keeper/query_all_resource_versions.go @@ -1,14 +1,15 @@ 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, legacyQuerierCdc *codec.LegacyAmino, collectionId, name, resourceType, mimeType string) ([]byte, error) { - queryServer := NewQueryServer(keeper) +func allResourceVersions(ctx sdk.Context, keeper Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *codec.LegacyAmino, collectionId, name, resourceType, mimeType string) ([]byte, error) { + queryServer := NewQueryServer(keeper, cheqdKeeper) resp, err := queryServer.AllResourceVersions(sdk.WrapSDKContext(ctx), &types.QueryGetAllResourceVersionsRequest{ CollectionId: collectionId, diff --git a/x/resource/keeper/query_resource.go b/x/resource/keeper/query_resource.go index bcaa4888f..1d881d984 100644 --- a/x/resource/keeper/query_resource.go +++ b/x/resource/keeper/query_resource.go @@ -1,14 +1,15 @@ 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, legacyQuerierCdc *codec.LegacyAmino, collectionId, id string) ([]byte, error) { - queryServer := NewQueryServer(keeper) +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 { diff --git a/x/resource/keeper/query_server.go b/x/resource/keeper/query_server.go index 5d474dab2..4c31162fc 100644 --- a/x/resource/keeper/query_server.go +++ b/x/resource/keeper/query_server.go @@ -1,16 +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) types.QueryServer { - return &queryServer{Keeper: 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 index b234be3a3..5c29432ca 100644 --- a/x/resource/keeper/query_server_all_resource_versions.go +++ b/x/resource/keeper/query_server_all_resource_versions.go @@ -2,6 +2,8 @@ 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" @@ -15,6 +17,14 @@ func (m queryServer) AllResourceVersions(c context.Context, req *types.QueryGetA 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, req.ResourceType, req.MimeType) return &types.QueryGetAllResourceVersionsResponse{ diff --git a/x/resource/keeper/query_server_collection_resources.go b/x/resource/keeper/query_server_collection_resources.go index 38c6ec80a..832eaceb2 100644 --- a/x/resource/keeper/query_server_collection_resources.go +++ b/x/resource/keeper/query_server_collection_resources.go @@ -2,6 +2,8 @@ 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" @@ -15,6 +17,14 @@ func (m queryServer) CollectionResources(c context.Context, request *types.Query 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{ diff --git a/x/resource/keeper/query_server_resource.go b/x/resource/keeper/query_server_resource.go index 86b1012eb..c6cee3bf3 100644 --- a/x/resource/keeper/query_server_resource.go +++ b/x/resource/keeper/query_server_resource.go @@ -2,6 +2,8 @@ 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" @@ -16,6 +18,13 @@ func (q queryServer) Resource(c context.Context, req *types.QueryGetResourceRequ 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 diff --git a/x/resource/module.go b/x/resource/module.go index ab84dc427..340a41dd9 100644 --- a/x/resource/module.go +++ b/x/resource/module.go @@ -140,13 +140,13 @@ 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, legacyQuerierCdc) + 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)) + types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServer(am.keeper, am.cheqdKeeper)) } // RegisterInvariants registers the resource module's invariants. diff --git a/x/resource/tests/query_collection_resources_test.go b/x/resource/tests/query_collection_resources_test.go index 7f88393e8..14172ffc5 100644 --- a/x/resource/tests/query_collection_resources_test.go +++ b/x/resource/tests/query_collection_resources_test.go @@ -14,7 +14,7 @@ import ( func TestQueryGetCollectionResources(t *testing.T) { keys := GenerateTestKeys() - existingResource := ExistingResource() + //existingResource := ExistingResource() cases := []struct { valid bool name string @@ -50,7 +50,7 @@ func TestQueryGetCollectionResources(t *testing.T) { CollectionId: NotFoundDIDIdentifier, }, response: nil, - errMsg: fmt.Sprintf("resource %s:%s: not found", NotFoundDIDIdentifier, existingResource.Id), + errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), }, } diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go index d1af42a19..6497ec453 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -61,7 +61,7 @@ func Setup() TestSetup { // Init Keepers cheqdKeeper := cheqdkeeper.NewKeeper(cdc, cheqdStoreKey) resourceKeeper := keeper.NewKeeper(cdc, resourceStoreKey) - queryServer := keeper.NewQueryServer(*resourceKeeper) + queryServer := keeper.NewQueryServer(*resourceKeeper, *cheqdKeeper) // Create Tx txBytes := make([]byte, 28) @@ -88,7 +88,7 @@ func Setup() TestSetup { QueryServer: queryServer, } - setup.Keeper.SetDidNamespace(ctx, "test") + setup.Keeper.SetDidNamespace(&ctx, "test") return setup } diff --git a/x/resource/types/error.go b/x/resource/types/error.go index 8901fd77f..0d13e8376 100644 --- a/x/resource/types/error.go +++ b/x/resource/types/error.go @@ -13,7 +13,6 @@ var ( ErrInvalidSignature = sdkerrors.Register(ModuleName, 2100, "invalid signature detected") ErrSignatureNotFound = sdkerrors.Register(ModuleName, 2101, "signature is required but not found") ErrResourceExists = sdkerrors.Register(ModuleName, 2200, "Resoure exists") - ErrDidDocNotFound = sdkerrors.Register(ModuleName, 2201, "DID Doc not found") ErrVerificationMethodNotFound = sdkerrors.Register(ModuleName, 2202, "verification method not found") ErrUnexpectedDidVersion = sdkerrors.Register(ModuleName, 2203, "unexpected DID version") ErrBasicValidation = sdkerrors.Register(ModuleName, 2205, "basic validation failed") From 8107b42f7fe2b1318ea474db9be24d793c3e1efa Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 12:25:26 +0300 Subject: [PATCH 34/65] Finidsh bash tests for collerction_resources, resource_versions --- .../tests/test_query_all_resource_versions.sh | 149 ++++++++++++++++++ ....sh => test_query_collection_resources.sh} | 54 ++++++- x/resource/client/cli/query.go | 3 +- .../client/cli/query_all_resource_versions.go | 2 +- .../client/cli/query_collection_resources.go | 39 +++++ 5 files changed, 244 insertions(+), 3 deletions(-) create mode 100644 tests/e2e-bash/tests/test_query_all_resource_versions.sh rename tests/e2e-bash/tests/{test_create_resource.sh => test_query_collection_resources.sh} (72%) create mode 100644 x/resource/client/cli/query_collection_resources.go 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..5cfefce71 --- /dev/null +++ b/tests/e2e-bash/tests/test_query_all_resource_versions.sh @@ -0,0 +1,149 @@ +#!/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_MIME_TYPE="application/json" +RESOURCE1_RESOURCE_TYPE="CL-Schema" +RESOURCE1_V1_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; + +MSG_CREATE_RESOURCE1='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V1_ID}'", + "name": "'${RESOURCE1_NAME}'", + "mime_type": "'${RESOURCE1_MIME_TYPE}'", + "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", + "data": "'${RESOURCE1_V1_DATA}'" +}'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE1}" "${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='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V1_ID}'", + "name": "'${RESOURCE1_NAME}'", + "mime_type": "'${RESOURCE1_MIME_TYPE}'", + "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", + "data": "'${RESOURCE1_V1_DATA}'" +}' + +DEL_FILTER='del(.checksum, .created, .next_version_id, .previous_version_id)' +assert_json_eq "$(echo "$RESULT" | jq -r ".resource | ${DEL_FILTER}")" "${EXPECTED_RES1_V1}" + + +########## Creating Resource 1 v2 ########## + +RESOURCE1_V2_ID=$(uuidgen) +RESOURCE1_V2_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhLg=='; + +MSG_CREATE_RESOURCE1_V2='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V2_ID}'", + "name": "'${RESOURCE1_NAME}'", + "mime_type": "'${RESOURCE1_MIME_TYPE}'", + "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", + "data": "'${RESOURCE1_V2_DATA}'" +}'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE1_V2}" "${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='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhdGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; +RESOURCE2_NAME="Resource 2" +RESOURCE2_MIME_TYPE="application/json" +RESOURCE2_RESOURCE_TYPE="CL-Schema" + +MSG_CREATE_RESOURCE2='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE2_ID}'", + "name": "'${RESOURCE2_NAME}'", + "mime_type": "'${RESOURCE2_MIME_TYPE}'", + "resource_type": "'${RESOURCE2_RESOURCE_TYPE}'", + "data": "'${RESOURCE2_DATA}'" +}'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE2}" "${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='{ + "collection_id": "'${ID1}'", + "id": "'${RESOURCE1_V2_ID}'", + "name": "'${RESOURCE1_NAME}'", + "mime_type": "'${RESOURCE1_MIME_TYPE}'", + "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", + "data": "'${RESOURCE1_V2_DATA}'" +}' + +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded query resource all-resource-versions "${ID1}" "${RESOURCE1_NAME}" ${RESOURCE1_RESOURCE_TYPE} ${RESOURCE1_MIME_TYPE} ${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}" +assert_json_eq "$(echo "$RESULT" | jq -r '.resources[] | select(.id == "'"${RESOURCE1_V2_ID}"'") | '"${DEL_FILTER}"'')" "${EXPECTED_RES1_V2}" diff --git a/tests/e2e-bash/tests/test_create_resource.sh b/tests/e2e-bash/tests/test_query_collection_resources.sh similarity index 72% rename from tests/e2e-bash/tests/test_create_resource.sh rename to tests/e2e-bash/tests/test_query_collection_resources.sh index 08380082e..362af474b 100644 --- a/tests/e2e-bash/tests/test_create_resource.sh +++ b/tests/e2e-bash/tests/test_query_collection_resources.sh @@ -105,6 +105,58 @@ RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE1_V2}" "$ 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='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhdGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; +RESOURCE2_NAME="Resource 2" +RESOURCE2_MIME_TYPE="application/json" +RESOURCE2_RESOURCE_TYPE="CL-Schema" + +MSG_CREATE_RESOURCE2='{ + "collection_id": "'${ID2}'", + "id": "'${RESOURCE2_ID}'", + "name": "'${RESOURCE2_NAME}'", + "mime_type": "'${RESOURCE2_MIME_TYPE}'", + "resource_type": "'${RESOURCE2_RESOURCE_TYPE}'", + "data": "'${RESOURCE2_DATA}'" +}'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE2}" "${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='{ @@ -117,7 +169,7 @@ EXPECTED_RES1_V2='{ }' # shellcheck disable=SC2086 -RESULT=$(cheqd-noded query resource all-resource-versions "${ID1}" "${RESOURCE1_V1_NAME}" ${RESOURCE1_V1_RESOURCE_TYPE} ${RESOURCE1_V1_MIME_TYPE} ${QUERY_PARAMS}) +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}" diff --git a/x/resource/client/cli/query.go b/x/resource/client/cli/query.go index 3ea176235..16ee30e90 100644 --- a/x/resource/client/cli/query.go +++ b/x/resource/client/cli/query.go @@ -20,7 +20,8 @@ func GetQueryCmd() *cobra.Command { } cmd.AddCommand(CmdGetResource(), - CmdGetAllResourceVersions()) + 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 index 814ae6156..3494e2136 100644 --- a/x/resource/client/cli/query_all_resource_versions.go +++ b/x/resource/client/cli/query_all_resource_versions.go @@ -11,7 +11,7 @@ import ( func CmdGetAllResourceVersions() *cobra.Command { cmd := &cobra.Command{ Use: "all-resource-versions [collectionId] [name] [resourceType] [mimeType]", - Short: "Query a resource", + Short: "Query all resource versions", Args: cobra.ExactArgs(4), RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(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..425518415 --- /dev/null +++ b/x/resource/client/cli/query_collection_resources.go @@ -0,0 +1,39 @@ +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 +} From a7b12bdd5c88a4ed3330e83f3dbf965412bd0166 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 12:26:57 +0300 Subject: [PATCH 35/65] Fix unit tests --- x/resource/tests/query_resource_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/resource/tests/query_resource_test.go b/x/resource/tests/query_resource_test.go index fd1e27f11..e027f1ac0 100644 --- a/x/resource/tests/query_resource_test.go +++ b/x/resource/tests/query_resource_test.go @@ -52,7 +52,7 @@ func TestQueryGetResource(t *testing.T) { Id: existingResource.Id, }, response: nil, - errMsg: fmt.Sprintf("resource %s:%s: not found", NotFoundDIDIdentifier, existingResource.Id), + errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), }, } From bd0c640fd650fdc6532c5d63f75afa78d9abf346 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 13:05:31 +0300 Subject: [PATCH 36/65] Fix formatting --- app/app.go | 5 +++-- x/cheqd/genesis.go | 1 + x/cheqd/types/validate.go | 3 ++- x/resource/client/cli/query_all_resource_versions.go | 1 + x/resource/client/cli/query_collection_resources.go | 1 + x/resource/client/cli/query_resource.go | 1 + x/resource/genesis.go | 3 +-- x/resource/handler.go | 1 + x/resource/keeper/msg_server.go | 2 +- x/resource/keeper/query.go | 2 +- x/resource/keeper/query_server.go | 2 +- x/resource/keeper/query_server_all_resource_versions.go | 1 + x/resource/keeper/query_server_collection_resources.go | 1 + x/resource/keeper/query_server_resource.go | 1 + x/resource/module.go | 5 +++-- x/resource/tests/create_resource_test.go | 5 +++-- x/resource/tests/query_collection_resources_test.go | 2 +- x/resource/tests/setup.go | 2 +- x/resource/utils/mime_type_test.go | 5 +++-- x/resource/utils/resource_type_test.go | 5 +++-- x/resource/utils/uuid.go | 3 ++- x/resource/utils/uuid_test.go | 3 ++- 22 files changed, 35 insertions(+), 20 deletions(-) diff --git a/app/app.go b/app/app.go index ad862a72e..f8716ffd6 100644 --- a/app/app.go +++ b/app/app.go @@ -1,12 +1,13 @@ package app import ( - "github.com/cheqd/cheqd-node/x/resource" "io" "net/http" "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" @@ -218,7 +219,7 @@ type App struct { ScopedIBCKeeper capabilitykeeper.ScopedKeeper ScopedTransferKeeper capabilitykeeper.ScopedKeeper - cheqdKeeper cheqdkeeper.Keeper + cheqdKeeper cheqdkeeper.Keeper resourceKeeper resourcekeeper.Keeper // the module manager diff --git a/x/cheqd/genesis.go b/x/cheqd/genesis.go index e21e2269c..50024476a 100644 --- a/x/cheqd/genesis.go +++ b/x/cheqd/genesis.go @@ -2,6 +2,7 @@ package cheqd import ( "fmt" + "github.com/cheqd/cheqd-node/x/cheqd/keeper" "github.com/cheqd/cheqd-node/x/cheqd/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/cheqd/types/validate.go b/x/cheqd/types/validate.go index b3c699a84..5f6e13097 100644 --- a/x/cheqd/types/validate.go +++ b/x/cheqd/types/validate.go @@ -3,9 +3,10 @@ package types import ( "errors" "fmt" - validation "github.com/go-ozzo/ozzo-validation/v4" "strings" + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/cheqd/cheqd-node/x/cheqd/utils" "github.com/multiformats/go-multibase" ) diff --git a/x/resource/client/cli/query_all_resource_versions.go b/x/resource/client/cli/query_all_resource_versions.go index 3494e2136..5765bf019 100644 --- a/x/resource/client/cli/query_all_resource_versions.go +++ b/x/resource/client/cli/query_all_resource_versions.go @@ -2,6 +2,7 @@ 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" diff --git a/x/resource/client/cli/query_collection_resources.go b/x/resource/client/cli/query_collection_resources.go index 425518415..e10c098c8 100644 --- a/x/resource/client/cli/query_collection_resources.go +++ b/x/resource/client/cli/query_collection_resources.go @@ -2,6 +2,7 @@ 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" diff --git a/x/resource/client/cli/query_resource.go b/x/resource/client/cli/query_resource.go index b36bee753..01536df7a 100644 --- a/x/resource/client/cli/query_resource.go +++ b/x/resource/client/cli/query_resource.go @@ -2,6 +2,7 @@ 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" diff --git a/x/resource/genesis.go b/x/resource/genesis.go index b2f1a216b..0393af2d2 100644 --- a/x/resource/genesis.go +++ b/x/resource/genesis.go @@ -12,7 +12,6 @@ import ( // 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())) } @@ -21,7 +20,7 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) // Set nym count k.SetResourceCount(&ctx, uint64(len(genState.ResourceList))) - //k.SetResourceNamespace(ctx, genState.ResourceNamespace) + // k.SetResourceNamespace(ctx, genState.ResourceNamespace) } // ExportGenesis returns the cheqd module's exported genesis. diff --git a/x/resource/handler.go b/x/resource/handler.go index 5526de917..d3d6aa181 100644 --- a/x/resource/handler.go +++ b/x/resource/handler.go @@ -2,6 +2,7 @@ package resource import ( "fmt" + cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" "github.com/cheqd/cheqd-node/x/resource/keeper" diff --git a/x/resource/keeper/msg_server.go b/x/resource/keeper/msg_server.go index a86b4bd49..7a95e5cf7 100644 --- a/x/resource/keeper/msg_server.go +++ b/x/resource/keeper/msg_server.go @@ -13,7 +13,7 @@ type msgServer struct { // 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, + Keeper: keeper, cheqdKeeper: cheqdKeeper, } } diff --git a/x/resource/keeper/query.go b/x/resource/keeper/query.go index d3cbfdb82..1a1054a91 100644 --- a/x/resource/keeper/query.go +++ b/x/resource/keeper/query.go @@ -20,7 +20,7 @@ func NewQuerier(k Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *code switch path[0] { case types.QueryGetResource: return resource(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2]) - //case types.QueryGetCollectionResources: + // case types.QueryGetCollectionResources: // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) case types.QueryGetAllResourceVersions: return allResourceVersions(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2], path[3], path[4]) diff --git a/x/resource/keeper/query_server.go b/x/resource/keeper/query_server.go index 4c31162fc..a701ec50e 100644 --- a/x/resource/keeper/query_server.go +++ b/x/resource/keeper/query_server.go @@ -13,7 +13,7 @@ type queryServer struct { // 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, + Keeper: keeper, cheqdKeeper: cheqdKeeper, } } diff --git a/x/resource/keeper/query_server_all_resource_versions.go b/x/resource/keeper/query_server_all_resource_versions.go index 5c29432ca..d3db32847 100644 --- a/x/resource/keeper/query_server_all_resource_versions.go +++ b/x/resource/keeper/query_server_all_resource_versions.go @@ -2,6 +2,7 @@ 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" diff --git a/x/resource/keeper/query_server_collection_resources.go b/x/resource/keeper/query_server_collection_resources.go index 832eaceb2..59eb9d7fe 100644 --- a/x/resource/keeper/query_server_collection_resources.go +++ b/x/resource/keeper/query_server_collection_resources.go @@ -2,6 +2,7 @@ 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" diff --git a/x/resource/keeper/query_server_resource.go b/x/resource/keeper/query_server_resource.go index c6cee3bf3..03125168a 100644 --- a/x/resource/keeper/query_server_resource.go +++ b/x/resource/keeper/query_server_resource.go @@ -2,6 +2,7 @@ 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" diff --git a/x/resource/module.go b/x/resource/module.go index 340a41dd9..fdf653642 100644 --- a/x/resource/module.go +++ b/x/resource/module.go @@ -4,9 +4,10 @@ import ( "context" "encoding/json" "fmt" - cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" "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" @@ -105,7 +106,7 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { type AppModule struct { AppModuleBasic - keeper keeper.Keeper + keeper keeper.Keeper cheqdKeeper cheqdkeeper.Keeper } diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index 02a86b571..e1809c69b 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -3,11 +3,12 @@ package tests import ( "crypto/ed25519" "crypto/sha256" + "fmt" + "testing" + "github.com/cheqd/cheqd-node/x/cheqd/utils" // "crypto/sha256" - "fmt" - "testing" "github.com/cheqd/cheqd-node/x/resource/types" diff --git a/x/resource/tests/query_collection_resources_test.go b/x/resource/tests/query_collection_resources_test.go index 14172ffc5..a00997489 100644 --- a/x/resource/tests/query_collection_resources_test.go +++ b/x/resource/tests/query_collection_resources_test.go @@ -14,7 +14,7 @@ import ( func TestQueryGetCollectionResources(t *testing.T) { keys := GenerateTestKeys() - //existingResource := ExistingResource() + // existingResource := ExistingResource() cases := []struct { valid bool name string diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go index 6497ec453..09ccecdf7 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -85,7 +85,7 @@ func Setup() TestSetup { }, ResourceKeeper: *resourceKeeper, ResourceHandler: resourceHandler, - QueryServer: queryServer, + QueryServer: queryServer, } setup.Keeper.SetDidNamespace(&ctx, "test") diff --git a/x/resource/utils/mime_type_test.go b/x/resource/utils/mime_type_test.go index 4c4114ff8..db2b213ac 100644 --- a/x/resource/utils/mime_type_test.go +++ b/x/resource/utils/mime_type_test.go @@ -1,13 +1,14 @@ package utils import ( - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" ) func TestValidateMimeType(t *testing.T) { cases := []struct { - mt string + mt string valid bool }{ {"application/json", true}, diff --git a/x/resource/utils/resource_type_test.go b/x/resource/utils/resource_type_test.go index 780144368..3bbb966c3 100644 --- a/x/resource/utils/resource_type_test.go +++ b/x/resource/utils/resource_type_test.go @@ -1,13 +1,14 @@ package utils import ( - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" ) func TestValidateResourceType(t *testing.T) { cases := []struct { - rt string + rt string valid bool }{ {"CL-Schema", true}, diff --git a/x/resource/utils/uuid.go b/x/resource/utils/uuid.go index d6c19ebb4..7620bc84d 100644 --- a/x/resource/utils/uuid.go +++ b/x/resource/utils/uuid.go @@ -2,8 +2,9 @@ package utils import ( "errors" - "github.com/google/uuid" "strconv" + + "github.com/google/uuid" ) const StandardUuidLength = 36 diff --git a/x/resource/utils/uuid_test.go b/x/resource/utils/uuid_test.go index 38fde6de6..0b7ff983f 100644 --- a/x/resource/utils/uuid_test.go +++ b/x/resource/utils/uuid_test.go @@ -1,8 +1,9 @@ package utils import ( - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" ) func TestValidateUUID(t *testing.T) { From 31d7f0929d4fe947c5d0d562610dfd6ba65f7ae2 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 13:15:35 +0300 Subject: [PATCH 37/65] Fix formatting --- x/cheqd/keeper/msg_server.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x/cheqd/keeper/msg_server.go b/x/cheqd/keeper/msg_server.go index 336310b30..dfef0033f 100644 --- a/x/cheqd/keeper/msg_server.go +++ b/x/cheqd/keeper/msg_server.go @@ -128,7 +128,8 @@ func VerifyAllSignersHaveAllValidSignatures(k *Keeper, ctx *sdk.Context, inMemor // 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 func VerifyAllSignersHaveAtLeastOneValidSignature(k *Keeper, ctx *sdk.Context, inMemoryDIDs map[string]types.StateValue, - message []byte, signers []string, signatures []*types.SignInfo, DIDToBeUpdated string, updatedDID string) error { + 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) From 47b5e0637fa7654ecbc832ea2c34468fb58e0e38 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 13:34:41 +0300 Subject: [PATCH 38/65] Cleaning up code --- x/cheqd/keeper/msg_server.go | 2 +- x/cheqd/module.go | 32 ++++++++++++++++---------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/x/cheqd/keeper/msg_server.go b/x/cheqd/keeper/msg_server.go index dfef0033f..ee41b5468 100644 --- a/x/cheqd/keeper/msg_server.go +++ b/x/cheqd/keeper/msg_server.go @@ -126,7 +126,7 @@ func VerifyAllSignersHaveAllValidSignatures(k *Keeper, ctx *sdk.Context, inMemor } // 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 +// 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 { diff --git a/x/cheqd/module.go b/x/cheqd/module.go index 022fe3b96..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() } @@ -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{} From e14c024864cb0f8075aef5f955641efdafb4c9b7 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 13:58:52 +0300 Subject: [PATCH 39/65] Fix python tests --- tests/e2e-pytest/test_identity.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e-pytest/test_identity.py b/tests/e2e-pytest/test_identity.py index cddbd458e..aba8978aa 100644 --- a/tests/e2e-pytest/test_identity.py +++ b/tests/e2e-pytest/test_identity.py @@ -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") From dff42869eb8ea075a634480e48cb6858fb171dd3 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:00:56 +0300 Subject: [PATCH 40/65] Regenerate protobufs --- x/cheqd/types/query.pb.gw.go | 2 +- x/resource/types/query.pb.gw.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/x/cheqd/types/query.pb.gw.go b/x/cheqd/types/query.pb.gw.go index bb740e001..7a537fc1b 100644 --- a/x/cheqd/types/query.pb.gw.go +++ b/x/cheqd/types/query.pb.gw.go @@ -181,7 +181,7 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } var ( - pattern_Query_Did_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"cheqd", "v1", "did", "id"}, "", runtime.AssumeColonVerbOpt(true))) + pattern_Query_Did_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"cheqd", "v1", "did", "id"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( diff --git a/x/resource/types/query.pb.gw.go b/x/resource/types/query.pb.gw.go index 63883e35f..274eb0b51 100644 --- a/x/resource/types/query.pb.gw.go +++ b/x/resource/types/query.pb.gw.go @@ -415,11 +415,11 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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(true))) + 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}, []string{"1.0", "identifiers", "collection_id", "resources"}, "", runtime.AssumeColonVerbOpt(true))) + pattern_Query_CollectionResources_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"1.0", "identifiers", "collection_id", "resources"}, "", 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}, []string{"1.0", "identifiers", "collection_id", "resources", "versions"}, "", runtime.AssumeColonVerbOpt(true))) + pattern_Query_AllResourceVersions_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", "versions"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( From 6f053c697f4152d3e05dafdd1cf87814501940d2 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:06:22 +0300 Subject: [PATCH 41/65] Fix genesis export/import --- x/resource/genesis.go | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/x/resource/genesis.go b/x/resource/genesis.go index 0393af2d2..0dae2bd4e 100644 --- a/x/resource/genesis.go +++ b/x/resource/genesis.go @@ -8,7 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// InitGenesis initializes the cheqd module's state from a provided genesis +// 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 { @@ -16,26 +16,18 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) panic(fmt.Sprintf("Cannot set resource case: %s", err.Error())) } } - - // Set nym count - k.SetResourceCount(&ctx, uint64(len(genState.ResourceList))) - - // k.SetResourceNamespace(ctx, genState.ResourceNamespace) } // ExportGenesis returns the cheqd module's exported genesis. func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { - genesis := types.DefaultGenesis() + genesis := types.GenesisState{} - // this line is used by starport scaffolding # genesis/module/export - // Get all resource - //resourceList := k.GetAllResource(&ctx) - //for _, elem := range resourceList { - // elem := elem - // genesis.ResourceList = append(genesis.ResourceList, &elem) - //} - // - //genesis.ResourceNamespace = k.GetResourceNamespace(ctx) + //Get all resource + resourceList := k.GetAllResources(&ctx) + for _, elem := range resourceList { + elem := elem + genesis.ResourceList = append(genesis.ResourceList, &elem) + } - return genesis + return &genesis } From be9d38663147ce1c7dbe4aa999452c9dcd9d3f19 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:09:12 +0300 Subject: [PATCH 42/65] Fix formatiing --- x/resource/genesis.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/resource/genesis.go b/x/resource/genesis.go index 0dae2bd4e..5ea0ed74f 100644 --- a/x/resource/genesis.go +++ b/x/resource/genesis.go @@ -22,7 +22,7 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { genesis := types.GenesisState{} - //Get all resource + // Get all resource resourceList := k.GetAllResources(&ctx) for _, elem := range resourceList { elem := elem From 7bd05677db329e85b64b3ec49b9f797dbf86e7e2 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:15:30 +0300 Subject: [PATCH 43/65] Fix legacy query routing --- go.mod | 3 - go.sum | 5 -- x/resource/keeper/query.go | 4 +- .../keeper/query_collection_resource.go | 58 ++++++++----------- 4 files changed, 27 insertions(+), 43 deletions(-) diff --git a/go.mod b/go.mod index 11823b275..dc6737ee4 100644 --- a/go.mod +++ b/go.mod @@ -57,7 +57,6 @@ require ( github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect github.com/felixge/httpsnoop v1.0.1 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect - github.com/ghodss/yaml v1.0.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.0 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect @@ -65,7 +64,6 @@ require ( github.com/goccy/go-json v0.9.4 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/gateway v1.1.0 // indirect - github.com/golang/glog v1.0.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 @@ -73,7 +71,6 @@ require ( github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/gtank/merlin v0.1.1 // indirect github.com/gtank/ristretto255 v0.1.2 // indirect diff --git a/go.sum b/go.sum index b276c407b..398ea4bb4 100644 --- a/go.sum +++ b/go.sum @@ -317,7 +317,6 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= -github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -375,8 +374,6 @@ github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2V github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= -github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -496,8 +493,6 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3 h1:BGNSrTRW4rwfhJiFwvwF4XQ0Y72Jj9YEgxVrtovbD5o= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.3/go.mod h1:VHn7KgNsRriXa4mcgtkpR00OXyQY6g67JWMvn+R27A4= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= diff --git a/x/resource/keeper/query.go b/x/resource/keeper/query.go index 1a1054a91..58de3f309 100644 --- a/x/resource/keeper/query.go +++ b/x/resource/keeper/query.go @@ -20,8 +20,8 @@ func NewQuerier(k Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *code switch path[0] { case types.QueryGetResource: return resource(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2]) - // case types.QueryGetCollectionResources: - // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) + case types.QueryGetCollectionResources: + return collectionResources(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1]) case types.QueryGetAllResourceVersions: return allResourceVersions(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2], path[3], path[4]) diff --git a/x/resource/keeper/query_collection_resource.go b/x/resource/keeper/query_collection_resource.go index 479203986..9da01a2d3 100644 --- a/x/resource/keeper/query_collection_resource.go +++ b/x/resource/keeper/query_collection_resource.go @@ -1,35 +1,27 @@ package keeper -//import ( -// "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, 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 k.Res(ctx, path[1], path[2], k, legacyQuerierCdc) -// // case types.QueryGetCollectionResources: -// // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) -// // case types.QueryGetAllResourceVersions: -// // return getAllResourceVersions(ctx, path[1], k, legacyQuerierCdc) -// -// default: -// err = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) -// } -// -// return res, err -// } -//} +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 +} From 202b3ba0a3c69d6a2752191e9ab60aa0302a731d Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:30:56 +0300 Subject: [PATCH 44/65] Remove unused errors --- x/resource/tests/setup.go | 3 --- x/resource/types/error.go | 7 ------- 2 files changed, 10 deletions(-) diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go index 09ccecdf7..fe7d7bd62 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -10,7 +10,6 @@ import ( "github.com/cheqd/cheqd-node/x/cheqd" cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" - // "github.com/btcsuite/btcutil/base58" 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" @@ -18,8 +17,6 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/stretchr/testify/require" - // "github.com/multiformats/go-multibase" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" "github.com/tendermint/tendermint/libs/log" diff --git a/x/resource/types/error.go b/x/resource/types/error.go index 0d13e8376..c292423b8 100644 --- a/x/resource/types/error.go +++ b/x/resource/types/error.go @@ -7,16 +7,9 @@ import ( ) // x/resource module sentinel errors -// TODO: Rework these errors to be used in the module var ( ErrBadRequest = sdkerrors.Register(ModuleName, 2000, "bad request") - ErrInvalidSignature = sdkerrors.Register(ModuleName, 2100, "invalid signature detected") - ErrSignatureNotFound = sdkerrors.Register(ModuleName, 2101, "signature is required but not found") ErrResourceExists = sdkerrors.Register(ModuleName, 2200, "Resoure exists") - ErrVerificationMethodNotFound = sdkerrors.Register(ModuleName, 2202, "verification method not found") - ErrUnexpectedDidVersion = sdkerrors.Register(ModuleName, 2203, "unexpected DID version") ErrBasicValidation = sdkerrors.Register(ModuleName, 2205, "basic validation failed") - ErrNamespaceValidation = sdkerrors.Register(ModuleName, 2206, "DID namespace validation failed") - ErrUnpackStateValue = sdkerrors.Register(ModuleName, 2300, "invalid did state value") ErrInternal = sdkerrors.Register(ModuleName, 2500, "internal error") ) From e339b374f472e320d3d79048c5c94fb5e0105c60 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:31:37 +0300 Subject: [PATCH 45/65] Fix formatting --- x/resource/types/error.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x/resource/types/error.go b/x/resource/types/error.go index c292423b8..f8786359d 100644 --- a/x/resource/types/error.go +++ b/x/resource/types/error.go @@ -8,8 +8,8 @@ import ( // 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") + 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") ) From ea5cfb5faf1d2e6f12247f3d5b020f47b68af81f Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:34:20 +0300 Subject: [PATCH 46/65] Fix genesis validation --- x/resource/types/genesis.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/x/resource/types/genesis.go b/x/resource/types/genesis.go index 4c7234e3d..13d635fe9 100644 --- a/x/resource/types/genesis.go +++ b/x/resource/types/genesis.go @@ -14,13 +14,13 @@ func DefaultGenesis() *GenesisState { // Validate performs basic genesis state validation returning an error upon any // failure. func (gs GenesisState) Validate() error { - // TODO: Are resource ids unique within a collection or globally? resourceIdMap := make(map[string]bool) for _, resource := range gs.ResourceList { + collectionResourceId := resource.CollectionId + ":" + resource.Id - if _, ok := resourceIdMap[resource.Id]; ok { - return fmt.Errorf("duplicated id for resource") + if _, ok := resourceIdMap[collectionResourceId]; ok { + return fmt.Errorf("duplicated id for resource within the same collection: %s", collectionResourceId) } resourceIdMap[resource.Id] = true From aeabc136f12640fe23e0eb1f9c808d13059ff7cd Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:43:08 +0300 Subject: [PATCH 47/65] Remove image from allowed mime types --- x/resource/utils/mime_type.go | 2 +- x/resource/utils/mime_type_test.go | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/x/resource/utils/mime_type.go b/x/resource/utils/mime_type.go index 47e7b23db..e4e36914d 100644 --- a/x/resource/utils/mime_type.go +++ b/x/resource/utils/mime_type.go @@ -7,7 +7,7 @@ import ( cheqdUtils "github.com/cheqd/cheqd-node/x/cheqd/utils" ) -var AllowedMimeTypes = []string{"application/json", "image/png"} +var AllowedMimeTypes = []string{"application/json", "application/octet-stream", "text/plain"} func IsValidMimeType(rt string) bool { return cheqdUtils.Contains(AllowedMimeTypes, rt) diff --git a/x/resource/utils/mime_type_test.go b/x/resource/utils/mime_type_test.go index db2b213ac..86ea7ac67 100644 --- a/x/resource/utils/mime_type_test.go +++ b/x/resource/utils/mime_type_test.go @@ -12,7 +12,6 @@ func TestValidateMimeType(t *testing.T) { valid bool }{ {"application/json", true}, - {"image/png", true}, {"my/mime", false}, {"notMine/type", false}, } From a3b48fcf418653e614c2fc1bee30aaea87857d10 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:53:46 +0300 Subject: [PATCH 48/65] Fix python tests --- tests/e2e-pytest/test_identity.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e-pytest/test_identity.py b/tests/e2e-pytest/test_identity.py index aba8978aa..9a0383e6c 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]) From 3db2b7621d1d2ed9d8bf47dd321a7eedbdeccab9 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 14:57:35 +0300 Subject: [PATCH 49/65] For the previous commit --- tests/e2e-pytest/test_identity.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e-pytest/test_identity.py b/tests/e2e-pytest/test_identity.py index 9a0383e6c..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_1100 + CODE_11, generate_public_multibase, generate_did, CODE_1100 @pytest.mark.parametrize("magic_number_positive", [1.3, 2, 3, 10]) From d61d14cff5b311eaa4305a8711cd8e7ab4ececb2 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 15:46:52 +0300 Subject: [PATCH 50/65] Fix unit tests --- x/resource/types/tx_msg_create_resource_payload_test.go | 4 ++-- x/resource/utils/mime_type.go | 2 +- x/resource/utils/resource_type.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/x/resource/types/tx_msg_create_resource_payload_test.go b/x/resource/types/tx_msg_create_resource_payload_test.go index 187512e11..544931649 100644 --- a/x/resource/types/tx_msg_create_resource_payload_test.go +++ b/x/resource/types/tx_msg_create_resource_payload_test.go @@ -36,7 +36,7 @@ func TestMsgCreateResourcePayloadValidation(t *testing.T) { Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, }, isValid: false, - errorMsg: "resource_type: Not-CL-Schema resource type is not allowed. Only CL-Schema,JSONSchema2020.", + errorMsg: "mime_type: image/png mime type is not allowed. Only application/json, application/octet-stream, text/plain; resource_type: Not-CL-Schema resource type is not allowed. Only CL-Schema, JSONSchema2020.", }, { name: "negative mime type", @@ -49,7 +49,7 @@ func TestMsgCreateResourcePayloadValidation(t *testing.T) { Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, }, isValid: false, - errorMsg: "mime_type: text/data mime type is not allowed. Only application/json,image/png.", + errorMsg: "mime_type: text/data mime type is not allowed. Only application/json, application/octet-stream, text/plain.", }, } diff --git a/x/resource/utils/mime_type.go b/x/resource/utils/mime_type.go index e4e36914d..bbdc5c8d2 100644 --- a/x/resource/utils/mime_type.go +++ b/x/resource/utils/mime_type.go @@ -15,7 +15,7 @@ func IsValidMimeType(rt string) bool { func ValidateMimeType(rt string) error { if !IsValidMimeType(rt) { - return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedMimeTypes, ",")) + return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedMimeTypes, ", ")) } return nil diff --git a/x/resource/utils/resource_type.go b/x/resource/utils/resource_type.go index dfeb24ddc..d774b98a1 100644 --- a/x/resource/utils/resource_type.go +++ b/x/resource/utils/resource_type.go @@ -15,7 +15,7 @@ func IsValidResourceType(rt string) bool { func ValidateResourceType(rt string) error { if !IsValidResourceType(rt) { - return errors.New(rt + " resource type is not allowed. Only " + strings.Join(AllowedResourceTypes, ",")) + return errors.New(rt + " resource type is not allowed. Only " + strings.Join(AllowedResourceTypes, ", ")) } return nil From 2ea7650d493d2336f72661ba7ab84f5f5222b892 Mon Sep 17 00:00:00 2001 From: Andrew Nikitin Date: Tue, 21 Jun 2022 17:42:36 +0300 Subject: [PATCH 51/65] Add tests for allresourceversions --- x/resource/keeper/query.go | 4 +- .../keeper/query_collection_resource.go | 35 ------ .../keeper/query_collection_resources.go | 27 +++++ x/resource/tests/constants.go | 1 + .../tests/query_all_resource_versions_test.go | 104 ++++++++++++++++++ .../tests/query_collection_resources_test.go | 49 ++------- 6 files changed, 146 insertions(+), 74 deletions(-) delete mode 100644 x/resource/keeper/query_collection_resource.go create mode 100644 x/resource/keeper/query_collection_resources.go create mode 100644 x/resource/tests/query_all_resource_versions_test.go diff --git a/x/resource/keeper/query.go b/x/resource/keeper/query.go index 1a1054a91..58de3f309 100644 --- a/x/resource/keeper/query.go +++ b/x/resource/keeper/query.go @@ -20,8 +20,8 @@ func NewQuerier(k Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *code switch path[0] { case types.QueryGetResource: return resource(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2]) - // case types.QueryGetCollectionResources: - // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) + case types.QueryGetCollectionResources: + return collectionResources(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1]) case types.QueryGetAllResourceVersions: return allResourceVersions(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2], path[3], path[4]) diff --git a/x/resource/keeper/query_collection_resource.go b/x/resource/keeper/query_collection_resource.go deleted file mode 100644 index 479203986..000000000 --- a/x/resource/keeper/query_collection_resource.go +++ /dev/null @@ -1,35 +0,0 @@ -package keeper - -//import ( -// "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, 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 k.Res(ctx, path[1], path[2], k, legacyQuerierCdc) -// // case types.QueryGetCollectionResources: -// // return getCollectionResources(ctx, path[1], k, legacyQuerierCdc) -// // case types.QueryGetAllResourceVersions: -// // return getAllResourceVersions(ctx, path[1], k, legacyQuerierCdc) -// -// 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_collection_resources.go b/x/resource/keeper/query_collection_resources.go new file mode 100644 index 000000000..e8c3085bc --- /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 +} \ No newline at end of file diff --git a/x/resource/tests/constants.go b/x/resource/tests/constants.go index 3a7399ac5..58fa1c659 100644 --- a/x/resource/tests/constants.go +++ b/x/resource/tests/constants.go @@ -12,6 +12,7 @@ const ( TestResourceName = "Test Resource Name" JsonResourceType = "application/json" ResourceId = "988b0ab3-6a39-4598-83ec-b84c6cf8da15" + AnotherResourceId = "71583c78-f16f-11ec-9dd4-cba0f34eb177" IncorrectResourceId = "1234" NotFoundDIDIdentifier = "nfdnfdnfdnfdnfdd" 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..0e1efff82 --- /dev/null +++ b/x/resource/tests/query_all_resource_versions_test.go @@ -0,0 +1,104 @@ +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.Name, + ResourceType: existingResource.ResourceType, + MimeType: existingResource.MimeType, + }, + response: &types.QueryGetAllResourceVersionsResponse{ + Resources: []*types.Resource{&existingResource}, + }, + errMsg: "", + }, + { + valid: false, + name: "Not Valid: DID Doc is not found", + msg: &types.QueryGetAllResourceVersionsRequest{ + CollectionId: NotFoundDIDIdentifier, + Name: existingResource.Name, + ResourceType: existingResource.ResourceType, + MimeType: existingResource.MimeType, + }, + 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.NextVersionId = createdResource.Id + expectedResources := map[string]types.Resource { + existingResource.Id: existingResource, + createdResource.Id: *createdResource, + } + require.Nil(t, err) + require.Equal(t, len(expectedResources), len(resources)) + for _, r := range resources { + CompareResources(t, r, expectedResources[r.Id]) + } + } 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 index a00997489..2d469e5a1 100644 --- a/x/resource/tests/query_collection_resources_test.go +++ b/x/resource/tests/query_collection_resources_test.go @@ -1,9 +1,6 @@ package tests import ( - - // "crypto/sha256" - // "crypto/ed25519" "fmt" "testing" @@ -14,7 +11,7 @@ import ( func TestQueryGetCollectionResources(t *testing.T) { keys := GenerateTestKeys() - // existingResource := ExistingResource() + existingResource := ExistingResource() cases := []struct { valid bool name string @@ -22,27 +19,17 @@ func TestQueryGetCollectionResources(t *testing.T) { response *types.QueryGetCollectionResourcesResponse errMsg string }{ - // { - // valid: true, - // name: "Valid: Works", - // msg: &types.QueryGetCollectionResourcesRequest{ - // CollectionId: ExistingDIDIdentifier, - // }, - // response: &types.QueryGetCollectionResourcesResponse{ - // Resources: []*types.Resource{&existingResource}, - // }, - // errMsg: "", - // }, - // { - // valid: false, - // name: "Not Valid: Resource is not found", - // msg: &types.QueryGetCollectionResources{ - // CollectionId: ExistingDIDIdentifier, - // Id: ResourceId, - // }, - // response: nil, - // errMsg: fmt.Sprintf("resource %s:%s: not found", ExistingDIDIdentifier, ResourceId), - // }, + { + valid: true, + name: "Valid: Works", + msg: &types.QueryGetCollectionResourcesRequest{ + CollectionId: ExistingDIDIdentifier, + }, + response: &types.QueryGetCollectionResourcesResponse{ + Resources: []*types.Resource{&existingResource}, + }, + errMsg: "", + }, { valid: false, name: "Not Valid: DID Doc is not found", @@ -59,23 +46,11 @@ func TestQueryGetCollectionResources(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, - // } - // createdResource, err := resourceSetup.SendCreateResource(newResourcePayload, didKey) - // require.Nil(t, err) - queryResponse, err := resourceSetup.QueryServer.CollectionResources(sdk.WrapSDKContext(resourceSetup.Ctx), msg) if tc.valid { resources := queryResponse.Resources expectedResources := tc.response.Resources - // expectedResources := map[string]types.Resource { - // existingResource.Id: existingResource, - // createdResource.Id: *createdResource, - // } require.Nil(t, err) require.Equal(t, len(expectedResources), len(resources)) for i, r := range resources { From 2f20de02064a9f50aed177f1fcdb50e1b829bb16 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Tue, 21 Jun 2022 17:55:44 +0300 Subject: [PATCH 52/65] Fix formatting --- x/resource/keeper/query_collection_resources.go | 2 +- .../tests/query_all_resource_versions_test.go | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/x/resource/keeper/query_collection_resources.go b/x/resource/keeper/query_collection_resources.go index e8c3085bc..9da01a2d3 100644 --- a/x/resource/keeper/query_collection_resources.go +++ b/x/resource/keeper/query_collection_resources.go @@ -24,4 +24,4 @@ func collectionResources(ctx sdk.Context, keeper Keeper, cheqdKeeper cheqdkeeper } return bz, nil -} \ No newline at end of file +} diff --git a/x/resource/tests/query_all_resource_versions_test.go b/x/resource/tests/query_all_resource_versions_test.go index 0e1efff82..df5469788 100644 --- a/x/resource/tests/query_all_resource_versions_test.go +++ b/x/resource/tests/query_all_resource_versions_test.go @@ -11,7 +11,6 @@ import ( "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 @@ -25,7 +24,6 @@ func SendAnotherResourceVersion(t require.TestingT, resourceSetup TestSetup, key return *createdResource } - func TestQueryGetAllResourceVersions(t *testing.T) { keys := GenerateTestKeys() existingResource := ExistingResource() @@ -41,9 +39,9 @@ func TestQueryGetAllResourceVersions(t *testing.T) { name: "Valid: Works", msg: &types.QueryGetAllResourceVersionsRequest{ CollectionId: ExistingDIDIdentifier, - Name: existingResource.Name, + Name: existingResource.Name, ResourceType: existingResource.ResourceType, - MimeType: existingResource.MimeType, + MimeType: existingResource.MimeType, }, response: &types.QueryGetAllResourceVersionsResponse{ Resources: []*types.Resource{&existingResource}, @@ -55,9 +53,9 @@ func TestQueryGetAllResourceVersions(t *testing.T) { name: "Not Valid: DID Doc is not found", msg: &types.QueryGetAllResourceVersionsRequest{ CollectionId: NotFoundDIDIdentifier, - Name: existingResource.Name, + Name: existingResource.Name, ResourceType: existingResource.ResourceType, - MimeType: existingResource.MimeType, + MimeType: existingResource.MimeType, }, response: nil, errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), @@ -86,9 +84,9 @@ func TestQueryGetAllResourceVersions(t *testing.T) { if tc.valid { resources := queryResponse.Resources existingResource.NextVersionId = createdResource.Id - expectedResources := map[string]types.Resource { + expectedResources := map[string]types.Resource{ existingResource.Id: existingResource, - createdResource.Id: *createdResource, + createdResource.Id: *createdResource, } require.Nil(t, err) require.Equal(t, len(expectedResources), len(resources)) From 1164a07e1598189d6ff1ab92401f0c807fc0774e Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Wed, 22 Jun 2022 19:11:38 +0300 Subject: [PATCH 53/65] Add user friendly resource creation command --- tests/e2e-bash/tests/test_create_resource.sh | 69 +++++++++++++++++++ .../tests/test_query_all_resource_versions.sh | 6 +- x/cheqd/client/cli/tx.go | 23 +++++-- x/resource/client/cli/tx.go | 3 +- x/resource/client/cli/tx_create_resource.go | 33 ++++++--- .../client/cli/tx_create_resource_raw.go | 63 +++++++++++++++++ 6 files changed, 181 insertions(+), 16 deletions(-) create mode 100644 tests/e2e-bash/tests/test_create_resource.sh create mode 100644 x/resource/client/cli/tx_create_resource_raw.go 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..0b185b3f4 --- /dev/null +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -0,0 +1,69 @@ +#!/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_MIME_TYPE="application/json" +RESOURCE_RESOURCE_TYPE="CL-Schema" +RESOURCE_DATA='test data'; + +# Post the message +# shellcheck disable=SC2086 +RESULT=$(cheqd-noded tx resource create-resource ${ID} ${RESOURCE_ID} "${RESOURCE_NAME}" ${RESOURCE_RESOURCE_TYPE} ${RESOURCE_MIME_TYPE} <(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.collection_id")" "${ID}" +assert_eq "$(echo "$RESULT" | jq -r ".resource.id")" "${RESOURCE_ID}" +assert_eq "$(echo "$RESULT" | jq -r ".resource.name")" "${RESOURCE_NAME}" +assert_eq "$(echo "$RESULT" | jq -r ".resource.resource_type")" "${RESOURCE_RESOURCE_TYPE}" +assert_eq "$(echo "$RESULT" | jq -r ".resource.mime_type")" "${RESOURCE_MIME_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 index 5cfefce71..9a55c77d7 100644 --- a/tests/e2e-bash/tests/test_query_all_resource_versions.sh +++ b/tests/e2e-bash/tests/test_query_all_resource_versions.sh @@ -60,7 +60,7 @@ MSG_CREATE_RESOURCE1='{ # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE1}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE1}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" @@ -99,7 +99,7 @@ MSG_CREATE_RESOURCE1_V2='{ # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE1_V2}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE1_V2}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" @@ -124,7 +124,7 @@ MSG_CREATE_RESOURCE2='{ # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE2}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE2}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" 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/resource/client/cli/tx.go b/x/resource/client/cli/tx.go index 3cc5eded9..9e2f05689 100644 --- a/x/resource/client/cli/tx.go +++ b/x/resource/client/cli/tx.go @@ -18,7 +18,8 @@ func GetTxCmd() *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdCreateDid()) + cmd.AddCommand(CmdCreateResource(), + CmdCreateResourceRaw()) return cmd } diff --git a/x/resource/client/cli/tx_create_resource.go b/x/resource/client/cli/tx_create_resource.go index 8a337c7ea..d80cb7d07 100644 --- a/x/resource/client/cli/tx_create_resource.go +++ b/x/resource/client/cli/tx_create_resource.go @@ -1,6 +1,8 @@ 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" @@ -9,31 +11,46 @@ import ( "github.com/spf13/cobra" ) -func CmdCreateDid() *cobra.Command { +func CmdCreateResource() *cobra.Command { cmd := &cobra.Command{ - Use: "create-resource [payload-json] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", + Use: "create-resource [collection-id] [id] [name] [resource-type] [mime-type] [file-path] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", Short: "Creates a new Resource.", Long: "Creates a new Resource. " + - "[payload-json] is JSON encoded MsgCreateResourcePayload. " + "[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-1] 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(1), + Args: cobra.MinimumNArgs(6), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } - payloadJson, signInputs, err := cheqdcli.GetPayloadAndSignInputs(clientCtx, args) + collectionId := args[0] + + id := args[1] + name := args[2] + resourceType := args[3] + mimeType := args[4] + + data, err := ioutil.ReadFile(args[5]) if err != nil { return err } - // Unmarshal payload - var payload types.MsgCreateResourcePayload - err = clientCtx.Codec.UnmarshalJSON([]byte(payloadJson), &payload) + // Prepare payload + payload := types.MsgCreateResourcePayload{ + CollectionId: collectionId, + Id: id, + Name: name, + ResourceType: resourceType, + MimeType: mimeType, + Data: data, + } + + // Read signatures + signInputs, err := cheqdcli.GetSignInputs(clientCtx, args[6:]) if err != nil { return err } diff --git a/x/resource/client/cli/tx_create_resource_raw.go b/x/resource/client/cli/tx_create_resource_raw.go new file mode 100644 index 000000000..d78053113 --- /dev/null +++ b/x/resource/client/cli/tx_create_resource_raw.go @@ -0,0 +1,63 @@ +package cli + +import ( + 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" +) + +func CmdCreateResourceRaw() *cobra.Command { + cmd := &cobra.Command{ + Use: "create-resource-raw [payload-json] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", + Short: "Creates a new Resource using raw payload. For testing purposes.", + Long: "Creates a new Resource. " + + "[payload-json] is JSON encoded MsgCreateResourcePayload. " + + "[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-1] 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(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + payloadJson, signInputs, err := cheqdcli.GetPayloadAndSignInputs(clientCtx, args) + if err != nil { + return err + } + + // Unmarshal payload + var payload types.MsgCreateResourcePayload + err = clientCtx.Codec.UnmarshalJSON([]byte(payloadJson), &payload) + 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) + + return cmd +} From 3a834226d6325f5b9a1cb674671820be911269c4 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Thu, 23 Jun 2022 15:32:59 +0300 Subject: [PATCH 54/65] Allow UUIDs as IDs in DIDs --- x/cheqd/tests/constants.go | 6 ++--- x/cheqd/types/validate.go | 11 ++++++++ x/cheqd/utils/did.go | 12 ++++----- x/cheqd/utils/did_test.go | 26 +++++++++++++++++++ x/cheqd/utils/encoding.go | 4 +++ x/{resource => cheqd}/utils/uuid.go | 4 +++ x/{resource => cheqd}/utils/uuid_test.go | 0 .../types/tx_msg_create_resource_payload.go | 12 ++++----- x/resource/types/validate.go | 11 -------- 9 files changed, 59 insertions(+), 27 deletions(-) rename x/{resource => cheqd}/utils/uuid.go (84%) rename x/{resource => cheqd}/utils/uuid_test.go (100%) 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/types/validate.go b/x/cheqd/types/validate.go index 5f6e13097..b691d1d92 100644 --- a/x/cheqd/types/validate.go +++ b/x/cheqd/types/validate.go @@ -193,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 cb3b005b5..876581430 100644 --- a/x/cheqd/utils/did.go +++ b/x/cheqd/utils/did.go @@ -84,14 +84,12 @@ func IsValidDID(did string, method string, allowedNamespaces []string) bool { } func ValidateID(id string) error { - // Length should be 16 or 32 symbols - if len(id) != 16 && len(id) != 32 { - return fmt.Errorf("unique id length should be 16 or 32 symbols") - } + isValidId := len(id) == 16 && IsValidBase58(id) || + len(id) == 32 && IsValidBase58(id) || + IsValidUUID(id) - // Base58 check - if err := ValidateBase58(id); 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 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/resource/utils/uuid.go b/x/cheqd/utils/uuid.go similarity index 84% rename from x/resource/utils/uuid.go rename to x/cheqd/utils/uuid.go index 7620bc84d..be86de9af 100644 --- a/x/resource/utils/uuid.go +++ b/x/cheqd/utils/uuid.go @@ -17,3 +17,7 @@ func ValidateUUID(u string) error { _, err := uuid.Parse(u) return err } + +func IsValidUUID(u string) bool { + return ValidateUUID(u) == nil +} diff --git a/x/resource/utils/uuid_test.go b/x/cheqd/utils/uuid_test.go similarity index 100% rename from x/resource/utils/uuid_test.go rename to x/cheqd/utils/uuid_test.go diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go index ec97a27ec..c9b381ff8 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -1,11 +1,11 @@ package types import ( - cheqdTypes "github.com/cheqd/cheqd-node/x/cheqd/types" + cheqdtypes "github.com/cheqd/cheqd-node/x/cheqd/types" validation "github.com/go-ozzo/ozzo-validation/v4" ) -var _ cheqdTypes.IdentityMsg = &MsgCreateResourcePayload{} +var _ cheqdtypes.IdentityMsg = &MsgCreateResourcePayload{} func (msg *MsgCreateResourcePayload) GetSignBytes() []byte { return ModuleCdc.MustMarshal(msg) @@ -28,8 +28,8 @@ func (msg *MsgCreateResourcePayload) ToResource() Resource { func (msg MsgCreateResourcePayload) Validate() error { return validation.ValidateStruct(&msg, - validation.Field(&msg.CollectionId, validation.Required, cheqdTypes.IsID()), - validation.Field(&msg.Id, validation.Required, IsUUID()), + 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, IsAllowedResourceType()), validation.Field(&msg.MimeType, validation.Required, IsAllowedMimeType()), @@ -37,8 +37,8 @@ func (msg MsgCreateResourcePayload) Validate() error { ) } -func ValidMsgCreateResourcePayload() *cheqdTypes.CustomErrorRule { - return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { +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") diff --git a/x/resource/types/validate.go b/x/resource/types/validate.go index 4a702878a..8d5c6daf9 100644 --- a/x/resource/types/validate.go +++ b/x/resource/types/validate.go @@ -7,17 +7,6 @@ import ( // Validation helpers -func IsUUID() *cheqdTypes.CustomErrorRule { - return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { - casted, ok := value.(string) - if !ok { - panic("IsDID must be only applied on string properties") - } - - return utils.ValidateUUID(casted) - }) -} - func IsAllowedResourceType() *cheqdTypes.CustomErrorRule { return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { casted, ok := value.(string) From fe0e4a6117828f24d56b29dfc568f7ea20c01fcb Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Thu, 23 Jun 2022 19:33:01 +0300 Subject: [PATCH 55/65] Optimize list queries not to return resource data --- proto/resource/v1/query.proto | 38 +- proto/resource/v1/resource.proto | 16 +- tests/e2e-bash/tests/test_create_resource.sh | 10 +- .../tests/test_query_all_resource_versions.sh | 17 +- .../tests/test_query_collection_resources.sh | 23 +- x/resource/keeper/keeper_resource.go | 166 ++++---- .../keeper/msg_server_create_resource.go | 14 +- x/resource/tests/constants.go | 14 +- x/resource/tests/create_resource_test.go | 28 +- .../tests/query_all_resource_versions_test.go | 23 +- .../tests/query_collection_resources_test.go | 5 +- x/resource/tests/query_resource_test.go | 20 +- x/resource/tests/setup.go | 10 +- x/resource/tests/utils.go | 20 - x/resource/types/genesis.go | 4 +- x/resource/types/keys.go | 5 +- x/resource/types/query.pb.go | 78 ++-- x/resource/types/resource.pb.go | 367 +++++++++++++----- .../types/tx_msg_create_resource_payload.go | 16 +- 19 files changed, 537 insertions(+), 337 deletions(-) delete mode 100644 x/resource/tests/utils.go diff --git a/proto/resource/v1/query.proto b/proto/resource/v1/query.proto index ac74923c6..01edc2ff7 100644 --- a/proto/resource/v1/query.proto +++ b/proto/resource/v1/query.proto @@ -9,41 +9,41 @@ 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"; - } - rpc AllResourceVersions(QueryGetAllResourceVersionsRequest) returns (QueryGetAllResourceVersionsResponse) { - option (google.api.http).get = "/1.0/identifiers/{collection_id}/resources/versions"; - } + 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"; + } + rpc AllResourceVersions(QueryGetAllResourceVersionsRequest) returns (QueryGetAllResourceVersionsResponse) { + option (google.api.http).get = "/1.0/identifiers/{collection_id}/resources/versions"; + } } message QueryGetResourceRequest { - string collection_id = 1; - string id = 2; + string collection_id = 1; + string id = 2; } message QueryGetResourceResponse { - Resource resource = 1; + Resource resource = 1; } message QueryGetCollectionResourcesRequest { - string collection_id = 1; + string collection_id = 1; } message QueryGetCollectionResourcesResponse { - repeated Resource resources = 1; + repeated ResourceHeader resources = 1; } message QueryGetAllResourceVersionsRequest { - string collection_id = 1; // Mapped to URL path - string name = 2; // Mapped to URL parameter `name` - string resource_type = 3; // Mapped to URL parameter `resource_type` - string mime_type = 4; // Mapped to URL parameter `mime_type` + string collection_id = 1; // Mapped to URL path + string name = 2; // Mapped to URL parameter `name` + string resource_type = 3; // Mapped to URL parameter `resource_type` + string mime_type = 4; // Mapped to URL parameter `mime_type` } message QueryGetAllResourceVersionsResponse { - repeated Resource resources = 1; + repeated ResourceHeader resources = 1; } diff --git a/proto/resource/v1/resource.proto b/proto/resource/v1/resource.proto index b4b0b4209..f5d070668 100644 --- a/proto/resource/v1/resource.proto +++ b/proto/resource/v1/resource.proto @@ -5,14 +5,18 @@ 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 mime_type = 5; - bytes data = 6; - string created = 7; - bytes checksum = 8; - string previous_version_id = 9; - string next_version_id = 10; -} \ No newline at end of file + string created = 6; + bytes checksum = 7; + string previous_version_id = 8; + string next_version_id = 9; +} diff --git a/tests/e2e-bash/tests/test_create_resource.sh b/tests/e2e-bash/tests/test_create_resource.sh index 0b185b3f4..9d713ca4a 100644 --- a/tests/e2e-bash/tests/test_create_resource.sh +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -61,9 +61,9 @@ assert_tx_successful "$RESULT" # shellcheck disable=SC2086 RESULT=$(cheqd-noded query resource resource "${ID}" ${RESOURCE_ID} ${QUERY_PARAMS}) -assert_eq "$(echo "$RESULT" | jq -r ".resource.collection_id")" "${ID}" -assert_eq "$(echo "$RESULT" | jq -r ".resource.id")" "${RESOURCE_ID}" -assert_eq "$(echo "$RESULT" | jq -r ".resource.name")" "${RESOURCE_NAME}" -assert_eq "$(echo "$RESULT" | jq -r ".resource.resource_type")" "${RESOURCE_RESOURCE_TYPE}" -assert_eq "$(echo "$RESULT" | jq -r ".resource.mime_type")" "${RESOURCE_MIME_TYPE}" +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.mime_type")" "${RESOURCE_MIME_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 index 9a55c77d7..1e2d7803b 100644 --- a/tests/e2e-bash/tests/test_query_all_resource_versions.sh +++ b/tests/e2e-bash/tests/test_query_all_resource_versions.sh @@ -70,17 +70,17 @@ assert_tx_successful "$RESULT" # shellcheck disable=SC2086 RESULT=$(cheqd-noded query resource resource "${ID1}" ${RESOURCE1_V1_ID} ${QUERY_PARAMS}) -EXPECTED_RES1_V1='{ +EXPECTED_RES1_V1_HEADER='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V1_ID}'", "name": "'${RESOURCE1_NAME}'", "mime_type": "'${RESOURCE1_MIME_TYPE}'", - "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", - "data": "'${RESOURCE1_V1_DATA}'" + "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'" }' DEL_FILTER='del(.checksum, .created, .next_version_id, .previous_version_id)' -assert_json_eq "$(echo "$RESULT" | jq -r ".resource | ${DEL_FILTER}")" "${EXPECTED_RES1_V1}" +assert_json_eq "$(echo "$RESULT" | jq -r ".resource.header | ${DEL_FILTER}")" "${EXPECTED_RES1_V1_HEADER}" +assert_json_eq "$(echo "$RESULT" | jq -r ".resource.data")" "${RESOURCE1_V1_DATA}" ########## Creating Resource 1 v2 ########## @@ -132,18 +132,17 @@ assert_tx_successful "$RESULT" ########## Querying All Resource 1 versions ########## -EXPECTED_RES1_V2='{ +EXPECTED_RES1_V2_HEADER='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V2_ID}'", "name": "'${RESOURCE1_NAME}'", "mime_type": "'${RESOURCE1_MIME_TYPE}'", - "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", - "data": "'${RESOURCE1_V2_DATA}'" + "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'" }' # shellcheck disable=SC2086 RESULT=$(cheqd-noded query resource all-resource-versions "${ID1}" "${RESOURCE1_NAME}" ${RESOURCE1_RESOURCE_TYPE} ${RESOURCE1_MIME_TYPE} ${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}" -assert_json_eq "$(echo "$RESULT" | jq -r '.resources[] | select(.id == "'"${RESOURCE1_V2_ID}"'") | '"${DEL_FILTER}"'')" "${EXPECTED_RES1_V2}" +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 index 362af474b..e13411ec0 100644 --- a/tests/e2e-bash/tests/test_query_collection_resources.sh +++ b/tests/e2e-bash/tests/test_query_collection_resources.sh @@ -60,7 +60,7 @@ MSG_CREATE_RESOURCE1='{ # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE1}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE1}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" @@ -70,17 +70,17 @@ assert_tx_successful "$RESULT" # shellcheck disable=SC2086 RESULT=$(cheqd-noded query resource resource "${ID1}" ${RESOURCE1_V1_ID} ${QUERY_PARAMS}) -EXPECTED_RES1_V1='{ +EXPECTED_RES1_V1_HEADER='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V1_ID}'", "name": "'${RESOURCE1_V1_NAME}'", "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", - "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", - "data": "'${RESOURCE1_V1_DATA}'" + "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 | ${DEL_FILTER}")" "${EXPECTED_RES1_V1}" +assert_json_eq "$(echo "$RESULT" | jq -r ".resource.header | ${DEL_FILTER}")" "${EXPECTED_RES1_V1_HEADER}" +assert_json_eq "$(echo "$RESULT" | jq -r ".resource.data")" "${RESOURCE1_V1_DATA}" ########## Creating Resource 1 v2 ########## @@ -99,7 +99,7 @@ MSG_CREATE_RESOURCE1_V2='{ # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE1_V2}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE1_V2}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" @@ -151,7 +151,7 @@ MSG_CREATE_RESOURCE2='{ # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource "${MSG_CREATE_RESOURCE2}" "${KEY2_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE2}" "${KEY2_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" @@ -159,18 +159,17 @@ assert_tx_successful "$RESULT" ########## Querying All Resource 1 versions ########## -EXPECTED_RES1_V2='{ +EXPECTED_RES1_V2_HEADER='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V2_ID}'", "name": "'${RESOURCE1_V1_NAME}'", "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", - "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", - "data": "'${RESOURCE1_V2_DATA}'" + "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}" -assert_json_eq "$(echo "$RESULT" | jq -r '.resources[] | select(.id == "'"${RESOURCE1_V2_ID}"'") | '"${DEL_FILTER}"'')" "${EXPECTED_RES1_V2}" +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/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index 244e377aa..8355ed2aa 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -4,7 +4,6 @@ import ( "strconv" "github.com/cheqd/cheqd-node/x/resource/types" - "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -40,18 +39,24 @@ func (k Keeper) SetResourceCount(ctx *sdk.Context, count uint64) { store.Set(byteKey, bz) } -// SetResource set a specific resource in the store +// SetResource create or update a specific resource in the store func (k Keeper) SetResource(ctx *sdk.Context, resource *types.Resource) error { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - key := GetResourceKeyBytes(resource.CollectionId, resource.Id) - bytes := k.cdc.MustMarshal(resource) - - if !store.Has(key) { + if !k.HasResource(ctx, resource.Header.CollectionId, resource.Header.Id) { count := k.GetResourceCount(ctx) k.SetResourceCount(ctx, count+1) } - store.Set(key, bytes) + 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 } @@ -61,47 +66,38 @@ func (k Keeper) GetResource(ctx *sdk.Context, collectionId string, id string) (t return types.Resource{}, sdkerrors.ErrNotFound.Wrap("resource " + collectionId + ":" + id) } - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - bytes := store.Get(GetResourceKeyBytes(collectionId, id)) + store := ctx.KVStore(k.storeKey) - var value types.Resource - if err := k.cdc.Unmarshal(bytes, &value); err != nil { + 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()) } - return value, nil + 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 := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - return store.Has(GetResourceKeyBytes(collectionId, id)) -} - -// GetResourceKeyBytes returns the byte representation of resource key -func GetResourceKeyBytes(collectionId string, id string) []byte { - return []byte(collectionId + ":" + id) -} - -func GetResourceCollectionPrefixBytes(collectionId string) []byte { - return []byte(collectionId + ":") + store := ctx.KVStore(k.storeKey) + return store.Has(GetResourceHeaderKeyBytes(collectionId, id)) } -func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) []*types.Resource { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - iterator := sdk.KVStorePrefixIterator(store, GetResourceCollectionPrefixBytes(collectionId)) +func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) []*types.ResourceHeader { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, GetResourceHeaderCollectionPrefixBytes(collectionId)) - defer func(iterator sdk.Iterator) { - err := iterator.Close() - if err != nil { - panic(err.Error()) - } - }(iterator) + defer closeIteratorOrPanic(iterator) - var result []*types.Resource + var result []*types.ResourceHeader for ; iterator.Valid(); iterator.Next() { - var val types.Resource + var val types.ResourceHeader k.cdc.MustUnmarshal(iterator.Value(), &val) if val.Name == name && @@ -114,21 +110,16 @@ func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, res return result } -func (k Keeper) GetResourceCollection(ctx *sdk.Context, collectionId string) []*types.Resource { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - iterator := sdk.KVStorePrefixIterator(store, GetResourceCollectionPrefixBytes(collectionId)) +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.Resource + var resources []*types.ResourceHeader - defer func(iterator sdk.Iterator) { - err := iterator.Close() - if err != nil { - panic(err.Error()) - } - }(iterator) + defer closeIteratorOrPanic(iterator) for ; iterator.Valid(); iterator.Next() { - var val types.Resource + var val types.ResourceHeader k.cdc.MustUnmarshal(iterator.Value(), &val) resources = append(resources, &val) @@ -137,19 +128,13 @@ func (k Keeper) GetResourceCollection(ctx *sdk.Context, collectionId string) []* return resources } -func (k Keeper) GetLastResourceVersion(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) (types.Resource, bool) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) - iterator := sdk.KVStorePrefixIterator(store, GetResourceCollectionPrefixBytes(collectionId)) +func (k Keeper) GetLastResourceVersionHeader(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) (types.ResourceHeader, bool) { + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), GetResourceHeaderCollectionPrefixBytes(collectionId)) - defer func(iterator sdk.Iterator) { - err := iterator.Close() - if err != nil { - panic(err.Error()) - } - }(iterator) + defer closeIteratorOrPanic(iterator) for ; iterator.Valid(); iterator.Next() { - var val types.Resource + var val types.ResourceHeader k.cdc.MustUnmarshal(iterator.Value(), &val) if val.Name == name && @@ -160,26 +145,73 @@ func (k Keeper) GetLastResourceVersion(ctx *sdk.Context, collectionId, name, res } } - return types.Resource{}, false + 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) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceKey)) + headerIterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceHeaderKey)) + dataIterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ResourceDataKey)) - defer func(iterator sdk.Iterator) { - err := iterator.Close() - if err != nil { - panic(err.Error()) + defer closeIteratorOrPanic(headerIterator) + defer closeIteratorOrPanic(dataIterator) + + + for headerIterator.Valid() { + if !dataIterator.Valid() { + panic("number of headers and data don't match") } - }(iterator) - for ; iterator.Valid(); iterator.Next() { - var val types.Resource - k.cdc.MustUnmarshal(iterator.Value(), &val) - list = append(list, val) + 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()) + } +} \ No newline at end of file diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 86388d0b6..3f9f5baa6 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -45,25 +45,25 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes // Build Resource resource := msg.Payload.ToResource() - resource.Checksum = sha256.New().Sum(resource.Data) - resource.Created = time.Now().UTC().Format(time.RFC3339) + resource.Header.Checksum = sha256.New().Sum(resource.Data) + resource.Header.Created = time.Now().UTC().Format(time.RFC3339) // Find previous version and upgrade backward and forward version links - previousResourceVersion, found := k.GetLastResourceVersion(&ctx, resource.CollectionId, resource.Name, resource.ResourceType, resource.MimeType) + previousResourceVersionHeader, found := k.GetLastResourceVersionHeader(&ctx, resource.Header.CollectionId, resource.Header.Name, resource.Header.ResourceType, resource.Header.MimeType) if found { // Set links - previousResourceVersion.NextVersionId = resource.Id - resource.PreviousVersionId = previousResourceVersion.Id + previousResourceVersionHeader.NextVersionId = resource.Header.Id + resource.Header.PreviousVersionId = previousResourceVersionHeader.Id // Update previous version - err := k.SetResource(&ctx, &previousResourceVersion) + err := k.UpdateResourceHeader(&ctx, &previousResourceVersionHeader) if err != nil { return nil, err } } // Append backlink to didDoc - didDocStateValue.Metadata.Resources = append(didDocStateValue.Metadata.Resources, resource.Id) + 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()) diff --git a/x/resource/tests/constants.go b/x/resource/tests/constants.go index 58fa1c659..887cb1a68 100644 --- a/x/resource/tests/constants.go +++ b/x/resource/tests/constants.go @@ -25,12 +25,14 @@ func ExistingResource() types.Resource { data := []byte(SchemaData) checksum := sha256.New().Sum(data) return types.Resource{ - CollectionId: ExistingDIDIdentifier, - Id: "a09abea0-22e0-4b35-8f70-9cc3a6d0b5fd", - Name: "Existing Resource Name", - ResourceType: CLSchemaType, - MimeType: JsonResourceType, + Header: &types.ResourceHeader{ + CollectionId: ExistingDIDIdentifier, + Id: "a09abea0-22e0-4b35-8f70-9cc3a6d0b5fd", + Name: "Existing Resource Name", + ResourceType: CLSchemaType, + MimeType: JsonResourceType, + Checksum: checksum, + }, Data: data, - Checksum: checksum, } } diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index e1809c69b..6124777bd 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -48,14 +48,14 @@ func TestCreateResource(t *testing.T) { ExistingDIDKey: keys[ExistingDIDKey].PrivateKey, }, msg: &types.MsgCreateResourcePayload{ - CollectionId: ExistingResource().CollectionId, + CollectionId: ExistingResource().Header.CollectionId, Id: ResourceId, - Name: ExistingResource().Name, - ResourceType: ExistingResource().ResourceType, - MimeType: ExistingResource().MimeType, + Name: ExistingResource().Header.Name, + ResourceType: ExistingResource().Header.ResourceType, + MimeType: ExistingResource().Header.MimeType, Data: ExistingResource().Data, }, - previousVersionId: ExistingResource().Id, + previousVersionId: ExistingResource().Header.Id, }, { valid: false, @@ -110,19 +110,19 @@ func TestCreateResource(t *testing.T) { if tc.valid { require.Nil(t, err) - did := utils.JoinDID("cheqd", "test", resource.CollectionId) + 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.Id) + require.Contains(t, didStateValue.Metadata.Resources, resource.Header.Id) - require.Equal(t, tc.msg.CollectionId, resource.CollectionId) - require.Equal(t, tc.msg.Id, resource.Id) - require.Equal(t, tc.msg.MimeType, resource.MimeType) - require.Equal(t, tc.msg.ResourceType, resource.ResourceType) + require.Equal(t, tc.msg.CollectionId, resource.Header.CollectionId) + require.Equal(t, tc.msg.Id, resource.Header.Id) + require.Equal(t, tc.msg.MimeType, resource.Header.MimeType) + require.Equal(t, tc.msg.ResourceType, resource.Header.ResourceType) require.Equal(t, tc.msg.Data, resource.Data) - require.Equal(t, tc.msg.Name, resource.Name) - require.Equal(t, sha256.New().Sum(resource.Data), resource.Checksum) - require.Equal(t, tc.previousVersionId, resource.PreviousVersionId) + 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 index df5469788..8c0aeff9b 100644 --- a/x/resource/tests/query_all_resource_versions_test.go +++ b/x/resource/tests/query_all_resource_versions_test.go @@ -39,12 +39,12 @@ func TestQueryGetAllResourceVersions(t *testing.T) { name: "Valid: Works", msg: &types.QueryGetAllResourceVersionsRequest{ CollectionId: ExistingDIDIdentifier, - Name: existingResource.Name, - ResourceType: existingResource.ResourceType, - MimeType: existingResource.MimeType, + Name: existingResource.Header.Name, + ResourceType: existingResource.Header.ResourceType, + MimeType: existingResource.Header.MimeType, }, response: &types.QueryGetAllResourceVersionsResponse{ - Resources: []*types.Resource{&existingResource}, + Resources: []*types.ResourceHeader{existingResource.Header}, }, errMsg: "", }, @@ -53,9 +53,9 @@ func TestQueryGetAllResourceVersions(t *testing.T) { name: "Not Valid: DID Doc is not found", msg: &types.QueryGetAllResourceVersionsRequest{ CollectionId: NotFoundDIDIdentifier, - Name: existingResource.Name, - ResourceType: existingResource.ResourceType, - MimeType: existingResource.MimeType, + Name: existingResource.Header.Name, + ResourceType: existingResource.Header.ResourceType, + MimeType: existingResource.Header.MimeType, }, response: nil, errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), @@ -83,15 +83,16 @@ func TestQueryGetAllResourceVersions(t *testing.T) { if tc.valid { resources := queryResponse.Resources - existingResource.NextVersionId = createdResource.Id + existingResource.Header.NextVersionId = createdResource.Header.Id expectedResources := map[string]types.Resource{ - existingResource.Id: existingResource, - createdResource.Id: *createdResource, + existingResource.Header.Id: existingResource, + createdResource.Header.Id: *createdResource, } require.Nil(t, err) require.Equal(t, len(expectedResources), len(resources)) for _, r := range resources { - CompareResources(t, r, expectedResources[r.Id]) + r.Created = expectedResources[r.Id].Header.Created + require.Equal(t, r, expectedResources[r.Id].Header) } } else { require.Error(t, err) diff --git a/x/resource/tests/query_collection_resources_test.go b/x/resource/tests/query_collection_resources_test.go index 2d469e5a1..a8f643f0c 100644 --- a/x/resource/tests/query_collection_resources_test.go +++ b/x/resource/tests/query_collection_resources_test.go @@ -26,7 +26,7 @@ func TestQueryGetCollectionResources(t *testing.T) { CollectionId: ExistingDIDIdentifier, }, response: &types.QueryGetCollectionResourcesResponse{ - Resources: []*types.Resource{&existingResource}, + Resources: []*types.ResourceHeader{existingResource.Header}, }, errMsg: "", }, @@ -54,7 +54,8 @@ func TestQueryGetCollectionResources(t *testing.T) { require.Nil(t, err) require.Equal(t, len(expectedResources), len(resources)) for i, r := range resources { - CompareResources(t, expectedResources[i], *r) + r.Created = expectedResources[i].Created + require.Equal(t, expectedResources[i], r) } } else { require.Error(t, err) diff --git a/x/resource/tests/query_resource_test.go b/x/resource/tests/query_resource_test.go index e027f1ac0..a04a5d29b 100644 --- a/x/resource/tests/query_resource_test.go +++ b/x/resource/tests/query_resource_test.go @@ -27,7 +27,7 @@ func TestQueryGetResource(t *testing.T) { name: "Valid: Works", msg: &types.QueryGetResourceRequest{ CollectionId: ExistingDIDIdentifier, - Id: existingResource.Id, + Id: existingResource.Header.Id, }, response: &types.QueryGetResourceResponse{ Resource: &existingResource, @@ -49,7 +49,7 @@ func TestQueryGetResource(t *testing.T) { name: "Not Valid: DID Doc is not found", msg: &types.QueryGetResourceRequest{ CollectionId: NotFoundDIDIdentifier, - Id: existingResource.Id, + Id: existingResource.Header.Id, }, response: nil, errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), @@ -66,15 +66,15 @@ func TestQueryGetResource(t *testing.T) { if tc.valid { resource := queryResponse.Resource require.Nil(t, err) - require.Equal(t, tc.response.Resource.CollectionId, resource.CollectionId) - require.Equal(t, tc.response.Resource.Id, resource.Id) - require.Equal(t, tc.response.Resource.MimeType, resource.MimeType) - require.Equal(t, tc.response.Resource.ResourceType, resource.ResourceType) + 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.MimeType, resource.Header.MimeType) + 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.Name, resource.Name) - require.Equal(t, sha256.New().Sum(tc.response.Resource.Data), resource.Checksum) - require.Equal(t, tc.response.Resource.PreviousVersionId, resource.PreviousVersionId) - require.Equal(t, tc.response.Resource.NextVersionId, resource.NextVersionId) + 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 index fe7d7bd62..2ca17079f 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -91,11 +91,11 @@ func Setup() TestSetup { func GenerateCreateResourcePayload(resource types.Resource) *types.MsgCreateResourcePayload { return &types.MsgCreateResourcePayload{ - CollectionId: resource.CollectionId, - Id: resource.Id, - Name: resource.Name, - ResourceType: resource.ResourceType, - MimeType: resource.MimeType, + CollectionId: resource.Header.CollectionId, + Id: resource.Header.Id, + Name: resource.Header.Name, + ResourceType: resource.Header.ResourceType, + MimeType: resource.Header.MimeType, Data: resource.Data, } } diff --git a/x/resource/tests/utils.go b/x/resource/tests/utils.go deleted file mode 100644 index 9065e7292..000000000 --- a/x/resource/tests/utils.go +++ /dev/null @@ -1,20 +0,0 @@ -package tests - -import ( - "crypto/sha256" - - "github.com/cheqd/cheqd-node/x/resource/types" - "github.com/stretchr/testify/require" -) - -func CompareResources(t require.TestingT, expectedResource *types.Resource, resource types.Resource) { - require.Equal(t, expectedResource.CollectionId, resource.CollectionId) - require.Equal(t, expectedResource.Id, resource.Id) - require.Equal(t, expectedResource.MimeType, resource.MimeType) - require.Equal(t, expectedResource.ResourceType, resource.ResourceType) - require.Equal(t, expectedResource.Data, resource.Data) - require.Equal(t, expectedResource.Name, resource.Name) - require.Equal(t, sha256.New().Sum(expectedResource.Data), resource.Checksum) - require.Equal(t, expectedResource.PreviousVersionId, resource.PreviousVersionId) - require.Equal(t, expectedResource.NextVersionId, resource.NextVersionId) -} diff --git a/x/resource/types/genesis.go b/x/resource/types/genesis.go index 13d635fe9..b877466fd 100644 --- a/x/resource/types/genesis.go +++ b/x/resource/types/genesis.go @@ -17,13 +17,13 @@ func (gs GenesisState) Validate() error { resourceIdMap := make(map[string]bool) for _, resource := range gs.ResourceList { - collectionResourceId := resource.CollectionId + ":" + resource.Id + 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[resource.Id] = true + resourceIdMap[collectionResourceId] = true } return nil diff --git a/x/resource/types/keys.go b/x/resource/types/keys.go index 7fe501c82..10cc9300a 100644 --- a/x/resource/types/keys.go +++ b/x/resource/types/keys.go @@ -19,6 +19,7 @@ func KeyPrefix(p string) []byte { } const ( - ResourceKey = "resource:" - ResourceCountKey = "resource-count:" + ResourceHeaderKey = "resource-header:" + ResourceDataKey = "resource-data:" + ResourceCountKey = "resource-count:" ) diff --git a/x/resource/types/query.pb.go b/x/resource/types/query.pb.go index 07893d52e..2becdb646 100644 --- a/x/resource/types/query.pb.go +++ b/x/resource/types/query.pb.go @@ -169,7 +169,7 @@ func (m *QueryGetCollectionResourcesRequest) GetCollectionId() string { } type QueryGetCollectionResourcesResponse struct { - Resources []*Resource `protobuf:"bytes,1,rep,name=resources,proto3" json:"resources,omitempty"` + Resources []*ResourceHeader `protobuf:"bytes,1,rep,name=resources,proto3" json:"resources,omitempty"` } func (m *QueryGetCollectionResourcesResponse) Reset() { *m = QueryGetCollectionResourcesResponse{} } @@ -205,7 +205,7 @@ func (m *QueryGetCollectionResourcesResponse) XXX_DiscardUnknown() { var xxx_messageInfo_QueryGetCollectionResourcesResponse proto.InternalMessageInfo -func (m *QueryGetCollectionResourcesResponse) GetResources() []*Resource { +func (m *QueryGetCollectionResourcesResponse) GetResources() []*ResourceHeader { if m != nil { return m.Resources } @@ -281,7 +281,7 @@ func (m *QueryGetAllResourceVersionsRequest) GetMimeType() string { } type QueryGetAllResourceVersionsResponse struct { - Resources []*Resource `protobuf:"bytes,1,rep,name=resources,proto3" json:"resources,omitempty"` + Resources []*ResourceHeader `protobuf:"bytes,1,rep,name=resources,proto3" json:"resources,omitempty"` } func (m *QueryGetAllResourceVersionsResponse) Reset() { *m = QueryGetAllResourceVersionsResponse{} } @@ -317,7 +317,7 @@ func (m *QueryGetAllResourceVersionsResponse) XXX_DiscardUnknown() { var xxx_messageInfo_QueryGetAllResourceVersionsResponse proto.InternalMessageInfo -func (m *QueryGetAllResourceVersionsResponse) GetResources() []*Resource { +func (m *QueryGetAllResourceVersionsResponse) GetResources() []*ResourceHeader { if m != nil { return m.Resources } @@ -336,39 +336,39 @@ func init() { func init() { proto.RegisterFile("resource/v1/query.proto", fileDescriptor_10aac3b48339734d) } var fileDescriptor_10aac3b48339734d = []byte{ - // 500 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0xce, 0xa6, 0x01, 0x25, 0xcb, 0xcf, 0x61, 0x7b, 0xa8, 0x65, 0xc0, 0xaa, 0xdc, 0x03, 0x08, - 0x15, 0x2f, 0x49, 0x05, 0x3d, 0x70, 0x6a, 0x2b, 0x40, 0xbd, 0x20, 0x11, 0x21, 0x0e, 0x5c, 0xa2, - 0xd4, 0x3b, 0xa4, 0x2b, 0x39, 0x5e, 0xc7, 0xbb, 0x89, 0x88, 0xaa, 0x5e, 0x78, 0x02, 0x24, 0x1e, - 0x80, 0x97, 0xe0, 0x21, 0x38, 0x46, 0xe2, 0x02, 0x37, 0x94, 0x70, 0xe5, 0x1d, 0xd0, 0x6e, 0xbc, - 0x4e, 0x11, 0x49, 0xb0, 0x45, 0x2f, 0xb6, 0xb5, 0x33, 0xdf, 0x37, 0xdf, 0x37, 0x33, 0x6b, 0xbc, - 0x95, 0x82, 0x14, 0xc3, 0x34, 0x04, 0x3a, 0x6a, 0xd2, 0xc1, 0x10, 0xd2, 0x71, 0x90, 0xa4, 0x42, - 0x09, 0x72, 0x27, 0x3c, 0x85, 0x01, 0xe3, 0x2c, 0x30, 0xef, 0x58, 0x30, 0x08, 0x6c, 0x6a, 0x30, - 0x6a, 0xba, 0xb7, 0x7b, 0x42, 0xf4, 0x22, 0xa0, 0xdd, 0x84, 0xd3, 0x6e, 0x1c, 0x0b, 0xd5, 0x55, - 0x5c, 0xc4, 0x72, 0x0e, 0x76, 0xdd, 0x8b, 0xac, 0x39, 0xcc, 0xc4, 0xfc, 0x17, 0x78, 0xeb, 0xa5, - 0xae, 0xf3, 0x1c, 0x54, 0x3b, 0x8b, 0xb4, 0x61, 0x30, 0x04, 0xa9, 0xc8, 0x0e, 0xbe, 0x11, 0x8a, - 0x28, 0x82, 0x50, 0x73, 0x75, 0x38, 0x73, 0xd0, 0x36, 0xba, 0xd7, 0x68, 0x5f, 0x5f, 0x1c, 0x1e, - 0x33, 0x72, 0x13, 0x57, 0x39, 0x73, 0xaa, 0x26, 0x52, 0xe5, 0xcc, 0xef, 0x60, 0xe7, 0x6f, 0x3e, - 0x99, 0x88, 0x58, 0x02, 0x39, 0xc2, 0x75, 0x5b, 0xdd, 0x70, 0x5d, 0x6b, 0xdd, 0x0d, 0xd6, 0xfa, - 0x0a, 0x72, 0x8a, 0x1c, 0xe8, 0x1f, 0x63, 0xdf, 0x16, 0x38, 0xca, 0x85, 0xd8, 0x3c, 0x59, 0x46, - 0xbb, 0x1f, 0xe1, 0x9d, 0xb5, 0x54, 0x99, 0xec, 0xa7, 0xb8, 0x61, 0xab, 0x4b, 0x07, 0x6d, 0x6f, - 0x94, 0xd1, 0xbd, 0x40, 0xfa, 0x9f, 0xd0, 0x42, 0xf9, 0x41, 0x14, 0xd9, 0x94, 0xd7, 0x90, 0x4a, - 0x3d, 0xab, 0x52, 0x5d, 0x27, 0xb8, 0x16, 0x77, 0xfb, 0x90, 0xf5, 0xdd, 0x7c, 0x6b, 0xa0, 0x2d, - 0xd6, 0x51, 0xe3, 0x04, 0x9c, 0x8d, 0x39, 0xd0, 0x1e, 0xbe, 0x1a, 0x27, 0x40, 0x6e, 0xe1, 0x46, - 0x9f, 0xf7, 0xb3, 0x84, 0x9a, 0x49, 0xa8, 0xeb, 0x03, 0x1d, 0xbc, 0xd8, 0x8f, 0xa5, 0x02, 0x2f, - 0xb5, 0x1f, 0xad, 0x5f, 0x35, 0x7c, 0xc5, 0x94, 0x23, 0x9f, 0x11, 0xae, 0xdb, 0x0c, 0xf2, 0xf8, - 0x1f, 0x54, 0x2b, 0xb6, 0xd5, 0xdd, 0x2f, 0x8d, 0x9b, 0xdb, 0xf1, 0xf7, 0xdf, 0x7f, 0xfd, 0xf9, - 0xb1, 0xda, 0x24, 0x94, 0x36, 0x83, 0x87, 0x94, 0x33, 0x88, 0x15, 0x7f, 0xcb, 0x21, 0x95, 0xf4, - 0xec, 0x8f, 0x41, 0x9c, 0xe7, 0x57, 0x47, 0xd2, 0x33, 0xce, 0xce, 0xc9, 0x04, 0xe1, 0xcd, 0x25, - 0x7b, 0x43, 0x0e, 0x0a, 0x2a, 0x59, 0xbd, 0xbe, 0xee, 0xe1, 0xff, 0x50, 0x64, 0xbe, 0x5a, 0xc6, - 0xd7, 0x2e, 0xb9, 0x5f, 0xdc, 0x17, 0xf9, 0x8e, 0xf0, 0xe6, 0x92, 0xd1, 0x17, 0xb6, 0xb4, 0x7a, - 0xaf, 0x0b, 0x5b, 0x5a, 0xb3, 0x79, 0xfe, 0x13, 0x63, 0xe9, 0x11, 0xd9, 0x2b, 0x31, 0xaa, 0x51, - 0x46, 0x72, 0xf8, 0xec, 0xcb, 0xd4, 0x43, 0x93, 0xa9, 0x87, 0x7e, 0x4c, 0x3d, 0xf4, 0x61, 0xe6, - 0x55, 0x26, 0x33, 0xaf, 0xf2, 0x6d, 0xe6, 0x55, 0xde, 0xec, 0xf6, 0xb8, 0x3a, 0x1d, 0x9e, 0x04, - 0xa1, 0xe8, 0x53, 0x23, 0x6e, 0xfe, 0x7c, 0xa0, 0x35, 0xd2, 0x77, 0x39, 0x17, 0xd5, 0x97, 0x46, - 0x9e, 0x5c, 0x35, 0x3f, 0xce, 0xbd, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xf4, 0xef, 0x1e, 0x9a, - 0xac, 0x05, 0x00, 0x00, + // 509 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xc1, 0x6e, 0xd3, 0x40, + 0x10, 0xcd, 0xa6, 0x01, 0x25, 0x5b, 0xe0, 0xb0, 0x3d, 0xd4, 0x32, 0x60, 0x55, 0xee, 0x81, 0x0a, + 0xb5, 0x5e, 0x92, 0x0a, 0x7a, 0xe0, 0xd4, 0x56, 0x02, 0x2a, 0x24, 0x24, 0x22, 0xc4, 0x81, 0x4b, + 0xe4, 0x7a, 0x87, 0x74, 0x25, 0xc7, 0xeb, 0x78, 0x9d, 0x88, 0xa8, 0xea, 0x85, 0x2f, 0x40, 0xe2, + 0x03, 0xf8, 0x09, 0x3e, 0x82, 0x63, 0x24, 0x2e, 0x70, 0x43, 0x09, 0x57, 0xfe, 0x01, 0xed, 0xc6, + 0xeb, 0x14, 0x91, 0x04, 0x5b, 0xa8, 0x17, 0xdb, 0xda, 0x99, 0xf7, 0xe6, 0xbd, 0x99, 0x59, 0xe3, + 0xcd, 0x04, 0xa4, 0x18, 0x24, 0x01, 0xd0, 0x61, 0x93, 0xf6, 0x07, 0x90, 0x8c, 0xbc, 0x38, 0x11, + 0xa9, 0x20, 0x77, 0x83, 0x33, 0xe8, 0x33, 0xce, 0x3c, 0xfd, 0x8e, 0x04, 0x03, 0xcf, 0xa4, 0x7a, + 0xc3, 0xa6, 0x7d, 0xa7, 0x2b, 0x44, 0x37, 0x04, 0xea, 0xc7, 0x9c, 0xfa, 0x51, 0x24, 0x52, 0x3f, + 0xe5, 0x22, 0x92, 0x33, 0xb0, 0x6d, 0x5f, 0x66, 0xcd, 0x61, 0x3a, 0xe6, 0xbe, 0xc0, 0x9b, 0x2f, + 0x55, 0x9d, 0xa7, 0x90, 0xb6, 0xb3, 0x48, 0x1b, 0xfa, 0x03, 0x90, 0x29, 0xd9, 0xc6, 0x37, 0x03, + 0x11, 0x86, 0x10, 0x28, 0xae, 0x0e, 0x67, 0x16, 0xda, 0x42, 0x3b, 0x8d, 0xf6, 0x8d, 0xf9, 0xe1, + 0x09, 0x23, 0xb7, 0x70, 0x95, 0x33, 0xab, 0xaa, 0x23, 0x55, 0xce, 0xdc, 0x0e, 0xb6, 0xfe, 0xe6, + 0x93, 0xb1, 0x88, 0x24, 0x90, 0x63, 0x5c, 0x37, 0xd5, 0x35, 0xd7, 0x7a, 0xeb, 0x9e, 0xb7, 0xd2, + 0x97, 0x97, 0x53, 0xe4, 0x40, 0xf7, 0x04, 0xbb, 0xa6, 0xc0, 0x71, 0x2e, 0xc4, 0xe4, 0xc9, 0x32, + 0xda, 0xdd, 0x04, 0x6f, 0xaf, 0xa4, 0xca, 0x64, 0x3f, 0xc7, 0x0d, 0x53, 0x5d, 0x5a, 0x68, 0x6b, + 0x6d, 0x67, 0xbd, 0xb5, 0x57, 0x50, 0xf7, 0x33, 0xf0, 0x19, 0x24, 0xed, 0x39, 0xde, 0xfd, 0x84, + 0xe6, 0xfa, 0x0f, 0xc3, 0xd0, 0x24, 0xbe, 0x86, 0x44, 0xaa, 0x89, 0x95, 0xea, 0x3d, 0xc1, 0xb5, + 0xc8, 0xef, 0x41, 0xd6, 0x7d, 0xfd, 0xad, 0x80, 0xa6, 0x58, 0x27, 0x1d, 0xc5, 0x60, 0xad, 0xcd, + 0x80, 0xe6, 0xf0, 0xd5, 0x28, 0x06, 0x72, 0x1b, 0x37, 0x7a, 0xbc, 0x97, 0x25, 0xd4, 0x74, 0x42, + 0x5d, 0x1d, 0xa8, 0xe0, 0xe5, 0xae, 0x2c, 0x14, 0x78, 0x05, 0x5d, 0x69, 0xfd, 0xaa, 0xe1, 0x6b, + 0xba, 0x28, 0xf9, 0x8c, 0x70, 0xdd, 0xe4, 0x91, 0x47, 0xff, 0x20, 0x5c, 0xb2, 0xb9, 0xf6, 0x41, + 0x69, 0xdc, 0xcc, 0x94, 0x7b, 0xf0, 0xfe, 0xeb, 0xcf, 0x8f, 0xd5, 0x26, 0xa1, 0xb4, 0xe9, 0x3d, + 0xa0, 0x9c, 0x41, 0x94, 0xf2, 0xb7, 0x1c, 0x12, 0x49, 0xcf, 0xff, 0x18, 0xc7, 0x45, 0x7e, 0x8d, + 0x24, 0x3d, 0xe7, 0xec, 0x82, 0x8c, 0x11, 0xde, 0x58, 0xb0, 0x43, 0xe4, 0xb0, 0xa0, 0x92, 0xe5, + 0xab, 0x6c, 0x1f, 0xfd, 0x0f, 0x45, 0xe6, 0xab, 0xa5, 0x7d, 0xed, 0x92, 0xfb, 0xc5, 0x7d, 0x91, + 0xef, 0x08, 0x6f, 0x2c, 0x58, 0x80, 0xc2, 0x96, 0x96, 0x6f, 0x77, 0x61, 0x4b, 0x2b, 0xf6, 0xcf, + 0x7d, 0xac, 0x2d, 0x3d, 0x24, 0xfb, 0x25, 0x46, 0x35, 0xcc, 0x48, 0x8e, 0x9e, 0x7c, 0x99, 0x38, + 0x68, 0x3c, 0x71, 0xd0, 0x8f, 0x89, 0x83, 0x3e, 0x4c, 0x9d, 0xca, 0x78, 0xea, 0x54, 0xbe, 0x4d, + 0x9d, 0xca, 0x9b, 0xdd, 0x2e, 0x4f, 0xcf, 0x06, 0xa7, 0x5e, 0x20, 0x7a, 0x54, 0x8b, 0x9b, 0x3d, + 0xf7, 0x94, 0x46, 0xfa, 0x2e, 0xe7, 0xa2, 0xea, 0xea, 0xc8, 0xd3, 0xeb, 0xfa, 0x27, 0xba, 0xff, + 0x3b, 0x00, 0x00, 0xff, 0xff, 0xc7, 0x26, 0x62, 0xc6, 0xb8, 0x05, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -1205,7 +1205,7 @@ func (m *QueryGetCollectionResourcesResponse) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Resources = append(m.Resources, &Resource{}) + m.Resources = append(m.Resources, &ResourceHeader{}) if err := m.Resources[len(m.Resources)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } @@ -1467,7 +1467,7 @@ func (m *QueryGetAllResourceVersionsResponse) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Resources = append(m.Resources, &Resource{}) + m.Resources = append(m.Resources, &ResourceHeader{}) if err := m.Resources[len(m.Resources)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } diff --git a/x/resource/types/resource.pb.go b/x/resource/types/resource.pb.go index 5e9e24211..e040e8dc3 100644 --- a/x/resource/types/resource.pb.go +++ b/x/resource/types/resource.pb.go @@ -23,16 +23,8 @@ var _ = math.Inf const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type Resource 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"` - MimeType string `protobuf:"bytes,5,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"` - Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` - Created string `protobuf:"bytes,7,opt,name=created,proto3" json:"created,omitempty"` - Checksum []byte `protobuf:"bytes,8,opt,name=checksum,proto3" json:"checksum,omitempty"` - PreviousVersionId string `protobuf:"bytes,9,opt,name=previous_version_id,json=previousVersionId,proto3" json:"previous_version_id,omitempty"` - NextVersionId string `protobuf:"bytes,10,opt,name=next_version_id,json=nextVersionId,proto3" json:"next_version_id,omitempty"` + 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{} } @@ -68,70 +60,122 @@ func (m *Resource) XXX_DiscardUnknown() { var xxx_messageInfo_Resource proto.InternalMessageInfo -func (m *Resource) GetCollectionId() string { +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"` + MimeType string `protobuf:"bytes,5,opt,name=mime_type,json=mimeType,proto3" json:"mime_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 *Resource) GetId() string { +func (m *ResourceHeader) GetId() string { if m != nil { return m.Id } return "" } -func (m *Resource) GetName() string { +func (m *ResourceHeader) GetName() string { if m != nil { return m.Name } return "" } -func (m *Resource) GetResourceType() string { +func (m *ResourceHeader) GetResourceType() string { if m != nil { return m.ResourceType } return "" } -func (m *Resource) GetMimeType() string { +func (m *ResourceHeader) GetMimeType() string { if m != nil { return m.MimeType } return "" } -func (m *Resource) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *Resource) GetCreated() string { +func (m *ResourceHeader) GetCreated() string { if m != nil { return m.Created } return "" } -func (m *Resource) GetChecksum() []byte { +func (m *ResourceHeader) GetChecksum() []byte { if m != nil { return m.Checksum } return nil } -func (m *Resource) GetPreviousVersionId() string { +func (m *ResourceHeader) GetPreviousVersionId() string { if m != nil { return m.PreviousVersionId } return "" } -func (m *Resource) GetNextVersionId() string { +func (m *ResourceHeader) GetNextVersionId() string { if m != nil { return m.NextVersionId } @@ -140,32 +184,35 @@ func (m *Resource) GetNextVersionId() string { 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{ - // 316 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0xc1, 0x4e, 0xc2, 0x40, - 0x10, 0x86, 0x69, 0x45, 0x28, 0x13, 0xd0, 0xb8, 0x5e, 0x36, 0x18, 0x1b, 0xa2, 0x89, 0xe1, 0xa0, - 0x6d, 0x88, 0x6f, 0xe0, 0xc1, 0x84, 0x2b, 0x31, 0x1e, 0xbc, 0x90, 0xb2, 0x3b, 0x91, 0x8d, 0xb4, - 0x5b, 0xb7, 0xdb, 0x06, 0xde, 0xc2, 0xb7, 0xf1, 0x15, 0x3c, 0x72, 0xf4, 0x68, 0xe0, 0x45, 0x4c, - 0x87, 0xb6, 0x7a, 0xd9, 0x9d, 0xf9, 0xff, 0x6f, 0x67, 0x33, 0x33, 0x30, 0x34, 0x98, 0xe9, 0xdc, - 0x08, 0x0c, 0x8b, 0x49, 0x58, 0xc7, 0x41, 0x6a, 0xb4, 0xd5, 0xec, 0x52, 0x2c, 0xf1, 0x5d, 0x2a, - 0x19, 0xd0, 0x9d, 0x68, 0x89, 0x41, 0x43, 0x14, 0x93, 0xab, 0x4f, 0x17, 0xbc, 0x59, 0x95, 0xb3, - 0x6b, 0x18, 0x08, 0xbd, 0x5a, 0xa1, 0xb0, 0x4a, 0x27, 0x73, 0x25, 0xb9, 0x33, 0x72, 0xc6, 0xbd, - 0x59, 0xff, 0x4f, 0x9c, 0x4a, 0x76, 0x02, 0xae, 0x92, 0xdc, 0x25, 0xc7, 0x55, 0x92, 0x31, 0x68, - 0x27, 0x51, 0x8c, 0xfc, 0x88, 0x14, 0x8a, 0xcb, 0x42, 0xf5, 0x27, 0x73, 0xbb, 0x49, 0x91, 0xb7, - 0x0f, 0x85, 0x6a, 0xf1, 0x69, 0x93, 0x22, 0xbb, 0x80, 0x5e, 0xac, 0xe2, 0x0a, 0x38, 0x26, 0xc0, - 0x2b, 0x05, 0x32, 0x19, 0xb4, 0x65, 0x64, 0x23, 0xde, 0x19, 0x39, 0xe3, 0xfe, 0x8c, 0x62, 0xc6, - 0xa1, 0x2b, 0x0c, 0x46, 0x16, 0x25, 0xef, 0x12, 0x5e, 0xa7, 0x6c, 0x08, 0x9e, 0x58, 0xa2, 0x78, - 0xcb, 0xf2, 0x98, 0x7b, 0xf4, 0xa2, 0xc9, 0x59, 0x00, 0xe7, 0xa9, 0xc1, 0x42, 0xe9, 0x3c, 0x9b, - 0x17, 0x68, 0xb2, 0xaa, 0xb5, 0x1e, 0x55, 0x38, 0xab, 0xad, 0xe7, 0x83, 0x33, 0x95, 0xec, 0x06, - 0x4e, 0x13, 0x5c, 0xdb, 0xff, 0x2c, 0x10, 0x3b, 0x28, 0xe5, 0x86, 0x7b, 0x78, 0xfc, 0xda, 0xf9, - 0xce, 0x76, 0xe7, 0x3b, 0x3f, 0x3b, 0xdf, 0xf9, 0xd8, 0xfb, 0xad, 0xed, 0xde, 0x6f, 0x7d, 0xef, - 0xfd, 0xd6, 0xcb, 0xed, 0xab, 0xb2, 0xcb, 0x7c, 0x11, 0x08, 0x1d, 0x87, 0x34, 0xf5, 0xc3, 0x79, - 0x57, 0x0e, 0x3f, 0x5c, 0x37, 0x0b, 0x0a, 0xcb, 0xc6, 0xb3, 0x45, 0x87, 0xf6, 0x74, 0xff, 0x1b, - 0x00, 0x00, 0xff, 0xff, 0x31, 0x30, 0xf1, 0xb4, 0xc5, 0x01, 0x00, 0x00, + // 347 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x52, 0xcd, 0x4e, 0xea, 0x40, + 0x14, 0xa6, 0xbd, 0x5c, 0x68, 0xe7, 0x02, 0x37, 0x77, 0xee, 0xa6, 0xc1, 0xd8, 0x10, 0x4c, 0x0c, + 0x0b, 0x69, 0x83, 0xbe, 0x81, 0x89, 0x46, 0xb6, 0x8d, 0x71, 0xe1, 0x86, 0x94, 0x99, 0x13, 0x3b, + 0x91, 0x76, 0xea, 0x74, 0xda, 0xc0, 0x5b, 0xf8, 0x1a, 0xbe, 0x89, 0x4b, 0x96, 0x2e, 0x0d, 0xbc, + 0x88, 0xe9, 0xa1, 0xad, 0xba, 0x71, 0xd3, 0x9e, 0xf3, 0xfd, 0xcd, 0x9c, 0x9c, 0x21, 0x43, 0x05, + 0x99, 0xcc, 0x15, 0x03, 0xbf, 0x98, 0xf9, 0x75, 0xed, 0xa5, 0x4a, 0x6a, 0x49, 0x8f, 0x59, 0x04, + 0x4f, 0x5c, 0x70, 0x0f, 0xff, 0x89, 0xe4, 0xe0, 0x35, 0x8a, 0x62, 0x36, 0x06, 0x62, 0x05, 0x55, + 0x4b, 0xaf, 0x48, 0x27, 0x82, 0x90, 0x83, 0x72, 0x8c, 0x91, 0x31, 0xf9, 0x73, 0x3e, 0xf5, 0x7e, + 0xf4, 0x7a, 0xb5, 0xf1, 0x06, 0x4d, 0x41, 0x65, 0xa6, 0x94, 0xb4, 0x79, 0xa8, 0x43, 0xc7, 0x1c, + 0x19, 0x93, 0x5e, 0x80, 0xf5, 0xf8, 0xc5, 0x24, 0x83, 0xef, 0x72, 0x7a, 0x42, 0xfa, 0x4c, 0xae, + 0x56, 0xc0, 0xb4, 0x90, 0xc9, 0x42, 0x70, 0x3c, 0xd4, 0x0e, 0x7a, 0x9f, 0xe0, 0x9c, 0xd3, 0x01, + 0x31, 0x05, 0xc7, 0x24, 0x3b, 0x30, 0x05, 0x2f, 0xb3, 0x93, 0x30, 0x06, 0xe7, 0x17, 0x22, 0x58, + 0x97, 0x41, 0xf5, 0xad, 0x16, 0x7a, 0x93, 0x82, 0xd3, 0x3e, 0x04, 0xd5, 0xe0, 0xed, 0x26, 0x05, + 0x7a, 0x44, 0xec, 0x58, 0xc4, 0x95, 0xe0, 0x37, 0x0a, 0xac, 0x12, 0x40, 0xd2, 0x21, 0x5d, 0xa6, + 0x20, 0xd4, 0xc0, 0x9d, 0x0e, 0x52, 0x75, 0x4b, 0x87, 0xc4, 0x62, 0x11, 0xb0, 0xc7, 0x2c, 0x8f, + 0x9d, 0x2e, 0xce, 0xd3, 0xf4, 0xd4, 0x23, 0xff, 0x53, 0x05, 0x85, 0x90, 0x79, 0xb6, 0x28, 0x40, + 0x65, 0xd5, 0x18, 0x16, 0x26, 0xfc, 0xab, 0xa9, 0xbb, 0x03, 0x33, 0xe7, 0xf4, 0x94, 0xfc, 0x4d, + 0x60, 0xad, 0xbf, 0x6a, 0x6d, 0xd4, 0xf6, 0x4b, 0xb8, 0xd1, 0x5d, 0x5e, 0xbf, 0xee, 0x5c, 0x63, + 0xbb, 0x73, 0x8d, 0xf7, 0x9d, 0x6b, 0x3c, 0xef, 0xdd, 0xd6, 0x76, 0xef, 0xb6, 0xde, 0xf6, 0x6e, + 0xeb, 0xfe, 0xec, 0x41, 0xe8, 0x28, 0x5f, 0x7a, 0x4c, 0xc6, 0x3e, 0xae, 0xe4, 0xf0, 0x9d, 0x96, + 0x9b, 0xf1, 0xd7, 0xcd, 0xe6, 0xfd, 0x72, 0xc8, 0x6c, 0xd9, 0xc1, 0x07, 0x70, 0xf1, 0x11, 0x00, + 0x00, 0xff, 0xff, 0x96, 0xa7, 0xa9, 0x15, 0x1e, 0x02, 0x00, 0x00, } func (m *Resource) Marshal() (dAtA []byte, err error) { @@ -184,6 +231,48 @@ func (m *Resource) MarshalTo(dAtA []byte) (int, error) { } 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 @@ -193,34 +282,27 @@ func (m *Resource) MarshalToSizedBuffer(dAtA []byte) (int, error) { copy(dAtA[i:], m.NextVersionId) i = encodeVarintResource(dAtA, i, uint64(len(m.NextVersionId))) i-- - dAtA[i] = 0x52 + 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] = 0x4a + 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] = 0x42 + 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] = 0x3a - } - 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] = 0x32 } if len(m.MimeType) > 0 { @@ -273,6 +355,23 @@ func encodeVarintResource(dAtA []byte, offset int, v uint64) int { 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 } @@ -298,10 +397,6 @@ func (m *Resource) Size() (n int) { if l > 0 { n += 1 + l + sovResource(uint64(l)) } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovResource(uint64(l)) - } l = len(m.Created) if l > 0 { n += 1 + l + sovResource(uint64(l)) @@ -358,9 +453,9 @@ func (m *Resource) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollectionId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowResource @@ -370,27 +465,115 @@ func (m *Resource) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthResource } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthResource } if postIndex > l { return io.ErrUnexpectedEOF } - m.CollectionId = string(dAtA[iNdEx:postIndex]) + 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 Id", wireType) + 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 { @@ -418,11 +601,11 @@ func (m *Resource) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Id = string(dAtA[iNdEx:postIndex]) + m.CollectionId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -450,11 +633,11 @@ func (m *Resource) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Name = string(dAtA[iNdEx:postIndex]) + m.Id = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 4: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ResourceType", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -482,11 +665,11 @@ func (m *Resource) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ResourceType = string(dAtA[iNdEx:postIndex]) + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 5: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MimeType", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ResourceType", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -514,13 +697,13 @@ func (m *Resource) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.MimeType = string(dAtA[iNdEx:postIndex]) + m.ResourceType = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 6: + case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field MimeType", wireType) } - var byteLen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowResource @@ -530,27 +713,25 @@ func (m *Resource) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if byteLen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthResource } - postIndex := iNdEx + byteLen + postIndex := iNdEx + intStringLen 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{} - } + m.MimeType = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 7: + case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Created", wireType) } @@ -582,7 +763,7 @@ func (m *Resource) Unmarshal(dAtA []byte) error { } m.Created = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 8: + case 7: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Checksum", wireType) } @@ -616,7 +797,7 @@ func (m *Resource) Unmarshal(dAtA []byte) error { m.Checksum = []byte{} } iNdEx = postIndex - case 9: + case 8: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field PreviousVersionId", wireType) } @@ -648,7 +829,7 @@ func (m *Resource) Unmarshal(dAtA []byte) error { } m.PreviousVersionId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 10: + case 9: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field NextVersionId", wireType) } diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go index c9b381ff8..b5a3b0f22 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -13,14 +13,14 @@ func (msg *MsgCreateResourcePayload) GetSignBytes() []byte { func (msg *MsgCreateResourcePayload) ToResource() Resource { return Resource{ - CollectionId: msg.CollectionId, - Id: msg.Id, - Name: msg.Name, - ResourceType: msg.ResourceType, - MimeType: msg.MimeType, - Data: msg.Data, - Created: "", - Checksum: []byte{}, + Header: &ResourceHeader{ + CollectionId: msg.CollectionId, + Id: msg.Id, + Name: msg.Name, + ResourceType: msg.ResourceType, + MimeType: msg.MimeType, + }, + Data: msg.Data, } } From accdcc7d18a0666aa950fb256e9c8be161bd51e4 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Thu, 23 Jun 2022 19:34:25 +0300 Subject: [PATCH 56/65] Fix formatting --- x/resource/keeper/keeper_resource.go | 3 +-- x/resource/tests/constants.go | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index 8355ed2aa..00c5d2a6b 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -173,7 +173,6 @@ func (k Keeper) GetAllResources(ctx *sdk.Context) (list []types.Resource) { defer closeIteratorOrPanic(headerIterator) defer closeIteratorOrPanic(dataIterator) - for headerIterator.Valid() { if !dataIterator.Valid() { panic("number of headers and data don't match") @@ -214,4 +213,4 @@ func closeIteratorOrPanic(iterator sdk.Iterator) { if err != nil { panic(err.Error()) } -} \ No newline at end of file +} diff --git a/x/resource/tests/constants.go b/x/resource/tests/constants.go index 887cb1a68..dc7914d3d 100644 --- a/x/resource/tests/constants.go +++ b/x/resource/tests/constants.go @@ -33,6 +33,6 @@ func ExistingResource() types.Resource { MimeType: JsonResourceType, Checksum: checksum, }, - Data: data, + Data: data, } } From ed2e83d355c37930a277faea6180685732c0ec1b Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Fri, 24 Jun 2022 16:35:03 +0300 Subject: [PATCH 57/65] Extend allowed mime types --- x/resource/utils/mime_type.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/x/resource/utils/mime_type.go b/x/resource/utils/mime_type.go index bbdc5c8d2..6c4dfb667 100644 --- a/x/resource/utils/mime_type.go +++ b/x/resource/utils/mime_type.go @@ -7,7 +7,18 @@ import ( cheqdUtils "github.com/cheqd/cheqd-node/x/cheqd/utils" ) -var AllowedMimeTypes = []string{"application/json", "application/octet-stream", "text/plain"} +var AllowedMimeTypes = []string{ + "application/json", + "application/octet-stream", + "text/plain", + "image/apng", + "image/avif", + "image/gif", + "image/jpeg", + "image/png", + "image/svg+xml", + "image/webp", +} func IsValidMimeType(rt string) bool { return cheqdUtils.Contains(AllowedMimeTypes, rt) From 29195433eefb73267682a10344e2afe33aa77562 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Mon, 27 Jun 2022 14:01:19 +0300 Subject: [PATCH 58/65] Rename mimeType to mediaType --- go.mod | 2 +- proto/resource/v1/query.proto | 2 +- proto/resource/v1/resource.proto | 2 +- proto/resource/v1/tx.proto | 2 +- tests/e2e-bash/tests/test_create_resource.sh | 6 +- .../tests/test_query_all_resource_versions.sh | 16 ++-- .../tests/test_query_collection_resources.sh | 14 ++-- .../client/cli/query_all_resource_versions.go | 6 +- x/resource/client/cli/tx_create_resource.go | 4 +- x/resource/keeper/keeper_resource.go | 8 +- .../keeper/msg_server_create_resource.go | 2 +- .../keeper/query_all_resource_versions.go | 4 +- .../query_server_all_resource_versions.go | 2 +- x/resource/tests/constants.go | 2 +- x/resource/tests/create_resource_test.go | 12 +-- .../tests/query_all_resource_versions_test.go | 4 +- x/resource/tests/query_resource_test.go | 2 +- x/resource/tests/setup.go | 2 +- x/resource/types/query.pb.go | 84 +++++++++---------- x/resource/types/resource.pb.go | 66 +++++++-------- x/resource/types/tx.pb.go | 47 ++++++----- .../types/tx_msg_create_resource_payload.go | 4 +- .../tx_msg_create_resource_payload_test.go | 10 +-- x/resource/types/validate.go | 6 +- x/resource/utils/mime_type.go | 12 +-- x/resource/utils/mime_type_test.go | 4 +- 26 files changed, 163 insertions(+), 162 deletions(-) diff --git a/go.mod b/go.mod index dc6737ee4..e20ff284b 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ 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.5 github.com/cosmos/ibc-go v1.4.0 github.com/go-ozzo/ozzo-validation/v4 v4.3.0 github.com/gogo/protobuf v1.3.3 diff --git a/proto/resource/v1/query.proto b/proto/resource/v1/query.proto index 01edc2ff7..2d7d266f2 100644 --- a/proto/resource/v1/query.proto +++ b/proto/resource/v1/query.proto @@ -41,7 +41,7 @@ message QueryGetAllResourceVersionsRequest { string collection_id = 1; // Mapped to URL path string name = 2; // Mapped to URL parameter `name` string resource_type = 3; // Mapped to URL parameter `resource_type` - string mime_type = 4; // Mapped to URL parameter `mime_type` + string media_type = 4; // Mapped to URL parameter `media_type` } message QueryGetAllResourceVersionsResponse { diff --git a/proto/resource/v1/resource.proto b/proto/resource/v1/resource.proto index f5d070668..b92d4488c 100644 --- a/proto/resource/v1/resource.proto +++ b/proto/resource/v1/resource.proto @@ -14,7 +14,7 @@ message ResourceHeader { string id = 2; string name = 3; string resource_type = 4; - string mime_type = 5; + string media_type = 5; string created = 6; bytes checksum = 7; string previous_version_id = 8; diff --git a/proto/resource/v1/tx.proto b/proto/resource/v1/tx.proto index 036db8ea1..529563b9a 100644 --- a/proto/resource/v1/tx.proto +++ b/proto/resource/v1/tx.proto @@ -22,7 +22,7 @@ message MsgCreateResourcePayload { string id = 2; string name = 3; string resource_type = 4; - string mime_type = 5; + string media_type = 5; bytes data = 6; } diff --git a/tests/e2e-bash/tests/test_create_resource.sh b/tests/e2e-bash/tests/test_create_resource.sh index 9d713ca4a..0b1d921b4 100644 --- a/tests/e2e-bash/tests/test_create_resource.sh +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -45,13 +45,13 @@ assert_tx_successful "$RESULT" RESOURCE_ID=$(uuidgen) RESOURCE_NAME="Resource 1" -RESOURCE_MIME_TYPE="application/json" +RESOURCE_MEDIA_TYPE="application/json" RESOURCE_RESOURCE_TYPE="CL-Schema" RESOURCE_DATA='test data'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource ${ID} ${RESOURCE_ID} "${RESOURCE_NAME}" ${RESOURCE_RESOURCE_TYPE} ${RESOURCE_MIME_TYPE} <(echo "${RESOURCE_DATA}") "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource ${ID} ${RESOURCE_ID} "${RESOURCE_NAME}" ${RESOURCE_RESOURCE_TYPE} ${RESOURCE_MEDIA_TYPE} <(echo "${RESOURCE_DATA}") "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" @@ -65,5 +65,5 @@ 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.mime_type")" "${RESOURCE_MIME_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 index 1e2d7803b..ed77f76c7 100644 --- a/tests/e2e-bash/tests/test_query_all_resource_versions.sh +++ b/tests/e2e-bash/tests/test_query_all_resource_versions.sh @@ -45,7 +45,7 @@ assert_tx_successful "$RESULT" RESOURCE1_V1_ID=$(uuidgen) RESOURCE1_NAME="Resource 1" -RESOURCE1_MIME_TYPE="application/json" +RESOURCE1_MEDIA_TYPE="application/json" RESOURCE1_RESOURCE_TYPE="CL-Schema" RESOURCE1_V1_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; @@ -53,7 +53,7 @@ MSG_CREATE_RESOURCE1='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V1_ID}'", "name": "'${RESOURCE1_NAME}'", - "mime_type": "'${RESOURCE1_MIME_TYPE}'", + "media_type": "'${RESOURCE1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", "data": "'${RESOURCE1_V1_DATA}'" }'; @@ -74,7 +74,7 @@ EXPECTED_RES1_V1_HEADER='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V1_ID}'", "name": "'${RESOURCE1_NAME}'", - "mime_type": "'${RESOURCE1_MIME_TYPE}'", + "media_type": "'${RESOURCE1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'" }' @@ -92,7 +92,7 @@ MSG_CREATE_RESOURCE1_V2='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V2_ID}'", "name": "'${RESOURCE1_NAME}'", - "mime_type": "'${RESOURCE1_MIME_TYPE}'", + "media_type": "'${RESOURCE1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", "data": "'${RESOURCE1_V2_DATA}'" }'; @@ -110,14 +110,14 @@ assert_tx_successful "$RESULT" RESOURCE2_ID=$(uuidgen) RESOURCE2_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhdGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; RESOURCE2_NAME="Resource 2" -RESOURCE2_MIME_TYPE="application/json" +RESOURCE2_MEDIA_TYPE="application/json" RESOURCE2_RESOURCE_TYPE="CL-Schema" MSG_CREATE_RESOURCE2='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE2_ID}'", "name": "'${RESOURCE2_NAME}'", - "mime_type": "'${RESOURCE2_MIME_TYPE}'", + "media_type": "'${RESOURCE2_MEDIA_TYPE}'", "resource_type": "'${RESOURCE2_RESOURCE_TYPE}'", "data": "'${RESOURCE2_DATA}'" }'; @@ -136,12 +136,12 @@ EXPECTED_RES1_V2_HEADER='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V2_ID}'", "name": "'${RESOURCE1_NAME}'", - "mime_type": "'${RESOURCE1_MIME_TYPE}'", + "media_type": "'${RESOURCE1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'" }' # shellcheck disable=SC2086 -RESULT=$(cheqd-noded query resource all-resource-versions "${ID1}" "${RESOURCE1_NAME}" ${RESOURCE1_RESOURCE_TYPE} ${RESOURCE1_MIME_TYPE} ${QUERY_PARAMS}) +RESULT=$(cheqd-noded query resource all-resource-versions "${ID1}" "${RESOURCE1_NAME}" ${RESOURCE1_RESOURCE_TYPE} ${RESOURCE1_MEDIA_TYPE} ${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}" diff --git a/tests/e2e-bash/tests/test_query_collection_resources.sh b/tests/e2e-bash/tests/test_query_collection_resources.sh index e13411ec0..9e0e0fb45 100644 --- a/tests/e2e-bash/tests/test_query_collection_resources.sh +++ b/tests/e2e-bash/tests/test_query_collection_resources.sh @@ -45,7 +45,7 @@ assert_tx_successful "$RESULT" RESOURCE1_V1_ID=$(uuidgen) RESOURCE1_V1_NAME="Resource 1" -RESOURCE1_V1_MIME_TYPE="application/json" +RESOURCE1_V1_MEDIA_TYPE="application/json" RESOURCE1_V1_RESOURCE_TYPE="CL-Schema" RESOURCE1_V1_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; @@ -53,7 +53,7 @@ MSG_CREATE_RESOURCE1='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V1_ID}'", "name": "'${RESOURCE1_V1_NAME}'", - "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", + "media_type": "'${RESOURCE1_V1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", "data": "'${RESOURCE1_V1_DATA}'" }'; @@ -74,7 +74,7 @@ EXPECTED_RES1_V1_HEADER='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V1_ID}'", "name": "'${RESOURCE1_V1_NAME}'", - "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", + "media_type": "'${RESOURCE1_V1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'" }' @@ -92,7 +92,7 @@ MSG_CREATE_RESOURCE1_V2='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V2_ID}'", "name": "'${RESOURCE1_V1_NAME}'", - "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", + "media_type": "'${RESOURCE1_V1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", "data": "'${RESOURCE1_V2_DATA}'" }'; @@ -137,14 +137,14 @@ assert_tx_successful "$RESULT" RESOURCE2_ID=$(uuidgen) RESOURCE2_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhdGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; RESOURCE2_NAME="Resource 2" -RESOURCE2_MIME_TYPE="application/json" +RESOURCE2_MEDIA_TYPE="application/json" RESOURCE2_RESOURCE_TYPE="CL-Schema" MSG_CREATE_RESOURCE2='{ "collection_id": "'${ID2}'", "id": "'${RESOURCE2_ID}'", "name": "'${RESOURCE2_NAME}'", - "mime_type": "'${RESOURCE2_MIME_TYPE}'", + "media_type": "'${RESOURCE2_MEDIA_TYPE}'", "resource_type": "'${RESOURCE2_RESOURCE_TYPE}'", "data": "'${RESOURCE2_DATA}'" }'; @@ -163,7 +163,7 @@ EXPECTED_RES1_V2_HEADER='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V2_ID}'", "name": "'${RESOURCE1_V1_NAME}'", - "mime_type": "'${RESOURCE1_V1_MIME_TYPE}'", + "media_type": "'${RESOURCE1_V1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'" }' diff --git a/x/resource/client/cli/query_all_resource_versions.go b/x/resource/client/cli/query_all_resource_versions.go index 5765bf019..97be4756c 100644 --- a/x/resource/client/cli/query_all_resource_versions.go +++ b/x/resource/client/cli/query_all_resource_versions.go @@ -11,7 +11,7 @@ import ( func CmdGetAllResourceVersions() *cobra.Command { cmd := &cobra.Command{ - Use: "all-resource-versions [collectionId] [name] [resourceType] [mimeType]", + Use: "all-resource-versions [collectionId] [name] [resourceType] [mediaType]", Short: "Query all resource versions", Args: cobra.ExactArgs(4), RunE: func(cmd *cobra.Command, args []string) error { @@ -22,13 +22,13 @@ func CmdGetAllResourceVersions() *cobra.Command { collectionId := args[0] name := args[1] resourceType := args[2] - mimeType := args[3] + mediaType := args[3] params := &types.QueryGetAllResourceVersionsRequest{ CollectionId: collectionId, Name: name, ResourceType: resourceType, - MimeType: mimeType, + MediaType: mediaType, } resp, err := queryClient.AllResourceVersions(context.Background(), params) diff --git a/x/resource/client/cli/tx_create_resource.go b/x/resource/client/cli/tx_create_resource.go index d80cb7d07..b16192098 100644 --- a/x/resource/client/cli/tx_create_resource.go +++ b/x/resource/client/cli/tx_create_resource.go @@ -32,7 +32,7 @@ func CmdCreateResource() *cobra.Command { id := args[1] name := args[2] resourceType := args[3] - mimeType := args[4] + mediaType := args[4] data, err := ioutil.ReadFile(args[5]) if err != nil { @@ -45,7 +45,7 @@ func CmdCreateResource() *cobra.Command { Id: id, Name: name, ResourceType: resourceType, - MimeType: mimeType, + MediaType: mediaType, Data: data, } diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index 00c5d2a6b..f2d0aacd9 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -88,7 +88,7 @@ func (k Keeper) HasResource(ctx *sdk.Context, collectionId string, id string) bo return store.Has(GetResourceHeaderKeyBytes(collectionId, id)) } -func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) []*types.ResourceHeader { +func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, resourceType, mediaType string) []*types.ResourceHeader { store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, GetResourceHeaderCollectionPrefixBytes(collectionId)) @@ -102,7 +102,7 @@ func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, res if val.Name == name && val.ResourceType == resourceType && - val.MimeType == mimeType { + val.MediaType == mediaType { result = append(result, &val) } } @@ -128,7 +128,7 @@ func (k Keeper) GetResourceCollection(ctx *sdk.Context, collectionId string) []* return resources } -func (k Keeper) GetLastResourceVersionHeader(ctx *sdk.Context, collectionId, name, resourceType, mimeType string) (types.ResourceHeader, bool) { +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) @@ -139,7 +139,7 @@ func (k Keeper) GetLastResourceVersionHeader(ctx *sdk.Context, collectionId, nam if val.Name == name && val.ResourceType == resourceType && - val.MimeType == mimeType && + val.MediaType == mediaType && val.NextVersionId == "" { return val, true } diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 3f9f5baa6..eb8b225cf 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -49,7 +49,7 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes resource.Header.Created = time.Now().UTC().Format(time.RFC3339) // 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.MimeType) + 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 diff --git a/x/resource/keeper/query_all_resource_versions.go b/x/resource/keeper/query_all_resource_versions.go index b7860f918..addd68786 100644 --- a/x/resource/keeper/query_all_resource_versions.go +++ b/x/resource/keeper/query_all_resource_versions.go @@ -8,14 +8,14 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -func allResourceVersions(ctx sdk.Context, keeper Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *codec.LegacyAmino, collectionId, name, resourceType, mimeType string) ([]byte, error) { +func allResourceVersions(ctx sdk.Context, keeper Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *codec.LegacyAmino, collectionId, name, resourceType, mediaType string) ([]byte, error) { queryServer := NewQueryServer(keeper, cheqdKeeper) resp, err := queryServer.AllResourceVersions(sdk.WrapSDKContext(ctx), &types.QueryGetAllResourceVersionsRequest{ CollectionId: collectionId, Name: name, ResourceType: resourceType, - MimeType: mimeType, + MediaType: mediaType, }) if err != nil { return nil, err diff --git a/x/resource/keeper/query_server_all_resource_versions.go b/x/resource/keeper/query_server_all_resource_versions.go index d3db32847..f4e42d9f7 100644 --- a/x/resource/keeper/query_server_all_resource_versions.go +++ b/x/resource/keeper/query_server_all_resource_versions.go @@ -26,7 +26,7 @@ func (m queryServer) AllResourceVersions(c context.Context, req *types.QueryGetA } // Get all versions - versions := m.GetAllResourceVersions(&ctx, req.CollectionId, req.Name, req.ResourceType, req.MimeType) + versions := m.GetAllResourceVersions(&ctx, req.CollectionId, req.Name, req.ResourceType, req.MediaType) return &types.QueryGetAllResourceVersionsResponse{ Resources: versions, diff --git a/x/resource/tests/constants.go b/x/resource/tests/constants.go index dc7914d3d..6f2befe27 100644 --- a/x/resource/tests/constants.go +++ b/x/resource/tests/constants.go @@ -30,7 +30,7 @@ func ExistingResource() types.Resource { Id: "a09abea0-22e0-4b35-8f70-9cc3a6d0b5fd", Name: "Existing Resource Name", ResourceType: CLSchemaType, - MimeType: JsonResourceType, + MediaType: JsonResourceType, Checksum: checksum, }, Data: data, diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index 6124777bd..1bf251971 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -36,7 +36,7 @@ func TestCreateResource(t *testing.T) { Id: ResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, - MimeType: JsonResourceType, + MediaType: JsonResourceType, Data: []byte(SchemaData), }, previousVersionId: "", @@ -52,7 +52,7 @@ func TestCreateResource(t *testing.T) { Id: ResourceId, Name: ExistingResource().Header.Name, ResourceType: ExistingResource().Header.ResourceType, - MimeType: ExistingResource().Header.MimeType, + MediaType: ExistingResource().Header.MediaType, Data: ExistingResource().Data, }, previousVersionId: ExistingResource().Header.Id, @@ -66,7 +66,7 @@ func TestCreateResource(t *testing.T) { Id: ResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, - MimeType: JsonResourceType, + MediaType: JsonResourceType, Data: []byte(SchemaData), }, errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), @@ -80,7 +80,7 @@ func TestCreateResource(t *testing.T) { Id: IncorrectResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, - MimeType: JsonResourceType, + MediaType: JsonResourceType, Data: []byte(SchemaData), }, errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), @@ -94,7 +94,7 @@ func TestCreateResource(t *testing.T) { Id: IncorrectResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, - MimeType: JsonResourceType, + MediaType: JsonResourceType, Data: []byte(SchemaData), }, errMsg: fmt.Sprintf("did:cheqd:test:%s: not found", NotFoundDIDIdentifier), @@ -117,7 +117,7 @@ func TestCreateResource(t *testing.T) { require.Equal(t, tc.msg.CollectionId, resource.Header.CollectionId) require.Equal(t, tc.msg.Id, resource.Header.Id) - require.Equal(t, tc.msg.MimeType, resource.Header.MimeType) + require.Equal(t, tc.msg.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) diff --git a/x/resource/tests/query_all_resource_versions_test.go b/x/resource/tests/query_all_resource_versions_test.go index 8c0aeff9b..6d066de4d 100644 --- a/x/resource/tests/query_all_resource_versions_test.go +++ b/x/resource/tests/query_all_resource_versions_test.go @@ -41,7 +41,7 @@ func TestQueryGetAllResourceVersions(t *testing.T) { CollectionId: ExistingDIDIdentifier, Name: existingResource.Header.Name, ResourceType: existingResource.Header.ResourceType, - MimeType: existingResource.Header.MimeType, + MediaType: existingResource.Header.MediaType, }, response: &types.QueryGetAllResourceVersionsResponse{ Resources: []*types.ResourceHeader{existingResource.Header}, @@ -55,7 +55,7 @@ func TestQueryGetAllResourceVersions(t *testing.T) { CollectionId: NotFoundDIDIdentifier, Name: existingResource.Header.Name, ResourceType: existingResource.Header.ResourceType, - MimeType: existingResource.Header.MimeType, + MediaType: existingResource.Header.MediaType, }, response: nil, errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), diff --git a/x/resource/tests/query_resource_test.go b/x/resource/tests/query_resource_test.go index a04a5d29b..1cfd044f4 100644 --- a/x/resource/tests/query_resource_test.go +++ b/x/resource/tests/query_resource_test.go @@ -68,7 +68,7 @@ func TestQueryGetResource(t *testing.T) { 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.MimeType, resource.Header.MimeType) + 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) diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go index 2ca17079f..4380d905c 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -95,7 +95,7 @@ func GenerateCreateResourcePayload(resource types.Resource) *types.MsgCreateReso Id: resource.Header.Id, Name: resource.Header.Name, ResourceType: resource.Header.ResourceType, - MimeType: resource.Header.MimeType, + MediaType: resource.Header.MediaType, Data: resource.Data, } } diff --git a/x/resource/types/query.pb.go b/x/resource/types/query.pb.go index 2becdb646..aa83939ac 100644 --- a/x/resource/types/query.pb.go +++ b/x/resource/types/query.pb.go @@ -216,7 +216,7 @@ 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"` ResourceType string `protobuf:"bytes,3,opt,name=resource_type,json=resourceType,proto3" json:"resource_type,omitempty"` - MimeType string `protobuf:"bytes,4,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"` + MediaType string `protobuf:"bytes,4,opt,name=media_type,json=mediaType,proto3" json:"media_type,omitempty"` } func (m *QueryGetAllResourceVersionsRequest) Reset() { *m = QueryGetAllResourceVersionsRequest{} } @@ -273,9 +273,9 @@ func (m *QueryGetAllResourceVersionsRequest) GetResourceType() string { return "" } -func (m *QueryGetAllResourceVersionsRequest) GetMimeType() string { +func (m *QueryGetAllResourceVersionsRequest) GetMediaType() string { if m != nil { - return m.MimeType + return m.MediaType } return "" } @@ -336,39 +336,39 @@ func init() { func init() { proto.RegisterFile("resource/v1/query.proto", fileDescriptor_10aac3b48339734d) } var fileDescriptor_10aac3b48339734d = []byte{ - // 509 bytes of a gzipped FileDescriptorProto + // 510 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xc1, 0x6e, 0xd3, 0x40, - 0x10, 0xcd, 0xa6, 0x01, 0x25, 0x5b, 0xe0, 0xb0, 0x3d, 0xd4, 0x32, 0x60, 0x55, 0xee, 0x81, 0x0a, - 0xb5, 0x5e, 0x92, 0x0a, 0x7a, 0xe0, 0xd4, 0x56, 0x02, 0x2a, 0x24, 0x24, 0x22, 0xc4, 0x81, 0x4b, - 0xe4, 0x7a, 0x87, 0x74, 0x25, 0xc7, 0xeb, 0x78, 0x9d, 0x88, 0xa8, 0xea, 0x85, 0x2f, 0x40, 0xe2, - 0x03, 0xf8, 0x09, 0x3e, 0x82, 0x63, 0x24, 0x2e, 0x70, 0x43, 0x09, 0x57, 0xfe, 0x01, 0xed, 0xc6, - 0xeb, 0x14, 0x91, 0x04, 0x5b, 0xa8, 0x17, 0xdb, 0xda, 0x99, 0xf7, 0xe6, 0xbd, 0x99, 0x59, 0xe3, - 0xcd, 0x04, 0xa4, 0x18, 0x24, 0x01, 0xd0, 0x61, 0x93, 0xf6, 0x07, 0x90, 0x8c, 0xbc, 0x38, 0x11, - 0xa9, 0x20, 0x77, 0x83, 0x33, 0xe8, 0x33, 0xce, 0x3c, 0xfd, 0x8e, 0x04, 0x03, 0xcf, 0xa4, 0x7a, - 0xc3, 0xa6, 0x7d, 0xa7, 0x2b, 0x44, 0x37, 0x04, 0xea, 0xc7, 0x9c, 0xfa, 0x51, 0x24, 0x52, 0x3f, - 0xe5, 0x22, 0x92, 0x33, 0xb0, 0x6d, 0x5f, 0x66, 0xcd, 0x61, 0x3a, 0xe6, 0xbe, 0xc0, 0x9b, 0x2f, - 0x55, 0x9d, 0xa7, 0x90, 0xb6, 0xb3, 0x48, 0x1b, 0xfa, 0x03, 0x90, 0x29, 0xd9, 0xc6, 0x37, 0x03, - 0x11, 0x86, 0x10, 0x28, 0xae, 0x0e, 0x67, 0x16, 0xda, 0x42, 0x3b, 0x8d, 0xf6, 0x8d, 0xf9, 0xe1, - 0x09, 0x23, 0xb7, 0x70, 0x95, 0x33, 0xab, 0xaa, 0x23, 0x55, 0xce, 0xdc, 0x0e, 0xb6, 0xfe, 0xe6, - 0x93, 0xb1, 0x88, 0x24, 0x90, 0x63, 0x5c, 0x37, 0xd5, 0x35, 0xd7, 0x7a, 0xeb, 0x9e, 0xb7, 0xd2, - 0x97, 0x97, 0x53, 0xe4, 0x40, 0xf7, 0x04, 0xbb, 0xa6, 0xc0, 0x71, 0x2e, 0xc4, 0xe4, 0xc9, 0x32, - 0xda, 0xdd, 0x04, 0x6f, 0xaf, 0xa4, 0xca, 0x64, 0x3f, 0xc7, 0x0d, 0x53, 0x5d, 0x5a, 0x68, 0x6b, - 0x6d, 0x67, 0xbd, 0xb5, 0x57, 0x50, 0xf7, 0x33, 0xf0, 0x19, 0x24, 0xed, 0x39, 0xde, 0xfd, 0x84, - 0xe6, 0xfa, 0x0f, 0xc3, 0xd0, 0x24, 0xbe, 0x86, 0x44, 0xaa, 0x89, 0x95, 0xea, 0x3d, 0xc1, 0xb5, - 0xc8, 0xef, 0x41, 0xd6, 0x7d, 0xfd, 0xad, 0x80, 0xa6, 0x58, 0x27, 0x1d, 0xc5, 0x60, 0xad, 0xcd, - 0x80, 0xe6, 0xf0, 0xd5, 0x28, 0x06, 0x72, 0x1b, 0x37, 0x7a, 0xbc, 0x97, 0x25, 0xd4, 0x74, 0x42, - 0x5d, 0x1d, 0xa8, 0xe0, 0xe5, 0xae, 0x2c, 0x14, 0x78, 0x05, 0x5d, 0x69, 0xfd, 0xaa, 0xe1, 0x6b, - 0xba, 0x28, 0xf9, 0x8c, 0x70, 0xdd, 0xe4, 0x91, 0x47, 0xff, 0x20, 0x5c, 0xb2, 0xb9, 0xf6, 0x41, - 0x69, 0xdc, 0xcc, 0x94, 0x7b, 0xf0, 0xfe, 0xeb, 0xcf, 0x8f, 0xd5, 0x26, 0xa1, 0xb4, 0xe9, 0x3d, - 0xa0, 0x9c, 0x41, 0x94, 0xf2, 0xb7, 0x1c, 0x12, 0x49, 0xcf, 0xff, 0x18, 0xc7, 0x45, 0x7e, 0x8d, - 0x24, 0x3d, 0xe7, 0xec, 0x82, 0x8c, 0x11, 0xde, 0x58, 0xb0, 0x43, 0xe4, 0xb0, 0xa0, 0x92, 0xe5, - 0xab, 0x6c, 0x1f, 0xfd, 0x0f, 0x45, 0xe6, 0xab, 0xa5, 0x7d, 0xed, 0x92, 0xfb, 0xc5, 0x7d, 0x91, - 0xef, 0x08, 0x6f, 0x2c, 0x58, 0x80, 0xc2, 0x96, 0x96, 0x6f, 0x77, 0x61, 0x4b, 0x2b, 0xf6, 0xcf, - 0x7d, 0xac, 0x2d, 0x3d, 0x24, 0xfb, 0x25, 0x46, 0x35, 0xcc, 0x48, 0x8e, 0x9e, 0x7c, 0x99, 0x38, - 0x68, 0x3c, 0x71, 0xd0, 0x8f, 0x89, 0x83, 0x3e, 0x4c, 0x9d, 0xca, 0x78, 0xea, 0x54, 0xbe, 0x4d, - 0x9d, 0xca, 0x9b, 0xdd, 0x2e, 0x4f, 0xcf, 0x06, 0xa7, 0x5e, 0x20, 0x7a, 0x54, 0x8b, 0x9b, 0x3d, - 0xf7, 0x94, 0x46, 0xfa, 0x2e, 0xe7, 0xa2, 0xea, 0xea, 0xc8, 0xd3, 0xeb, 0xfa, 0x27, 0xba, 0xff, - 0x3b, 0x00, 0x00, 0xff, 0xff, 0xc7, 0x26, 0x62, 0xc6, 0xb8, 0x05, 0x00, 0x00, + 0x10, 0xcd, 0xa6, 0x01, 0x35, 0x5b, 0xe0, 0xb0, 0x3d, 0xd4, 0xb2, 0xa8, 0x55, 0xb9, 0x07, 0x2a, + 0xd4, 0x7a, 0x49, 0x2a, 0xe8, 0x81, 0x53, 0x5b, 0x09, 0xa8, 0x90, 0x90, 0x88, 0x10, 0x07, 0x2e, + 0x91, 0xeb, 0x1d, 0xd2, 0x95, 0x1c, 0xaf, 0xe3, 0xdd, 0x44, 0x44, 0x55, 0x2f, 0x7c, 0x01, 0x12, + 0x5f, 0xc0, 0x3f, 0xf0, 0x11, 0x1c, 0x23, 0x71, 0x81, 0x1b, 0x4a, 0xb8, 0xf2, 0x0f, 0xc8, 0x6b, + 0xaf, 0x13, 0x44, 0x12, 0x1c, 0xa1, 0x5e, 0x6c, 0x6b, 0x67, 0xde, 0x9b, 0xf7, 0x66, 0x66, 0x8d, + 0xb7, 0x12, 0x90, 0xa2, 0x9f, 0x04, 0x40, 0x07, 0x0d, 0xda, 0xeb, 0x43, 0x32, 0xf4, 0xe2, 0x44, + 0x28, 0x41, 0xb6, 0x83, 0x0b, 0xe8, 0x31, 0xce, 0x3c, 0xfd, 0x8e, 0x04, 0x03, 0xcf, 0xa4, 0x7a, + 0x83, 0x86, 0x7d, 0xb7, 0x23, 0x44, 0x27, 0x04, 0xea, 0xc7, 0x9c, 0xfa, 0x51, 0x24, 0x94, 0xaf, + 0xb8, 0x88, 0x64, 0x06, 0xb6, 0xed, 0x59, 0xd6, 0x02, 0xa6, 0x63, 0xee, 0x0b, 0xbc, 0xf5, 0x32, + 0xad, 0xf3, 0x14, 0x54, 0x2b, 0x8f, 0xb4, 0xa0, 0xd7, 0x07, 0xa9, 0xc8, 0x2e, 0xbe, 0x1d, 0x88, + 0x30, 0x84, 0x20, 0xe5, 0x6a, 0x73, 0x66, 0xa1, 0x1d, 0xb4, 0x57, 0x6f, 0xdd, 0x9a, 0x1e, 0x9e, + 0x31, 0x72, 0x07, 0x57, 0x39, 0xb3, 0xaa, 0x3a, 0x52, 0xe5, 0xcc, 0x6d, 0x63, 0xeb, 0x6f, 0x3e, + 0x19, 0x8b, 0x48, 0x02, 0x39, 0xc5, 0xeb, 0xa6, 0xba, 0xe6, 0xda, 0x68, 0xde, 0xf3, 0x96, 0xfa, + 0xf2, 0x0a, 0x8a, 0x02, 0xe8, 0x9e, 0x61, 0xd7, 0x14, 0x38, 0x2d, 0x84, 0x98, 0x3c, 0xb9, 0x8a, + 0x76, 0x37, 0xc1, 0xbb, 0x4b, 0xa9, 0x72, 0xd9, 0xcf, 0x71, 0xdd, 0x54, 0x97, 0x16, 0xda, 0x59, + 0xdb, 0xdb, 0x68, 0x1e, 0x94, 0xd4, 0xfd, 0x0c, 0x7c, 0x06, 0x49, 0x6b, 0x8a, 0x77, 0x3f, 0xa1, + 0xa9, 0xfe, 0xe3, 0x30, 0x34, 0x89, 0xaf, 0x21, 0x91, 0xe9, 0xc4, 0x56, 0xea, 0x3d, 0xc1, 0xb5, + 0xc8, 0xef, 0x42, 0xde, 0x7d, 0xfd, 0x9d, 0x02, 0x4d, 0xb1, 0xb6, 0x1a, 0xc6, 0x60, 0xad, 0x65, + 0x40, 0x73, 0xf8, 0x6a, 0x18, 0x03, 0xd9, 0xc6, 0xb8, 0x0b, 0x8c, 0xfb, 0x59, 0x46, 0x4d, 0x67, + 0xd4, 0xf5, 0x49, 0x1a, 0x9e, 0xed, 0xcb, 0x5c, 0x89, 0xd7, 0xd0, 0x97, 0xe6, 0xaf, 0x1a, 0xbe, + 0xa1, 0x8b, 0x92, 0xcf, 0x08, 0xaf, 0x9b, 0x3c, 0xf2, 0xe8, 0x1f, 0x84, 0x0b, 0x76, 0xd7, 0x3e, + 0x5a, 0x19, 0x97, 0x99, 0x72, 0x8f, 0xde, 0x7f, 0xfd, 0xf9, 0xb1, 0xda, 0x20, 0x94, 0x36, 0xbc, + 0x07, 0x94, 0x33, 0x88, 0x14, 0x7f, 0xcb, 0x21, 0x91, 0xf4, 0xf2, 0x8f, 0x81, 0x5c, 0x15, 0x17, + 0x49, 0xd2, 0x4b, 0xce, 0xae, 0xc8, 0x08, 0xe1, 0xcd, 0x39, 0x5b, 0x44, 0x8e, 0x4b, 0x2a, 0x59, + 0xbc, 0xcc, 0xf6, 0xc9, 0xff, 0x50, 0xe4, 0xbe, 0x9a, 0xda, 0xd7, 0x3e, 0xb9, 0x5f, 0xde, 0x17, + 0xf9, 0x8e, 0xf0, 0xe6, 0x9c, 0x05, 0x28, 0x6d, 0x69, 0xf1, 0x7e, 0x97, 0xb6, 0xb4, 0x64, 0xff, + 0xdc, 0xc7, 0xda, 0xd2, 0x43, 0x72, 0xb8, 0xc2, 0xa8, 0x06, 0x39, 0xc9, 0xc9, 0x93, 0x2f, 0x63, + 0x07, 0x8d, 0xc6, 0x0e, 0xfa, 0x31, 0x76, 0xd0, 0x87, 0x89, 0x53, 0x19, 0x4d, 0x9c, 0xca, 0xb7, + 0x89, 0x53, 0x79, 0xb3, 0xdf, 0xe1, 0xea, 0xa2, 0x7f, 0xee, 0x05, 0xa2, 0x4b, 0xb5, 0xb8, 0xec, + 0x79, 0x90, 0x6a, 0xa4, 0xef, 0x0a, 0x2e, 0x9a, 0xde, 0x1d, 0x79, 0x7e, 0x53, 0xff, 0x46, 0x0f, + 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0x4b, 0xc7, 0xfa, 0x53, 0xba, 0x05, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -682,10 +682,10 @@ func (m *QueryGetAllResourceVersionsRequest) MarshalToSizedBuffer(dAtA []byte) ( _ = i var l int _ = l - if len(m.MimeType) > 0 { - i -= len(m.MimeType) - copy(dAtA[i:], m.MimeType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.MimeType))) + if len(m.MediaType) > 0 { + i -= len(m.MediaType) + copy(dAtA[i:], m.MediaType) + i = encodeVarintQuery(dAtA, i, uint64(len(m.MediaType))) i-- dAtA[i] = 0x22 } @@ -837,7 +837,7 @@ func (m *QueryGetAllResourceVersionsRequest) Size() (n int) { if l > 0 { n += 1 + l + sovQuery(uint64(l)) } - l = len(m.MimeType) + l = len(m.MediaType) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } @@ -1358,7 +1358,7 @@ func (m *QueryGetAllResourceVersionsRequest) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MimeType", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field MediaType", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1386,7 +1386,7 @@ func (m *QueryGetAllResourceVersionsRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.MimeType = string(dAtA[iNdEx:postIndex]) + m.MediaType = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex diff --git a/x/resource/types/resource.pb.go b/x/resource/types/resource.pb.go index e040e8dc3..bfd0792f7 100644 --- a/x/resource/types/resource.pb.go +++ b/x/resource/types/resource.pb.go @@ -79,7 +79,7 @@ type ResourceHeader struct { 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"` - MimeType string `protobuf:"bytes,5,opt,name=mime_type,json=mimeType,proto3" json:"mime_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"` @@ -147,9 +147,9 @@ func (m *ResourceHeader) GetResourceType() string { return "" } -func (m *ResourceHeader) GetMimeType() string { +func (m *ResourceHeader) GetMediaType() string { if m != nil { - return m.MimeType + return m.MediaType } return "" } @@ -190,29 +190,29 @@ func init() { func init() { proto.RegisterFile("resource/v1/resource.proto", fileDescriptor_cebae6241f1ea243) } var fileDescriptor_cebae6241f1ea243 = []byte{ - // 347 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x52, 0xcd, 0x4e, 0xea, 0x40, - 0x14, 0xa6, 0xbd, 0x5c, 0x68, 0xe7, 0x02, 0x37, 0x77, 0xee, 0xa6, 0xc1, 0xd8, 0x10, 0x4c, 0x0c, - 0x0b, 0x69, 0x83, 0xbe, 0x81, 0x89, 0x46, 0xb6, 0x8d, 0x71, 0xe1, 0x86, 0x94, 0x99, 0x13, 0x3b, - 0x91, 0x76, 0xea, 0x74, 0xda, 0xc0, 0x5b, 0xf8, 0x1a, 0xbe, 0x89, 0x4b, 0x96, 0x2e, 0x0d, 0xbc, - 0x88, 0xe9, 0xa1, 0xad, 0xba, 0x71, 0xd3, 0x9e, 0xf3, 0xfd, 0xcd, 0x9c, 0x9c, 0x21, 0x43, 0x05, - 0x99, 0xcc, 0x15, 0x03, 0xbf, 0x98, 0xf9, 0x75, 0xed, 0xa5, 0x4a, 0x6a, 0x49, 0x8f, 0x59, 0x04, - 0x4f, 0x5c, 0x70, 0x0f, 0xff, 0x89, 0xe4, 0xe0, 0x35, 0x8a, 0x62, 0x36, 0x06, 0x62, 0x05, 0x55, - 0x4b, 0xaf, 0x48, 0x27, 0x82, 0x90, 0x83, 0x72, 0x8c, 0x91, 0x31, 0xf9, 0x73, 0x3e, 0xf5, 0x7e, - 0xf4, 0x7a, 0xb5, 0xf1, 0x06, 0x4d, 0x41, 0x65, 0xa6, 0x94, 0xb4, 0x79, 0xa8, 0x43, 0xc7, 0x1c, - 0x19, 0x93, 0x5e, 0x80, 0xf5, 0xf8, 0xc5, 0x24, 0x83, 0xef, 0x72, 0x7a, 0x42, 0xfa, 0x4c, 0xae, - 0x56, 0xc0, 0xb4, 0x90, 0xc9, 0x42, 0x70, 0x3c, 0xd4, 0x0e, 0x7a, 0x9f, 0xe0, 0x9c, 0xd3, 0x01, - 0x31, 0x05, 0xc7, 0x24, 0x3b, 0x30, 0x05, 0x2f, 0xb3, 0x93, 0x30, 0x06, 0xe7, 0x17, 0x22, 0x58, - 0x97, 0x41, 0xf5, 0xad, 0x16, 0x7a, 0x93, 0x82, 0xd3, 0x3e, 0x04, 0xd5, 0xe0, 0xed, 0x26, 0x05, - 0x7a, 0x44, 0xec, 0x58, 0xc4, 0x95, 0xe0, 0x37, 0x0a, 0xac, 0x12, 0x40, 0xd2, 0x21, 0x5d, 0xa6, - 0x20, 0xd4, 0xc0, 0x9d, 0x0e, 0x52, 0x75, 0x4b, 0x87, 0xc4, 0x62, 0x11, 0xb0, 0xc7, 0x2c, 0x8f, - 0x9d, 0x2e, 0xce, 0xd3, 0xf4, 0xd4, 0x23, 0xff, 0x53, 0x05, 0x85, 0x90, 0x79, 0xb6, 0x28, 0x40, - 0x65, 0xd5, 0x18, 0x16, 0x26, 0xfc, 0xab, 0xa9, 0xbb, 0x03, 0x33, 0xe7, 0xf4, 0x94, 0xfc, 0x4d, - 0x60, 0xad, 0xbf, 0x6a, 0x6d, 0xd4, 0xf6, 0x4b, 0xb8, 0xd1, 0x5d, 0x5e, 0xbf, 0xee, 0x5c, 0x63, - 0xbb, 0x73, 0x8d, 0xf7, 0x9d, 0x6b, 0x3c, 0xef, 0xdd, 0xd6, 0x76, 0xef, 0xb6, 0xde, 0xf6, 0x6e, - 0xeb, 0xfe, 0xec, 0x41, 0xe8, 0x28, 0x5f, 0x7a, 0x4c, 0xc6, 0x3e, 0xae, 0xe4, 0xf0, 0x9d, 0x96, - 0x9b, 0xf1, 0xd7, 0xcd, 0xe6, 0xfd, 0x72, 0xc8, 0x6c, 0xd9, 0xc1, 0x07, 0x70, 0xf1, 0x11, 0x00, - 0x00, 0xff, 0xff, 0x96, 0xa7, 0xa9, 0x15, 0x1e, 0x02, 0x00, 0x00, + // 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) { @@ -305,10 +305,10 @@ func (m *ResourceHeader) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x32 } - if len(m.MimeType) > 0 { - i -= len(m.MimeType) - copy(dAtA[i:], m.MimeType) - i = encodeVarintResource(dAtA, i, uint64(len(m.MimeType))) + 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 } @@ -393,7 +393,7 @@ func (m *ResourceHeader) Size() (n int) { if l > 0 { n += 1 + l + sovResource(uint64(l)) } - l = len(m.MimeType) + l = len(m.MediaType) if l > 0 { n += 1 + l + sovResource(uint64(l)) } @@ -701,7 +701,7 @@ func (m *ResourceHeader) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MimeType", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field MediaType", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -729,7 +729,7 @@ func (m *ResourceHeader) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.MimeType = string(dAtA[iNdEx:postIndex]) + m.MediaType = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 6: if wireType != 2 { diff --git a/x/resource/types/tx.pb.go b/x/resource/types/tx.pb.go index c5b5ebca8..45afb731c 100644 --- a/x/resource/types/tx.pb.go +++ b/x/resource/types/tx.pb.go @@ -86,7 +86,7 @@ type MsgCreateResourcePayload struct { 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"` - MimeType string `protobuf:"bytes,5,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"` + MediaType string `protobuf:"bytes,5,opt,name=media_type,json=mediaType,proto3" json:"media_type,omitempty"` Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` } @@ -151,9 +151,9 @@ func (m *MsgCreateResourcePayload) GetResourceType() string { return "" } -func (m *MsgCreateResourcePayload) GetMimeType() string { +func (m *MsgCreateResourcePayload) GetMediaType() string { if m != nil { - return m.MimeType + return m.MediaType } return "" } @@ -218,7 +218,7 @@ func init() { func init() { proto.RegisterFile("resource/v1/tx.proto", fileDescriptor_f5b76d41c4c62339) } var fileDescriptor_f5b76d41c4c62339 = []byte{ - // 399 bytes of a gzipped FileDescriptorProto + // 401 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, @@ -228,22 +228,23 @@ var fileDescriptor_f5b76d41c4c62339 = []byte{ 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, 0xed, 0x64, 0xe4, + 0x23, 0x83, 0x33, 0xd3, 0xf3, 0x3c, 0xf3, 0xd2, 0xf2, 0x83, 0x90, 0xf4, 0x29, 0xed, 0x66, 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, 0xaa, 0x90, 0x34, 0x17, 0x67, 0x6e, - 0x66, 0x2e, 0x54, 0x01, 0x2b, 0x58, 0x01, 0x07, 0x48, 0x00, 0x2c, 0x29, 0xc4, 0xc5, 0x92, 0x92, - 0x58, 0x92, 0x28, 0xc1, 0xa6, 0xc0, 0xa8, 0xc1, 0x13, 0x04, 0x66, 0x2b, 0x25, 0x70, 0x49, 0x62, - 0x38, 0x3d, 0x28, 0xb5, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, 0xc8, 0x99, 0x8b, 0x03, 0x66, 0x3a, - 0x34, 0xc8, 0xd5, 0x09, 0x04, 0x39, 0xdc, 0x08, 0xb8, 0x46, 0xa3, 0x66, 0x46, 0x2e, 0x66, 0xdf, - 0xe2, 0x74, 0xa1, 0x1a, 0x2e, 0x3e, 0xb4, 0x08, 0x35, 0x20, 0x35, 0xfe, 0xa4, 0x2c, 0x48, 0xd5, - 0x01, 0xf3, 0x8a, 0x93, 0xdb, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, - 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0xe9, - 0xa4, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x43, 0x92, 0x29, 0x98, 0xd4, - 0x05, 0x19, 0xae, 0x5f, 0x01, 0x4f, 0x9a, 0xfa, 0xa0, 0x20, 0x2d, 0x4e, 0x62, 0x03, 0xa7, 0x50, - 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x30, 0x46, 0xdb, 0xa5, 0x07, 0x03, 0x00, 0x00, + 0xaa, 0x04, 0x0b, 0xc4, 0x20, 0x98, 0x60, 0x48, 0x65, 0x41, 0xaa, 0x90, 0x2c, 0x17, 0x57, 0x6e, + 0x6a, 0x4a, 0x66, 0x22, 0x44, 0x05, 0x2b, 0x58, 0x05, 0x27, 0x58, 0x04, 0x2c, 0x2d, 0xc4, 0xc5, + 0x92, 0x92, 0x58, 0x92, 0x28, 0xc1, 0xa6, 0xc0, 0xa8, 0xc1, 0x13, 0x04, 0x66, 0x2b, 0x25, 0x70, + 0x49, 0x62, 0x38, 0x3e, 0x28, 0xb5, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, 0xc8, 0x99, 0x8b, 0x03, + 0x66, 0x3e, 0x34, 0xd0, 0xd5, 0x09, 0x04, 0x3a, 0xdc, 0x08, 0xb8, 0x46, 0xa3, 0x66, 0x46, 0x2e, + 0x66, 0xdf, 0xe2, 0x74, 0xa1, 0x1a, 0x2e, 0x3e, 0xb4, 0x28, 0x35, 0x20, 0x35, 0x06, 0xa5, 0x2c, + 0x48, 0xd5, 0x01, 0xf3, 0x8a, 0x93, 0xdb, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, + 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, + 0x44, 0xe9, 0xa4, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x43, 0x12, 0x2a, + 0x98, 0xd4, 0x05, 0x19, 0xae, 0x5f, 0x01, 0x4f, 0x9c, 0xfa, 0xa0, 0x30, 0x2d, 0x4e, 0x62, 0x03, + 0xa7, 0x51, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x85, 0xa5, 0x6a, 0xda, 0x09, 0x03, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -402,10 +403,10 @@ func (m *MsgCreateResourcePayload) MarshalToSizedBuffer(dAtA []byte) (int, error i-- dAtA[i] = 0x32 } - if len(m.MimeType) > 0 { - i -= len(m.MimeType) - copy(dAtA[i:], m.MimeType) - i = encodeVarintTx(dAtA, i, uint64(len(m.MimeType))) + if len(m.MediaType) > 0 { + i -= len(m.MediaType) + copy(dAtA[i:], m.MediaType) + i = encodeVarintTx(dAtA, i, uint64(len(m.MediaType))) i-- dAtA[i] = 0x2a } @@ -527,7 +528,7 @@ func (m *MsgCreateResourcePayload) Size() (n int) { if l > 0 { n += 1 + l + sovTx(uint64(l)) } - l = len(m.MimeType) + l = len(m.MediaType) if l > 0 { n += 1 + l + sovTx(uint64(l)) } @@ -836,7 +837,7 @@ func (m *MsgCreateResourcePayload) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MimeType", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field MediaType", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -864,7 +865,7 @@ func (m *MsgCreateResourcePayload) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.MimeType = string(dAtA[iNdEx:postIndex]) + m.MediaType = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 6: if wireType != 2 { diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go index b5a3b0f22..22cc124d0 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -18,7 +18,7 @@ func (msg *MsgCreateResourcePayload) ToResource() Resource { Id: msg.Id, Name: msg.Name, ResourceType: msg.ResourceType, - MimeType: msg.MimeType, + MediaType: msg.MediaType, }, Data: msg.Data, } @@ -32,7 +32,7 @@ func (msg MsgCreateResourcePayload) Validate() error { validation.Field(&msg.Id, validation.Required, cheqdtypes.IsUUID()), validation.Field(&msg.Name, validation.Required, validation.Length(1, 64)), validation.Field(&msg.ResourceType, validation.Required, IsAllowedResourceType()), - validation.Field(&msg.MimeType, validation.Required, IsAllowedMimeType()), + validation.Field(&msg.MediaType, validation.Required, IsAllowedMediaType()), validation.Field(&msg.Data, validation.Required, validation.Length(1, 1024*1024)), // 1MB ) } diff --git a/x/resource/types/tx_msg_create_resource_payload_test.go b/x/resource/types/tx_msg_create_resource_payload_test.go index 544931649..d710dec0a 100644 --- a/x/resource/types/tx_msg_create_resource_payload_test.go +++ b/x/resource/types/tx_msg_create_resource_payload_test.go @@ -20,7 +20,7 @@ func TestMsgCreateResourcePayloadValidation(t *testing.T) { Id: "ba62c728-cb15-498b-8e9e-9259cc242186", Name: "Test Resource", ResourceType: "CL-Schema", - MimeType: "application/json", + MediaType: "application/json", Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, }, isValid: true, @@ -32,11 +32,11 @@ func TestMsgCreateResourcePayloadValidation(t *testing.T) { Id: "ba62c728-cb15-498b-8e9e-9259cc242186", Name: "Test Resource", ResourceType: "Not-CL-Schema", - MimeType: "image/png", + MediaType: "image/png", Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, }, isValid: false, - errorMsg: "mime_type: image/png mime type is not allowed. Only application/json, application/octet-stream, text/plain; resource_type: Not-CL-Schema resource type is not allowed. Only CL-Schema, JSONSchema2020.", + errorMsg: "resource_type: Not-CL-Schema resource type is not allowed. Only CL-Schema, JSONSchema2020.", }, { name: "negative mime type", @@ -45,11 +45,11 @@ func TestMsgCreateResourcePayloadValidation(t *testing.T) { Id: "ba62c728-cb15-498b-8e9e-9259cc242186", Name: "Test Resource", ResourceType: "CL-Schema", - MimeType: "text/data", + MediaType: "text/data", Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, }, isValid: false, - errorMsg: "mime_type: text/data mime type is not allowed. Only application/json, application/octet-stream, text/plain.", + errorMsg: "media_type: text/data mime type is not allowed. Only application/json, application/octet-stream, text/plain, image/apng, image/avif, image/gif, image/jpeg, image/png, image/svg+xml, image/webp.", }, } diff --git a/x/resource/types/validate.go b/x/resource/types/validate.go index 8d5c6daf9..1c057adef 100644 --- a/x/resource/types/validate.go +++ b/x/resource/types/validate.go @@ -18,13 +18,13 @@ func IsAllowedResourceType() *cheqdTypes.CustomErrorRule { }) } -func IsAllowedMimeType() *cheqdTypes.CustomErrorRule { +func IsAllowedMediaType() *cheqdTypes.CustomErrorRule { return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { casted, ok := value.(string) if !ok { - panic("IsAllowedMimeType must be only applied on string properties") + panic("IsAllowedMediaType must be only applied on string properties") } - return utils.ValidateMimeType(casted) + return utils.ValidateMediaType(casted) }) } diff --git a/x/resource/utils/mime_type.go b/x/resource/utils/mime_type.go index 6c4dfb667..f6128ef3c 100644 --- a/x/resource/utils/mime_type.go +++ b/x/resource/utils/mime_type.go @@ -7,7 +7,7 @@ import ( cheqdUtils "github.com/cheqd/cheqd-node/x/cheqd/utils" ) -var AllowedMimeTypes = []string{ +var AllowedMediaTypes = []string{ "application/json", "application/octet-stream", "text/plain", @@ -20,13 +20,13 @@ var AllowedMimeTypes = []string{ "image/webp", } -func IsValidMimeType(rt string) bool { - return cheqdUtils.Contains(AllowedMimeTypes, rt) +func IsValidMediaType(rt string) bool { + return cheqdUtils.Contains(AllowedMediaTypes, rt) } -func ValidateMimeType(rt string) error { - if !IsValidMimeType(rt) { - return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedMimeTypes, ", ")) +func ValidateMediaType(rt string) error { + if !IsValidMediaType(rt) { + return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedMediaTypes, ", ")) } return nil diff --git a/x/resource/utils/mime_type_test.go b/x/resource/utils/mime_type_test.go index 86ea7ac67..bd7dfa36b 100644 --- a/x/resource/utils/mime_type_test.go +++ b/x/resource/utils/mime_type_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" ) -func TestValidateMimeType(t *testing.T) { +func TestValidateMediaType(t *testing.T) { cases := []struct { mt string valid bool @@ -18,7 +18,7 @@ func TestValidateMimeType(t *testing.T) { for _, tc := range cases { t.Run(tc.mt, func(t *testing.T) { - err_ := ValidateMimeType(tc.mt) + err_ := ValidateMediaType(tc.mt) if tc.valid { require.NoError(t, err_) From 9ea1ef80d7ad6dfe182bfc3d55a4d064cabe8413 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Mon, 27 Jun 2022 16:49:52 +0300 Subject: [PATCH 59/65] Implement media_type detectin on chain --- go.mod | 1 + go.sum | 3 + proto/resource/v1/tx.proto | 1 - tests/e2e-bash/resource.dat | Bin 0 -> 491520 bytes tests/e2e-bash/tests/test_create_resource.sh | 4 +- .../tests/test_query_all_resource_versions.sh | 9 +- .../tests/test_query_collection_resources.sh | 9 +- x/resource/client/cli/tx_create_resource.go | 10 +-- .../keeper/msg_server_create_resource.go | 2 + x/resource/types/tx.pb.go | 77 +++--------------- .../types/tx_msg_create_resource_payload.go | 6 +- x/resource/types/validate.go | 30 ------- x/resource/utils/media_type.go | 13 +++ x/resource/utils/media_type_test.go | 32 ++++++++ x/resource/utils/mime_type.go | 33 -------- x/resource/utils/mime_type_test.go | 30 ------- x/resource/utils/resource_type.go | 22 ----- x/resource/utils/resource_type_test.go | 31 ------- x/resource/utils/testdata/resource.csv | 23 ++++++ x/resource/utils/testdata/resource.dat | 3 + x/resource/utils/testdata/resource.json | 13 +++ x/resource/utils/testdata/resource.pdf | Bin 0 -> 13264 bytes x/resource/utils/testdata/resource.txt | 1 + 23 files changed, 117 insertions(+), 236 deletions(-) create mode 100644 tests/e2e-bash/resource.dat delete mode 100644 x/resource/types/validate.go create mode 100644 x/resource/utils/media_type.go create mode 100644 x/resource/utils/media_type_test.go delete mode 100644 x/resource/utils/mime_type.go delete mode 100644 x/resource/utils/mime_type_test.go delete mode 100644 x/resource/utils/resource_type.go delete mode 100644 x/resource/utils/resource_type_test.go create mode 100644 x/resource/utils/testdata/resource.csv create mode 100644 x/resource/utils/testdata/resource.dat create mode 100644 x/resource/utils/testdata/resource.json create mode 100644 x/resource/utils/testdata/resource.pdf create mode 100644 x/resource/utils/testdata/resource.txt diff --git a/go.mod b/go.mod index e20ff284b..a3076e242 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce github.com/cosmos/cosmos-sdk v0.45.5 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 diff --git a/go.sum b/go.sum index 398ea4bb4..d38527885 100644 --- a/go.sum +++ b/go.sum @@ -316,6 +316,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= @@ -1173,6 +1175,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= diff --git a/proto/resource/v1/tx.proto b/proto/resource/v1/tx.proto index 529563b9a..118c6736b 100644 --- a/proto/resource/v1/tx.proto +++ b/proto/resource/v1/tx.proto @@ -22,7 +22,6 @@ message MsgCreateResourcePayload { string id = 2; string name = 3; string resource_type = 4; - string media_type = 5; bytes data = 6; } diff --git a/tests/e2e-bash/resource.dat b/tests/e2e-bash/resource.dat new file mode 100644 index 0000000000000000000000000000000000000000..2f8e9776b0d49cc5331a91a3069d0e34930845dd GIT binary patch literal 491520 zcmeIufdBvi0K=g9Q{UhOg-~I@fB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM z7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b* z1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd z0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwA zz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEj zFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r z3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@ z0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VK zfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5 zV8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM z7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b* z1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd z0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwA zz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEj zFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r z3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@ z0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VK zfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5 zV8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM z7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b* z1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd z0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwA zz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEj zFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r z3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@ z0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VK zfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5 zV8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM z7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b* z1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd z0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwA zz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEj zFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r z3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@ z0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VK zfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5 zV8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM z7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b* z1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd z0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwA zz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEj iFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5@CF8eX#fEL literal 0 HcmV?d00001 diff --git a/tests/e2e-bash/tests/test_create_resource.sh b/tests/e2e-bash/tests/test_create_resource.sh index 0b1d921b4..7d9d6fe12 100644 --- a/tests/e2e-bash/tests/test_create_resource.sh +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -47,11 +47,11 @@ RESOURCE_ID=$(uuidgen) RESOURCE_NAME="Resource 1" RESOURCE_MEDIA_TYPE="application/json" RESOURCE_RESOURCE_TYPE="CL-Schema" -RESOURCE_DATA='test data'; +RESOURCE_DATA='{ "content": "test data" }'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource ${ID} ${RESOURCE_ID} "${RESOURCE_NAME}" ${RESOURCE_RESOURCE_TYPE} ${RESOURCE_MEDIA_TYPE} <(echo "${RESOURCE_DATA}") "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +RESULT=$(cheqd-noded tx resource create-resource ${ID} ${RESOURCE_ID} "${RESOURCE_NAME}" ${RESOURCE_RESOURCE_TYPE} <(echo "${RESOURCE_DATA}") "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ --from "${BASE_ACCOUNT_1}" ${TX_PARAMS}) assert_tx_successful "$RESULT" diff --git a/tests/e2e-bash/tests/test_query_all_resource_versions.sh b/tests/e2e-bash/tests/test_query_all_resource_versions.sh index ed77f76c7..a81fe479a 100644 --- a/tests/e2e-bash/tests/test_query_all_resource_versions.sh +++ b/tests/e2e-bash/tests/test_query_all_resource_versions.sh @@ -47,13 +47,12 @@ RESOURCE1_V1_ID=$(uuidgen) RESOURCE1_NAME="Resource 1" RESOURCE1_MEDIA_TYPE="application/json" RESOURCE1_RESOURCE_TYPE="CL-Schema" -RESOURCE1_V1_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; +RESOURCE1_V1_DATA=$(echo '{ "content": "resource 1 v1" }'| base64 -w 0); MSG_CREATE_RESOURCE1='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V1_ID}'", "name": "'${RESOURCE1_NAME}'", - "media_type": "'${RESOURCE1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", "data": "'${RESOURCE1_V1_DATA}'" }'; @@ -86,13 +85,12 @@ assert_json_eq "$(echo "$RESULT" | jq -r ".resource.data")" "${RESOURCE1_V1_DATA ########## Creating Resource 1 v2 ########## RESOURCE1_V2_ID=$(uuidgen) -RESOURCE1_V2_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhLg=='; +RESOURCE1_V2_DATA=$(echo '{ "content": "resource 1 v2" }'| base64 -w 0); MSG_CREATE_RESOURCE1_V2='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V2_ID}'", "name": "'${RESOURCE1_NAME}'", - "media_type": "'${RESOURCE1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", "data": "'${RESOURCE1_V2_DATA}'" }'; @@ -108,7 +106,7 @@ assert_tx_successful "$RESULT" ########## Creating Resource 2 ########## RESOURCE2_ID=$(uuidgen) -RESOURCE2_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhdGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; +RESOURCE2_DATA=$(echo '{ "content": "resource 2" }'| base64 -w 0); RESOURCE2_NAME="Resource 2" RESOURCE2_MEDIA_TYPE="application/json" RESOURCE2_RESOURCE_TYPE="CL-Schema" @@ -117,7 +115,6 @@ MSG_CREATE_RESOURCE2='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE2_ID}'", "name": "'${RESOURCE2_NAME}'", - "media_type": "'${RESOURCE2_MEDIA_TYPE}'", "resource_type": "'${RESOURCE2_RESOURCE_TYPE}'", "data": "'${RESOURCE2_DATA}'" }'; diff --git a/tests/e2e-bash/tests/test_query_collection_resources.sh b/tests/e2e-bash/tests/test_query_collection_resources.sh index 9e0e0fb45..a68e26f0a 100644 --- a/tests/e2e-bash/tests/test_query_collection_resources.sh +++ b/tests/e2e-bash/tests/test_query_collection_resources.sh @@ -47,13 +47,12 @@ RESOURCE1_V1_ID=$(uuidgen) RESOURCE1_V1_NAME="Resource 1" RESOURCE1_V1_MEDIA_TYPE="application/json" RESOURCE1_V1_RESOURCE_TYPE="CL-Schema" -RESOURCE1_V1_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; +RESOURCE1_V1_DATA=$(echo '{ "content": "resource 1 v1" }'| base64 -w 0); MSG_CREATE_RESOURCE1='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V1_ID}'", "name": "'${RESOURCE1_V1_NAME}'", - "media_type": "'${RESOURCE1_V1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", "data": "'${RESOURCE1_V1_DATA}'" }'; @@ -86,13 +85,12 @@ assert_json_eq "$(echo "$RESULT" | jq -r ".resource.data")" "${RESOURCE1_V1_DATA ########## Creating Resource 1 v2 ########## RESOURCE1_V2_ID=$(uuidgen) -RESOURCE1_V2_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhLg=='; +RESOURCE1_V2_DATA=$(echo '{ "content": "resource 1 v2" }' | base64 -w 0); MSG_CREATE_RESOURCE1_V2='{ "collection_id": "'${ID1}'", "id": "'${RESOURCE1_V2_ID}'", "name": "'${RESOURCE1_V1_NAME}'", - "media_type": "'${RESOURCE1_V1_MEDIA_TYPE}'", "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", "data": "'${RESOURCE1_V2_DATA}'" }'; @@ -135,7 +133,7 @@ assert_tx_successful "$RESULT" ########## Creating Resource 2 ########## RESOURCE2_ID=$(uuidgen) -RESOURCE2_DATA='dGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRhdGVzdCBiYXNlNTYgZW5jb2RlZCBkYXRh'; +RESOURCE2_DATA=$(echo '{ "content": "resource 2" }' | base64 -w 0); RESOURCE2_NAME="Resource 2" RESOURCE2_MEDIA_TYPE="application/json" RESOURCE2_RESOURCE_TYPE="CL-Schema" @@ -144,7 +142,6 @@ MSG_CREATE_RESOURCE2='{ "collection_id": "'${ID2}'", "id": "'${RESOURCE2_ID}'", "name": "'${RESOURCE2_NAME}'", - "media_type": "'${RESOURCE2_MEDIA_TYPE}'", "resource_type": "'${RESOURCE2_RESOURCE_TYPE}'", "data": "'${RESOURCE2_DATA}'" }'; diff --git a/x/resource/client/cli/tx_create_resource.go b/x/resource/client/cli/tx_create_resource.go index b16192098..7373ab431 100644 --- a/x/resource/client/cli/tx_create_resource.go +++ b/x/resource/client/cli/tx_create_resource.go @@ -13,14 +13,14 @@ import ( func CmdCreateResource() *cobra.Command { cmd := &cobra.Command{ - Use: "create-resource [collection-id] [id] [name] [resource-type] [mime-type] [file-path] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", + Use: "create-resource [collection-id] [id] [name] [resource-type] [file-path] [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-1] 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(6), + Args: cobra.MinimumNArgs(5), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) if err != nil { @@ -32,9 +32,8 @@ func CmdCreateResource() *cobra.Command { id := args[1] name := args[2] resourceType := args[3] - mediaType := args[4] - data, err := ioutil.ReadFile(args[5]) + data, err := ioutil.ReadFile(args[4]) if err != nil { return err } @@ -45,12 +44,11 @@ func CmdCreateResource() *cobra.Command { Id: id, Name: name, ResourceType: resourceType, - MediaType: mediaType, Data: data, } // Read signatures - signInputs, err := cheqdcli.GetSignInputs(clientCtx, args[6:]) + signInputs, err := cheqdcli.GetSignInputs(clientCtx, args[5:]) if err != nil { return err } diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index eb8b225cf..7d5a383e4 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -3,6 +3,7 @@ package keeper import ( "context" "crypto/sha256" + "github.com/cheqd/cheqd-node/x/resource/utils" "time" cheqdkeeper "github.com/cheqd/cheqd-node/x/cheqd/keeper" @@ -47,6 +48,7 @@ func (k msgServer) CreateResource(goCtx context.Context, msg *types.MsgCreateRes 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) diff --git a/x/resource/types/tx.pb.go b/x/resource/types/tx.pb.go index 45afb731c..ce64040de 100644 --- a/x/resource/types/tx.pb.go +++ b/x/resource/types/tx.pb.go @@ -86,7 +86,6 @@ type MsgCreateResourcePayload struct { 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"` Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` } @@ -151,13 +150,6 @@ func (m *MsgCreateResourcePayload) GetResourceType() string { return "" } -func (m *MsgCreateResourcePayload) GetMediaType() string { - if m != nil { - return m.MediaType - } - return "" -} - func (m *MsgCreateResourcePayload) GetData() []byte { if m != nil { return m.Data @@ -218,7 +210,7 @@ func init() { func init() { proto.RegisterFile("resource/v1/tx.proto", fileDescriptor_f5b76d41c4c62339) } var fileDescriptor_f5b76d41c4c62339 = []byte{ - // 401 bytes of a gzipped FileDescriptorProto + // 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, @@ -228,23 +220,21 @@ var fileDescriptor_f5b76d41c4c62339 = []byte{ 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, 0xed, 0x66, 0xe4, + 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, 0xaa, 0x90, 0x2c, 0x17, 0x57, 0x6e, - 0x6a, 0x4a, 0x66, 0x22, 0x44, 0x05, 0x2b, 0x58, 0x05, 0x27, 0x58, 0x04, 0x2c, 0x2d, 0xc4, 0xc5, - 0x92, 0x92, 0x58, 0x92, 0x28, 0xc1, 0xa6, 0xc0, 0xa8, 0xc1, 0x13, 0x04, 0x66, 0x2b, 0x25, 0x70, - 0x49, 0x62, 0x38, 0x3e, 0x28, 0xb5, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, 0xc8, 0x99, 0x8b, 0x03, - 0x66, 0x3e, 0x34, 0xd0, 0xd5, 0x09, 0x04, 0x3a, 0xdc, 0x08, 0xb8, 0x46, 0xa3, 0x66, 0x46, 0x2e, - 0x66, 0xdf, 0xe2, 0x74, 0xa1, 0x1a, 0x2e, 0x3e, 0xb4, 0x28, 0x35, 0x20, 0x35, 0x06, 0xa5, 0x2c, - 0x48, 0xd5, 0x01, 0xf3, 0x8a, 0x93, 0xdb, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, - 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, - 0x44, 0xe9, 0xa4, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x43, 0x12, 0x2a, - 0x98, 0xd4, 0x05, 0x19, 0xae, 0x5f, 0x01, 0x4f, 0x9c, 0xfa, 0xa0, 0x30, 0x2d, 0x4e, 0x62, 0x03, - 0xa7, 0x51, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x85, 0xa5, 0x6a, 0xda, 0x09, 0x03, 0x00, - 0x00, + 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. @@ -403,13 +393,6 @@ func (m *MsgCreateResourcePayload) MarshalToSizedBuffer(dAtA []byte) (int, error i-- dAtA[i] = 0x32 } - if len(m.MediaType) > 0 { - i -= len(m.MediaType) - copy(dAtA[i:], m.MediaType) - i = encodeVarintTx(dAtA, i, uint64(len(m.MediaType))) - i-- - dAtA[i] = 0x2a - } if len(m.ResourceType) > 0 { i -= len(m.ResourceType) copy(dAtA[i:], m.ResourceType) @@ -528,10 +511,6 @@ func (m *MsgCreateResourcePayload) Size() (n int) { if l > 0 { n += 1 + l + sovTx(uint64(l)) } - l = len(m.MediaType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } l = len(m.Data) if l > 0 { n += 1 + l + sovTx(uint64(l)) @@ -835,38 +814,6 @@ func (m *MsgCreateResourcePayload) Unmarshal(dAtA []byte) error { } 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 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.MediaType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) diff --git a/x/resource/types/tx_msg_create_resource_payload.go b/x/resource/types/tx_msg_create_resource_payload.go index 22cc124d0..f521f5088 100644 --- a/x/resource/types/tx_msg_create_resource_payload.go +++ b/x/resource/types/tx_msg_create_resource_payload.go @@ -18,7 +18,6 @@ func (msg *MsgCreateResourcePayload) ToResource() Resource { Id: msg.Id, Name: msg.Name, ResourceType: msg.ResourceType, - MediaType: msg.MediaType, }, Data: msg.Data, } @@ -31,9 +30,8 @@ func (msg MsgCreateResourcePayload) Validate() error { 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, IsAllowedResourceType()), - validation.Field(&msg.MediaType, validation.Required, IsAllowedMediaType()), - validation.Field(&msg.Data, validation.Required, validation.Length(1, 1024*1024)), // 1MB + validation.Field(&msg.ResourceType, validation.Required, validation.Length(1, 64)), + validation.Field(&msg.Data, validation.Required, validation.Length(1, 200*1024)), // 200KB ) } diff --git a/x/resource/types/validate.go b/x/resource/types/validate.go deleted file mode 100644 index 1c057adef..000000000 --- a/x/resource/types/validate.go +++ /dev/null @@ -1,30 +0,0 @@ -package types - -import ( - cheqdTypes "github.com/cheqd/cheqd-node/x/cheqd/types" - "github.com/cheqd/cheqd-node/x/resource/utils" -) - -// Validation helpers - -func IsAllowedResourceType() *cheqdTypes.CustomErrorRule { - return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { - casted, ok := value.(string) - if !ok { - panic("IsAllowedResourceType must be only applied on string properties") - } - - return utils.ValidateResourceType(casted) - }) -} - -func IsAllowedMediaType() *cheqdTypes.CustomErrorRule { - return cheqdTypes.NewCustomErrorRule(func(value interface{}) error { - casted, ok := value.(string) - if !ok { - panic("IsAllowedMediaType must be only applied on string properties") - } - - return utils.ValidateMediaType(casted) - }) -} 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..719cb1904 --- /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/mime_type.go b/x/resource/utils/mime_type.go deleted file mode 100644 index f6128ef3c..000000000 --- a/x/resource/utils/mime_type.go +++ /dev/null @@ -1,33 +0,0 @@ -package utils - -import ( - "errors" - "strings" - - cheqdUtils "github.com/cheqd/cheqd-node/x/cheqd/utils" -) - -var AllowedMediaTypes = []string{ - "application/json", - "application/octet-stream", - "text/plain", - "image/apng", - "image/avif", - "image/gif", - "image/jpeg", - "image/png", - "image/svg+xml", - "image/webp", -} - -func IsValidMediaType(rt string) bool { - return cheqdUtils.Contains(AllowedMediaTypes, rt) -} - -func ValidateMediaType(rt string) error { - if !IsValidMediaType(rt) { - return errors.New(rt + " mime type is not allowed. Only " + strings.Join(AllowedMediaTypes, ", ")) - } - - return nil -} diff --git a/x/resource/utils/mime_type_test.go b/x/resource/utils/mime_type_test.go deleted file mode 100644 index bd7dfa36b..000000000 --- a/x/resource/utils/mime_type_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package utils - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestValidateMediaType(t *testing.T) { - cases := []struct { - mt string - valid bool - }{ - {"application/json", true}, - {"my/mime", false}, - {"notMine/type", false}, - } - - for _, tc := range cases { - t.Run(tc.mt, func(t *testing.T) { - err_ := ValidateMediaType(tc.mt) - - if tc.valid { - require.NoError(t, err_) - } else { - require.Error(t, err_) - } - }) - } -} diff --git a/x/resource/utils/resource_type.go b/x/resource/utils/resource_type.go deleted file mode 100644 index d774b98a1..000000000 --- a/x/resource/utils/resource_type.go +++ /dev/null @@ -1,22 +0,0 @@ -package utils - -import ( - "errors" - "strings" - - cheqdUtils "github.com/cheqd/cheqd-node/x/cheqd/utils" -) - -var AllowedResourceTypes = []string{"CL-Schema", "JSONSchema2020"} - -func IsValidResourceType(rt string) bool { - return cheqdUtils.Contains(AllowedResourceTypes, rt) -} - -func ValidateResourceType(rt string) error { - if !IsValidResourceType(rt) { - return errors.New(rt + " resource type is not allowed. Only " + strings.Join(AllowedResourceTypes, ", ")) - } - - return nil -} diff --git a/x/resource/utils/resource_type_test.go b/x/resource/utils/resource_type_test.go deleted file mode 100644 index 3bbb966c3..000000000 --- a/x/resource/utils/resource_type_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package utils - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestValidateResourceType(t *testing.T) { - cases := []struct { - rt string - valid bool - }{ - {"CL-Schema", true}, - {"JSONSchema2020", true}, - {"My-Schema", false}, - {"Not schema", false}, - } - - for _, tc := range cases { - t.Run(tc.rt, func(t *testing.T) { - err_ := ValidateResourceType(tc.rt) - - if tc.valid { - require.NoError(t, err_) - } else { - require.Error(t, err_) - } - }) - } -} 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 0000000000000000000000000000000000000000..774c2ea70c55104973794121eae56bcad918da97 GIT binary patch literal 13264 zcmaibWmsIxvUW%|5FkJZ7A&~y%m9Oj;I6>~WPrgfxD$eVfZ*=#?hsspJHa(bATYRn zGueBev(G*EKHr+BrK+pDs^6;aH9u<6Dv3$30@ygwX}fZ|TDt1G($Rqw927PN=I8~c_R69-cY5S*jJE@5Wr0JUS6u!J~3#h`{ZMo=LkbbALoD8vfgB}Fh|2>mhOnfS$3 zNV5}8Ox=$fj;C0=UKy*{myZZPRVS|0mqr-HxZAy;()@wxQ}MN`QWAZTXb3Z&Om9W2 zbnA^OWoQbAW|3W^fw#J;YzDato8*`rHQs+@W70D&SyT{wb`SN*3nI z5G%$wJlq932=n{60Eii*9H8dFih2ks?QY=>nAFL=5g^P@#b{YUEHt0S$D7WbX zx%TzvzIK%zpvzLEd9LNr0ch#LFf_(9 zEGt0C9v~%b54vynAc{~;v&2?S(-sTTft@9CABMNFZHtY1W0-99CEbUNfp_yu{LDBz z@8z^$LPN$wX4Hi+dZQs6K3QiKKF0}Nme@EII;;F}IplC(YvT*C3-Oh#(A}e5pIz01 zyR}D2|ftBF0T=1moHZy}$wS*PSCmSzHQ%x z2tCQQCx4jt7w1cuhY69~eH`31KC4)ZZJ^)f=IabocAkBPa zEeg25yPX&9-i_N(Qiq!I3RDrfx&0t^i)&MSQ1D(w%|%#LTNr>1cPiltAYO;6kBn(B?r11c^Bz~#)z5~~V+*`U)lDFtKbZ|;? z&4wTUtK=KE&uQIWUQv1mDE;LIhXXgx44PMa@%Z<7a& zx45^oYSnei^~%}`?!O-+cgfSmn_c?`=Gmm*Z^I(96ve&$zDs|)r84)IEEiE1kfQ$q zm3km*m1)PjdU9nkk9BTlidI1~M|O~WfP7AUu2T}d>5is9l$<%;7r2&Re06w>W$KM~ zqITBTd=Ln>^crw`_N?{ z;2d_=E0n!*NisQ|XYuX9q3+UcqdA(MC45|>2tz^c6HdZOmXTB?X2Elx@_0f)1z&-gS;UxN`>Ll-kWb0X0 zTrQis=w9sJ(q7k|@|k3SA~DJ@uMXP@4(Mgn+LJC+3F~3NHW71pIzY(aHg~{O+squi zWO_|F>78)L5*gcRXXRD9IzQ(ddSxh}E7(8sC~EYrOz$9BkSMBCkGGO9FuZ{#*mW+h zvwE7d)6Ag=a*R5URs>}qdqb_E6g)kN2Wel;pWe9=hZ)XvRZR!RQg&gxAPGj8J0!gR zrdV<2@MZQ?_Ocbd5@0zI?t>$z3eD80_h^{DI)H5lk`T4lbn8kteH3%fOBH^g26#lLN2&P^s zr&d05GDs)u_8OKzCgNxllk5pLC<2wKmghL{zW%}5^}%S$?d=3OzjaSzT3>uWYikZN z2ZcR7*L|%UMs|u)wMi7#vkN?cxlBcyAM80Tyzzv&zHMF1TH9?Mx5&E57P^)^zE5N| z^foq}!--if$Uj=U6Tc>EM!Pv)e^_SZSdvtQ=@>)(ONejQ!XW8u6>ESl<*s^6cH;Q1 z#n}nL{#|{l}}@td^zNSA;R{`3A&Jjr8L9(3^2FSyZ1W9$%;!XP#N2 z-SAzyRfxtgq^py7_3*GJFO%x_v<`xJ46`~S*IukgQDKfLxzFnS&GYL!1LA{I z!c#{A90{k(b*tUfbgjOH>}{#V;%^O+LUU<*#QkLtWzjho*Kb?Cr&wC38%wxpn}^Wy zG6EpV9x3xioCWA6H6=aE3)%jmZePu#Ji7wy0CmkDZNG`a{J1i-2`Bt&UrFb&<~V$^ zy9i`R1<35M&{mtCz144%v#7LKBTPPApjoV}#W-gDc5cn;A@Mbt#zXUK@J9^vj*ME( zo8(%K{c-KDr8n1-I&Mjn)*i|pF|7l*`fXvo8-z&j{$NOfUPM-xILbX1D29IHp|__B zL*JQ8*7-VrZVY*&$!PiE%zv@osg`qx0M8+w9iy7Az7;HYezs;5NRvrdNM~t@o}5Gc zjagk3Y_>6!Ct;ITqhu3FojJO^(^SG-($M4|frkp?4y-QoSmFcw9Z%(z?eC0kGi9@? zm(vAgXU|%!6_)CrnqYL-Hj@B5hA?#8C3G^cjd?0dMSZ!wbe%O4bWvlIG=nwOEInVj zhjzd`Bry8sXBTfIUr+juZH5JyE#7~UQiwR!gmG@wm}aNyo`13xEo)tzP64MWWG|j8 z8u8a2_=C2FdRZ9(eG&Au`@$mY9vvWldP-@wj5@38H0W2V8wnaQO?!)qoS_J=(ieoI zOvH}mkBRh_p1oTW66+?3u-GH2Ex~c=BQiwpJ zJlF7O2PBaCojRRL_mp44*Iq}vcRFpBD>V9M7do5{w&b;4^<_V~Vr{+O_&hz9k5Sm` zq3|%Z(6B5~wz2k0iH-QlafAa>1%ZebdxkR;6SdA?@dK|4Jf8PIO%64Fpw$6RYG2R# zX>Iq(xf`5Xk)79-@;BAQjlWu|w@Ss3sJv3Ew&%lBu-H?vYsC8XPJD!lkv*A~z_-k= zLOaM?B5}$Sf-KF5BWHoB51WFA{GlweQna618{*tqVn)YKUVq?khU_=QER9uW?N17xgAponbjg0W`=>f;sulH3?st)Y_@k$We2-__a>^{E78lUiI13qq!3# zwxMEl75MK1q`~J>ST#?`mUx#vr%-jwpZ+DV;W!0KNkZmO#sK)zt)H@`EQl6RRWhwb z0&E7|fG~@z)wlK1-RsxN#8Gr)D5=xpv=b}=CWPbwz@(9bIhD0Crd-Q>qEo>~Gh{X7 z77AK5>TfF0wK!?7Nx!<5uDy?D{Qg$SEc_R3J9EuH!Z@qmEJ*QRRHd3BPirM6783nv zAnab$>rhdDJ6pO@%Ox(}BYw{Ba<3|=A%Fg5_Hfxj{%CfzZCFO{?%h&=?%CNBvi&p; z(otqN>+5giLLa^*G?xzN30=IgQrV+r7dW4bX;zKtuD)O$UnwAKC?CpkPt{77nUArH ze-jKcCfRrOlp(Q^b&W}mrgt4n%wikNxeSBBE_n>K-IOIzi6!<)xGRYA)wGgqp^s@d46N#krDHPc#9SOgXhI7Vbj?B z%c6@8dCOGPYBoNE#3N7HD^ihbC9*xGm6chu;?fcuv)s01keHHZ1vXl5D;29O7wZBr zyPzyLZHKMtUI%PK+*X2zTFtaDzU1qn(H=hRRj-SoJw7I5i%4b0u=&InEAKgoae-lp zXk0SkjlJ52HruS*1QykTZ&aCN`PbcKuw$1st{peJ@&aF^aR@~{XA@L&YvK%+VU}G4 ze5iuesu&i6=*#nvHbm_v-ZLr5^Ij#|YSAper4XpsH;0x(2h1-tIobIy;0~2a( z!G($SB!iu#P;;hGeI~C`O=-3|d~zoB0!`*JrU-)Ko_X5#kSpy5o^z49RG;{j#l~45 zF?X9Ih4IdviT(8@+q|`BveLTprbESZ6^2I&ew|V3pDXRe9gSyXT)zzqKQ;gCD;p+( zM)2(;YJ%P5)X(N3ZSn>dn6UIcEcvQOXZBn}uD!7V0yXr$f+d@eTSYoquPit2S8cPW zA8t3dX)Cv{0cKF`@e|PP(xS0|z2_R0(P6)#+kC$0^5- z$7Hs|bOQanE z1oJ;uh(dYiDt}mVmtC3&HaGT6-dY429v#ySHJ7V)C8ow=PSmnEI)=b3_RJsU(S*+J zV$p3>RkK?DFvTc;(-T=h!1u~CP!pE=0eSSu#c@N7S0Z57CPg}!5z{QL#`2v?DJDt^ zCGN{0p-&&=)Sb28Xlo;ZXc^CGdwL9prf30uu$y5aPeWD6WIk4%%~DEhTiwOvy!rS% z&3z#DWo2qBA*=M2xIu=_R0sbrmP;Y?_rRa^k}3WYU6n9H^(})Zi-woMKKXfgbab@J zWx3DUr0MLpdDYk_LO8As}d*Z=x^K+uIv#T&SnY6&C$9 zBn1u`G#TBt+n5b%a;Cr0h^sm5Fl^OdxJ^8IebW);DWATq#Ba=#rggj*wNKy5NMzz& zBm`bk9bcSVPJbC`dHrI>o^=LSvTFpT`VAK`x_naOpvS~*l2$1vIk$avBA!|aeZ+7c z$_9Zzh>fc4$uX&w@-$VORCscG(B)OA@SPj>BNY3gxkkcPgNi9bE=?&3A4`3ekrdsb zn~`M;p8I>4?@@ZI{9Afv(tC@pp@Oe5BYUw-%&J_WaTBGls)&d8q?t$i<<@=_CNfH! z4H!ww7#gkp_^`bxZaJI9@C+A9x7@E1ZRoG5PL?w3GDi>`8Qq%I+0ygfT78%{Zt#mP zqX0CzaHKn@hAOQsv=^8UbfpuyFnT8Ht++Vmmx$~09!e{5t8fMkEjr~tfIxMlIpr4zGwvEIWKC2`Q#C)c7QF9wet?hE zLKoU?t@nqm=iBc` z8_((*(i(g}7z)3{%SJ!uya{?Ir-2^Fiap*VC4pF@N zpL5F*DG+(taLhdu4DbyAP(0&60n@%?G~hHugBI^-X6@_YOu}8UqwbQ8V`2vwDRLMz z)aRFo+r1f?5idT9xRF`cjgx$a-IpH3AH|bs$emw}d23*3aU0hYNh4(D0o-Z+wIX{d zeann?lzjgsAt62`er@<$`G755?i7tl%CHNgXp}#j>j&S1n5wZ;ofNbI>B2*4L1}@3 zq(LzPqn()w{KBsX!5*a&=dv<}t=R%II;TcQatbnKM7S4Q1PQIoT=^$#=>Y(m{mBYtl5W z6}|l4kxikOcJ`C3o{TSxIi?8|N6sH7Lkhq5qttl@uBTA|-cBluU$hU0&xYKvNidrL z4q>|j76}G1Db23Fa|XlFm%W&jW0h#7B$_FD-ZhqJ5#7i!0ZmCrereX z|Jlf`<1zR2akFe|boWv-r=}kM03o|%$mZA7Of2T99u~e56~6sh$P=yk9f!H6msn)n zvFOLF?W?iqi6fK9C)a42Sgt0kz4#M6 z-UY6451Er~=V;ITs1O-q*>}{;bs74MMZ(Z&=Z{5#q+i@cw^vI#0|Dh~-Dh-tn2I(S zTXXp-bLEG{p0#BbIqIcTM|DWZmr`&br8u)jQ`CR*^+g_fIX%=K+)x}F%Oak-Uh$6nIHUavnNV5M7YffU80QPRD%y>T{bIzn<6Rsy zb6cW6`?0EwSn;uJddPn@`?^Cry2s(6ccP1ykKr!kmDg2~zbTJq@+e(z5N>ZNr|8$j zPi-~ofp7E|Xx1#H+f@UR@AS}iLP!}}dRwf{u!avAq-_hNw#uaoOD{2jo*eRn8$~bDK`h1&ssOC6ekGV38+hU!KR z+kpnSzT;y#o|V2h|F?SY4-z1MFxz0;)@Lk`H>Cj zSl@fR%*@F79;HJcsX%L8_d!%TwmQyi$|n&C{oBMJ9~Xm!@@#lZdz(WB9SgJ#NIC%@ zy+~ZnI|4E`7f@W0Y9I@N7UTs1fTPD-ZiU%Lr2MnP+2h8AGh?(WGVf>h@W-_M>jRkD z(KNxvo(UJ7)o+*t%fCcM10;2XM$1NAFKwhp(c917^io_ynn-yv58IFIF*UJUw*2Ma zm?a-a1yp9B?WxpLzap-c^$HKkX_IfT_W8Lqaltl*A%vZSZWAe`Kv}vjz}>Tc;Hw9T zA+Nc49X&{WDmxY~ReV0YceXdL!$9mTL$Q@_vXIW6I{G=`$KR7jFcE&IsHwnKX;KldV#YL z(xwKAB5cFiz+r6m*5iJvo&E)XQqVWjmA}BfyVS&dm9&Y%$Sp^sW!JE3iI0v(kQHdo zmhWk|gC!e@CFKPv4BE*U;mYo0y}J0J-Fhu!c%v+paQf9+3Ed2EkfPt(D7|Ok#t)^PGr3Y)RGfvO=k;@Xry=Cf3fLCQ# zi`%oCt+vyB-t{iEgI&+2dczmnMXj>EOmSpMuuL8Ob`1$D;fc$wM6j2HH4Q$ zqaoj&M$2sLhpptdJMbs!krJId=iOd}HdP4Lt@yf42OZ{pOoQ4_gShz_sMoWYX}yQd zDQ8(tc7UvTt%`0#?9K!C^J>GpucEnBhnsWg102Z=uzOlwez^q^j7nV$krID#wC}A$ zcRfc2)T5Y~({6@1`{yL-Lzs;miT@C9|1SIFBMK7cz*E;v2H|EStZphjfb5mGMpw{q z!pl;Vw772tuvDH4o$;j4u8)@=m+&BIf4Ix(u75P?Q{4Y8^uvpq)mCW(enuQc)hx$B zOY{`_*%~bm%k*x6y;)D8_-yYbMsC8y#1H}89X;M=a#*HT>d*NFf}x$pQ&X?nFtvzA zKH|l8y;frsm|&}<%&*}Yu}Yn0M=Jy8qe%<1qXRR%Nut}Aqr+1pQS*D7Cp`+8Y`RO02p14DyVOmSYlEzZ;9&JzYhtybMZ%e4s zlks=V(+aJ!LK-()3ox`%9c)lx#3#y4{ulL6KpG|&>9`n?Uh#m3G-mZy-3h98Scyja zH^3Pb7?P z+2hAkyvg}g$#)n$Gs2fL19JNOZ|~>Nx(|}lmwesC!>?Y~72mpf4XZ8t^TIwbCk;i0 z+a2ymSZ^=OrtrSH!(y#Vn!8KWk#O7<1-!if+`dDDy18U7wS3k$lIeM}Z0fhYqI)+x zo*o4*S$S|hGf6vL>PaQ(OQ_%eskx-G-FV|dXHbTH<#w@RbeIx9I$d$xqHh`{*&d3y zevlYNk)}w@cuu4A$^DYJsOvO7VBaom@Rx@gb$V5IKJ{Xue16H-1H0j=U0brW-aVRG znWCQRkESBmD^4?a7mB@!jf2>(Hs=Bd-;XX1oEilevb9axB^NhIPLO>jl03S+Rw|fx z&oIsIk(~W!4$zzKF|uSR<@S#;{r;fKup)iDaxz_9JouroY>XHcrN(Mm@UHV?-8bCh zXGfY~7U`rCasv(h-R*ava)^ zF1`BMT*n3xQBTdM?`n&h2Ecf*XXuLo7Zyl_El(v~oh>}mK01$%0a@#uzyiX_g>Bav2XWwH%YekAxU%pBT!p*?%cS#zA zv;^eDC#KZP@7o=^GDc_V8<3w>`*L(+=A#(fcH)dGjqM}Vk_el+c>B`{9xm<>IZ-Zm zLL!-Yf*3nju_(8ZGUd9*K`iofWW+BYFnZF&+a|=yxqV?oUOcG#ulnSR$DMs|e5Tph%WW zVjzE3nMh7+rG!}av)+~;o$#+EHyPX zzOUO?^#)Jh*t^b7pTW+I%f;xy&JMPCO&5RR``BmHX-Mw{qoJp9BjKea$;A9%>-iEZ zvuUBm%0j5UWax~`ue!K6dDdip+zs3f{+qQKqH;9C(1Z@95()-Ew=`BdLh2VS3zI8qYGH&&7m9+vpUc+x8l!i-ATXKhw34XL2;ya_VIQz!OL^)8mtqnb?q=~&^h-$;Zn^HRZ2p(gH z39An;`AWT=i&VP0u&CUe7OYW51Icv=q%Vc7%Zm z_uAp9n}osEUdk2*pV)*i`WRSa-FWtCwGqS-75@K#V0)r;+0(0XVp9vnb7lWiMj!q= z>Zf(ioa@gSwA55Jil$lh)%4U<)$j@HTQU2KwuUUsZA*2O^QTKobak8g0Qb~ROMTW7 zfTF2yF*na6i(lQ*Nq^rPen^0>$$b`K!Kp{FVa-VF`kCiXZg0Vtr}i*rcpny_YOR!} z+?Jiv?dWlT`}o$s9Fxt%%684d7ek-q-Q~jS*I5+8HtvSw+Rp!D=+gVr!gqcYy9K74 z&eClx6f6{1Din;ynjz?XZlJ~W7^A@0wiHIt8$aou;f>MYpU%gUlDwAK*nX0#vHtyl z_C=B+ZkOffY|oR^2>(+IlZCTMFirZMhn>bqzR=38hvJpcM4-@gUYY7_k^G*FW9;5r zc9q4c>C?hd{uS3{MThN*(w!3e05e?bI#SNlo$U&%>((Dz0_JeqbG|}!wI$& z%q2JQ)Vas;i0RYqNXW!CC~QK%u$K$beGI zT2KuzMjus26(zmofK;m2gY%d*o~sHBKA#`RBNc9c*-GLmbgh?*9V;^TBSot2E%~Q5 zl+R!WA_h_JT;+irbJ#Z-tSy-;B^t&&dOSwPV(T!CB)no8Y4sP%k(MD^0P!NL1vK&7 z`3luW2$gkI#Zf>IZT2=m4R&e@d zeo#B=Q|9`w8}%|)f%GBjYO01&Dk5qjm$+#1yia#CE=Sh~88Vdp%|VU}0a6mF@JkhUY&~W3f#rHK-1Qdo z>0*z5?#-hQUY}k^X7~1bkI?($-~3#c3mF4Cl@2%|0@1=ARZ z^qlNaN63&>;O_~mmto}?tAhznb}p;GpyIq1Z^yf<_6Ui~cpbbP;uV7W!+ke>wYG-f zPPz2~%UgSs(>vsKFle%uo=WIDYz;BR!doAy)aQ0QCpE_Wz1XK+3Kpr=V_H8w zqzaizn9ALx#?fo-N)_CtENYH*1|ID|x=xa9d#;9~1Wgrcx^8=evrfky*Xj`269~A;kh^O|ewZnM}=SmM7NX=?h#jjLh&1kIT+A z)If4luYo@s+e_L&eRJ$gw1`)>u#efOq=M0iYIPS$GII0z`T56eNxK@~Y%*^~Q&w$1b)jM9Z~kuRc~YX`6r#ySCskW5cq|#a39s;ZiaL~OdEpgu z1k*sKkLZ&?6fAi=)77yKI1xii%)@DG8r}663xkJcwLTj?s`h{GP@_2}`A|;w7zrzk4QOQ*O$(e|M^<`vLD*1^i>Nr*= z+A`y@f{!zLi)ys9OrFM5`Qw0292Ciyq>zC>8(TkG1O;#UUh?#I08kuwpS_vhufJ0v&p^Yr`=^WG7!qVG(8n9u7=J64fr zQq7B|9rzl7s)I_|8UeVp?=cqGILQ}0O(n+^vJz=vFBU9JmG$=DWzi+qCHw@D0a7`M zA`%pmU8+8W{u0{2*^tg&3;I&i`4`{YJe_n8 z{viTJZL?$}#l9w${3mydrW>Z%nY!WXf$HJv5$Zw4F%7^mXWsZ-s&olv31;C*KlH)j z?j?Eika^cI`l>)WJ*ga?%>0HwJm{%<)OP8pdvwMG@fm;Ca`jfy7ixY-sic42*f&ld zJg3(O0~;=Zsp@cdUj@&Zj~#~LX=F5Ws@!Ik0-~(wlbJO6&)S~s6WrAW9lrQ%6+S03 z&P&xJ{;BC%2s%J#uxZy3=Fc}fkwE9(T}QAK9b{FT!L3^PQ~;#X$T|9v&JFq)ru$h|ls zvPxYyWT}V&Dol3#)t6pVE4nIClEq=r++eGcG-tkOW4{n$Ra~3z?`@_gXRUiR`SrhY4K z#>C+t>pNtm>!Zw*;p^qI0|g<)Ob`r0jaN6asw2ZGLT}bMbHnQ$OH8cR7{Rq?=4%&x z2Qe&O`w$~b%fuo>fkgT`PVx=uto@&SdDpIXL)<da|A*x(b?o zdUj^iN+B9%;2{1URo7=%m@r*RJi3fQNO_`AZY;b#tClm;A}NQF#!Y;pMMdh=^fO@9 z>J>Xv^joKJM>M7x=xh!oSLO3JlxVwTn$DPHdGsnkAvB)9d)IE6ZHgd1vd+Z;W1d682CBy4zti z&6;T6!rzSKIy&zKKfAx9J%7q-=Mac{u-_GIYEaZt*`h25Ne?ch`E_c2{pGA<;nVkx z102u6#||N$g5MhA{!rFwaI(;8$S{1DePGc^L~j6?Q$2QMIO09 zPdma#_kX(|;oOau(pX877ac9V4O8x3g{Mdbr6oS)7 zN0v#H_j!bhUNl;q>GrkeA~){;lCg@&Mg5(z%E1HV`d7{>_}@9JZ(VJn>=HKC4q{My zLpw8D2OD@&E}T?=SV7rE-XI?4H+E(aOI8sZOC$NW=!leE6MG6ycn2;fB4XpB!^#Z= zQ?P=-+!R0#4h{+c2LPbUF6{uZG&6i-ZDI+f;6P`8V{ZtxcA((p;6i6ds6r4x005m` z6k;m{H8U}FK+J;+syaZe)G2u2J;eI(G+`)^0+C~@0#BIzJLi_?-}e8NR15?I|34|k zx>2LneiYApj|7nW4k1sp9h-vz^G);Jq7ONB*clw!(IJ2QT3sYWS)>yb_Ual2Um3r5 zw706UJD48HLY73$&Gm=sl|EYND&Uk>VT!eN_p49f6HS<{TU>u{4&#WYh1dwy^E8il ziH`_=$2m8k)y$Q2yDZQluP+AZbND!Yi7Co@fwHnw2pV1bo*=wGx2n7Urt$y1@imz1&#&nK47Nw zT-dLY@^1NHY?5B#-Qf9?`lA_={@NnLpmwJGQG7&oU}0>) ziZ`GdjY(jIKi2Q?e+d=de}nq3pkP;ZG;lyf$Xh!{=x?qF#2$)p%>NM^W_I=tqNWf# zgv;e1fAtY=)-W@2FtyhKb8%3Bfj|mw00#vR4=)857d&XdU z(4fLD4>dA_AWjHkeJ)-u3LZ|NF1w_ijiW6*A6^xXD#Y5}7O{k(E4!#F{9rhl8A4Sg zMcAb&9N>rx39*a9v4(4~r$8jq|MLt0{*hTPYU2nu0sub&aQG~$!9>qU@%LGVw1{ZAdD5crj3WAdl2KV62-uIT7sX=aUZ*>8aV1F3(c z_P=p-FtxG!8!9*^U<3>RcoByeFaipAK|lhB5)AqaI)n^@hmeEwxOw0OKK@%C0pZ{C z5o^F{FbEE(DEt!$_$B<8DlYiaV7ME855ql#Py+_S#o(c8`L;d6lqRR~$cn(zq-4};(pf)4`xt=`PWS`7YO27?$MdgtpDP{`vCa4 z{2x3Z5bm@8-~oUj5Zv+q!Gl}N`CoDX0N4M*gTIpgb1nb?;)Y)s|FIqb0Ot6gw!m#h zTnhg~j+YZ2)c?r?0yzIm4hZ1=FTFrc;D6}=a`OJeW(PY6{AFi{I1;L6ZcsR+>?$@k z@FNVDLEL!K*2XpzfZwk|I3Y%%Lm?mm76XGtKw?0k2(JV$kO#;s#>p!o!6gRf5#f;l j@(7{-|3%=32kuUL2Z)`+Z(jm{U>-0!Ev>ks1p5C2Hj`#V literal 0 HcmV?d00001 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 From ec02936758241e21726f9179469b42e4e78444b1 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Mon, 27 Jun 2022 17:36:20 +0300 Subject: [PATCH 60/65] Fix tests, formatting --- .../keeper/msg_server_create_resource.go | 3 ++- x/resource/tests/create_resource_test.go | 19 ++++++++++--------- x/resource/tests/setup.go | 1 - .../tx_msg_create_resource_payload_test.go | 19 ++----------------- x/resource/utils/media_type_test.go | 12 ++++++------ 5 files changed, 20 insertions(+), 34 deletions(-) diff --git a/x/resource/keeper/msg_server_create_resource.go b/x/resource/keeper/msg_server_create_resource.go index 7d5a383e4..aea4be33c 100644 --- a/x/resource/keeper/msg_server_create_resource.go +++ b/x/resource/keeper/msg_server_create_resource.go @@ -3,9 +3,10 @@ package keeper import ( "context" "crypto/sha256" - "github.com/cheqd/cheqd-node/x/resource/utils" "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" diff --git a/x/resource/tests/create_resource_test.go b/x/resource/tests/create_resource_test.go index 1bf251971..ce4b95b9d 100644 --- a/x/resource/tests/create_resource_test.go +++ b/x/resource/tests/create_resource_test.go @@ -22,6 +22,7 @@ func TestCreateResource(t *testing.T) { name string signerKeys map[string]ed25519.PrivateKey msg *types.MsgCreateResourcePayload + mediaType string previousVersionId string errMsg string }{ @@ -36,9 +37,9 @@ func TestCreateResource(t *testing.T) { Id: ResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, - MediaType: JsonResourceType, Data: []byte(SchemaData), }, + mediaType: JsonResourceType, previousVersionId: "", }, { @@ -52,9 +53,9 @@ func TestCreateResource(t *testing.T) { Id: ResourceId, Name: ExistingResource().Header.Name, ResourceType: ExistingResource().Header.ResourceType, - MediaType: ExistingResource().Header.MediaType, Data: ExistingResource().Data, }, + mediaType: ExistingResource().Header.MediaType, previousVersionId: ExistingResource().Header.Id, }, { @@ -66,10 +67,10 @@ func TestCreateResource(t *testing.T) { Id: ResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, - MediaType: JsonResourceType, Data: []byte(SchemaData), }, - errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), + mediaType: JsonResourceType, + errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), }, { valid: false, @@ -80,10 +81,10 @@ func TestCreateResource(t *testing.T) { Id: IncorrectResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, - MediaType: JsonResourceType, Data: []byte(SchemaData), }, - errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), + mediaType: JsonResourceType, + errMsg: fmt.Sprintf("signer: %s: signature is required but not found", ExistingDID), }, { valid: false, @@ -94,10 +95,10 @@ func TestCreateResource(t *testing.T) { Id: IncorrectResourceId, Name: "Test Resource Name", ResourceType: CLSchemaType, - MediaType: JsonResourceType, Data: []byte(SchemaData), }, - errMsg: fmt.Sprintf("did:cheqd:test:%s: not found", NotFoundDIDIdentifier), + mediaType: JsonResourceType, + errMsg: fmt.Sprintf("did:cheqd:test:%s: not found", NotFoundDIDIdentifier), }, } @@ -117,7 +118,7 @@ func TestCreateResource(t *testing.T) { require.Equal(t, tc.msg.CollectionId, resource.Header.CollectionId) require.Equal(t, tc.msg.Id, resource.Header.Id) - require.Equal(t, tc.msg.MediaType, resource.Header.MediaType) + 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) diff --git a/x/resource/tests/setup.go b/x/resource/tests/setup.go index 4380d905c..1709e37f2 100644 --- a/x/resource/tests/setup.go +++ b/x/resource/tests/setup.go @@ -95,7 +95,6 @@ func GenerateCreateResourcePayload(resource types.Resource) *types.MsgCreateReso Id: resource.Header.Id, Name: resource.Header.Name, ResourceType: resource.Header.ResourceType, - MediaType: resource.Header.MediaType, Data: resource.Data, } } diff --git a/x/resource/types/tx_msg_create_resource_payload_test.go b/x/resource/types/tx_msg_create_resource_payload_test.go index d710dec0a..26fb75ab6 100644 --- a/x/resource/types/tx_msg_create_resource_payload_test.go +++ b/x/resource/types/tx_msg_create_resource_payload_test.go @@ -20,7 +20,6 @@ func TestMsgCreateResourcePayloadValidation(t *testing.T) { Id: "ba62c728-cb15-498b-8e9e-9259cc242186", Name: "Test Resource", ResourceType: "CL-Schema", - MediaType: "application/json", Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, }, isValid: true, @@ -31,25 +30,11 @@ func TestMsgCreateResourcePayloadValidation(t *testing.T) { CollectionId: "123456789abcdefg", Id: "ba62c728-cb15-498b-8e9e-9259cc242186", Name: "Test Resource", - ResourceType: "Not-CL-Schema", - MediaType: "image/png", + ResourceType: "", Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, }, isValid: false, - errorMsg: "resource_type: Not-CL-Schema resource type is not allowed. Only CL-Schema, JSONSchema2020.", - }, - { - name: "negative mime type", - struct_: &MsgCreateResourcePayload{ - CollectionId: "123456789abcdefg", - Id: "ba62c728-cb15-498b-8e9e-9259cc242186", - Name: "Test Resource", - ResourceType: "CL-Schema", - MediaType: "text/data", - Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, - }, - isValid: false, - errorMsg: "media_type: text/data mime type is not allowed. Only application/json, application/octet-stream, text/plain, image/apng, image/avif, image/gif, image/jpeg, image/png, image/svg+xml, image/webp.", + errorMsg: "resource_type: cannot be blank.", }, } diff --git a/x/resource/utils/media_type_test.go b/x/resource/utils/media_type_test.go index 719cb1904..becbc3578 100644 --- a/x/resource/utils/media_type_test.go +++ b/x/resource/utils/media_type_test.go @@ -10,13 +10,13 @@ import ( func TestValidateMediaType(t *testing.T) { cases := []struct { path string - mt 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" }, + {"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 { From 59ce8f337cf1c39b8ae5b31adefe426862299df2 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Mon, 27 Jun 2022 17:38:41 +0300 Subject: [PATCH 61/65] Fix linter issues --- tests/e2e-bash/tests/test_query_all_resource_versions.sh | 1 - tests/e2e-bash/tests/test_query_collection_resources.sh | 1 - 2 files changed, 2 deletions(-) diff --git a/tests/e2e-bash/tests/test_query_all_resource_versions.sh b/tests/e2e-bash/tests/test_query_all_resource_versions.sh index a81fe479a..ec020e3fa 100644 --- a/tests/e2e-bash/tests/test_query_all_resource_versions.sh +++ b/tests/e2e-bash/tests/test_query_all_resource_versions.sh @@ -108,7 +108,6 @@ assert_tx_successful "$RESULT" RESOURCE2_ID=$(uuidgen) RESOURCE2_DATA=$(echo '{ "content": "resource 2" }'| base64 -w 0); RESOURCE2_NAME="Resource 2" -RESOURCE2_MEDIA_TYPE="application/json" RESOURCE2_RESOURCE_TYPE="CL-Schema" MSG_CREATE_RESOURCE2='{ diff --git a/tests/e2e-bash/tests/test_query_collection_resources.sh b/tests/e2e-bash/tests/test_query_collection_resources.sh index a68e26f0a..96ef3a92e 100644 --- a/tests/e2e-bash/tests/test_query_collection_resources.sh +++ b/tests/e2e-bash/tests/test_query_collection_resources.sh @@ -135,7 +135,6 @@ assert_tx_successful "$RESULT" RESOURCE2_ID=$(uuidgen) RESOURCE2_DATA=$(echo '{ "content": "resource 2" }' | base64 -w 0); RESOURCE2_NAME="Resource 2" -RESOURCE2_MEDIA_TYPE="application/json" RESOURCE2_RESOURCE_TYPE="CL-Schema" MSG_CREATE_RESOURCE2='{ From 1085dc183d85fd0e798afac5bbfba50006f17f23 Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Mon, 27 Jun 2022 17:45:35 +0300 Subject: [PATCH 62/65] Allow any value for service-type in did docs --- x/cheqd/types/did_service.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) 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), ) } From e7fe839129b098edf7cacb307479be2d1a39437e Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Wed, 29 Jun 2022 15:47:25 +0300 Subject: [PATCH 63/65] Switch from positional arguments to flags --- go.mod | 2 +- go.sum | 4 +- tests/e2e-bash/tests/test_create_resource.sh | 8 ++- .../tests/test_query_all_resource_versions.sh | 53 +++++++------- .../tests/test_query_collection_resources.sh | 55 +++++++-------- x/resource/client/cli/tx.go | 9 ++- x/resource/client/cli/tx_create_resource.go | 69 ++++++++++++++++--- .../client/cli/tx_create_resource_raw.go | 63 ----------------- 8 files changed, 125 insertions(+), 138 deletions(-) delete mode 100644 x/resource/client/cli/tx_create_resource_raw.go diff --git a/go.mod b/go.mod index a3076e242..ad50a7468 100644 --- a/go.mod +++ b/go.mod @@ -18,7 +18,7 @@ require ( 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 diff --git a/go.sum b/go.sum index d38527885..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= @@ -925,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= diff --git a/tests/e2e-bash/tests/test_create_resource.sh b/tests/e2e-bash/tests/test_create_resource.sh index 7d9d6fe12..024555882 100644 --- a/tests/e2e-bash/tests/test_create_resource.sh +++ b/tests/e2e-bash/tests/test_create_resource.sh @@ -51,7 +51,13 @@ RESOURCE_DATA='{ "content": "test data" }'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource ${ID} ${RESOURCE_ID} "${RESOURCE_NAME}" ${RESOURCE_RESOURCE_TYPE} <(echo "${RESOURCE_DATA}") "${KEY_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +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" diff --git a/tests/e2e-bash/tests/test_query_all_resource_versions.sh b/tests/e2e-bash/tests/test_query_all_resource_versions.sh index ec020e3fa..9b76d9a20 100644 --- a/tests/e2e-bash/tests/test_query_all_resource_versions.sh +++ b/tests/e2e-bash/tests/test_query_all_resource_versions.sh @@ -47,19 +47,17 @@ RESOURCE1_V1_ID=$(uuidgen) RESOURCE1_NAME="Resource 1" RESOURCE1_MEDIA_TYPE="application/json" RESOURCE1_RESOURCE_TYPE="CL-Schema" -RESOURCE1_V1_DATA=$(echo '{ "content": "resource 1 v1" }'| base64 -w 0); - -MSG_CREATE_RESOURCE1='{ - "collection_id": "'${ID1}'", - "id": "'${RESOURCE1_V1_ID}'", - "name": "'${RESOURCE1_NAME}'", - "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", - "data": "'${RESOURCE1_V1_DATA}'" -}'; +RESOURCE1_V1_DATA='{ "content": "resource 1 v1" }'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE1}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +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" @@ -79,25 +77,23 @@ EXPECTED_RES1_V1_HEADER='{ 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")" "${RESOURCE1_V1_DATA}" +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=$(echo '{ "content": "resource 1 v2" }'| base64 -w 0); - -MSG_CREATE_RESOURCE1_V2='{ - "collection_id": "'${ID1}'", - "id": "'${RESOURCE1_V2_ID}'", - "name": "'${RESOURCE1_NAME}'", - "resource_type": "'${RESOURCE1_RESOURCE_TYPE}'", - "data": "'${RESOURCE1_V2_DATA}'" -}'; +RESOURCE1_V2_DATA='{ "content": "resource 1 v2" }'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE1_V2}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +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" @@ -110,17 +106,16 @@ RESOURCE2_DATA=$(echo '{ "content": "resource 2" }'| base64 -w 0); RESOURCE2_NAME="Resource 2" RESOURCE2_RESOURCE_TYPE="CL-Schema" -MSG_CREATE_RESOURCE2='{ - "collection_id": "'${ID1}'", - "id": "'${RESOURCE2_ID}'", - "name": "'${RESOURCE2_NAME}'", - "resource_type": "'${RESOURCE2_RESOURCE_TYPE}'", - "data": "'${RESOURCE2_DATA}'" -}'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE2}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +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" diff --git a/tests/e2e-bash/tests/test_query_collection_resources.sh b/tests/e2e-bash/tests/test_query_collection_resources.sh index 96ef3a92e..c88acb24d 100644 --- a/tests/e2e-bash/tests/test_query_collection_resources.sh +++ b/tests/e2e-bash/tests/test_query_collection_resources.sh @@ -47,19 +47,18 @@ RESOURCE1_V1_ID=$(uuidgen) RESOURCE1_V1_NAME="Resource 1" RESOURCE1_V1_MEDIA_TYPE="application/json" RESOURCE1_V1_RESOURCE_TYPE="CL-Schema" -RESOURCE1_V1_DATA=$(echo '{ "content": "resource 1 v1" }'| base64 -w 0); +RESOURCE1_V1_DATA='{ "content": "resource 1 v1" }'; -MSG_CREATE_RESOURCE1='{ - "collection_id": "'${ID1}'", - "id": "'${RESOURCE1_V1_ID}'", - "name": "'${RESOURCE1_V1_NAME}'", - "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", - "data": "'${RESOURCE1_V1_DATA}'" -}'; # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE1}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +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" @@ -79,25 +78,23 @@ EXPECTED_RES1_V1_HEADER='{ 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")" "${RESOURCE1_V1_DATA}" +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=$(echo '{ "content": "resource 1 v2" }' | base64 -w 0); - -MSG_CREATE_RESOURCE1_V2='{ - "collection_id": "'${ID1}'", - "id": "'${RESOURCE1_V2_ID}'", - "name": "'${RESOURCE1_V1_NAME}'", - "resource_type": "'${RESOURCE1_V1_RESOURCE_TYPE}'", - "data": "'${RESOURCE1_V2_DATA}'" -}'; +RESOURCE1_V2_DATA='{ "content": "resource 1 v2" }' # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE1_V2}" "${KEY1_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +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" @@ -133,21 +130,19 @@ assert_tx_successful "$RESULT" ########## Creating Resource 2 ########## RESOURCE2_ID=$(uuidgen) -RESOURCE2_DATA=$(echo '{ "content": "resource 2" }' | base64 -w 0); +RESOURCE2_DATA='{ "content": "resource 2" }' RESOURCE2_NAME="Resource 2" RESOURCE2_RESOURCE_TYPE="CL-Schema" -MSG_CREATE_RESOURCE2='{ - "collection_id": "'${ID2}'", - "id": "'${RESOURCE2_ID}'", - "name": "'${RESOURCE2_NAME}'", - "resource_type": "'${RESOURCE2_RESOURCE_TYPE}'", - "data": "'${RESOURCE2_DATA}'" -}'; - # Post the message # shellcheck disable=SC2086 -RESULT=$(cheqd-noded tx resource create-resource-raw "${MSG_CREATE_RESOURCE2}" "${KEY2_ID}" "${ALICE_VER_PRIV_BASE_64}" \ +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" diff --git a/x/resource/client/cli/tx.go b/x/resource/client/cli/tx.go index 9e2f05689..36fdfa128 100644 --- a/x/resource/client/cli/tx.go +++ b/x/resource/client/cli/tx.go @@ -18,8 +18,13 @@ func GetTxCmd() *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdCreateResource(), - CmdCreateResourceRaw()) + 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 index 7373ab431..06a30d58e 100644 --- a/x/resource/client/cli/tx_create_resource.go +++ b/x/resource/client/cli/tx_create_resource.go @@ -11,29 +11,56 @@ import ( "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] [id] [name] [resource-type] [file-path] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", + Use: "create-resource [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-1] is base base64 encoded ed25519 private key for 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(5), + Args: cobra.MinimumNArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } - collectionId := args[0] + collectionId, err := cmd.Flags().GetString(FlagCollectionId) + if err != nil { + return err + } - id := args[1] - name := args[2] - resourceType := args[3] + resourceId, err := cmd.Flags().GetString(FlagResourceId) + if err != nil { + return err + } + + resourceName, err := cmd.Flags().GetString(FlagResourceName) + if err != nil { + return err + } - data, err := ioutil.ReadFile(args[4]) + 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 } @@ -41,14 +68,14 @@ func CmdCreateResource() *cobra.Command { // Prepare payload payload := types.MsgCreateResourcePayload{ CollectionId: collectionId, - Id: id, - Name: name, + Id: resourceId, + Name: resourceName, ResourceType: resourceType, Data: data, } // Read signatures - signInputs, err := cheqdcli.GetSignInputs(clientCtx, args[5:]) + signInputs, err := cheqdcli.GetSignInputs(clientCtx, args) if err != nil { return err } @@ -74,5 +101,25 @@ func CmdCreateResource() *cobra.Command { flags.AddTxFlagsToCmd(cmd) + cmd.Flags().String(FlagCollectionId, "", "Collection ID") + err := cobra.MarkFlagRequired(cmd.Flags(), FlagCollectionId) + panicIfErr(err) + + cmd.Flags().String(FlagResourceId, "", "Resource ID") + err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceId) + panicIfErr(err) + + cmd.Flags().String(FlagResourceName, "", "Resource name") + err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceName) + panicIfErr(err) + + cmd.Flags().String(FlagResourceType, "", "Resource type") + err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceType) + panicIfErr(err) + + cmd.Flags().String(FlagResourceFile, "", "Resource file") + err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceFile) + panicIfErr(err) + return cmd } diff --git a/x/resource/client/cli/tx_create_resource_raw.go b/x/resource/client/cli/tx_create_resource_raw.go deleted file mode 100644 index d78053113..000000000 --- a/x/resource/client/cli/tx_create_resource_raw.go +++ /dev/null @@ -1,63 +0,0 @@ -package cli - -import ( - 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" -) - -func CmdCreateResourceRaw() *cobra.Command { - cmd := &cobra.Command{ - Use: "create-resource-raw [payload-json] [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", - Short: "Creates a new Resource using raw payload. For testing purposes.", - Long: "Creates a new Resource. " + - "[payload-json] is JSON encoded MsgCreateResourcePayload. " + - "[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-1] 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(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - payloadJson, signInputs, err := cheqdcli.GetPayloadAndSignInputs(clientCtx, args) - if err != nil { - return err - } - - // Unmarshal payload - var payload types.MsgCreateResourcePayload - err = clientCtx.Codec.UnmarshalJSON([]byte(payloadJson), &payload) - 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) - - return cmd -} From f3a3bb563789bc6bae445e8ce42f9034bf6751cb Mon Sep 17 00:00:00 2001 From: Alexandr Kolesov Date: Wed, 29 Jun 2022 16:02:50 +0300 Subject: [PATCH 64/65] Remove resource_type, media_type form the versioning logic --- go.mod | 2 +- proto/resource/v1/query.proto | 10 +- .../tests/test_query_all_resource_versions.sh | 2 +- .../client/cli/query_all_resource_versions.go | 6 +- x/resource/keeper/keeper_resource.go | 11 +- x/resource/keeper/query.go | 2 +- .../keeper/query_all_resource_versions.go | 4 +- .../query_server_all_resource_versions.go | 2 +- .../tests/query_all_resource_versions_test.go | 4 - x/resource/types/query.pb.go | 167 ++++-------------- x/resource/types/query.pb.gw.go | 32 ++-- 11 files changed, 63 insertions(+), 179 deletions(-) diff --git a/go.mod b/go.mod index ad50a7468..ac059b06c 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ 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.5 + 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 diff --git a/proto/resource/v1/query.proto b/proto/resource/v1/query.proto index 2d7d266f2..ba341e9cc 100644 --- a/proto/resource/v1/query.proto +++ b/proto/resource/v1/query.proto @@ -13,10 +13,10 @@ service Query { 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"; + 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"; + option (google.api.http).get = "/1.0/identifiers/{collection_id}/resources/versions/{name}"; } } @@ -38,10 +38,8 @@ message QueryGetCollectionResourcesResponse { } message QueryGetAllResourceVersionsRequest { - string collection_id = 1; // Mapped to URL path - string name = 2; // Mapped to URL parameter `name` - string resource_type = 3; // Mapped to URL parameter `resource_type` - string media_type = 4; // Mapped to URL parameter `media_type` + string collection_id = 1; + string name = 2; } message QueryGetAllResourceVersionsResponse { diff --git a/tests/e2e-bash/tests/test_query_all_resource_versions.sh b/tests/e2e-bash/tests/test_query_all_resource_versions.sh index 9b76d9a20..d901d0655 100644 --- a/tests/e2e-bash/tests/test_query_all_resource_versions.sh +++ b/tests/e2e-bash/tests/test_query_all_resource_versions.sh @@ -132,7 +132,7 @@ EXPECTED_RES1_V2_HEADER='{ }' # shellcheck disable=SC2086 -RESULT=$(cheqd-noded query resource all-resource-versions "${ID1}" "${RESOURCE1_NAME}" ${RESOURCE1_RESOURCE_TYPE} ${RESOURCE1_MEDIA_TYPE} ${QUERY_PARAMS}) +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}" diff --git a/x/resource/client/cli/query_all_resource_versions.go b/x/resource/client/cli/query_all_resource_versions.go index 97be4756c..79c60392c 100644 --- a/x/resource/client/cli/query_all_resource_versions.go +++ b/x/resource/client/cli/query_all_resource_versions.go @@ -13,7 +13,7 @@ func CmdGetAllResourceVersions() *cobra.Command { cmd := &cobra.Command{ Use: "all-resource-versions [collectionId] [name] [resourceType] [mediaType]", Short: "Query all resource versions", - Args: cobra.ExactArgs(4), + Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) @@ -21,14 +21,10 @@ func CmdGetAllResourceVersions() *cobra.Command { collectionId := args[0] name := args[1] - resourceType := args[2] - mediaType := args[3] params := &types.QueryGetAllResourceVersionsRequest{ CollectionId: collectionId, Name: name, - ResourceType: resourceType, - MediaType: mediaType, } resp, err := queryClient.AllResourceVersions(context.Background(), params) diff --git a/x/resource/keeper/keeper_resource.go b/x/resource/keeper/keeper_resource.go index f2d0aacd9..1d957b56d 100644 --- a/x/resource/keeper/keeper_resource.go +++ b/x/resource/keeper/keeper_resource.go @@ -88,7 +88,7 @@ func (k Keeper) HasResource(ctx *sdk.Context, collectionId string, id string) bo return store.Has(GetResourceHeaderKeyBytes(collectionId, id)) } -func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, resourceType, mediaType string) []*types.ResourceHeader { +func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name string) []*types.ResourceHeader { store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, GetResourceHeaderCollectionPrefixBytes(collectionId)) @@ -100,9 +100,7 @@ func (k Keeper) GetAllResourceVersions(ctx *sdk.Context, collectionId, name, res var val types.ResourceHeader k.cdc.MustUnmarshal(iterator.Value(), &val) - if val.Name == name && - val.ResourceType == resourceType && - val.MediaType == mediaType { + if val.Name == name { result = append(result, &val) } } @@ -137,10 +135,7 @@ func (k Keeper) GetLastResourceVersionHeader(ctx *sdk.Context, collectionId, nam var val types.ResourceHeader k.cdc.MustUnmarshal(iterator.Value(), &val) - if val.Name == name && - val.ResourceType == resourceType && - val.MediaType == mediaType && - val.NextVersionId == "" { + if val.Name == name && val.NextVersionId == "" { return val, true } } diff --git a/x/resource/keeper/query.go b/x/resource/keeper/query.go index 58de3f309..bb3ff6131 100644 --- a/x/resource/keeper/query.go +++ b/x/resource/keeper/query.go @@ -23,7 +23,7 @@ func NewQuerier(k Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *code case types.QueryGetCollectionResources: return collectionResources(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1]) case types.QueryGetAllResourceVersions: - return allResourceVersions(ctx, k, cheqdKeeper, legacyQuerierCdc, path[1], path[2], path[3], path[4]) + 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]) diff --git a/x/resource/keeper/query_all_resource_versions.go b/x/resource/keeper/query_all_resource_versions.go index addd68786..6059feba9 100644 --- a/x/resource/keeper/query_all_resource_versions.go +++ b/x/resource/keeper/query_all_resource_versions.go @@ -8,14 +8,12 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -func allResourceVersions(ctx sdk.Context, keeper Keeper, cheqdKeeper cheqdkeeper.Keeper, legacyQuerierCdc *codec.LegacyAmino, collectionId, name, resourceType, mediaType string) ([]byte, error) { +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, - ResourceType: resourceType, - MediaType: mediaType, }) if err != nil { return nil, err diff --git a/x/resource/keeper/query_server_all_resource_versions.go b/x/resource/keeper/query_server_all_resource_versions.go index f4e42d9f7..bdc07294b 100644 --- a/x/resource/keeper/query_server_all_resource_versions.go +++ b/x/resource/keeper/query_server_all_resource_versions.go @@ -26,7 +26,7 @@ func (m queryServer) AllResourceVersions(c context.Context, req *types.QueryGetA } // Get all versions - versions := m.GetAllResourceVersions(&ctx, req.CollectionId, req.Name, req.ResourceType, req.MediaType) + versions := m.GetAllResourceVersions(&ctx, req.CollectionId, req.Name) return &types.QueryGetAllResourceVersionsResponse{ Resources: versions, diff --git a/x/resource/tests/query_all_resource_versions_test.go b/x/resource/tests/query_all_resource_versions_test.go index 6d066de4d..fd90c72da 100644 --- a/x/resource/tests/query_all_resource_versions_test.go +++ b/x/resource/tests/query_all_resource_versions_test.go @@ -40,8 +40,6 @@ func TestQueryGetAllResourceVersions(t *testing.T) { msg: &types.QueryGetAllResourceVersionsRequest{ CollectionId: ExistingDIDIdentifier, Name: existingResource.Header.Name, - ResourceType: existingResource.Header.ResourceType, - MediaType: existingResource.Header.MediaType, }, response: &types.QueryGetAllResourceVersionsResponse{ Resources: []*types.ResourceHeader{existingResource.Header}, @@ -54,8 +52,6 @@ func TestQueryGetAllResourceVersions(t *testing.T) { msg: &types.QueryGetAllResourceVersionsRequest{ CollectionId: NotFoundDIDIdentifier, Name: existingResource.Header.Name, - ResourceType: existingResource.Header.ResourceType, - MediaType: existingResource.Header.MediaType, }, response: nil, errMsg: fmt.Sprintf("did:cheqd:test:%s: DID Doc not found", NotFoundDIDIdentifier), diff --git a/x/resource/types/query.pb.go b/x/resource/types/query.pb.go index aa83939ac..a54d8ac82 100644 --- a/x/resource/types/query.pb.go +++ b/x/resource/types/query.pb.go @@ -215,8 +215,6 @@ func (m *QueryGetCollectionResourcesResponse) GetResources() []*ResourceHeader { 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"` - ResourceType string `protobuf:"bytes,3,opt,name=resource_type,json=resourceType,proto3" json:"resource_type,omitempty"` - MediaType string `protobuf:"bytes,4,opt,name=media_type,json=mediaType,proto3" json:"media_type,omitempty"` } func (m *QueryGetAllResourceVersionsRequest) Reset() { *m = QueryGetAllResourceVersionsRequest{} } @@ -266,20 +264,6 @@ func (m *QueryGetAllResourceVersionsRequest) GetName() string { return "" } -func (m *QueryGetAllResourceVersionsRequest) GetResourceType() string { - if m != nil { - return m.ResourceType - } - return "" -} - -func (m *QueryGetAllResourceVersionsRequest) GetMediaType() string { - if m != nil { - return m.MediaType - } - return "" -} - type QueryGetAllResourceVersionsResponse struct { Resources []*ResourceHeader `protobuf:"bytes,1,rep,name=resources,proto3" json:"resources,omitempty"` } @@ -336,39 +320,38 @@ func init() { func init() { proto.RegisterFile("resource/v1/query.proto", fileDescriptor_10aac3b48339734d) } var fileDescriptor_10aac3b48339734d = []byte{ - // 510 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xc1, 0x6e, 0xd3, 0x40, - 0x10, 0xcd, 0xa6, 0x01, 0x35, 0x5b, 0xe0, 0xb0, 0x3d, 0xd4, 0xb2, 0xa8, 0x55, 0xb9, 0x07, 0x2a, - 0xd4, 0x7a, 0x49, 0x2a, 0xe8, 0x81, 0x53, 0x5b, 0x09, 0xa8, 0x90, 0x90, 0x88, 0x10, 0x07, 0x2e, - 0x91, 0xeb, 0x1d, 0xd2, 0x95, 0x1c, 0xaf, 0xe3, 0xdd, 0x44, 0x44, 0x55, 0x2f, 0x7c, 0x01, 0x12, - 0x5f, 0xc0, 0x3f, 0xf0, 0x11, 0x1c, 0x23, 0x71, 0x81, 0x1b, 0x4a, 0xb8, 0xf2, 0x0f, 0xc8, 0x6b, - 0xaf, 0x13, 0x44, 0x12, 0x1c, 0xa1, 0x5e, 0x6c, 0x6b, 0x67, 0xde, 0x9b, 0xf7, 0x66, 0x66, 0x8d, - 0xb7, 0x12, 0x90, 0xa2, 0x9f, 0x04, 0x40, 0x07, 0x0d, 0xda, 0xeb, 0x43, 0x32, 0xf4, 0xe2, 0x44, - 0x28, 0x41, 0xb6, 0x83, 0x0b, 0xe8, 0x31, 0xce, 0x3c, 0xfd, 0x8e, 0x04, 0x03, 0xcf, 0xa4, 0x7a, - 0x83, 0x86, 0x7d, 0xb7, 0x23, 0x44, 0x27, 0x04, 0xea, 0xc7, 0x9c, 0xfa, 0x51, 0x24, 0x94, 0xaf, - 0xb8, 0x88, 0x64, 0x06, 0xb6, 0xed, 0x59, 0xd6, 0x02, 0xa6, 0x63, 0xee, 0x0b, 0xbc, 0xf5, 0x32, - 0xad, 0xf3, 0x14, 0x54, 0x2b, 0x8f, 0xb4, 0xa0, 0xd7, 0x07, 0xa9, 0xc8, 0x2e, 0xbe, 0x1d, 0x88, - 0x30, 0x84, 0x20, 0xe5, 0x6a, 0x73, 0x66, 0xa1, 0x1d, 0xb4, 0x57, 0x6f, 0xdd, 0x9a, 0x1e, 0x9e, - 0x31, 0x72, 0x07, 0x57, 0x39, 0xb3, 0xaa, 0x3a, 0x52, 0xe5, 0xcc, 0x6d, 0x63, 0xeb, 0x6f, 0x3e, - 0x19, 0x8b, 0x48, 0x02, 0x39, 0xc5, 0xeb, 0xa6, 0xba, 0xe6, 0xda, 0x68, 0xde, 0xf3, 0x96, 0xfa, - 0xf2, 0x0a, 0x8a, 0x02, 0xe8, 0x9e, 0x61, 0xd7, 0x14, 0x38, 0x2d, 0x84, 0x98, 0x3c, 0xb9, 0x8a, - 0x76, 0x37, 0xc1, 0xbb, 0x4b, 0xa9, 0x72, 0xd9, 0xcf, 0x71, 0xdd, 0x54, 0x97, 0x16, 0xda, 0x59, - 0xdb, 0xdb, 0x68, 0x1e, 0x94, 0xd4, 0xfd, 0x0c, 0x7c, 0x06, 0x49, 0x6b, 0x8a, 0x77, 0x3f, 0xa1, - 0xa9, 0xfe, 0xe3, 0x30, 0x34, 0x89, 0xaf, 0x21, 0x91, 0xe9, 0xc4, 0x56, 0xea, 0x3d, 0xc1, 0xb5, - 0xc8, 0xef, 0x42, 0xde, 0x7d, 0xfd, 0x9d, 0x02, 0x4d, 0xb1, 0xb6, 0x1a, 0xc6, 0x60, 0xad, 0x65, - 0x40, 0x73, 0xf8, 0x6a, 0x18, 0x03, 0xd9, 0xc6, 0xb8, 0x0b, 0x8c, 0xfb, 0x59, 0x46, 0x4d, 0x67, - 0xd4, 0xf5, 0x49, 0x1a, 0x9e, 0xed, 0xcb, 0x5c, 0x89, 0xd7, 0xd0, 0x97, 0xe6, 0xaf, 0x1a, 0xbe, - 0xa1, 0x8b, 0x92, 0xcf, 0x08, 0xaf, 0x9b, 0x3c, 0xf2, 0xe8, 0x1f, 0x84, 0x0b, 0x76, 0xd7, 0x3e, - 0x5a, 0x19, 0x97, 0x99, 0x72, 0x8f, 0xde, 0x7f, 0xfd, 0xf9, 0xb1, 0xda, 0x20, 0x94, 0x36, 0xbc, - 0x07, 0x94, 0x33, 0x88, 0x14, 0x7f, 0xcb, 0x21, 0x91, 0xf4, 0xf2, 0x8f, 0x81, 0x5c, 0x15, 0x17, - 0x49, 0xd2, 0x4b, 0xce, 0xae, 0xc8, 0x08, 0xe1, 0xcd, 0x39, 0x5b, 0x44, 0x8e, 0x4b, 0x2a, 0x59, - 0xbc, 0xcc, 0xf6, 0xc9, 0xff, 0x50, 0xe4, 0xbe, 0x9a, 0xda, 0xd7, 0x3e, 0xb9, 0x5f, 0xde, 0x17, - 0xf9, 0x8e, 0xf0, 0xe6, 0x9c, 0x05, 0x28, 0x6d, 0x69, 0xf1, 0x7e, 0x97, 0xb6, 0xb4, 0x64, 0xff, - 0xdc, 0xc7, 0xda, 0xd2, 0x43, 0x72, 0xb8, 0xc2, 0xa8, 0x06, 0x39, 0xc9, 0xc9, 0x93, 0x2f, 0x63, - 0x07, 0x8d, 0xc6, 0x0e, 0xfa, 0x31, 0x76, 0xd0, 0x87, 0x89, 0x53, 0x19, 0x4d, 0x9c, 0xca, 0xb7, - 0x89, 0x53, 0x79, 0xb3, 0xdf, 0xe1, 0xea, 0xa2, 0x7f, 0xee, 0x05, 0xa2, 0x4b, 0xb5, 0xb8, 0xec, - 0x79, 0x90, 0x6a, 0xa4, 0xef, 0x0a, 0x2e, 0x9a, 0xde, 0x1d, 0x79, 0x7e, 0x53, 0xff, 0x46, 0x0f, - 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0x4b, 0xc7, 0xfa, 0x53, 0xba, 0x05, 0x00, 0x00, + // 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. @@ -682,20 +665,6 @@ func (m *QueryGetAllResourceVersionsRequest) MarshalToSizedBuffer(dAtA []byte) ( _ = i var l int _ = l - if len(m.MediaType) > 0 { - i -= len(m.MediaType) - copy(dAtA[i:], m.MediaType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.MediaType))) - i-- - dAtA[i] = 0x22 - } - if len(m.ResourceType) > 0 { - i -= len(m.ResourceType) - copy(dAtA[i:], m.ResourceType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ResourceType))) - i-- - dAtA[i] = 0x1a - } if len(m.Name) > 0 { i -= len(m.Name) copy(dAtA[i:], m.Name) @@ -833,14 +802,6 @@ func (m *QueryGetAllResourceVersionsRequest) Size() (n int) { if l > 0 { n += 1 + l + sovQuery(uint64(l)) } - l = len(m.ResourceType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.MediaType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } return n } @@ -1324,70 +1285,6 @@ func (m *QueryGetAllResourceVersionsRequest) Unmarshal(dAtA []byte) error { } m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: - 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 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.ResourceType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - 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 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.MediaType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) diff --git a/x/resource/types/query.pb.gw.go b/x/resource/types/query.pb.gw.go index 274eb0b51..6186e0bda 100644 --- a/x/resource/types/query.pb.gw.go +++ b/x/resource/types/query.pb.gw.go @@ -163,10 +163,6 @@ func local_request_Query_CollectionResources_0(ctx context.Context, marshaler ru } -var ( - filter_Query_AllResourceVersions_0 = &utilities.DoubleArray{Encoding: map[string]int{"collection_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - 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 @@ -189,11 +185,15 @@ func request_Query_AllResourceVersions_0(ctx context.Context, marshaler runtime. return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collection_id", err) } - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + val, ok = pathParams["name"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name") } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AllResourceVersions_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + + 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)) @@ -223,11 +223,15 @@ func local_request_Query_AllResourceVersions_0(ctx context.Context, marshaler ru return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collection_id", err) } - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + val, ok = pathParams["name"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name") } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AllResourceVersions_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + + 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) @@ -417,9 +421,9 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie 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}, []string{"1.0", "identifiers", "collection_id", "resources"}, "", 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}, []string{"1.0", "identifiers", "collection_id", "resources", "versions"}, "", 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 ( From 9fe9dd3f7fe64f2bc8a339defe2c08f801c424e2 Mon Sep 17 00:00:00 2001 From: Ankur Banerjee Date: Thu, 30 Jun 2022 12:28:24 +0100 Subject: [PATCH 65/65] Clarified usage instructions and flags --- x/resource/client/cli/tx_create_resource.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/x/resource/client/cli/tx_create_resource.go b/x/resource/client/cli/tx_create_resource.go index 06a30d58e..470e15fc4 100644 --- a/x/resource/client/cli/tx_create_resource.go +++ b/x/resource/client/cli/tx_create_resource.go @@ -21,11 +21,11 @@ const ( func CmdCreateResource() *cobra.Command { cmd := &cobra.Command{ - Use: "create-resource [ver-method-id-1] [priv-key-1] [ver-method-id-N] [priv-key-N] ...", + 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." + + "[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), @@ -101,23 +101,23 @@ func CmdCreateResource() *cobra.Command { flags.AddTxFlagsToCmd(cmd) - cmd.Flags().String(FlagCollectionId, "", "Collection ID") + 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") + cmd.Flags().String(FlagResourceId, "", "Resource ID (must be a UUID)") err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceId) panicIfErr(err) - cmd.Flags().String(FlagResourceName, "", "Resource name") + 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") + 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") + cmd.Flags().String(FlagResourceFile, "", "Resource File (path to file to be stored as a resource)") err = cobra.MarkFlagRequired(cmd.Flags(), FlagResourceFile) panicIfErr(err)