github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/common/antireplay/antireplay.go (about)

     1  package antireplay
     2  
     3  import (
     4  	cuckoo "github.com/seiflotfy/cuckoofilter"
     5  	"sync"
     6  	"time"
     7  )
     8  
     9  func NewAntiReplayWindow(AntiReplayTime int64) *AntiReplayWindow {
    10  	arw := &AntiReplayWindow{}
    11  	arw.AntiReplayTime = AntiReplayTime
    12  	return arw
    13  }
    14  
    15  type AntiReplayWindow struct {
    16  	lock           sync.Mutex
    17  	poolA          *cuckoo.Filter
    18  	poolB          *cuckoo.Filter
    19  	lastSwapTime   int64
    20  	PoolSwap       bool
    21  	AntiReplayTime int64
    22  }
    23  
    24  func (aw *AntiReplayWindow) Check(sum []byte) bool {
    25  	aw.lock.Lock()
    26  
    27  	if aw.lastSwapTime == 0 {
    28  		aw.lastSwapTime = time.Now().Unix()
    29  		aw.poolA = cuckoo.NewFilter(100000)
    30  		aw.poolB = cuckoo.NewFilter(100000)
    31  	}
    32  
    33  	tnow := time.Now().Unix()
    34  	timediff := tnow - aw.lastSwapTime
    35  
    36  	if timediff >= aw.AntiReplayTime {
    37  		if aw.PoolSwap {
    38  			aw.PoolSwap = false
    39  			aw.poolA.Reset()
    40  		} else {
    41  			aw.PoolSwap = true
    42  			aw.poolB.Reset()
    43  		}
    44  		aw.lastSwapTime = tnow
    45  	}
    46  
    47  	ret := aw.poolA.InsertUnique(sum) && aw.poolB.InsertUnique(sum)
    48  	aw.lock.Unlock()
    49  	return ret
    50  }