-
Notifications
You must be signed in to change notification settings - Fork 29
/
decorators.go
349 lines (299 loc) · 11.3 KB
/
decorators.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
package project
import (
"bytes"
"fmt"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
"github.com/cosmos/cosmos-sdk/x/auth/keeper"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
didkeeper "github.com/ixofoundation/ixo-blockchain/x/did/keeper"
ixotypes "github.com/ixofoundation/ixo-blockchain/x/ixo/types"
"github.com/ixofoundation/ixo-blockchain/x/project/types"
)
// SetUpContextDecorator sets the GasMeter in the Context and wraps the next AnteHandler with a defer clause
// to recover from any downstream OutOfGas panics in the AnteHandler chain to return an error with information
// on gas provided and gas used.
// CONTRACT: Must be first decorator in the chain
// CONTRACT: Tx must implement GasTx interface
type SetUpContextDecorator struct{}
func NewSetUpContextDecorator() SetUpContextDecorator {
return SetUpContextDecorator{}
}
func (sud SetUpContextDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
// all transactions must implement GasTx
gasTx, ok := tx.(ante.GasTx)
if !ok {
// Set a gas meter with limit 0 as to prevent an infinite gas meter attack
// during runTx.
newCtx = ante.SetGasMeter(simulate, ctx, 0)
return newCtx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be GasTx")
}
// Addding of DID uses an infinite gas meter
newCtx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
// Decorator will catch an OutOfGasPanic caused in the next antehandler
// AnteHandlers must have their own defer/recover in order for the BaseApp
// to know how much gas was used! This is because the GasMeter is created in
// the AnteHandler, but if it panics the context won't be set properly in
// runTx's recover call.
defer func() {
if r := recover(); r != nil {
switch rType := r.(type) {
case sdk.ErrorOutOfGas:
log := fmt.Sprintf(
"out of gas in location: %v; gasWanted: %d, gasUsed: %d",
rType.Descriptor, gasTx.GetGas(), newCtx.GasMeter().GasConsumed())
err = sdkerrors.Wrap(sdkerrors.ErrOutOfGas, log)
default:
panic(r)
}
}
}()
return next(newCtx, tx, simulate)
}
type SetPubKeyDecorator struct {
ak keeper.AccountKeeper
pkg ixotypes.PubKeyGetter
}
func NewSetPubKeyDecorator(ak keeper.AccountKeeper, pkg ixotypes.PubKeyGetter) SetPubKeyDecorator {
return SetPubKeyDecorator{
ak: ak,
pkg: pkg,
}
}
func (spkd SetPubKeyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
_, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid tx type")
}
// message must be of type MsgCreateProject
msg, ok := tx.GetMsgs()[0].(*types.MsgCreateProject)
if !ok {
return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "msg must be MsgCreateProject")
}
// Get project pubKey
pubKey, err := spkd.pkg(ctx, msg)
if err != nil {
return ctx, err
}
// Fetch signer (project itself). Account expected to not exist
signerAddr := sdk.AccAddress(pubKey.Address())
_, err = ante.GetSignerAcc(ctx, spkd.ak, signerAddr)
if err == nil {
return ctx, fmt.Errorf("expected project account to not exist")
}
// Create signer's account
signerAcc := spkd.ak.NewAccountWithAddress(ctx, signerAddr)
spkd.ak.SetAccount(ctx, signerAcc)
pubkeys := []cryptotypes.PubKey{pubKey}
signers := []sdk.AccAddress{signerAddr}
for i, pk := range pubkeys {
// PublicKey was omitted from slice since it has already been set in context
if pk == nil {
if !simulate {
continue
}
pk = &simEd25519Pubkey
}
// Only make check if simulate=false
if !simulate && !bytes.Equal(pk.Address(), signers[i]) {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrInvalidPubKey,
"pubKey does not match signer address %s with signer index: %d", signers[i], i)
}
acc, err := ante.GetSignerAcc(ctx, spkd.ak, signers[i])
if err != nil {
return ctx, err
}
// account already has pubkey set,no need to reset
if acc.GetPubKey() != nil {
continue
}
err = acc.SetPubKey(pk)
if err != nil {
return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidPubKey, err.Error())
}
spkd.ak.SetAccount(ctx, acc)
}
return next(ctx, tx, simulate)
}
// DeductFeeDecorator deducts fees from the first signer of the tx
// If the first signer does not have the funds to pay for the fees, return with InsufficientFunds error
// Call next AnteHandler if fees successfully deducted
// CONTRACT: Tx must implement FeeTx interface to use DeductFeeDecorator
type DeductFeeDecorator struct {
ak keeper.AccountKeeper
bk bankkeeper.Keeper
didKeeper didkeeper.Keeper
pkg ixotypes.PubKeyGetter
}
func NewDeductFeeDecorator(ak keeper.AccountKeeper, bk bankkeeper.Keeper,
didKeeper didkeeper.Keeper, pkg ixotypes.PubKeyGetter) DeductFeeDecorator {
return DeductFeeDecorator{
ak: ak,
bk: bk,
didKeeper: didKeeper,
pkg: pkg,
}
}
func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
feeTx, ok := tx.(sdk.FeeTx)
if !ok {
return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx")
}
if addr := dfd.ak.GetModuleAddress(authtypes.FeeCollectorName); addr == nil {
panic(fmt.Sprintf("%s module account has not been set", authtypes.FeeCollectorName))
}
// all messages must be of type MsgCreateProject
msg, ok := tx.GetMsgs()[0].(*types.MsgCreateProject)
if !ok {
return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "msg must be MsgCreateProject")
}
// Get pubKey
pubKey, err := dfd.pkg(ctx, msg)
if err != nil {
return ctx, err
}
// fetch first (and only) signer, who's going to pay the fees
feePayer := sdk.AccAddress(pubKey.Address())
feePayerAcc := dfd.ak.GetAccount(ctx, feePayer)
if feePayerAcc == nil {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "fee payer address: %s does not exist", feePayer)
}
// confirm that fee is the exact amount expected
expectedTotalFee := sdk.NewCoins(sdk.NewCoin(
ixotypes.IxoNativeToken, sdk.NewInt(types.MsgCreateProjectTotalFee)))
if !feeTx.GetFee().IsEqual(expectedTotalFee) {
return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid fee")
}
// Calculate transaction fee and project funding
transactionFee := sdk.NewCoins(sdk.NewCoin(
ixotypes.IxoNativeToken, sdk.NewInt(types.MsgCreateProjectTransactionFee)))
projectFunding := expectedTotalFee.Sub(transactionFee) // panics if negative result
// deduct the fees
if !feeTx.GetFee().IsZero() {
// fetch fee payer account
feePayerDidDoc, err := dfd.didKeeper.GetDidDoc(ctx, msg.SenderDid)
if err != nil {
return ctx, err
}
feePayerAcc, err := ante.GetSignerAcc(ctx, dfd.ak, feePayerDidDoc.Address())
if err != nil {
return ctx, err
}
err = ante.DeductFees(dfd.bk, ctx, feePayerAcc, transactionFee)
if err != nil {
return ctx, err
}
projectAddr := sdk.AccAddress(pubKey.Address())
err = deductProjectFundingFees(dfd.bk, ctx, feePayerAcc, projectAddr, projectFunding)
if err != nil {
return ctx, err
}
}
return next(ctx, tx, simulate)
}
// Verify all signatures for a tx and return an error if any are invalid. Note,
// the SigVerificationDecorator decorator will not get executed on ReCheck.
//
// CONTRACT: Pubkeys are set in context for all signers before this decorator runs
// CONTRACT: Tx must implement SigVerifiableTx interface
type SigVerificationDecorator struct {
ak keeper.AccountKeeper
signModeHandler authsigning.SignModeHandler
pkg ixotypes.PubKeyGetter
}
func NewSigVerificationDecorator(ak keeper.AccountKeeper, signModeHandler authsigning.SignModeHandler, pkg ixotypes.PubKeyGetter) SigVerificationDecorator {
return SigVerificationDecorator{
ak: ak,
signModeHandler: signModeHandler,
pkg: pkg,
}
}
func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
// no need to verify signatures on recheck tx
if ctx.IsReCheckTx() {
return next(ctx, tx, simulate)
}
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type")
}
// stdSigs contains the sequence number, account number, and signatures.
// When simulating, this would just be a 0-length slice.
sigs, err := sigTx.GetSignaturesV2()
if err != nil {
return ctx, err
}
// message must be of type MsgCreateProject
msg, ok := tx.GetMsgs()[0].(*types.MsgCreateProject)
if !ok {
return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "msg must be MsgCreateProject")
}
// Get signer did pubKey
pubKey, err := svd.pkg(ctx, msg)
if err != nil {
return ctx, err
}
// Fetch signer (account underlying DID). Account expected to not exist
signerAddrs := []sdk.AccAddress{sdk.AccAddress(pubKey.Address())}
// check that signer length and signature length are the same
if len(sigs) != len(signerAddrs) {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "invalid number of signer; expected: %d, got %d", len(signerAddrs), len(sigs))
}
for i, sig := range sigs {
acc, err := ante.GetSignerAcc(ctx, svd.ak, signerAddrs[i])
if err != nil {
return ctx, err
}
// check signature, return account with incremented nonce
// retrieve pubkey
pubKey := acc.GetPubKey()
if !simulate && pubKey == nil {
return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidPubKey, "pubkey on account is not set")
}
// Check account sequence number.
// When using Amino StdSignatures, we actually don't have the Sequence in
// the SignatureV2 struct (it's only in the SignDoc). In this case, we
// cannot check sequence directly, and must do it via signature
// verification (in the VerifySignature call below).
onlyAminoSigners := ante.OnlyLegacyAminoSigners(sig.Data)
if !onlyAminoSigners {
if sig.Sequence != acc.GetSequence() {
return ctx, sdkerrors.Wrapf(
sdkerrors.ErrWrongSequence,
"account sequence mismatch, expected %d, got %d", acc.GetSequence(), sig.Sequence,
)
}
}
genesis := ctx.BlockHeight() == 0
chainID := ctx.ChainID()
var accNum uint64
if !genesis {
// Fixed account number used so that sign bytes do not depend on it
accNum = uint64(0)
}
signerData := authsigning.SignerData{
ChainID: chainID,
AccountNumber: accNum,
Sequence: acc.GetSequence(),
}
if !simulate {
err := authsigning.VerifySignature(pubKey, signerData, sig.Data, svd.signModeHandler, tx)
if err != nil {
var errMsg string
if onlyAminoSigners {
// If all signers are using SIGN_MODE_LEGACY_AMINO, we rely on VerifySignature to check account sequence number,
// and therefore communicate sequence number as a potential cause of error.
errMsg = fmt.Sprintf("signature verification failed; please verify account number (%d), sequence (%d) and chain-id (%s)", accNum, acc.GetSequence(), chainID)
} else {
errMsg = fmt.Sprintf("signature verification failed; please verify account number (%d) and chain-id (%s)", accNum, chainID)
}
return ctx, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, errMsg)
}
}
}
return next(ctx, tx, simulate)
}