implement rotating nonce list
This commit is contained in:
parent
04032cca4c
commit
6ae1fee758
2 changed files with 72 additions and 0 deletions
46
net/lux_noncelist.go
Normal file
46
net/lux_noncelist.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package net
|
||||
|
||||
import "math/rand/v2"
|
||||
|
||||
const LUX_NONCE_MAX = 128
|
||||
|
||||
// Anti replay measure.
|
||||
type LuxNonceList struct {
|
||||
nonces []uint64
|
||||
}
|
||||
|
||||
func GenerateLuxNonce() uint64 {
|
||||
return rand.Uint64()
|
||||
}
|
||||
|
||||
func NewLuxNonceList() LuxNonceList {
|
||||
return LuxNonceList{
|
||||
nonces: make([]uint64, 0),
|
||||
}
|
||||
}
|
||||
|
||||
func (list *LuxNonceList) RotateOrFail(newNonce uint64) bool {
|
||||
for _, nonce := range list.nonces {
|
||||
if nonce == newNonce {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if len(list.nonces) == LUX_NONCE_MAX {
|
||||
// rotate
|
||||
for i := LUX_NONCE_MAX - 1; i > 0; i-- {
|
||||
list.nonces[i] = list.nonces[i-1]
|
||||
}
|
||||
|
||||
list.nonces[0] = newNonce
|
||||
} else {
|
||||
// append to head
|
||||
list.nonces = append([]uint64{newNonce}, list.nonces...)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (list *LuxNonceList) Get(idx int) uint64 {
|
||||
return list.nonces[idx]
|
||||
}
|
||||
26
tests/lux_noncelist_test.go
Normal file
26
tests/lux_noncelist_test.go
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
package tests
|
||||
|
||||
import (
|
||||
"lux/net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNonces(t *testing.T) {
|
||||
list := net.NewLuxNonceList()
|
||||
for i := 0; i < 129; i++ {
|
||||
if !list.RotateOrFail(net.GenerateLuxNonce()) {
|
||||
t.Fatal("duplicate 64bit nonce per 129 items")
|
||||
}
|
||||
}
|
||||
|
||||
// sanity checks
|
||||
if list.Get(0) == list.Get(1) {
|
||||
t.Fatal("list.Get(0) == list.Get(1)")
|
||||
}
|
||||
if list.Get(0) == list.Get(127) {
|
||||
t.Fatal("list.Get(0) == list.Get(127)")
|
||||
}
|
||||
if list.Get(126) == list.Get(127) {
|
||||
t.Fatal("list.Get(26) == list.Get(127)")
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue