Ejemplo n.º 1
0
        /// <summary>
        /// Processes the agent message
        /// </summary>
        /// <param name="agentContext"></param>
        /// <param name="messageContext">The agent message agentContext.</param>
        /// <returns></returns>
        /// <exception cref="AriesFrameworkException">Unsupported message type {messageType}</exception>
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            // v1.0
            case MessageTypes.PresentProofNames.RequestPresentation:
            {
                var message = messageContext.GetMessage <RequestPresentationMessage>();
                var record  = await _proofService.ProcessRequestAsync(agentContext, message, messageContext.Connection);

                messageContext.ContextRecord = record;
                break;
            }

            case MessageTypes.PresentProofNames.Presentation:
            {
                var message = messageContext.GetMessage <PresentationMessage>();
                var record  = await _proofService.ProcessPresentationAsync(agentContext, message);

                messageContext.ContextRecord = record;
                break;
            }

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }
            return(null);
        }
        /// <inheritdoc />
        public async Task OnMessageAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            // TrustPingMessage event aggregator event doesn't include the connection so we can't verify whether the
            // received trust ping comes from the connection we send the connection response to.
            // For this reason we handle this specific case through a middleware where we do have the
            // connection from which the trust ping message came
            if (messageContext.GetMessageType() == MessageTypes.TrustPingMessageType)
            {
                var message = messageContext.GetMessage <TrustPingMessage>();

                var THConnection = _cache.Get <TestHarnessConnection>(messageContext.Connection.Id);

                if (THConnection != null && THConnection.State == TestHarnessConnectionState.Responded)
                {
                    THConnection.State = TestHarnessConnectionState.Complete;
                }
            }
            // When we receive a request presentation message we need to create a TestHarnessPresentationExchange and
            // store it in the cache for future use. This allow us to keep track of the current state of the presentation exchange
            else if (messageContext.GetMessageType() == MessageTypes.PresentProofNames.RequestPresentation)
            {
                var message = messageContext.GetMessage <RequestPresentationMessage>();

                var proofRecord = await _proofService.GetByThreadIdAsync(agentContext, message.GetThreadId());

                var THPresentationExchange = new TestHarnessPresentationExchange
                {
                    ThreadId = message.GetThreadId(),
                    RecordId = proofRecord.Id,
                    State    = TestHarnessPresentationExchangeState.RequestReceived,
                };

                _cache.Set(THPresentationExchange.ThreadId, THPresentationExchange);
            }
        }
