diff --git a/storage/reception/IdentityUse.go b/storage/reception/IdentityUse.go index 1507d9321ccacc4ead7cc94931401dda84b55d1b..1fb7066b65d4c731cf8c0dd4beb450be29c3dccf 100644 --- a/storage/reception/IdentityUse.go +++ b/storage/reception/IdentityUse.go @@ -11,48 +11,45 @@ import ( "time" ) -type IdentityUse struct{ +type IdentityUse struct { Identity - //randomly generated time to poll between - StartRequest time.Time //timestamp to request the start of bloom filters - EndRequest time.Time //timestamp to request the End of bloom filters + // Randomly generated time to poll between + StartRequest time.Time // Timestamp to request the start of bloom filters + EndRequest time.Time // Timestamp to request the End of bloom filters - // denotes if the identity is fake, in which case we do not process - // messages + // Denotes if the identity is fake, in which case we do not process messages Fake bool - //rounds data + // rounds data KR KnownRounds } // setSamplingPeriod add the Request mask as a random buffer around the sampling -// time to obfuscate it -func (iu IdentityUse)setSamplingPeriod(rng io.Reader)(IdentityUse, error){ - - //generate the seed - seed := make([]byte,32) - if _, err := rng.Read(seed);err!=nil{ - return IdentityUse{}, errors.WithMessage(err, "Failed to " + - "choose id due to rng failure") +// time to obfuscate it. +func (iu IdentityUse) setSamplingPeriod(rng io.Reader) (IdentityUse, error) { + + // Generate the seed + seed := make([]byte, 32) + if _, err := rng.Read(seed); err != nil { + return IdentityUse{}, errors.WithMessage(err, "Failed to "+ + "choose ID due to rng failure") } h, err := hash.NewCMixHash() - if err!=nil{ + if err != nil { return IdentityUse{}, err } - //calculate the period offset - periodOffset := - randomness.RandInInterval(big.NewInt(iu.RequestMask.Nanoseconds()), - seed,h).Int64() + // Calculate the period offset + periodOffset := randomness.RandInInterval( + big.NewInt(iu.RequestMask.Nanoseconds()), seed, h).Int64() iu.StartRequest = iu.StartValid.Add(-time.Duration(periodOffset)) - iu.EndRequest = iu.EndValid.Add(iu.RequestMask - - time.Duration(periodOffset)) + iu.EndRequest = iu.EndValid.Add(iu.RequestMask - time.Duration(periodOffset)) return iu, nil } -type KnownRounds interface{ +type KnownRounds interface { Checked(rid id.Round) bool Check(rid id.Round) Forward(rid id.Round) @@ -61,4 +58,4 @@ type KnownRounds interface{ roundCheck knownRounds.RoundCheckFunc, maxChecked int) RangeUncheckedMaskedRange(mask *knownRounds.KnownRounds, roundCheck knownRounds.RoundCheckFunc, start, end id.Round, maxChecked int) -} \ No newline at end of file +} diff --git a/storage/reception/fake.go b/storage/reception/fake.go index 17c0b1a319de4ff997d3a55dd34e291c21019633..b0e4ade9c68d652dc1a336d9dccac56d7370dfb1 100644 --- a/storage/reception/fake.go +++ b/storage/reception/fake.go @@ -10,11 +10,11 @@ import ( // generateFakeIdentity generates a fake identity of the given size with the // given random number generator -func generateFakeIdentity(rng io.Reader, idSize uint, now time.Time)(IdentityUse, error){ - //randomly generate an identity +func generateFakeIdentity(rng io.Reader, idSize uint, now time.Time) (IdentityUse, error) { + // Randomly generate an identity randIDbytes := make([]byte, id.ArrIDLen-1) - if _, err := rng.Read(randIDbytes); err!=nil{ - return IdentityUse{}, errors.WithMessage(err, "failed to " + + if _, err := rng.Read(randIDbytes); err != nil { + return IdentityUse{}, errors.WithMessage(err, "failed to "+ "generate a random identity when none is available") } @@ -22,17 +22,17 @@ func generateFakeIdentity(rng io.Reader, idSize uint, now time.Time)(IdentityUse copy(randID[:id.ArrIDLen-1], randIDbytes) randID.SetType(id.User) - //generate the current ephemeral ID from the random identity + // Generate the current ephemeral ID from the random identity ephID, start, end, err := ephemeral.GetId(randID, idSize, now.UnixNano()) - if err!=nil{ - return IdentityUse{}, errors.WithMessage(err, "failed to " + - "generate an ephemral ID for random identity when none is " + + if err != nil { + return IdentityUse{}, errors.WithMessage(err, "failed to "+ + "generate an ephemeral ID for random identity when none is "+ "available") } return IdentityUse{ - Identity: Identity{ + Identity: Identity{ EphId: ephID, Source: randID, End: end, @@ -42,6 +42,6 @@ func generateFakeIdentity(rng io.Reader, idSize uint, now time.Time)(IdentityUse RequestMask: 24 * time.Hour, Ephemeral: true, }, - Fake: true, + Fake: true, }, nil } diff --git a/storage/reception/fake_test.go b/storage/reception/fake_test.go index f8b3ceb779c146d987faacaa35a66aadaf74a2b8..f33daa20f84a25516b84d5eeb396b921654c038c 100644 --- a/storage/reception/fake_test.go +++ b/storage/reception/fake_test.go @@ -7,7 +7,7 @@ import ( "time" ) -//tests Generate Fake identity is consistant and returns a correct result +// Tests Generate Fake identity is consistent and returns a correct result. func TestGenerateFakeIdentity(t *testing.T) { rng := rand.New(rand.NewSource(42)) diff --git a/storage/reception/identity.go b/storage/reception/identity.go index 7a32ca96d68edcc80145a8963ce4357378a497c8..e64c0dd33c172a5bc4a854c8f6379670d08316f1 100644 --- a/storage/reception/identity.go +++ b/storage/reception/identity.go @@ -14,23 +14,22 @@ const identityStorageKey = "IdentityStorage" const identityStorageVersion = 0 type Identity struct { - //identity + // Identity EphId ephemeral.Id Source *id.ID - //usage variables - End time.Time // timestamp when active polling will stop - ExtraChecks uint // number of extra checks executed as active - // after the id exits active + // Usage variables + End time.Time // Timestamp when active polling will stop + ExtraChecks uint // Number of extra checks executed as active after the + // ID exits active - //polling parameters - StartValid time.Time // timestamp when the ephID begins being valid - EndValid time.Time // timestamp when the ephID stops being valid - RequestMask time.Duration // amount of extra time requested for the poll - // in order to mask the exact valid time for - // the id + // Polling parameters + StartValid time.Time // Timestamp when the ephID begins being valid + EndValid time.Time // Timestamp when the ephID stops being valid + RequestMask time.Duration // Amount of extra time requested for the poll in + // order to mask the exact valid time for the ID - //makes the identity not store on disk + // Makes the identity not store on disk Ephemeral bool } @@ -49,7 +48,7 @@ func loadIdentity(kv *versioned.KV) (Identity, error) { } func (i Identity) store(kv *versioned.KV) error { - //marshal the registration + // Marshal the registration regStr, err := json.Marshal(&i) if err != nil { return errors.WithMessage(err, "Failed to marshal Identity") @@ -62,7 +61,7 @@ func (i Identity) store(kv *versioned.KV) error { Data: regStr, } - //store the data + // Store the data err = kv.Set(identityStorageKey, obj) if err != nil { return errors.WithMessage(err, "Failed to store Identity") @@ -92,5 +91,4 @@ func (i Identity) Equal(b Identity) bool { i.EndValid.Equal(b.EndValid) && i.RequestMask == b.RequestMask && i.Ephemeral == b.Ephemeral - } diff --git a/storage/reception/identityUse_test.go b/storage/reception/identityUse_test.go index 3c14746f3b9e3a16b4c93b96d332507197884bd6..e54d73e723a4daa8365f34e446c60916a43ca3dd 100644 --- a/storage/reception/identityUse_test.go +++ b/storage/reception/identityUse_test.go @@ -11,51 +11,50 @@ func TestIdentityUse_SetSamplingPeriod(t *testing.T) { const numTests = 1000 - for i:=0;i<numTests;i++{ - //generate an identity use + for i := 0; i < numTests; i++ { + // Generate an identity use start := randate() - end := start.Add(time.Duration(rand.Uint64()%uint64(92*time.Hour))) - mask := time.Duration(rand.Uint64()%uint64(92*time.Hour)) + end := start.Add(time.Duration(rand.Uint64() % uint64(92*time.Hour))) + mask := time.Duration(rand.Uint64() % uint64(92*time.Hour)) iu := IdentityUse{ - Identity: Identity{ + Identity: Identity{ StartValid: start, EndValid: end, RequestMask: mask, }, } - //generate the sampling period + // Generate the sampling period var err error iu, err = iu.setSamplingPeriod(rng) - if err!=nil{ - t.Errorf("Errored in generatign sampling " + + if err != nil { + t.Errorf("Errored in generatign sampling "+ "period on interation %v: %+v", i, err) } - //test that the range between the periods is correct + // Test that the range between the periods is correct resultRange := iu.EndRequest.Sub(iu.StartRequest) expectedRange := iu.EndValid.Sub(iu.StartValid) + iu.RequestMask if resultRange != expectedRange { - t.Errorf("The generated sampling period is of the wrong " + + t.Errorf("The generated sampling period is of the wrong "+ "size: Expecterd: %s, Received: %s", expectedRange, resultRange) } - //test the sampling range does not exceed a reasonable lower bound + // Test the sampling range does not exceed a reasonable lower bound lowerBound := iu.StartValid.Add(-iu.RequestMask) - if !iu.StartRequest.After(lowerBound){ - t.Errorf("Start request exceeds the reasonable lower " + + if !iu.StartRequest.After(lowerBound) { + t.Errorf("Start request exceeds the reasonable lower "+ "bound: \n\t Bound: %s\n\t Start: %s", lowerBound, iu.StartValid) } - //test the sampling range does not exceed a reasonable upper bound - upperBound := iu.EndValid.Add(iu.RequestMask-time.Millisecond) - if iu.EndRequest.After(upperBound){ + // Test the sampling range does not exceed a reasonable upper bound + upperBound := iu.EndValid.Add(iu.RequestMask - time.Millisecond) + if iu.EndRequest.After(upperBound) { t.Errorf("End request exceeds the reasonable upper bound") } } - } func randate() time.Time { @@ -65,4 +64,4 @@ func randate() time.Time { sec := rand.Int63n(delta) + min return time.Unix(sec, 0) -} \ No newline at end of file +} diff --git a/storage/reception/identity_test.go b/storage/reception/identity_test.go index 96c6dea4ebee402394bb65139bdeff98e02e33f1..2f61eb3cbc055b7062a527569fadd8240dcbde16 100644 --- a/storage/reception/identity_test.go +++ b/storage/reception/identity_test.go @@ -90,12 +90,12 @@ func TestIdentity_CalculateKrSize(t *testing.T) { for _, d := range deltas { expected := int(d.Seconds()+1) * maxRoundsPerSecond now := time.Now() - id := Identity{ + i := Identity{ StartValid: now, EndValid: now.Add(d), } - krSize := id.calculateKrSize() + krSize := i.calculateKrSize() if krSize != expected { t.Errorf("kr size not correct! expected: %v, recieved: %v", expected, krSize) diff --git a/storage/reception/registration.go b/storage/reception/registration.go index 814294d94f3aa0c6c976312ca2bf1a45a2d7c0f7..f87d7303edb692223fe7853dd3b43ae2e2b97a94 100644 --- a/storage/reception/registration.go +++ b/storage/reception/registration.go @@ -9,54 +9,52 @@ import ( "gitlab.com/xx_network/primitives/id/ephemeral" "strconv" "time" - ) const maxRoundsPerSecond = 100 const knownRoundsStorageKey = "krStorage" - -type registration struct{ +type registration struct { Identity - knownRounds *knownRounds.KnownRounds + knownRounds *knownRounds.KnownRounds knownRoundsStorage *utility.KnownRounds - kv *versioned.KV + kv *versioned.KV } -func newRegistration(reg Identity, kv *versioned.KV)(*registration, error){ - //round the times to remove the monotic clocks for future saving +func newRegistration(reg Identity, kv *versioned.KV) (*registration, error) { + // Round the times to remove the monotonic clocks for future saving reg.StartValid = reg.StartValid.Round(0) reg.EndValid = reg.EndValid.Round(0) reg.End = reg.End.Round(0) now := time.Now() - //do edge checks to determine if the identity is valid - if now.After(reg.End) && reg.ExtraChecks<1{ + // Do edge checks to determine if the identity is valid + if now.After(reg.End) && reg.ExtraChecks < 1 { return nil, errors.New("Cannot create a registration for an " + "identity which has expired") } - //set the prefix + // Set the prefix kv = kv.Prefix(regPrefix(reg.EphId, reg.Source, reg.StartValid)) - r := ®istration{ Identity: reg, knownRounds: knownRounds.NewKnownRound(reg.calculateKrSize()), kv: kv, } - //if this isn't ephemeral, store everything - if !reg.Ephemeral{ - //store known rounds + // If this is not ephemeral, then store everything + if !reg.Ephemeral { + // Store known rounds var err error r.knownRoundsStorage, err = utility.NewKnownRounds(kv, knownRoundsStorageKey, r.knownRounds) - if err!=nil{ + if err != nil { return nil, errors.WithMessage(err, "failed to store known rounds") } - //store the registration - if err = reg.store(kv); err!=nil{ + + // Store the registration + if err = reg.store(kv); err != nil { return nil, errors.WithMessage(err, "failed to store registration") } } @@ -64,55 +62,57 @@ func newRegistration(reg Identity, kv *versioned.KV)(*registration, error){ return r, nil } -func loadRegistration(EphId ephemeral.Id, Source *id.ID, startvalid time.Time, kv *versioned.KV)(*registration, error){ - kv = kv.Prefix(regPrefix(EphId, Source, startvalid)) +func loadRegistration(EphId ephemeral.Id, Source *id.ID, startValid time.Time, + kv *versioned.KV) (*registration, error) { + + kv = kv.Prefix(regPrefix(EphId, Source, startValid)) reg, err := loadIdentity(kv) - if err!=nil{ - return nil, errors.WithMessagef(err, "Failed to load identity " + - "for %s", regPrefix(EphId, Source, startvalid)) + if err != nil { + return nil, errors.WithMessagef(err, "Failed to load identity "+ + "for %s", regPrefix(EphId, Source, startValid)) } - kr, err := utility.LoadKnownRounds(kv,knownRoundsStorageKey, reg.calculateKrSize()) - if err!=nil{ - return nil, errors.WithMessagef(err, "Failed to load known " + - "rounds for %s", regPrefix(EphId, Source, startvalid)) + kr, err := utility.LoadKnownRounds(kv, knownRoundsStorageKey, reg.calculateKrSize()) + if err != nil { + return nil, errors.WithMessagef(err, "Failed to load known "+ + "rounds for %s", regPrefix(EphId, Source, startValid)) } r := ®istration{ - Identity: reg, + Identity: reg, knownRoundsStorage: kr, - kv: kv, + kv: kv, } return r, nil } - -func (r *registration)Delete()error{ - if !r.Ephemeral{ - if err:=r.knownRoundsStorage.Delete(); err!=nil{ - return errors.WithMessagef(err, "Failed to delete " + +func (r *registration) Delete() error { + if !r.Ephemeral { + if err := r.knownRoundsStorage.Delete(); err != nil { + return errors.WithMessagef(err, "Failed to delete "+ "registration known rounds %s", r) } - if err:=r.delete(r.kv); err!=nil{ - return errors.WithMessagef(err, "Failed to delete " + + if err := r.delete(r.kv); err != nil { + return errors.WithMessagef(err, "Failed to delete "+ "registration public data %s", r) } } + return nil } -func (r registration)getKR()KnownRounds{ - if r.Ephemeral{ +func (r registration) getKR() KnownRounds { + if r.Ephemeral { return r.knownRounds - }else{ + } else { return r.knownRoundsStorage } } -func regPrefix(EphId ephemeral.Id, Source *id.ID, startTime time.Time)string{ +func regPrefix(EphId ephemeral.Id, Source *id.ID, startTime time.Time) string { return "receptionRegistration_" + strconv.FormatInt(EphId.Int64(), 16) + Source.String() + strconv.FormatInt(startTime.Round(0).UnixNano(), 10) -} \ No newline at end of file +} diff --git a/storage/reception/registration_test.go b/storage/reception/registration_test.go index d57c5ff005567fb2f7a734b43bad2a7f6bbd0c18..d9c1b0bd79df90f3fd15d37964704bf80a80c086 100644 --- a/storage/reception/registration_test.go +++ b/storage/reception/registration_test.go @@ -11,10 +11,10 @@ import ( ) func TestNewRegistration_Failed(t *testing.T) { - //generate an identity for use + // Generate an identity for use rng := rand.New(rand.NewSource(42)) - timestamp := time.Date(2009, 11, 17, 20, + timestamp := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) idu, _ := generateFakeIdentity(rng, 15, timestamp) @@ -26,16 +26,16 @@ func TestNewRegistration_Failed(t *testing.T) { id.ExtraChecks = 0 _, err := newRegistration(id, kv) - if err==nil || !strings.Contains(err.Error(), "Cannot create a registration for an identity which has expired"){ + if err == nil || !strings.Contains(err.Error(), "Cannot create a registration for an identity which has expired") { t.Errorf("Registeration creation succeded with expired identity") } } func TestNewRegistration_Ephemeral(t *testing.T) { - //generate an identity for use + // Generate an identity for use rng := rand.New(rand.NewSource(42)) - timestamp := time.Date(2009, 11, 17, 20, + timestamp := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) idu, _ := generateFakeIdentity(rng, 15, timestamp) @@ -43,43 +43,42 @@ func TestNewRegistration_Ephemeral(t *testing.T) { kv := versioned.NewKV(make(ekv.Memstore)) - id.End = time.Now().Add(1*time.Hour) + id.End = time.Now().Add(1 * time.Hour) id.ExtraChecks = 2 id.Ephemeral = true reg, err := newRegistration(id, kv) - if err!=nil{ - t.Errorf("Registeration creation failed when it should have " + + if err != nil { + t.Errorf("Registeration creation failed when it should have "+ "succeded: %+v", err) t.FailNow() } - if reg.knownRounds == nil{ + if reg.knownRounds == nil { t.Errorf("Ephemenral identity does not have a known rounds") } - if reg.knownRoundsStorage!=nil{ + if reg.knownRoundsStorage != nil { t.Errorf("Ephemenral identity has a known rounds storage") } - //check if the known rounds is stored, it should not be - if _, err = utility.LoadKnownRounds(reg.kv,knownRoundsStorageKey,id.calculateKrSize()); err==nil{ + // Check if the known rounds is stored, it should not be + if _, err = utility.LoadKnownRounds(reg.kv, knownRoundsStorageKey, id.calculateKrSize()); err == nil { t.Errorf("Ephemeral identity stored the known rounds when it " + "shouldnt") } - - if _, err = reg.kv.Get(identityStorageKey); err==nil{ + if _, err = reg.kv.Get(identityStorageKey); err == nil { t.Errorf("Ephemeral identity stored the idenity when it " + "shouldnt") } } func TestNewRegistration_Persistent(t *testing.T) { - //generate an identity for use + // Generate an identity for use rng := rand.New(rand.NewSource(42)) - timestamp := time.Date(2009, 11, 17, 20, + timestamp := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) idu, _ := generateFakeIdentity(rng, 15, timestamp) @@ -87,42 +86,42 @@ func TestNewRegistration_Persistent(t *testing.T) { kv := versioned.NewKV(make(ekv.Memstore)) - id.End = time.Now().Add(1*time.Hour) + id.End = time.Now().Add(1 * time.Hour) id.ExtraChecks = 2 id.Ephemeral = false reg, err := newRegistration(id, kv) - if err!=nil{ - t.Errorf("Registeration creation failed when it should have " + + if err != nil { + t.Errorf("Registeration creation failed when it should have "+ "succeded: %+v", err) t.FailNow() } - if reg.knownRounds == nil{ + if reg.knownRounds == nil { t.Errorf("Persistent identity does not have a known rounds") } - if reg.knownRoundsStorage==nil{ + if reg.knownRoundsStorage == nil { t.Errorf("Persistent identity does not have a known rounds storage") } - //check if the known rounds is stored, it should not be - if _, err = utility.LoadKnownRounds(reg.kv,knownRoundsStorageKey,id.calculateKrSize()); err!=nil{ - t.Errorf("Persistent identity did not store known rounds when " + + // Check if the known rounds is stored, it should not be + if _, err = utility.LoadKnownRounds(reg.kv, knownRoundsStorageKey, id.calculateKrSize()); err != nil { + t.Errorf("Persistent identity did not store known rounds when "+ "it should: %+v", err) } - if _, err = reg.kv.Get(identityStorageKey); err!=nil{ + if _, err = reg.kv.Get(identityStorageKey); err != nil { t.Errorf("Persistent identity did not store the idenity when " + "it should") } } func TestLoadRegistration(t *testing.T) { - //generate an identity for use + // Generate an identity for use rng := rand.New(rand.NewSource(42)) - timestamp := time.Date(2009, 11, 17, 20, + timestamp := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) idu, _ := generateFakeIdentity(rng, 15, timestamp) @@ -130,28 +129,28 @@ func TestLoadRegistration(t *testing.T) { kv := versioned.NewKV(make(ekv.Memstore)) - id.End = time.Now().Add(1*time.Hour) + id.End = time.Now().Add(1 * time.Hour) id.ExtraChecks = 2 id.Ephemeral = false _, err := newRegistration(id, kv) - if err!=nil{ - t.Errorf("Registeration creation failed when it should have " + + if err != nil { + t.Errorf("Registeration creation failed when it should have "+ "succeded: %+v", err) t.FailNow() } reg, err := loadRegistration(idu.EphId, idu.Source, idu.StartValid, kv) - if err!=nil{ + if err != nil { t.Errorf("Registeration loading failed: %+v", err) t.FailNow() } - if reg.knownRounds != nil{ + if reg.knownRounds != nil { t.Errorf("Loading has a seperated known rounds, it shouldnt") } - if reg.knownRoundsStorage==nil{ + if reg.knownRoundsStorage == nil { t.Errorf("Loading identity does not have a known rounds storage") } -} \ No newline at end of file +} diff --git a/storage/reception/store.go b/storage/reception/store.go index d154d9139104144dfe70c8f7426bcb5cbe069b6e..29dc7409f6a682b639e207dc985e95d9d0621557 100644 --- a/storage/reception/store.go +++ b/storage/reception/store.go @@ -24,10 +24,10 @@ const receptionIDSizeStorageKey = "receptionIDSizeKey" const receptionIDSizeStorageVersion = 0 const defaultIDSize = 12 -type Store struct{ - // identities which are being actively checked - active []*registration - idSize int +type Store struct { + // Identities which are being actively checked + active []*registration + idSize int kv *versioned.KV @@ -35,13 +35,13 @@ type Store struct{ } type storedReference struct { - Eph ephemeral.Id - Source *id.ID + Eph ephemeral.Id + Source *id.ID StartValid time.Time } -//creates a new reception store. It starts empty -func NewStore(kv *versioned.KV)*Store{ +// NewStore creates a new reception store that starts empty. +func NewStore(kv *versioned.KV) *Store { kv = kv.Prefix(receptionPrefix) s := &Store{ active: make([]*registration, 0), @@ -49,21 +49,21 @@ func NewStore(kv *versioned.KV)*Store{ kv: kv, } - //store the empty list - if err := s.save(); err!=nil{ + // Store the empty list + if err := s.save(); err != nil { jww.FATAL.Panicf("Failed to save new reception store: %+v", err) } - //update the size so queries can be made + // Update the size so queries can be made s.UpdateIDSize(defaultIDSize) return s } -func LoadStore(kv *versioned.KV)*Store{ +func LoadStore(kv *versioned.KV) *Store { kv = kv.Prefix(receptionPrefix) s := &Store{ - kv: kv, + kv: kv, } // Load the versioned object for the reception list @@ -75,43 +75,43 @@ func LoadStore(kv *versioned.KV)*Store{ identities := make([]storedReference, len(s.active)) err = json.Unmarshal(vo.Data, &identities) - if err!=nil{ - jww.FATAL.Panicf("Failed to unmarshal the reception storage " + + if err != nil { + jww.FATAL.Panicf("Failed to unmarshal the reception storage "+ "list: %+v", err) } s.active = make([]*registration, len(identities)) - for i, sr := range identities{ + for i, sr := range identities { s.active[i], err = loadRegistration(sr.Eph, sr.Source, sr.StartValid, s.kv) - if err!=nil{ + if err != nil { jww.FATAL.Panicf("Failed to load registration for %s: %+v", regPrefix(sr.Eph, sr.Source, sr.StartValid), err) } } - //load the ephmemeral ID length + // Load the ephemeral ID length vo, err = kv.Get(receptionIDSizeStorageKey) if err != nil { - jww.FATAL.Panicf("Failed to get the reception id size: %+v", + jww.FATAL.Panicf("Failed to get the reception ID size: %+v", err) } - if s.idSize, err = strconv.Atoi(string(vo.Data)); err!=nil{ - jww.FATAL.Panicf("Failed to unmarshal the reception id size: %+v", + if s.idSize, err = strconv.Atoi(string(vo.Data)); err != nil { + jww.FATAL.Panicf("Failed to unmarshal the reception ID size: %+v", err) } return s } -func (s *Store) save()error{ +func (s *Store) save() error { identities := make([]storedReference, len(s.active)) i := 0 - for _, reg := range s.active{ - if !reg.Ephemeral{ + for _, reg := range s.active { + if !reg.Ephemeral { identities[i] = storedReference{ - Eph: reg.EphId, - Source: reg.Source, + Eph: reg.EphId, + Source: reg.Source, StartValid: reg.StartValid.Round(0), } i++ @@ -120,8 +120,8 @@ func (s *Store) save()error{ identities = identities[:i] data, err := json.Marshal(&identities) - if err!=nil{ - return errors.WithMessage(err, "failed to store reception " + + if err != nil { + return errors.WithMessage(err, "failed to store reception "+ "store") } @@ -133,64 +133,64 @@ func (s *Store) save()error{ } err = s.kv.Set(receptionStoreStorageKey, obj) - if err!=nil{ + if err != nil { return errors.WithMessage(err, "Failed to store reception store") } return nil } -func (s *Store)GetIdentity(rng io.Reader)(IdentityUse, error){ +func (s *Store) GetIdentity(rng io.Reader) (IdentityUse, error) { s.mux.Lock() defer s.mux.Unlock() now := time.Now() - //remove any now expired identities + // Remove any now expired identities s.prune(now) var identity IdentityUse var err error - // if the list is empty, we return a randomly generated identity to poll - // with so we can continue tracking the network and to further obfuscate - // network identities - if len(s.active)==0{ + // If the list is empty, then we return a randomly generated identity to + // poll with so we can continue tracking the network and to further + // obfuscate network identities. + if len(s.active) == 0 { identity, err = generateFakeIdentity(rng, uint(s.idSize), now) - if err!=nil{ - jww.FATAL.Panicf("Failed to generate a new ID when none " + + if err != nil { + jww.FATAL.Panicf("Failed to generate a new ID when none "+ "available: %+v", err) } - }else{ + } else { identity, err = s.selectIdentity(rng, now) - if err!=nil{ - jww.FATAL.Panicf("Failed to select an id: %+v", err) + if err != nil { + jww.FATAL.Panicf("Failed to select an ID: %+v", err) } } - //calculate the sampling period + // Calculate the sampling period identity, err = identity.setSamplingPeriod(rng) - if err!=nil{ - jww.FATAL.Panicf("Failed to caluclate the sampling period: " + + if err != nil { + jww.FATAL.Panicf("Failed to calculate the sampling period: "+ "%+v", err) } return identity, nil } -func (s *Store)AddIdentity(identity Identity)error { +func (s *Store) AddIdentity(identity Identity) error { s.mux.Lock() defer s.mux.Unlock() reg, err := newRegistration(identity, s.kv) - if err!=nil{ - return errors.WithMessage(err,"failed to add new identity to " + + if err != nil { + return errors.WithMessage(err, "failed to add new identity to "+ "reception store") } s.active = append(s.active, reg) - if !identity.Ephemeral{ - if err := s.save(); err!=nil{ + if !identity.Ephemeral { + if err := s.save(); err != nil { jww.FATAL.Panicf("Failed to save reception store after identity " + "addition") } @@ -199,20 +199,20 @@ func (s *Store)AddIdentity(identity Identity)error { return nil } -func (s *Store)RemoveIdentity(ephID ephemeral.Id) { +func (s *Store) RemoveIdentity(ephID ephemeral.Id) { s.mux.Lock() defer s.mux.Unlock() - for i:=0;i<len(s.active);i++{ + for i := 0; i < len(s.active); i++ { inQuestion := s.active[i] - if bytes.Equal(inQuestion.EphId[:],ephID[:]){ + if bytes.Equal(inQuestion.EphId[:], ephID[:]) { s.active = append(s.active[:i], s.active[i+1:]...) err := inQuestion.Delete() - if err!=nil{ + if err != nil { jww.FATAL.Panicf("Failed to delete identity: %+v", err) } - if !inQuestion.Ephemeral{ - if err := s.save(); err!=nil{ + if !inQuestion.Ephemeral { + if err := s.save(); err != nil { jww.FATAL.Panicf("Failed to save reception store after " + "identity removal") } @@ -222,32 +222,33 @@ func (s *Store)RemoveIdentity(ephID ephemeral.Id) { } } -func (s *Store)UpdateIDSize(idSize uint){ +func (s *Store) UpdateIDSize(idSize uint) { s.mux.Lock() defer s.mux.Unlock() s.idSize = int(idSize) - //store the id size + + // Store the ID size obj := &versioned.Object{ Version: receptionIDSizeStorageVersion, Timestamp: time.Now(), - Data: []byte(strconv.Itoa(s.idSize)), + Data: []byte(strconv.Itoa(s.idSize)), } err := s.kv.Set(receptionIDSizeStorageKey, obj) - if err!=nil{ + if err != nil { jww.FATAL.Panicf("Failed to store reception ID size: %+v", err) } } -func (s *Store)prune(now time.Time) { +func (s *Store) prune(now time.Time) { lengthBefore := len(s.active) - //prune the list - for i:=0;i<len(s.active);i++{ + // Prune the list + for i := 0; i < len(s.active); i++ { inQuestion := s.active[i] - if now.After(inQuestion.End) && inQuestion.ExtraChecks ==0{ - if err := inQuestion.Delete(); err!=nil{ - jww.ERROR.Printf("Failed to delete Identity for %s: " + + if now.After(inQuestion.End) && inQuestion.ExtraChecks == 0 { + if err := inQuestion.Delete(); err != nil { + jww.ERROR.Printf("Failed to delete Identity for %s: "+ "%+v", inQuestion, err) } @@ -257,46 +258,45 @@ func (s *Store)prune(now time.Time) { } } - //save the list if it changed - if lengthBefore!=len(s.active){ - if err := s.save(); err!=nil{ + // Save the list if it changed + if lengthBefore != len(s.active) { + if err := s.save(); err != nil { jww.FATAL.Panicf("Failed to store reception storage") } } } -func (s *Store)selectIdentity(rng io.Reader, now time.Time)(IdentityUse, error) { +func (s *Store) selectIdentity(rng io.Reader, now time.Time) (IdentityUse, error) { - //choose a member from the list + // Choose a member from the list var selected *registration - if len(s.active)==1{ - selected= s.active[0] - }else{ - - seed := make([]byte,32) - if _, err := rng.Read(seed);err!=nil{ - return IdentityUse{}, errors.WithMessage(err, "Failed to " + - "choose id due to rng failure") + if len(s.active) == 1 { + selected = s.active[0] + } else { + seed := make([]byte, 32) + if _, err := rng.Read(seed); err != nil { + return IdentityUse{}, errors.WithMessage(err, "Failed to "+ + "choose ID due to rng failure") } h, err := hash.NewCMixHash() - if err==nil{ + if err == nil { return IdentityUse{}, err } selectedNum := randomness.RandInInterval( - big.NewInt(int64(len(s.active)-1)),seed,h) + big.NewInt(int64(len(s.active)-1)), seed, h) selected = s.active[selectedNum.Uint64()] } - if now.After(selected.End){ + if now.After(selected.End) { selected.ExtraChecks-- } return IdentityUse{ - Identity: selected.Identity, - Fake: false, - KR: selected.getKR(), + Identity: selected.Identity, + Fake: false, + KR: selected.getKR(), }, nil -} \ No newline at end of file +}