-
Notifications
You must be signed in to change notification settings - Fork 2
/
keeper.go
528 lines (429 loc) · 16.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package keeper
import (
"bytes"
"fmt"
"time"
"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/codec"
"github.com/fibonacci-chain/fbc/libs/tendermint/libs/log"
sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types"
sdkerrors "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types/errors"
"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types/innertx"
authexported "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/auth/exported"
vestexported "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/auth/vesting/exported"
"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/bank/internal/types"
"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/params"
"github.com/fibonacci-chain/fbc/libs/tendermint/global"
)
var _ Keeper = (*BaseKeeper)(nil)
// Keeper defines a module interface that facilitates the transfer of coins
// between accounts.
type Keeper interface {
SendKeeper
DelegateCoins(ctx sdk.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) error
UndelegateCoins(ctx sdk.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) error
GetInnerTxKeeper() innertx.InnerTxKeeper
}
// BaseKeeper manages transfers between accounts. It implements the Keeper interface.
type BaseKeeper struct {
BaseSendKeeper
ak types.AccountKeeper
paramSpace params.Subspace
marshal *codec.CodecProxy
}
// NewBaseKeeper returns a new BaseKeeper
func NewBaseKeeper(
ak types.AccountKeeper, paramSpace params.Subspace, blacklistedAddrs map[string]bool,
) BaseKeeper {
ps := paramSpace.WithKeyTable(types.ParamKeyTable())
return BaseKeeper{
BaseSendKeeper: NewBaseSendKeeper(ak, ps, blacklistedAddrs),
ak: ak,
paramSpace: ps,
}
}
func NewBaseKeeperWithMarshal(ak types.AccountKeeper, marshal *codec.CodecProxy, paramSpace params.Subspace, blacklistedAddrs map[string]bool,
) BaseKeeper {
ret := NewBaseKeeper(ak, paramSpace, blacklistedAddrs)
ret.marshal = marshal
return ret
}
// DelegateCoins performs delegation by deducting amt coins from an account with
// address addr. For vesting accounts, delegations amounts are tracked for both
// vesting and vested coins.
// The coins are then transferred from the delegator address to a ModuleAccount address.
// If any of the delegation amounts are negative, an error is returned.
func (keeper BaseKeeper) DelegateCoins(ctx sdk.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) (err error) {
defer func() {
if !ctx.IsCheckTx() && keeper.ik != nil {
keeper.ik.UpdateInnerTx(ctx.TxBytes(), ctx.BlockHeight(), innertx.CosmosDepth, delegatorAddr, moduleAccAddr, innertx.CosmosCallType, innertx.DelegateCallName, amt, err)
}
}()
delegatorAcc := keeper.ak.GetAccount(ctx, delegatorAddr)
if delegatorAcc == nil {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", delegatorAddr)
}
moduleAcc := keeper.ak.GetAccount(ctx, moduleAccAddr)
if moduleAcc == nil {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleAccAddr)
}
if !amt.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
oldCoins := delegatorAcc.GetCoins()
_, hasNeg := oldCoins.SafeSub(amt)
if hasNeg {
return sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds, "insufficient account funds; %s < %s", oldCoins, amt,
)
}
if err := trackDelegation(delegatorAcc, ctx.BlockHeader().Time, amt); err != nil {
return sdkerrors.Wrap(err, "failed to track delegation")
}
keeper.ak.SetAccount(ctx, delegatorAcc)
_, err = keeper.AddCoins(ctx, moduleAccAddr, amt)
if err != nil {
return err
}
return nil
}
// UndelegateCoins performs undelegation by crediting amt coins to an account with
// address addr. For vesting accounts, undelegation amounts are tracked for both
// vesting and vested coins.
// The coins are then transferred from a ModuleAccount address to the delegator address.
// If any of the undelegation amounts are negative, an error is returned.
func (keeper BaseKeeper) UndelegateCoins(ctx sdk.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) (err error) {
defer func() {
if !ctx.IsCheckTx() && keeper.ik != nil {
keeper.ik.UpdateInnerTx(ctx.TxBytes(), ctx.BlockHeight(), innertx.CosmosDepth, moduleAccAddr, delegatorAddr, innertx.CosmosCallType, innertx.UndelegateCallName, amt, err)
}
}()
delegatorAcc := keeper.ak.GetAccount(ctx, delegatorAddr)
if delegatorAcc == nil {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", delegatorAddr)
}
moduleAcc := keeper.ak.GetAccount(ctx, moduleAccAddr)
if moduleAcc == nil {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleAccAddr)
}
if !amt.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
oldCoins := moduleAcc.GetCoins()
newCoins, hasNeg := oldCoins.SafeSub(amt)
if hasNeg {
return sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds, "insufficient account funds; %s < %s", oldCoins, amt,
)
}
if err = keeper.SetCoins(ctx, moduleAccAddr, newCoins); err != nil {
return err
}
if err := trackUndelegation(delegatorAcc, amt); err != nil {
return sdkerrors.Wrap(err, "failed to track undelegation")
}
keeper.ak.SetAccount(ctx, delegatorAcc)
return nil
}
// SendKeeper defines a module interface that facilitates the transfer of coins
// between accounts without the possibility of creating coins.
type SendKeeper interface {
ViewKeeper
InputOutputCoins(ctx sdk.Context, inputs []types.Input, outputs []types.Output) error
SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error
SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, error)
AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, error)
SetCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) error
GetSendEnabled(ctx sdk.Context) bool
SetSendEnabled(ctx sdk.Context, enabled bool)
BlacklistedAddr(addr sdk.AccAddress) bool
}
var _ SendKeeper = (*BaseSendKeeper)(nil)
// BaseSendKeeper only allows transfers between accounts without the possibility of
// creating coins. It implements the SendKeeper interface.
type BaseSendKeeper struct {
BaseViewKeeper
ak types.AccountKeeper
ask authexported.SizerAccountKeeper
paramSpace params.Subspace
// list of addresses that are restricted from receiving transactions
blacklistedAddrs map[string]bool
ik innertx.InnerTxKeeper
}
// NewBaseSendKeeper returns a new BaseSendKeeper.
func NewBaseSendKeeper(
ak types.AccountKeeper, paramSpace params.Subspace, blacklistedAddrs map[string]bool,
) BaseSendKeeper {
bsk := BaseSendKeeper{
BaseViewKeeper: NewBaseViewKeeper(ak),
ak: ak,
paramSpace: paramSpace,
blacklistedAddrs: blacklistedAddrs,
}
bsk.ask, _ = bsk.ak.(authexported.SizerAccountKeeper)
return bsk
}
// InputOutputCoins handles a list of inputs and outputs
func (keeper BaseSendKeeper) InputOutputCoins(ctx sdk.Context, inputs []types.Input, outputs []types.Output) (err error) {
defer func() {
if !ctx.IsCheckTx() && keeper.ik != nil {
for _, in := range inputs {
keeper.ik.UpdateInnerTx(ctx.TxBytes(), ctx.BlockHeight(), innertx.CosmosDepth, in.Address, sdk.AccAddress{}, innertx.CosmosCallType, innertx.MultiCallName, in.Coins, err)
}
for _, out := range outputs {
keeper.ik.UpdateInnerTx(ctx.TxBytes(), ctx.BlockHeight(), innertx.CosmosDepth, sdk.AccAddress{}, out.Address, innertx.CosmosCallType, innertx.MultiCallName, out.Coins, err)
}
}
}()
// Safety check ensuring that when sending coins the keeper must maintain the
// Check supply invariant and validity of Coins.
if err := types.ValidateInputsOutputs(inputs, outputs); err != nil {
return err
}
for _, in := range inputs {
_, err := keeper.SubtractCoins(ctx, in.Address, in.Coins)
if err != nil {
return err
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(types.AttributeKeySender, in.Address.String()),
),
)
}
for _, out := range outputs {
_, err := keeper.AddCoins(ctx, out.Address, out.Coins)
if err != nil {
return err
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeTransfer,
sdk.NewAttribute(types.AttributeKeyRecipient, out.Address.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, out.Coins.String()),
),
)
// Create account if recipient does not exist.
//
// NOTE: This should ultimately be removed in favor a more flexible approach
// such as delegated fee messages.
acc := keeper.ak.GetAccount(ctx, out.Address)
if acc == nil {
keeper.ak.SetAccount(ctx, keeper.ak.NewAccountWithAddress(ctx, out.Address))
}
}
return nil
}
// SendCoins moves coins from one account to another
func (keeper BaseSendKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) (err error) {
defer func() {
if !ctx.IsCheckTx() && keeper.ik != nil {
keeper.ik.UpdateInnerTx(ctx.TxBytes(), ctx.BlockHeight(), innertx.CosmosDepth, fromAddr, toAddr, innertx.CosmosCallType, innertx.SendCallName, amt, err)
}
}()
fromAddrStr := fromAddr.String()
ctx.EventManager().EmitEvents(sdk.Events{
// This event should have all info (to, from, amount) without looking at other events
sdk.NewEvent(
types.EventTypeTransfer,
sdk.NewAttribute(types.AttributeKeyRecipient, toAddr.String()),
sdk.NewAttribute(types.AttributeKeySender, fromAddrStr),
sdk.NewAttribute(sdk.AttributeKeyAmount, amt.String()),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(types.AttributeKeySender, fromAddrStr),
),
})
if !amt.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
fromAcc, _ := ctx.GetFromAccountCacheData().(authexported.Account)
toAcc, _ := ctx.GetToAccountCacheData().(authexported.Account)
fromAccGas, toAccGas := ctx.GetFromAccountCacheGas(), ctx.GetToAccountCacheGas()
fromAcc, fromAccGas = keeper.getAccount(&ctx, fromAddr, fromAcc, fromAccGas)
_, err = keeper.subtractCoins(ctx, fromAddr, fromAcc, fromAccGas, amt)
if err != nil {
return err
}
ctx.UpdateFromAccountCache(fromAcc, 0)
toAcc, toAccGas = keeper.getAccount(&ctx, toAddr, toAcc, toAccGas)
_, err = keeper.addCoins(ctx, toAddr, toAcc, toAccGas, amt)
if err != nil {
return err
}
ctx.UpdateToAccountCache(toAcc, 0)
return nil
}
// SubtractCoins subtracts amt from the coins at the addr.
//
// CONTRACT: If the account is a vesting account, the amount has to be spendable.
func (keeper BaseSendKeeper) SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, error) {
if !amt.IsValid() {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
acc, gasUsed := authexported.GetAccountAndGas(&ctx, keeper.ak, addr)
return keeper.subtractCoins(ctx, addr, acc, gasUsed, amt)
}
func (keeper *BaseSendKeeper) subtractCoins(ctx sdk.Context, addr sdk.AccAddress, acc authexported.Account, accGas sdk.Gas, amt sdk.Coins) (sdk.Coins, error) {
oldCoins, spendableCoins := sdk.NewCoins(), sdk.NewCoins()
if acc != nil {
oldCoins = acc.GetCoins()
spendableCoins = acc.SpendableCoins(ctx.BlockTime())
}
// For non-vesting accounts, spendable coins will simply be the original coins.
// So the check here is sufficient instead of subtracting from oldCoins.
_, hasNeg := spendableCoins.SafeSub(amt)
if hasNeg {
return amt, sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds, "insufficient account funds; %s < %s", spendableCoins, amt,
)
}
newCoins := oldCoins.Sub(amt) // should not panic as spendable coins was already checked
err := keeper.setCoinsToAccount(ctx, addr, acc, accGas, newCoins)
return newCoins, err
}
// AddCoins adds amt to the coins at the addr.
func (keeper BaseSendKeeper) AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, error) {
if !amt.IsValid() {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
// oldCoins := keeper.GetCoins(ctx, addr)
acc, gasUsed := authexported.GetAccountAndGas(&ctx, keeper.ak, addr)
return keeper.addCoins(ctx, addr, acc, gasUsed, amt)
}
func (keeper *BaseSendKeeper) addCoins(ctx sdk.Context, addr sdk.AccAddress, acc authexported.Account, accGas sdk.Gas, amt sdk.Coins) (sdk.Coins, error) {
var oldCoins sdk.Coins
if acc == nil {
oldCoins = sdk.NewCoins()
} else {
oldCoins = acc.GetCoins()
}
newCoins := oldCoins.Add(amt...)
if newCoins.IsAnyNegative() {
return amt, sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds, "insufficient account funds; %s < %s", oldCoins, amt,
)
}
err := keeper.setCoinsToAccount(ctx, addr, acc, accGas, newCoins)
return newCoins, err
}
// SetCoins sets the coins at the addr.
func (keeper BaseSendKeeper) SetCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) error {
if !amt.IsValid() {
sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
acc := keeper.ak.GetAccount(ctx, addr)
if acc == nil {
acc = keeper.ak.NewAccountWithAddress(ctx, addr)
}
err := acc.SetCoins(amt)
if err != nil {
panic(err)
}
keeper.ak.SetAccount(ctx, acc)
return nil
}
func (keeper *BaseSendKeeper) getAccount(ctx *sdk.Context, addr sdk.AccAddress, acc authexported.Account, getgas sdk.Gas) (authexported.Account, sdk.Gas) {
gasMeter := ctx.GasMeter()
if acc != nil && bytes.Equal(acc.GetAddress(), addr) {
if getgas > 0 {
gasMeter.ConsumeGas(getgas, "get account")
return acc, getgas
}
if ok, gasused := authexported.TryAddGetAccountGas(gasMeter, keeper.ask, acc); ok {
return acc, gasused
}
}
return authexported.GetAccountAndGas(ctx, keeper.ak, addr)
}
func (keeper *BaseSendKeeper) setCoinsToAccount(ctx sdk.Context, addr sdk.AccAddress, acc authexported.Account, accGas sdk.Gas, amt sdk.Coins) error {
if !amt.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
acc, _ = keeper.getAccount(&ctx, addr, acc, accGas)
if acc == nil {
acc = keeper.ak.NewAccountWithAddress(ctx, addr)
}
err := acc.SetCoins(amt)
if err != nil {
panic(err)
}
keeper.ak.SetAccount(ctx, acc)
return nil
}
// GetSendEnabled returns the current SendEnabled
func (keeper BaseSendKeeper) GetSendEnabled(ctx sdk.Context) bool {
var enabled bool
keeper.paramSpace.Get(ctx, types.ParamStoreKeySendEnabled, &enabled)
return enabled
}
// SetSendEnabled sets the send enabled
func (keeper BaseSendKeeper) SetSendEnabled(ctx sdk.Context, enabled bool) {
global.Manager.SetSendEnabled(enabled)
keeper.paramSpace.Set(ctx, types.ParamStoreKeySendEnabled, &enabled)
}
// BlacklistedAddr checks if a given address is blacklisted (i.e restricted from
// receiving funds)
func (keeper BaseSendKeeper) BlacklistedAddr(addr sdk.AccAddress) bool {
return keeper.blacklistedAddrs[addr.String()]
}
// SetInnerTxKeeper set innerTxKeeper
func (k *BaseKeeper) SetInnerTxKeeper(keeper innertx.InnerTxKeeper) {
k.BaseSendKeeper.SetInnerTxKeeper(keeper)
}
func (k *BaseSendKeeper) SetInnerTxKeeper(keeper innertx.InnerTxKeeper) {
k.ik = keeper
}
func (k BaseSendKeeper) GetInnerTxKeeper() innertx.InnerTxKeeper {
return k.ik
}
var _ ViewKeeper = (*BaseViewKeeper)(nil)
// ViewKeeper defines a module interface that facilitates read only access to
// account balances.
type ViewKeeper interface {
GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins
HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool
}
// BaseViewKeeper implements a read only keeper implementation of ViewKeeper.
type BaseViewKeeper struct {
ak types.AccountKeeper
}
// NewBaseViewKeeper returns a new BaseViewKeeper.
func NewBaseViewKeeper(ak types.AccountKeeper) BaseViewKeeper {
return BaseViewKeeper{ak: ak}
}
// Logger returns a module-specific logger.
func (keeper BaseViewKeeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName))
}
// GetCoins returns the coins at the addr.
func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {
acc := keeper.ak.GetAccount(ctx, addr)
if acc == nil {
return sdk.NewCoins()
}
return acc.GetCoins()
}
// HasCoins returns whether or not an account has at least amt coins.
func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {
return keeper.GetCoins(ctx, addr).IsAllGTE(amt)
}
// CONTRACT: assumes that amt is valid.
func trackDelegation(acc authexported.Account, blockTime time.Time, amt sdk.Coins) error {
vacc, ok := acc.(vestexported.VestingAccount)
if ok {
// TODO: return error on account.TrackDelegation
vacc.TrackDelegation(blockTime, amt)
}
return acc.SetCoins(acc.GetCoins().Sub(amt))
}
// CONTRACT: assumes that amt is valid.
func trackUndelegation(acc authexported.Account, amt sdk.Coins) error {
vacc, ok := acc.(vestexported.VestingAccount)
if ok {
// TODO: return error on account.TrackUndelegation
vacc.TrackUndelegation(amt)
}
return acc.SetCoins(acc.GetCoins().Add(amt...))
}