| 1 |
|
| 2 |
package replaydetector |
| 3 |
|
| 4 |
|
| 5 |
type ReplayDetector interface { |
| 6 |
|
| 7 |
|
| 8 |
Check(seq uint64) (accept func(), ok bool) |
| 9 |
} |
| 10 |
|
| 11 |
type slidingWindowDetector struct { |
| 12 |
latestSeq uint64 |
| 13 |
maxSeq uint64 |
| 14 |
windowSize uint |
| 15 |
mask *fixedBigInt |
| 16 |
} |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
func New(windowSize uint, maxSeq uint64) ReplayDetector { |
| 23 |
return &slidingWindowDetector{ |
| 24 |
maxSeq: maxSeq, |
| 25 |
windowSize: windowSize, |
| 26 |
mask: newFixedBigInt(windowSize), |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
func (d *slidingWindowDetector) Check(seq uint64) (accept func(), ok bool) { |
| 31 |
if seq > d.maxSeq { |
| 32 |
|
| 33 |
return func() {}, false |
| 34 |
} |
| 35 |
|
| 36 |
if seq <= d.latestSeq { |
| 37 |
if d.latestSeq >= uint64(d.windowSize)+seq { |
| 38 |
return func() {}, false |
| 39 |
} |
| 40 |
if d.mask.Bit(uint(d.latestSeq-seq)) != 0 { |
| 41 |
|
| 42 |
return func() {}, false |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
return func() { |
| 47 |
if seq > d.latestSeq { |
| 48 |
|
| 49 |
d.mask.Lsh(uint(seq - d.latestSeq)) |
| 50 |
d.latestSeq = seq |
| 51 |
} |
| 52 |
diff := (d.latestSeq - seq) % d.maxSeq |
| 53 |
d.mask.SetBit(uint(diff)) |
| 54 |
}, true |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
func WithWrap(windowSize uint, maxSeq uint64) ReplayDetector { |
| 60 |
return &wrappedSlidingWindowDetector{ |
| 61 |
maxSeq: maxSeq, |
| 62 |
windowSize: windowSize, |
| 63 |
mask: newFixedBigInt(windowSize), |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
type wrappedSlidingWindowDetector struct { |
| 68 |
latestSeq uint64 |
| 69 |
maxSeq uint64 |
| 70 |
windowSize uint |
| 71 |
mask *fixedBigInt |
| 72 |
init bool |
| 73 |
} |
| 74 |
|
| 75 |
func (d *wrappedSlidingWindowDetector) Check(seq uint64) (accept func(), ok bool) { |
| 76 |
if seq > d.maxSeq { |
| 77 |
|
| 78 |
return func() {}, false |
| 79 |
} |
| 80 |
if !d.init { |
| 81 |
if seq != 0 { |
| 82 |
d.latestSeq = seq - 1 |
| 83 |
} else { |
| 84 |
d.latestSeq = d.maxSeq |
| 85 |
} |
| 86 |
d.init = true |
| 87 |
} |
| 88 |
|
| 89 |
diff := int64(d.latestSeq) - int64(seq) |
| 90 |
|
| 91 |
if diff > int64(d.maxSeq)/2 { |
| 92 |
diff -= int64(d.maxSeq + 1) |
| 93 |
} else if diff <= -int64(d.maxSeq)/2 { |
| 94 |
diff += int64(d.maxSeq + 1) |
| 95 |
} |
| 96 |
|
| 97 |
if diff >= int64(d.windowSize) { |
| 98 |
|
| 99 |
return func() {}, false |
| 100 |
} |
| 101 |
if diff >= 0 { |
| 102 |
if d.mask.Bit(uint(diff)) != 0 { |
| 103 |
|
| 104 |
return func() {}, false |
| 105 |
} |
| 106 |
} |
| 107 |
|
| 108 |
return func() { |
| 109 |
if diff < 0 { |
| 110 |
|
| 111 |
d.mask.Lsh(uint(-diff)) |
| 112 |
d.latestSeq = seq |
| 113 |
} |
| 114 |
d.mask.SetBit(uint(d.latestSeq - seq)) |
| 115 |
}, true |
| 116 |
} |