78 lines
1.3 KiB
Go
78 lines
1.3 KiB
Go
package replay
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"math/rand"
|
|
"testing"
|
|
)
|
|
|
|
func TestAntiReplay_Verify(t *testing.T) {
|
|
t.Run("NoReplays", func(t *testing.T) {
|
|
// ASSIGN
|
|
r := NewAntiReplay()
|
|
|
|
start := rand.Uint64()
|
|
sum := make([]byte, 8)
|
|
|
|
// ACT + ASSERT
|
|
for i := start; i < start+128; i++ {
|
|
// ACT
|
|
binary.LittleEndian.PutUint64(sum, i)
|
|
err := r.Verify(nil, sum)
|
|
|
|
// ASSERT
|
|
require.Nil(t, err)
|
|
}
|
|
})
|
|
|
|
t.Run("ImmediateReplay", func(t *testing.T) {
|
|
// ASSIGN
|
|
r := NewAntiReplay()
|
|
|
|
start := rand.Uint64()
|
|
sum := make([]byte, 8)
|
|
|
|
// ACT
|
|
binary.LittleEndian.PutUint64(sum, start)
|
|
|
|
err1 := r.Verify(nil, sum)
|
|
err2 := r.Verify(nil, sum)
|
|
|
|
// ASSERT
|
|
require.Nil(t, err1)
|
|
require.Equal(t, ErrReplayedPacket, err2)
|
|
})
|
|
|
|
t.Run("RandomReplays", func(t *testing.T) {
|
|
// ASSIGN
|
|
r := NewAntiReplay()
|
|
|
|
start := rand.Uint64()
|
|
sum := make([]byte, 8)
|
|
|
|
random := make([]byte, 512/8)
|
|
rand.Read(random)
|
|
|
|
// ACT + ASSERT
|
|
for i := 0; i < 512; i++ {
|
|
// ACT
|
|
replay := (random[i/8] & (1 << (i % 8)) > 0) && i != 0
|
|
if !replay {
|
|
start++
|
|
}
|
|
|
|
binary.LittleEndian.PutUint64(sum, start)
|
|
err := r.Verify(nil, sum)
|
|
|
|
// ASSERT
|
|
if replay {
|
|
assert.Equal(t, ErrReplayedPacket, err)
|
|
} else {
|
|
assert.Nil(t, err)
|
|
}
|
|
}
|
|
})
|
|
}
|