Example #1
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];
            int       BasePort    = (int)ArgumentValues["Base Port"];
            int       LocPort     = (int)ArgumentValues["LOC Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1},BasePort:{2},LocPort:{3})", ServerIp, PrimaryPort, BasePort, LocPort);

            bool res = false;

            Passed = false;

            ProtocolClient client        = new ProtocolClient();
            ProfileServer  profileServer = null;
            LocServer      locServer     = null;

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");

                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();

                // Create identities.
                int    profileNumber = 0;
                byte[] imageData     = File.ReadAllBytes(Path.Combine("images", TestName + ".png"));

                Dictionary <string, ProtocolClient> expectedLastClients = new Dictionary <string, ProtocolClient>(StringComparer.Ordinal);
                List <string> excessClientNames = new List <string>();
                for (int i = 0; i < 20050; i++)
                {
                    ProtocolClient protocolClient = new ProtocolClient();
                    protocolClient.InitializeRandomProfile(profileNumber, imageData);
                    profileNumber++;
                    if (i >= 19990)
                    {
                        protocolClient.Profile.Type = "last";
                        if (i < 20000)
                        {
                            expectedLastClients.Add(protocolClient.Profile.Name, protocolClient);
                        }
                        else
                        {
                            excessClientNames.Add(protocolClient.Profile.Name);
                        }
                    }
                    TestProfiles.Add(protocolClient.Profile.Name, protocolClient);
                }


                // Start simulated profile server.
                profileServer = new ProfileServer("TestProfileServer", ServerIp, BasePort, client.GetIdentityKeys(), new GpsLocation(1, 2));
                bool profileServerStartOk = profileServer.Start();

                // Start simulated LOC server.
                locServer = new LocServer("TestLocServer", ServerIp, LocPort);
                bool locServerStartOk = locServer.Start();

                await locServer.WaitForProfileServerConnectionAsync();

                bool step1Ok = profileServerStartOk && locServerStartOk;
                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");


                // Step 2
                log.Trace("Step 2");

                // Announce new neighbor.
                Iop.Locnet.NeighbourhoodChange change = new Iop.Locnet.NeighbourhoodChange()
                {
                    AddedNodeInfo = profileServer.GetNodeInfo(LocPort)
                };

                bool changeNotificationOk = await locServer.SendChangeNotification(change);

                // Wait for start of neighborhood initialization process.
                IncomingServerMessage incomingServerMessage = await profileServer.WaitForConversationRequest(ServerRole.ServerNeighbor, ConversationRequest.RequestTypeOneofCase.StartNeighborhoodInitialization);


                // Send update.
                bool statusOk     = false;
                bool updateOk     = true;
                int  profilesSent = 0;
                List <ProtocolClient> allProfiles    = new List <ProtocolClient>(TestProfiles.Values);
                List <ProtocolClient> profilesToSend = allProfiles.GetRange(0, 19990);
                while (profilesToSend.Count > 0)
                {
                    int batchSize = Math.Min(Rng.Next(100, 150), profilesToSend.Count);

                    List <SharedProfileUpdateItem> updateItems = new List <SharedProfileUpdateItem>();
                    foreach (ProtocolClient pc in profilesToSend.GetRange(0, batchSize))
                    {
                        updateItems.Add(pc.GetSharedProfileUpdateAddItem());
                    }

                    profilesToSend.RemoveRange(0, batchSize);

                    Message updateRequest = await profileServer.SendNeighborhoodSharedProfileUpdateRequest(incomingServerMessage.Client, updateItems);

                    profilesSent         += batchSize;
                    incomingServerMessage = await profileServer.WaitForResponse(ServerRole.ServerNeighbor, updateRequest);

                    statusOk = incomingServerMessage.IncomingMessage.Response.Status == Status.Ok;
                    bool batchOk = (updateRequest != null) && statusOk;
                    if (!batchOk)
                    {
                        updateOk = false;
                        break;
                    }
                }


                // Finish neighborhood initialization process.
                Message finishRequest = await profileServer.SendFinishNeighborhoodInitializationRequest(incomingServerMessage.Client);

                incomingServerMessage = await profileServer.WaitForResponse(ServerRole.ServerNeighbor, finishRequest);

                statusOk = incomingServerMessage.IncomingMessage.Response.Status == Status.Ok;
                bool finishOk = (finishRequest != null) && statusOk;


                bool step2Ok = changeNotificationOk && updateOk && finishOk;
                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");



                // Step 3
                log.Trace("Step 3");

                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool verifyIdentityOk = await client.VerifyIdentityAsync();

                List <SharedProfileUpdateItem> badUpdateItems = new List <SharedProfileUpdateItem>();
                foreach (ProtocolClient pc in allProfiles.GetRange(19990, 60))
                {
                    badUpdateItems.Add(pc.GetSharedProfileUpdateAddItem());
                }


                Message requestMessage = mb.CreateNeighborhoodSharedProfileUpdateRequest(badUpdateItems);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.ErrorInvalidValue;
                bool detailsOk = responseMessage.Response.Details == "10.add";

                bool badUpdateOk = idOk && statusOk && detailsOk;
                client.CloseConnection();

                // Step 3 Acceptance
                bool step3Ok = verifyIdentityOk && badUpdateOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");



                // Step 4
                log.Trace("Step 4");

                // Start conversation.
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool startConversationOk = await client.StartConversationAsync();

                HashSet <byte[]> expectedCoveredServers = new HashSet <byte[]>(StructuralEqualityComparer <byte[]> .Default)
                {
                    client.GetIdentityId(), Crypto.Sha256(client.ServerKey)
                };

                // Search all profiles with type "last".
                requestMessage = mb.CreateProfileSearchRequest("last", null, null, null, 0, 100, 100);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;


                bool totalRecordCountOk       = responseMessage.Response.ConversationResponse.ProfileSearch.TotalRecordCount == 10;
                bool maxResponseRecordCountOk = responseMessage.Response.ConversationResponse.ProfileSearch.MaxResponseRecordCount == 100;
                bool profilesCountOk          = responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.Count == 10;
                bool resultsOk = client.CheckProfileListMatchSearchResultItems(expectedLastClients, responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.ToList(), false, false, client.GetIdentityId(), true);

                bool queryOk = idOk && statusOk && totalRecordCountOk && maxResponseRecordCountOk && profilesCountOk && resultsOk;

                client.CloseConnection();

                // Step 4 Acceptance
                bool step4Ok = startConversationOk && queryOk;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");



                // Step 5
                log.Trace("Step 5");

                // Make TestProfiles reflect the status on the target profile server.
                foreach (string excessClientName in excessClientNames)
                {
                    TestProfiles[excessClientName].Dispose();
                    TestProfiles.Remove(excessClientName);
                }

                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                verifyIdentityOk = await client.VerifyIdentityAsync();

                // Select 140 profiles for deletion.
                List <SharedProfileUpdateItem> deleteUpdateItems = new List <SharedProfileUpdateItem>();
                while (deleteUpdateItems.Count < 140)
                {
                    int            index = Rng.Next(TestProfiles.Count);
                    ProtocolClient pc    = TestProfiles.ElementAt(index).Value;
                    deleteUpdateItems.Add(pc.GetSharedProfileUpdateDeleteItem());

                    if (expectedLastClients.ContainsKey(pc.Profile.Name))
                    {
                        expectedLastClients.Remove(pc.Profile.Name);
                    }

                    TestProfiles.Remove(pc.Profile.Name);
                    pc.Dispose();
                }

                // Send delete update.
                requestMessage = mb.CreateNeighborhoodSharedProfileUpdateRequest(deleteUpdateItems);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool deleteUpdateOk = idOk && statusOk;


                // Generate 160 new identities.
                badUpdateItems.Clear();
                excessClientNames.Clear();
                for (int i = 0; i < 160; i++)
                {
                    ProtocolClient protocolClient = new ProtocolClient();
                    protocolClient.InitializeRandomProfile(profileNumber, imageData);
                    profileNumber++;
                    protocolClient.Profile.Type = "last";

                    if (TestProfiles.Count < 20000)
                    {
                        expectedLastClients.Add(protocolClient.Profile.Name, protocolClient);
                    }
                    else
                    {
                        excessClientNames.Add(protocolClient.Profile.Name);
                    }

                    TestProfiles.Add(protocolClient.Profile.Name, protocolClient);
                    badUpdateItems.Add(protocolClient.GetSharedProfileUpdateAddItem());
                }


                // Add the new profiles to the profile server.
                requestMessage = mb.CreateNeighborhoodSharedProfileUpdateRequest(badUpdateItems);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "140.add";

                badUpdateOk = idOk && statusOk && detailsOk;
                client.CloseConnection();

                // Step 5 Acceptance
                bool step5Ok = verifyIdentityOk && deleteUpdateOk && badUpdateOk;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");



                // Step 6
                log.Trace("Step 6");

                // Make TestProfiles reflect the status on the target profile server.
                foreach (string excessClientName in excessClientNames)
                {
                    TestProfiles[excessClientName].Dispose();
                    TestProfiles.Remove(excessClientName);
                }

                // Start conversation.
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                startConversationOk = await client.StartConversationAsync();

                // Search all profiles with type "last".
                requestMessage = mb.CreateProfileSearchRequest("last", null, null, null, 0, 1000, 1000, false, false);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;


                totalRecordCountOk       = responseMessage.Response.ConversationResponse.ProfileSearch.TotalRecordCount == expectedLastClients.Count;
                maxResponseRecordCountOk = responseMessage.Response.ConversationResponse.ProfileSearch.MaxResponseRecordCount == 1000;
                profilesCountOk          = responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.Count == expectedLastClients.Count;
                resultsOk = client.CheckProfileListMatchSearchResultItems(expectedLastClients, responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.ToList(), false, false, client.GetIdentityId(), false);

                queryOk = idOk && statusOk && totalRecordCountOk && maxResponseRecordCountOk && profilesCountOk && resultsOk;

                client.CloseConnection();

                // Step 6 Acceptance
                bool step6Ok = startConversationOk && queryOk;

                log.Trace("Step 6: {0}", step6Ok ? "PASSED" : "FAILED");



                // Step 7
                log.Trace("Step 7");

                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                verifyIdentityOk = await client.VerifyIdentityAsync();

                // Select 40 profiles for deletion.
                deleteUpdateItems = new List <SharedProfileUpdateItem>();
                while (deleteUpdateItems.Count < 40)
                {
                    int            index = Rng.Next(TestProfiles.Count);
                    ProtocolClient pc    = TestProfiles.ElementAt(index).Value;
                    deleteUpdateItems.Add(pc.GetSharedProfileUpdateDeleteItem());

                    if (expectedLastClients.ContainsKey(pc.Profile.Name))
                    {
                        expectedLastClients.Remove(pc.Profile.Name);
                    }

                    TestProfiles.Remove(pc.Profile.Name);
                    pc.Dispose();
                }

                // Select 40 profiles for change, but avoid updating one profile twice in a single update message, which is forbidden.
                HashSet <int> usedIndexes = new HashSet <int>();
                List <SharedProfileUpdateItem> changeUpdateItems = new List <SharedProfileUpdateItem>();
                while (changeUpdateItems.Count < 40)
                {
                    int index = Rng.Next(TestProfiles.Count);

                    if (usedIndexes.Contains(index))
                    {
                        continue;
                    }
                    usedIndexes.Add(index);

                    ProtocolClient pc = TestProfiles.ElementAt(index).Value;
                    pc.Profile.ExtraData = "1234567890";
                    SharedProfileUpdateItem changeUpdateItem = new SharedProfileUpdateItem()
                    {
                        Change = new SharedProfileChangeItem()
                        {
                            IdentityNetworkId = ProtocolHelper.ByteArrayToByteString(pc.GetIdentityId()),
                            SetExtraData      = true,
                            ExtraData         = pc.Profile.ExtraData
                        }
                    };
                    changeUpdateItems.Add(changeUpdateItem);
                }

                // Generate 40 new identities.
                List <SharedProfileUpdateItem> addUpdateItems = new List <SharedProfileUpdateItem>();
                for (int i = 0; i < 40; i++)
                {
                    ProtocolClient protocolClient = new ProtocolClient();
                    protocolClient.InitializeRandomProfile(profileNumber, imageData);
                    profileNumber++;
                    protocolClient.Profile.Type = "last";

                    expectedLastClients.Add(protocolClient.Profile.Name, protocolClient);

                    TestProfiles.Add(protocolClient.Profile.Name, protocolClient);
                    addUpdateItems.Add(protocolClient.GetSharedProfileUpdateAddItem());
                }


                // Send all the updates as one.
                List <SharedProfileUpdateItem> newUpdateItems = new List <SharedProfileUpdateItem>();
                newUpdateItems.AddRange(deleteUpdateItems);
                newUpdateItems.AddRange(changeUpdateItems);
                newUpdateItems.AddRange(addUpdateItems);
                requestMessage = mb.CreateNeighborhoodSharedProfileUpdateRequest(newUpdateItems);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool newUpdateOk = idOk && statusOk;
                client.CloseConnection();

                // Step 7 Acceptance
                bool step7Ok = verifyIdentityOk && newUpdateOk;

                log.Trace("Step 7: {0}", step7Ok ? "PASSED" : "FAILED");



                // Step 8
                log.Trace("Step 8");

                // Start conversation.
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                startConversationOk = await client.StartConversationAsync();

                // Search all profiles with type "last".
                requestMessage = mb.CreateProfileSearchRequest("last", null, null, null, 0, 1000, 1000, false, false);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                totalRecordCountOk       = responseMessage.Response.ConversationResponse.ProfileSearch.TotalRecordCount == expectedLastClients.Count;
                maxResponseRecordCountOk = responseMessage.Response.ConversationResponse.ProfileSearch.MaxResponseRecordCount == 1000;
                profilesCountOk          = responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.Count == expectedLastClients.Count;
                resultsOk = client.CheckProfileListMatchSearchResultItems(expectedLastClients, responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.ToList(), false, false, client.GetIdentityId(), false);

                queryOk = idOk && statusOk && totalRecordCountOk && maxResponseRecordCountOk && profilesCountOk && resultsOk;

                client.CloseConnection();

                // Step 8 Acceptance
                bool step8Ok = startConversationOk && queryOk;

                log.Trace("Step 8: {0}", step8Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok && step6Ok && step7Ok && step8Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            foreach (ProtocolClient protocolClient in TestProfiles.Values)
            {
                protocolClient.Dispose();
            }

            if (profileServer != null)
            {
                profileServer.Shutdown();
            }
            if (locServer != null)
            {
                locServer.Shutdown();
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #2
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];
            int       BasePort    = (int)ArgumentValues["Base Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1},BasePort:{2})", ServerIp, PrimaryPort, BasePort);

            bool res = false;

            Passed = false;

            ProtocolClient client        = new ProtocolClient();
            ProfileServer  profileServer = null;

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();


                bool   profileInitializationOk = true;
                byte[] testImageData           = File.ReadAllBytes(Path.Combine("images", TestName + ".jpg"));

                int profileIndex = 1;
                int profileCount = 10;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        TestProfiles.Add(profileClient.Profile.Name, profileClient);
                    }
                    else
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }
                }


                profileServer = new ProfileServer("TestServer", ServerIp, BasePort, client.GetIdentityKeys());
                bool serverStartOk = profileServer.Start();

                bool step1Ok = listPortsOk && profileInitializationOk && serverStartOk;
                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool neighborhoodInitializationProcessOk = await client.NeighborhoodInitializationProcessAsync(profileServer.PrimaryPort, profileServer.ServerNeighborPort, TestProfiles);

                client.CloseConnection();

                bool step2Ok = neighborhoodInitializationProcessOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                // Step 3
                log.Trace("Step 3");

                // Add 5 more identities.
                Dictionary <string, ProtocolClient> newProfiles = new Dictionary <string, ProtocolClient>(StringComparer.Ordinal);
                profileInitializationOk = true;
                profileCount            = 5;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        TestProfiles.Add(profileClient.Profile.Name, profileClient);
                        newProfiles.Add(profileClient.Profile.Name, profileClient);
                    }
                    else
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }
                }

                log.Trace("Waiting 20 seconds ...");
                await Task.Delay(20000);

                // Meanwhile we expect updates to arrive on our simulated profile server.
                bool error = false;
                List <IncomingServerMessage> psMessages = profileServer.GetMessageList();
                List <SharedProfileAddItem>  addUpdates = new List <SharedProfileAddItem>();
                foreach (IncomingServerMessage ism in psMessages)
                {
                    if (ism.Role != ServerRole.ServerNeighbor)
                    {
                        continue;
                    }
                    Message message = ism.IncomingMessage;

                    if ((message.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                        (message.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                        (message.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate))
                    {
                        foreach (SharedProfileUpdateItem updateItem in message.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                        {
                            if (updateItem.ActionTypeCase == SharedProfileUpdateItem.ActionTypeOneofCase.Add)
                            {
                                SharedProfileAddItem addItem = updateItem.Add;
                                addUpdates.Add(addItem);
                            }
                            else
                            {
                                log.Trace("Received invalid update action type {0}.", updateItem.ActionTypeCase);
                                error = true;
                                break;
                            }
                        }
                    }

                    if (error)
                    {
                        break;
                    }
                }

                bool receivedUpdatesOk = !error;

                bool updatesOk = client.CheckProfileListMatchAddItems(newProfiles, addUpdates);

                bool step3Ok = profileInitializationOk && receivedUpdatesOk && updatesOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");



                // Step 4
                log.Trace("Step 4");

                // Set profile server to reject updates.
                profileServer.RejectNeighborhoodSharedProfileUpdate = true;

                // Add 1 more identity.
                newProfiles             = new Dictionary <string, ProtocolClient>(StringComparer.Ordinal);
                profileInitializationOk = true;
                profileCount            = 1;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        TestProfiles.Add(profileClient.Profile.Name, profileClient);
                        newProfiles.Add(profileClient.Profile.Name, profileClient);
                    }
                    else
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }
                }

                await Task.Delay(20000);

                // Set profile server to accept updates again.
                profileServer.RejectNeighborhoodSharedProfileUpdate = false;

                // Meanwhile we expect the update to arrive on our simulated profile server.
                error      = false;
                psMessages = profileServer.GetMessageList();
                addUpdates = new List <SharedProfileAddItem>();
                foreach (IncomingServerMessage ism in psMessages)
                {
                    if (ism.Role != ServerRole.ServerNeighbor)
                    {
                        continue;
                    }
                    Message message = ism.IncomingMessage;

                    if ((message.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                        (message.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                        (message.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate))
                    {
                        foreach (SharedProfileUpdateItem updateItem in message.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                        {
                            if (updateItem.ActionTypeCase == SharedProfileUpdateItem.ActionTypeOneofCase.Add)
                            {
                                SharedProfileAddItem addItem = updateItem.Add;
                                addUpdates.Add(addItem);
                            }
                            else
                            {
                                log.Trace("Received invalid update action type {0}.", updateItem.ActionTypeCase);
                                error = true;
                                break;
                            }
                        }
                    }

                    if (error)
                    {
                        break;
                    }
                }

                receivedUpdatesOk = !error && (addUpdates.Count == 1);

                bool step4Ok = profileInitializationOk && receivedUpdatesOk;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");



                // Step 5
                log.Trace("Step 5");

                // Add 5 more identities.
                newProfiles             = new Dictionary <string, ProtocolClient>(StringComparer.Ordinal);
                profileInitializationOk = true;
                profileCount            = 5;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        TestProfiles.Add(profileClient.Profile.Name, profileClient);
                        newProfiles.Add(profileClient.Profile.Name, profileClient);
                    }
                    else
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }
                }

                log.Trace("Waiting 20 seconds ...");
                await Task.Delay(20000);

                // Meanwhile we expect updates to arrive on our simulated profile server.
                error      = false;
                psMessages = profileServer.GetMessageList();
                addUpdates = new List <SharedProfileAddItem>();
                foreach (IncomingServerMessage ism in psMessages)
                {
                    if (ism.Role != ServerRole.ServerNeighbor)
                    {
                        continue;
                    }
                    Message message = ism.IncomingMessage;

                    if ((message.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                        (message.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                        (message.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate))
                    {
                        foreach (SharedProfileUpdateItem updateItem in message.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                        {
                            if (updateItem.ActionTypeCase == SharedProfileUpdateItem.ActionTypeOneofCase.Add)
                            {
                                SharedProfileAddItem addItem = updateItem.Add;
                                addUpdates.Add(addItem);
                            }
                            else
                            {
                                log.Trace("Received invalid update action type {0}.", updateItem.ActionTypeCase);
                                error = true;
                                break;
                            }
                        }
                    }

                    if (error)
                    {
                        break;
                    }
                }

                receivedUpdatesOk = !error;

                updatesOk = addUpdates.Count == 0;

                bool step5Ok = profileInitializationOk && receivedUpdatesOk && updatesOk;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            foreach (ProtocolClient protocolClient in TestProfiles.Values)
            {
                protocolClient.Dispose();
            }

            if (profileServer != null)
            {
                profileServer.Shutdown();
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #3
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp            = (IPAddress)ArgumentValues["Node IP"];
            int       ClNonCustomerPort = (int)ArgumentValues["clNonCustomer Port"];
            int       ClCustomerPort    = (int)ArgumentValues["clCustomer Port"];

            log.Trace("(NodeIp:'{0}',ClNonCustomerPort:{1},ClCustomerPort:{2})", NodeIp, ClNonCustomerPort, ClCustomerPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb             = client.MessageBuilder;
                byte[]         testIdentityId = client.GetIdentityId();

                // Step 1
                await client.ConnectAsync(NodeIp, ClNonCustomerPort, true);

                bool establishHomeNodeOk = await client.EstablishHomeNodeAsync();

                // Step 1 Acceptance
                bool step1Ok = establishHomeNodeOk;
                client.CloseConnection();


                // Step 2
                await client.ConnectAsync(NodeIp, ClCustomerPort, true);

                bool checkInOk = await client.CheckInAsync();

                byte[]  newNodeId      = Encoding.UTF8.GetBytes("test");
                Message requestMessage = mb.CreateCancelHomeNodeAgreementRequest(newNodeId);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk      = responseMessage.Id == requestMessage.Id;
                bool statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                bool detailsOk = responseMessage.Response.Details == "newHomeNodeNetworkId";

                bool cancelAgreementOk = idOk && statusOk && detailsOk;

                // Step 2 Acceptance
                bool step2Ok = checkInOk && cancelAgreementOk;


                Passed = step1Ok && step2Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #4
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient clientPrimary   = new ProtocolClient();
            ProtocolClient clientSecondary = new ProtocolClient();

            try
            {
                MessageBuilder mbPrimary   = clientPrimary.MessageBuilder;
                MessageBuilder mbSecondary = clientSecondary.MessageBuilder;

                // Step 1
                log.Trace("Step 1");

                // Get port list.
                await clientPrimary.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await clientPrimary.ListServerPorts(rolePorts);

                clientPrimary.CloseConnection();

                // Establish hosting agreement for primary client.
                await clientPrimary.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHostingOk = await clientPrimary.EstablishHostingAsync("Primary");

                clientPrimary.CloseConnection();

                // Check in primary client.
                await clientPrimary.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await clientPrimary.CheckInAsync();

                bool primaryOk = establishHostingOk && checkInOk;

                // Establish hosting agreement for secondary client.
                await clientSecondary.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                establishHostingOk = await clientSecondary.EstablishHostingAsync("Primary");

                clientSecondary.CloseConnection();

                // Check in secondary client.
                await clientSecondary.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                checkInOk = await clientSecondary.CheckInAsync();

                bool secondaryOk = establishHostingOk && checkInOk;

                // Create card issuers.
                CardIssuers = new List <ProtocolClient>();
                for (int i = 0; i < IssuerCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    CardIssuers.Add(profileClient);
                }


                // Step 1 Acceptance
                bool step1Ok = listPortsOk && primaryOk && secondaryOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");

                SignedCards      = new List <SignedRelationshipCard>();
                CardApplications = new List <CardApplicationInformation>();

                // Just to make it easy to follow the test specification.
                ProtocolClient Identity1 = CardIssuers[0];
                ProtocolClient Identity2 = CardIssuers[1];
                ProtocolClient Identity3 = CardIssuers[2];
                ProtocolClient Identity4 = CardIssuers[3];
                ProtocolClient Identity5 = CardIssuers[4];

                log.Trace("Identity1 ID: {0}", Crypto.ToHex(Identity1.GetIdentityId()));
                log.Trace("Identity2 ID: {0}", Crypto.ToHex(Identity2.GetIdentityId()));
                log.Trace("Identity3 ID: {0}", Crypto.ToHex(Identity3.GetIdentityId()));
                log.Trace("Identity4 ID: {0}", Crypto.ToHex(Identity4.GetIdentityId()));
                log.Trace("Identity5 ID: {0}", Crypto.ToHex(Identity5.GetIdentityId()));


                byte[]   primaryPubKey            = clientPrimary.GetIdentityKeys().PublicKey;
                string   type                     = "Card Type A";
                DateTime validFrom                = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                DateTime validTo                  = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                SignedRelationshipCard signedCard = Identity1.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                byte[] applicationId = new byte[] { 1 };
                CardApplicationInformation cardApplication = clientPrimary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                Message requestMessage = mbPrimary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientPrimary.SendMessageAsync(requestMessage);

                Message responseMessage = await clientPrimary.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.Ok;

                bool req1Ok = idOk && statusOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(1479220557000);
                signedCard = Identity1.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                applicationId   = new byte[] { 2 };
                cardApplication = clientPrimary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                requestMessage = mbPrimary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req2Ok = idOk && statusOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = Identity2.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                applicationId   = new byte[] { 3 };
                cardApplication = clientPrimary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                requestMessage = mbPrimary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req3Ok = idOk && statusOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(2479220555000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = Identity2.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                applicationId   = new byte[] { 4 };
                cardApplication = clientPrimary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                requestMessage = mbPrimary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req4Ok = idOk && statusOk;


                type       = "Card Type B";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = Identity3.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                applicationId   = new byte[] { 5 };
                cardApplication = clientPrimary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                requestMessage = mbPrimary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req5Ok = idOk && statusOk;


                type       = "Card Type B";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = Identity4.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                applicationId   = new byte[] { 6 };
                cardApplication = clientPrimary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                requestMessage = mbPrimary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req6Ok = idOk && statusOk;


                type       = "Card Type C";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = Identity4.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                applicationId   = new byte[] { 7 };
                cardApplication = clientPrimary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                requestMessage = mbPrimary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req7Ok = idOk && statusOk;


                type       = "Card Type C";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = Identity4.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                applicationId   = new byte[] { 8 };
                cardApplication = clientPrimary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                requestMessage = mbPrimary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req8Ok = idOk && statusOk;


                type       = "Other";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = Identity5.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                applicationId   = new byte[] { 9 };
                cardApplication = clientPrimary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                requestMessage = mbPrimary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req9Ok = idOk && statusOk;


                // Step 2 Acceptance
                bool step2Ok = req1Ok && req2Ok && req3Ok && req4Ok && req5Ok && req6Ok && req7Ok && req8Ok && req9Ok;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                // Step 3
                log.Trace("Step 3");

                byte[] secondaryPubKey = clientSecondary.GetIdentityKeys().PublicKey;
                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = Identity1.IssueRelationshipCard(secondaryPubKey, type, validFrom, validTo);
                SignedCards.Add(signedCard);

                applicationId   = new byte[] { 1 };
                cardApplication = clientSecondary.CreateRelationshipCardApplication(applicationId, signedCard);
                CardApplications.Add(cardApplication);

                requestMessage = mbSecondary.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req10Ok = idOk && statusOk;


                // Step 3 Acceptance
                bool step3Ok = req10Ok;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");


                // Step 4
                log.Trace("Step 4");

                byte[] primaryClientId = clientPrimary.GetIdentityId();
                requestMessage = mbSecondary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, true, null, null);
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;
                SemVer receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                bool   versionOk       = receivedVersion.Equals(SemVer.V100);

                HashSet <int> numberList = new HashSet <int>()
                {
                    1, 2, 3, 4, 5, 6, 7, 8, 9
                };
                bool relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req1Ok = idOk && statusOk && versionOk && relationshipsOk;


                requestMessage = mbSecondary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, false, null, null);
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                numberList = new HashSet <int>()
                {
                    1, 3, 5, 6, 7, 8, 9
                };
                relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req2Ok = idOk && statusOk && versionOk && relationshipsOk;


                requestMessage = mbSecondary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, true, "*", null);
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                numberList = new HashSet <int>()
                {
                    1, 2, 3, 4, 5, 6, 7, 8, 9
                };
                relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req3Ok = idOk && statusOk && versionOk && relationshipsOk;


                requestMessage = mbSecondary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, true, "**", null);
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                numberList = new HashSet <int>()
                {
                    1, 2, 3, 4, 5, 6, 7, 8, 9
                };
                relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req4Ok = idOk && statusOk && versionOk && relationshipsOk;


                requestMessage = mbSecondary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, true, "Card*", null);
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                numberList = new HashSet <int>()
                {
                    1, 2, 3, 4, 5, 6, 7, 8
                };
                relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req5Ok = idOk && statusOk && versionOk && relationshipsOk;


                requestMessage = mbSecondary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, true, "*Type A", null);
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                numberList = new HashSet <int>()
                {
                    1, 2, 3, 4
                };
                relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req6Ok = idOk && statusOk && versionOk && relationshipsOk;


                requestMessage = mbSecondary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, true, "*Type *", null);
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                numberList = new HashSet <int>()
                {
                    1, 2, 3, 4, 5, 6, 7, 8
                };
                relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req7Ok = idOk && statusOk && versionOk && relationshipsOk;


                requestMessage = mbSecondary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, true, null, Identity1.GetIdentityId());
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                numberList = new HashSet <int>()
                {
                    1, 2
                };
                relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req8Ok = idOk && statusOk && versionOk && relationshipsOk;


                requestMessage = mbSecondary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, true, "*C", Identity4.GetIdentityId());
                await clientSecondary.SendMessageAsync(requestMessage);

                responseMessage = await clientSecondary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                numberList = new HashSet <int>()
                {
                    7, 8
                };
                relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req9Ok = idOk && statusOk && versionOk && relationshipsOk;


                // Step 4 Acceptance
                bool step4Ok = req1Ok && req2Ok && req3Ok && req4Ok && req5Ok && req6Ok && req7Ok && req8Ok && req9Ok;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");



                // Step 5
                log.Trace("Step 5");

                applicationId  = new byte[] { 2 };
                requestMessage = mbPrimary.CreateRemoveRelatedIdentityRequest(applicationId);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool removeRelation1Ok = idOk && statusOk;

                applicationId  = new byte[] { 4 };
                requestMessage = mbPrimary.CreateRemoveRelatedIdentityRequest(applicationId);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool removeRelation2Ok = idOk && statusOk;



                requestMessage = mbPrimary.CreateGetIdentityRelationshipsInformationRequest(primaryClientId, true, "*Type a*", null);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                numberList = new HashSet <int>()
                {
                    1, 3
                };
                relationshipsOk = CheckRelationships(numberList, responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships);

                req1Ok = idOk && statusOk && versionOk && relationshipsOk;



                byte[] partId = new byte[10];
                Array.Copy(primaryClientId, partId, partId.Length);
                requestMessage = mbPrimary.CreateGetIdentityRelationshipsInformationRequest(partId, true, "*Type a*", null);
                await clientPrimary.SendMessageAsync(requestMessage);

                responseMessage = await clientPrimary.ReceiveMessageAsync();

                idOk            = responseMessage.Id == requestMessage.Id;
                statusOk        = responseMessage.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessage.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                relationshipsOk = responseMessage.Response.SingleResponse.GetIdentityRelationshipsInformation.Relationships.Count == 0;

                req1Ok = idOk && statusOk && versionOk && relationshipsOk;



                // Step 5 Acceptance
                bool step5Ok = removeRelation1Ok && removeRelation2Ok && req1Ok && req2Ok;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            clientPrimary.Dispose();
            clientSecondary.Dispose();

            if (CardIssuers != null)
            {
                for (int i = 0; i < IssuerCount; i++)
                {
                    if (CardIssuers[i] != null)
                    {
                        CardIssuers[i].Dispose();
                    }
                }
            }


            log.Trace("(-):{0}", res);
            return(res);
        }
