/
keeper.go
358 lines (282 loc) · 11.7 KB
/
keeper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package keeper
import (
"bytes"
"encoding/hex"
"fmt"
ctypes "github.com/commercionetwork/commercionetwork/x/common/types"
"github.com/commercionetwork/commercionetwork/x/id/internal/types"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/supply"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/crypto/secp256k1"
)
type Keeper struct {
storeKey sdk.StoreKey
cdc *codec.Codec
accKeeper auth.AccountKeeper
supplyKeeper supply.Keeper
}
// NewKeeper creates new instances of the CommercioID Keeper
func NewKeeper(cdc *codec.Codec, storeKey sdk.StoreKey, accKeeper auth.AccountKeeper, supplyKeeper supply.Keeper) Keeper {
// ensure commerciomint module account is set
if addr := supplyKeeper.GetModuleAddress(types.ModuleName); addr == nil {
panic(fmt.Sprintf("%s module account has not been set", types.ModuleName))
}
return Keeper{
storeKey: storeKey,
cdc: cdc,
accKeeper: accKeeper,
supplyKeeper: supplyKeeper,
}
}
// ------------------
// --- Identities
// ------------------
// SaveDidDocument saves the given didDocumentUri associating it with the given owner, replacing any existent one.
func (k Keeper) SaveDidDocument(ctx sdk.Context, document types.DidDocument) sdk.Error {
owner := document.ID
// Get the account and its public key
account := k.accKeeper.GetAccount(ctx, owner)
if account == nil {
return sdk.ErrUnknownRequest(fmt.Sprintf("Could not find account %s", owner.String()))
}
accountPubKey := account.GetPubKey()
// --------------------------------------------
// --- Check the authentication key validity
// --------------------------------------------
// Get the authentication key
authKey, found := document.PubKeys.FindByID(document.Authentication[0])
if !found {
return sdk.ErrUnknownRequest("Authentication key not found inside publicKey array")
}
// Get the authentication key bytes
authKeyBytes, err := hex.DecodeString(authKey.PublicKeyHex)
if err != nil {
return sdk.ErrUnknownRequest("Invalid authentication key hex value")
}
// TODO: The following code should be tested
var key []byte
if ed25519key, isEd25519 := accountPubKey.(ed25519.PubKeyEd25519); isEd25519 {
// Check the auth key type coherence with its value
if authKey.Type != types.KeyTypeEd25519 {
msg := fmt.Sprintf("Invalid authentication key value, must be of type %s", types.KeyTypeEd25519)
return sdk.ErrUnknownRequest(msg)
}
key = ed25519key[:]
}
if secp256k1key, isSecp256k1 := accountPubKey.(secp256k1.PubKeySecp256k1); isSecp256k1 {
// Check the auth key type coherence with its value
if authKey.Type != types.KeyTypeSecp256k1 {
msg := fmt.Sprintf("Invalid authentication key value, must be of type %s", types.KeyTypeSecp256k1)
return sdk.ErrUnknownRequest(msg)
}
key = secp256k1key[:]
}
// Check that the authentication key bytes are the same of the key associated with the account
if !bytes.Equal(authKeyBytes, key) {
msg := fmt.Sprintf(
"Authentication key is not the one associated with the account. Expected %s but got %s",
hex.EncodeToString(key),
hex.EncodeToString(authKeyBytes),
)
return sdk.ErrUnknownRequest(msg)
}
// TODO: Check that the proof signatureValue is the valid signature of the entire Did Document made with the user private key
// ------------------------------
// --- Store the Did Document
// ------------------------------
// Set the Did Document into the store
identitiesStore := ctx.KVStore(k.storeKey)
identitiesStore.Set(getIdentityStoreKey(owner), k.cdc.MustMarshalBinaryBare(document))
return nil
}
// GetIdentity returns the Did Document reference associated to a given Did.
// If the given Did has no Did Document reference associated, returns nil.
func (k Keeper) GetDidDocumentByOwner(ctx sdk.Context, owner sdk.AccAddress) (types.DidDocument, error) {
store := ctx.KVStore(k.storeKey)
identityKey := getIdentityStoreKey(owner)
if !store.Has(identityKey) {
return types.DidDocument{}, fmt.Errorf("did document with owner %s not found", owner.String())
}
var didDocument types.DidDocument
k.cdc.MustUnmarshalBinaryBare(store.Get(identityKey), &didDocument)
return didDocument, nil
}
// -------------------------
// --- Genesis utils
// -------------------------
// GetDidDocuments returns the list of all identities for the given context
func (k Keeper) GetDidDocuments(ctx sdk.Context) ([]types.DidDocument, error) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte(types.IdentitiesStorePrefix))
var didDocuments []types.DidDocument
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var didDocument types.DidDocument
k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &didDocument)
didDocuments = append(didDocuments, didDocument)
}
return didDocuments, nil
}
// ----------------------------
// --- Did deposit requests
// ----------------------------
// StorePowerUpRequest allows to save the given request. Returns an error if a request with
// the same proof already exists
func (k Keeper) StoreDidDepositRequest(ctx sdk.Context, request types.DidDepositRequest) sdk.Error {
store := ctx.KVStore(k.storeKey)
requestKey := getDepositRequestStoreKey(request.Proof)
if store.Has(requestKey) {
return sdk.ErrUnknownRequest("Did deposit request with the same proof already exists")
}
store.Set(requestKey, k.cdc.MustMarshalBinaryBare(&request))
return nil
}
// GetDidDepositRequestByProof returns the request having the same proof.
func (k Keeper) GetDidDepositRequestByProof(ctx sdk.Context, proof string) (types.DidDepositRequest, error) {
store := ctx.KVStore(k.storeKey)
requestKey := getDepositRequestStoreKey(proof)
if !store.Has(requestKey) {
return types.DidDepositRequest{}, fmt.Errorf("deposit request with proof %s not found", proof)
}
request := types.DidDepositRequest{}
k.cdc.MustUnmarshalBinaryBare(store.Get(requestKey), &request)
return request, nil
}
// ChangePowerUpRequestStatus changes the status of the request having the same proof, or returns an error
// if no request with the given proof could be found
func (k Keeper) ChangeDepositRequestStatus(ctx sdk.Context, proof string, status types.RequestStatus) sdk.Error {
store := ctx.KVStore(k.storeKey)
request, err := k.GetDidDepositRequestByProof(ctx, proof)
if err != nil {
return sdk.ErrUnknownRequest(err.Error())
}
// Update and store the request
request.Status = &status
store.Set(getDepositRequestStoreKey(request.Proof), k.cdc.MustMarshalBinaryBare(request))
return nil
}
// GetDepositRequests returns the list of the deposit requests existing inside the given context
func (k Keeper) GetDepositRequests(ctx sdk.Context) (requests []types.DidDepositRequest) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte(types.DidDepositRequestStorePrefix))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var request types.DidDepositRequest
k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &request)
requests = append(requests, request)
}
return requests
}
// ----------------------------
// --- Did power up requests
// ----------------------------
// StorePowerUpRequest allows to save the given request. Returns an error if a request with
// the same proof already exists
func (k Keeper) StorePowerUpRequest(ctx sdk.Context, request types.DidPowerUpRequest) sdk.Error {
store := ctx.KVStore(k.storeKey)
requestStoreKey := getDidPowerUpRequestStoreKey(request.Proof)
if store.Has(requestStoreKey) {
return sdk.ErrUnknownRequest("PowerUp request with the same proof already exists")
}
store.Set(requestStoreKey, k.cdc.MustMarshalBinaryBare(&request))
return nil
}
// GetDidDepositRequestByProof returns the request having the same proof.
func (k Keeper) GetPowerUpRequestByProof(ctx sdk.Context, proof string) (types.DidPowerUpRequest, error) {
store := ctx.KVStore(k.storeKey)
requestStoreKey := getDidPowerUpRequestStoreKey(proof)
if !store.Has(requestStoreKey) {
return types.DidPowerUpRequest{}, fmt.Errorf("power-up request with proof %s not found", proof)
}
request := types.DidPowerUpRequest{}
k.cdc.MustUnmarshalBinaryBare(store.Get(requestStoreKey), &request)
return request, nil
}
// ChangePowerUpRequestStatus changes the status of the request having the same proof, or returns an error
// if no request with the given proof could be found
func (k Keeper) ChangePowerUpRequestStatus(ctx sdk.Context, proof string, status types.RequestStatus) sdk.Error {
store := ctx.KVStore(k.storeKey)
request, err := k.GetPowerUpRequestByProof(ctx, proof)
if err != nil {
return sdk.ErrUnknownRequest(err.Error())
}
// Update and store the request
request.Status = &status
store.Set(getDidPowerUpRequestStoreKey(proof), k.cdc.MustMarshalBinaryBare(&request))
return nil
}
// GetPowerUpRequests returns the list the requests saved inside the given context
func (k Keeper) GetPowerUpRequests(ctx sdk.Context) (requests []types.DidPowerUpRequest) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte(types.DidPowerUpRequestStorePrefix))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var request types.DidPowerUpRequest
k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &request)
requests = append(requests, request)
}
return requests
}
// ------------------------
// --- Deposits handling
// ------------------------
func (k Keeper) SetPowerUpRequestHandled(ctx sdk.Context, activationReference string) error {
store := ctx.KVStore(k.storeKey)
if store.Has(getHandledPowerUpRequestsReferenceStoreKey(activationReference)) {
return fmt.Errorf("reference %s already marked as handled", activationReference)
}
k.SetHandledPowerUpRequestsReference(ctx, activationReference)
return nil
}
func (k Keeper) GetHandledPowerUpRequestsReferences(ctx sdk.Context) ctypes.Strings {
hi := k.HandledPowerUpRequestsIterator(ctx)
defer hi.Close()
data := ctypes.Strings{}
for ; hi.Valid(); hi.Next() {
data = append(data, string(hi.Value()))
}
return data
}
func (k Keeper) SetHandledPowerUpRequestsReference(ctx sdk.Context, reference string) {
store := ctx.KVStore(k.storeKey)
store.Set(getHandledPowerUpRequestsReferenceStoreKey(reference), []byte(reference))
}
func (k Keeper) HandledPowerUpRequestsIterator(ctx sdk.Context) sdk.Iterator {
store := ctx.KVStore(k.storeKey)
return sdk.KVStorePrefixIterator(store, []byte(types.HandledPowerUpRequestsReferenceStorePrefix))
}
// DepositIntoPool allows to deposit the specified amount into the liquidity pool, taking it from the
// specified depositor balance
func (k Keeper) DepositIntoPool(ctx sdk.Context, depositor sdk.AccAddress, amount sdk.Coins) sdk.Error {
// Check the amount
if !amount.IsValid() || amount.Empty() || amount.IsAnyNegative() {
return sdk.ErrInvalidCoins(fmt.Sprintf("Invalid coins: %s", amount))
}
// Subtract the coins from the user
if err := k.supplyKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleName, amount); err != nil {
return err
}
return nil
}
// FundAccount allows to take the specified amount from the liquidity pool and move them into the
// specified account balance
func (k Keeper) FundAccount(ctx sdk.Context, account sdk.AccAddress, amount sdk.Coins) sdk.Error {
// Check the amount
if amount.Empty() || !amount.IsValid() {
return sdk.ErrInvalidCoins(fmt.Sprintf("Invalid coins: %s", amount))
}
// Get the current pool
currentPool := k.GetPoolAmount(ctx)
// Check that the pool has enough funds
if amount.IsAnyGT(currentPool) {
return sdk.ErrInsufficientFunds("Pool does not have enough funds")
}
// Add the coins to the user
if err := k.supplyKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, account, amount); err != nil {
return err
}
return nil
}