Пример #1
0
        /// <inheritdoc />
        public virtual async Task <(ConnectionRequestMessage, ConnectionRecord)> CreateRequestAsync(IAgentContext agentContext, ConnectionInvitationMessage invitation)
        {
            Logger.LogInformation(LoggingEvents.AcceptInvitation, "Key {0}, Endpoint {1}",
                                  invitation.RecipientKeys[0], invitation.ServiceEndpoint);

            var my = await Did.CreateAndStoreMyDidAsync(agentContext.Wallet, "{}");

            var connection = new ConnectionRecord
            {
                Endpoint = new AgentEndpoint(invitation.ServiceEndpoint, null, invitation.RoutingKeys != null && invitation.RoutingKeys.Count != 0 ? invitation.RoutingKeys[0] : null),
                MyDid    = my.Did,
                MyVk     = my.VerKey,
                Id       = Guid.NewGuid().ToString().ToLowerInvariant()
            };

            if (!string.IsNullOrEmpty(invitation.Label) || !string.IsNullOrEmpty(invitation.ImageUrl))
            {
                connection.Alias = new ConnectionAlias
                {
                    Name     = invitation.Label,
                    ImageUrl = invitation.ImageUrl
                };

                if (string.IsNullOrEmpty(invitation.Label))
                {
                    connection.SetTag(TagConstants.Alias, invitation.Label);
                }
            }

            await connection.TriggerAsync(ConnectionTrigger.InvitationAccept);

            var provisioning = await ProvisioningService.GetProvisioningAsync(agentContext.Wallet);

            var request = new ConnectionRequestMessage
            {
                Connection = new Connection {
                    Did = connection.MyDid, DidDoc = connection.MyDidDoc(provisioning)
                },
                Label    = provisioning.Owner?.Name,
                ImageUrl = provisioning.Owner?.ImageUrl
            };

            // also set image as attachment
            if (provisioning.Owner?.ImageUrl != null)
            {
                request.AddAttachment(new Attachment
                {
                    Nickname = "profile-image",
                    Content  = new AttachmentContent {
                        Links = new[] { provisioning.Owner.ImageUrl }
                    }
                });
            }

            await RecordService.AddAsync(agentContext.Wallet, connection);

            return(request,
                   connection);
        }
        public void CanDetectTransportDecoratorOnMessage()
        {
            var outboundMessage = new ConnectionRequestMessage();

            outboundMessage.AddReturnRouting();

            Assert.True(outboundMessage.ReturnRoutingRequested());
        }
        public void CanAddTransportDecoratorToMessage()
        {
            var outboundMessage = new ConnectionRequestMessage();

            outboundMessage.AddReturnRouting();

            var transportDecorator = outboundMessage.GetDecorator <TransportDecorator>(Core.Decorators.Decorators.TransportDecorator);

            Assert.NotNull(transportDecorator);
            Assert.True(transportDecorator.ReturnRoute == ReturnRouteTypes.all.ToString("G"));
        }
        public void CreatesNewThreadFromUnthreadedInboundMessage()
        {
            var inboundMessage = new ConnectionRequestMessage();

            var outboundMessage = inboundMessage.CreateThreadedReply <ConnectionResponseMessage>();

            var threadingBlock = outboundMessage.GetDecorator <ThreadDecorator>("thread");

            Assert.True(threadingBlock.ThreadId == inboundMessage.Id);
            Assert.True(threadingBlock.SenderOrder == 0);
            Assert.True(threadingBlock.ReceivedOrders.Count == 0);
        }
        public void ExtractDecoratorAndAttachment()
        {
            var message = new ConnectionRequestMessage();

            message.AddAttachment(new Attachment {
                Nickname = "file1"
            });

            var jobj = JObject.Parse(message.ToJson());

            Assert.NotNull(jobj["~attach"]);
            Assert.Equal("file1", jobj["~attach"].First["nickname"]);
        }