Ejemplo n.º 3
0
        public static async Task <AgentMessage> ParseMessageAsync(string value)
        {
            string messageDecoded = null;

            if (value.StartsWith("http", StringComparison.OrdinalIgnoreCase) ||
                value.StartsWith("https", StringComparison.OrdinalIgnoreCase) ||
                value.StartsWith("didcomm", StringComparison.OrdinalIgnoreCase) ||
                value.StartsWith("id.streetcred", StringComparison.OrdinalIgnoreCase))
            {
                var url   = new Uri(value);
                var query = QueryHelpers.ParseQuery(url.Query);
                if (query.TryGetValue("c_i", out var messageEncoded) ||
                    query.TryGetValue("d_m", out messageEncoded) ||
                    query.TryGetValue("m", out messageEncoded))
                {
                    messageDecoded = Uri.UnescapeDataString(messageEncoded);
                }
                else
                {
                    var client = new HttpClient(new HttpClientHandler {
                        AllowAutoRedirect = false
                    });
                    var response = await client.GetAsync(value);

                    var invitationUri = response.Headers.Location;
                    query = QueryHelpers.ParseNullableQuery(invitationUri.Query);

                    if (query.TryGetValue("c_i", out messageEncoded) ||
                        query.TryGetValue("d_m", out messageEncoded) ||
                        query.TryGetValue("m", out messageEncoded))
                    {
                        messageDecoded = Uri.UnescapeDataString(messageEncoded);
                    }
                }
            }
            else
            {
                messageDecoded = Uri.UnescapeDataString(value);
            }

            // Because the decoder above strips the +
            // https://github.com/aspnet/HttpAbstractions/blob/bc7092a32b1943c7f17439e419d3f66cd94ce9bd/src/Microsoft.AspNetCore.WebUtilities/QueryHelpers.cs#L165
            messageDecoded = messageDecoded.Replace(' ', '+');

            var json            = messageDecoded.GetBytesFromBase64().GetUTF8String();
            var unpackedMessage = new UnpackedMessageContext(json, senderVerkey: null);

            switch (unpackedMessage.GetMessageType())
            {
            case MessageTypes.ConnectionInvitation:
                return(unpackedMessage.GetMessage <ConnectionInvitationMessage>());

//                case MessageTypes.EphemeralChallenge:
//                    return unpackedMessage.GetMessage<EphemeralChallengeMessage>();
            case MessageTypes.PresentProofNames.RequestPresentation:
                return(unpackedMessage.GetMessage <RequestPresentationMessage>());
            }
            return(null);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Processes the agent message
        /// </summary>
        /// <param name="agentContext"></param>
        /// <param name="messageContext">The agent message.</param>
        /// <returns></returns>
        /// <exception cref="AriesFrameworkException">Unsupported message type {messageType}</exception>
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            // v1
            case MessageTypes.IssueCredentialNames.OfferCredential:
            {
                var offer    = messageContext.GetMessage <CredentialOfferMessage>();
                var recordId = await _credentialService.ProcessOfferAsync(
                    agentContext, offer, messageContext.Connection);

                messageContext.ContextRecord = await _credentialService.GetAsync(agentContext, recordId);

                return(null);
            }

            case MessageTypes.IssueCredentialNames.RequestCredential:
            {
                var request  = messageContext.GetMessage <CredentialRequestMessage>();
                var recordId = await _credentialService.ProcessCredentialRequestAsync(
                    agentContext : agentContext,
                    credentialRequest : request,
                    connection : messageContext.Connection);

                if (request.ReturnRoutingRequested() && messageContext.Connection == null)
                {
                    var(message, record) = await _credentialService.CreateCredentialAsync(agentContext, recordId);

                    messageContext.ContextRecord = record;
                    return(message);
                }
                else
                {
                    messageContext.ContextRecord = await _credentialService.GetAsync(agentContext, recordId);

                    return(null);
                }
            }

            case MessageTypes.IssueCredentialNames.IssueCredential:
            {
                var credential = messageContext.GetMessage <CredentialIssueMessage>();
                var recordId   = await _credentialService.ProcessCredentialAsync(
                    agentContext, credential, messageContext.Connection);

                messageContext.ContextRecord = await UpdateValuesAsync(
                    credentialId : recordId,
                    credentialIssue : messageContext.GetMessage <CredentialIssueMessage>(),
                    agentContext : agentContext);

                return(null);
            }

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }
        }
        /// <summary>
        /// Processes the agent message
        /// </summary>
        /// <param name="agentContext"></param>
        /// <param name="messageContext">The agent message agentContext.</param>
        /// <returns></returns>
        /// <exception cref="AriesFrameworkException">Unsupported message type {message.Type}</exception>
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            case MessageTypesHttps.ConnectionAcknowledgement:
            case MessageTypes.ConnectionAcknowledgement:
            {
                var acknowledgementMessage = messageContext.GetMessage <ConnectionAcknowledgeMessage>();
                await _connectionService.ProcessAcknowledgementMessageAsync(agentContext, acknowledgementMessage);

                return(null);
            }

            case MessageTypesHttps.ConnectionInvitation:
            case MessageTypes.ConnectionInvitation:
            {
                var invitation = messageContext.GetMessage <ConnectionInvitationMessage>();
                await _connectionService.ProcessInvitationAsync(agentContext, invitation);

                return(null);
            }

            case MessageTypesHttps.ConnectionRequest:
            case MessageTypes.ConnectionRequest:
            {
                var request      = messageContext.GetMessage <ConnectionRequestMessage>();
                var connectionId = await _connectionService.ProcessRequestAsync(agentContext, request, messageContext.Connection);

                messageContext.ContextRecord = messageContext.Connection;

                // Auto accept connection if set during invitation
                if (messageContext.Connection.GetTag(TagConstants.AutoAcceptConnection) == "true")
                {
                    var(message, record) = await _connectionService.CreateResponseAsync(agentContext, connectionId);

                    messageContext.ContextRecord = record;
                    return(message);
                }
                return(null);
            }

            case MessageTypesHttps.ConnectionResponse:
            case MessageTypes.ConnectionResponse:
            {
                var response = messageContext.GetMessage <ConnectionResponseMessage>();
                await _connectionService.ProcessResponseAsync(agentContext, response, messageContext.Connection);

                messageContext.ContextRecord = messageContext.Connection;
                return(null);
            }

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }
        }
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            var msgJson = messageContext.GetMessageJson();

            switch (messageContext.GetMessageType())
            {
            case BackupTypeNames.RetrieveBackupAgentMessage:
            {
                var message = messageContext.GetMessage <RetrieveBackupAgentMessage>();

                var signature = message.Signature.GetBytesFromBase64();
                var backupId  = Multibase.Base58.Decode(message.BackupId);

                var result = await Crypto.VerifyAsync(
                    message.BackupId,
                    backupId,
                    signature);


                if (!result)
                {
                    throw new ArgumentException($"{nameof(result)} signature does not match the signer");
                }

                var backupAttachments = await _storageService.RetrieveBackupAsync(message.BackupId);

                return(new RetrieveBackupResponseAgentMessage
                    {
                        Payload = backupAttachments
                    });
            }

            case BackupTypeNames.ListBackupsAgentMessage:
            {
                var message    = messageContext.GetMessage <ListBackupsAgentMessage>();
                var backupList = await _storageService.ListBackupsAsync(message.BackupId);

                var timestampList = backupList.Select(p => new DirectoryInfo(p).Name);

                return(new ListBackupsResponseAgentMessage
                    {
                        BackupList = timestampList
                                     .Select(x => long.Parse(x))
                                     .OrderByDescending(x => x)
                                     .ToList()
                    });
            }
            }

            return(null);
        }
        /// <summary>
        /// Processes the agent message
        /// </summary>
        /// <param name="agentContext"></param>
        /// <param name="messageContext">The agent message.</param>
        /// <returns></returns>
        /// <exception cref="AriesFrameworkException">Unsupported message type {messageType}</exception>
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            case CustomMessageTypes.AckPresentation:
            case CustomMessageTypes.AckPresentationHttps:
            {
                var presentationAck = messageContext.GetMessage <AckPresentationMessage>();

                var threadId = presentationAck.GetThreadId();
                var THPresentationExchange = _proofCache.Get <TestHarnessPresentationExchange>(threadId);

                if (presentationAck.Status == "OK" && THPresentationExchange.State == TestHarnessPresentationExchangeState.PresentationSent)
                {
                    THPresentationExchange.State = TestHarnessPresentationExchangeState.Done;
                }

                break;
            }

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }

            return(null);
        }
        /// <summary>
        /// Processes the agent message
        /// </summary>
        /// <param name="agentContext">The agent context.</param>
        /// <param name="messageContext">The agent message context.</param>
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            await Task.Yield();

            switch (messageContext.GetMessageType())
            {
            case CustomMessageTypes.TrustPingMessageType:
            {
                var pingMessage = messageContext.GetMessage <TrustPingMessage>();

                if (pingMessage.ResponseRequested)
                {
                    return(pingMessage.CreateThreadedReply <TrustPingResponseMessage>());
                }
                break;
            }

            case CustomMessageTypes.TrustPingResponseMessageType:
            {
                _eventAggregator.Publish(new ServiceMessageProcessingEvent
                    {
                        MessageType = CustomMessageTypes.TrustPingResponseMessageType
                    });
                break;
            }
            }
            return(null);
        }
