[lib.wtime] TimeID management .GuessId() + renamed 'getID' to 'GenerateID' + unit tests for guessing protocol

This commit is contained in:
xdrm-brackets 2018-04-20 13:43:06 +02:00
parent 777137eb6e
commit 6b9fdecfb1
2 changed files with 47 additions and 4 deletions

View File

@ -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<uint> Window Size in seconds
* @wsize<float64> 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<float64> Window Size in seconds
* @parity<uint> Received parity
*
* @return id<uint> 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) ));
}

View File

@ -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);
}
}