Пример #6
0
        private void Connect(IPEndPoint endPoint, Key32?hostKey, JoinSecret secret, OnH3ClientDisconnect onDisconnect)
        {
            _clientLog.LogInfo($"Connecting to {endPoint}...");

            float  ups = 1 / Time.fixedDeltaTime;
            double tps = 1 / secret.TickDeltaTime;

            _clientLog.LogDebug($"Fixed update rate: {ups:.00} u/s");
            _clientLog.LogDebug($"Tick rate: {tps:.00} t/s");

            var request = new ConnectionRequestMessage(secret.Key, hostKey);

            Client = new H3Client(_clientLog, _config.Client, Activity, _messages.Client, _messages.ChannelsCount, secret.TickDeltaTime, _version, endPoint, request, onDisconnect);
        }
        /// <inheritdoc />
        public async Task <string> ProcessRequestAsync(IAgentContext agentContext, ConnectionRequestMessage request)
        {
            Logger.LogInformation(LoggingEvents.ProcessConnectionRequest, "Key {0}", request.Verkey);

            var my = await Did.CreateAndStoreMyDidAsync(agentContext.Wallet, "{}");

            await Did.StoreTheirDidAsync(agentContext.Wallet, new { did = request.Did, verkey = request.Verkey }.ToJson());

            agentContext.Connection.Endpoint = request.Endpoint;
            agentContext.Connection.TheirDid = request.Did;
            agentContext.Connection.TheirVk  = request.Verkey;
            agentContext.Connection.MyDid    = my.Did;
            agentContext.Connection.MyVk     = my.VerKey;

            agentContext.Connection.Alias = new ConnectionAlias
            {
                Name     = request.Name,
                ImageUrl = request.ImageUrl
            };

            if (!agentContext.Connection.MultiPartyInvitation)
            {
                await agentContext.Connection.TriggerAsync(ConnectionTrigger.InvitationAccept);

                await RecordService.UpdateAsync(agentContext.Wallet, agentContext.Connection);

                EventAggregator.Publish(new ServiceMessageProcessingEvent
                {
                    RecordId    = agentContext.Connection.Id,
                    MessageType = request.Type,
                });

                return(agentContext.Connection.Id);
            }

            var newConnection = agentContext.Connection.DeepCopy();

            newConnection.Id = Guid.NewGuid().ToString();
            await newConnection.TriggerAsync(ConnectionTrigger.InvitationAccept);

            await RecordService.AddAsync(agentContext.Wallet, newConnection);

            EventAggregator.Publish(new ServiceMessageProcessingEvent
            {
                RecordId    = newConnection.Id,
                MessageType = request.Type,
            });

            return(newConnection.Id);
        }
Пример #8
0
        public void SerializeAgentMessageWithDecorators()
        {
            var message = new ConnectionRequestMessage();

            message.AddDecorator(new SampleDecorator()
            {
                Prop1 = "123"
            }, "sample");

            var serialized = message.ToJson();

            var token = JObject.Parse(serialized);

            Assert.NotNull(token["~sample"]);
            Assert.Equal("123", token["~sample"]["Prop1"]);
        }