Ejemplo n.º 9
0
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            case MessageTypesHttps.DidExchange.Request:
                var request = messageContext.GetMessage <DidExchangeRequestMessage>();
                try
                {
                    await _didExchangeService.ProcessRequestAsync(agentContext, request);
                }
                catch (Exception)
                {
                    return(CreateProblemReportMessage(request));
                }

                return(null);

            case MessageTypesHttps.DidExchange.Response:
                var response = messageContext.GetMessage <DidExchangeResponseMessage>();
                try
                {
                    await _didExchangeService.ProcessResponseAsync(agentContext, response, messageContext.Connection);
                }
                catch (Exception)
                {
                    return(CreateProblemReportMessage(response));
                }

                return(null);

            case MessageTypesHttps.DidExchange.Complete:
                var complete = messageContext.GetMessage <DidExchangeCompleteMessage>();
                await _didExchangeService.ProcessComplete(agentContext, complete, messageContext.Connection);

                return(null);

            case MessageTypesHttps.DidExchange.ProblemReport:
                var problemReport = messageContext.GetMessage <DidExchangeProblemReportMessage>();
                await _didExchangeService.ProcessProblemReportMessage(agentContext, problemReport, messageContext.Connection);

                return(null);

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }
        }
Ejemplo n.º 10
0
        public static AgentMessage GetInternalMessage(UnpackedMessageContext source)
        {
            switch (source.GetMessageType())
            {
            //MessageTypes.ConnectionInvitation
            case MessageTypes.ConnectionInvitation:
                return(source.GetMessage <ConnectionInvitationMessage>());

            //MessageTypes.PresentProofNames
            case MessageTypes.PresentProofNames.RequestPresentation:
                return(source.GetMessage <RequestPresentationMessage>());

            //MessageTypes.IssueCredentialNames
            case MessageTypes.IssueCredentialNames.OfferCredential:
                return(source.GetMessage <CredentialOfferMessage>());

            default:
                return(null);
            }
        }
        /// <inheritdoc />
        public async Task OnMessageAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            var message          = messageContext.GetMessage <AnyAgentMessage>();
            var requestDecorator = message.FindDecorator <PaymentRequestDecorator>("payment_request");

            if (requestDecorator != null)
            {
                var record = new PaymentRecord
                {
                    ConnectionId = messageContext.Connection.Id,
                    Details      = requestDecorator.Details,
                    ReferenceId  = requestDecorator.Details.Id,
                    Address      = requestDecorator.Method.Data.PayeeId,
                    Amount       = requestDecorator.Details.Total.Amount.Value
                };
                await record.TriggerAsync(PaymentTrigger.RequestReceived);

                await _recordService.AddAsync(agentContext.Wallet, record);

                if (messageContext.ContextRecord != null)
                {
                    messageContext.ContextRecord.SetTag("PaymentRecordId", record.Id);
                    await _recordService.UpdateAsync(agentContext.Wallet, messageContext.ContextRecord);
                }
            }

            var receiptDecorator = message.FindDecorator <PaymentReceiptDecorator>("payment_receipt");

            if (receiptDecorator != null)
            {
                var search = await _recordService.SearchAsync <PaymentRecord>(
                    wallet : agentContext.Wallet,
                    query : SearchQuery.Equal(nameof(PaymentRecord.ReferenceId), receiptDecorator.RequestId),
                    options : null,
                    count : 5);

                var record = search.FirstOrDefault() ?? new PaymentRecord();
                record.ReceiptId = receiptDecorator.TransactionId;

                await record.TriggerAsync(PaymentTrigger.ReceiptReceived);

                if (search.Any())
                {
                    await _recordService.UpdateAsync(agentContext.Wallet, record);
                }
                else
                {
                    await _recordService.AddAsync(agentContext.Wallet, record);
                }
            }
        }
