Skip to content

Commit

Permalink
Fix bug when popping pending TXs (#188)
Browse files Browse the repository at this point in the history
  • Loading branch information
codchen authored and udpatil committed Apr 16, 2024
1 parent 675fafc commit 2b21cc2
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 2 deletions.
10 changes: 8 additions & 2 deletions internal/mempool/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,10 +342,16 @@ func (p *PendingTxs) popTxsAtIndices(indices []int) {
newTxs := []TxWithResponse{}
start := 0
for _, idx := range indices {
if idx <= start-1 {
panic("indices popped from pending tx store should be sorted without duplicate")
}
if idx >= len(p.txs) {
panic("indices popped from pending tx store out of range")
}
newTxs = append(newTxs, p.txs[start:idx]...)
start = idx
start = idx + 1
}
newTxs = append(newTxs, p.txs[start+1:]...)
newTxs = append(newTxs, p.txs[start:]...)
p.txs = newTxs
}

Expand Down
72 changes: 72 additions & 0 deletions internal/mempool/tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,75 @@ func TestWrappedTxList_Remove(t *testing.T) {
sort.Ints(expected)
require.Equal(t, expected, got)
}

func TestPendingTxsPopTxsGood(t *testing.T) {
pendingTxs := NewPendingTxs()
for _, test := range []struct {
origLen int
popIndices []int
expected []int
}{
{
origLen: 1,
popIndices: []int{},
expected: []int{0},
}, {
origLen: 1,
popIndices: []int{0},
expected: []int{},
}, {
origLen: 2,
popIndices: []int{0},
expected: []int{1},
}, {
origLen: 2,
popIndices: []int{1},
expected: []int{0},
}, {
origLen: 2,
popIndices: []int{0, 1},
expected: []int{},
}, {
origLen: 3,
popIndices: []int{1},
expected: []int{0, 2},
}, {
origLen: 3,
popIndices: []int{0, 2},
expected: []int{1},
}, {
origLen: 3,
popIndices: []int{0, 1, 2},
expected: []int{},
}, {
origLen: 5,
popIndices: []int{0, 1, 4},
expected: []int{2, 3},
}, {
origLen: 5,
popIndices: []int{1, 3},
expected: []int{0, 2, 4},
},
} {
pendingTxs.txs = []TxWithResponse{}
for i := 0; i < test.origLen; i++ {
pendingTxs.txs = append(pendingTxs.txs, TxWithResponse{txInfo: TxInfo{SenderID: uint16(i)}})
}
pendingTxs.popTxsAtIndices(test.popIndices)
require.Equal(t, len(test.expected), len(pendingTxs.txs))
for i, e := range test.expected {
require.Equal(t, e, int(pendingTxs.txs[i].txInfo.SenderID))
}
}
}

func TestPendingTxsPopTxsBad(t *testing.T) {
pendingTxs := NewPendingTxs()
// out of range
require.Panics(t, func() { pendingTxs.popTxsAtIndices([]int{0}) })
// out of order
pendingTxs.txs = []TxWithResponse{{}, {}, {}}
require.Panics(t, func() { pendingTxs.popTxsAtIndices([]int{1, 0}) })
// duplicate
require.Panics(t, func() { pendingTxs.popTxsAtIndices([]int{2, 2}) })
}

0 comments on commit 2b21cc2

Please sign in to comment.