Пример #9
0
        public void CanConvertContentMessage()
        {
            var type = MessageUtils.FormatKeyMessageType("2J6h65V5CjvWceHDMq7htRkG6EdCE2SiDEtCRyfngwfw",
                                                         MessageTypes.ConnectionRequest);

            var expected = new ConnectionRequestMessage
            {
                Key  = "2J6h65V5CjvWceHDMq7htRkG6EdCE2SiDEtCRyfngwfw",
                Type = type
            };
            var json = JsonConvert.SerializeObject(expected);

            var actual = JsonConvert.DeserializeObject <IContentMessage>(json);

            Assert.IsType <ConnectionRequestMessage>(actual);
            Assert.Equal(type, ((ConnectionRequestMessage)actual).Type);
        }
        public void ThreadFromThrowsExceptionOnAlreadyThreadedMessage()
        {
            var message = new ConnectionRequestMessage();

            var threadId = Guid.NewGuid().ToString();

            message.AddDecorator(new ThreadDecorator()
            {
                ThreadId = threadId
            }, "thread");

            var inboundMessage = new ConnectionInvitationMessage();

            var ex = Assert.Throws <AriesFrameworkException>(() => message.ThreadFrom(inboundMessage));

            Assert.True(ex.ErrorCode == ErrorCode.InvalidMessage);
        }
        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            var item = JObject.Load(reader);

            var(_, messageType) = MessageUtils.ParseMessageType(item["@type"].ToObject <string>());

            IContentMessage message;

            switch (messageType)
            {
            case MessageTypes.ConnectionRequest:
                message = new ConnectionRequestMessage();
                break;

            case MessageTypes.ConnectionResponse:
                message = new ConnectionResponseMessage();
                break;

            case MessageTypes.CredentialOffer:
                message = new CredentialOfferMessage();
                break;

            case MessageTypes.CredentialRequest:
                message = new CredentialRequestMessage();
                break;

            case MessageTypes.Credential:
                message = new CredentialMessage();
                break;

            case MessageTypes.ProofRequest:
                message = new ProofRequestMessage();
                break;

            case MessageTypes.DisclosedProof:
                message = new ProofMessage();
                break;

            default: throw new TypeLoadException("Unsupported serialization type.");
            }

            serializer.Populate(item.CreateReader(), message);
            return(message);
        }
        private static async Task <ASConnectionConnectResult> ConnectInternalAsync(string appServiceName,
                                                                                   string packageFamilyName, RemoteSystem remoteSystem, IObjectSerializer serializer)
        {
            var connection = new AppServiceConnection
            {
                AppServiceName    = appServiceName,
                PackageFamilyName = packageFamilyName
            };

            var isRemoteSystemConnection = (remoteSystem != null);

            var connectStatus = isRemoteSystemConnection
                ? await connection.OpenRemoteAsync(new RemoteSystemConnectionRequest(remoteSystem))
                : await connection.OpenAsync();

            if (connectStatus != AppServiceConnectionStatus.Success)
            {
                return(new ASConnectionConnectResult(connectStatus, AppServiceHandshakeStatus.Unknown, null));
            }

            // Send connection request, receive connection response
            var request  = new ConnectionRequestMessage();
            var response = await connection.SendMessageAsync(request, RequestOptions.Default, serializer);

            var success =
                response.Status == RequestStatus.Success &&
                response.Response is ConnectionResponseMessage responseObject &&
                responseObject.IsSuccessful;

            if (!success)
            {
                return(new ASConnectionConnectResult(
                           AppServiceConnectionStatus.Success, AppServiceHandshakeStatus.ConnectionRequestFailure, null));
            }

            var asConnection = new ASConnection(
                ((ConnectionResponseMessage)response.Response).ConnectionId,
                connection, null, isRemoteSystemConnection, serializer);

            return(new ASConnectionConnectResult(
                       AppServiceConnectionStatus.Success,
                       AppServiceHandshakeStatus.Success,
                       asConnection));
        }
        public void AddsToThreadFromThreadedInboundMessage()
        {
            var inboundMessage = new ConnectionRequestMessage();

            var threadId = Guid.NewGuid().ToString();

            inboundMessage.AddDecorator(new ThreadDecorator()
            {
                ThreadId = threadId
            }, "thread");

            var outgoingMessage = inboundMessage.CreateThreadedReply <ConnectionResponseMessage>();

            var threadingBlock = outgoingMessage.GetDecorator <ThreadDecorator>("thread");

            Assert.True(threadingBlock.ThreadId == threadId);
            Assert.True(threadingBlock.SenderOrder == 0);
            Assert.True(threadingBlock.ReceivedOrders.Count == 0);
        }