Ejemplo n.º 12
0
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            if (messageContext.Connection == null ||
                messageContext.Connection.MultiPartyInvitation ||
                messageContext.Connection.State != ConnectionState.Connected)
            {
                throw new InvalidOperationException("Connection is missing or invalid");
            }

            switch (messageContext.GetMessageType())
            {
            case RoutingTypeNames.CreateInboxMessage:
                return(await CreateInboxAsync(agentContext, messageContext.Connection, messageContext.GetMessage <CreateInboxMessage>()));

            case RoutingTypeNames.AddRouteMessage:
                await AddRouteAsync(agentContext, messageContext.Connection, messageContext.GetMessage <AddRouteMessage>());

                break;

            case RoutingTypeNames.GetInboxItemsMessage:
                return(await GetInboxItemsAsync(agentContext, messageContext.Connection, messageContext.GetMessage <GetInboxItemsMessage>()));

            case RoutingTypeNames.DeleteInboxItemsMessage:
                await DeleteInboxItemsAsync(agentContext, messageContext.Connection, messageContext.GetMessage <DeleteInboxItemsMessage>());

                break;

            case RoutingTypeNames.AddDeviceInfoMessage:
                await AddDeviceInfoAsync(agentContext, messageContext.Connection, messageContext.GetMessage <AddDeviceInfoMessage>());

                break;

            default:
                break;
            }

            return(null);
        }
