From 6b9fdecfb17d77e6deec475301af610c790ad7cd Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Fri, 20 Apr 2018 13:43:06 +0200 Subject: [PATCH] [lib.wtime] TimeID management .GuessId() + renamed 'getID' to 'GenerateID' + unit tests for guessing protocol --- src/git.xdrm.io/schastsp/lib/wtime/wtime.go | 28 ++++++++++++++++--- .../schastsp/lib/wtime/wtime_test.go | 23 +++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 src/git.xdrm.io/schastsp/lib/wtime/wtime_test.go diff --git a/src/git.xdrm.io/schastsp/lib/wtime/wtime.go b/src/git.xdrm.io/schastsp/lib/wtime/wtime.go index 3dec14d..cbbf53e 100644 --- a/src/git.xdrm.io/schastsp/lib/wtime/wtime.go +++ b/src/git.xdrm.io/schastsp/lib/wtime/wtime.go @@ -1,6 +1,7 @@ package wtime import ( + "math" "time" ) @@ -14,10 +15,10 @@ type TimeID struct { ID uint; Parity uint } /* (1) Generates the current time id * -* @wsize Window Size in seconds +* @wsize Window Size in seconds * ---------------------------------------------------------*/ -func GetID(wsize uint) *TimeID{ +func GenerateID(wsize float64) *TimeID{ /* (0) Initialise instance */ instance := new(TimeID); @@ -26,13 +27,32 @@ func GetID(wsize uint) *TimeID{ if wsize == 0 { return instance } /* (2) Get current timestamp */ - timestamp := uint( time.Now().Unix() ); + timestamp := float64( time.Now().Unix() ); /* (3) Calculate the time id */ - instance.ID = timestamp / wsize; + instance.ID = uint( timestamp / wsize ); /* (4) Calculate parity */ instance.Parity = instance.ID % 2; return instance; +} + + +/* (2) Try to guess the received ID from current time and received parity +* +* @wsize Window Size in seconds +* @parity Received parity +* +* @return id The guessed time id +* +---------------------------------------------------------*/ +func GuessID(wsize float64, parity uint) uint{ + + /* (1) Get current time id */ + var tidNow *TimeID = GenerateID(wsize); + + /* (2) Update ID with tidNow parity difference */ + return tidNow.ID - uint(math.Abs( float64(tidNow.Parity) - float64(parity) )); + } \ No newline at end of file diff --git a/src/git.xdrm.io/schastsp/lib/wtime/wtime_test.go b/src/git.xdrm.io/schastsp/lib/wtime/wtime_test.go new file mode 100644 index 0000000..d7f9365 --- /dev/null +++ b/src/git.xdrm.io/schastsp/lib/wtime/wtime_test.go @@ -0,0 +1,23 @@ +package wtime + +import ( + "time" + "testing" +) + + +func TestGuessing(t *testing.T){ + + var windowSize float64 = .5; + + var tid *TimeID = GenerateID(windowSize); + + time.Sleep( time.Duration(windowSize) * time.Second); + + var guessedId uint = GuessID(windowSize, tid.Parity); + + if tid.ID != guessedId { + t.Errorf("Wrong guessed id, expected '%d' ; got '%d'", tid.ID, guessedId); + } + +} \ No newline at end of file