Пример #14
0
        /// <inheritdoc />
        public async Task <string> ProcessRequestAsync(Wallet wallet, ConnectionRequestMessage request)
        {
            Logger.LogInformation(LoggingEvents.StoreConnectionRequest, "Key {0}", request.Key);

            var(didOrKey, _) = MessageUtils.ParseMessageType(request.Type);

            var connectionSearch = await RecordService.SearchAsync <ConnectionRecord>(wallet,
                                                                                      new SearchRecordQuery { { TagConstants.ConnectionKey, didOrKey } }, null, 1);

            var connection = connectionSearch.Single();

            var(their, theirKey) =
                await MessageSerializer.UnpackSealedAsync <ConnectionDetails>(request.Content, wallet, request.Key);

            if (!their.Verkey.Equals(theirKey))
            {
                throw new ArgumentException("Signed and enclosed keys don't match");
            }

            await connection.TriggerAsync(ConnectionTrigger.InvitationAccept);

            var my = await Did.CreateAndStoreMyDidAsync(wallet, "{}");

            await Did.StoreTheirDidAsync(wallet, new { did = their.Did, verkey = their.Verkey }.ToJson());

            connection.Endpoint = their.Endpoint;
            connection.TheirDid = their.Did;
            connection.TheirVk  = their.Verkey;
            connection.MyDid    = my.Did;
            connection.MyVk     = my.VerKey;
            connection.Tags[TagConstants.MyDid]    = my.Did;
            connection.Tags[TagConstants.TheirDid] = their.Did;

            await RecordService.UpdateAsync(wallet, connection);

            if (connection.Tags.Any(_ => _.Key == TagConstants.AutoAcceptConnection && _.Value == "true"))
            {
                await AcceptRequestAsync(wallet, connection.ConnectionId);
            }

            return(connection.GetId());
        }
        /// <inheritdoc />
        public async Task <(ConnectionRequestMessage, ConnectionRecord)> CreateRequestAsync(IAgentContext agentContext, ConnectionRecord connection)
        {
            Logger.LogInformation(LoggingEvents.AcceptInvitation, "Key {0}, Endpoint {1}",
                                  connection.Endpoint.Verkey, connection.Endpoint.Uri);

            await connection.TriggerAsync(ConnectionTrigger.Request);

            var provisioning = await ProvisioningService.GetProvisioningAsync(agentContext.Wallet);

            var request = new ConnectionRequestMessage(agentContext.UseMessageTypesHttps)
            {
                Connection = new Common.Connection
                {
                    Did    = connection.MyDid,
                    DidDoc = connection.MyDidDoc(provisioning)
                },
                Label    = provisioning.Owner?.Name,
                ImageUrl = provisioning.Owner?.ImageUrl
            };

            // also set image as attachment
            if (provisioning.Owner?.ImageUrl != null)
            {
                request.AddAttachment(new Attachment
                {
                    Nickname = "profile-image",
                    Data     = new AttachmentContent {
                        Links = new[] { provisioning.Owner.ImageUrl }
                    }
                });
            }

            await RecordService.UpdateAsync(agentContext.Wallet, connection);

            return(request, connection);
        }
Пример #16
0
 public Task <string> ProcessRequestAsync(IAgentContext agentContext, ConnectionRequestMessage request, ConnectionRecord connection)
 {
     throw new System.NotImplementedException();
 }
        /// <inheritdoc />
        public virtual async Task <string> ProcessRequestAsync(IAgentContext agentContext, ConnectionRequestMessage request, ConnectionRecord connection)
        {
            Logger.LogInformation(LoggingEvents.ProcessConnectionRequest, "Did {0}", request.Connection.Did);

            var my = await Did.CreateAndStoreMyDidAsync(agentContext.Wallet, "{}");

            //TODO throw exception or a problem report if the connection request features a did doc that has no indy agent did doc convention featured
            //i.e there is no way for this agent to respond to messages. And or no keys specified
            await Did.StoreTheirDidAsync(agentContext.Wallet, new { did = request.Connection.Did, verkey = request.Connection.DidDoc.Keys[0].PublicKeyBase58 }.ToJson());

            if (request.Connection.DidDoc.Services != null &&
                request.Connection.DidDoc.Services.Count > 0 &&
                request.Connection.DidDoc.Services[0] is IndyAgentDidDocService service)
            {
                connection.Endpoint = new AgentEndpoint(service.ServiceEndpoint, null, service.RoutingKeys != null && service.RoutingKeys.Count > 0 ? service.RoutingKeys.ToArray() : null);
            }

            connection.TheirDid = request.Connection.Did;
            connection.TheirVk  = request.Connection.DidDoc.Keys[0].PublicKeyBase58;
            connection.MyDid    = my.Did;
            connection.MyVk     = my.VerKey;

            connection.SetTag(TagConstants.LastThreadId, request.Id);

            if (connection.Alias == null)
            {
                connection.Alias = new ConnectionAlias();
            }

            if (!string.IsNullOrEmpty(request.Label) && string.IsNullOrEmpty(connection.Alias.Name))
            {
                connection.Alias.Name = request.Label;
            }

            if (!string.IsNullOrEmpty(request.ImageUrl) && string.IsNullOrEmpty(connection.Alias.ImageUrl))
            {
                connection.Alias.ImageUrl = request.ImageUrl;
            }

            if (!connection.MultiPartyInvitation)
            {
                await connection.TriggerAsync(ConnectionTrigger.Request);

                await RecordService.UpdateAsync(agentContext.Wallet, connection);

                EventAggregator.Publish(new ServiceMessageProcessingEvent
                {
                    RecordId    = connection.Id,
                    MessageType = request.Type,
                    ThreadId    = request.GetThreadId()
                });

                return(connection.Id);
            }
            else
            {
                var newConnection = connection.DeepCopy();
                newConnection.Id = Guid.NewGuid().ToString();
                newConnection.MultiPartyInvitation = false;

                await newConnection.TriggerAsync(ConnectionTrigger.Request);

                await RecordService.AddAsync(agentContext.Wallet, newConnection);

                EventAggregator.Publish(new ServiceMessageProcessingEvent
                {
                    RecordId    = newConnection.Id,
                    MessageType = request.Type,
                    ThreadId    = request.GetThreadId()
                });
                return(newConnection.Id);
            }
        }