Ejemplo n.º 13
0
        /// <inheritdoc />
        public async Task OnMessageAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            // TrustPingMessage event aggregator event doesn't include the connection so we can't verify whether the
            // received trust ping comes from the connection we send the connection response to.
            // For this reason we handle this specific case through a middleware where we do have the
            // connection from which the trust ping message came
            // TODO: should we also move the other events to here, or should we keep it as is for the rest?
            if (messageContext.GetMessageType() == MessageTypes.TrustPingMessageType)
            {
                var message = messageContext.GetMessage <TrustPingMessage>();

                var THConnection = _cache.Get <TestHarnessConnection>(messageContext.Connection.Id);

                if (THConnection != null && THConnection.State == TestHarnessConnectionState.Responded)
                {
                    THConnection.State = TestHarnessConnectionState.Complete;
                }
            }
        }
        /// <summary>
        /// Processes the agent message
        /// </summary>
        /// <param name="agentContext"></param>
        /// <param name="messageContext">The agent message agentContext.</param>
        /// <returns></returns>
        /// <exception cref="AriesFrameworkException">Unsupported message type {message.Type}</exception>
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            case CustomMessageTypes.TransactionResponse:
            case CustomMessageTypes.TransactionResponseHttps:
            {
                var transaction = messageContext.GetMessage <TransactionResponseMessage>();
                await _transactionService.ProcessTransactionAsync(agentContext, transaction, messageContext.Connection);

                messageContext.ContextRecord = messageContext.Connection;
                return(null);
            }

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }
        }
Ejemplo n.º 15
0
        public async Task OnMessageAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            if (messageContext.GetMessageType() == new ForwardMessage().Type)
            {
                ForwardMessage forwardMessage = messageContext.GetMessage <ForwardMessage>();

                //if (forwardMessage.To == Environment.GetEnvironmentVariable("ACA_ROUTE"))
                if (forwardMessage.To == this.acaList.FirstOrDefault(kvp => kvp.Key == forwardMessage.To).Key)
                {
                    //var uri = new Uri(Environment.GetEnvironmentVariable("ACA_ENDPOINT"));
                    var uri = new Uri(this.acaList.First(kvp => kvp.Key == forwardMessage.To).Value);

                    var dispatcher = GetDispatcher(uri.Scheme);

                    //byte[] wireMsg = Encoding.UTF8.GetBytes(forwardMessage.ToString());
                    await dispatcher.DispatchAsync(uri, new PackedMessageContext(forwardMessage.Message));
                }
            }
        }
