Exemplo n.º 1
0
        private void AddOrUpdateConnection(ConnectionRecord connectionRecord)
        {
            foreach (ConnectionViewModel connection in Connections)
            {
                if (connectionRecord.Id == connection.Id)
                {
                    connection.ConnectionSubtitle = ConnectionStateTranslator.Translate(connectionRecord.State);
                    return;
                }
            }
            var con = _scope.Resolve <ConnectionViewModel>(new NamedParameter("record", connectionRecord));

            if (string.IsNullOrWhiteSpace(con.ConnectionName))
            {
                con.ConnectionName = "Agent Médiateur";
            }
            con.ConnectionSubtitle = ConnectionStateTranslator.Translate(connectionRecord.State);
            DateTime datetime = DateTime.Now;

            if (connectionRecord.CreatedAtUtc.HasValue)
            {
                datetime     = connectionRecord.CreatedAtUtc.Value.ToLocalTime();
                con.DateTime = datetime;
            }
            Connections.Insert(0, con);
        }
Exemplo n.º 2
0
 private void UpdateConnection(ConnectionRecord connection)
 {
     txtServer.Text   = connection.Server;
     txtDatabase.Text = connection.Database;
     txtUser.Text     = connection.User;
     txtPassword.Text = connection.Password;
 }
Exemplo n.º 3
0
        public async Task CanUpdateRecordWithTags()
        {
            var tagName  = Guid.NewGuid().ToString();
            var tagValue = Guid.NewGuid().ToString();

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

            var record = new ConnectionRecord {
                ConnectionId = id
            };

            record.Tags.Add(tagName, tagValue);

            await _recordService.AddAsync(_wallet, record);

            var retrieved = await _recordService.GetAsync <ConnectionRecord>(_wallet, id);

            retrieved.MyDid         = "123";
            retrieved.Tags[tagName] = "value";

            await _recordService.UpdateAsync(_wallet, retrieved);

            var updated = await _recordService.GetAsync <ConnectionRecord>(_wallet, id);

            Assert.NotNull(updated);
            Assert.Equal(updated.GetId(), record.GetId());
            Assert.True(updated.Tags.ContainsKey(tagName));
            Assert.Equal("value", updated.Tags[tagName]);
            Assert.Equal("123", updated.MyDid);
        }
Exemplo n.º 4
0
        public async Task CanStoreAndRetrieveRecordWithTagsUsingSearch()
        {
            var tagName  = Guid.NewGuid().ToString();
            var tagValue = Guid.NewGuid().ToString();

            var record = new ConnectionRecord {
                ConnectionId = Guid.NewGuid().ToString()
            };

            record.Tags.Add(tagName, tagValue);

            await _recordService.AddAsync(_wallet, record);

            var search =
                await _recordService.SearchAsync <ConnectionRecord>(_wallet,
                                                                    new SearchRecordQuery()
            {
                { tagName, tagValue }
            }, null, 100);

            var retrieved = search.Single();

            Assert.NotNull(retrieved);
            Assert.Equal(retrieved.GetId(), record.GetId());
            Assert.True(retrieved.Tags.ContainsKey(tagName));
            Assert.Equal(tagValue, retrieved.Tags[tagName]);
        }
Exemplo n.º 5
0
        public void InitialConnectionRecordIsInvitedAndHasTag()
        {
            var record = new ConnectionRecord();

            Assert.True(record.State == ConnectionState.Invited);
            Assert.True(record.Tags[TagConstants.State] == ConnectionState.Invited.ToString("G"));
        }