Пример #18
0
 private KeyValuePair <string, StringValues> GetAuthorizationHeader(ConnectionRequestMessage request) =>
 new KeyValuePair <string, StringValues>(AuthorizationHeaderKey, $"Bearer {request.AccessToken}");
Пример #19
0
        internal H3Client(ManualLogSource log, ClientConfig config, StatefulActivity discord, PeerMessageList <H3Client> messages, byte channelsCount, double tickDeltaTime, Version version, IPEndPoint endpoint, ConnectionRequestMessage request, OnH3ClientDisconnect onDisconnected)
            : base(log, messages, channelsCount, new Events(), version, endpoint, x => x.Put(request))
        {
            _log            = log;
            _config         = config;
            _discord        = discord;
            _onDisconnected = onDisconnected;

            _tickDeltaTime = tickDeltaTime;
            _tickTimer     = new LoopTimer(tickDeltaTime);

            _players = new Dictionary <byte, Puppet>();
            _items   = new Dictionary <byte, Item>();
            _health  = new HealthInfo(HEALTH_INTERVAL, (int)(HEALTH_INTERVAL / PING_INTERVAL));
        }
Пример #20
0
        private void HandleMessage(MessageType type, byte[] data)
        {
            var dataStream = new MemoryStream(data);
            IMessage <object> resultMessage = null;

            switch (type)
            {
            case MessageType.ServerToClientHeartbeat:
                resultMessage = new ServerToClientHeartbeatMessage(new BinaryReader(dataStream));
                break;

            case MessageType.ClientToServerHeartbeat:
                resultMessage = new ClientToServerHeartbeatMessage(new BinaryReader(dataStream));
                break;

            case MessageType.Ping:
                resultMessage = new PingMessage(new BinaryReader(dataStream));
                break;

            case MessageType.PingReply:
                resultMessage = new PingReplyMessage(new BinaryReader(dataStream));
                break;

            case MessageType.ConnectionRequest:
                resultMessage = new ConnectionRequestMessage(new BinaryReader(dataStream));
                break;

            case MessageType.ConnectionRequestReply:
                resultMessage = new ConnectionRequestReplyMessage(new BinaryReader(dataStream));
                break;

            case MessageType.ConnectionRequestReplyConfirm:
                resultMessage = new ConnectionRequestReplyConfirmMessage(new BinaryReader(dataStream));
                break;

            case MessageType.ConnectionAcceptOrDeny:
                resultMessage = new ConnectionAcceptOrDenyMessage(new BinaryReader(dataStream));
                break;

            case MessageType.GetOwnAddress:
                break;

            case MessageType.GetOwnAddressReply:
                break;

            case MessageType.NatPunchRequest:
                break;

            case MessageType.NatPunch:
                break;

            case MessageType.TransferBlockRequest:
                resultMessage = new TransferBlockRequestMessage(new BinaryReader(dataStream));
                break;

            case MessageType.TransferBlock:
                resultMessage = new TransferBlockMessage(new BinaryReader(dataStream));
                break;

            case MessageType.RequestForHeartbeatWhenDisconnecting:
                resultMessage = new RequestForHeartbeatWhenDisconnectingMessage(new BinaryReader(dataStream));
                break;

            case MessageType.LanBroadcast:
                resultMessage = new LanBroadcastMessage(new BinaryReader(dataStream));
                break;

            case MessageType.GameInformationRequest:
                resultMessage = new GameInformationRequestMessage(new BinaryReader(dataStream));
                break;

            case MessageType.GameInformationRequestReply:
                break;

            case MessageType.Empty:
                resultMessage = new EmptyMessage(new BinaryReader(dataStream));
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }

            OnMessageReceived?.Invoke(resultMessage);

            if (dataStream.Position == dataStream.Length)
            {
                return;
            }

            Console.WriteLine($"F****d up: {dataStream.Position}/{dataStream.Length}; Type: {type}");
            File.WriteAllBytes($"f****d-up-{lastFuckedUpId}.bin", data);
            lastFuckedUpId++;
        }