Ejemplo n.º 16
0
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            // v1.0
            case MessageTypesHttps.PresentProofNames.ProposePresentation:
            case MessageTypes.PresentProofNames.ProposePresentation:
            {
                var _proofService = App.Container.Resolve <IProofService>();
                var message       = messageContext.GetMessage <ProposePresentationMessage>();
                var record        = await _proofService.ProcessProposalAsync(agentContext, message, messageContext.Connection);

                messageContext.ContextRecord = record;
                break;
            }

            case MessageTypes.PresentProofNames.RequestPresentation:
            case MessageTypesHttps.PresentProofNames.RequestPresentation:
            {
                try
                {
                    var _proofService      = App.Container.Resolve <IProofService>();
                    var navigation         = App.Container.Resolve <INavigationService>();
                    var presentation       = messageContext.GetMessage <RequestPresentationMessage>();
                    var holderProofRequest =
                        await _proofService.ProcessRequestAsync(agentContext, presentation, messageContext.Connection);

                    messageContext.ContextRecord = await _proofService.GetAsync(agentContext, holderProofRequest.Id);

                    var transport = new ProofRequestTransport()
                    {
                        Message        = presentation,
                        MessageContext = messageContext,
                        Record         = messageContext.ContextRecord as ProofRecord
                    };

                    await navigation.NavigateToAsync <ProofRequestViewModel>(transport, NavigationType.Modal);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                break;
            }

            case MessageTypes.PresentProofNames.Presentation:
            case MessageTypesHttps.PresentProofNames.Presentation:
            {
                var _proofService = App.Container.Resolve <IProofService>();
                var message       = messageContext.GetMessage <PresentationMessage>();
                var record        = await _proofService.ProcessPresentationAsync(agentContext, message);

                messageContext.ContextRecord = record;
                break;
            }

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }
            return(null);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Processes the agent message
        /// </summary>
        /// <param name="agentContext"></param>
        /// <param name="messageContext">The agent message.</param>
        /// <returns></returns>
        /// <exception cref="AriesFrameworkException">Unsupported message type {messageType}</exception>
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            case MessageTypes.IssueCredentialNames.ProposeCredential:
            case MessageTypesHttps.IssueCredentialNames.ProposeCredential:
            {
                var credentialProposal = messageContext.GetMessage <CustomCredentialProposeMessage>();

                CredentialRecord credentialRecord;
                TestHarnessCredentialExchange THCredentialExchange;
                try
                {
                    // Credential can be proposed for an existing exchange
                    // so we must first check if the message contains
                    THCredentialExchange = _credentialCache.Get <TestHarnessCredentialExchange>(credentialProposal.GetThreadId());
                    credentialRecord     = await _credentialService.GetByThreadIdAsync(agentContext, THCredentialExchange.ThreadId);

                    // check if the proposal came from the same connection
                    if (messageContext.Connection?.Id != credentialRecord.ConnectionId)
                    {
                        throw new AriesFrameworkException(ErrorCode.RecordInInvalidState, "Connection from credential proposal is not same as previously stored record.");
                    }
                }
                catch
                {
                    // Create new CredentialRecord if no existing credential record exists
                    credentialRecord = new CredentialRecord
                    {
                        Id           = Guid.NewGuid().ToString(),
                        ConnectionId = messageContext.Connection?.Id,
                    };

                    credentialRecord.SetTag(TagConstants.Role, TagConstants.Issuer);
                    credentialRecord.SetTag(TagConstants.LastThreadId, credentialProposal.GetThreadId());

                    await _recordService.AddAsync(agentContext.Wallet, credentialRecord);

                    THCredentialExchange = new TestHarnessCredentialExchange
                    {
                        RecordId = credentialRecord.Id,
                        ThreadId = credentialProposal.GetThreadId(),
                        State    = TestHarnessCredentialExchangeState.ProposalReceived,
                    };
                    _credentialCache.Set(THCredentialExchange.ThreadId, THCredentialExchange);
                }

                // Updates that should be applied both when the credential record already exists or not
                credentialRecord.CredentialDefinitionId = credentialProposal.CredentialDefinitionId;
                credentialRecord.SchemaId = credentialProposal.SchemaId;
                credentialRecord.CredentialAttributesValues = credentialProposal.CredentialProposal?.Attributes
                                                              .Select(x => new CredentialPreviewAttribute
                    {
                        Name     = x.Name,
                        MimeType = x.MimeType,
                        Value    = x.Value
                    }).ToArray();
                // State should be proposal-received
                credentialRecord.State = CredentialState.Offered;

                await _recordService.UpdateAsync(agentContext.Wallet, credentialRecord);

                _eventAggregator.Publish(new ServiceMessageProcessingEvent
                    {
                        RecordId    = credentialRecord.Id,
                        MessageType = credentialProposal.Type,
                        ThreadId    = credentialProposal.GetThreadId()
                    });

                messageContext.ContextRecord = credentialRecord;

                return(null);
            }

            case MessageTypes.IssueCredentialNames.OfferCredential:
            case MessageTypesHttps.IssueCredentialNames.OfferCredential:
            {
                var offer    = messageContext.GetMessage <CredentialOfferMessage>();
                var recordId = await this.ProcessOfferAsync(
                    agentContext, offer, messageContext.Connection);

                messageContext.ContextRecord = await _credentialService.GetAsync(agentContext, recordId);

                return(null);
            }

            case MessageTypes.IssueCredentialNames.RequestCredential:
            case MessageTypesHttps.IssueCredentialNames.RequestCredential:
            {
                var request  = messageContext.GetMessage <CredentialRequestMessage>();
                var recordId = await _credentialService.ProcessCredentialRequestAsync(
                    agentContext : agentContext,
                    credentialRequest : request,
                    connection : messageContext.Connection);

                if (request.ReturnRoutingRequested() && messageContext.Connection == null)
                {
                    var(message, record) = await _credentialService.CreateCredentialAsync(agentContext, recordId);

                    messageContext.ContextRecord = record;
                    return(message);
                }
                else
                {
                    messageContext.ContextRecord = await _credentialService.GetAsync(agentContext, recordId);

                    return(null);
                }
            }

            case MessageTypes.IssueCredentialNames.IssueCredential:
            case MessageTypesHttps.IssueCredentialNames.IssueCredential:
            {
                var credential = messageContext.GetMessage <CredentialIssueMessage>();
                var recordId   = await _credentialService.ProcessCredentialAsync(
                    agentContext, credential, messageContext.Connection);

                messageContext.ContextRecord = await UpdateValuesAsync(
                    credentialId : recordId,
                    credentialIssue : messageContext.GetMessage <CredentialIssueMessage>(),
                    agentContext : agentContext);

                return(null);
            }

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }
        }
