@agoric/cosmos 0.34.1 → 0.34.2-calypso-dev-dabccdc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/MAINTAINERS.md +3 -0
  2. package/Makefile +67 -41
  3. package/agoric/config.go +35 -0
  4. package/ante/ante.go +65 -0
  5. package/ante/expected_keepers.go +26 -0
  6. package/ante/inbound.go +137 -0
  7. package/ante/inbound_test.go +228 -0
  8. package/ante/vm_admission.go +65 -0
  9. package/app/app.go +396 -211
  10. package/app/export.go +13 -9
  11. package/app/sim_test.go +4 -4
  12. package/app/upgrade.go +215 -0
  13. package/binding.gyp.in +29 -4
  14. package/buf.work.yaml +4 -0
  15. package/cmd/agd/agvm.go +42 -0
  16. package/cmd/agd/find_binary.go +22 -7
  17. package/cmd/agd/main.go +133 -10
  18. package/cmd/libdaemon/main.go +67 -53
  19. package/cmd/libdaemon/main_test.go +37 -0
  20. package/daemon/cmd/genaccounts.go +22 -18
  21. package/daemon/cmd/root.go +253 -52
  22. package/daemon/cmd/root_test.go +190 -2
  23. package/daemon/cmd/testnet.go +17 -6
  24. package/daemon/main.go +6 -3
  25. package/e2e_test/Makefile +29 -0
  26. package/e2e_test/README.md +100 -0
  27. package/e2e_test/go.mod +217 -0
  28. package/e2e_test/go.sum +1323 -0
  29. package/e2e_test/ibc_conformance_test.go +56 -0
  30. package/e2e_test/pfm_test.go +613 -0
  31. package/e2e_test/util.go +271 -0
  32. package/git-revision.txt +1 -0
  33. package/go.mod +207 -0
  34. package/go.sum +1877 -0
  35. package/package.json +13 -21
  36. package/proto/agoric/swingset/genesis.proto +14 -0
  37. package/proto/agoric/swingset/swingset.proto +6 -3
  38. package/proto/agoric/vlocalchain/.clang-format +7 -0
  39. package/proto/agoric/vlocalchain/vlocalchain.proto +31 -0
  40. package/proto/agoric/vstorage/query.proto +53 -1
  41. package/proto/agoric/vtransfer/genesis.proto +18 -0
  42. package/scripts/protocgen.sh +16 -6
  43. package/third_party/proto/buf.yaml +1 -0
  44. package/third_party/proto/cosmos/base/query/v1beta1/pagination.proto +4 -1
  45. package/third_party/proto/cosmos/base/v1beta1/coin.proto +7 -4
  46. package/third_party/proto/cosmos/upgrade/v1beta1/upgrade.proto +16 -6
  47. package/third_party/proto/cosmos_proto/cosmos.proto +97 -0
  48. package/third_party/proto/google/api/annotations.proto +1 -1
  49. package/third_party/proto/google/api/http.proto +181 -120
  50. package/third_party/proto/google/api/httpbody.proto +9 -6
  51. package/third_party/proto/google/protobuf/any.proto +1 -7
  52. package/third_party/proto/ibc/core/channel/v1/channel.proto +15 -1
  53. package/third_party/proto/ibc/core/client/v1/client.proto +9 -6
  54. package/tools/tools.go +11 -0
  55. package/types/events.go +41 -0
  56. package/types/kv_entry.go +114 -0
  57. package/types/kv_entry_helpers.go +276 -0
  58. package/types/kv_entry_helpers_test.go +237 -0
  59. package/types/kv_entry_test.go +143 -0
  60. package/upgradegaia.sh +75 -0
  61. package/vm/action.go +134 -0
  62. package/vm/action_test.go +149 -0
  63. package/vm/client.go +113 -0
  64. package/vm/client_test.go +182 -0
  65. package/vm/controller.go +49 -0
  66. package/vm/core_proposals.go +51 -0
  67. package/vm/jsonrpcconn/jsonrpcconn.go +160 -0
  68. package/vm/jsonrpcconn/jsonrpcconn_test.go +126 -0
  69. package/vm/proto_json.go +38 -0
  70. package/vm/proto_json_test.go +103 -0
  71. package/vm/server.go +124 -0
  72. package/x/swingset/abci.go +26 -37
  73. package/x/swingset/alias.go +9 -6
  74. package/x/swingset/client/cli/query.go +2 -2
  75. package/x/swingset/client/cli/tx.go +52 -33
  76. package/x/swingset/client/proposal_handler.go +2 -17
  77. package/x/swingset/genesis.go +163 -37
  78. package/x/swingset/handler.go +2 -1
  79. package/x/swingset/keeper/extension_snapshotter.go +309 -0
  80. package/x/swingset/keeper/extension_snapshotter_test.go +104 -0
  81. package/x/swingset/keeper/keeper.go +95 -48
  82. package/x/swingset/keeper/keeper_test.go +77 -0
  83. package/x/swingset/keeper/migrations.go +7 -2
  84. package/x/swingset/keeper/msg_server.go +71 -56
  85. package/x/swingset/keeper/proposal.go +15 -9
  86. package/x/swingset/keeper/querier.go +24 -15
  87. package/x/swingset/keeper/swing_store_exports_handler.go +872 -0
  88. package/x/swingset/keeper/swing_store_exports_handler_test.go +247 -0
  89. package/x/swingset/keeper/test_utils.go +16 -0
  90. package/x/swingset/module.go +33 -11
  91. package/x/swingset/proposal_handler.go +5 -4
  92. package/x/swingset/swingset.go +73 -0
  93. package/x/swingset/testing/queue.go +17 -0
  94. package/x/swingset/types/codec.go +2 -2
  95. package/x/swingset/types/default-params.go +23 -17
  96. package/x/swingset/types/expected_keepers.go +14 -2
  97. package/x/swingset/types/genesis.pb.go +361 -18
  98. package/x/swingset/types/msgs.go +87 -26
  99. package/x/swingset/types/msgs.pb.go +16 -16
  100. package/x/swingset/types/params.go +76 -1
  101. package/x/swingset/types/params_test.go +116 -0
  102. package/x/swingset/types/proposal.go +10 -9
  103. package/x/swingset/types/swingset.pb.go +83 -81
  104. package/x/swingset/types/types.go +30 -28
  105. package/x/vbank/genesis.go +0 -2
  106. package/x/vbank/handler.go +2 -1
  107. package/x/vbank/keeper/keeper.go +3 -2
  108. package/x/vbank/keeper/querier.go +9 -4
  109. package/x/vbank/keeper/rewards.go +1 -1
  110. package/x/vbank/module.go +0 -5
  111. package/x/vbank/types/msgs.go +0 -12
  112. package/x/vbank/vbank.go +34 -32
  113. package/x/vbank/vbank_test.go +20 -20
  114. package/x/vibc/alias.go +3 -0
  115. package/x/vibc/handler.go +17 -15
  116. package/x/vibc/keeper/keeper.go +113 -89
  117. package/x/vibc/keeper/triggers.go +101 -0
  118. package/x/vibc/module.go +5 -8
  119. package/x/vibc/types/expected_keepers.go +28 -6
  120. package/x/vibc/types/ibc_module.go +336 -0
  121. package/x/vibc/types/msgs.go +1 -1
  122. package/x/vibc/types/msgs.pb.go +1 -1
  123. package/x/vibc/types/receiver.go +170 -0
  124. package/x/vlocalchain/alias.go +19 -0
  125. package/x/vlocalchain/handler.go +21 -0
  126. package/x/vlocalchain/keeper/keeper.go +279 -0
  127. package/x/vlocalchain/keeper/keeper_test.go +97 -0
  128. package/x/vlocalchain/types/codec.go +34 -0
  129. package/x/vlocalchain/types/key.go +27 -0
  130. package/x/vlocalchain/types/msgs.go +16 -0
  131. package/x/vlocalchain/types/vlocalchain.pb.go +1072 -0
  132. package/x/vlocalchain/vlocalchain.go +114 -0
  133. package/x/vlocalchain/vlocalchain_test.go +434 -0
  134. package/x/vstorage/README.md +138 -0
  135. package/x/vstorage/capdata/capdata.go +298 -0
  136. package/x/vstorage/capdata/capdata_test.go +352 -0
  137. package/x/vstorage/client/cli/query.go +51 -4
  138. package/x/vstorage/genesis.go +0 -3
  139. package/x/vstorage/handler.go +2 -1
  140. package/x/vstorage/keeper/grpc_query.go +220 -0
  141. package/x/vstorage/keeper/keeper.go +75 -57
  142. package/x/vstorage/keeper/keeper_grpc_test.go +300 -0
  143. package/x/vstorage/keeper/keeper_test.go +40 -62
  144. package/x/vstorage/keeper/querier.go +39 -14
  145. package/x/vstorage/keeper/querier_test.go +113 -0
  146. package/x/vstorage/module.go +0 -5
  147. package/x/vstorage/testing/queue.go +27 -0
  148. package/x/vstorage/types/path_keys.go +22 -10
  149. package/x/vstorage/types/path_keys_test.go +84 -18
  150. package/x/vstorage/types/query.pb.go +646 -36
  151. package/x/vstorage/types/query.pb.gw.go +119 -0
  152. package/x/vstorage/types/types.go +0 -66
  153. package/x/vstorage/vstorage.go +33 -35
  154. package/x/vstorage/vstorage_test.go +19 -19
  155. package/x/vtransfer/alias.go +13 -0
  156. package/x/vtransfer/genesis.go +39 -0
  157. package/x/vtransfer/genesis_test.go +12 -0
  158. package/x/vtransfer/handler.go +20 -0
  159. package/x/vtransfer/ibc_middleware.go +186 -0
  160. package/x/vtransfer/ibc_middleware_test.go +448 -0
  161. package/x/vtransfer/keeper/keeper.go +281 -0
  162. package/x/vtransfer/module.go +124 -0
  163. package/x/vtransfer/types/expected_keepers.go +38 -0
  164. package/x/vtransfer/types/genesis.pb.go +327 -0
  165. package/x/vtransfer/types/key.go +9 -0
  166. package/x/vtransfer/types/msgs.go +9 -0
  167. package/app/const.go +0 -6
  168. package/cmd/helper/main.go +0 -21
  169. package/proto/agoric/lien/genesis.proto +0 -25
  170. package/proto/agoric/lien/lien.proto +0 -25
  171. package/x/lien/alias.go +0 -17
  172. package/x/lien/genesis.go +0 -58
  173. package/x/lien/genesis_test.go +0 -101
  174. package/x/lien/keeper/account.go +0 -285
  175. package/x/lien/keeper/keeper.go +0 -254
  176. package/x/lien/keeper/keeper_test.go +0 -623
  177. package/x/lien/lien.go +0 -203
  178. package/x/lien/lien_test.go +0 -529
  179. package/x/lien/module.go +0 -115
  180. package/x/lien/spec/01_concepts.md +0 -146
  181. package/x/lien/spec/02_messages.md +0 -96
  182. package/x/lien/types/accountkeeper.go +0 -81
  183. package/x/lien/types/accountstate.go +0 -27
  184. package/x/lien/types/expected_keepers.go +0 -18
  185. package/x/lien/types/genesis.pb.go +0 -567
  186. package/x/lien/types/key.go +0 -25
  187. package/x/lien/types/lien.pb.go +0 -403
  188. package/x/swingset/keeper/snapshotter.go +0 -491
  189. package/x/swingset/keeper/snapshotter_test.go +0 -185
  190. package/x/swingset/legacy/v32/params.go +0 -37
  191. package/x/swingset/legacy/v32/params_test.go +0 -133
  192. package/x/vibc/ibc.go +0 -442
  193. /package/{src/index.cjs → index.cjs} +0 -0