Example #5
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp            = (IPAddress)ArgumentValues["Node IP"];
            int       ClNonCustomerPort = (int)ArgumentValues["clNonCustomer Port"];

            log.Trace("(NodeIp:'{0}',ClNonCustomerPort:{1})", NodeIp, ClNonCustomerPort);

            bool res = false;

            Passed = false;

            ProtocolClient client1 = new ProtocolClient();
            ProtocolClient client2 = new ProtocolClient();

            try
            {
                MessageBuilder mb1         = client1.MessageBuilder;
                MessageBuilder mb2         = client2.MessageBuilder;
                byte[]         identityId1 = client1.GetIdentityId();

                // Step 1
                await client1.ConnectAsync(NodeIp, ClNonCustomerPort, true);

                bool homeNodeOk = await client1.EstablishHomeNodeAsync();

                client1.CloseConnection();

                // Step 1 Acceptance
                bool step1Ok = homeNodeOk;


                // Step 2
                await client2.ConnectAsync(NodeIp, ClNonCustomerPort, true);

                bool verifyIdentityOk = await client2.VerifyIdentityAsync();

                Message requestMessage = mb2.CreateCallIdentityApplicationServiceRequest(identityId1, "Test Service");
                await client2.SendMessageAsync(requestMessage);

                Message responseMessage = await client2.ReceiveMessageAsync();

                bool idOk           = responseMessage.Id == requestMessage.Id;
                bool statusOk       = responseMessage.Response.Status == Status.ErrorUninitialized;
                bool callIdentityOk = idOk && statusOk;

                // Step 2 Acceptance
                bool step2Ok = verifyIdentityOk && callIdentityOk;


                Passed = step1Ok && step2Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client1.Dispose();
            client2.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #6
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];
            int       BasePort    = (int)ArgumentValues["Base Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1},BasePort:{2})", ServerIp, PrimaryPort, BasePort);

            bool res = false;

            Passed = false;

            ProtocolClient client        = new ProtocolClient();
            ProfileServer  profileServer = null;

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();


                bool   profileInitializationOk = true;
                byte[] testImageData           = File.ReadAllBytes(Path.Combine("images", TestName + ".jpg"));
                byte[] testImageData2          = File.ReadAllBytes(Path.Combine("images", TestName + "b.png"));

                int profileIndex = 1;
                int profileCount = 50;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        TestProfiles.Add(profileClient.Profile.Name, profileClient);
                    }
                    else
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }
                }


                profileServer = new ProfileServer("TestServer", ServerIp, BasePort, client.GetIdentityKeys());
                bool serverStartOk = profileServer.Start();

                bool step1Ok = listPortsOk && profileInitializationOk && serverStartOk;
                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool neighborhoodInitializationProcessOk = await client.NeighborhoodInitializationProcessAsync(profileServer.PrimaryPort, profileServer.ServerNeighborPort, TestProfiles);

                client.CloseConnection();

                bool step2Ok = neighborhoodInitializationProcessOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                // Step 3
                log.Trace("Step 3");

                // Add 15 more identities.
                Dictionary <string, ProtocolClient> newProfiles = new Dictionary <string, ProtocolClient>(StringComparer.Ordinal);
                profileInitializationOk = true;
                profileCount            = 15;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        TestProfiles.Add(profileClient.Profile.Name, profileClient);
                        newProfiles.Add(profileClient.Profile.Name, profileClient);
                    }
                    else
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }
                }

                log.Trace("Waiting 20 seconds ...");
                await Task.Delay(20000);

                // Meanwhile we expect updates to arrive on our simulated profile server.
                bool error = false;
                List <IncomingServerMessage> psMessages = profileServer.GetMessageList();
                List <SharedProfileAddItem>  addUpdates = new List <SharedProfileAddItem>();
                foreach (IncomingServerMessage ism in psMessages)
                {
                    if (ism.Role != ServerRole.ServerNeighbor)
                    {
                        continue;
                    }
                    Message message = ism.IncomingMessage;

                    if ((message.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                        (message.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                        (message.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate))
                    {
                        foreach (SharedProfileUpdateItem updateItem in message.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                        {
                            if (updateItem.ActionTypeCase == SharedProfileUpdateItem.ActionTypeOneofCase.Add)
                            {
                                SharedProfileAddItem addItem = updateItem.Add;
                                addUpdates.Add(addItem);
                            }
                            else
                            {
                                log.Trace("Received invalid update action type {0}.", updateItem.ActionTypeCase);
                                error = true;
                                break;
                            }
                        }
                    }

                    if (error)
                    {
                        break;
                    }
                }

                bool receivedUpdatesOk = !error;

                bool updatesOk = client.CheckProfileListMatchAddItems(newProfiles, addUpdates);

                bool step3Ok = profileInitializationOk && receivedUpdatesOk && updatesOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");



                // Step 4
                log.Trace("Step 4");

                // Cancel 15 identities.
                HashSet <byte[]> cancelledProfiles  = new HashSet <byte[]>(StructuralEqualityComparer <byte[]> .Default);
                bool             profileCancelingOk = true;
                profileCount = 15;
                for (int i = 0; i < profileCount; i++)
                {
                    int            index         = Rng.Next(TestProfiles.Count);
                    List <string>  keys          = TestProfiles.Keys.ToList();
                    ProtocolClient profileClient = TestProfiles[keys[index]];

                    if (await profileClient.CancelHostingAgreementAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        TestProfiles.Remove(keys[index]);
                        cancelledProfiles.Add(profileClient.GetIdentityId());
                    }
                    else
                    {
                        profileCancelingOk = false;
                        break;
                    }
                }

                await Task.Delay(20000);

                // Meanwhile we expect updates to arrive on our simulated profile server.
                psMessages = profileServer.GetMessageList();
                List <SharedProfileDeleteItem> deleteUpdates = new List <SharedProfileDeleteItem>();
                foreach (IncomingServerMessage ism in psMessages)
                {
                    if (ism.Role != ServerRole.ServerNeighbor)
                    {
                        continue;
                    }
                    Message message = ism.IncomingMessage;

                    if ((message.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                        (message.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                        (message.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate))
                    {
                        foreach (SharedProfileUpdateItem updateItem in message.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                        {
                            if (updateItem.ActionTypeCase == SharedProfileUpdateItem.ActionTypeOneofCase.Delete)
                            {
                                SharedProfileDeleteItem deleteItem = updateItem.Delete;
                                deleteUpdates.Add(deleteItem);
                            }
                            else
                            {
                                log.Trace("Received invalid update action type {0}.", updateItem.ActionTypeCase);
                                error = true;
                                break;
                            }
                        }
                    }

                    if (error)
                    {
                        break;
                    }
                }

                receivedUpdatesOk = !error;

                updatesOk = client.CheckProfileListMatchDeleteItems(cancelledProfiles, deleteUpdates);

                bool step4Ok = profileCancelingOk && receivedUpdatesOk && updatesOk;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");



                // Step 5
                log.Trace("Step 5");

                // Change 25 profiles.
                Dictionary <byte[], SharedProfileChangeItem> changedProfiles = new Dictionary <byte[], SharedProfileChangeItem>(StructuralEqualityComparer <byte[]> .Default);
                bool profileChangingOk = true;
                profileCount = 25;
                for (int i = 0; i < profileCount; i++)
                {
                    int            index         = Rng.Next(TestProfiles.Count);
                    List <string>  keys          = TestProfiles.Keys.ToList();
                    ProtocolClient profileClient = TestProfiles[keys[index]];
                    if (changedProfiles.ContainsKey(profileClient.GetIdentityId()))
                    {
                        // Do not take one client twice.
                        i--;
                        continue;
                    }

                    SharedProfileChangeItem changeItem = new SharedProfileChangeItem()
                    {
                        IdentityNetworkId = ProtocolHelper.ByteArrayToByteString(profileClient.GetIdentityId()),
                        SetName           = Rng.NextDouble() < 0.20,
                        SetLocation       = Rng.NextDouble() < 0.20,
                        SetExtraData      = Rng.NextDouble() < 0.20,
                        SetThumbnailImage = Rng.NextDouble() < 0.20,
                        SetVersion        = false,
                    };

                    // Make sure we change at least one thing.
                    if (!changeItem.SetName && !changeItem.SetLocation && !changeItem.SetThumbnailImage)
                    {
                        changeItem.SetExtraData = true;
                    }

                    if (changeItem.SetName)
                    {
                        log.Trace("Changing name of identity name '{0}'.", profileClient.Profile.Name);
                        TestProfiles.Remove(profileClient.Profile.Name);

                        profileClient.Profile.Name += "-change";
                        changeItem.Name             = profileClient.Profile.Name;
                        TestProfiles.Add(profileClient.Profile.Name, profileClient);
                    }

                    if (changeItem.SetLocation)
                    {
                        log.Trace("Changing location of identity name '{0}'.", profileClient.Profile.Name);
                        if (Rng.NextDouble() < 0.30)
                        {
                            profileClient.Profile.Location.Latitude = profileClient.Profile.Location.Latitude / 2 + 1;
                        }
                        else if (Rng.NextDouble() < 0.30)
                        {
                            profileClient.Profile.Location.Longitude = profileClient.Profile.Location.Latitude / 2 + 1;
                        }
                        else
                        {
                            profileClient.Profile.Location.Latitude  = profileClient.Profile.Location.Latitude / 2 + 1;
                            profileClient.Profile.Location.Longitude = profileClient.Profile.Location.Latitude / 2 + 1;
                        }
                        changeItem.Latitude  = profileClient.Profile.Location.GetLocationTypeLatitude();
                        changeItem.Longitude = profileClient.Profile.Location.GetLocationTypeLongitude();
                    }

                    if (changeItem.SetExtraData)
                    {
                        log.Trace("Changing extra data of identity name '{0}'.", profileClient.Profile.Name);
                        if (!string.IsNullOrEmpty(profileClient.Profile.ExtraData))
                        {
                            profileClient.Profile.ExtraData = profileClient.Profile.ExtraData.Substring(0, Math.Min(10, profileClient.Profile.ExtraData.Length)) + "-change";
                        }
                        else
                        {
                            profileClient.Profile.ExtraData = "new value";
                        }
                        changeItem.ExtraData = profileClient.Profile.ExtraData;
                    }

                    if (changeItem.SetThumbnailImage)
                    {
                        log.Trace("Changing profile image of identity name '{0}'.", profileClient.Profile.Name);
                        profileClient.Profile.ProfileImage   = testImageData2;
                        profileClient.Profile.ThumbnailImage = testImageData2;
                        changeItem.ThumbnailImage            = ProtocolHelper.ByteArrayToByteString(testImageData2);
                    }

                    changedProfiles.Add(profileClient.GetIdentityId(), changeItem);

                    await profileClient.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                    bool ccheckInOk = await profileClient.CheckInAsync();

                    Message clientRequest = profileClient.MessageBuilder.CreateUpdateProfileRequest(null, changeItem.SetName ? changeItem.Name : null, changeItem.SetThumbnailImage ? profileClient.Profile.ProfileImage : null, changeItem.SetLocation ? profileClient.Profile.Location : null, changeItem.SetExtraData ? changeItem.ExtraData : null);
                    await profileClient.SendMessageAsync(clientRequest);

                    Message clientResponse = await profileClient.ReceiveMessageAsync();

                    bool cidOk     = clientResponse.Id == clientRequest.Id;
                    bool cstatusOk = clientResponse.Response.Status == Status.Ok;

                    profileClient.CloseConnection();

                    bool changeOk = ccheckInOk && cidOk && cstatusOk;

                    if (!changeOk)
                    {
                        profileChangingOk = false;
                        break;
                    }
                }

                await Task.Delay(20000);

                // Meanwhile we expect updates to arrive on our simulated profile server.
                psMessages = profileServer.GetMessageList();
                List <SharedProfileChangeItem> changeUpdates = new List <SharedProfileChangeItem>();
                foreach (IncomingServerMessage ism in psMessages)
                {
                    if (ism.Role != ServerRole.ServerNeighbor)
                    {
                        continue;
                    }
                    Message message = ism.IncomingMessage;

                    if ((message.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                        (message.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                        (message.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate))
                    {
                        foreach (SharedProfileUpdateItem updateItem in message.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                        {
                            if (updateItem.ActionTypeCase == SharedProfileUpdateItem.ActionTypeOneofCase.Change)
                            {
                                SharedProfileChangeItem changeItem = updateItem.Change;
                                changeUpdates.Add(changeItem);
                            }
                            else
                            {
                                log.Trace("Received invalid update action type {0}.", updateItem.ActionTypeCase);
                                error = true;
                                break;
                            }
                        }
                    }

                    if (error)
                    {
                        break;
                    }
                }

                receivedUpdatesOk = !error;

                updatesOk = client.CheckProfileListMatchChangeItems(changedProfiles, changeUpdates);

                bool step5Ok = profileChangingOk && receivedUpdatesOk && updatesOk;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");



                // Step 6
                log.Trace("Step 6");

                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool verifyIdentityOk = await client.VerifyIdentityAsync();

                Message request = mb.CreateStopNeighborhoodUpdatesRequest();
                await client.SendMessageAsync(request);

                Message response = await client.ReceiveMessageAsync();

                bool idOk          = response.Id == request.Id;
                bool statusOk      = response.Response.Status == Status.Ok;
                bool stopUpdatesOk = idOk && statusOk;

                client.CloseConnection();

                bool step6Ok = verifyIdentityOk && stopUpdatesOk;

                log.Trace("Step 6: {0}", step6Ok ? "PASSED" : "FAILED");



                // Step 7
                log.Trace("Step 7");

                // Add 5 more identities.
                profileCount = 5;
                error        = false;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (!await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        log.Trace("Failed to register and initialize client #{0}.", i);
                        profileClient.Dispose();
                        error = true;
                        break;
                    }

                    TestProfiles.Add(profileClient.Profile.Name, profileClient);
                }

                bool addProfilesOk = !error;


                // Cancel 5 identities.
                error        = false;
                profileCount = 5;
                for (int i = 0; i < profileCount; i++)
                {
                    int            index         = Rng.Next(TestProfiles.Count);
                    List <string>  keys          = TestProfiles.Keys.ToList();
                    ProtocolClient profileClient = TestProfiles[keys[index]];

                    if (!await profileClient.CancelHostingAgreementAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        log.Trace("Failed to cancel hosting agreement of client name '{0}'.", profileClient.Profile.Name);
                        error = true;
                        break;
                    }

                    TestProfiles.Remove(keys[index]);
                }

                bool cancelProfilesOk = !error;



                // Change 5 profiles.
                error        = false;
                profileCount = 5;
                for (int i = 0; i < profileCount; i++)
                {
                    int            index         = Rng.Next(TestProfiles.Count);
                    List <string>  keys          = TestProfiles.Keys.ToList();
                    ProtocolClient profileClient = TestProfiles[keys[index]];

                    SharedProfileChangeItem changeItem = new SharedProfileChangeItem()
                    {
                        IdentityNetworkId = ProtocolHelper.ByteArrayToByteString(profileClient.GetIdentityId()),
                        SetExtraData      = true,
                        ExtraData         = "last change",
                        SetVersion        = false,
                        SetLocation       = false,
                        SetName           = false,
                        SetThumbnailImage = false,
                    };

                    profileClient.Profile.ExtraData = changeItem.ExtraData;

                    await profileClient.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                    bool checkInOk = await profileClient.CheckInAsync();

                    Message clientRequest = profileClient.MessageBuilder.CreateUpdateProfileRequest(null, null, null, null, changeItem.ExtraData);
                    await profileClient.SendMessageAsync(clientRequest);

                    Message clientResponse = await profileClient.ReceiveMessageAsync();

                    bool cidOk     = clientResponse.Id == clientRequest.Id;
                    bool cstatusOk = clientResponse.Response.Status == Status.Ok;

                    profileClient.CloseConnection();

                    bool changeOk = checkInOk && cidOk && cstatusOk;

                    if (!changeOk)
                    {
                        log.Trace("Failed to change profile of client name '{0}'.", profileClient.Profile.Name);
                        error = true;
                        break;
                    }
                }

                bool changeProfileOk = !error;

                await Task.Delay(20000);

                // Meanwhile we expect NO update messages to arrive on our simulated profile server.
                error      = false;
                psMessages = profileServer.GetMessageList();
                foreach (IncomingServerMessage ism in psMessages)
                {
                    if (ism.Role != ServerRole.ServerNeighbor)
                    {
                        continue;
                    }
                    Message message = ism.IncomingMessage;

                    if ((message.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                        (message.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                        (message.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate))
                    {
                        error = true;
                        break;
                    }
                }
                bool noNewUpdatesOk = !error;


                bool step7Ok = addProfilesOk && cancelProfilesOk && changeProfileOk && noNewUpdatesOk;

                log.Trace("Step 7: {0}", step7Ok ? "PASSED" : "FAILED");



                // Step 8
                log.Trace("Step 8");

                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                verifyIdentityOk = await client.VerifyIdentityAsync();

                request = mb.CreateStartNeighborhoodInitializationRequest((uint)profileServer.PrimaryPort, (uint)profileServer.ServerNeighborPort);
                await client.SendMessageAsync(request);

                response = await client.ReceiveMessageAsync();

                idOk     = response.Id == request.Id;
                statusOk = response.Response.Status == Status.Ok;
                bool startNeighborhoodInitializationOk = idOk && statusOk;

                bool step8Ok = verifyIdentityOk && startNeighborhoodInitializationOk;

                log.Trace("Step 8: {0}", step8Ok ? "PASSED" : "FAILED");



                // Step 9
                log.Trace("Step 9");

                // Add 5 more identities.
                // These identities may or may not be included in the current initialization process in progress.
                List <ProtocolClient> newClients = new List <ProtocolClient>();
                profileCount = 5;
                error        = false;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (!await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        log.Trace("Failed to register and initialize client #{0}.", i);
                        profileClient.Dispose();
                        error = true;
                        break;
                    }

                    newClients.Add(profileClient);
                }

                addProfilesOk = !error;

                bool step9Ok = addProfilesOk;

                log.Trace("Step 9: {0}", step9Ok ? "PASSED" : "FAILED");



                // Step 10
                log.Trace("Step 10");


                // Wait for update request.
                Message serverRequestMessage  = null;
                Message clientResponseMessage = null;
                bool    typeOk = false;

                List <SharedProfileAddItem> receivedItems = new List <SharedProfileAddItem>();

                error = false;
                while (receivedItems.Count < TestProfiles.Count)
                {
                    serverRequestMessage = await client.ReceiveMessageAsync();

                    typeOk = serverRequestMessage.MessageTypeCase == Message.MessageTypeOneofCase.Request &&
                             serverRequestMessage.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest &&
                             serverRequestMessage.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate;

                    clientResponseMessage = mb.CreateNeighborhoodSharedProfileUpdateResponse(serverRequestMessage);
                    await client.SendMessageAsync(clientResponseMessage);


                    if (!typeOk)
                    {
                        break;
                    }

                    foreach (SharedProfileUpdateItem updateItem in serverRequestMessage.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                    {
                        if (updateItem.ActionTypeCase != SharedProfileUpdateItem.ActionTypeOneofCase.Add)
                        {
                            log.Trace("Received invalid update item action type '{0}'.", updateItem.ActionTypeCase);
                            error = true;
                            break;
                        }

                        receivedItems.Add(updateItem.Add);
                    }

                    if (error)
                    {
                        break;
                    }
                }

                log.Trace("Received {0} profiles from target profile server.", receivedItems.Count);

                bool receivedProfilesOk = false;
                if (!error)
                {
                    // As we do not know if new identities made it to the initialization process, we just try all possible combinations.
                    // First possibility is that no new clients were present in the process.
                    if (client.CheckProfileListMatchAddItems(TestProfiles, receivedItems))
                    {
                        receivedProfilesOk = true;
                    }

                    for (int i = 0; i < newClients.Count; i++)
                    {
                        ProtocolClient newClient = newClients[i];
                        TestProfiles.Add(newClient.Profile.Name, newClient);

                        // Other possibilities are that one or more clients were present in the process.
                        if (!receivedProfilesOk)
                        {
                            if (client.CheckProfileListMatchAddItems(TestProfiles, receivedItems))
                            {
                                receivedProfilesOk = true;
                            }
                        }
                    }
                }

                bool step10Ok = receivedProfilesOk;

                log.Trace("Step 10: {0}", step10Ok ? "PASSED" : "FAILED");



                // Step 11
                log.Trace("Step 11");

                // Add 5 more identities.
                profileCount = 5;
                error        = false;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (!await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        log.Trace("Failed to register and initialize client #{0}.", i);
                        profileClient.Dispose();
                        error = true;
                        break;
                    }

                    TestProfiles.Add(profileClient.Profile.Name, profileClient);
                }

                addProfilesOk = !error;

                bool step11Ok = addProfilesOk;

                log.Trace("Step 11: {0}", step11Ok ? "PASSED" : "FAILED");



                // Step 12
                log.Trace("Step 12");

                client.CloseConnection();
                bool step12Ok = true;

                log.Trace("Step 12: {0}", step12Ok ? "PASSED" : "FAILED");



                // Step 13
                log.Trace("Step 13");

                // Add 5 more identities.
                profileCount = 5;
                error        = false;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (!await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        log.Trace("Failed to register and initialize client #{0}.", i);
                        profileClient.Dispose();
                        error = true;
                        break;
                    }

                    TestProfiles.Add(profileClient.Profile.Name, profileClient);
                }

                addProfilesOk = !error;

                await Task.Delay(20000);

                // Meanwhile we expect NO update messages to arrive on our simulated profile server.
                error      = false;
                psMessages = profileServer.GetMessageList();
                foreach (IncomingServerMessage ism in psMessages)
                {
                    if (ism.Role != ServerRole.ServerNeighbor)
                    {
                        continue;
                    }
                    Message message = ism.IncomingMessage;

                    if ((message.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                        (message.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                        (message.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate))
                    {
                        error = true;
                        break;
                    }
                }
                noNewUpdatesOk = !error;

                bool step13Ok = addProfilesOk && noNewUpdatesOk;

                log.Trace("Step 13: {0}", step13Ok ? "PASSED" : "FAILED");



                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok && step6Ok && step7Ok && step8Ok && step9Ok && step10Ok && step11Ok && step12Ok && step13Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            foreach (ProtocolClient protocolClient in TestProfiles.Values)
            {
                protocolClient.Dispose();
            }

            if (profileServer != null)
            {
                profileServer.Shutdown();
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #7
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp          = (IPAddress)ArgumentValues["Server IP"];
            int       ClNonCustomerPort = (int)ArgumentValues["clNonCustomer Port"];
            int       ClCustomerPort    = (int)ArgumentValues["clCustomer Port"];

            log.Trace("(ServerIp:'{0}',ClNonCustomerPort:{1},ClCustomerPort:{2})", ServerIp, ClNonCustomerPort, ClCustomerPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                await client.ConnectAsync(ServerIp, ClNonCustomerPort, true);

                bool establishHostingOk = await client.EstablishHostingAsync();

                // Step 1 Acceptance
                bool step1Ok = establishHostingOk;
                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");

                client.CloseConnection();


                // Step 2
                log.Trace("Step 2");
                await client.ConnectAsync(ServerIp, ClCustomerPort, true);

                bool startConversationOk = await client.StartConversationAsync();

                Message requestMessage = mb.CreateCheckInRequest(client.Challenge);
                // Invalidate the signature.
                byte[] signature = requestMessage.Request.ConversationRequest.Signature.ToByteArray();
                byte[] sig32     = new byte[32];
                Array.Copy(signature, sig32, sig32.Length);
                requestMessage.Request.ConversationRequest.Signature = ProtocolHelper.ByteArrayToByteString(sig32);

                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk      = responseMessage.Id == requestMessage.Id;
                bool statusOk  = responseMessage.Response.Status == Status.ErrorInvalidSignature;
                bool checkInOk = idOk && statusOk;

                // Step 2 Acceptance
                bool step2Ok = startConversationOk && checkInOk;
                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");

                Passed = step1Ok && step2Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #8
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient clientCallee           = new ProtocolClient();
            ProtocolClient clientCalleeAppService = new ProtocolClient(0, SemVer.V100, clientCallee.GetIdentityKeys());

            ProtocolClient clientCaller           = new ProtocolClient();
            ProtocolClient clientCallerAppService = new ProtocolClient(0, SemVer.V100, clientCaller.GetIdentityKeys());

            try
            {
                MessageBuilder mbCallee           = clientCallee.MessageBuilder;
                MessageBuilder mbCalleeAppService = clientCalleeAppService.MessageBuilder;

                MessageBuilder mbCaller           = clientCaller.MessageBuilder;
                MessageBuilder mbCallerAppService = clientCallerAppService.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                byte[] pubKeyCallee     = clientCallee.GetIdentityKeys().PublicKey;
                byte[] identityIdCallee = clientCallee.GetIdentityId();

                byte[] pubKeyCaller     = clientCaller.GetIdentityKeys().PublicKey;
                byte[] identityIdCaller = clientCaller.GetIdentityId();


                await clientCallee.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await clientCallee.ListServerPorts(rolePorts);

                clientCallee.CloseConnection();


                // Establish hosting agreement for identity 1.
                await clientCallee.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHostingOk = await clientCallee.EstablishHostingAsync();

                clientCallee.CloseConnection();


                // Check-in and initialize the profile of identity 1.

                await clientCallee.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await clientCallee.CheckInAsync();

                bool initializeProfileOk = await clientCallee.InitializeProfileAsync("Test Identity", null, new GpsLocation(0, 0), null);


                // Add application service to the current session.
                string serviceName     = "Test Service";
                bool   addAppServiceOk = await clientCallee.AddApplicationServicesAsync(new List <string>() { serviceName });


                // Step 1 Acceptance
                bool step1Ok = listPortsOk && establishHostingOk && checkInOk && initializeProfileOk && addAppServiceOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await clientCaller.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool verifyIdentityOk = await clientCaller.VerifyIdentityAsync();


                Message requestMessage = mbCaller.CreateGetIdentityInformationRequest(identityIdCallee, false, false, true);
                await clientCaller.SendMessageAsync(requestMessage);

                Message responseMessage = await clientCaller.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.Ok;

                bool isHostedOk = responseMessage.Response.SingleResponse.GetIdentityInformation.IsHosted;
                bool isOnlineOk = responseMessage.Response.SingleResponse.GetIdentityInformation.IsOnline;

                byte[] receivedPubKey = responseMessage.Response.SingleResponse.GetIdentityInformation.IdentityPublicKey.ToByteArray();
                bool   pubKeyOk       = StructuralComparisons.StructuralComparer.Compare(receivedPubKey, pubKeyCallee) == 0;

                HashSet <string> receivedAsList    = new HashSet <string>(responseMessage.Response.SingleResponse.GetIdentityInformation.ApplicationServices, StringComparer.Ordinal);
                bool             appServiceReadyOk = receivedAsList.Contains(serviceName);

                bool getInfoOk = idOk && statusOk && isHostedOk && isOnlineOk && pubKeyOk && appServiceReadyOk;


                // Step 2 Acceptance
                bool step2Ok = verifyIdentityOk && getInfoOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");



                // Step 3
                log.Trace("Step 3");
                requestMessage = mbCaller.CreateCallIdentityApplicationServiceRequest(identityIdCallee, serviceName);
                await clientCaller.SendMessageAsync(requestMessage);

                // Step 3 Acceptance
                bool step3Ok = true;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");



                // Step 4
                log.Trace("Step 4");
                Message serverRequestMessage = await clientCallee.ReceiveMessageAsync();

                receivedPubKey = serverRequestMessage.Request.ConversationRequest.IncomingCallNotification.CallerPublicKey.ToByteArray();
                pubKeyOk       = StructuralComparisons.StructuralComparer.Compare(receivedPubKey, pubKeyCaller) == 0;
                bool serviceNameOk = serverRequestMessage.Request.ConversationRequest.IncomingCallNotification.ServiceName == serviceName;

                bool incomingCallNotificationOk = pubKeyOk && serviceNameOk;

                byte[] calleeToken = serverRequestMessage.Request.ConversationRequest.IncomingCallNotification.CalleeToken.ToByteArray();

                Message serverResponseMessage = mbCallee.CreateIncomingCallNotificationResponse(serverRequestMessage);
                await clientCallee.SendMessageAsync(serverResponseMessage);


                // Connect to clAppService and send initialization message.
                await clientCalleeAppService.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCallee = mbCalleeAppService.CreateApplicationServiceSendMessageRequest(calleeToken, null);
                await clientCalleeAppService.SendMessageAsync(requestMessageAppServiceCallee);


                // Step 4 Acceptance
                bool step4Ok = incomingCallNotificationOk;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");


                // Step 5
                log.Trace("Step 5");
                responseMessage = await clientCaller.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;
                byte[] callerToken = responseMessage.Response.ConversationResponse.CallIdentityApplicationService.CallerToken.ToByteArray();

                bool callIdentityOk = idOk && statusOk;

                // Connect to clAppService and send initialization message.
                await clientCallerAppService.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, null);
                await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);

                Message responseMessageAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCaller.Id == requestMessageAppServiceCaller.Id;
                statusOk = responseMessageAppServiceCaller.Response.Status == Status.Ok;

                bool initAppServiceMessageOk = idOk && statusOk;


                // And close connection to clNonCustomer port.
                clientCaller.CloseConnection();


                // Step 5 Acceptance
                bool step5Ok = callIdentityOk && initAppServiceMessageOk;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");



                // Step 6
                log.Trace("Step 6");
                Message responseMessageAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCallee.Id == requestMessageAppServiceCallee.Id;
                statusOk = responseMessageAppServiceCallee.Response.Status == Status.Ok;

                bool typeOk = (responseMessageAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Response) &&
                              (responseMessageAppServiceCallee.Response.ConversationTypeCase == Response.ConversationTypeOneofCase.SingleResponse) &&
                              (responseMessageAppServiceCallee.Response.SingleResponse.ResponseTypeCase == SingleResponse.ResponseTypeOneofCase.ApplicationServiceSendMessage);

                bool appServiceSendOk = idOk && statusOk && typeOk;

                // Step 6 Acceptance
                bool step6Ok = appServiceSendOk;

                log.Trace("Step 6: {0}", step6Ok ? "PASSED" : "FAILED");


                // Step 7
                log.Trace("Step 7");
                string callerMessage1 = "Message #1 to callee.";
                byte[] messageBytes   = Encoding.UTF8.GetBytes(callerMessage1);
                requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, messageBytes);
                uint callerMessage1Id = requestMessageAppServiceCaller.Id;
                await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);

                string callerMessage2 = "Message #2 to callee.";
                messageBytes = Encoding.UTF8.GetBytes(callerMessage2);
                requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, messageBytes);
                uint callerMessage2Id = requestMessageAppServiceCaller.Id;
                await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);

                string callerMessage3 = "Message #3 to callee.";
                messageBytes = Encoding.UTF8.GetBytes(callerMessage3);
                requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, messageBytes);
                uint callerMessage3Id = requestMessageAppServiceCaller.Id;
                await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);


                // Step 7 Acceptance
                bool step7Ok = true;

                log.Trace("Step 7: {0}", step7Ok ? "PASSED" : "FAILED");


                // Step 8
                log.Trace("Step 8");
                // Receive message #1.
                Message serverRequestAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                SemVer receivedVersion = new SemVer(serverRequestAppServiceCallee.Request.SingleRequest.Version);
                bool   versionOk       = receivedVersion.Equals(SemVer.V100);

                typeOk = (serverRequestAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                         (serverRequestAppServiceCallee.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                         (serverRequestAppServiceCallee.Request.SingleRequest.RequestTypeCase == SingleRequest.RequestTypeOneofCase.ApplicationServiceReceiveMessageNotification);

                string receivedMessage = Encoding.UTF8.GetString(serverRequestAppServiceCallee.Request.SingleRequest.ApplicationServiceReceiveMessageNotification.Message.ToByteArray());
                bool   messageOk       = receivedMessage == callerMessage1;

                bool receiveMessageOk1 = versionOk && typeOk && messageOk;


                // ACK message #1.
                Message serverResponseAppServiceCallee = mbCalleeAppService.CreateApplicationServiceReceiveMessageNotificationResponse(serverRequestAppServiceCallee);
                await clientCalleeAppService.SendMessageAsync(serverResponseAppServiceCallee);


                // Receive message #2.
                serverRequestAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                receivedVersion = new SemVer(serverRequestAppServiceCallee.Request.SingleRequest.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                typeOk = (serverRequestAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                         (serverRequestAppServiceCallee.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                         (serverRequestAppServiceCallee.Request.SingleRequest.RequestTypeCase == SingleRequest.RequestTypeOneofCase.ApplicationServiceReceiveMessageNotification);

                receivedMessage = Encoding.UTF8.GetString(serverRequestAppServiceCallee.Request.SingleRequest.ApplicationServiceReceiveMessageNotification.Message.ToByteArray());
                messageOk       = receivedMessage == callerMessage2;

                bool receiveMessageOk2 = versionOk && typeOk && messageOk;


                // ACK message #2.
                serverResponseAppServiceCallee = mbCalleeAppService.CreateApplicationServiceReceiveMessageNotificationResponse(serverRequestAppServiceCallee);
                await clientCalleeAppService.SendMessageAsync(serverResponseAppServiceCallee);


                // Send our message #1.
                string calleeMessage1 = "Message #1 to CALLER.";
                messageBytes = Encoding.UTF8.GetBytes(calleeMessage1);
                requestMessageAppServiceCallee = mbCalleeAppService.CreateApplicationServiceSendMessageRequest(calleeToken, messageBytes);
                uint calleeMessage1Id = requestMessageAppServiceCallee.Id;
                await clientCalleeAppService.SendMessageAsync(requestMessageAppServiceCallee);


                await Task.Delay(3000);


                // Send ping request.
                byte[] payload = Encoding.UTF8.GetBytes("test");
                requestMessageAppServiceCallee = mbCalleeAppService.CreatePingRequest(payload);
                await clientCalleeAppService.SendMessageAsync(requestMessageAppServiceCallee);



                // Receive message #3.
                serverRequestAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                receivedVersion = new SemVer(serverRequestAppServiceCallee.Request.SingleRequest.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                typeOk = (serverRequestAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                         (serverRequestAppServiceCallee.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                         (serverRequestAppServiceCallee.Request.SingleRequest.RequestTypeCase == SingleRequest.RequestTypeOneofCase.ApplicationServiceReceiveMessageNotification);

                receivedMessage = Encoding.UTF8.GetString(serverRequestAppServiceCallee.Request.SingleRequest.ApplicationServiceReceiveMessageNotification.Message.ToByteArray());
                messageOk       = receivedMessage == callerMessage3;

                bool receiveMessageOk3 = versionOk && typeOk && messageOk;


                // Read ping response.
                responseMessageAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                idOk            = responseMessageAppServiceCallee.Id == requestMessageAppServiceCallee.Id;
                statusOk        = responseMessageAppServiceCallee.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessageAppServiceCallee.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);


                typeOk = (responseMessageAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Response) &&
                         (responseMessageAppServiceCallee.Response.ConversationTypeCase == Response.ConversationTypeOneofCase.SingleResponse) &&
                         (responseMessageAppServiceCallee.Response.SingleResponse.ResponseTypeCase == SingleResponse.ResponseTypeOneofCase.Ping);

                byte[] receivedPayload = responseMessageAppServiceCallee.Response.SingleResponse.Ping.Payload.ToByteArray();
                bool   payloadOk       = StructuralComparisons.StructuralComparer.Compare(receivedPayload, payload) == 0;

                bool pingOk = idOk && statusOk && versionOk && typeOk && payloadOk;


                // ACK message #2.
                serverResponseAppServiceCallee = mbCalleeAppService.CreateApplicationServiceReceiveMessageNotificationResponse(serverRequestAppServiceCallee);
                await clientCalleeAppService.SendMessageAsync(serverResponseAppServiceCallee);



                // Send our message #2.
                string calleeMessage2 = "Message #2 to CALLER.";
                messageBytes = Encoding.UTF8.GetBytes(calleeMessage2);
                requestMessageAppServiceCallee = mbCalleeAppService.CreateApplicationServiceSendMessageRequest(calleeToken, messageBytes);
                uint calleeMessage2Id = requestMessageAppServiceCallee.Id;
                await clientCalleeAppService.SendMessageAsync(requestMessageAppServiceCallee);

                await Task.Delay(3000);


                // Step 8 Acceptance
                bool step8Ok = receiveMessageOk1 && receiveMessageOk2 && pingOk && receiveMessageOk3;

                log.Trace("Step 8: {0}", step8Ok ? "PASSED" : "FAILED");



                // Step 9
                log.Trace("Step 9");
                // Receive ACK message #1.
                responseMessageAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                idOk            = responseMessageAppServiceCaller.Id == callerMessage1Id;
                statusOk        = responseMessageAppServiceCaller.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessageAppServiceCaller.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                bool receiveAck1Ok = idOk && statusOk && versionOk;



                // Receive ACK message #2.
                responseMessageAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                idOk            = responseMessageAppServiceCaller.Id == callerMessage2Id;
                statusOk        = responseMessageAppServiceCaller.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessageAppServiceCaller.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                bool receiveAck2Ok = idOk && statusOk && versionOk;



                // Receive message #1 from callee.
                Message serverRequestAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                receivedVersion = new SemVer(serverRequestAppServiceCaller.Request.SingleRequest.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                typeOk = (serverRequestAppServiceCaller.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                         (serverRequestAppServiceCaller.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                         (serverRequestAppServiceCaller.Request.SingleRequest.RequestTypeCase == SingleRequest.RequestTypeOneofCase.ApplicationServiceReceiveMessageNotification);

                receivedMessage = Encoding.UTF8.GetString(serverRequestAppServiceCaller.Request.SingleRequest.ApplicationServiceReceiveMessageNotification.Message.ToByteArray());
                messageOk       = receivedMessage == calleeMessage1;

                receiveMessageOk1 = versionOk && typeOk && messageOk;



                // ACK message #1 from callee.
                Message serverResponseAppServiceCaller = mbCallerAppService.CreateApplicationServiceReceiveMessageNotificationResponse(serverRequestAppServiceCaller);
                await clientCallerAppService.SendMessageAsync(serverResponseAppServiceCaller);



                // Receive ACK message #3.
                responseMessageAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                idOk            = responseMessageAppServiceCaller.Id == callerMessage3Id;
                statusOk        = responseMessageAppServiceCaller.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessageAppServiceCaller.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                bool receiveAck3Ok = idOk && statusOk && versionOk;



                // Receive message #2 from callee.
                serverRequestAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                receivedVersion = new SemVer(serverRequestAppServiceCaller.Request.SingleRequest.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                typeOk = (serverRequestAppServiceCaller.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                         (serverRequestAppServiceCaller.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                         (serverRequestAppServiceCaller.Request.SingleRequest.RequestTypeCase == SingleRequest.RequestTypeOneofCase.ApplicationServiceReceiveMessageNotification);

                receivedMessage = Encoding.UTF8.GetString(serverRequestAppServiceCaller.Request.SingleRequest.ApplicationServiceReceiveMessageNotification.Message.ToByteArray());
                messageOk       = receivedMessage == calleeMessage2;

                receiveMessageOk2 = versionOk && typeOk && messageOk;



                // ACK message #2 from callee.
                serverResponseAppServiceCaller = mbCallerAppService.CreateApplicationServiceReceiveMessageNotificationResponse(serverRequestAppServiceCaller);
                await clientCallerAppService.SendMessageAsync(serverResponseAppServiceCaller);


                // Step 9 Acceptance
                bool step9Ok = receiveAck1Ok && receiveAck2Ok && receiveMessageOk1 && receiveAck3Ok && receiveMessageOk2;

                log.Trace("Step 9: {0}", step9Ok ? "PASSED" : "FAILED");



                // Step 10
                log.Trace("Step 10");

                // Receive ACK message #1.
                responseMessageAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                idOk            = responseMessageAppServiceCallee.Id == calleeMessage1Id;
                statusOk        = responseMessageAppServiceCallee.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessageAppServiceCallee.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                receiveAck1Ok = idOk && statusOk && versionOk;

                // Receive ACK message #2.
                responseMessageAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                idOk            = responseMessageAppServiceCallee.Id == calleeMessage2Id;
                statusOk        = responseMessageAppServiceCallee.Response.Status == Status.Ok;
                receivedVersion = new SemVer(responseMessageAppServiceCallee.Response.SingleResponse.Version);
                versionOk       = receivedVersion.Equals(SemVer.V100);

                receiveAck2Ok = idOk && statusOk && versionOk;


                // Step 10 Acceptance
                bool step10Ok = receiveAck1Ok && receiveAck2Ok;

                log.Trace("Step 10: {0}", step10Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok && step6Ok && step7Ok && step8Ok && step9Ok && step10Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            clientCallee.Dispose();
            clientCalleeAppService.Dispose();
            clientCaller.Dispose();
            clientCallerAppService.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #9
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();


                bool   profileInitializationOk = true;
                byte[] testImageData           = File.ReadAllBytes(Path.Combine("images", TestName + ".jpg"));

                int profileIndex = 1;
                int profileCount = 10;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (!await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }

                    TestProfiles.Add(profileClient.Profile.Name, profileClient);
                }

                bool step1Ok = listPortsOk && profileInitializationOk;
                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool verifyIdentityOk = await client.VerifyIdentityAsync();

                // Start neighborhood initialization process.
                Message requestMessage = mb.CreateStartNeighborhoodInitializationRequest(1, 1);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.Ok;
                bool startNeighborhoodInitializationOk = idOk && statusOk;


                // Wait for update request.
                Message serverRequestMessage  = null;
                Message clientResponseMessage = null;
                bool    typeOk = false;

                List <SharedProfileAddItem> receivedItems = new List <SharedProfileAddItem>();

                bool error = false;
                while (receivedItems.Count < TestProfiles.Count)
                {
                    serverRequestMessage = await client.ReceiveMessageAsync();

                    typeOk = serverRequestMessage.MessageTypeCase == Message.MessageTypeOneofCase.Request &&
                             serverRequestMessage.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest &&
                             serverRequestMessage.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate;

                    clientResponseMessage = mb.CreateNeighborhoodSharedProfileUpdateResponse(serverRequestMessage);
                    await client.SendMessageAsync(clientResponseMessage);


                    if (!typeOk)
                    {
                        break;
                    }

                    foreach (SharedProfileUpdateItem updateItem in serverRequestMessage.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                    {
                        if (updateItem.ActionTypeCase != SharedProfileUpdateItem.ActionTypeOneofCase.Add)
                        {
                            log.Trace("Received invalid update item action type '{0}'.", updateItem.ActionTypeCase);
                            error = true;
                            break;
                        }

                        receivedItems.Add(updateItem.Add);
                    }

                    if (error)
                    {
                        break;
                    }
                }

                log.Trace("Received {0} profiles from target profile server.", receivedItems.Count);
                bool receivedProfilesOk = !error && client.CheckProfileListMatchAddItems(TestProfiles, receivedItems);

                log.Trace("Waiting 450 seconds ...");
                await Task.Delay(450 * 1000);

                client.CloseConnection();

                bool step2Ok = verifyIdentityOk && startNeighborhoodInitializationOk && receivedProfilesOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                // Step 3
                log.Trace("Step 3");
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool neighborhoodInitializationProcessOk = await client.NeighborhoodInitializationProcessAsync(1, 1, TestProfiles);

                bool step3Ok = neighborhoodInitializationProcessOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok && step3Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            foreach (ProtocolClient protocolClient in TestProfiles.Values)
            {
                protocolClient.Dispose();
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #10
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");

                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();


                bool   profileInitializationOk = true;
                byte[] testImageData           = File.ReadAllBytes(Path.Combine("images", TestName + ".jpg"));

                int profileIndex = 1;
                int profileCount = 10;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        TestProfiles.Add(profileClient.Profile.Name, profileClient);
                    }
                    else
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }
                }


                bool step1Ok = listPortsOk && profileInitializationOk;
                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool neighborhoodInitializationProcessOk = await client.NeighborhoodInitializationProcessAsync(1, 1, TestProfiles);

                client.CloseConnection();

                bool step2Ok = neighborhoodInitializationProcessOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                // Step 3
                log.Trace("Step 3");

                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool verifyIdentityOk = await client.VerifyIdentityAsync();

                // Start neighborhood initialization process.
                Message requestMessage = client.MessageBuilder.CreateStartNeighborhoodInitializationRequest(2, 2);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.ErrorAlreadyExists;
                bool startNeighborhoodInitializationOk = idOk && statusOk;

                bool step3Ok = profileInitializationOk && startNeighborhoodInitializationOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");



                Passed = step1Ok && step2Ok && step3Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            foreach (ProtocolClient protocolClient in TestProfiles.Values)
            {
                protocolClient.Dispose();
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #11
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp      = (IPAddress)ArgumentValues["Node IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(NodeIp:'{0}',PrimaryPort:{1})", NodeIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient clientCallee            = new ProtocolClient();
            ProtocolClient clientCallee1AppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCallee.GetIdentityKeys());
            ProtocolClient clientCallee2AppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCallee.GetIdentityKeys());

            ProtocolClient clientCaller1           = new ProtocolClient();
            ProtocolClient clientCaller1AppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCaller1.GetIdentityKeys());

            ProtocolClient clientCaller2           = new ProtocolClient();
            ProtocolClient clientCaller2AppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCaller2.GetIdentityKeys());

            try
            {
                MessageBuilder mbCallee            = clientCallee.MessageBuilder;
                MessageBuilder mbCallee1AppService = clientCallee1AppService.MessageBuilder;
                MessageBuilder mbCallee2AppService = clientCallee2AppService.MessageBuilder;

                MessageBuilder mbCaller1           = clientCaller1.MessageBuilder;
                MessageBuilder mbCaller1AppService = clientCaller1AppService.MessageBuilder;

                MessageBuilder mbCaller2           = clientCaller2.MessageBuilder;
                MessageBuilder mbCaller2AppService = clientCaller2AppService.MessageBuilder;


                // Step 1
                log.Trace("Step 1");

                byte[] pubKeyCallee     = clientCallee.GetIdentityKeys().PublicKey;
                byte[] identityIdCallee = clientCallee.GetIdentityId();

                byte[] pubKeyCaller1     = clientCaller1.GetIdentityKeys().PublicKey;
                byte[] identityIdCaller1 = clientCaller1.GetIdentityId();

                byte[] pubKeyCaller2     = clientCaller2.GetIdentityKeys().PublicKey;
                byte[] identityIdCaller2 = clientCaller2.GetIdentityId();

                // Get port list.

                await clientCallee.ConnectAsync(NodeIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await clientCallee.ListNodePorts(rolePorts);

                clientCallee.CloseConnection();


                // Establish home node for identity 1.
                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHomeNodeOk = await clientCallee.EstablishHomeNodeAsync();

                clientCallee.CloseConnection();


                // Check-in and initialize the profile of identity 1.

                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await clientCallee.CheckInAsync();

                bool initializeProfileOk = await clientCallee.InitializeProfileAsync("Test Identity", null, 0x12345678, null);


                // Add application service to the current session.
                string serviceName     = "Test Service";
                bool   addAppServiceOk = await clientCallee.AddApplicationServicesAsync(new List <string>() { serviceName });


                // Step 1 Acceptance
                bool step1Ok = listPortsOk && establishHomeNodeOk && checkInOk && initializeProfileOk && addAppServiceOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await clientCaller1.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool verifyIdentityOk1 = await clientCaller1.VerifyIdentityAsync();

                Message requestMessage       = mbCaller1.CreateCallIdentityApplicationServiceRequest(identityIdCallee, serviceName);
                uint    initMessageCaller1Id = requestMessage.Id;
                await clientCaller1.SendMessageAsync(requestMessage);


                await clientCaller2.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool verifyIdentityOk2 = await clientCaller2.VerifyIdentityAsync();

                requestMessage = mbCaller2.CreateCallIdentityApplicationServiceRequest(identityIdCallee, serviceName);
                uint initMessageCaller2Id = requestMessage.Id;
                await clientCaller2.SendMessageAsync(requestMessage);



                // Step 2 Acceptance
                bool step2Ok = verifyIdentityOk1 && verifyIdentityOk2;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");



                // Step 3
                log.Trace("Step 3");
                Message nodeRequestMessage = await clientCallee.ReceiveMessageAsync();

                byte[] receivedPubKey = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CallerPublicKey.ToByteArray();
                bool   pubKeyOk       = StructuralComparisons.StructuralComparer.Compare(receivedPubKey, pubKeyCaller1) == 0;
                bool   serviceNameOk  = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.ServiceName == serviceName;

                bool incomingCallNotificationOk1 = pubKeyOk && serviceNameOk;

                byte[] calleeToken1 = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CalleeToken.ToByteArray();

                Message nodeResponseMessage = mbCallee.CreateIncomingCallNotificationResponse(nodeRequestMessage);
                await clientCallee.SendMessageAsync(nodeResponseMessage);



                nodeRequestMessage = await clientCallee.ReceiveMessageAsync();

                receivedPubKey = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CallerPublicKey.ToByteArray();
                pubKeyOk       = StructuralComparisons.StructuralComparer.Compare(receivedPubKey, pubKeyCaller2) == 0;
                serviceNameOk  = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.ServiceName == serviceName;

                bool incomingCallNotificationOk2 = pubKeyOk && serviceNameOk;

                byte[] calleeToken2 = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CalleeToken.ToByteArray();

                nodeResponseMessage = mbCallee.CreateIncomingCallNotificationResponse(nodeRequestMessage);
                await clientCallee.SendMessageAsync(nodeResponseMessage);



                // Connect to clAppService and send initialization message (FIRST connection).
                await clientCallee1AppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCallee = mbCallee1AppService.CreateApplicationServiceSendMessageRequest(calleeToken1, null);
                await clientCallee1AppService.SendMessageAsync(requestMessageAppServiceCallee);


                // Connect to clAppService and send initialization message (SECOND connection).
                await clientCallee2AppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                requestMessageAppServiceCallee = mbCallee2AppService.CreateApplicationServiceSendMessageRequest(calleeToken2, null);
                await clientCallee2AppService.SendMessageAsync(requestMessageAppServiceCallee);


                // Step 3 Acceptance
                bool step3Ok = incomingCallNotificationOk1 && incomingCallNotificationOk2;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");



                // Step 4
                log.Trace("Step 4");
                Message responseMessage = await clientCaller1.ReceiveMessageAsync();

                bool   idOk         = responseMessage.Id == initMessageCaller1Id;
                bool   statusOk     = responseMessage.Response.Status == Status.Ok;
                byte[] callerToken1 = responseMessage.Response.ConversationResponse.CallIdentityApplicationService.CallerToken.ToByteArray();

                bool callIdentityOk1 = idOk && statusOk;

                // Connect to clAppService and send initialization message.
                await clientCaller1AppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCaller = mbCaller1AppService.CreateApplicationServiceSendMessageRequest(callerToken1, null);
                await clientCaller1AppService.SendMessageAsync(requestMessageAppServiceCaller);

                Message responseMessageAppServiceCaller = await clientCaller1AppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCaller.Id == requestMessageAppServiceCaller.Id;
                statusOk = responseMessageAppServiceCaller.Response.Status == Status.Ok;

                bool initAppServiceMessageOk1 = idOk && statusOk;



                responseMessage = await clientCaller2.ReceiveMessageAsync();

                idOk     = responseMessage.Id == initMessageCaller1Id;
                statusOk = responseMessage.Response.Status == Status.Ok;
                byte[] callerToken2 = responseMessage.Response.ConversationResponse.CallIdentityApplicationService.CallerToken.ToByteArray();

                bool callIdentityOk2 = idOk && statusOk;

                // Connect to clAppService and send initialization message.
                await clientCaller2AppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                requestMessageAppServiceCaller = mbCaller2AppService.CreateApplicationServiceSendMessageRequest(callerToken2, null);
                await clientCaller2AppService.SendMessageAsync(requestMessageAppServiceCaller);

                responseMessageAppServiceCaller = await clientCaller2AppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCaller.Id == requestMessageAppServiceCaller.Id;
                statusOk = responseMessageAppServiceCaller.Response.Status == Status.Ok;

                bool initAppServiceMessageOk2 = idOk && statusOk;


                // Step 4 Acceptance
                bool step4Ok = callIdentityOk1 && initAppServiceMessageOk1 && callIdentityOk2 && initAppServiceMessageOk2;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");



                // Step 5
                log.Trace("Step 5");
                Message responseMessageAppServiceCallee = await clientCallee1AppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCallee.Id == requestMessageAppServiceCallee.Id;
                statusOk = responseMessageAppServiceCallee.Response.Status == Status.Ok;

                bool typeOk = (responseMessageAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Response) &&
                              (responseMessageAppServiceCallee.Response.ConversationTypeCase == Response.ConversationTypeOneofCase.SingleResponse) &&
                              (responseMessageAppServiceCallee.Response.SingleResponse.ResponseTypeCase == SingleResponse.ResponseTypeOneofCase.ApplicationServiceSendMessage);

                bool appServiceSendOk1 = idOk && statusOk && typeOk;


                responseMessageAppServiceCallee = await clientCallee2AppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCallee.Id == requestMessageAppServiceCallee.Id;
                statusOk = responseMessageAppServiceCallee.Response.Status == Status.Ok;

                typeOk = (responseMessageAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Response) &&
                         (responseMessageAppServiceCallee.Response.ConversationTypeCase == Response.ConversationTypeOneofCase.SingleResponse) &&
                         (responseMessageAppServiceCallee.Response.SingleResponse.ResponseTypeCase == SingleResponse.ResponseTypeOneofCase.ApplicationServiceSendMessage);

                bool appServiceSendOk2 = idOk && statusOk && typeOk;

                // Step 5 Acceptance
                bool step5Ok = appServiceSendOk1 && appServiceSendOk2;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");



                // Step 6
                log.Trace("Step 6");
                string caller1Message1 = "Message #1 to callee from caller1.";
                byte[] messageBytes    = Encoding.UTF8.GetBytes(caller1Message1);
                requestMessageAppServiceCaller = mbCaller1AppService.CreateApplicationServiceSendMessageRequest(callerToken1, messageBytes);
                uint callerMessage1Id = requestMessageAppServiceCaller.Id;
                await clientCaller1AppService.SendMessageAsync(requestMessageAppServiceCaller);


                // Step 6 Acceptance
                bool step6Ok = true;

                log.Trace("Step 6: {0}", step6Ok ? "PASSED" : "FAILED");


                // Step 7
                log.Trace("Step 7");
                // Receive message #1.
                Message nodeRequestAppServiceCallee = await clientCallee1AppService.ReceiveMessageAsync();

                byte[] receivedVersion = nodeRequestAppServiceCallee.Request.SingleRequest.Version.ToByteArray();
                bool   versionOk       = StructuralComparisons.StructuralComparer.Compare(receivedVersion, new byte[] { 1, 0, 0 }) == 0;

                typeOk = (nodeRequestAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                         (nodeRequestAppServiceCallee.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                         (nodeRequestAppServiceCallee.Request.SingleRequest.RequestTypeCase == SingleRequest.RequestTypeOneofCase.ApplicationServiceReceiveMessageNotification);

                string receivedMessage = Encoding.UTF8.GetString(nodeRequestAppServiceCallee.Request.SingleRequest.ApplicationServiceReceiveMessageNotification.Message.ToByteArray());
                bool   messageOk       = receivedMessage == caller1Message1;

                bool receiveMessageOk = versionOk && typeOk && messageOk;


                // ACK message #1.
                Message nodeResponseAppServiceCallee = mbCallee1AppService.CreateApplicationServiceReceiveMessageNotificationResponse(nodeRequestAppServiceCallee);
                await clientCallee1AppService.SendMessageAsync(nodeResponseAppServiceCallee);



                // Send invalid message - over the FIRST connection with token from the SECOND connection.
                await Task.Delay(3000);

                string calleeMessage = "Invalid Message";
                messageBytes = Encoding.UTF8.GetBytes(calleeMessage);
                requestMessageAppServiceCallee = mbCallee1AppService.CreateApplicationServiceSendMessageRequest(calleeToken2, messageBytes);
                await clientCallee1AppService.SendMessageAsync(requestMessageAppServiceCallee);

                Message responseAppServiceCallee = await clientCallee1AppService.ReceiveMessageAsync();

                idOk     = responseAppServiceCallee.Id == requestMessageAppServiceCallee.Id;
                statusOk = responseAppServiceCallee.Response.Status == Status.ErrorNotFound;

                bool sendMessageOk = idOk && statusOk;


                // Step 7 Acceptance
                bool step7Ok = sendMessageOk;

                log.Trace("Step 7: {0}", step7Ok ? "PASSED" : "FAILED");


                // Step 8
                log.Trace("Step 8");
                await Task.Delay(3000);

                string caller2Message1 = "Message #1 to callee from caller2.";
                messageBytes = Encoding.UTF8.GetBytes(caller2Message1);
                requestMessageAppServiceCaller = mbCaller2AppService.CreateApplicationServiceSendMessageRequest(callerToken2, messageBytes);

                // Either the third client is disconnected and this should prevent sending a message or receiving a response,
                // OR just the relay was destroyed and the client will receive error not found.
                bool disconnectOk = false;
                messageOk = false;
                try
                {
                    await clientCaller2AppService.SendMessageAsync(requestMessageAppServiceCaller);

                    responseMessage = await clientCaller2AppService.ReceiveMessageAsync();

                    idOk      = responseMessage.Id == requestMessageAppServiceCaller.Id;
                    statusOk  = responseMessage.Response.Status == Status.ErrorNotFound;
                    messageOk = idOk && statusOk;
                }
                catch
                {
                    log.Trace("Expected exception occurred.");
                    disconnectOk = true;
                }

                // Step 8 Acceptance
                bool step8Ok = disconnectOk || messageOk;

                log.Trace("Step 8: {0}", step8Ok ? "PASSED" : "FAILED");


                // Step 9
                log.Trace("Step 9");

                // Receive ACK message #1.
                responseMessageAppServiceCaller = await clientCaller1AppService.ReceiveMessageAsync();

                idOk            = responseMessageAppServiceCaller.Id == callerMessage1Id;
                statusOk        = responseMessageAppServiceCaller.Response.Status == Status.Ok;
                receivedVersion = responseMessageAppServiceCaller.Response.SingleResponse.Version.ToByteArray();
                versionOk       = StructuralComparisons.StructuralComparer.Compare(receivedVersion, new byte[] { 1, 0, 0 }) == 0;

                bool receiveAckOk = idOk && statusOk && versionOk;

                // Step 9 Acceptance
                bool step9Ok = receiveAckOk;

                log.Trace("Step 9: {0}", step9Ok ? "PASSED" : "FAILED");

                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok && step6Ok && step7Ok && step8Ok && step9Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            clientCallee.Dispose();
            clientCallee1AppService.Dispose();
            clientCallee2AppService.Dispose();
            clientCaller1.Dispose();
            clientCaller1AppService.Dispose();
            clientCaller2.Dispose();
            clientCaller2AppService.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #12
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp            = (IPAddress)ArgumentValues["Node IP"];
            int       ClNonCustomerPort = (int)ArgumentValues["clNonCustomer Port"];
            int       ClCustomerPort    = (int)ArgumentValues["clCustomer Port"];

            log.Trace("(NodeIp:'{0}',ClNonCustomerPort:{1},ClCustomerPort:{2})", NodeIp, ClNonCustomerPort, ClCustomerPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb             = client.MessageBuilder;
                byte[]         testPubKey     = client.GetIdentityKeys().PublicKey;
                byte[]         testIdentityId = client.GetIdentityId();

                // Step 1
                await client.ConnectAsync(NodeIp, ClNonCustomerPort, true);

                bool establishHomeNodeOk = await client.EstablishHomeNodeAsync();

                // Step 1 Acceptance
                bool step1Ok = establishHomeNodeOk;
                client.CloseConnection();


                // Step 2
                await client.ConnectAsync(NodeIp, ClCustomerPort, true);

                bool checkInOk = await client.CheckInAsync();

                Message requestMessage = mb.CreateUpdateProfileRequest(null, "Test Identity", null, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk      = responseMessage.Id == requestMessage.Id;
                bool statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                bool detailsOk = responseMessage.Response.Details == "setVersion";

                bool updateProfileOk1 = idOk && statusOk && detailsOk;


                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, null, null, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "setName";

                bool updateProfileOk2 = idOk && statusOk && detailsOk;


                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, "Test Identity", null, null, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "setLocation";

                bool updateProfileOk3 = idOk && statusOk && detailsOk;


                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 0, 0, 0 }, "Test Identity", null, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "version";

                bool updateProfileOk4 = idOk && statusOk && detailsOk;


                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 255, 0, 0 }, "Test Identity", null, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "version";

                bool updateProfileOk5 = idOk && statusOk && detailsOk;


                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, "", null, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "name";

                bool updateProfileOk6 = idOk && statusOk && detailsOk;

                string name = new string('a', 100);
                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, name, null, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "name";

                bool updateProfileOk7 = idOk && statusOk && detailsOk;


                name           = new string('ɐ', 50);
                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, name, null, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "name";

                bool updateProfileOk8 = idOk && statusOk && detailsOk;


                byte[] imageData = File.ReadAllBytes(string.Format("images{0}HN04007-too-big.jpg", Path.DirectorySeparatorChar));
                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, "Test Identity", imageData, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "image";

                bool updateProfileOk9 = idOk && statusOk && detailsOk;


                imageData      = File.ReadAllBytes(string.Format("images{0}HN04007-not-image.jpg", Path.DirectorySeparatorChar));
                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, "Test Identity", imageData, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "image";

                bool updateProfileOk10 = idOk && statusOk && detailsOk;


                string extraData = new string('a', 300);
                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, "Test Identity", null, 0x12345678, extraData);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "extraData";

                bool updateProfileOk11 = idOk && statusOk && detailsOk;


                extraData      = new string('ɐ', 150);
                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, "Test Identity", null, 0x12345678, extraData);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "extraData";

                bool updateProfileOk12 = idOk && statusOk && detailsOk;


                requestMessage = mb.CreateUpdateProfileRequest(new byte[] { 1, 0, 0 }, "Test Identity", null, 0x12345678, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool updateProfileOk13 = idOk && statusOk;


                requestMessage = mb.CreateUpdateProfileRequest(null, null, null, null, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "set*";

                bool updateProfileOk14 = idOk && statusOk && detailsOk;


                // Step 2 Acceptance
                bool step2Ok = checkInOk && updateProfileOk1 && updateProfileOk2 && updateProfileOk3 && updateProfileOk4 && updateProfileOk5 && updateProfileOk6 && updateProfileOk7 && updateProfileOk8 &&
                               updateProfileOk9 && updateProfileOk10 && updateProfileOk11 && updateProfileOk12 && updateProfileOk13 && updateProfileOk14;


                Passed = step1Ok && step2Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #13
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();


                ProfilePublicKeys = new List <byte[]>();

                bool profileInitializationOk = true;
                for (int i = 0; i < ProfileNames.Count; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    ProfilePublicKeys.Add(profileClient.GetIdentityKeys().PublicKey);

                    await profileClient.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                    bool establishHostingOk = await profileClient.EstablishHostingAsync(ProfileTypes[i]);

                    profileClient.CloseConnection();


                    await profileClient.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                    bool checkInOk = await profileClient.CheckInAsync();

                    byte[] imageData = ProfileImages[i] != null?File.ReadAllBytes(ProfileImages[i]) : null;

                    bool initializeProfileOk = await profileClient.InitializeProfileAsync(ProfileNames[i], imageData, ProfileLocations[i], ProfileExtraData[i]);

                    profileInitializationOk = establishHostingOk && checkInOk && initializeProfileOk;
                    profileClient.Dispose();

                    if (!profileInitializationOk)
                    {
                        break;
                    }
                }

                bool step1Ok = listPortsOk && profileInitializationOk;
                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool verifyIdentityOk = await client.VerifyIdentityAsync();

                // Start neighborhood initialization process.
                Message requestMessage = mb.CreateStartNeighborhoodInitializationRequest(1, 1);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.Ok;
                bool startNeighborhoodInitializationOk = idOk && statusOk;

                // Wait for update request.
                Message serverRequestMessage = await client.ReceiveMessageAsync();

                bool typeOk = serverRequestMessage.MessageTypeCase == Message.MessageTypeOneofCase.Request &&
                              serverRequestMessage.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest &&
                              serverRequestMessage.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate;

                bool listMatch = CheckProfileList(serverRequestMessage.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items);
                bool startNeighborhoodInitializationResponseOk = typeOk && listMatch;

                Message clientResponseMessage = mb.CreateNeighborhoodSharedProfileUpdateResponse(serverRequestMessage);
                await client.SendMessageAsync(clientResponseMessage);


                // Wait for finish request.
                serverRequestMessage = await client.ReceiveMessageAsync();

                typeOk = serverRequestMessage.MessageTypeCase == Message.MessageTypeOneofCase.Request &&
                         serverRequestMessage.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest &&
                         serverRequestMessage.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.FinishNeighborhoodInitialization;

                bool finishNeighborhoodInitializationResponseOk = typeOk;

                clientResponseMessage = mb.CreateFinishNeighborhoodInitializationResponse(serverRequestMessage);
                await client.SendMessageAsync(clientResponseMessage);

                // Step 2 Acceptance
                bool step2Ok = verifyIdentityOk && startNeighborhoodInitializationOk && startNeighborhoodInitializationResponseOk && finishNeighborhoodInitializationResponseOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();


            log.Trace("(-):{0}", res);
            return(res);
        }
Example #14
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();
            ProtocolClient issuer = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");

                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();

                // Establish hosting agreement for primary client.
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHostingOk = await client.EstablishHostingAsync("Primary");

                client.CloseConnection();

                // Check in primary client.
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await client.CheckInAsync();

                // Step 1 Acceptance
                bool step1Ok = listPortsOk && establishHostingOk && checkInOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");

                byte[] primaryPubKey = client.GetIdentityKeys().PublicKey;
                string type          = "Card Type A";

                DateTime validFrom = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                DateTime validTo   = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);

                bool reqOk = true;
                for (int i = 0; i < RequestCount; i++)
                {
                    SignedRelationshipCard signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                    byte[] applicationId = new byte[] { (byte)i };
                    CardApplicationInformation cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                    Message requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                    await client.SendMessageAsync(requestMessage);

                    Message responseMessage = await client.ReceiveMessageAsync();

                    bool idOk     = responseMessage.Id == requestMessage.Id;
                    bool statusOk = i < 100 ? (responseMessage.Response.Status == Status.Ok) : responseMessage.Response.Status == Status.ErrorQuotaExceeded;

                    reqOk = idOk && statusOk;
                    if (!reqOk)
                    {
                        break;
                    }
                }

                // Step 2 Acceptance
                bool step2Ok = reqOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();
            issuer.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #15
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp          = (IPAddress)ArgumentValues["Server IP"];
            int       ClNonCustomerPort = (int)ArgumentValues["clNonCustomer Port"];

            log.Trace("(ServerIp:'{0}',ClNonCustomerPort:{1})", ServerIp, ClNonCustomerPort);

            bool res = false;

            Passed = false;

            ProtocolClient client1 = new ProtocolClient();
            MessageBuilder mb1     = client1.MessageBuilder;

            // Second client will use the same identity as the first client.
            ProtocolClient client2 = new ProtocolClient(0, SemVer.V100, client1.GetIdentityKeys());
            MessageBuilder mb2     = client2.MessageBuilder;

            try
            {
                // Step 1
                await client1.ConnectAsync(ServerIp, ClNonCustomerPort, true);

                bool startConversationOk = await client1.StartConversationAsync();

                Message requestMessage = mb1.CreateVerifyIdentityRequest(client1.Challenge);
                await client1.SendMessageAsync(requestMessage);

                Message responseMessage = await client1.ReceiveMessageAsync();

                bool idOk             = responseMessage.Id == requestMessage.Id;
                bool statusOk         = responseMessage.Response.Status == Status.Ok;
                bool verifyIdentityOk = idOk && statusOk;

                // Step 1 Acceptance
                bool step1Ok = startConversationOk && verifyIdentityOk;



                // Step 2
                await client2.ConnectAsync(ServerIp, ClNonCustomerPort, true);

                startConversationOk = await client2.StartConversationAsync();

                requestMessage = mb2.CreateVerifyIdentityRequest(client2.Challenge);
                await client2.SendMessageAsync(requestMessage);

                responseMessage = await client2.ReceiveMessageAsync();

                idOk             = responseMessage.Id == requestMessage.Id;
                statusOk         = responseMessage.Response.Status == Status.Ok;
                verifyIdentityOk = idOk && statusOk;

                // Step 2 Acceptance
                bool step2Ok = startConversationOk && verifyIdentityOk;



                // Step 3
                byte[] payload = Encoding.UTF8.GetBytes("test");
                requestMessage = mb1.CreatePingRequest(payload);
                await client1.SendMessageAsync(requestMessage);

                responseMessage = await client1.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                byte[] payloadReceived = responseMessage.Response.SingleResponse.Ping.Payload.ToByteArray();
                bool   payloadOk       = StructuralComparisons.StructuralComparer.Compare(payload, payloadReceived) == 0;

                // Step 3 Acceptance
                bool step3Ok = idOk && statusOk && payloadOk;


                Passed = step1Ok && step2Ok && step3Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client1.Dispose();
            client2.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #16
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];
            int       BasePort    = (int)ArgumentValues["Base Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1},BasePort:{2})", ServerIp, PrimaryPort, BasePort);

            bool res = false;

            Passed = false;

            ProtocolClient client        = new ProtocolClient();
            ProfileServer  profileServer = null;

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();


                bool   profileInitializationOk = true;
                byte[] testImageData           = File.ReadAllBytes(Path.Combine("images", TestName + ".jpg"));

                int profileIndex = 1;
                int profileCount = 10;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (!await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }

                    TestProfiles.Add(profileClient.Profile.Name, profileClient);
                }

                profileServer = new ProfileServer("TestServer", ServerIp, BasePort, client.GetIdentityKeys());
                bool serverStartOk = profileServer.Start();

                bool step1Ok = listPortsOk && profileInitializationOk && serverStartOk;
                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.SrNeighbor], true);

                bool verifyIdentityOk = await client.VerifyIdentityAsync();

                // Start neighborhood initialization process.
                Message requestMessage = mb.CreateStartNeighborhoodInitializationRequest((uint)profileServer.PrimaryPort, (uint)profileServer.ServerNeighborPort);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.Ok;
                bool startNeighborhoodInitializationOk = idOk && statusOk;

                bool step2Ok = verifyIdentityOk && startNeighborhoodInitializationOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                // Step 3
                log.Trace("Step 3");

                profileInitializationOk = true;
                profileCount            = 5;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (!await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }

                    TestProfiles.Add(profileClient.Profile.Name, profileClient);
                }

                bool step3Ok = profileInitializationOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");



                // Step 4
                log.Trace("Step 4");

                List <SharedProfileAddItem> remoteProfiles = new List <SharedProfileAddItem>();

                // Wait for update request.
                Message serverRequestMessage  = null;
                Message clientResponseMessage = null;
                bool    typeOk = false;

                List <SharedProfileAddItem> receivedItems = new List <SharedProfileAddItem>();

                bool error = false;
                while (receivedItems.Count < 10)
                {
                    serverRequestMessage = await client.ReceiveMessageAsync();

                    typeOk = serverRequestMessage.MessageTypeCase == Message.MessageTypeOneofCase.Request &&
                             serverRequestMessage.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest &&
                             serverRequestMessage.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate;

                    clientResponseMessage = mb.CreateNeighborhoodSharedProfileUpdateResponse(serverRequestMessage);
                    await client.SendMessageAsync(clientResponseMessage);


                    if (!typeOk)
                    {
                        break;
                    }

                    foreach (SharedProfileUpdateItem updateItem in serverRequestMessage.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                    {
                        if (updateItem.ActionTypeCase != SharedProfileUpdateItem.ActionTypeOneofCase.Add)
                        {
                            log.Trace("Received invalid update item action type '{0}'.", updateItem.ActionTypeCase);
                            error = true;
                            break;
                        }

                        receivedItems.Add(updateItem.Add);
                    }

                    if (error)
                    {
                        break;
                    }
                }

                log.Trace("Received {0} profiles from target profile server.", receivedItems.Count);
                bool receivedProfilesOk = !error;
                remoteProfiles.AddRange(receivedItems);

                bool step4Ok = receivedProfilesOk;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");


                // Step 5
                log.Trace("Step 5");

                profileInitializationOk = true;
                profileCount            = 5;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (!await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }

                    TestProfiles.Add(profileClient.Profile.Name, profileClient);
                }

                bool step5Ok = profileInitializationOk;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");



                // Step 6
                log.Trace("Step 6");

                // Wait for finish request.
                serverRequestMessage = await client.ReceiveMessageAsync();

                typeOk = serverRequestMessage.MessageTypeCase == Message.MessageTypeOneofCase.Request &&
                         serverRequestMessage.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest &&
                         serverRequestMessage.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.FinishNeighborhoodInitialization;

                bool finishNeighborhoodInitializationResponseOk = typeOk;

                clientResponseMessage = mb.CreateFinishNeighborhoodInitializationResponse(serverRequestMessage);
                await client.SendMessageAsync(clientResponseMessage);

                client.CloseConnection();

                bool step6Ok = finishNeighborhoodInitializationResponseOk;

                log.Trace("Step 6: {0}", step6Ok ? "PASSED" : "FAILED");



                // Step 7
                log.Trace("Step 7");

                profileInitializationOk = true;
                profileCount            = 5;
                for (int i = 0; i < profileCount; i++)
                {
                    ProtocolClient profileClient = new ProtocolClient();
                    profileClient.InitializeRandomProfile(profileIndex, testImageData);
                    profileIndex++;

                    if (!await profileClient.RegisterAndInitializeProfileAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], (int)rolePorts[ServerRoleType.ClCustomer]))
                    {
                        profileClient.Dispose();
                        profileInitializationOk = false;
                        break;
                    }

                    TestProfiles.Add(profileClient.Profile.Name, profileClient);
                }


                await Task.Delay(20000);


                // Meanwhile we expect updates to arrive on our simulated profile server.
                error = false;
                List <IncomingServerMessage> psMessages = profileServer.GetMessageList();
                List <SharedProfileAddItem>  addUpdates = new List <SharedProfileAddItem>();
                foreach (IncomingServerMessage ism in psMessages)
                {
                    if (ism.Role != ServerRole.ServerNeighbor)
                    {
                        continue;
                    }
                    Message message = ism.IncomingMessage;

                    if ((message.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                        (message.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                        (message.Request.ConversationRequest.RequestTypeCase == ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate))
                    {
                        foreach (SharedProfileUpdateItem updateItem in message.Request.ConversationRequest.NeighborhoodSharedProfileUpdate.Items)
                        {
                            if (updateItem.ActionTypeCase == SharedProfileUpdateItem.ActionTypeOneofCase.Add)
                            {
                                SharedProfileAddItem addItem = updateItem.Add;
                                addUpdates.Add(addItem);
                            }
                            else
                            {
                                log.Trace("Received invalid update action type {0}.", updateItem.ActionTypeCase);
                                error = true;
                                break;
                            }
                        }
                    }

                    if (error)
                    {
                        break;
                    }
                }

                bool receivedUpdatesOk = !error;

                remoteProfiles.AddRange(addUpdates);
                bool profilesOk = client.CheckProfileListMatchAddItems(TestProfiles, remoteProfiles);

                bool step7Ok = profileInitializationOk && receivedUpdatesOk && profilesOk;

                log.Trace("Step 7: {0}", step7Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok && step6Ok && step7Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            foreach (ProtocolClient protocolClient in TestProfiles.Values)
            {
                protocolClient.Dispose();
            }

            if (profileServer != null)
            {
                profileServer.Shutdown();
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #17
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp      = (IPAddress)ArgumentValues["Node IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(NodeIp:'{0}',PrimaryPort:{1})", NodeIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient clientCallee           = new ProtocolClient();
            ProtocolClient clientCalleeAppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCallee.GetIdentityKeys());

            ProtocolClient clientCaller           = new ProtocolClient();
            ProtocolClient clientCallerAppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCaller.GetIdentityKeys());

            try
            {
                MessageBuilder mbCallee           = clientCallee.MessageBuilder;
                MessageBuilder mbCalleeAppService = clientCalleeAppService.MessageBuilder;

                MessageBuilder mbCaller           = clientCaller.MessageBuilder;
                MessageBuilder mbCallerAppService = clientCallerAppService.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                byte[] pubKeyCallee     = clientCallee.GetIdentityKeys().PublicKey;
                byte[] identityIdCallee = clientCallee.GetIdentityId();

                byte[] pubKeyCaller     = clientCaller.GetIdentityKeys().PublicKey;
                byte[] identityIdCaller = clientCaller.GetIdentityId();


                await clientCallee.ConnectAsync(NodeIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await clientCallee.ListNodePorts(rolePorts);

                clientCallee.CloseConnection();


                // Establish home node for identity 1.
                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHomeNodeOk = await clientCallee.EstablishHomeNodeAsync();

                clientCallee.CloseConnection();


                // Check-in and initialize the profile of identity 1.

                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await clientCallee.CheckInAsync();

                bool initializeProfileOk = await clientCallee.InitializeProfileAsync("Test Identity", null, 0x12345678, null);


                // Add application service to the current session.
                string serviceName     = "Test Service";
                bool   addAppServiceOk = await clientCallee.AddApplicationServicesAsync(new List <string>() { serviceName });


                // Step 1 Acceptance
                bool step1Ok = listPortsOk && establishHomeNodeOk && checkInOk && initializeProfileOk && addAppServiceOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await clientCaller.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool verifyIdentityOk = await clientCaller.VerifyIdentityAsync();

                Message requestMessage = mbCaller.CreateCallIdentityApplicationServiceRequest(identityIdCallee, serviceName);
                await clientCaller.SendMessageAsync(requestMessage);


                // Step 2 Acceptance
                bool step2Ok = verifyIdentityOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");



                // Step 3
                log.Trace("Step 3");
                Message nodeRequestMessage = await clientCallee.ReceiveMessageAsync();

                byte[] receivedPubKey = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CallerPublicKey.ToByteArray();
                bool   pubKeyOk       = StructuralComparisons.StructuralComparer.Compare(receivedPubKey, pubKeyCaller) == 0;
                bool   serviceNameOk  = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.ServiceName == serviceName;

                bool incomingCallNotificationOk = pubKeyOk && serviceNameOk;

                byte[] calleeToken = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CalleeToken.ToByteArray();

                Message nodeResponseMessage = mbCallee.CreateIncomingCallNotificationResponse(nodeRequestMessage);
                await clientCallee.SendMessageAsync(nodeResponseMessage);


                // Connect to clAppService and send initialization message.
                await clientCalleeAppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCallee = mbCalleeAppService.CreateApplicationServiceSendMessageRequest(calleeToken, null);
                await clientCalleeAppService.SendMessageAsync(requestMessageAppServiceCallee);


                // Step 3 Acceptance
                bool step3Ok = incomingCallNotificationOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");


                // Step 4
                log.Trace("Step 4");
                Message responseMessage = await clientCaller.ReceiveMessageAsync();

                bool   idOk        = responseMessage.Id == requestMessage.Id;
                bool   statusOk    = responseMessage.Response.Status == Status.Ok;
                byte[] callerToken = responseMessage.Response.ConversationResponse.CallIdentityApplicationService.CallerToken.ToByteArray();

                bool callIdentityOk = idOk && statusOk;

                // Connect to clAppService and send initialization message.
                await clientCallerAppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, null);
                await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);

                Message responseMessageAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCaller.Id == requestMessageAppServiceCaller.Id;
                statusOk = responseMessageAppServiceCaller.Response.Status == Status.Ok;

                bool initAppServiceMessageOk = idOk && statusOk;

                // And close connection to clNonCustomer port.
                clientCaller.CloseConnection();


                // Step 4 Acceptance
                bool step4Ok = callIdentityOk && initAppServiceMessageOk;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");



                // Step 5
                log.Trace("Step 5");
                Message responseMessageAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCallee.Id == requestMessageAppServiceCallee.Id;
                statusOk = responseMessageAppServiceCallee.Response.Status == Status.Ok;

                bool typeOk = (responseMessageAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Response) &&
                              (responseMessageAppServiceCallee.Response.ConversationTypeCase == Response.ConversationTypeOneofCase.SingleResponse) &&
                              (responseMessageAppServiceCallee.Response.SingleResponse.ResponseTypeCase == SingleResponse.ResponseTypeOneofCase.ApplicationServiceSendMessage);

                bool appServiceSendOk = idOk && statusOk && typeOk;

                // Step 5 Acceptance
                bool step5Ok = appServiceSendOk;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");



                // Step 6
                log.Trace("Step 6");
                string callerMessage1 = "Message #1 to callee.";
                byte[] messageBytes   = Encoding.UTF8.GetBytes(callerMessage1);
                requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, messageBytes);
                uint callerMessage1Id = requestMessageAppServiceCaller.Id;
                await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);


                // Step 6 Acceptance
                bool step6Ok = true;

                log.Trace("Step 6: {0}", step6Ok ? "PASSED" : "FAILED");


                // Step 7
                log.Trace("Step 7");
                // Receive message #1.
                Message nodeRequestAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                byte[] receivedVersion = nodeRequestAppServiceCallee.Request.SingleRequest.Version.ToByteArray();
                bool   versionOk       = StructuralComparisons.StructuralComparer.Compare(receivedVersion, new byte[] { 1, 0, 0 }) == 0;

                typeOk = (nodeRequestAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                         (nodeRequestAppServiceCallee.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                         (nodeRequestAppServiceCallee.Request.SingleRequest.RequestTypeCase == SingleRequest.RequestTypeOneofCase.ApplicationServiceReceiveMessageNotification);

                string receivedMessage = Encoding.UTF8.GetString(nodeRequestAppServiceCallee.Request.SingleRequest.ApplicationServiceReceiveMessageNotification.Message.ToByteArray());
                bool   messageOk       = receivedMessage == callerMessage1;

                bool receiveMessageOk = versionOk && typeOk && messageOk;


                // ACK message #1.
                Message nodeResponseAppServiceCallee = mbCalleeAppService.CreateApplicationServiceReceiveMessageNotificationResponse(nodeRequestAppServiceCallee);
                await clientCalleeAppService.SendMessageAsync(nodeResponseAppServiceCallee);


                // Send our message #1.
                string calleeMessage1 = "Message #1 to CALLER.";
                messageBytes = Encoding.UTF8.GetBytes(calleeMessage1);
                requestMessageAppServiceCallee = mbCalleeAppService.CreateApplicationServiceSendMessageRequest(calleeToken, messageBytes);
                uint calleeMessage1Id = requestMessageAppServiceCallee.Id;
                await clientCalleeAppService.SendMessageAsync(requestMessageAppServiceCallee);

                clientCalleeAppService.CloseConnection();


                // Step 7 Acceptance
                bool step7Ok = receiveMessageOk;

                log.Trace("Step 7: {0}", step7Ok ? "PASSED" : "FAILED");


                // Step 8
                log.Trace("Step 8");
                // Receive ACK message #1.
                responseMessageAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                idOk            = responseMessageAppServiceCaller.Id == callerMessage1Id;
                statusOk        = responseMessageAppServiceCaller.Response.Status == Status.Ok;
                receivedVersion = responseMessageAppServiceCaller.Response.SingleResponse.Version.ToByteArray();
                versionOk       = StructuralComparisons.StructuralComparer.Compare(receivedVersion, new byte[] { 1, 0, 0 }) == 0;

                bool receiveAckOk = idOk && statusOk && versionOk;


                // Receive message #1 from callee.
                Message nodeRequestAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                receivedVersion = nodeRequestAppServiceCaller.Request.SingleRequest.Version.ToByteArray();
                versionOk       = StructuralComparisons.StructuralComparer.Compare(receivedVersion, new byte[] { 1, 0, 0 }) == 0;

                typeOk = (nodeRequestAppServiceCaller.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                         (nodeRequestAppServiceCaller.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                         (nodeRequestAppServiceCaller.Request.SingleRequest.RequestTypeCase == SingleRequest.RequestTypeOneofCase.ApplicationServiceReceiveMessageNotification);

                receivedMessage = Encoding.UTF8.GetString(nodeRequestAppServiceCaller.Request.SingleRequest.ApplicationServiceReceiveMessageNotification.Message.ToByteArray());
                messageOk       = receivedMessage == calleeMessage1;

                receiveMessageOk = versionOk && typeOk && messageOk;


                // ACK message #1 from callee.
                Message nodeResponseAppServiceCaller = mbCallerAppService.CreateApplicationServiceReceiveMessageNotificationResponse(nodeRequestAppServiceCaller);


                // We should be disconnected now, send or receive should throw.

                bool disconnectedOk = false;
                try
                {
                    await clientCallerAppService.SendMessageAsync(nodeResponseAppServiceCaller);

                    string callerMessage2 = "Message #2 to callee.";
                    messageBytes = Encoding.UTF8.GetBytes(callerMessage2);
                    requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, messageBytes);
                    await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);

                    await clientCallerAppService.ReceiveMessageAsync();
                }
                catch
                {
                    log.Trace("Expected exception occurred.");
                    disconnectedOk = true;
                }


                // Step 8 Acceptance
                bool step8Ok = receiveAckOk && receiveMessageOk && disconnectedOk;

                log.Trace("Step 8: {0}", step8Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok && step6Ok && step7Ok && step8Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            clientCallee.Dispose();
            clientCalleeAppService.Dispose();
            clientCaller.Dispose();
            clientCallerAppService.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #18
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp          = (IPAddress)ArgumentValues["Server IP"];
            int       ClNonCustomerPort = (int)ArgumentValues["clNonCustomer Port"];
            int       ClCustomerPort    = (int)ArgumentValues["clCustomer Port"];

            log.Trace("(ServerIp:'{0}',ClNonCustomerPort:{1},ClCustomerPort:{2})", ServerIp, ClNonCustomerPort, ClCustomerPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                await client.ConnectAsync(ServerIp, ClNonCustomerPort, true);

                bool establishHostingOk = await client.EstablishHostingAsync();

                // Step 1 Acceptance
                bool step1Ok = establishHostingOk;
                client.CloseConnection();


                // Step 2
                await client.ConnectAsync(ServerIp, ClCustomerPort, true);

                bool checkInOk = await client.CheckInAsync();

                Message requestMessage = mb.CreateCancelHostingAgreementRequest(null);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.Ok;

                bool cancelHostingAgreementOk = idOk && statusOk;

                // Step 2 Acceptance
                bool step2Ok = checkInOk && cancelHostingAgreementOk;

                client.CloseConnection();

                // Step 3
                await client.ConnectAsync(ServerIp, ClCustomerPort, true);

                bool startConversationOk = await client.StartConversationAsync();

                requestMessage = mb.CreateCheckInRequest(client.Challenge);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorNotFound;
                checkInOk = idOk && statusOk;

                // Step 3 Acceptance
                bool step3Ok = startConversationOk && checkInOk;

                client.CloseConnection();



                // Step 4
                await client.ConnectAsync(ServerIp, ClNonCustomerPort, true);

                establishHostingOk = await client.EstablishHostingAsync();

                // Step 4 Acceptance
                bool step4Ok = establishHostingOk;
                client.CloseConnection();



                // Step 5
                await client.ConnectAsync(ServerIp, ClCustomerPort, true);

                checkInOk = await client.CheckInAsync();

                // Step 5 Acceptance
                bool step5Ok = checkInOk;


                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #19
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public async Task <bool> RunAsyncInternal(int Index)
        {
            IPAddress NodeIp      = (IPAddress)ArgumentValues["Node IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(NodeIp:'{0}',PrimaryPort:{1},Index:{2})", NodeIp, PrimaryPort, Index);

            bool res = false;

            PassedArray[Index] = false;

            ProtocolClient clientCallee           = new ProtocolClient();
            ProtocolClient clientCalleeAppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCallee.GetIdentityKeys());

            ProtocolClient clientCaller           = new ProtocolClient();
            ProtocolClient clientCallerAppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCaller.GetIdentityKeys());

            try
            {
                MessageBuilder mbCallee           = clientCallee.MessageBuilder;
                MessageBuilder mbCalleeAppService = clientCalleeAppService.MessageBuilder;

                MessageBuilder mbCaller           = clientCaller.MessageBuilder;
                MessageBuilder mbCallerAppService = clientCallerAppService.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                byte[] pubKeyCallee     = clientCallee.GetIdentityKeys().PublicKey;
                byte[] identityIdCallee = clientCallee.GetIdentityId();

                byte[] pubKeyCaller     = clientCaller.GetIdentityKeys().PublicKey;
                byte[] identityIdCaller = clientCaller.GetIdentityId();


                await clientCallee.ConnectAsync(NodeIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await clientCallee.ListNodePorts(rolePorts);

                clientCallee.CloseConnection();


                // Establish home node for identity 1.
                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHomeNodeOk = await clientCallee.EstablishHomeNodeAsync();

                clientCallee.CloseConnection();


                // Check-in and initialize the profile of identity 1.

                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await clientCallee.CheckInAsync();

                bool initializeProfileOk = await clientCallee.InitializeProfileAsync("Test Identity", null, 0x12345678, null);


                // Add application service to the current session.
                string serviceName     = "Test Service";
                bool   addAppServiceOk = await clientCallee.AddApplicationServicesAsync(new List <string>() { serviceName });


                // Step 1 Acceptance
                bool step1Ok = listPortsOk && establishHomeNodeOk && checkInOk && initializeProfileOk && addAppServiceOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await clientCaller.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool verifyIdentityOk = await clientCaller.VerifyIdentityAsync();

                Message requestMessage = mbCaller.CreateCallIdentityApplicationServiceRequest(identityIdCallee, serviceName);
                await clientCaller.SendMessageAsync(requestMessage);


                // Step 2 Acceptance
                bool step2Ok = verifyIdentityOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");



                // Step 3
                log.Trace("Step 3");
                Message nodeRequestMessage = await clientCallee.ReceiveMessageAsync();

                byte[] receivedPubKey = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CallerPublicKey.ToByteArray();
                bool   pubKeyOk       = StructuralComparisons.StructuralComparer.Compare(receivedPubKey, pubKeyCaller) == 0;
                bool   serviceNameOk  = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.ServiceName == serviceName;

                bool incomingCallNotificationOk = pubKeyOk && serviceNameOk;

                byte[] calleeToken = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CalleeToken.ToByteArray();

                Message nodeResponseMessage = mbCallee.CreateIncomingCallNotificationResponse(nodeRequestMessage);
                await clientCallee.SendMessageAsync(nodeResponseMessage);


                // Connect to clAppService and send initialization message.
                await clientCalleeAppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCallee = mbCalleeAppService.CreateApplicationServiceSendMessageRequest(calleeToken, null);
                await clientCalleeAppService.SendMessageAsync(requestMessageAppServiceCallee);


                // Step 3 Acceptance
                bool step3Ok = incomingCallNotificationOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");


                // Step 4
                log.Trace("Step 4");
                Message responseMessage = await clientCaller.ReceiveMessageAsync();

                bool   idOk        = responseMessage.Id == requestMessage.Id;
                bool   statusOk    = responseMessage.Response.Status == Status.Ok;
                byte[] callerToken = responseMessage.Response.ConversationResponse.CallIdentityApplicationService.CallerToken.ToByteArray();

                bool callIdentityOk = idOk && statusOk;

                // Connect to clAppService and send initialization message.
                await clientCallerAppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, null);
                await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);

                Message responseMessageAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCaller.Id == requestMessageAppServiceCaller.Id;
                statusOk = responseMessageAppServiceCaller.Response.Status == Status.Ok;

                bool initAppServiceMessageOk = idOk && statusOk;

                // And close connection to clNonCustomer port.
                clientCaller.CloseConnection();


                // Step 4 Acceptance
                bool step4Ok = callIdentityOk && initAppServiceMessageOk;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");



                // Step 5
                log.Trace("Step 5");
                Message responseMessageAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCallee.Id == requestMessageAppServiceCallee.Id;
                statusOk = responseMessageAppServiceCallee.Response.Status == Status.Ok;

                bool typeOk = (responseMessageAppServiceCallee.MessageTypeCase == Message.MessageTypeOneofCase.Response) &&
                              (responseMessageAppServiceCallee.Response.ConversationTypeCase == Response.ConversationTypeOneofCase.SingleResponse) &&
                              (responseMessageAppServiceCallee.Response.SingleResponse.ResponseTypeCase == SingleResponse.ResponseTypeOneofCase.ApplicationServiceSendMessage);

                bool appServiceSendOk = idOk && statusOk && typeOk;

                // Step 5 Acceptance
                bool step5Ok = appServiceSendOk;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");



                // Step 6
                UnfinishedRequestCounter callerCounter = new UnfinishedRequestCounter()
                {
                    Name = string.Format("Caller-{0}", Index)
                };
                UnfinishedRequestCounter calleeCounter = new UnfinishedRequestCounter()
                {
                    Name = string.Format("Callee-{0}", Index)
                };
                SemaphoreSlim callerWriteLock = new SemaphoreSlim(1);
                SemaphoreSlim calleeWriteLock = new SemaphoreSlim(1);

                Task <byte[]> messageReceivingTaskCaller = MessageReceivingLoop(clientCallerAppService, mbCallerAppService, "CallerReceiving", callerWriteLock, callerCounter);
                Task <byte[]> messageReceivingTaskCallee = MessageReceivingLoop(clientCalleeAppService, mbCalleeAppService, "CalleeReceiving", calleeWriteLock, calleeCounter);

                Task <byte[]> messageSendingTaskCaller = MessageSendingLoop(clientCallerAppService, mbCallerAppService, "CallerSending", callerToken, callerWriteLock, callerCounter);
                Task <byte[]> messageSendingTaskCallee = MessageSendingLoop(clientCalleeAppService, mbCalleeAppService, "CalleeSending", calleeToken, calleeWriteLock, calleeCounter);

                byte[] callerSendMessageHash = messageSendingTaskCaller.Result;
                byte[] calleeSendMessageHash = messageSendingTaskCallee.Result;

                byte[] callerReceiveMessageHash = messageReceivingTaskCaller.Result;
                byte[] calleeReceiveMessageHash = messageReceivingTaskCallee.Result;


                bool callerMessageHashOk = StructuralComparisons.StructuralComparer.Compare(callerSendMessageHash, calleeReceiveMessageHash) == 0;
                bool calleeMessageHashOk = StructuralComparisons.StructuralComparer.Compare(calleeSendMessageHash, callerReceiveMessageHash) == 0;


                // Step 6 Acceptance
                bool step6Ok = callerMessageHashOk && calleeMessageHashOk;

                log.Trace("Step 6: {0}", step6Ok ? "PASSED" : "FAILED");


                PassedArray[Index] = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok && step6Ok;
                log.Trace("PassedArray[{0}] = {1}", Index, PassedArray[Index]);

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            clientCallee.Dispose();
            clientCalleeAppService.Dispose();
            clientCaller.Dispose();
            clientCallerAppService.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #20
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp     = (IPAddress)ArgumentValues["Server IP"];
            int       NeighborPort = (int)ArgumentValues["srNeighbor Port"];

            log.Trace("(ServerIp:'{0}',NeighborPort:{1})", ServerIp, NeighborPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                await client.ConnectAsync(ServerIp, NeighborPort, true);

                Message requestMessage = mb.CreateStartNeighborhoodInitializationRequest(1, 1);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.ErrorUnauthorized;
                bool startNeighborhoodInitializationOk = idOk && statusOk;


                requestMessage = mb.CreateFinishNeighborhoodInitializationRequest();
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.ErrorUnauthorized;
                bool finishNeighborhoodInitializationOk = idOk && statusOk;


                requestMessage = mb.CreateNeighborhoodSharedProfileUpdateRequest(null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.ErrorUnauthorized;
                bool neighborhoodSharedProfileUpdateOk = idOk && statusOk;


                requestMessage = mb.CreateStopNeighborhoodUpdatesRequest();
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.ErrorUnauthorized;
                bool stopNeighborhoodUpdatesOk = idOk && statusOk;

                // Step 1 Acceptance

                Passed = startNeighborhoodInitializationOk && finishNeighborhoodInitializationOk && neighborhoodSharedProfileUpdateOk && stopNeighborhoodUpdatesOk;
                res    = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();


            log.Trace("(-):{0}", res);
            return(res);
        }
Example #21
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient clientCallee           = new ProtocolClient();
            ProtocolClient clientCalleeAppService = new ProtocolClient(0, SemVer.V100, clientCallee.GetIdentityKeys());

            ProtocolClient clientCaller           = new ProtocolClient();
            ProtocolClient clientCallerAppService = new ProtocolClient(0, SemVer.V100, clientCaller.GetIdentityKeys());

            try
            {
                MessageBuilder mbCallee           = clientCallee.MessageBuilder;
                MessageBuilder mbCalleeAppService = clientCalleeAppService.MessageBuilder;

                MessageBuilder mbCaller           = clientCaller.MessageBuilder;
                MessageBuilder mbCallerAppService = clientCallerAppService.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                byte[] pubKeyCallee     = clientCallee.GetIdentityKeys().PublicKey;
                byte[] identityIdCallee = clientCallee.GetIdentityId();

                byte[] pubKeyCaller     = clientCaller.GetIdentityKeys().PublicKey;
                byte[] identityIdCaller = clientCaller.GetIdentityId();


                await clientCallee.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await clientCallee.ListServerPorts(rolePorts);

                clientCallee.CloseConnection();


                // Establish hosting agreement for identity 1.
                await clientCallee.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHostingOk = await clientCallee.EstablishHostingAsync();

                clientCallee.CloseConnection();


                // Check-in and initialize the profile of identity 1.

                await clientCallee.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await clientCallee.CheckInAsync();

                bool initializeProfileOk = await clientCallee.InitializeProfileAsync("Test Identity", null, new GpsLocation(0, 0), null);


                // Add application service to the current session.
                string serviceName     = "Test Service";
                bool   addAppServiceOk = await clientCallee.AddApplicationServicesAsync(new List <string>() { serviceName });


                // Step 1 Acceptance
                bool step1Ok = listPortsOk && establishHostingOk && checkInOk && initializeProfileOk && addAppServiceOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await clientCaller.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool verifyIdentityOk = await clientCaller.VerifyIdentityAsync();

                Message requestMessage = mbCaller.CreateCallIdentityApplicationServiceRequest(identityIdCallee, serviceName);
                await clientCaller.SendMessageAsync(requestMessage);


                // Step 2 Acceptance
                bool step2Ok = verifyIdentityOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");



                // Step 3
                log.Trace("Step 3");
                Message serverRequestMessage = await clientCallee.ReceiveMessageAsync();

                byte[] receivedPubKey = serverRequestMessage.Request.ConversationRequest.IncomingCallNotification.CallerPublicKey.ToByteArray();
                bool   pubKeyOk       = StructuralComparisons.StructuralComparer.Compare(receivedPubKey, pubKeyCaller) == 0;
                bool   serviceNameOk  = serverRequestMessage.Request.ConversationRequest.IncomingCallNotification.ServiceName == serviceName;

                bool incomingCallNotificationOk = pubKeyOk && serviceNameOk;

                Message serverResponseMessage = mbCallee.CreateErrorRejectedResponse(serverRequestMessage);
                await clientCallee.SendMessageAsync(serverResponseMessage);


                // Step 3 Acceptance
                bool step3Ok = incomingCallNotificationOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");


                // Step 4
                log.Trace("Step 4");
                Message responseMessage = await clientCaller.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.ErrorRejected;

                bool callIdentityOk = idOk && statusOk;

                // Step 4 Acceptance
                bool step4Ok = callIdentityOk;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok && step3Ok && step4Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            clientCallee.Dispose();
            clientCalleeAppService.Dispose();
            clientCaller.Dispose();
            clientCallerAppService.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #22
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp      = (IPAddress)ArgumentValues["Node IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(NodeIp:'{0}',PrimaryPort:{1})", NodeIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient clientCallee           = new ProtocolClient();
            ProtocolClient clientCalleeAppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCallee.GetIdentityKeys());

            ProtocolClient clientCaller           = new ProtocolClient();
            ProtocolClient clientCallerAppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCaller.GetIdentityKeys());

            try
            {
                MessageBuilder mbCallee           = clientCallee.MessageBuilder;
                MessageBuilder mbCalleeAppService = clientCalleeAppService.MessageBuilder;

                MessageBuilder mbCaller           = clientCaller.MessageBuilder;
                MessageBuilder mbCallerAppService = clientCallerAppService.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                byte[] pubKeyCallee     = clientCallee.GetIdentityKeys().PublicKey;
                byte[] identityIdCallee = clientCallee.GetIdentityId();

                byte[] pubKeyCaller     = clientCaller.GetIdentityKeys().PublicKey;
                byte[] identityIdCaller = clientCaller.GetIdentityId();


                await clientCallee.ConnectAsync(NodeIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await clientCallee.ListNodePorts(rolePorts);

                clientCallee.CloseConnection();


                // Establish home node for identity 1.
                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHomeNodeOk = await clientCallee.EstablishHomeNodeAsync();

                clientCallee.CloseConnection();


                // Check-in and initialize the profile of identity 1.

                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await clientCallee.CheckInAsync();

                bool initializeProfileOk = await clientCallee.InitializeProfileAsync("Test Identity", null, 0x12345678, null);

                clientCallee.CloseConnection();

                // Step 1 Acceptance
                bool step1Ok = listPortsOk && establishHomeNodeOk && checkInOk && initializeProfileOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await clientCaller.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool verifyIdentityOk = await clientCaller.VerifyIdentityAsync();

                Message requestMessage = mbCaller.CreateCallIdentityApplicationServiceRequest(identityIdCallee, "Test Service");
                await clientCaller.SendMessageAsync(requestMessage);

                Message responseMessage = await clientCaller.ReceiveMessageAsync();

                bool idOk           = responseMessage.Id == requestMessage.Id;
                bool statusOk       = responseMessage.Response.Status == Status.ErrorNotAvailable;
                bool callIdentityOk = idOk && statusOk;

                // Step 2 Acceptance
                bool step2Ok = verifyIdentityOk && callIdentityOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            clientCallee.Dispose();
            clientCalleeAppService.Dispose();
            clientCaller.Dispose();
            clientCallerAppService.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #23
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp      = (IPAddress)ArgumentValues["Node IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(NodeIp:'{0}',PrimaryPort:{1})", NodeIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                await client.ConnectAsync(NodeIp, PrimaryPort, false);

                byte[]  data           = Encoding.UTF8.GetBytes("test");
                byte[]  token          = Crypto.Sha1(data);
                Message requestMessage = mb.CreateIncomingCallNotificationRequest(client.GetIdentityKeys().PublicKey, "Test Service", token);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                // Step 1 Acceptance
                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.ErrorProtocolViolation;


                // We should be disconnected by now, so sending or receiving should throw.
                bool disconnectedOk = false;
                data = Encoding.UTF8.GetBytes("Hello");
                byte[] payload = Crypto.Sha1(data);
                requestMessage = mb.CreatePingRequest(payload);

                try
                {
                    await client.SendMessageAsync(requestMessage);

                    await client.ReceiveMessageAsync();
                }
                catch
                {
                    log.Trace("Expected exception occurred.");
                    disconnectedOk = true;
                }

                Passed = idOk && statusOk && disconnectedOk;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #24
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();

                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool hostingOk = await client.EstablishHostingAsync("Test");

                client.CloseConnection();

                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await client.CheckInAsync();

                bool step1Ok = listPortsOk && hostingOk && checkInOk;
                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                byte[] serverId = new byte[5] {
                    0x40, 0x40, 0x40, 0x40, 0x40
                };
                List <CanKeyValue> clientData = new List <CanKeyValue>()
                {
                    new CanKeyValue()
                    {
                        Key = "key1", StringValue = "value 1"
                    },
                    new CanKeyValue()
                    {
                        Key = "key2", Uint32Value = 2
                    },
                    new CanKeyValue()
                    {
                        Key = "key3", BoolValue = true
                    },
                    new CanKeyValue()
                    {
                        Key = "key4", BinaryValue = ProtocolHelper.ByteArrayToByteString(new byte[] { 1, 2, 3 })
                    },
                };

                CanIdentityData identityData1 = new CanIdentityData()
                {
                    HostingServerId = ProtocolHelper.ByteArrayToByteString(serverId)
                };
                identityData1.KeyValueList.AddRange(clientData);

                Message requestMessage = mb.CreateCanStoreDataRequest(identityData1);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk      = responseMessage.Id == requestMessage.Id;
                bool statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                bool detailsOk = responseMessage.Response.Details == "data.hostingServerId";

                // Step 2 Acceptance
                bool step2Ok = idOk && statusOk && detailsOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();


            log.Trace("(-):{0}", res);
            return(res);
        }
Example #25
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Message requestMessage = mb.CreateListRolesRequest();
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                // Step 1 Acceptance
                bool idOk                = responseMessage.Id == requestMessage.Id;
                bool statusOk            = responseMessage.Response.Status == Status.Ok;
                bool primaryPortOk       = false;
                bool srNeighborPortOk    = false;
                bool clNonCustomerPortOk = false;
                bool clCustomerPortOk    = false;
                bool clAppServicePortOk  = false;

                bool error = false;

                HashSet <uint> encryptedPorts   = new HashSet <uint>();
                HashSet <uint> unencryptedPorts = new HashSet <uint>();

                foreach (Iop.Profileserver.ServerRole serverRole in responseMessage.Response.SingleResponse.ListRoles.Roles)
                {
                    switch (serverRole.Role)
                    {
                    case ServerRoleType.Primary:
                        unencryptedPorts.Add(serverRole.Port);
                        primaryPortOk = serverRole.IsTcp && !serverRole.IsTls && !encryptedPorts.Contains(serverRole.Port);
                        log.Trace("Primary port is {0}OK: TCP is {1}, TLS is {2}, Port no. is {3}, encrypted port list: {4}", primaryPortOk ? "" : "NOT ", serverRole.IsTcp, serverRole.IsTls, serverRole.Port, string.Join(",", encryptedPorts));
                        break;

                    case ServerRoleType.SrNeighbor:
                        encryptedPorts.Add(serverRole.Port);
                        srNeighborPortOk = serverRole.IsTcp && serverRole.IsTls && !unencryptedPorts.Contains(serverRole.Port);
                        log.Trace("Server Neighbor port is {0}OK: TCP is {1}, TLS is {2}, Port no. is {3}, unencrypted port list: {4}", srNeighborPortOk ? "" : "NOT ", serverRole.IsTcp, serverRole.IsTls, serverRole.Port, string.Join(",", unencryptedPorts));
                        break;


                    case ServerRoleType.ClNonCustomer:
                        encryptedPorts.Add(serverRole.Port);
                        clNonCustomerPortOk = serverRole.IsTcp && serverRole.IsTls && !unencryptedPorts.Contains(serverRole.Port);
                        log.Trace("Client Non-customer port is {0}OK: TCP is {1}, TLS is {2}, Port no. is {3}, unencrypted port list: {4}", clNonCustomerPortOk ? "" : "NOT ", serverRole.IsTcp, serverRole.IsTls, serverRole.Port, string.Join(",", unencryptedPorts));
                        break;

                    case ServerRoleType.ClCustomer:
                        encryptedPorts.Add(serverRole.Port);
                        clCustomerPortOk = serverRole.IsTcp && serverRole.IsTls && !unencryptedPorts.Contains(serverRole.Port);
                        log.Trace("Client Customer port is {0}OK: TCP is {1}, TLS is {2}, Port no. is {3}, unencrypted port list: {4}", clCustomerPortOk ? "" : "NOT ", serverRole.IsTcp, serverRole.IsTls, serverRole.Port, string.Join(",", unencryptedPorts));
                        break;

                    case ServerRoleType.ClAppService:
                        encryptedPorts.Add(serverRole.Port);
                        clAppServicePortOk = serverRole.IsTcp && serverRole.IsTls && !unencryptedPorts.Contains(serverRole.Port);
                        log.Trace("Client AppService port is {0}OK: TCP is {1}, TLS is {2}, Port no. is {3}, unencrypted port list: {4}", clAppServicePortOk ? "" : "NOT ", serverRole.IsTcp, serverRole.IsTls, serverRole.Port, string.Join(",", unencryptedPorts));
                        break;

                    default:
                        log.Error("Unknown server role {0}.", serverRole.Role);
                        error = true;
                        break;
                    }
                }

                bool portsOk = primaryPortOk &&
                               srNeighborPortOk &&
                               clNonCustomerPortOk &&
                               clCustomerPortOk &&
                               clAppServicePortOk;


                Passed = !error && idOk && statusOk && portsOk;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #26
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp            = (IPAddress)ArgumentValues["Node IP"];
            int       ClNonCustomerPort = (int)ArgumentValues["clNonCustomer Port"];
            int       ClCustomerPort    = (int)ArgumentValues["clCustomer Port"];

            log.Trace("(NodeIp:'{0}',ClNonCustomerPort:{1},ClCustomerPort:{2})", NodeIp, ClNonCustomerPort, ClCustomerPort);

            bool res = false;

            Passed = false;

            ProtocolClient client1 = new ProtocolClient();
            ProtocolClient client2 = new ProtocolClient(0, new byte[] { 1, 0, 0 }, client1.GetIdentityKeys());

            try
            {
                MessageBuilder mb1 = client1.MessageBuilder;

                // Step 1
                await client1.ConnectAsync(NodeIp, ClNonCustomerPort, true);

                bool establishHomeNodeOk = await client1.EstablishHomeNodeAsync();

                // Step 1 Acceptance
                bool step1Ok = establishHomeNodeOk;
                client1.CloseConnection();


                // Step 2
                await client1.ConnectAsync(NodeIp, ClCustomerPort, true);

                bool checkInOk = await client1.CheckInAsync();

                // Step 2 Acceptance
                bool step2Ok = checkInOk;


                // Step 3
                await client2.ConnectAsync(NodeIp, ClCustomerPort, true);

                checkInOk = await client2.CheckInAsync();

                // Step 3 Acceptance
                bool step3Ok = checkInOk;


                // Step 4
                byte[]  payload        = Encoding.UTF8.GetBytes("test");
                Message requestMessage = mb1.CreatePingRequest(payload);
                bool    disconnectedOk = false;

                // We should be disconnected by now, so sending or receiving should throw.
                try
                {
                    await client1.SendMessageAsync(requestMessage);

                    await client1.ReceiveMessageAsync();
                }
                catch
                {
                    log.Trace("Expected exception occurred.");
                    disconnectedOk = true;
                }

                // Step 4 Acceptance
                bool step4Ok = disconnectedOk;


                Passed = step1Ok && step2Ok && step3Ok && step4Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client1.Dispose();
            client2.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #27
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();

                // Radius generation.
                R2 = (uint)Rng.Next(R2Min, R2Max);
                R1 = (uint)Rng.Next(R1Min, (int)(R1R2RatioMax * R2));
                R3 = (uint)Rng.Next((int)(R3R2RatioMax * R2), R3Max);
                log.Trace("R1: {0,8} m", R1);
                log.Trace("R2: {0,8} m", R2);
                log.Trace("R3: {0,8} m", R3);

                // Location generation
                for (int i = 0; i < LocationCount; i++)
                {
                    if (PredefinedLocations.Count > i)
                    {
                        GeneratedLocations.Add(GenerateLocation(PredefinedLocations[i], R2));
                    }
                    else
                    {
                        int lat = Rng.Next((int)(GpsLocation.LatitudeMin * GpsLocation.LocationTypeFactor), (int)(GpsLocation.LatitudeMax * GpsLocation.LocationTypeFactor) + 1);
                        int lon = Rng.Next((int)(GpsLocation.LongitudeMin * GpsLocation.LocationTypeFactor) + 1, (int)(GpsLocation.LongitudeMax * GpsLocation.LocationTypeFactor) + 1);
                        GeneratedLocations.Add(new GpsLocation(lat, lon));
                    }
                }

                log.Trace("Generated locations:");
                for (int i = 0; i < LocationCount; i++)
                {
                    log.Trace(" #{0:00}: {1:US}", i, GeneratedLocations[i]);
                }


                bool profileInitializationOk = true;

                uint[] rads = new uint[] { R1, R2, R3 };
                for (int locIndex = 0; locIndex < LocationCount; locIndex++)
                {
                    for (uint radIndex = 0; radIndex < rads.Length; radIndex++)
                    {
                        for (int idIndex = 0; idIndex < RadiusIdentityCount; idIndex++)
                        {
                            GpsLocation basePoint = GeneratedLocations[locIndex];
                            uint        radius    = rads[radIndex];
                            GpsLocation location  = GenerateLocation(basePoint, radius);
                            ProfileLocations.Add(location);

                            string name = string.Format("{0:00}-{1:00}-{2:00} [{3:US}]", locIndex, idIndex, radIndex, location);
                            ProfileNames.Add(name);

                            ProtocolClient profileClient = new ProtocolClient();

                            await profileClient.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                            bool establishHostingOk = await profileClient.EstablishHostingAsync("test");

                            profileClient.CloseConnection();

                            await profileClient.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                            bool checkInOk = await profileClient.CheckInAsync();

                            bool initializeProfileOk = await profileClient.InitializeProfileAsync(name, null, location, null);

                            profileInitializationOk = establishHostingOk && checkInOk && initializeProfileOk;
                            profileClient.Dispose();

                            if (!profileInitializationOk)
                            {
                                break;
                            }
                        }
                    }
                }


                log.Trace("Generated profile names:");
                for (int i = 0; i < ProfileNames.Count; i++)
                {
                    log.Trace(" {0}", ProfileNames[i]);
                }


                // Step 1 Acceptance
                bool step1Ok = listPortsOk && profileInitializationOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");


                // Step 2
                log.Trace("Step 2");

                // Start conversation.
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool startConversationOk = await client.StartConversationAsync();

                // Search all profiles.
                Message requestMessage = mb.CreateProfileSearchRequest(null, null, null, null, 0, 1000, 1000, false, false);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.Ok;


                bool totalRecordCountOk       = responseMessage.Response.ConversationResponse.ProfileSearch.TotalRecordCount == ProfileNames.Count;
                bool maxResponseRecordCountOk = responseMessage.Response.ConversationResponse.ProfileSearch.MaxResponseRecordCount == 1000;
                bool profilesCountOk          = responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.Count == ProfileNames.Count;

                bool queryRespOk = idOk && statusOk && totalRecordCountOk && maxResponseRecordCountOk && profilesCountOk;
                bool resultsOk   = CompareResults(ProfileNames, responseMessage.Response.ConversationResponse.ProfileSearch.Profiles);

                bool query1Ok = queryRespOk && resultsOk;

                bool queriesOk = true;
                // Search queries around target locations.
                for (int locIndex = 0; locIndex < LocationCount; locIndex++)
                {
                    for (uint radIndex = 0; radIndex < rads.Length + 1; radIndex++)
                    {
                        uint        radius         = radIndex < rads.Length ? rads[radIndex] : (uint)Rng.Next(1000000, 10000000);
                        GpsLocation targetLocation = GeneratedLocations[locIndex];
                        requestMessage = mb.CreateProfileSearchRequest(null, null, null, targetLocation, radius, 1000, 1000, false, false);
                        await client.SendMessageAsync(requestMessage);

                        responseMessage = await client.ReceiveMessageAsync();

                        idOk     = responseMessage.Id == requestMessage.Id;
                        statusOk = responseMessage.Response.Status == Status.Ok;

                        List <string> expectedNames = GetProfileNamesInLocation(targetLocation, radius);
                        totalRecordCountOk       = responseMessage.Response.ConversationResponse.ProfileSearch.TotalRecordCount == expectedNames.Count;
                        maxResponseRecordCountOk = responseMessage.Response.ConversationResponse.ProfileSearch.MaxResponseRecordCount == 1000;
                        profilesCountOk          = responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.Count == expectedNames.Count;

                        queryRespOk = idOk && statusOk && totalRecordCountOk && maxResponseRecordCountOk && profilesCountOk;
                        resultsOk   = CompareResults(expectedNames, responseMessage.Response.ConversationResponse.ProfileSearch.Profiles);

                        queriesOk = queryRespOk && resultsOk;
                        if (!queriesOk)
                        {
                            log.Trace("Search query location {0} with radius {1} should produce {2} profiles, but produced {3} profiles.", targetLocation, radius, expectedNames.Count, responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.Count);
                            log.Trace("Expected names list:");
                            foreach (string name in expectedNames)
                            {
                                log.Trace("  {0}", name);
                            }

                            List <string> resultNames = responseMessage.Response.ConversationResponse.ProfileSearch.Profiles.Select(r => r.Name).OrderBy(r => r).ToList();
                            log.Trace("Query result names list:");
                            foreach (string name in resultNames)
                            {
                                log.Trace("  {0}", name);
                            }
                            break;
                        }

                        log.Trace("Search query location {0} with radius {1} produced {2} correct profiles.", targetLocation, radius, expectedNames.Count);
                    }

                    if (!queriesOk)
                    {
                        break;
                    }
                }

                // Step 2 Acceptance
                bool step2Ok = startConversationOk && query1Ok && queriesOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");



                Passed = step1Ok && step2Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #28
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp      = (IPAddress)ArgumentValues["Node IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(NodeIp:'{0}',PrimaryPort:{1})", NodeIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                await client.ConnectAsync(NodeIp, PrimaryPort, false);

                byte[]  payload        = Encoding.UTF8.GetBytes("test");
                Message requestMessage = mb.CreatePingRequest(payload);

                byte[] messageData = ProtocolHelper.GetMessageBytes(requestMessage);
                byte[] part1       = new byte[4];
                byte[] part2       = new byte[messageData.Length - part1.Length];
                Array.Copy(messageData, 0, part1, 0, part1.Length);
                Array.Copy(messageData, part1.Length, part2, 0, part2.Length);
                await client.SendRawAsync(part1);


                log.Trace("Entering 500 seconds wait...");
                await Task.Delay(500 * 1000);

                log.Trace("Wait completed.");

                // We should be disconnected by now, so sending or receiving should throw.
                bool disconnectedOk = false;
                try
                {
                    await client.SendRawAsync(part2);

                    await client.ReceiveMessageAsync();
                }
                catch
                {
                    log.Trace("Expected exception occurred.");
                    disconnectedOk = true;
                }

                // Step 1 Acceptance
                Passed = disconnectedOk;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #29
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress NodeIp      = (IPAddress)ArgumentValues["Node IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(NodeIp:'{0}',PrimaryPort:{1})", NodeIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient clientCallee           = new ProtocolClient();
            ProtocolClient clientCalleeAppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCallee.GetIdentityKeys());

            ProtocolClient clientCaller           = new ProtocolClient();
            ProtocolClient clientCallerAppService = new ProtocolClient(0, new byte[] { 1, 0, 0 }, clientCaller.GetIdentityKeys());

            try
            {
                MessageBuilder mbCallee           = clientCallee.MessageBuilder;
                MessageBuilder mbCalleeAppService = clientCalleeAppService.MessageBuilder;

                MessageBuilder mbCaller           = clientCaller.MessageBuilder;
                MessageBuilder mbCallerAppService = clientCallerAppService.MessageBuilder;

                // Step 1
                log.Trace("Step 1");
                // Get port list.
                byte[] pubKeyCallee     = clientCallee.GetIdentityKeys().PublicKey;
                byte[] identityIdCallee = clientCallee.GetIdentityId();

                byte[] pubKeyCaller     = clientCaller.GetIdentityKeys().PublicKey;
                byte[] identityIdCaller = clientCaller.GetIdentityId();


                await clientCallee.ConnectAsync(NodeIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await clientCallee.ListNodePorts(rolePorts);

                clientCallee.CloseConnection();


                // Establish home node for identity 1.
                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHomeNodeOk = await clientCallee.EstablishHomeNodeAsync();

                clientCallee.CloseConnection();


                // Check-in and initialize the profile of identity 1.

                await clientCallee.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await clientCallee.CheckInAsync();

                bool initializeProfileOk = await clientCallee.InitializeProfileAsync("Test Identity", null, 0x12345678, null);


                // Add application service to the current session.
                string serviceName     = "Test Service";
                bool   addAppServiceOk = await clientCallee.AddApplicationServicesAsync(new List <string>() { serviceName });


                // Step 1 Acceptance
                bool step1Ok = listPortsOk && establishHomeNodeOk && checkInOk && initializeProfileOk && addAppServiceOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");
                await clientCaller.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool verifyIdentityOk = await clientCaller.VerifyIdentityAsync();

                Message requestMessage = mbCaller.CreateCallIdentityApplicationServiceRequest(identityIdCallee, serviceName);
                await clientCaller.SendMessageAsync(requestMessage);


                // Step 2 Acceptance
                bool step2Ok = verifyIdentityOk;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");



                // Step 3
                log.Trace("Step 3");
                Message nodeRequestMessage = await clientCallee.ReceiveMessageAsync();

                byte[] receivedPubKey = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CallerPublicKey.ToByteArray();
                bool   pubKeyOk       = StructuralComparisons.StructuralComparer.Compare(receivedPubKey, pubKeyCaller) == 0;
                bool   serviceNameOk  = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.ServiceName == serviceName;

                bool incomingCallNotificationOk = pubKeyOk && serviceNameOk;

                byte[] calleeToken = nodeRequestMessage.Request.ConversationRequest.IncomingCallNotification.CalleeToken.ToByteArray();

                Message nodeResponseMessage = mbCallee.CreateIncomingCallNotificationResponse(nodeRequestMessage);
                await clientCallee.SendMessageAsync(nodeResponseMessage);


                // Connect to clAppService and send initialization message.
                await clientCalleeAppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCallee = mbCalleeAppService.CreateApplicationServiceSendMessageRequest(calleeToken, null);
                await clientCalleeAppService.SendMessageAsync(requestMessageAppServiceCallee);


                // Step 3 Acceptance
                bool step3Ok = incomingCallNotificationOk;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");



                // Step 4
                log.Trace("Step 4");
                Message responseMessage = await clientCaller.ReceiveMessageAsync();

                bool   idOk        = responseMessage.Id == requestMessage.Id;
                bool   statusOk    = responseMessage.Response.Status == Status.Ok;
                byte[] callerToken = responseMessage.Response.ConversationResponse.CallIdentityApplicationService.CallerToken.ToByteArray();

                bool callIdentityOk = idOk && statusOk;

                // Connect to clAppService and send initialization message.
                await clientCallerAppService.ConnectAsync(NodeIp, (int)rolePorts[ServerRoleType.ClAppService], true);

                Message requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, null);
                await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);

                Message responseMessageAppServiceCaller = await clientCallerAppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCaller.Id == requestMessageAppServiceCaller.Id;
                statusOk = responseMessageAppServiceCaller.Response.Status == Status.Ok;

                bool initAppServiceMessageOk = idOk && statusOk;

                clientCaller.CloseConnection();


                // Step 4 Acceptance
                bool step4Ok = callIdentityOk && initAppServiceMessageOk;

                log.Trace("Step 4: {0}", step4Ok ? "PASSED" : "FAILED");



                // Step 5
                log.Trace("Step 5");
                Message responseMessageAppServiceCallee = await clientCalleeAppService.ReceiveMessageAsync();

                idOk     = responseMessageAppServiceCallee.Id == requestMessageAppServiceCallee.Id;
                statusOk = responseMessageAppServiceCallee.Response.Status == Status.Ok;

                bool appServiceSendOk = idOk && statusOk;


                // Step 5 Acceptance
                bool step5Ok = appServiceSendOk;

                log.Trace("Step 5: {0}", step5Ok ? "PASSED" : "FAILED");



                // Step 6
                log.Trace("Step 6");

                for (int i = 0; i < 21; i++)
                {
                    // Caller sends message.
                    string callerMessage = string.Format("Message #{0} to callee.", i + 1);
                    byte[] messageBytes  = Encoding.UTF8.GetBytes(callerMessage);
                    requestMessageAppServiceCaller = mbCallerAppService.CreateApplicationServiceSendMessageRequest(callerToken, messageBytes);
                    await clientCallerAppService.SendMessageAsync(requestMessageAppServiceCaller);
                }

                Message response = await clientCallerAppService.ReceiveMessageAsync();

                statusOk = response.Response.Status == Status.ErrorNotFound;


                // Step 6 Acceptance
                bool step6Ok = statusOk;

                log.Trace("Step 6: {0}", step6Ok ? "PASSED" : "FAILED");


                Passed = step1Ok && step2Ok && step3Ok && step4Ok && step5Ok && step6Ok;

                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            clientCallee.Dispose();
            clientCalleeAppService.Dispose();
            clientCaller.Dispose();
            clientCallerAppService.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #30
0
        /// <summary>
        /// Implementation of the test itself.
        /// </summary>
        /// <returns>true if the test passes, false otherwise.</returns>
        public override async Task <bool> RunAsync()
        {
            IPAddress ServerIp    = (IPAddress)ArgumentValues["Server IP"];
            int       PrimaryPort = (int)ArgumentValues["primary Port"];

            log.Trace("(ServerIp:'{0}',PrimaryPort:{1})", ServerIp, PrimaryPort);

            bool res = false;

            Passed = false;

            ProtocolClient client = new ProtocolClient();
            ProtocolClient issuer = new ProtocolClient();

            try
            {
                MessageBuilder mb = client.MessageBuilder;

                // Step 1
                log.Trace("Step 1");

                // Get port list.
                await client.ConnectAsync(ServerIp, PrimaryPort, false);

                Dictionary <ServerRoleType, uint> rolePorts = new Dictionary <ServerRoleType, uint>();
                bool listPortsOk = await client.ListServerPorts(rolePorts);

                client.CloseConnection();

                // Establish hosting agreement for primary client.
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClNonCustomer], true);

                bool establishHostingOk = await client.EstablishHostingAsync("Primary");

                client.CloseConnection();

                // Check in primary client.
                await client.ConnectAsync(ServerIp, (int)rolePorts[ServerRoleType.ClCustomer], true);

                bool checkInOk = await client.CheckInAsync();

                // Step 1 Acceptance
                bool step1Ok = listPortsOk && establishHostingOk && checkInOk;

                log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED");



                // Step 2
                log.Trace("Step 2");

                byte[]   primaryPubKey            = client.GetIdentityKeys().PublicKey;
                string   type                     = "Card Type A";
                DateTime validFrom                = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                DateTime validTo                  = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                SignedRelationshipCard signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                byte[] applicationId = new byte[] { 1 };
                CardApplicationInformation cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                byte[] signature = new byte[16];
                for (int i = 0; i < signature.Length; i++)
                {
                    signature[i] = 0x40;
                }

                Message requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                requestMessage.Request.ConversationRequest.Signature = ProtocolHelper.ByteArrayToByteString(signature);
                await client.SendMessageAsync(requestMessage);

                Message responseMessage = await client.ReceiveMessageAsync();

                bool idOk     = responseMessage.Id == requestMessage.Id;
                bool statusOk = responseMessage.Response.Status == Status.ErrorInvalidSignature;

                bool req1Ok = idOk && statusOk;



                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 2 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                signature      = requestMessage.Request.ConversationRequest.Signature.ToByteArray();
                signature[0]  ^= 0x12;
                requestMessage.Request.ConversationRequest.Signature = ProtocolHelper.ByteArrayToByteString(signature);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.ErrorInvalidSignature;

                bool req2Ok = idOk && statusOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 3 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.Ok;

                bool req3Ok = idOk && statusOk;



                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 3 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.ErrorAlreadyExists;

                bool req4Ok = idOk && statusOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 4 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                byte[] hash = new byte[16];
                for (int i = 0; i < hash.Length; i++)
                {
                    hash[i] = 0x40;
                }

                cardApplication.CardId = ProtocolHelper.ByteArrayToByteString(hash);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.ErrorInvalidValue;
                bool detailsOk = responseMessage.Response.Details == "cardApplication.cardId";

                bool req5Ok = idOk && statusOk && detailsOk;



                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 5 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                hash     = cardApplication.CardId.ToByteArray();
                hash[0] ^= 0x12;
                cardApplication.CardId = ProtocolHelper.ByteArrayToByteString(hash);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "cardApplication.cardId";

                bool req6Ok = idOk && statusOk && detailsOk;



                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "cardApplication.applicationId";

                bool req7Ok = idOk && statusOk && detailsOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId = new byte[40];
                for (int i = 0; i < applicationId.Length; i++)
                {
                    applicationId[i] = 0x40;
                }

                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "cardApplication.applicationId";

                bool req8Ok = idOk && statusOk && detailsOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                byte[] issuerPubKey = new byte[10];
                Array.Copy(signedCard.Card.IssuerPublicKey.ToByteArray(), issuerPubKey, issuerPubKey.Length);
                signedCard.Card.IssuerPublicKey = ProtocolHelper.ByteArrayToByteString(issuerPubKey);


                RelationshipCard card = new RelationshipCard()
                {
                    CardId             = ProtocolHelper.ByteArrayToByteString(new byte[32]),
                    Version            = SemVer.V100.ToByteString(),
                    IssuerPublicKey    = signedCard.Card.IssuerPublicKey,
                    RecipientPublicKey = signedCard.Card.RecipientPublicKey,
                    Type      = signedCard.Card.Type,
                    ValidFrom = signedCard.Card.ValidFrom,
                    ValidTo   = signedCard.Card.ValidTo,
                };

                byte[] cardDataToHash = card.ToByteArray();
                byte[] cardId         = Crypto.Sha256(cardDataToHash);
                signedCard.Card.CardId = ProtocolHelper.ByteArrayToByteString(cardId);



                applicationId   = new byte[] { 6 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.issuerSignature";

                bool req9Ok = idOk && statusOk && detailsOk;



                type             = "Card Type A";
                validFrom        = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo          = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard       = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                issuerPubKey     = signedCard.Card.IssuerPublicKey.ToByteArray();
                issuerPubKey[0] ^= 0x12;
                signedCard.Card.IssuerPublicKey = ProtocolHelper.ByteArrayToByteString(issuerPubKey);


                card = new RelationshipCard()
                {
                    CardId             = ProtocolHelper.ByteArrayToByteString(new byte[32]),
                    Version            = SemVer.V100.ToByteString(),
                    IssuerPublicKey    = signedCard.Card.IssuerPublicKey,
                    RecipientPublicKey = signedCard.Card.RecipientPublicKey,
                    Type      = signedCard.Card.Type,
                    ValidFrom = signedCard.Card.ValidFrom,
                    ValidTo   = signedCard.Card.ValidTo,
                };

                cardDataToHash         = card.ToByteArray();
                cardId                 = Crypto.Sha256(cardDataToHash);
                signedCard.Card.CardId = ProtocolHelper.ByteArrayToByteString(cardId);


                applicationId   = new byte[] { 7 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.issuerSignature";

                bool req10Ok = idOk && statusOk && detailsOk;



                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                byte[] issuerSignature = new byte[20];
                Array.Copy(signedCard.IssuerSignature.ToByteArray(), issuerSignature, issuerSignature.Length);
                signedCard.IssuerSignature = ProtocolHelper.ByteArrayToByteString(issuerSignature);


                applicationId   = new byte[] { 8 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.issuerSignature";

                bool req11Ok = idOk && statusOk && detailsOk;


                type                       = "Card Type A";
                validFrom                  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo                    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard                 = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                issuerSignature            = signedCard.IssuerSignature.ToByteArray();
                issuerSignature[0]        ^= 0x12;
                signedCard.IssuerSignature = ProtocolHelper.ByteArrayToByteString(issuerSignature);


                applicationId   = new byte[] { 9 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.issuerSignature";

                bool req12Ok = idOk && statusOk && detailsOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                cardId     = new byte[20];
                Array.Copy(signedCard.Card.CardId.ToByteArray(), cardId, cardId.Length);
                signedCard.Card.CardId = ProtocolHelper.ByteArrayToByteString(cardId);


                applicationId   = new byte[] { 10 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.cardId";

                bool req13Ok = idOk && statusOk && detailsOk;


                type                   = "Card Type A";
                validFrom              = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo                = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard             = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);
                cardId                 = signedCard.Card.CardId.ToByteArray();
                cardId[0]             ^= 0x12;
                signedCard.Card.CardId = ProtocolHelper.ByteArrayToByteString(cardId);


                applicationId   = new byte[] { 11 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.cardId";

                bool req14Ok = idOk && statusOk && detailsOk;


                type      = "Card Type A";
                validFrom = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo   = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                byte[] rcptPubKey = new byte[20];
                Array.Copy(signedCard.Card.RecipientPublicKey.ToByteArray(), rcptPubKey, rcptPubKey.Length);
                signedCard = issuer.IssueRelationshipCard(rcptPubKey, type, validFrom, validTo);


                applicationId   = new byte[] { 12 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.recipientPublicKey";

                bool req15Ok = idOk && statusOk && detailsOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                rcptPubKey = new byte[primaryPubKey.Length];
                Array.Copy(primaryPubKey, rcptPubKey, rcptPubKey.Length);
                rcptPubKey[0] ^= 0x12;
                signedCard     = issuer.IssueRelationshipCard(rcptPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 13 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.recipientPublicKey";

                bool req16Ok = idOk && statusOk && detailsOk;



                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(1479220555000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 14 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.validFrom";

                bool req17Ok = idOk && statusOk && detailsOk;



                type       = new string('a', 70);
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 15 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.type";

                bool req18Ok = idOk && statusOk && detailsOk;


                type       = new string('ɐ', 35);
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 16 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.type";

                bool req19Ok = idOk && statusOk && detailsOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(new byte[] { 0, 0, 0 }, primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 17 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.version";

                bool req20Ok = idOk && statusOk && detailsOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(new byte[] { 1, 0 }, primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 18 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.version";

                bool req21Ok = idOk && statusOk && detailsOk;


                type       = "Card Type A";
                validFrom  = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo    = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                signedCard = issuer.IssueRelationshipCard(new byte[] { 1, 0, 0, 0 }, primaryPubKey, type, validFrom, validTo);

                applicationId   = new byte[] { 19 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.version";

                bool req22Ok = idOk && statusOk && detailsOk;


                type      = "Card Type A";
                validFrom = ProtocolHelper.UnixTimestampMsToDateTime(1479220556000);
                validTo   = ProtocolHelper.UnixTimestampMsToDateTime(2479220556000);
                byte[] badPubKey = new byte[130];
                for (int i = 0; i < badPubKey.Length; i++)
                {
                    badPubKey[i] = 0x40;
                }

                RelationshipCard badIssuerKeyCard = new RelationshipCard()
                {
                    CardId             = ProtocolHelper.ByteArrayToByteString(new byte[32]),
                    Version            = SemVer.V100.ToByteString(),
                    IssuerPublicKey    = ProtocolHelper.ByteArrayToByteString(badPubKey),
                    RecipientPublicKey = ProtocolHelper.ByteArrayToByteString(primaryPubKey),
                    Type      = type,
                    ValidFrom = ProtocolHelper.DateTimeToUnixTimestampMs(validFrom),
                    ValidTo   = ProtocolHelper.DateTimeToUnixTimestampMs(validTo)
                };

                signedCard = issuer.IssueRelationshipCard(badIssuerKeyCard);

                applicationId   = new byte[] { 20 };
                cardApplication = client.CreateRelationshipCardApplication(applicationId, signedCard);

                requestMessage = mb.CreateAddRelatedIdentityRequest(cardApplication, signedCard);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "signedCard.card.issuerPublicKey";

                bool req23Ok = idOk && statusOk && detailsOk;



                // Step 2 Acceptance
                bool step2Ok = req1Ok && req2Ok && req3Ok && req4Ok && req5Ok && req6Ok && req7Ok && req8Ok && req9Ok && req10Ok &&
                               req11Ok && req12Ok && req13Ok && req14Ok && req15Ok && req16Ok && req17Ok && req18Ok && req19Ok && req20Ok &&
                               req21Ok && req22Ok && req23Ok;

                log.Trace("Step 2: {0}", step2Ok ? "PASSED" : "FAILED");



                // Step 3
                log.Trace("Step 3");

                applicationId  = new byte[] { 21 };
                requestMessage = mb.CreateRemoveRelatedIdentityRequest(applicationId);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk     = responseMessage.Id == requestMessage.Id;
                statusOk = responseMessage.Response.Status == Status.ErrorNotFound;
                bool removeOk = idOk && statusOk;


                type           = new string('a', 70);
                requestMessage = mb.CreateGetIdentityRelationshipsInformationRequest(client.GetIdentityId(), true, type, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "type";

                req1Ok = idOk && statusOk && detailsOk;


                type           = new string('ɐ', 35);
                requestMessage = mb.CreateGetIdentityRelationshipsInformationRequest(client.GetIdentityId(), true, type, null);
                await client.SendMessageAsync(requestMessage);

                responseMessage = await client.ReceiveMessageAsync();

                idOk      = responseMessage.Id == requestMessage.Id;
                statusOk  = responseMessage.Response.Status == Status.ErrorInvalidValue;
                detailsOk = responseMessage.Response.Details == "type";

                req2Ok = idOk && statusOk && detailsOk;


                // Step 3 Acceptance
                bool step3Ok = removeOk && req1Ok && req2Ok;

                log.Trace("Step 3: {0}", step3Ok ? "PASSED" : "FAILED");



                Passed = step1Ok && step2Ok && step3Ok;


                res = true;
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }
            client.Dispose();
            issuer.Dispose();

            log.Trace("(-):{0}", res);
            return(res);
        }