Ejemplo n.º 18
0
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            case MessageTypesHttps.ConnectionInvitation:
            case MessageTypes.ConnectionInvitation:
            {
                var invitation = messageContext.GetMessage <ConnectionInvitationMessage>();
                await _connectionService.CreateRequestAsync(agentContext, invitation);

                return(null);
            }

            case MessageTypesHttps.ConnectionRequest:
            case MessageTypes.ConnectionRequest:
            {
                var request      = messageContext.GetMessage <ConnectionRequestMessage>();
                var connectionId = await _connectionService.ProcessRequestAsync(agentContext, request, messageContext.Connection);

                messageContext.ContextRecord = messageContext.Connection;

                // Auto accept connection if set during invitation
                if (messageContext.Connection.GetTag(TagConstants.AutoAcceptConnection) == "true")
                {
                    var(message, record) = await _connectionService.CreateResponseAsync(agentContext, connectionId);

                    messageContext.ContextRecord = record;
                    return(message);
                }
                else
                {
                    //var (message, record) = await _connectionService.CreateResponseAsync(agentContext, connectionId);
                    //messageContext.ContextRecord = record;

                    List <object> data = new List <object>();
                    data.Add(request);
                    data.Add(connectionId);
                    //data.Add(record);
                    //new WalletEventService().ShowAcceptRequestDialog(data);
                    Device.BeginInvokeOnMainThread(async() => await _navigationService.NavigateToAsync <AcceptRequestViewModel>(data, NavigationType.Modal));
                    return(null);
                }
                //return null;
            }

            case MessageTypesHttps.ConnectionResponse:
            case MessageTypes.ConnectionResponse:
            {
                var response = messageContext.GetMessage <ConnectionResponseMessage>();
                await _connectionService.ProcessResponseAsync(agentContext, response, messageContext.Connection);

                messageContext.ContextRecord = messageContext.Connection;

                var attachment = response.GetAttachment("agent-profile-pic");
                messageContext.Connection.Alias.ImageUrl = attachment.Data.Base64;
                var context = await _agentContextProvider.GetContextAsync();

                await _walletRecordService.UpdateAsync(context.Wallet, messageContext.Connection);

                return(null);
            }

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }
        }