@@ -4,6 +4,7 @@ import (
4
4
  "github.com/Agoric/agoric-sdk/golang/cosmos/x/vstorage/types"
5
5
  "github.com/cosmos/cosmos-sdk/client"
6
6
  "github.com/cosmos/cosmos-sdk/client/flags"
7
+ "github.com/gogo/protobuf/proto"
7
8
  "github.com/spf13/cobra"
8
9
  )
9
10
 
@@ -18,6 +19,7 @@ func GetQueryCmd(storeKey string) *cobra.Command {
18
19
  swingsetQueryCmd.AddCommand(
19
20
  GetCmdGetData(storeKey),
20
21
  GetCmdGetChildren(storeKey),
22
+ GetCmdGetPath(storeKey),
21
23
  )
22
24
 
23
25
  return swingsetQueryCmd
@@ -26,8 +28,8 @@ func GetQueryCmd(storeKey string) *cobra.Command {
26
28
  // GetCmdGetData queries information about storage
27
29
  func GetCmdGetData(queryRoute string) *cobra.Command {
28
30
  cmd := &cobra.Command{
29
- Use: "data [path]",
30
- Short: "get vstorage data for path",
31
+ Use: "data <path>",
32
+ Short: "get data for vstorage path",
31
33
  Args: cobra.ExactArgs(1),
32
34
  RunE: func(cmd *cobra.Command, args []string) error {
33
35
  clientCtx, err := client.GetClientQueryContext(cmd)
@@ -58,8 +60,12 @@ func GetCmdGetChildren(queryRoute string) *cobra.Command {
58
60
  cmd := &cobra.Command{
59
61
  Use: "children [path]",
60
62
  Aliases: []string{"keys"},
61
- Short: "get vstorage subkey names for path",
62
- Args: cobra.MaximumNArgs(1),
63
+ Short: "get child path segments under vstorage path",
64
+ Long: `get child path segments under vstorage path.
65
+ When absent, path defaults to the empty root path.
66
+ Path segments are dot-separated, so a child "baz" under path "foo.bar" has path
67
+ "foo.bar.baz".`,
68
+ Args: cobra.MaximumNArgs(1),
63
69
  RunE: func(cmd *cobra.Command, args []string) error {
64
70
  clientCtx, err := client.GetClientQueryContext(cmd)
65
71
  if err != nil {
@@ -86,3 +92,44 @@ func GetCmdGetChildren(queryRoute string) *cobra.Command {
86
92
  flags.AddQueryFlagsToCmd(cmd)
87
93
  return cmd
88
94
  }
95
+
96
+ // GetCmdGetPath queries vstorage data or children, depending on the path
97
+ func GetCmdGetPath(queryRoute string) *cobra.Command {
98
+ cmd := &cobra.Command{
99
+ Use: "path <path>",
100
+ Short: "get vstorage data, or children if path ends with '.'",
101
+ Args: cobra.ExactArgs(1),
102
+ RunE: func(cmd *cobra.Command, args []string) error {
103
+ clientCtx, err := client.GetClientQueryContext(cmd)
104
+ if err != nil {
105
+ return err
106
+ }
107
+ queryClient := types.NewQueryClient(clientCtx)
108
+
109
+ path := args[0]
110
+
111
+ var res proto.Message
112
+
113
+ // if path ends with '.' then remove it and query children
114
+ if path[len(path)-1] == '.' {
115
+ path = path[:len(path)-1]
116
+ res, err = queryClient.Children(cmd.Context(), &types.QueryChildrenRequest{
117
+ Path: path,
118
+ })
119
+ } else {
120
+ res, err = queryClient.Data(cmd.Context(), &types.QueryDataRequest{
121
+ Path: path,
122
+ })
123
+ }
124
+
125
+ if err != nil {
126
+ return err
127
+ }
128
+
129
+ return clientCtx.PrintProto(res)
130
+ },
131
+ }
132
+
133
+ flags.AddQueryFlagsToCmd(cmd)
134
+ return cmd
135
+ }
@@ -22,9 +22,6 @@ func ValidateGenesis(data *types.GenesisState) error {
22
22
  if err := types.ValidatePath(entry.Path); err != nil {
23
23
  return fmt.Errorf("genesis vstorage.data entry %q has invalid path format: %s", entry.Path, err)
24
24
  }
25
- if entry.Value == "" {
26
- return fmt.Errorf("genesis vstorage.data entry %q has no data", entry.Path)
27
- }
28
25
  }
29
26
  return nil
30
27
  }
@@ -3,6 +3,7 @@ package vstorage
3
3
  import (
4
4
  "fmt"
5
5
 
6
+ sdkioerrors "cosmossdk.io/errors"
6
7
  sdk "github.com/cosmos/cosmos-sdk/types"
7
8
  sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
8
9
  )
@@ -11,6 +12,6 @@ import (
11
12
  func NewHandler(k Keeper) sdk.Handler {
12
13
  return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {
13
14
  errMsg := fmt.Sprintf("Unrecognized vstorage Msg type: %T", msg)
14
- return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg)
15
+ return nil, sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg)
15
16
  }
16
17
  }
@@ -2,10 +2,14 @@ package keeper
2
2
 
3
3
  import (
4
4
  "context"
5
+ "encoding/json"
6
+ "fmt"
7
+ "strings"
5
8
 
6
9
  "google.golang.org/grpc/codes"
7
10
  "google.golang.org/grpc/status"
8
11
 
12
+ "github.com/Agoric/agoric-sdk/golang/cosmos/x/vstorage/capdata"
9
13
  "github.com/Agoric/agoric-sdk/golang/cosmos/x/vstorage/types"
10
14
  sdk "github.com/cosmos/cosmos-sdk/types"
11
15
  )
@@ -17,6 +21,11 @@ type Querier struct {
17
21
 
18
22
  var _ types.QueryServer = Querier{}
19
23
 
24
+ // ===================================================================
25
+ // /agoric.vstorage.Query/Data
26
+ // ===================================================================
27
+
28
+ // /agoric.vstorage.Query/Data returns data for a specified path.
20
29
  func (k Querier) Data(c context.Context, req *types.QueryDataRequest) (*types.QueryDataResponse, error) {
21
30
  if req == nil {
22
31
  return nil, status.Error(codes.InvalidArgument, "empty request")
@@ -30,6 +39,217 @@ func (k Querier) Data(c context.Context, req *types.QueryDataRequest) (*types.Qu
30
39
  }, nil
31
40
  }
32
41
 
42
+ // ===================================================================
43
+ // /agoric.vstorage.Query/CapData
44
+ // ===================================================================
45
+
46
+ const (
47
+ // Media types.
48
+ JSONLines = "JSON Lines"
49
+
50
+ // CapData transformation formats.
51
+ FormatCapDataFlat = "flat"
52
+
53
+ // CapData remotable value formats.
54
+ FormatRemotableAsObject = "object"
55
+ FormatRemotableAsString = "string"
56
+ )
57
+
58
+ var capDataResponseMediaTypes = map[string]string{
59
+ JSONLines: JSONLines,
60
+ // Default to JSON Lines.
61
+ "": JSONLines,
62
+ }
63
+ var capDataTransformationFormats = map[string]string{
64
+ FormatCapDataFlat: FormatCapDataFlat,
65
+ // Default to no transformation.
66
+ "": "",
67
+ }
68
+ var capDataRemotableValueFormats = map[string]string{
69
+ FormatRemotableAsObject: FormatRemotableAsObject,
70
+ FormatRemotableAsString: FormatRemotableAsString,
71
+ // No default because both formats are lossy.
72
+ }
73
+
74
+ // flatten converts data into a flat structure in which each deep leaf entry is replaced with
75
+ // a top-level entry having the same value but a key generated by joining the keys on its path
76
+ // with separating dashes.
77
+ // For example,
78
+ // ```
79
+ // { "contacts": [
80
+ //
81
+ // { "name": "Alice", "email": "a@example.com" },
82
+ // { "name": "Bob", "email": "b@example.com" }
83
+ //
84
+ // ] }
85
+ // ```
86
+ // becomes
87
+ // ```
88
+ //
89
+ // {
90
+ // "contacts-0-name": "Alice",
91
+ // "contacts-0-email": "a@example.com",
92
+ // "contacts-1-name": "Bob",
93
+ // "contacts-1-email": "b@example.com"
94
+ // }
95
+ //
96
+ // ```
97
+ func flatten(input interface{}, output map[string]interface{}, key string, top bool) error {
98
+ // Act on the raw representation of a Remotable.
99
+ if remotable, ok := input.(*capdata.CapdataRemotable); ok {
100
+ var replacement interface{}
101
+ repr, err := capdata.JsonMarshal(remotable)
102
+ if err == nil {
103
+ err = json.Unmarshal(repr, &replacement)
104
+ }
105
+ if err != nil {
106
+ return err
107
+ }
108
+ input = replacement
109
+ }
110
+
111
+ childKeyPrefix := key
112
+ if !top {
113
+ childKeyPrefix = childKeyPrefix + "-"
114
+ }
115
+ if arr, ok := input.([]interface{}); ok {
116
+ for i, v := range arr {
117
+ if err := flatten(v, output, childKeyPrefix+fmt.Sprintf("%d", i), false); err != nil {
118
+ return err
119
+ }
120
+ }
121
+ } else if obj, ok := input.(map[string]interface{}); ok {
122
+ for k, v := range obj {
123
+ if err := flatten(v, output, childKeyPrefix+k, false); err != nil {
124
+ return err
125
+ }
126
+ }
127
+ } else {
128
+ if _, has := output[key]; has {
129
+ return fmt.Errorf("key conflict: %q", key)
130
+ }
131
+ output[key] = input
132
+ }
133
+ return nil
134
+ }
135
+
136
+ // capdataBigintToDigits represents a bigint as a string consisting of
137
+ // an optional "-" followed by a sequence of digits with no extraneous zeroes
138
+ // (e.g., "0" or "-40").
139
+ func capdataBigintToDigits(bigint *capdata.CapdataBigint) interface{} {
140
+ return bigint.Normalized
141
+ }
142
+
143
+ // capdataRemotableToString represents a Remotable as a bracketed string
144
+ // containing its alleged name and id from `slots`
145
+ // (e.g., "[Alleged: IST brand <board007>]").
146
+ func capdataRemotableToString(r *capdata.CapdataRemotable) interface{} {
147
+ iface := "Remotable"
148
+ if r.Iface != nil || *r.Iface != "" {
149
+ iface = *r.Iface
150
+ }
151
+ return fmt.Sprintf("[%s <%s>]", iface, r.Id)
152
+ }
153
+
154
+ // capdataRemotableToObject represents a Remotable as an object containing
155
+ // its id from `slots` and its alleged name minus any "Alleged:" prefix
156
+ // (e.g., `{ "id": "board007", "allegedName": "IST brand" }`).
157
+ func capdataRemotableToObject(r *capdata.CapdataRemotable) interface{} {
158
+ iface := "Remotable"
159
+ if r.Iface != nil || *r.Iface != "" {
160
+ iface = *r.Iface
161
+ iface, _ = strings.CutPrefix(iface, "Alleged: ")
162
+ }
163
+ return map[string]interface{}{"id": r.Id, "allegedName": iface}
164
+ }
165
+
166
+ // /agoric.vstorage.Query/CapData returns data for a specified path,
167
+ // interpreted as CapData in a StreamCell (auto-promoting isolated CapData
168
+ // into a single-item StreamCell) and transformed as specified.
169
+ func (k Querier) CapData(c context.Context, req *types.QueryCapDataRequest) (*types.QueryCapDataResponse, error) {
170
+ if req == nil {
171
+ return nil, status.Error(codes.InvalidArgument, "empty request")
172
+ }
173
+ ctx := sdk.UnwrapSDKContext(c)
174
+
175
+ valueTransformations := capdata.CapdataValueTransformations{
176
+ Bigint: capdataBigintToDigits,
177
+ }
178
+
179
+ // A response Value is "<prefix><separator-joined items><suffix>".
180
+ prefix, separator, suffix := "", "\n", ""
181
+
182
+ // Read options.
183
+ mediaType, ok := capDataResponseMediaTypes[req.MediaType]
184
+ if !ok {
185
+ return nil, status.Error(codes.InvalidArgument, "invalid media_type")
186
+ }
187
+ transformation, ok := capDataTransformationFormats[req.ItemFormat]
188
+ if !ok {
189
+ return nil, status.Error(codes.InvalidArgument, "invalid item_format")
190
+ }
191
+ switch remotableFormat, ok := capDataRemotableValueFormats[req.RemotableValueFormat]; {
192
+ case !ok:
193
+ return nil, status.Error(codes.InvalidArgument, "invalid remotable_value_format")
194
+ case remotableFormat == FormatRemotableAsObject:
195
+ valueTransformations.Remotable = capdataRemotableToObject
196
+ case remotableFormat == FormatRemotableAsString:
197
+ valueTransformations.Remotable = capdataRemotableToString
198
+ }
199
+
200
+ // Read data, auto-upgrading a standalone value to a single-value StreamCell.
201
+ entry := k.GetEntry(ctx, req.Path)
202
+ if !entry.HasValue() {
203
+ return nil, status.Error(codes.FailedPrecondition, "no data")
204
+ }
205
+ value := entry.StringValue()
206
+ var cell StreamCell
207
+ _ = json.Unmarshal([]byte(value), &cell)
208
+ if cell.BlockHeight == "" {
209
+ cell = StreamCell{Values: []string{value}}
210
+ }
211
+
212
+ // Format each StreamCell value.
213
+ responseItems := make([]string, len(cell.Values))
214
+ for i, capDataJson := range cell.Values {
215
+ item, err := capdata.DecodeSerializedCapdata(capDataJson, valueTransformations)
216
+ if err != nil {
217
+ return nil, status.Error(codes.FailedPrecondition, err.Error())
218
+ }
219
+ if transformation == FormatCapDataFlat {
220
+ flattened := map[string]interface{}{}
221
+ if err := flatten(item, flattened, "", true); err != nil {
222
+ return nil, status.Error(codes.Internal, err.Error())
223
+ }
224
+ // Replace the item, unless it was a scalar that "flattened" to `{ "": ... }`.
225
+ if _, singleton := flattened[""]; !singleton {
226
+ item = flattened
227
+ }
228
+ }
229
+ switch mediaType {
230
+ case JSONLines:
231
+ jsonText, err := capdata.JsonMarshal(item)
232
+ if err != nil {
233
+ return nil, status.Error(codes.Internal, err.Error())
234
+ }
235
+ responseItems[i] = string(jsonText)
236
+ }
237
+ }
238
+
239
+ return &types.QueryCapDataResponse{
240
+ BlockHeight: cell.BlockHeight,
241
+ Value: prefix + strings.Join(responseItems, separator) + suffix,
242
+ }, nil
243
+ }
244
+
245
+ // ===================================================================
246
+ // /agoric.vstorage.Query/Children
247
+ // ===================================================================
248
+
249
+ // /agoric.vstorage.Query/Children returns the list of path segments
250
+ // that exist immediately underneath a specified path, including
251
+ // those corresponding with "empty non-terminals" having children
252
+ // but no data of their own.
33
253
  func (k Querier) Children(c context.Context, req *types.QueryChildrenRequest) (*types.QueryChildrenResponse, error) {
34
254
  if req == nil {
35
255
  return nil, status.Error(codes.InvalidArgument, "empty request")
@@ -10,6 +10,8 @@ import (
10
10
  "strconv"
11
11
  "strings"
12
12
 
13
+ sdkmath "cosmossdk.io/math"
14
+ storetypes "github.com/cosmos/cosmos-sdk/store/types"
13
15
  sdk "github.com/cosmos/cosmos-sdk/types"
14
16
  db "github.com/tendermint/tm-db"
15
17
 
@@ -20,8 +22,8 @@ import (
20
22
  // StreamCell is an envelope representing a sequence of values written at a path in a single block.
21
23
  // It is persisted to storage as a { "blockHeight": "<digits>", "values": ["...", ...] } JSON text
22
24
  // that off-chain consumers rely upon.
23
- // Many of those consumers *also* rely upon the strings of "values" being valid JSON text
24
- // (cf. scripts/get-flattened-publication.sh), but we do not enforce that in this package.
25
+ // Many of those consumers *also* rely upon the strings of "values" being valid JSON text,
26
+ // but we do not enforce that in this package.
25
27
  type StreamCell struct {
26
28
  BlockHeight string `json:"blockHeight"`
27
29
  Values []string `json:"values"`
@@ -35,7 +37,7 @@ type ProposedChange struct {
35
37
  }
36
38
 
37
39
  type ChangeManager interface {
38
- Track(ctx sdk.Context, k Keeper, entry types.StorageEntry, isLegacy bool)
40
+ Track(ctx sdk.Context, k Keeper, entry agoric.KVEntry, isLegacy bool)
39
41
  EmitEvents(ctx sdk.Context, k Keeper)
40
42
  Rollback(ctx sdk.Context)
41
43
  }
@@ -50,23 +52,15 @@ var _ ChangeManager = (*BatchingChangeManager)(nil)
50
52
  // 2 ** 256 - 1
51
53
  var MaxSDKInt = sdk.NewIntFromBigInt(new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)))
52
54
 
53
- // TODO: Use bytes.CutPrefix once we can rely upon go >= 1.20.
54
- func cutPrefix(s, prefix []byte) (after []byte, found bool) {
55
- if !bytes.HasPrefix(s, prefix) {
56
- return s, false
57
- }
58
- return s[len(prefix):], true
59
- }
60
-
61
55
  // Keeper maintains the link to data storage and exposes getter/setter methods
62
56
  // for the various parts of the state machine
63
57
  type Keeper struct {
64
58
  changeManager ChangeManager
65
- storeKey sdk.StoreKey
59
+ storeKey storetypes.StoreKey
66
60
  }
67
61
 
68
- func (bcm *BatchingChangeManager) Track(ctx sdk.Context, k Keeper, entry types.StorageEntry, isLegacy bool) {
69
- path := entry.Path()
62
+ func (bcm *BatchingChangeManager) Track(ctx sdk.Context, k Keeper, entry agoric.KVEntry, isLegacy bool) {
63
+ path := entry.Key()
70
64
  // TODO: differentiate between deletion and setting empty string?
71
65
  // Using empty string for deletion for backwards compatibility
72
66
  value := entry.StringValue()
@@ -116,7 +110,7 @@ func NewBatchingChangeManager() *BatchingChangeManager {
116
110
  return &bcm
117
111
  }
118
112
 
119
- func NewKeeper(storeKey sdk.StoreKey) Keeper {
113
+ func NewKeeper(storeKey storetypes.StoreKey) Keeper {
120
114
  return Keeper{
121
115
  storeKey: storeKey,
122
116
  changeManager: NewBatchingChangeManager(),
@@ -162,7 +156,7 @@ func (k Keeper) ExportStorageFromPrefix(ctx sdk.Context, pathPrefix string) []*t
162
156
  if !strings.HasPrefix(path, pathPrefix) {
163
157
  continue
164
158
  }
165
- value, hasPrefix := cutPrefix(rawValue, types.EncodedDataPrefix)
159
+ value, hasPrefix := bytes.CutPrefix(rawValue, types.EncodedDataPrefix)
166
160
  if !hasPrefix {
167
161
  panic(fmt.Errorf("value at path %q starts with unexpected prefix", path))
168
162
  }
@@ -177,32 +171,56 @@ func (k Keeper) ImportStorage(ctx sdk.Context, entries []*types.DataEntry) {
177
171
  for _, entry := range entries {
178
172
  // This set does the bookkeeping for us in case the entries aren't a
179
173
  // complete tree.
180
- k.SetStorage(ctx, types.NewStorageEntry(entry.Path, entry.Value))
174
+ k.SetStorage(ctx, agoric.NewKVEntry(entry.Path, entry.Value))
175
+ }
176
+ }
177
+
178
+ func getEncodedKeysWithPrefixFromIterator(iterator sdk.Iterator, prefix string) [][]byte {
179
+ keys := make([][]byte, 0)
180
+ defer iterator.Close()
181
+ for ; iterator.Valid(); iterator.Next() {
182
+ key := iterator.Key()
183
+ path := types.EncodedKeyToPath(key)
184
+ if strings.HasPrefix(path, prefix) {
185
+ keys = append(keys, key)
186
+ }
181
187
  }
188
+ return keys
182
189
  }
183
190
 
184
- func (k Keeper) MigrateNoDataPlaceholders(ctx sdk.Context) {
191
+ // RemoveEntriesWithPrefix removes all storage entries starting with the
192
+ // supplied pathPrefix, which may not be empty.
193
+ // It has the same effect as listing children of the prefix and removing each
194
+ // descendant recursively.
195
+ func (k Keeper) RemoveEntriesWithPrefix(ctx sdk.Context, pathPrefix string) {
185
196
  store := ctx.KVStore(k.storeKey)
186
197
 
198
+ if len(pathPrefix) == 0 {
199
+ panic("cannot remove all content")
200
+ }
201
+ if err := types.ValidatePath(pathPrefix); err != nil {
202
+ panic(err)
203
+ }
204
+ descendantPrefix := pathPrefix + types.PathSeparator
205
+
206
+ // since vstorage encodes keys with a prefix indicating the number of path
207
+ // elements, we cannot use a simple prefix iterator.
208
+ // Instead we iterate over the whole vstorage content and check
209
+ // whether each entry matches the descendantPrefix. This choice assumes most
210
+ // entries will be deleted. An alternative implementation would be to
211
+ // recursively list all children under the descendantPrefix, and delete them.
212
+
187
213
  iterator := sdk.KVStorePrefixIterator(store, nil)
188
214
 
189
- // Copy empty keys first since cosmos stores do not support writing keys
190
- // while an iterator is open over the domain
191
- emptyKeys := [][]byte{}
192
- for ; iterator.Valid(); iterator.Next() {
193
- rawValue := iterator.Value()
194
- if bytes.Equal(rawValue, types.EncodedDataPrefix) {
195
- key := iterator.Key()
196
- clonedKey := make([]byte, len(key))
197
- copy(clonedKey, key)
198
- emptyKeys = append(emptyKeys, clonedKey)
199
- }
200
- }
201
- iterator.Close()
215
+ keys := getEncodedKeysWithPrefixFromIterator(iterator, descendantPrefix)
202
216
 
203
- for _, key := range emptyKeys {
204
- store.Set(key, types.EncodedNoDataValue)
217
+ for _, key := range keys {
218
+ store.Delete(key)
205
219
  }
220
+
221
+ // Update the prefix entry itself with SetStorage, which will effectively
222
+ // delete it and all necessary ancestors.
223
+ k.SetStorage(ctx, agoric.NewKVEntryWithNoValue(pathPrefix))
206
224
  }
207
225
 
208
226
  func (k Keeper) EmitChange(ctx sdk.Context, change *ProposedChange) {
@@ -229,22 +247,22 @@ func (k Keeper) EmitChange(ctx sdk.Context, change *ProposedChange) {
229
247
  }
230
248
 
231
249
  // GetEntry gets generic storage. The default value is an empty string.
232
- func (k Keeper) GetEntry(ctx sdk.Context, path string) types.StorageEntry {
250
+ func (k Keeper) GetEntry(ctx sdk.Context, path string) agoric.KVEntry {
233
251
  //fmt.Printf("GetEntry(%s)\n", path);
234
252
  store := ctx.KVStore(k.storeKey)
235
253
  encodedKey := types.PathToEncodedKey(path)
236
254
  rawValue := store.Get(encodedKey)
237
255
  if len(rawValue) == 0 {
238
- return types.NewStorageEntryWithNoData(path)
256
+ return agoric.NewKVEntryWithNoValue(path)
239
257
  }
240
258
  if bytes.Equal(rawValue, types.EncodedNoDataValue) {
241
- return types.NewStorageEntryWithNoData(path)
259
+ return agoric.NewKVEntryWithNoValue(path)
242
260
  }
243
- value, hasPrefix := cutPrefix(rawValue, types.EncodedDataPrefix)
261
+ value, hasPrefix := bytes.CutPrefix(rawValue, types.EncodedDataPrefix)
244
262
  if !hasPrefix {
245
263
  panic(fmt.Errorf("value at path %q starts with unexpected prefix", path))
246
264
  }
247
- return types.NewStorageEntry(path, string(value))
265
+ return agoric.NewKVEntry(path, string(value))
248
266
  }
249
267
 
250
268
  func (k Keeper) getKeyIterator(ctx sdk.Context, path string) db.Iterator {
@@ -273,7 +291,7 @@ func (k Keeper) GetChildren(ctx sdk.Context, path string) *types.Children {
273
291
  // (just an empty string) and exist only to provide linkage to subnodes with
274
292
  // data.
275
293
  func (k Keeper) HasStorage(ctx sdk.Context, path string) bool {
276
- return k.GetEntry(ctx, path).HasData()
294
+ return k.GetEntry(ctx, path).HasValue()
277
295
  }
278
296
 
279
297
  // HasEntry tells if a given path has either subnodes or data.
@@ -302,12 +320,12 @@ func (k Keeper) FlushChangeEvents(ctx sdk.Context) {
302
320
  k.changeManager.Rollback(ctx)
303
321
  }
304
322
 
305
- func (k Keeper) SetStorageAndNotify(ctx sdk.Context, entry types.StorageEntry) {
323
+ func (k Keeper) SetStorageAndNotify(ctx sdk.Context, entry agoric.KVEntry) {
306
324
  k.changeManager.Track(ctx, k, entry, false)
307
325
  k.SetStorage(ctx, entry)
308
326
  }
309
327
 
310
- func (k Keeper) LegacySetStorageAndNotify(ctx sdk.Context, entry types.StorageEntry) {
328
+ func (k Keeper) LegacySetStorageAndNotify(ctx sdk.Context, entry agoric.KVEntry) {
311
329
  k.changeManager.Track(ctx, k, entry, true)
312
330
  k.SetStorage(ctx, entry)
313
331
  }
@@ -332,7 +350,7 @@ func (k Keeper) AppendStorageValueAndNotify(ctx sdk.Context, path, value string)
332
350
  if err != nil {
333
351
  return err
334
352
  }
335
- k.SetStorageAndNotify(ctx, types.NewStorageEntry(path, string(bz)))
353
+ k.SetStorageAndNotify(ctx, agoric.NewKVEntry(path, string(bz)))
336
354
  return nil
337
355
  }
338
356
 
@@ -344,12 +362,12 @@ func componentsToPath(components []string) string {
344
362
  //
345
363
  // Maintains the invariant: path entries exist if and only if self or some
346
364
  // descendant has non-empty storage
347
- func (k Keeper) SetStorage(ctx sdk.Context, entry types.StorageEntry) {
365
+ func (k Keeper) SetStorage(ctx sdk.Context, entry agoric.KVEntry) {
348
366
  store := ctx.KVStore(k.storeKey)
349
- path := entry.Path()
367
+ path := entry.Key()
350
368
  encodedKey := types.PathToEncodedKey(path)
351
369
 
352
- if !entry.HasData() {
370
+ if !entry.HasValue() {
353
371
  if !k.HasChildren(ctx, path) {
354
372
  // We have no children, can delete.
355
373
  store.Delete(encodedKey)
@@ -364,7 +382,7 @@ func (k Keeper) SetStorage(ctx sdk.Context, entry types.StorageEntry) {
364
382
 
365
383
  // Update our other parent children.
366
384
  pathComponents := strings.Split(path, types.PathSeparator)
367
- if !entry.HasData() {
385
+ if !entry.HasValue() {
368
386
  // delete placeholder ancestors if they're no longer needed
369
387
  for i := len(pathComponents) - 1; i >= 0; i-- {
370
388
  ancestor := componentsToPath(pathComponents[0:i])
@@ -403,9 +421,9 @@ func (k Keeper) GetNoDataValue() []byte {
403
421
  return types.EncodedNoDataValue
404
422
  }
405
423
 
406
- func (k Keeper) getIntValue(ctx sdk.Context, path string) (sdk.Int, error) {
424
+ func (k Keeper) GetIntValue(ctx sdk.Context, path string) (sdkmath.Int, error) {
407
425
  indexEntry := k.GetEntry(ctx, path)
408
- if !indexEntry.HasData() {
426
+ if !indexEntry.HasValue() {
409
427
  return sdk.NewInt(0), nil
410
428
  }
411
429
 
@@ -416,14 +434,14 @@ func (k Keeper) getIntValue(ctx sdk.Context, path string) (sdk.Int, error) {
416
434
  return index, nil
417
435
  }
418
436
 
419
- func (k Keeper) GetQueueLength(ctx sdk.Context, queuePath string) (sdk.Int, error) {
420
- head, err := k.getIntValue(ctx, queuePath+".head")
437
+ func (k Keeper) GetQueueLength(ctx sdk.Context, queuePath string) (sdkmath.Int, error) {
438
+ head, err := k.GetIntValue(ctx, queuePath+".head")
421
439
  if err != nil {
422
- return sdk.NewInt(0), err
440
+ return sdkmath.NewInt(0), err
423
441
  }
424
- tail, err := k.getIntValue(ctx, queuePath+".tail")
442
+ tail, err := k.GetIntValue(ctx, queuePath+".tail")
425
443
  if err != nil {
426
- return sdk.NewInt(0), err
444
+ return sdkmath.NewInt(0), err
427
445
  }
428
446
  // The tail index is exclusive
429
447
  return tail.Sub(head), nil
@@ -432,22 +450,22 @@ func (k Keeper) GetQueueLength(ctx sdk.Context, queuePath string) (sdk.Int, erro
432
450
  func (k Keeper) PushQueueItem(ctx sdk.Context, queuePath string, value string) error {
433
451
  // Get the current queue tail, defaulting to zero if its vstorage doesn't exist.
434
452
  // The `tail` is the value of the next index to be inserted
435
- tail, err := k.getIntValue(ctx, queuePath+".tail")
453
+ tail, err := k.GetIntValue(ctx, queuePath+".tail")
436
454
  if err != nil {
437
455
  return err
438
456
  }
439
457
 
440
- if tail.Equal(MaxSDKInt) {
458
+ if tail.GTE(MaxSDKInt) {
441
459
  return errors.New(queuePath + " overflow")
442
460
  }
443
461
  nextTail := tail.Add(sdk.NewInt(1))
444
462
 
445
463
  // Set the vstorage corresponding to the queue entry for the current tail.
446
464
  path := queuePath + "." + tail.String()
447
- k.SetStorage(ctx, types.NewStorageEntry(path, value))
465
+ k.SetStorage(ctx, agoric.NewKVEntry(path, value))
448
466
 
449
467
  // Update the tail to point to the next available entry.
450
468
  path = queuePath + ".tail"
451
- k.SetStorage(ctx, types.NewStorageEntry(path, nextTail.String()))
469
+ k.SetStorage(ctx, agoric.NewKVEntry(path, nextTail.String()))
452
470
  return nil
453
471
  }