Exemplo n.º 6
0
        /// <inheritdoc />
        public virtual async Task <string> AcceptInvitationAsync(Wallet wallet, ConnectionInvitationMessage invitation)
        {
            Logger.LogInformation(LoggingEvents.AcceptInvitation, "Key {0}, Endpoint {1}",
                                  invitation.ConnectionKey, invitation.Endpoint.Uri);

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

            var connection = new ConnectionRecord
            {
                Endpoint     = invitation.Endpoint,
                MyDid        = my.Did,
                MyVk         = my.VerKey,
                ConnectionId = Guid.NewGuid().ToString().ToLowerInvariant()
            };

            connection.Tags.Add(TagConstants.MyDid, my.Did);

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

                if (string.IsNullOrEmpty(invitation.Name))
                {
                    connection.Tags.Add(TagConstants.Alias, invitation.Name);
                }
            }

            await connection.TriggerAsync(ConnectionTrigger.InvitationAccept);

            await RecordService.AddAsync(wallet, connection);

            var provisioning = await ProvisioningService.GetProvisioningAsync(wallet);

            var connectionDetails = new ConnectionDetails
            {
                Did      = my.Did,
                Verkey   = my.VerKey,
                Endpoint = provisioning.Endpoint
            };

            var request = await MessageSerializer.PackSealedAsync <ConnectionRequestMessage>(connectionDetails, wallet,
                                                                                             my.VerKey, invitation.ConnectionKey);

            request.Key  = invitation.ConnectionKey;
            request.Type = MessageUtils.FormatKeyMessageType(invitation.ConnectionKey, MessageTypes.ConnectionRequest);

            var forwardMessage = new ForwardToKeyEnvelopeMessage
            {
                Type    = MessageUtils.FormatKeyMessageType(invitation.ConnectionKey, MessageTypes.ForwardToKey),
                Content = request.ToJson()
            };

            await RouterService.ForwardAsync(forwardMessage, invitation.Endpoint);

            return(connection.GetId());
        }
 /// <summary>
 /// This constructor is used when proof request details are fetched from mediator
 /// </summary>
 public ProofRequestViewModel(IUserDialogs userDialogs,
                              INavigationService navigationService,
                              IAgentProvider agentContextProvider,
                              IProofService proofService,
                              ILifetimeScope scope,
                              ICredentialService credentialService,
                              IConnectionService connectionService,
                              IEventAggregator eventAggregator,
                              IMessageService messageService,
                              ProofRecord proofRecord,
                              ConnectionRecord connection) : base("Proof Request Detail", userDialogs, navigationService)
 {
     this.userDialogs          = userDialogs;
     this.navigationService    = navigationService;
     this.agentContextProvider = agentContextProvider;
     this.proofService         = proofService;
     this.scope             = scope;
     this.credentialService = credentialService;
     this.connectionService = connectionService;
     this.eventAggregator   = eventAggregator;
     this.messageService    = messageService;
     this.proofRecord       = proofRecord;
     this.connection        = connection;
     ConnectionLogo         = connection.Alias.ImageUrl;
     ConnectionName         = connection.Alias.Name;
     ProofRequest           = JsonConvert.DeserializeObject <ProofRequest>(proofRecord.RequestJson);
     ProofRequestName       = ProofRequest?.Name;
     RequestedAttributes    = new ObservableCollection <ProofRequestAttributeViewModel>();
     HasLogo = !string.IsNullOrWhiteSpace(ConnectionLogo);
 }
Exemplo n.º 8
0
        public ConnectionViewModel(IUserDialogs userDialogs,
                                   INavigationService navigationService,
                                   ICustomAgentContextProvider agentContextProvider,
                                   IMessageService messageService,
                                   IDiscoveryService discoveryService,
                                   IConnectionService connectionService,
                                   IEventAggregator eventAggregator,
                                   ConnectionRecord record) :
            base(nameof(ConnectionViewModel),
                 userDialogs,
                 navigationService)
        {
            _agentContextProvider = agentContextProvider;
            _messageService       = messageService;
            _discoveryService     = discoveryService;
            _connectionService    = connectionService;
            _eventAggregator      = eventAggregator;

            _record            = record;
            MyDid              = _record.MyDid;
            TheirDid           = _record.TheirDid;
            ConnectionName     = _record.Alias.Name;
            ConnectionSubtitle = $"{_record.State:G}";
            ConnectionImageUrl = _record.Alias.ImageUrl;
        }