Ejemplo n.º 19
0
        /*
         *
         * [Issuer: Creates offer for Holder.]
         * [Issuer: Sends offer for Holder.]
         *
         * Holder: Receives credential offer.
         * Holder: Process the credential offer by storing it.
         *
         * (Holder: Creates master secret if not already.)
         *
         * Holder: Sends a credential request using the stored offer id.
         *
         * [Issuer: Retrieved credential request]
         * [Issuer: Receives the credential request and sends a credential issue message]
         *
         * Holder: Receives the credential issue message.
         * Holder: Process the message and store its.
         */


        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            switch (messageContext.GetMessageType())
            {
            // v1
            case MessageTypesHttps.IssueCredentialNames.OfferCredential:
            case MessageTypes.IssueCredentialNames.OfferCredential:
            {
                try
                {
                    var navigation         = App.Container.Resolve <INavigationService>();
                    var _credentialService = App.Container.Resolve <ICredentialService>();

                    var offer = messageContext.GetMessage <CredentialOfferMessage>();

                    Console.WriteLine("New Credential Offering: {0}", offer.Id);

                    var recordId = await _credentialService.ProcessOfferAsync(
                        agentContext, offer, messageContext.Connection);

                    messageContext.ContextRecord = await _credentialService.GetAsync(agentContext, recordId);

                    var transport = new CredentialOfferTransport()
                    {
                        Record         = messageContext.ContextRecord as CredentialRecord,
                        Message        = offer,
                        MessageContext = messageContext
                    };

                    await navigation.NavigateToAsync <CredentialOfferPageViewModel>(transport, NavigationType.Modal);
                }
                catch (Exception ex)
                {
                    Tracking.TrackException(ex);
                }
                return(null);
            }

            case MessageTypesHttps.IssueCredentialNames.RequestCredential:
            case MessageTypes.IssueCredentialNames.RequestCredential:
            {
                var request  = messageContext.GetMessage <CredentialRequestMessage>();
                var recordId = await _credentialService.ProcessCredentialRequestAsync(
                    agentContext : agentContext,
                    credentialRequest : request,
                    connection : messageContext.Connection);

                if (request.ReturnRoutingRequested() && messageContext.Connection == null)
                {
                    var(message, record) = await _credentialService.CreateCredentialAsync(agentContext, recordId);

                    messageContext.ContextRecord = record;
                    return(message);
                }
                else
                {
                    // Auto create credential if set in the agent option
                    if (_agentOptions != null && _agentOptions.AutoRespondCredentialRequest)
                    {
                        var(message, record) =
                            await _credentialService.CreateCredentialAsync(agentContext, recordId);

                        messageContext.ContextRecord = record;
                        return(message);
                    }
                    messageContext.ContextRecord = await _credentialService.GetAsync(agentContext, recordId);

                    return(null);
                }
            }

            case MessageTypesHttps.IssueCredentialNames.IssueCredential:
            case MessageTypes.IssueCredentialNames.IssueCredential:
            {
                try
                {
                    var navigation         = App.Container.Resolve <INavigationService>();
                    var _credentialService = App.Container.Resolve <ICredentialService>();

                    var credential = messageContext.GetMessage <CredentialIssueMessage>();
                    var recordId   = await _credentialService.ProcessCredentialAsync(
                        agentContext, credential, messageContext.Connection);

                    messageContext.ContextRecord = await UpdateValuesAsync(
                        credentialId : recordId,
                        credentialIssue : messageContext.GetMessage <CredentialIssueMessage>(),
                        agentContext : agentContext);
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                    SentrySdk.CaptureException(ex);
                    Console.WriteLine(ex.Message);
                }
                return(null);
            }

            default:
                throw new AriesFrameworkException(ErrorCode.InvalidMessage,
                                                  $"Unsupported message type {messageContext.GetMessageType()}");
            }
        }