diff --git a/lib/mempool.go b/lib/mempool.go index 387f979dab..1fa555d718 100644 --- a/lib/mempool.go +++ b/lib/mempool.go @@ -41,11 +41,7 @@ type MempoolTx struct { // NewMempool() creates a new FeeMempool instance of a Mempool func NewMempool(config MempoolConfig) Mempool { - // if the config drop percentage is set to 0 - if config.DropPercentage == 0 { - // set the drop percentage to the default mempool config - config.DropPercentage = DefaultMempoolConfig().DropPercentage - } + config.DropPercentage = normalizeDropPercentage(config.DropPercentage) // return the default mempool return &FeeMempool{ pool: MempoolTxs{}, @@ -281,6 +277,7 @@ func (t *MempoolTxs) delete(txs [][]byte) (deleted []MempoolTx, deletedBz int) { // drop() removes the bottom (the lowest fee) X percent of Transactions func (t *MempoolTxs) drop(percent int) (dropped []MempoolTx) { + percent = normalizeDropPercentage(percent) // calculate the percent using integer division numDrop := (len(t.s)*percent)/100 + 1 // avoid slicing out of bounds @@ -300,6 +297,13 @@ func (t *MempoolTxs) drop(percent int) (dropped []MempoolTx) { return } +func normalizeDropPercentage(percent int) int { + if percent <= 0 { + return DefaultMempoolConfig().DropPercentage + } + return percent +} + // copy() returns a shallow copy of the MempoolTxs func (t *MempoolTxs) copy() *MempoolTxs { // allocate a destination diff --git a/lib/mempool_test.go b/lib/mempool_test.go index 7a7df077a5..adaefaf58b 100644 --- a/lib/mempool_test.go +++ b/lib/mempool_test.go @@ -221,6 +221,39 @@ func TestAddTransaction(t *testing.T) { } } +func TestAddTransactionNormalizesNegativeDropPercentage(t *testing.T) { + sig := &Signature{ + PublicKey: newTestPublicKeyBytes(t), + Signature: newTestPublicKeyBytes(t), + } + a, e := NewAny(sig) + require.NoError(t, e) + + mempool := NewMempool(MempoolConfig{ + MaxTotalBytes: math.MaxUint64, + MaxTransactionCount: 4, + IndividualMaxTxSize: math.MaxUint32, + DropPercentage: -35, + }) + + for i := uint64(1); i <= 4; i++ { + tx, err := Marshal(&Transaction{ + MessageType: testMessageName, + Msg: a, + Signature: sig, + CreatedHeight: 1, + Time: uint64(time.Now().UnixMicro()), + Fee: i, + NetworkId: 1, + ChainId: i, + }) + require.NoError(t, err) + require.NoError(t, mempool.AddTransactions(tx)) + } + + require.Equal(t, 2, mempool.TxCount()) +} + func TestGetAndContainsTransaction(t *testing.T) { // pre-define a test message sig := &Signature{