diff --git a/api/client.go b/api/client.go index bd30a8bae5abb633f64956143edf38edf20036c2..7919c62b869f1befb9a7567022bdc51475e8b4c2 100644 --- a/api/client.go +++ b/api/client.go @@ -559,12 +559,12 @@ func (c *Client) DeleteContact(partnerId *id.ID) error { jww.DEBUG.Printf("Deleting contact with ID %s", partnerId) //get the partner so they can be removed from preiamge store partner, err := c.storage.E2e().GetPartner(partnerId) - if err!=nil{ - return errors.WithMessagef(err,"Could not delete %s because " + + if err != nil { + return errors.WithMessagef(err, "Could not delete %s because "+ "they could not be found", partnerId) } e2ePreimage := partner.GetE2EPreimage() - rekeyPreimage:= partner.GetRekeyPreimage() + rekeyPreimage := partner.GetRekeyPreimage() //delete the partner if err = c.storage.E2e().DeletePartner(partnerId); err != nil { @@ -572,20 +572,20 @@ func (c *Client) DeleteContact(partnerId *id.ID) error { } //delete the preimages if err = c.storage.GetEdge().Remove(edge.Preimage{ - Data: e2ePreimage, + Data: e2ePreimage, Type: preimage.E2e, Source: partnerId[:], - }, c.storage.GetUser().ReceptionID); err!=nil{ - jww.WARN.Printf("Failed delete the preimage for e2e " + + }, c.storage.GetUser().ReceptionID); err != nil { + jww.WARN.Printf("Failed delete the preimage for e2e "+ "from %s on contact deletion: %+v", partnerId, err) } if err = c.storage.GetEdge().Remove(edge.Preimage{ - Data: rekeyPreimage, + Data: rekeyPreimage, Type: preimage.Rekey, Source: partnerId[:], - }, c.storage.GetUser().ReceptionID); err!=nil{ - jww.WARN.Printf("Failed delete the preimage for rekey " + + }, c.storage.GetUser().ReceptionID); err != nil { + jww.WARN.Printf("Failed delete the preimage for rekey "+ "from %s on contact deletion: %+v", partnerId, err) } @@ -733,7 +733,7 @@ func checkVersionAndSetupStorage(def *ndf.NetworkDefinition, storageDir string, Data: preimage.GenerateRequest(protoUser.ReceptionID), Type: preimage.Request, Source: protoUser.ReceptionID[:], - },protoUser.ReceptionID) + }, protoUser.ReceptionID) if err != nil { return errors.WithMessage(err, "Failed to denote state "+ diff --git a/auth/callback.go b/auth/callback.go index 31028bea0a2189597885cbd32d7b1d3384747890..e3d53fb47f4aa868ee23b27c757dd9d05145bb39 100644 --- a/auth/callback.go +++ b/auth/callback.go @@ -315,14 +315,13 @@ func (m *Manager) doConfirm(sr *auth.SentRequest, grp *cyclic.Group, sr.GetPartner(), err) } - //remove the confirm fingerprint - fp:= sr.GetFingerprint() + fp := sr.GetFingerprint() if err := m.storage.GetEdge().Remove(edge.Preimage{ - Data: preimage.Generate(fp[:],preimage.Confirm), + Data: preimage.Generate(fp[:], preimage.Confirm), Type: preimage.Confirm, Source: sr.GetPartner()[:], - }, m.storage.GetUser().ReceptionID); err!=nil{ + }, m.storage.GetUser().ReceptionID); err != nil { jww.WARN.Printf("Failed delete the preimage for confirm from %s: %+v", sr.GetPartner(), err) } @@ -330,7 +329,7 @@ func (m *Manager) doConfirm(sr *auth.SentRequest, grp *cyclic.Group, //add the e2e and rekey firngeprints //e2e sessionPartner, err := m.storage.E2e().GetPartner(sr.GetPartner()) - if err!=nil{ + if err != nil { jww.FATAL.Panicf("Cannot find %s right after creating: %+v", sr.GetPartner(), err) } me := m.storage.GetUser().ReceptionID diff --git a/auth/confirm.go b/auth/confirm.go index a8c622832d39caae61e5081087f3524b90d41b30..62216ed28935abe65db07f3fe6c313f3bd273b0c 100644 --- a/auth/confirm.go +++ b/auth/confirm.go @@ -89,7 +89,7 @@ func ConfirmRequestAuth(partner contact.Contact, rng io.Reader, //get the fingerprint from the old ownership proof fp := cAuth.MakeOwnershipProofFP(storedContact.OwnershipProof) - preimg := preimage.Generate(fp[:],preimage.Confirm) + preimg := preimage.Generate(fp[:], preimage.Confirm) //final construction baseFmt.SetEcrPayload(ecrPayload) @@ -119,7 +119,7 @@ func ConfirmRequestAuth(partner contact.Contact, rng io.Reader, //add the preimages sessionPartner, err := storage.E2e().GetPartner(partner.ID) - if err!=nil{ + if err != nil { jww.FATAL.Panicf("Cannot find %s right after creating: %+v", partner.ID, err) } me := storage.GetUser().ReceptionID diff --git a/auth/request.go b/auth/request.go index cbf4b36a5830243fa57122134da9727a5fd62bd4..d323eeec7de5b9d734b25a6bfccac8a327a0c10d 100644 --- a/auth/request.go +++ b/auth/request.go @@ -144,10 +144,10 @@ func RequestAuth(partner, me contact.Contact, message string, rng io.Reader, cmixMsg.SetContents(baseFmt.Marshal()) storage.GetEdge().Add(edge.Preimage{ - Data: preimage.Generate(confirmFp[:],preimage.Confirm), + Data: preimage.Generate(confirmFp[:], preimage.Confirm), Type: preimage.Confirm, Source: partner.ID[:], - },me.ID) + }, me.ID) jww.TRACE.Printf("RequestAuth SALT: %v", salt) jww.TRACE.Printf("RequestAuth ECRPAYLOAD: %v", baseFmt.GetEcrPayload()) diff --git a/auth/verify.go b/auth/verify.go index 1798e42be0781f19a1da2d9be1c9673c0d28f36d..66a86df6f125bb0abe7c28be4ecbb408603b0a98 100644 --- a/auth/verify.go +++ b/auth/verify.go @@ -18,6 +18,3 @@ func VerifyOwnership(received, verified contact.Contact, storage *storage.Sessio return cAuth.VerifyOwnershipProof(myHistoricalPrivKey, verified.DhPubKey, storage.E2e().GetGroup(), received.OwnershipProof) } - - - diff --git a/bindings/notifications.go b/bindings/notifications.go index 1741003694c41364baf1ee5f0c211241e4c8528c..2274b096a5bb6b3969419f14538707243180ad23 100644 --- a/bindings/notifications.go +++ b/bindings/notifications.go @@ -15,26 +15,24 @@ import ( "gitlab.com/elixxir/crypto/fingerprint" ) - -type NotificationForMeReport struct{ - forMe bool - tYpe string +type NotificationForMeReport struct { + forMe bool + tYpe string source []byte } -func (nfmr *NotificationForMeReport)ForMe()bool{ +func (nfmr *NotificationForMeReport) ForMe() bool { return nfmr.forMe } -func (nfmr *NotificationForMeReport)Type()string{ +func (nfmr *NotificationForMeReport) Type() string { return nfmr.tYpe } -func (nfmr *NotificationForMeReport)Source()[]byte{ +func (nfmr *NotificationForMeReport) Source() []byte { return nfmr.source } - // NotificationForMe Check if a notification received is for me func NotificationForMe(messageHash, idFP string, preimages string) (*NotificationForMeReport, error) { //handle message hash and idFP @@ -49,14 +47,14 @@ func NotificationForMe(messageHash, idFP string, preimages string) (*Notificatio //handle deserialization of preimages var preimageList []edge.Preimage - if err := json.Unmarshal([]byte(preimages),&preimageList); err!=nil{ - return nil, errors.WithMessagef(err,"Failed to unmarshal the preimages list, " + + if err := json.Unmarshal([]byte(preimages), &preimageList); err != nil { + return nil, errors.WithMessagef(err, "Failed to unmarshal the preimages list, "+ "cannot check if notification is for me") } //check if any preimages match with the passed in data for _, preimage := range preimageList { - if fingerprint.CheckIdentityFpFromMessageHash(idFpBytes, messageHashBytes, preimage.Data){ + if fingerprint.CheckIdentityFpFromMessageHash(idFpBytes, messageHashBytes, preimage.Data) { return &NotificationForMeReport{ forMe: true, tYpe: preimage.Type, diff --git a/bindings/preimage.go b/bindings/preimage.go index 0540be51be4f89efaf90d9a91a7c55b58328fc70..38c2bf715ffa8b89a6e9bf266f963e352ff25937 100644 --- a/bindings/preimage.go +++ b/bindings/preimage.go @@ -6,34 +6,33 @@ import ( "gitlab.com/xx_network/primitives/id" ) - -type PreimageNotification interface{ +type PreimageNotification interface { Notify(identity []byte, deleted bool) } -func (c *Client)RegisterPreimageCallback(identity []byte, pin PreimageNotification){ +func (c *Client) RegisterPreimageCallback(identity []byte, pin PreimageNotification) { iid := &id.ID{} copy(iid[:], identity) - cb := func(localIdentity *id.ID, deleted bool){ - pin.Notify(localIdentity[:],deleted) + cb := func(localIdentity *id.ID, deleted bool) { + pin.Notify(localIdentity[:], deleted) } c.api.GetStorage().GetEdge().AddUpdateCallback(iid, cb) } -func (c *Client)GetPreimages(identity []byte)(string, error){ +func (c *Client) GetPreimages(identity []byte) (string, error) { iid := &id.ID{} copy(iid[:], identity) list, exist := c.api.GetStorage().GetEdge().Get(iid) - if !exist{ + if !exist { return "", errors.Errorf("Could not find a preimage list for %s", iid) } marshaled, err := json.Marshal(&list) return string(marshaled), err -} \ No newline at end of file +} diff --git a/bindings/ud.go b/bindings/ud.go index 900e102d75621c76d110732fca3c4011dfd23b8b..727f4118333c2813c8acd227000deffab78ad6e3 100644 --- a/bindings/ud.go +++ b/bindings/ud.go @@ -207,12 +207,11 @@ type MultiLookupCallback interface { Callback(Succeeded *ContactList, failed *IdList, errors string) } - -type lookupResponse struct{ - C contact.Contact - err error +type lookupResponse struct { + C contact.Contact + err error index int - id *id.ID + id *id.ID } // MultiLookup Looks for the contact object associated with all given userIDs. @@ -223,12 +222,12 @@ type lookupResponse struct{ func (ud UserDiscovery) MultiLookup(ids *IdList, callback MultiLookupCallback, timeoutMS int) error { - idList := make([]*id.ID,0,ids.Len()) + idList := make([]*id.ID, 0, ids.Len()) //extract all IDs from - for i:=0;i<ids.Len();i++{ + for i := 0; i < ids.Len(); i++ { idBytes, err := ids.Get(i) - if err!=nil{ + if err != nil { return errors.WithMessagef(err, "Failed to get ID at index %d", i) } uid, err := id.Unmarshal(idBytes) @@ -245,54 +244,52 @@ func (ud UserDiscovery) MultiLookup(ids *IdList, callback MultiLookupCallback, timeout := time.Duration(timeoutMS) * time.Millisecond //loop through the IDs and send the lookup - for i := range idList{ + for i := range idList { locali := i localID := idList[locali] - cb := func(c contact.Contact, err error){ + cb := func(c contact.Contact, err error) { results <- lookupResponse{ C: c, err: err, index: locali, - id: localID, + id: localID, } } - go func(){ + go func() { err := ud.ud.Lookup(localID, cb, timeout) - if err!=nil{ + if err != nil { results <- lookupResponse{ - C: contact.Contact{}, - err: errors.WithMessagef(err, "Failed to send lookup " + + C: contact.Contact{}, + err: errors.WithMessagef(err, "Failed to send lookup "+ "for user %s[%d]", localID, locali), index: locali, - id: localID, + id: localID, } } }() } //run the result gathering in its own thread - go func(){ - returnedContactList := make([]contact.Contact,0,len(idList)) - failedIDList := make([]*id.ID,0,len(idList)) + go func() { + returnedContactList := make([]contact.Contact, 0, len(idList)) + failedIDList := make([]*id.ID, 0, len(idList)) var concatonatedErrs string //Get the responses and return - for numReturned := 0; numReturned<len(idList);numReturned++{ - response := <- results - if response.err==nil{ + for numReturned := 0; numReturned < len(idList); numReturned++ { + response := <-results + if response.err == nil { returnedContactList = append(returnedContactList, response.C) - }else{ + } else { failedIDList = append(failedIDList, response.id) - concatonatedErrs = concatonatedErrs + fmt.Sprintf("Error returned from " + + concatonatedErrs = concatonatedErrs + fmt.Sprintf("Error returned from "+ "send to %d [%d]:%+v\t", response.id, response.index, response.err) } } - callback.Callback(&ContactList{list:returnedContactList}, &IdList{list:failedIDList}, concatonatedErrs) + callback.Callback(&ContactList{list: returnedContactList}, &IdList{list: failedIDList}, concatonatedErrs) }() - return nil } - diff --git a/cmd/root.go b/cmd/root.go index 036ff66cf9fef36c45b79b114ce85a5de5774b59..23416872ee7e210fbe6b886bee12788a17d0e1bc 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -236,7 +236,7 @@ var rootCmd = &cobra.Command{ expectedCnt := viper.GetUint("receiveCount") receiveCnt := uint(0) waitSecs := viper.GetUint("waitTimeout") - waitTimeout := time.Duration(waitSecs)* time.Second + waitTimeout := time.Duration(waitSecs) * time.Second done := false for !done && expectedCnt != 0 { @@ -261,7 +261,7 @@ var rootCmd = &cobra.Command{ //wait an extra 5 seconds to make sure no messages were missed done = false - timer := time.NewTimer(5*time.Second) + timer := time.NewTimer(5 * time.Second) for !done { select { case <-timer.C: diff --git a/cmd/single.go b/cmd/single.go index 6600cbfbbf9b9358d79163c555096127609379d2..27300ef1e6adb9965cc79682890df1ad6f0f7914 100644 --- a/cmd/single.go +++ b/cmd/single.go @@ -89,7 +89,7 @@ var singleCmd = &cobra.Command{ jww.FATAL.Panicf("Could not add single use process: %+v", err) } - for numReg, total := 1, 100; numReg < total; { + for numReg, total := 1, 100; numReg < (total*3)/4; { time.Sleep(1 * time.Second) numReg, total, err = client.GetNodeRegistrationStatus() if err != nil { diff --git a/dummy/send.go b/dummy/send.go index 96e9274cf84d8f9ad65faa3aa46dbe26df8568cc..f37f79927402b86f59606d901c0f2d393ff41b05 100644 --- a/dummy/send.go +++ b/dummy/send.go @@ -74,8 +74,8 @@ func (m *Manager) sendMessages(msgs map[id.ID]format.Message) error { p := params.GetDefaultCMIX() p.IdentityPreimage = make([]byte, 32) rng := m.rng.GetStream() - if _, err := rng.Read(p.IdentityPreimage); err!=nil{ - jww.FATAL.Panicf("Failed to generate data for random " + + if _, err := rng.Read(p.IdentityPreimage); err != nil { + jww.FATAL.Panicf("Failed to generate data for random "+ "identity preimage in e2e send: %+v", err) } rng.Close() diff --git a/interfaces/preimage/generate.go b/interfaces/preimage/generate.go index a372f02c4c50fa32d72c4d1e394fef7b5d37662b..f410e087332478d09dcff8ce32c33af5a4263855 100644 --- a/interfaces/preimage/generate.go +++ b/interfaces/preimage/generate.go @@ -15,7 +15,6 @@ func Generate(data []byte, t string) []byte { return h.Sum(nil) } - func GenerateRequest(recipient *id.ID) []byte { // Hash fingerprints h, _ := blake2b.New256(nil) @@ -25,4 +24,3 @@ func GenerateRequest(recipient *id.ID) []byte { // Base 64 encode hash and truncate return h.Sum(nil) } - diff --git a/interfaces/preimage/request.go b/interfaces/preimage/request.go index 00a29f7384f4b864b14f323a319b49e184cc7934..199c10909af8f723f2605dd4b5000d2072744b73 100644 --- a/interfaces/preimage/request.go +++ b/interfaces/preimage/request.go @@ -5,7 +5,7 @@ import ( "golang.org/x/crypto/blake2b" ) -func MakeRequest(uid *id.ID)[]byte{ +func MakeRequest(uid *id.ID) []byte { h, _ := blake2b.New256(nil) h.Write(uid[:]) h.Write([]byte(Request)) @@ -14,7 +14,7 @@ func MakeRequest(uid *id.ID)[]byte{ return h.Sum(nil) } -func MakeDefault(uid *id.ID)[]byte{ +func MakeDefault(uid *id.ID) []byte { h, _ := blake2b.New256(nil) h.Write(uid[:]) h.Write([]byte(Default)) diff --git a/interfaces/preimage/types.go b/interfaces/preimage/types.go index 9688251fbbe1c4fe0240f67339b0ef75c78b8aa0..3588b4f24ca24ecdb5cc6840d35ade097b5468d8 100644 --- a/interfaces/preimage/types.go +++ b/interfaces/preimage/types.go @@ -1,14 +1,10 @@ package preimage -const( +const ( Default = "default" Request = "request" Confirm = "confirm" Rekey = "rekey" E2e = "e2e" Group = "group" - ) - - - diff --git a/network/follow.go b/network/follow.go index bdcdf5deb8d5bda9d72c587f2ceae7d20b80a0f8..9a33cd6c515685019f1f1375c5c28d6c2aa8240b 100644 --- a/network/follow.go +++ b/network/follow.go @@ -321,8 +321,8 @@ func (m *manager) follow(report interfaces.ClientErrorReport, rng csprng.Source, //threshold is the earliest round that will not be excluded from earliest remaining earliestRemaining, roundsWithMessages, roundsUnknown := gwRoundsState.RangeUnchecked(updated, m.param.KnownRoundsThreshold, roundChecker) - jww.DEBUG.Printf("Processed RangeUnchecked, Oldest: %d, firstUnchecked: %d, " + - "last Checked: %d, threshold: %d, NewEarliestRemaning: %d, NumWithMessages: %d, " + + jww.DEBUG.Printf("Processed RangeUnchecked, Oldest: %d, firstUnchecked: %d, "+ + "last Checked: %d, threshold: %d, NewEarliestRemaning: %d, NumWithMessages: %d, "+ "NumUnknown: %d", updated, gwRoundsState.GetFirstUnchecked(), gwRoundsState.GetLastChecked(), m.param.KnownRoundsThreshold, earliestRemaining, len(roundsWithMessages), len(roundsUnknown)) diff --git a/network/message/handler.go b/network/message/handler.go index 4dc26f2f29f5c44c337afa276177bd68a47459a4..5610c0570aed6785dd4f2f168e1c84c25c53a689 100644 --- a/network/message/handler.go +++ b/network/message/handler.go @@ -54,11 +54,11 @@ func (m *Manager) handleMessage(ecrMsg format.Message, bundle Bundle, edge *edge var relationshipFingerprint []byte //if it exists, check against all in the list - has, forMe, _ := m.Session.GetEdge().Check(identity.Source,fingerprint[:],ecrMsg.GetContents()) - if !has{ + has, forMe, _ := m.Session.GetEdge().Check(identity.Source, fingerprint[:], ecrMsg.GetContents()) + if !has { //if it doesnt exist, check against the default fingerprint for the identity forMe = fingerprint2.CheckIdentityFP(ecrMsg.GetIdentityFP(), - ecrMsg.GetContents(),preimage.MakeDefault(identity.Source)) + ecrMsg.GetContents(), preimage.MakeDefault(identity.Source)) } if !forMe { diff --git a/network/message/sendCmixUtils.go b/network/message/sendCmixUtils.go index 7535a66d97f8b66396e92e2c3284e5ff6488a399..6452467faf12169b771d719f75912d05f5946790 100644 --- a/network/message/sendCmixUtils.go +++ b/network/message/sendCmixUtils.go @@ -142,7 +142,7 @@ func buildSlotMessage(msg format.Message, recipient *id.ID, target *id.ID, // use the alternate identity preimage if it is set preimage := recipient[:] - if param.IdentityPreimage!=nil{ + if param.IdentityPreimage != nil { preimage = param.IdentityPreimage } diff --git a/network/message/sendE2E.go b/network/message/sendE2E.go index f0d20c0687abceb72ecdc57aa31b7c3848168dac..52d202393cc8817f2bf9ffd8acace69fb9df72eb 100644 --- a/network/message/sendE2E.go +++ b/network/message/sendE2E.go @@ -94,7 +94,7 @@ func (m *Manager) SendE2E(msg message.Send, param params.E2E, i+i, len(partitions), msg.Recipient, msgEnc.Digest(), key.Fingerprint()) //set the preimage to the default e2e one if it is not already set - if param.IdentityPreimage==nil{ + if param.IdentityPreimage == nil { param.IdentityPreimage = partner.GetE2EPreimage() } diff --git a/storage/e2e/manager.go b/storage/e2e/manager.go index b601640ea2e5774a48e1d7d7794f7adb5952b913..68119395dc81f3c3dff50dfcfdd5b5d8b6da9ea4 100644 --- a/storage/e2e/manager.go +++ b/storage/e2e/manager.go @@ -228,21 +228,6 @@ const relationshipFpLength = 15 // relationship. The fingerprint is a base 64 encoded hash of of the two // relationship fingerprints truncated to 15 characters. func (m *Manager) GetRelationshipFingerprint() string { - // Sort fingerprints - var fps [][]byte - - - if bytes.Compare(m.receive.fingerprint, m.send.fingerprint)==1{ - fps = [][]byte{m.receive.fingerprint,m.send.fingerprint} - }else{ - fps = [][]byte{m.receive.fingerprint,m.send.fingerprint} - } - - // Hash fingerprints - h, _ := blake2b.New256(nil) - for _, fp := range fps { - h.Write(fp) - } // Base 64 encode hash and truncate return base64.StdEncoding.EncodeToString(m.GetRelationshipFingerprintBytes())[:relationshipFpLength] @@ -254,11 +239,10 @@ func (m *Manager) GetRelationshipFingerprintBytes() []byte { // Sort fingerprints var fps [][]byte - - if bytes.Compare(m.receive.fingerprint, m.send.fingerprint)==1{ - fps = [][]byte{m.receive.fingerprint,m.send.fingerprint} - }else{ - fps = [][]byte{m.receive.fingerprint,m.send.fingerprint} + if bytes.Compare(m.receive.fingerprint, m.send.fingerprint) == 1 { + fps = [][]byte{m.send.fingerprint, m.receive.fingerprint} + } else { + fps = [][]byte{m.receive.fingerprint, m.send.fingerprint} } // Hash fingerprints @@ -282,4 +266,3 @@ func (m *Manager) GetE2EPreimage() []byte { func (m *Manager) GetRekeyPreimage() []byte { return preimage.Generate(m.GetRelationshipFingerprintBytes(), preimage.Rekey) } - diff --git a/storage/edge/edge.go b/storage/edge/edge.go index d1bc30bb0e5c33d5a739ba63a8cf7952753f4fe5..7e88d35eccbbe19752dccd4de63363e37e5a12f5 100644 --- a/storage/edge/edge.go +++ b/storage/edge/edge.go @@ -152,14 +152,14 @@ func (s *Store) Get(identity *id.ID) ([]Preimage, bool) { defer s.mux.RUnlock() preimages, exists := s.edge[*identity] - if !exists{ + if !exists { return nil, false } preiamgesSlice := make([]Preimage, 0, len(preimages)) - for _, preimage := range preimages{ - preiamgesSlice = append(preiamgesSlice,preimage) + for _, preimage := range preimages { + preiamgesSlice = append(preiamgesSlice, preimage) } return preiamgesSlice, exists } @@ -172,12 +172,12 @@ func (s *Store) Check(identity *id.ID, identityFP []byte, messageContents []byte defer s.mux.RUnlock() preimages, exists := s.edge[*identity] - if !exists{ + if !exists { return false, false, Preimage{} } - for _, preimage := range preimages{ - if fingerprint2.CheckIdentityFP(identityFP, messageContents, preimage.Data){ + for _, preimage := range preimages { + if fingerprint2.CheckIdentityFP(identityFP, messageContents, preimage.Data) { return true, true, preimage } } @@ -214,8 +214,8 @@ func LoadStore(kv *versioned.KV) (*Store, error) { } s := &Store{ - kv: kv, - edge: make(map[id.ID]Preimages), + kv: kv, + edge: make(map[id.ID]Preimages), callbacks: make(map[id.ID][]ListUpdateCallBack), } diff --git a/storage/edge/edge_test.go b/storage/edge/edge_test.go index a1796cf322d8498bc91e1c897ae61b88b84af1a5..e059e749666f0f30223e78e584a5af995a91092a 100644 --- a/storage/edge/edge_test.go +++ b/storage/edge/edge_test.go @@ -18,6 +18,7 @@ import ( "encoding/json" "gitlab.com/elixxir/client/interfaces/preimage" "gitlab.com/elixxir/client/storage/versioned" + fingerprint2 "gitlab.com/elixxir/crypto/fingerprint" "gitlab.com/elixxir/ekv" "gitlab.com/xx_network/primitives/id" "math/rand" @@ -148,7 +149,7 @@ func TestStore_Add(t *testing.T) { "\nexpected: %d\nreceived: %d", identities[0], 3, len(pis)) } - expected := Preimage{preimage.Generate(identities[0].Bytes(),preimage.Default), preimage.Default, identities[0].Bytes()} + expected := Preimage{preimage.Generate(identities[0].Bytes(), preimage.Default), preimage.Default, identities[0].Bytes()} if !reflect.DeepEqual(pis[expected.key()], expected) { t.Errorf("First Preimage of first Preimages does not match expected."+ "\nexpected: %+v\nreceived: %+v", expected, pis[expected.key()]) @@ -173,7 +174,7 @@ func TestStore_Add(t *testing.T) { "\nexpected: %d\nreceived: %d", identities[1], 2, len(pis)) } - expected = Preimage{preimage.Generate(identities[1].Bytes(),preimage.Default), preimage.Default, identities[1].Bytes()} + expected = Preimage{preimage.Generate(identities[1].Bytes(), preimage.Default), preimage.Default, identities[1].Bytes()} if !reflect.DeepEqual(pis[expected.key()], expected) { t.Errorf("First Preimage of second Preimages does not match expected."+ "\nexpected: %+v\nreceived: %+v", expected, pis[expected.key()]) @@ -242,8 +243,6 @@ func TestStore_Remove(t *testing.T) { } }() - - id1Chan := make(chan struct { identity *id.ID deleted bool @@ -350,20 +349,20 @@ func TestStore_Get(t *testing.T) { } expected := []Preimage{ - {preimage.Generate(identities[0].Bytes(),preimage.Default), preimage.Default, identities[0].Bytes()}, + {preimage.Generate(identities[0].Bytes(), preimage.Default), preimage.Default, identities[0].Bytes()}, preimages[0], preimages[2], } - if len(expected)!=len(pis){ + if len(expected) != len(pis) { t.Errorf("First Preimages for identity %s does not match expected, difrent lengths of %d and %d"+ - "\nexpected: %+v\nreceived: %+v", identities[0],len(expected), len(pis), expected, pis) + "\nexpected: %+v\nreceived: %+v", identities[0], len(expected), len(pis), expected, pis) } - top: - for i, lookup := range expected{ - for _, checked := range pis{ - if reflect.DeepEqual(lookup,checked){ +top: + for i, lookup := range expected { + for _, checked := range pis { + if reflect.DeepEqual(lookup, checked) { continue top } } @@ -376,19 +375,19 @@ func TestStore_Get(t *testing.T) { } expected = []Preimage{ - {preimage.Generate(identities[1].Bytes(),preimage.Default), preimage.Default, identities[1].Bytes()}, + {preimage.Generate(identities[1].Bytes(), preimage.Default), preimage.Default, identities[1].Bytes()}, preimages[1], } - if len(expected)!=len(pis){ + if len(expected) != len(pis) { t.Errorf("First Preimages for identity %s does not match expected, difrent lengths of %d and %d"+ - "\nexpected: %+v\nreceived: %+v", identities[0],len(expected), len(pis), expected, pis) + "\nexpected: %+v\nreceived: %+v", identities[0], len(expected), len(pis), expected, pis) } - top2: - for i, lookup := range expected{ - for _, checked := range pis{ - if reflect.DeepEqual(lookup,checked){ +top2: + for i, lookup := range expected { + for _, checked := range pis { + if reflect.DeepEqual(lookup, checked) { continue top2 } } @@ -492,23 +491,70 @@ func TestLoadStore(t *testing.T) { t.Errorf("Identity %s does not exist in loaded store", identity) } - if len(expectedPis[i])!=len(pis){ + if len(expectedPis[i]) != len(pis) { t.Errorf("First Preimages for identity %s does not match expected, difrent lengths of %d and %d"+ - "\nexpected: %+v\nreceived: %+v", identities[0],len(expectedPis[i]), len(pis), expectedPis[i], pis) + "\nexpected: %+v\nreceived: %+v", identities[0], len(expectedPis[i]), len(pis), expectedPis[i], pis) } top: - for idx, lookup := range expectedPis[i]{ - for _, checked := range pis{ - if reflect.DeepEqual(lookup,checked){ + for idx, lookup := range expectedPis[i] { + for _, checked := range pis { + if reflect.DeepEqual(lookup, checked) { continue top } } t.Errorf("Entree %d in expected %v not found in received %v", idx, lookup, pis) } + } +} +func TestStore_Check(t *testing.T) { + // Initialize store + s, _, _ := newTestStore(t) + identities := []*id.ID{ + id.NewIdFromString("identity0", id.User, t), + id.NewIdFromString("identity1", id.User, t), } + preimages := []Preimage{ + {[]byte("ID0"), "default0", []byte("ID0")}, + {[]byte("ID1"), "default1", []byte("ID1")}, + {[]byte("ID2"), "default2", []byte("ID2")}, + } + + // Add preimages + s.Add(preimages[0], identities[0]) + s.Add(preimages[1], identities[1]) + s.Add(preimages[2], identities[0]) + + testMsg := []byte("test message 123") + preImageData := preimages[0].Data + testFp := fingerprint2.IdentityFP(testMsg, preImageData) + + has, forMe, receivedPreImage := s.Check(identities[0], testFp, testMsg) + + if !has || !forMe || !reflect.DeepEqual(receivedPreImage, preimages[0]) { + t.Errorf("Unexpected result from Check()."+ + "\nExpected results: (has: %v) "+ + "\n\t(forMe: %v)"+ + "\n\t(Preimage: %v)"+ + "\nReceived results: (has: %v) "+ + "\n\t(forME: %v)"+ + "\n\t(Preimage: %v)", true, true, preimages[0], + has, forMe, receivedPreImage) + } + + // Check with wrong identity (has should be true, for me false) + has, forMe, _ = s.Check(identities[1], testFp, testMsg) + if !has || forMe { + t.Errorf("Unexpected results from check."+ + "\nExpected results: (has: %v)"+ + "\n\t(ForMe %v)"+ + "\nReceived results: "+ + "has: %v"+ + "\n\t(ForMe: %v)", true, false, has, forMe) + } + } func TestStore_save(t *testing.T) { diff --git a/storage/edge/preimage_test.go b/storage/edge/preimage_test.go index b4f3c7ee781ff0b8ecf04b7b3e699bf19c9f9d37..b31cc4274075344ad705b5308e7ac30e93bac5d0 100644 --- a/storage/edge/preimage_test.go +++ b/storage/edge/preimage_test.go @@ -21,12 +21,13 @@ import ( // Tests that newPreimages returns the expected new Preimages. func Test_newPreimages(t *testing.T) { identity := id.NewIdFromString("identity", id.User, t) + pimg := Preimage{ + Data: preimage.MakeDefault(identity), + Type: "default", + Source: identity.Bytes(), + } expected := Preimages{ - identity.String(): { - Data: preimage.MakeDefault(identity), - Type: "default", - Source: identity.Bytes(), - }, + pimg.key(): pimg, } received := newPreimages(identity) @@ -43,36 +44,47 @@ func TestPreimages_add(t *testing.T) { identity1 := id.NewIdFromString("identity1", id.User, t) identity2 := id.NewIdFromString("identity3", id.User, t) expected := Preimages{ - identity0.String(): {identity0.Bytes(), preimage.Default, preimage.MakeDefault(identity0)}, - identity1.String(): {identity1.Bytes(), preimage.Group, identity1.Bytes()}, - identity2.String(): {identity2.Bytes(), preimage.Default, identity2.Bytes()}, + identity0.String(): {preimage.Generate(identity0.Bytes(), preimage.Default), preimage.Default, preimage.MakeDefault(identity0)}, + identity1.String(): {preimage.Generate(identity1.Bytes(), preimage.Group), preimage.Group, identity1.Bytes()}, + identity2.String(): {preimage.Generate(identity2.Bytes(), preimage.Default), preimage.Default, identity2.Bytes()}, } pis := newPreimages(identity0) - exists := pis.add(Preimage{identity1.Bytes(), preimage.Group, identity1.Bytes()}) + preimageOne := Preimage{preimage.Generate(identity1.Bytes(), preimage.Group), preimage.Group, identity1.Bytes()} + exists := pis.add(preimageOne) if !exists { t.Errorf("Failed to add idenetity.") } - exists = pis.add(Preimage{identity2.Bytes(), preimage.Default, identity2.Bytes()}) + + preimageTwo := Preimage{preimage.Generate(identity2.Bytes(), preimage.Default), preimage.Default, identity2.Bytes()} + exists = pis.add(preimageTwo) if !exists { t.Errorf("Failed to add idenetity.") } - if !reflect.DeepEqual(expected, pis) { - t.Errorf("Failed to add expected Preimages."+ - "\nexpected: %+v\nreceived: %+v", expected, pis) + for identity, pimg := range expected { + if _, exists = pis[pimg.key()]; !exists { + t.Errorf("Identity %s could not be found", identity) + } } + expectedPreimageIdentityTwo := Preimage{ + Data: preimage.Generate(identity2.Bytes(), preimage.Default), + Type: preimage.Default, + Source: identity2.Bytes(), + } // Test that nothing happens when a Preimage with the same data exists - exists = pis.add(Preimage{identity2.Bytes(), "test", identity2.Bytes()}) + exists = pis.add(Preimage{preimage.Generate(identity2.Bytes(), preimage.Default), "test", identity2.Bytes()}) if exists { t.Errorf("Add idenetity that shoudl already exist.") } - if !reflect.DeepEqual(expected, pis) { - t.Errorf("Failed to add expected Preimages."+ - "\nexpected: %+v\nreceived: %+v", expected, pis) + receivedPreimageIdentityTwo := pis[preimageTwo.key()] + + if !reflect.DeepEqual(expectedPreimageIdentityTwo, receivedPreimageIdentityTwo) { + t.Errorf("Unexpected overwritting of existing identity") } + } // Tests that Preimages.remove removes all the correct Preimage from the list.