cosmos-sdk/modules/nonce/replaycheck.go

74 lines
1.8 KiB
Go
Raw Normal View History

2017-07-11 17:00:39 -07:00
package nonce
import (
"github.com/tendermint/basecoin"
"github.com/tendermint/basecoin/stack"
"github.com/tendermint/basecoin/state"
)
//nolint
const (
NameNonce = "nonce"
)
2017-07-12 02:02:16 -07:00
// ReplayCheck uses the sequence to check for replay attacks
2017-07-11 17:00:39 -07:00
type ReplayCheck struct {
stack.PassOption
}
// Name of the module - fulfills Middleware interface
func (ReplayCheck) Name() string {
return NameNonce
}
var _ stack.Middleware = ReplayCheck{}
2017-07-12 02:02:16 -07:00
// CheckTx verifies tx is not being replayed - fulfills Middlware interface
func (r ReplayCheck) CheckTx(ctx basecoin.Context, store state.SimpleDB,
2017-07-12 02:02:16 -07:00
tx basecoin.Tx, next basecoin.Checker) (res basecoin.Result, err error) {
2017-07-13 07:34:57 -07:00
stx, err := r.checkIncrementNonceTx(ctx, store, tx)
2017-07-11 17:00:39 -07:00
if err != nil {
return res, err
}
2017-07-13 01:37:22 -07:00
2017-07-13 07:34:57 -07:00
return next.CheckTx(ctx, store, stx)
2017-07-11 17:00:39 -07:00
}
2017-07-12 02:02:16 -07:00
// DeliverTx verifies tx is not being replayed - fulfills Middlware interface
2017-07-13 07:34:57 -07:00
// NOTE It is okay to modify the sequence before running the wrapped TX because if the
// wrapped Tx fails, the state changes are not applied
func (r ReplayCheck) DeliverTx(ctx basecoin.Context, store state.SimpleDB,
2017-07-12 02:02:16 -07:00
tx basecoin.Tx, next basecoin.Deliver) (res basecoin.Result, err error) {
2017-07-13 07:34:57 -07:00
stx, err := r.checkIncrementNonceTx(ctx, store, tx)
2017-07-11 17:00:39 -07:00
if err != nil {
return res, err
}
2017-07-13 01:37:22 -07:00
2017-07-13 07:34:57 -07:00
return next.DeliverTx(ctx, store, stx)
2017-07-12 02:02:16 -07:00
}
2017-07-13 07:34:57 -07:00
// checkNonceTx varifies the nonce sequence, an increment sequence number
func (r ReplayCheck) checkIncrementNonceTx(ctx basecoin.Context, store state.SimpleDB,
2017-07-12 02:02:16 -07:00
tx basecoin.Tx) (basecoin.Tx, error) {
// make sure it is a the nonce Tx (Tx from this package)
nonceTx, ok := tx.Unwrap().(Tx)
if !ok {
2017-07-14 13:29:43 -07:00
return tx, ErrNoNonce()
}
err := nonceTx.ValidateBasic()
if err != nil {
return tx, err
2017-07-12 02:02:16 -07:00
}
// check the nonce sequence number
2017-07-14 13:29:43 -07:00
err = nonceTx.CheckIncrementSeq(ctx, store)
2017-07-12 02:02:16 -07:00
if err != nil {
return tx, err
}
return nonceTx.Tx, nil
2017-07-11 17:00:39 -07:00
}