Exemplo n.º 9
0
        public ConnectionViewModel(IUserDialogs userDialogs,
                                   INavigationService navigationService,
                                   IAgentProvider agentProvider,
                                   IMessageService messageService,
                                   IDiscoveryService discoveryService,
                                   IConnectionService connectionService,
                                   IEventAggregator eventAggregator,
                                   ConnectionRecord record) : base(nameof(ConnectionsViewModel), userDialogs, navigationService)
        {
            _agentProvider     = agentProvider;
            _messageService    = messageService;
            _discoveryService  = discoveryService;
            _connectionService = connectionService;
            _eventAggregator   = eventAggregator;
            _record            = record;
            someMaterialColor  = new Helpers.SomeMaterialColor();

            MyDid              = _record.MyDid;
            TheirDid           = _record.TheirDid;
            ConnectionName     = _record.Alias.Name;
            ConnectionSubtitle = $"{_record.State:G}";
            Title              = "Connection Detail";
            if (this._connectionImageUrl == null)
            {
                _connectionImageUrl = $"https://ui-avatars.com/api/?name={_connectionName}&length=1&background={_organizeColor}&color=fff&size=128";
            }
            else
            {
                _connectionImageUrl = _record.Alias.ImageUrl;
            }
            if (_record.CreatedAtUtc != null)
            {
                _createdDate = (DateTime)_record.CreatedAtUtc;
            }
        }
Exemplo n.º 10
0
        private async Task AddDeviceInfoAsync(IAgentContext agentContext, ConnectionRecord connection, AddDeviceInfoMessage addDeviceInfoMessage)
        {
            var inboxId = connection.GetTag("InboxId");

            if (inboxId == null)
            {
                throw new InvalidOperationException("Inbox was not found. Create an inbox first");
            }

            var deviceRecord = new DeviceInfoRecord
            {
                InboxId      = inboxId,
                DeviceId     = addDeviceInfoMessage.DeviceId,
                DeviceVendor = addDeviceInfoMessage.DeviceVendor
            };

            try
            {
                await recordService.AddAsync(agentContext.Wallet, deviceRecord);
            }
            catch (WalletItemAlreadyExistsException)
            {
            }
            catch (Exception e)
            {
                logger.LogError(e, "Unable to register device", addDeviceInfoMessage);
            }
        }
Exemplo n.º 11
0
        public async Task CanUpdateRecordWithTags()
        {
            var tagName  = Guid.NewGuid().ToString();
            var tagValue = Guid.NewGuid().ToString();

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

            var record = new ConnectionRecord {
                Id = id
            };

            record.SetTag(tagName, tagValue);

            await recordService.AddAsync(Context.Wallet, record);

            var retrieved = await recordService.GetAsync <ConnectionRecord>(Context.Wallet, id);

            retrieved.MyDid = "123";
            retrieved.SetTag(tagName, "value");

            await recordService.UpdateAsync(Context.Wallet, retrieved);

            var updated = await recordService.GetAsync <ConnectionRecord>(Context.Wallet, id);

            Assert.NotNull(updated);
            Assert.Equal(updated.Id, record.Id);
            Assert.NotNull(updated.GetTag(tagName));
            Assert.Equal("value", updated.GetTag(tagName));
            Assert.Equal("123", updated.MyDid);
        }
Exemplo n.º 12
0
        public async Task <OfferCredentialResponse> Handle
        (
            OfferCredentialRequest aOfferCredentialRequest,
            CancellationToken aCancellationToken
        )
        {
            IAgentContext agentContext = await AgentProvider.GetContextAsync();

            ProvisioningRecord provisioningRecord = await ProvisioningService.GetProvisioningAsync(agentContext.Wallet);

            ConnectionRecord connectionRecord = await ConnectionService.GetAsync(agentContext, aOfferCredentialRequest.ConnectionId);

            (CredentialOfferMessage credentialOfferMessage, _) =
                await CredentialService.CreateOfferAsync
                (
                    agentContext,
                    new OfferConfiguration
            {
                CredentialDefinitionId = aOfferCredentialRequest.CredentialDefinitionId,
                IssuerDid = provisioningRecord.IssuerDid,
                CredentialAttributeValues = aOfferCredentialRequest.CredentialPreviewAttributes
            }
                );

            await MessageService.SendAsync(agentContext.Wallet, credentialOfferMessage, connectionRecord);

            var response = new OfferCredentialResponse(aOfferCredentialRequest.CorrelationId);

            return(response);
        }
Exemplo n.º 13
0
        public void InitialConnectionRecordIsInvitedAndHasTag()
        {
            var record = new ConnectionRecord();

            Assert.True(record.State == ConnectionState.Invited);
            Assert.True(record.GetTag(nameof(ConnectionRecord.State)) == ConnectionState.Invited.ToString("G"));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AriesFrameworkException"/> class.
 /// </summary>
 /// <param name="errorCode">The error code.</param>
 /// <param name="message">The message.</param>
 /// <param name="contextRecord"></param>
 /// <param name="connectionRecord"></param>
 public AriesFrameworkException(ErrorCode errorCode, string message, RecordBase contextRecord, ConnectionRecord connectionRecord) :
     base(message)
 {
     ErrorCode        = errorCode;
     ContextRecord    = contextRecord;
     ConnectionRecord = connectionRecord;
 }
Exemplo n.º 15
0
        public override async Task InitializeAsync(object navigationData)
        {
            _connectionRecord = navigationData as ConnectionRecord;
            var context = await _agentContextProvider.GetContextAsync();

            var credentialsRecords = await _credentialService.ListAsync(context);

            List <SchemaRecord>     schemasList     = new List <SchemaRecord>();
            List <DefinitionRecord> definitionsList = new List <DefinitionRecord>();

            foreach (var credentialRecord in credentialsRecords)
            {
                if (credentialRecord.State == CredentialState.Rejected)
                {
                    continue;
                }
                var schemaResp = await _ledgerService.LookupSchemaAsync(context, credentialRecord.SchemaId);

                var schemaJobj = JObject.Parse(schemaResp?.ObjectJson ?? "");
                schemasList.Add(new SchemaRecord {
                    Id = schemaResp.Id, Name = schemaJobj.GetValue("name").ToString()
                });
                var defResp = await _ledgerService.LookupDefinitionAsync(context, credentialRecord.CredentialDefinitionId);

                definitionsList.Add(new DefinitionRecord {
                    Id = defResp.Id
                });
            }
            Schemas.InsertRange(schemasList);
            CredDefinitions.InsertRange(definitionsList);

            //CredDefinitions = await _schemaService.ListCredentialDefinitionsAsync(context.Wallet);
            await base.InitializeAsync(navigationData);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Constructs my DID doc in a pairwise relationship from a connection record and the agents provisioning record.
        /// </summary>
        /// <param name="connection">Connection record.</param>
        /// <param name="provisioningRecord">Provisioning record.</param>
        /// <returns>DID Doc</returns>
        public static DidDoc MyDidDoc(this ConnectionRecord connection, ProvisioningRecord provisioningRecord)
        {
            var doc = new DidDoc
            {
                Keys = new List <DidDocKey>
                {
                    new DidDocKey
                    {
                        Id              = $"{connection.MyDid}#keys-1",
                        Type            = DefaultKeyType,
                        Controller      = connection.MyDid,
                        PublicKeyBase58 = connection.MyVk
                    }
                }
            };

            if (!string.IsNullOrEmpty(provisioningRecord.Endpoint.Uri))
            {
                doc.Services = new List <IDidDocServiceEndpoint>
                {
                    new IndyAgentDidDocService
                    {
                        Id = $"{connection.MyDid};indy",
                        ServiceEndpoint = provisioningRecord.Endpoint.Uri,
                        RecipientKeys   = connection.MyVk != null ? new[] { connection.MyVk } : new string[0],
                        RoutingKeys     = provisioningRecord.Endpoint?.Verkey != null ? new[] { provisioningRecord.Endpoint.Verkey } : new string[0]
                    }
                };
            }

            return(doc);
        }
        /// <inheritdoc />
        public async Task <string> ProcessCredentialRequestAsync(IAgentContext agentContext, CredentialRequestMessage
                                                                 credentialRequest, ConnectionRecord connection)
        {
            Logger.LogInformation(LoggingEvents.StoreCredentialRequest, "Type {0},", credentialRequest.Type);

            // TODO Handle case when no thread is included
            var credential = await this.GetByThreadIdAsync(agentContext, credentialRequest.GetThreadId());

            var credentialAttachment = credentialRequest.Requests.FirstOrDefault(x => x.Id == "libindy-cred-request-0")
                                       ?? throw new ArgumentException("Credential request attachment not found.");

            if (credential.State != CredentialState.Offered)
            {
                throw new AriesFrameworkException(ErrorCode.RecordInInvalidState,
                                                  $"Credential state was invalid. Expected '{CredentialState.Offered}', found '{credential.State}'");
            }
            credential.RequestJson  = credentialAttachment.Data.Base64.GetBytesFromBase64().GetUTF8String();
            credential.ConnectionId = connection?.Id;
            await credential.TriggerAsync(CredentialTrigger.Request);

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

            EventAggregator.Publish(new ServiceMessageProcessingEvent
            {
                RecordId    = credential.Id,
                MessageType = credentialRequest.Type,
                ThreadId    = credentialRequest.GetThreadId()
            });
            return(credential.Id);
        }
Exemplo n.º 18
0
        public ConnectionViewModel Assemble(ConnectionRecord connectionRecord)
        {
            if (connectionRecord == null)
            {
                return(null);
            }

            ConnectionViewModel connection = _scope.Resolve <ConnectionViewModel>(new NamedParameter("record", connectionRecord));

            if (string.IsNullOrWhiteSpace(connection.ConnectionName))
            {
                connection.ConnectionName = "Agent Médiateur";
            }

            connection.ConnectionSubtitle = ConnectionStateTranslator.Translate(connectionRecord.State);

            DateTime datetime = DateTime.Now;

            if (connectionRecord.CreatedAtUtc.HasValue)
            {
                datetime            = connectionRecord.CreatedAtUtc.Value.ToLocalTime();
                connection.DateTime = datetime;
            }

            return(connection);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Look for the module of the user and create an instance of the database
        /// </summary>
        /// <param name="connectionId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static Common.Database.DatabaseManager CreateDatabase(string connectionId, int userId)
        {
            DatabaseContext dbContext = GetDatabase(Syncytium.Module.Administration.DatabaseContext.AREA_NAME);

            // Get the current connection properties to retrieve the user's area

            ConnectionRecord currentConnection = dbContext._Connection.FirstOrDefault(c => c.ConnectionId.Equals(connectionId) &&
                                                                                      c.Machine.Equals(Environment.MachineName) &&
                                                                                      c.UserId == userId);

            if (currentConnection == null)
            {
                Common.Logger.LoggerManager.Instance.Error("DatabaseManager", $"The connection '{connectionId}' doesn't exist!");
                throw new ExceptionDefinitionRecord("ERR_CONNECTION");
            }

            string area = currentConnection.Area;

            if (area == null || area.Equals(DatabaseContext.AREA_NAME))
            {
                return(new Syncytium.Common.Database.DatabaseManager(dbContext, new UserManager(dbContext), connectionId, userId));
            }

            // look for the current database manager

            dbContext.Dispose();
            dbContext = null;

            return(CreateDatabase(area, connectionId, userId));
        }
Exemplo n.º 20
0
        public async Task CanSearchMulipleProperties()
        {
            var record1 = new ConnectionRecord {
                State = ConnectionState.Connected, ConnectionId = "1"
            };
            var record2 = new ConnectionRecord
            {
                State        = ConnectionState.Connected,
                ConnectionId = "2",
                Tags         = { ["tagName"] = "tagValue" }
            };
            var record3 = new ConnectionRecord
            {
                State        = ConnectionState.Invited,
                ConnectionId = "3",
                Tags         = { ["tagName"] = "tagValue" }
            };

            await _recordService.AddAsync(_wallet, record1);

            await _recordService.AddAsync(_wallet, record2);

            await _recordService.AddAsync(_wallet, record3);


            var searchResult = await _recordService.SearchAsync <ConnectionRecord>(_wallet,
                                                                                   new SearchRecordQuery
            {
                { "State", ConnectionState.Connected.ToString("G") },
                { "tagName", "tagValue" }
            }, null, 10);

            Assert.Single(searchResult);
            Assert.Equal("2", searchResult.Single().ConnectionId);
        }
        private async Task AcceptProofRequest()
        {
            if (_proofRecord.State != ProofState.Requested)
            {
                await DialogService.AlertAsync(string.Format(AppResources.ProofStateShouldBeMessage, ProofStateTranslator.Translate(ProofState.Requested)));

                return;
            }

            RequestedCredentials requestedCredentials = new RequestedCredentials()
            {
                RequestedAttributes = new Dictionary <string, RequestedAttribute>(),
                RequestedPredicates = new Dictionary <string, RequestedAttribute>()
            };

            foreach (ProofAttributeViewModel proofAttribute in Attributes)
            {
                if (proofAttribute.IsPredicate)
                {
                    requestedCredentials.RequestedPredicates.Add(proofAttribute.Id, new RequestedAttribute {
                        CredentialId = proofAttribute.CredentialId, Revealed = proofAttribute.IsRevealed
                    });
                }
                else
                {
                    requestedCredentials.RequestedAttributes.Add(proofAttribute.Id, new RequestedAttribute {
                        CredentialId = proofAttribute.CredentialId, Revealed = proofAttribute.IsRevealed
                    });
                }
            }

            // TODO: Mettre le Timestamp à null car lorsqu'il est présent, la création de la preuve ne marche pas. Pourquoi?
            //foreach (var keyValue in requestedCredentials.RequestedAttributes.Values)
            //{
            //    keyValue.Timestamp = null;
            //}

            var context = await _agentContextProvider.GetContextAsync();

            ProofRecord proofRecord = await _recordService.GetAsync <ProofRecord>(context.Wallet, _proofRecord.Id);

            var(msg, rec) = await _proofService.CreatePresentationAsync(context, proofRecord.Id, requestedCredentials);

            if (string.IsNullOrEmpty(proofRecord.ConnectionId))
            {
                await _messageService.SendAsync(context.Wallet, msg, proofRecord.GetTag("RecipientKey"), proofRecord.GetTag("ServiceEndpoint"));
            }
            else
            {
                ConnectionRecord connectionRecord = await _recordService.GetAsync <ConnectionRecord>(context.Wallet, proofRecord.ConnectionId);

                await _messageService.SendAsync(context.Wallet, msg, connectionRecord);
            }

            _eventAggregator.Publish(new ApplicationEvent {
                Type = ApplicationEventType.ProofRequestUpdated
            });

            await NavigationService.PopModalAsync();
        }
        public async Task SendToConnectionAsyncThrowsInvalidMessageNoType()
        {
            var connection = new ConnectionRecord
            {
                Alias = new ConnectionAlias
                {
                    Name = "Test"
                },
                Endpoint = new AgentEndpoint
                {
                    Uri = "https://mock.com"
                },
                TheirVk = Guid.NewGuid().ToString()
            };

            var agentContext = new AgentContext()
            {
                Wallet = _wallet
            };
            var ex = await Assert.ThrowsAsync <AriesFrameworkException>(async() =>
                                                                        await _messagingService.SendAsync(agentContext, new MockAgentMessage {
                Id = Guid.NewGuid().ToString()
            }, connection));

            Assert.True(ex.ErrorCode == ErrorCode.InvalidMessage);
        }
Exemplo n.º 23
0
 public Task UpdateConnectionRecordAsync(ConnectionRecord record, CancellationToken cancellationToken = default)
 => UpdateItemAsync(
     record,
     pk: CONNECTION_PREFIX + record.ConnectionId,
     sk: INFO,
     cancellationToken
     );
        public async Task <CreateProofRequestResponse> Handle
        (
            CreateProofRequestRequest aCreateProofRequestRequest,
            CancellationToken aCancellationToken
        )
        {
            IAgentContext agentContext = await AgentProvider.GetContextAsync();

            ConnectionRecord connectionRecord = await ConnectionService.GetAsync(agentContext, aCreateProofRequestRequest.ConnectionId);

            aCreateProofRequestRequest.ProofRequest.Nonce = await AnonCreds.GenerateNonceAsync();

            (RequestPresentationMessage requestPresentationMessage, ProofRecord proofRecord) =
                await ProofService.CreateRequestAsync(agentContext, aCreateProofRequestRequest.ProofRequest, aCreateProofRequestRequest.ConnectionId);

            await MessageService.SendAsync(agentContext, requestPresentationMessage, connectionRecord);

            //(requestPresentationMessage, proofRecord) =
            //  await ProofService.CreateRequestAsync(agentContext, aSendRequestForProofRequest.ProofRequest);

            //string endpointUri = (await ProvisioningService.GetProvisioningAsync(agentContext.Wallet)).Endpoint.Uri;
            //string encodedRequestPresentationMessage = requestPresentationMessage.ToJson().ToBase64();
            //string proofRequestUrl = $"{endpointUri}?c_i={encodedRequestPresentationMessage}";

            var response = new CreateProofRequestResponse(requestPresentationMessage, aCreateProofRequestRequest.CorrelationId);

            return(await Task.Run(() => response));
        }
Exemplo n.º 25
0
        public async Task <bool> SetConnectionRecordStateAsync(ConnectionRecord record, ConnectionState state, CancellationToken cancellationToken = default)
        {
            try {
                await DynamoDbClient.UpdateItemAsync(new UpdateItemRequest {
                    TableName = TableName,
                    Key       = new Dictionary <string, AttributeValue> {
                        ["PK"] = new AttributeValue(CONNECTION_PREFIX + record.ConnectionId),
                        ["SK"] = new AttributeValue(INFO)
                    },
                    UpdateExpression         = "SET #State = :state, #Modified = :modified",
                    ExpressionAttributeNames =
                    {
                        ["#State"]    = nameof(record.State),
                        ["#Modified"] = "_Modified"
                    },
                    ExpressionAttributeValues =
                    {
                        [":state"]    = new AttributeValue(state.ToString()),
                        [":modified"] = new AttributeValue {
                            N = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()
                        }
                    }
                });

                record.State = state;
                return(true);
            } catch (ConditionalCheckFailedException) {
                return(false);
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Constructs their DID doc in a pairwise relationship from a connection record.
 /// </summary>
 /// <param name="connection">Connectio record.</param>
 /// <returns>DID Doc</returns>
 public static DidDoc TheirDidDoc(this ConnectionRecord connection)
 {
     return(new DidDoc
     {
         Keys = new List <DidDocKey>
         {
             new DidDocKey
             {
                 Id = $"{connection.MyDid}#keys-1",
                 Type = DefaultKeyType,
                 Controller = connection.TheirDid,
                 PublicKeyBase58 = connection.TheirVk
             }
         },
         Services = new List <IDidDocServiceEndpoint>
         {
             new IndyAgentDidDocService
             {
                 Id = $"{connection.MyDid};indy",
                 ServiceEndpoint = connection.Endpoint.Verkey,
                 RecipientKeys = connection.TheirVk != null ? new[] { connection.TheirVk } : new string[0],
                 RoutingKeys = connection.Endpoint?.Verkey != null ? new[] { connection.Endpoint.Verkey } : new string[0]
             }
         }
     });
 }
        public ConnectionViewModel(IUserDialogs userDialogs,
                                   INavigationService navigationService,
                                   IAgentProvider agentContextProvider,
                                   IMessageService messageService,
                                   IDiscoveryService discoveryService,
                                   IConnectionService connectionService,
                                   IEventAggregator eventAggregator,
                                   IWalletRecordService walletRecordService,
                                   ILifetimeScope scope,
                                   ConnectionRecord record) :
            base(nameof(ConnectionViewModel),
                 userDialogs,
                 navigationService)
        {
            _agentContextProvider = agentContextProvider;
            _messageService       = messageService;
            _discoveryService     = discoveryService;
            _connectionService    = connectionService;
            _eventAggregator      = eventAggregator;
            _walletRecordSevice   = walletRecordService;
            _scope = scope;

            _record               = record;
            MyDid                 = _record.MyDid;
            TheirDid              = _record.TheirDid;
            ConnectionName        = _record.Alias?.Name ?? _record.Id;
            ConnectionSubtitle    = $"{_record.State:G}";
            ConnectionImageUrl    = _record.Alias?.ImageUrl;
            ConnectionImageSource = Base64StringToImageSource.Base64StringToImage(_record.Alias?.ImageUrl);

            Messages = new ObservableCollection <RecordBase>();
        }
Exemplo n.º 28
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);
        }
Exemplo n.º 29
0
 public Task CreateConnectionAsync(ConnectionRecord record, CancellationToken cancellationToken = default)
 => PutItemsAsync(
     record,
     pk: CONNECTION_PREFIX + record.ConnectionId,
     sk: INFO,
     CreateItemConfig,
     cancellationToken
     );
Exemplo n.º 30
0
        /// <inheritdoc />
        public virtual async Task <(ConnectionInvitationMessage, ConnectionRecord)> CreateInvitationAsync(IAgentContext agentContext,
                                                                                                          InviteConfiguration config = null)
        {
            var connectionId = !string.IsNullOrEmpty(config?.ConnectionId)
                ? config.ConnectionId
                : Guid.NewGuid().ToString();

            config = config ?? new InviteConfiguration();

            Logger.LogInformation(LoggingEvents.CreateInvitation, "ConnectionId {0}", connectionId);

            var connectionKey = await Crypto.CreateKeyAsync(agentContext.Wallet, "{}");

            var connection = new ConnectionRecord {
                Id = connectionId
            };

            connection.SetTag(TagConstants.ConnectionKey, connectionKey);

            if (config.AutoAcceptConnection)
            {
                connection.SetTag(TagConstants.AutoAcceptConnection, "true");
            }

            connection.MultiPartyInvitation = config.MultiPartyInvitation;

            if (!config.MultiPartyInvitation)
            {
                connection.Alias = config.TheirAlias;
                if (!string.IsNullOrEmpty(config.TheirAlias.Name))
                {
                    connection.SetTag(TagConstants.Alias, config.TheirAlias.Name);
                }
            }

            foreach (var tag in config.Tags)
            {
                connection.SetTag(tag.Key, tag.Value);
            }

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

            if (string.IsNullOrEmpty(provisioning.Endpoint.Uri))
            {
                throw new AgentFrameworkException(ErrorCode.RecordInInvalidState, "Provision record has no endpoint information specified");
            }

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

            return(new ConnectionInvitationMessage
            {
                ServiceEndpoint = provisioning.Endpoint.Uri,
                RoutingKeys = provisioning.Endpoint.Verkey != null ? new[] { provisioning.Endpoint.Verkey } : null,
                RecipientKeys = new[] { connectionKey },
                Label = config.MyAlias.Name ?? provisioning.Owner.Name,
                ImageUrl = config.MyAlias.ImageUrl ?? provisioning.Owner.ImageUrl
            }, connection);
        }