public ProofRequestViewModel(IUserDialogs userDialogs,
                                     INavigationService navigationService,
                                     IProofService proofService,
                                     IAgentProvider agentContextProvider,
                                     IMessageService messageService,
                                     IConnectionService connectionService,
                                     IEventAggregator eventAggregator,
                                     IWalletRecordService recordService,
                                     IProofCredentialSelector proofCredentialSelector,
                                     ProofRecord proof) : base(AppResources.ProofRequestPageTitle, userDialogs, navigationService)
        {
            _proofRecord             = proof;
            _proofService            = proofService;
            _agentContextProvider    = agentContextProvider;
            _messageService          = messageService;
            _connectionService       = connectionService;
            _eventAggregator         = eventAggregator;
            _userDialogs             = userDialogs;
            _recordService           = recordService;
            _navigationService       = navigationService;
            _proofCredentialSelector = proofCredentialSelector;
            GetConnectionAlias();

            _proofRequest = JsonConvert.DeserializeObject <ProofRequest>(_proofRecord.RequestJson);

            ProofName = _proofRequest.Name;

            Version = _proofRequest.Version;

            State = ProofStateTranslator.Translate(_proofRecord.State);

            AreButtonsVisible = _proofRecord.State == ProofState.Requested;

            Attributes = new List <ProofAttributeViewModel>();
        }
 /// <summary>
 /// This constructor is used presentation request is scanned
 /// </summary>
 public ProofRequestViewModel(IUserDialogs userDialogs,
                              INavigationService navigationService,
                              IAgentProvider agentContextProvider,
                              IProofService proofService,
                              ILifetimeScope scope,
                              ICredentialService credentialService,
                              IConnectionService connectionService,
                              IEventAggregator eventAggregator,
                              IMessageService messageService,
                              ProofRequest proofRequest,
                              RequestPresentationMessage requestPresentationMessage) : 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.requestPresentationMessage = requestPresentationMessage;
     ConnectionName                  = "Scanned Presentation Request";
     ProofRequest                    = proofRequest;
     ProofRequestName                = ProofRequest?.Name;
     RequestedAttributes             = new ObservableCollection <ProofRequestAttributeViewModel>();
     HasLogo = !string.IsNullOrWhiteSpace(ConnectionLogo);
 }
Exemplo n.º 3
0
        /// <inheritdoc />
        public virtual async Task <string> CreateProofAsync(IAgentContext agentContext,
                                                            ProofRequest proofRequest, RequestedCredentials requestedCredentials)
        {
            var provisioningRecord = await ProvisioningService.GetProvisioningAsync(agentContext.Wallet);

            var credentialObjects = new List <CredentialInfo>();

            foreach (var credId in requestedCredentials.GetCredentialIdentifiers())
            {
                credentialObjects.Add(
                    JsonConvert.DeserializeObject <CredentialInfo>(
                        await AnonCreds.ProverGetCredentialAsync(agentContext.Wallet, credId)));
            }

            var schemas = await BuildSchemasAsync(await agentContext.Pool,
                                                  credentialObjects
                                                  .Select(x => x.SchemaId)
                                                  .Distinct());

            var definitions = await BuildCredentialDefinitionsAsync(await agentContext.Pool,
                                                                    credentialObjects
                                                                    .Select(x => x.CredentialDefinitionId)
                                                                    .Distinct());

            var revocationStates = await BuildRevocationStatesAsync(await agentContext.Pool,
                                                                    credentialObjects,
                                                                    requestedCredentials);

            var proofJson = await AnonCreds.ProverCreateProofAsync(agentContext.Wallet, proofRequest.ToJson(),
                                                                   requestedCredentials.ToJson(), provisioningRecord.MasterSecretId, schemas, definitions,
                                                                   revocationStates);

            return(proofJson);
        }
Exemplo n.º 4
0
        public async Task <GetCredentialsForProofResponse> Handle
        (
            GetCredentialsForProofRequest aGetCredentialsForProofRequest,
            CancellationToken aCancellationToken
        )
        {
            IAgentContext agentContext = await AgentProvider.GetContextAsync();

            ProofRecord proofRecord = await ProofService.GetAsync(agentContext, aGetCredentialsForProofRequest.ProofId);

            ProofRequest proofRequest = JsonConvert.DeserializeObject <ProofRequest>(proofRecord.RequestJson);

            //ProofServiceUtils.GetAutoRequestedCredentialsForProofCredentials
            List <Credential> credentials =
                await ProofService
                .ListCredentialsForProofRequestAsync
                (
                    agentContext,
                    proofRequest,
                    aGetCredentialsForProofRequest.Referent
                );

            var response = new GetCredentialsForProofResponse(credentials, aGetCredentialsForProofRequest.CorrelationId);

            return(response);
        }
Exemplo n.º 5
0
        public static async Task <(ProofRecord holderProofRecord, ProofRecord RequestorProofRecord)> ProofProtocolAsync(
            IProofService proofService,
            IProducerConsumerCollection <AgentMessage> messages,
            ConnectionRecord holderConnection, ConnectionRecord requestorConnection,
            IAgentContext holderContext,
            IAgentContext requestorContext, ProofRequest proofRequestObject)
        {
            //Requestor sends a proof request
            var(message, requestorProofRecord) = await proofService.CreateRequestAsync(requestorContext, proofRequestObject, requestorConnection.Id);

            messages.TryAdd(message);

            // Holder accepts the proof requests and builds a proof
            var proofRequest = FindContentMessage <RequestPresentationMessage>(messages);

            Assert.NotNull(proofRequest);

            //Holder stores the proof request
            var holderProofRequestRecord = await proofService.ProcessRequestAsync(holderContext, proofRequest, holderConnection);

            var holderProofRecord = await proofService.GetAsync(holderContext, holderProofRequestRecord.Id);

            var holderProofRequest = JsonConvert.DeserializeObject <ProofRequest>(holderProofRecord.RequestJson);

            // Auto satify the proof with which ever credentials in the wallet are capable
            var requestedCredentials =
                await ProofServiceUtils.GetAutoRequestedCredentialsForProofCredentials(holderContext, proofService,
                                                                                       holderProofRequest);

            //Holder accepts the proof request and sends a proof
            (var proofMessage, _) = await proofService.CreatePresentationAsync(
                holderContext,
                holderProofRequestRecord.Id,
                requestedCredentials);

            messages.TryAdd(proofMessage);

            //Requestor retrives proof message from their cloud agent
            var proof = FindContentMessage <PresentationMessage>(messages);

            Assert.NotNull(proof);

            //Requestor stores proof
            requestorProofRecord = await proofService.ProcessPresentationAsync(requestorContext, proof);

            //Requestor verifies proof
            var requestorVerifyResult = await proofService.VerifyProofAsync(requestorContext, requestorProofRecord.Id);

            //Verify the proof is valid
            Assert.True(requestorVerifyResult);

            var requestorProofRecordResult = await proofService.GetAsync(requestorContext, requestorProofRecord.Id);

            var holderProofRecordResult = await proofService.GetAsync(holderContext, holderProofRecord.Id);

            return(holderProofRecordResult, requestorProofRecordResult);
        }
        public async Task <ProofRequestViewModel> Assemble(ProofRecord proofRecord)
        {
            if (proofRecord == null)
            {
                return(null);
            }

            ProofRequestViewModel proofRequest2 = _scope.Resolve <ProofRequestViewModel>(new NamedParameter("proof", proofRecord));

            proofRequest2.Id = proofRecord.Id;

            if (proofRecord.ProofJson != null)
            {
                var partialProof = JsonConvert.DeserializeObject <PartialProof>(proofRecord.ProofJson);
                var proofRequest = JsonConvert.DeserializeObject <ProofRequest>(proofRecord.RequestJson);
                proofRequest2.Attributes.Clear();
                foreach (var revealedAttributeKey in partialProof.RequestedProof.RevealedAttributes.Keys)
                {
                    var proofAttribute = new ProofAttributeViewModel
                    {
                        Name        = proofRequest.RequestedAttributes[revealedAttributeKey].Name, // TODO: Que faire pour gérer l'attribut Names?
                        IsPredicate = false,
                        IsRevealed  = true,
                        Type        = "Text",
                        Value       = partialProof.RequestedProof.RevealedAttributes[revealedAttributeKey].Raw
                    };
                    proofRequest2.Attributes.Add(proofAttribute);
                }
            }
            else
            {
                ProofRequest proofRequest = JsonConvert.DeserializeObject <ProofRequest>(proofRecord.RequestJson);
                proofRequest2.Attributes.Clear();
                foreach (KeyValuePair <string, ProofAttributeInfo> requestedAttribute in proofRequest.RequestedAttributes)
                {
                    proofRequest2.Attributes.Add(new ProofAttributeViewModel
                    {
                        Id   = requestedAttribute.Key,
                        Name = requestedAttribute.Value.Name // TODO: Que faire pour gérer l'attribut Names?
                    });
                }
                foreach (KeyValuePair <string, ProofPredicateInfo> requestedAttribute in proofRequest.RequestedPredicates)
                {
                    proofRequest2.Attributes.Add(new ProofAttributeViewModel
                    {
                        Id          = requestedAttribute.Key,
                        Name        = requestedAttribute.Value.Name, // TODO: Que faire pour gérer l'attribut Names?
                        IsPredicate = true
                    });
                }
            }

            proofRequest2.State = ProofStateTranslator.Translate(proofRecord.State);

            return(proofRequest2);
        }
Exemplo n.º 7
0
        public async Task RejectProofRequestCredentialInvalidState()
        {
            //Setup a connection and issue the credentials to the holder
            var(issuerConnection, holderConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _issuerWallet, _holderWallet);

            await Scenarios.IssueCredentialAsync(
                _schemaService, _credentialService, _messages, issuerConnection,
                holderConnection, _issuerWallet, _holderWallet, await _holderWallet.Pool, TestConstants.DefaultMasterSecret, true, new List <CredentialPreviewAttribute>
            {
                new CredentialPreviewAttribute("first_name", "Test"),
                new CredentialPreviewAttribute("last_name", "Holder")
            });

            _messages.Clear();

            //Requestor initialize a connection with the holder
            var(_, requestorConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _holderWallet, _requestorWallet);

            // Verifier sends a proof request to prover
            {
                var proofRequestObject = new ProofRequest
                {
                    Name                = "ProofReq",
                    Version             = "1.0",
                    Nonce               = await AnonCreds.GenerateNonceAsync(),
                    RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                    {
                        { "first-name-requirement", new ProofAttributeInfo {
                              Name = "first_name"
                          } }
                    }
                };

                //Requestor sends a proof request
                var(message, _) = await _proofService.CreateRequestAsync(_requestorWallet, proofRequestObject, requestorConnection.Id);

                _messages.Add(message);
            }

            //Holder retrieves proof request message from their cloud agent
            var proofRequest = FindContentMessage <RequestPresentationMessage>();

            Assert.NotNull(proofRequest);

            //Holder stores the proof request
            var holderProofRequestId = await _proofService.ProcessRequestAsync(_holderWallet, proofRequest, holderConnection);

            //Holder accepts the proof request and sends a proof
            await _proofService.RejectProofRequestAsync(_holderWallet, holderProofRequestId.Id);

            var ex = await Assert.ThrowsAsync <AriesFrameworkException>(async() => await _proofService.RejectProofRequestAsync(_holderWallet, holderProofRequestId.Id));

            Assert.True(ex.ErrorCode == ErrorCode.RecordInInvalidState);
        }
        /// <inheritdoc />
        public virtual async Task <ProofRequestMessage> CreateProofRequestAsync(Wallet wallet, string connectionId,
                                                                                ProofRequest proofRequest)
        {
            if (string.IsNullOrWhiteSpace(proofRequest.Nonce))
            {
                throw new ArgumentNullException(nameof(proofRequest.Nonce), "Nonce must be set.");
            }

            return(await CreateProofRequestAsync(wallet, connectionId, proofRequest.ToJson()));
        }
Exemplo n.º 9
0
        /// <inheritdoc />
        public virtual async Task <(ProofRequestMessage, ProofRecord)> CreateProofRequestAsync(
            IAgentContext agentContext, ProofRequest proofRequest,
            string connectionId)
        {
            if (string.IsNullOrWhiteSpace(proofRequest.Nonce))
            {
                throw new ArgumentNullException(nameof(proofRequest.Nonce), "Nonce must be set.");
            }

            return(await CreateProofRequestAsync(agentContext, proofRequest.ToJson(), connectionId));
        }
Exemplo n.º 10
0
        public async Task RejectProofRequestCredentialInvalidState()
        {
            //Setup a connection and issue the credentials to the holder
            var(issuerConnection, holderConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _issuerWallet, _holderWallet);

            await Scenarios.IssueCredentialAsync(
                _schemaService, _credentialService, _messages, issuerConnection,
                holderConnection, _issuerWallet, _holderWallet, _pool, MasterSecretId, true);

            _messages.Clear();

            //Requestor initialize a connection with the holder
            var(_, requestorConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _holderWallet, _requestorWallet);

            // Verifier sends a proof request to prover
            {
                var proofRequestObject = new ProofRequest
                {
                    Name                = "ProofReq",
                    Version             = "1.0",
                    Nonce               = "123",
                    RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                    {
                        { "first-name-requirement", new ProofAttributeInfo {
                              Name = "first_name"
                          } }
                    }
                };

                //Requestor sends a proof request
                await _proofService.SendProofRequestAsync(_requestorWallet, requestorConnection.Id, proofRequestObject);
            }

            //Holder retrives proof request message from their cloud agent
            var proofRequest = FindContentMessage <ProofRequestMessage>();

            Assert.NotNull(proofRequest);

            _holderWallet.Connection = holderConnection;
            //Holder stores the proof request
            var holderProofRequestId = await _proofService.ProcessProofRequestAsync(_holderWallet, proofRequest);

            //Holder accepts the proof request and sends a proof
            await _proofService.RejectProofRequestAsync(_holderWallet, holderProofRequestId);

            var ex = await Assert.ThrowsAsync <AgentFrameworkException>(async() => await _proofService.RejectProofRequestAsync(_holderWallet, holderProofRequestId));

            Assert.True(ex.ErrorCode == ErrorCode.RecordInInvalidState);
        }
Exemplo n.º 11
0
        public async Task <IList <CredentialRecord> > Select(ProofRequest proofRequest, string attributeName)
        {
            IAgentContext context = await _agentContextProvider.GetContextAsync();

            List <CredentialRecord> credentialRecords = await _credentialService.ListAsync(context);

            credentialRecords = credentialRecords.Where(cr => cr.State == CredentialState.Issued).ToList();

            List <AttributeFilter> restrictions = GetRestrictions(proofRequest, attributeName);

            ProofCredentialFilter proofCredentialFilter = new ProofCredentialFilter(restrictions, attributeName);

            return(proofCredentialFilter.Filter(credentialRecords));
        }
Exemplo n.º 12
0
        public static async Task <(ProofRecord holderProofRecord, ProofRecord requestorProofRecord)> RequestorInitiatedProofProtocolAsync(
            IProofService proofService,
            IProducerConsumerCollection <AgentMessage> messages,
            ConnectionRecord holderConnection, ConnectionRecord requestorConnection,
            IAgentContext holderContext,
            IAgentContext requestorContext, ProofRequest proofRequestObject)
        {
            //Requestor sends a proof request
            var(message, requestorProofRecord) = await proofService.CreateRequestAsync(requestorContext, proofRequestObject, requestorConnection.Id);

            messages.TryAdd(message);

            return(await ProofProtocolAsync(proofService, messages, holderConnection, requestorConnection, holderContext, requestorContext, requestorProofRecord));
        }
Exemplo n.º 13
0
        public async Task <IActionResult> SendPresentationRequestAsync(OperationBody body)
        {
            // NOTE: AATH can only start from presentation request, not respond to previous message
            var context = await _agentContextProvider.GetContextAsync();

            var presentationRequest        = body.Data;
            var connectionId               = (string)presentationRequest["connection_id"];
            var presentationRequestMessage = presentationRequest["presentation_proposal"]["request_presentations~attach"]["data"];

            var proofRequest = new ProofRequest
            {
                Name                = (string)presentationRequestMessage["name"] ?? "test proof",
                Version             = (string)presentationRequestMessage["version"] ?? "1.0",
                Nonce               = await AnonCreds.GenerateNonceAsync(),
                RequestedAttributes = presentationRequestMessage["requested_attributes"]?.ToObject <Dictionary <string, ProofAttributeInfo> >() ?? new Dictionary <string, ProofAttributeInfo>
                {
                },
                RequestedPredicates = presentationRequestMessage["requested_predicates"]?.ToObject <Dictionary <string, ProofPredicateInfo> >() ?? new Dictionary <string, ProofPredicateInfo> {
                }
            };

            _logger.LogInformation("SendPresentationRequest {proofRequest}", proofRequest.ToJson());


            var(requestPresentationMessage, proofRecord) = await _proofService.CreateRequestAsync(context, proofRequest, connectionId);

            var connection = await _connectionService.GetAsync(context, connectionId);

            var THPresentationExchange = new TestHarnessPresentationExchange
            {
                RecordId = proofRecord.Id,
                ThreadId = proofRecord.GetTag(TagConstants.LastThreadId),
                State    = TestHarnessPresentationExchangeState.RequestSent
            };

            _proofCache.Set(THPresentationExchange.ThreadId, THPresentationExchange);

            UpdateStateOnMessage(THPresentationExchange, TestHarnessPresentationExchangeState.PresentationReceived, _ => _.MessageType == MessageTypes.PresentProofNames.Presentation && _.ThreadId == THPresentationExchange.ThreadId);

            _logger.LogDebug("Send Presentation Request {requestPresentationMessage}", requestPresentationMessage.ToJson());

            await _messageService.SendAsync(context, requestPresentationMessage, connection);

            return(Ok(THPresentationExchange));
        }
Exemplo n.º 14
0
        public async Task RequestIdentityProof()
        {
            var context = await _agentContextProvider.GetContextAsync();

            //var connection = await _connectionService.GetAsync(context, _connectionRecord.Id);

            if (SelectedDefinition == null || SelectedSchema == null)
            {
                return;
            }

            var identityAttributes = new ProofAttributeInfo
            {
                Names        = new string[] { "fist_name", "last_name" },
                Restrictions = new List <AttributeFilter>
                {
                    new AttributeFilter
                    {
                        SchemaId = SelectedSchema.Id,
                        CredentialDefinitionId = SelectedDefinition.Id
                    }
                }
            };


            var proofRequestObject = new ProofRequest
            {
                Name                = "Identity Proof Request",
                Version             = "3.0",
                Nonce               = new BigInteger(Guid.NewGuid().ToByteArray()).ToString(),
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                {
                    { $"identity_attrs_requirement", identityAttributes }
                },
                RequestedPredicates = null
            };

            var(request, _) = await _proofService.CreateRequestAsync(context, proofRequestObject, _connectionRecord.Id);

            await _messageService.SendAsync(context, request, _connectionRecord);
        }
Exemplo n.º 15
0
        public async Task SendProofRequestThrowsA2AMessageTransmissionFailure()
        {
            //Setup a connection and issue the credentials to the holder
            var(issuerConnection, holderConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _issuerWallet, _holderWallet);

            await Scenarios.IssueCredentialAsync(
                _schemaService, _credentialService, _messages, issuerConnection,
                holderConnection, _issuerWallet, _holderWallet, _pool, MasterSecretId, true);

            _messages.Clear();

            //Requestor initialize a connection with the holder
            var(_, requestorConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _holderWallet, _requestorWallet);

            // Verifier sends a proof request to prover
            {
                var proofRequestObject = new ProofRequest
                {
                    Name                = "ProofReq",
                    Version             = "1.0",
                    Nonce               = "123",
                    RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                    {
                        { "first-name-requirement", new ProofAttributeInfo {
                              Name = "first_name"
                          } }
                    }
                };

                //Requestor sends a proof request
                _routeMessage = false;
                var ex = await Assert.ThrowsAsync <AgentFrameworkException>(async() => await _proofService.SendProofRequestAsync(_requestorWallet, requestorConnection.Id, proofRequestObject));

                _routeMessage = true;

                Assert.True(ex.ErrorCode == ErrorCode.A2AMessageTransmissionError);
            }
        }
Exemplo n.º 16
0
        private List <AttributeFilter> GetRestrictions(ProofRequest proofRequest, string attributeName)
        {
            List <AttributeFilter> restrictions = new List <AttributeFilter>();

            foreach (ProofAttributeInfo proofAttributeInfo in proofRequest.RequestedAttributes.Values)
            {
                if (proofAttributeInfo.Name == attributeName || (proofAttributeInfo.Names != null && proofAttributeInfo.Names.Contains(attributeName)))
                {
                    restrictions = restrictions.Concat(proofAttributeInfo.Restrictions).ToList();
                }
            }

            foreach (ProofAttributeInfo proofAttributeInfo in proofRequest.RequestedPredicates.Values)
            {
                if (proofAttributeInfo.Name == attributeName || proofAttributeInfo.Names.Contains(attributeName))
                {
                    restrictions = restrictions.Concat(proofAttributeInfo.Restrictions).ToList();
                }
            }

            return(restrictions);
        }
Exemplo n.º 17
0
        public async Task <RequestPresentationMessage> CreateOver21ProofMessage(ConnectionRecord connectionRecord)
        {
            var agentContext = await _agentProvider.GetContextAsync();

            var name         = connectionRecord.Alias?.Name ?? connectionRecord.Id;
            var proofRequest = new ProofRequest
            {
                Name                = "Over21Request",
                Version             = "1.0",
                Nonce               = await AnonCreds.GenerateNonceAsync(),
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                {
                    { "birthdate", new ProofAttributeInfo {
                          Name = "birthdate"
                      } }
                },
            };

            (var msg, _) = await _proofService.CreateRequestAsync(agentContext, proofRequest);

            return(msg);
        }
Exemplo n.º 18
0
        /// <inheritdoc />
        public virtual async Task <(TransactionRecord transaction, ConnectionRecord connection, ConnectionInvitationMessage message)> CreateOrUpadteTransactionAsync(
            IAgentContext agentContext,
            string transactionId = null,
            string connectionId  = null,
            OfferConfiguration offerConfiguration = null,
            ProofRequest proofRequest             = null,
            InviteConfiguration connectionConfig  = null,
            string CredentialComment = "",
            string ProofComment      = "")
        {
            Logger.LogInformation(CustomLoggingEvents.CreateTransaction, "For {1}", transactionId);

            (ConnectionInvitationMessage message, ConnectionRecord record)connection;
            TransactionRecord transactionRecord;

            if (string.IsNullOrEmpty(connectionId))
            {
                connectionConfig = connectionConfig ?? new InviteConfiguration()
                {
                    AutoAcceptConnection = true,
                    MultiPartyInvitation = true
                };

                connection = (await ConnectionService.CreateInvitationAsync(agentContext, connectionConfig));
                connection.record.SetTag("InvitationMessage", JObject.FromObject(connection.message).ToString());
                await RecordService.UpdateAsync(agentContext.Wallet, connection.record);
            }
            else
            {
                if ((await ConnectionService.GetAsync(agentContext, connectionId)) != null)
                {
                    connection.record = await RecordService.GetAsync <ConnectionRecord>(agentContext.Wallet, connectionId);

                    var message = connection.record.GetTag("InvitationMessage");
                    connection.message = JObject.Parse(message).ToObject <ConnectionInvitationMessage>();
                }
                else
                {
                    throw new AriesFrameworkException(ErrorCode.RecordNotFound,
                                                      $"Connection '{connectionId}' not found.");
                }
            }

            transactionId = !string.IsNullOrEmpty(transactionId)
            ? transactionId
            : Guid.NewGuid().ToString();

            if ((await RecordService.GetAsync <TransactionRecord>(agentContext.Wallet, transactionId)) == null)
            {
                transactionRecord = new TransactionRecord
                {
                    Id                 = transactionId,
                    ConnectionId       = connection.record.Id,
                    OfferConfiguration = offerConfiguration,
                    ProofRequest       = proofRequest,
                    Used               = false,
                    CredentialComment  = CredentialComment,
                    ProofComment       = ProofComment
                };

                await RecordService.AddAsync(agentContext.Wallet, transactionRecord);
            }
            else
            {
                transactionRecord = await RecordService.GetAsync <TransactionRecord>(agentContext.Wallet, transactionId);

                transactionRecord.ConnectionId       = connection.record.Id;
                transactionRecord.OfferConfiguration = offerConfiguration;
                transactionRecord.ProofRequest       = proofRequest;

                await RecordService.UpdateAsync(agentContext.Wallet, transactionRecord);
            }

            return(transactionRecord, connection.record, connection.message);
        }
Exemplo n.º 19
0
        public async Task AcceptProofRequestCredentialInvalidState()
        {
            //Setup a connection and issue the credentials to the holder
            var(issuerConnection, holderConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _issuerWallet, _holderWallet);

            await Scenarios.IssueCredentialAsync(
                _schemaService, _credentialService, _messages, issuerConnection,
                holderConnection, _issuerWallet, _holderWallet, await _holderWallet.Pool, TestConstants.DefaultMasterSecret, true, new List <CredentialPreviewAttribute>
            {
                new CredentialPreviewAttribute("first_name", "Test"),
                new CredentialPreviewAttribute("last_name", "Holder")
            });

            _messages.Clear();

            //Requestor initialize a connection with the holder
            var(_, requestorConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _holderWallet, _requestorWallet);

            // Verifier sends a proof request to prover
            {
                var proofRequestObject = new ProofRequest
                {
                    Name                = "ProofReq",
                    Version             = "1.0",
                    Nonce               = await AnonCreds.GenerateNonceAsync(),
                    RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                    {
                        { "first-name-requirement", new ProofAttributeInfo {
                              Name = "first_name"
                          } }
                    }
                };

                //Requestor sends a proof request
                var(message, _) = await _proofService.CreateProofRequestAsync(_requestorWallet, proofRequestObject, requestorConnection.Id);

                _messages.Add(message);
            }

            // Holder accepts the proof requests and builds a proof
            //Holder retrives proof request message from their cloud agent
            var proofRequest = FindContentMessage <ProofRequestMessage>();

            Assert.NotNull(proofRequest);

            //Holder stores the proof request
            var holderProofRequestId = await _proofService.ProcessProofRequestAsync(_holderWallet, proofRequest, holderConnection);

            var holderProofRecord = await _proofService.GetAsync(_holderWallet, holderProofRequestId);

            var holderProofObject =
                JsonConvert.DeserializeObject <ProofRequest>(holderProofRecord.RequestJson);

            var requestedCredentials = new RequestedCredentials();

            foreach (var requestedAttribute in holderProofObject.RequestedAttributes)
            {
                var credentials =
                    await _proofService.ListCredentialsForProofRequestAsync(_holderWallet, holderProofObject,
                                                                            requestedAttribute.Key);

                requestedCredentials.RequestedAttributes.Add(requestedAttribute.Key,
                                                             new RequestedAttribute
                {
                    CredentialId = credentials.First().CredentialInfo.Referent,
                    Revealed     = true
                });
            }

            foreach (var requestedAttribute in holderProofObject.RequestedPredicates)
            {
                var credentials =
                    await _proofService.ListCredentialsForProofRequestAsync(_holderWallet, holderProofObject,
                                                                            requestedAttribute.Key);

                requestedCredentials.RequestedPredicates.Add(requestedAttribute.Key,
                                                             new RequestedAttribute
                {
                    CredentialId = credentials.First().CredentialInfo.Referent,
                    Revealed     = true
                });
            }

            //Holder accepts the proof request and sends a proof
            await _proofService.CreateProofAsync(_holderWallet, holderProofRequestId, requestedCredentials);

            var ex = await Assert.ThrowsAsync <AgentFrameworkException>(async() => await _proofService.CreateProofAsync(_holderWallet, holderProofRequestId,
                                                                                                                        requestedCredentials));

            Assert.True(ex.ErrorCode == ErrorCode.RecordInInvalidState);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Proof Generates the download URL for Proof (Seed / Merkle Tree). This interface must be used to obtain the proof or certificate of your tamper-proof timestamp. The parameters are as follows: Cryptocurrency (e.g., Bitcoin, Ethereum,..), type of evidence (e.g., certificate, merkle tree) and the associated hash. The entries are analyzed, e.g., whether a valid timestamp exists for the hash. Then the URL and the filename are returned, with which your proof can be saved. Please note that the download link is only valid for 5 minutes. When using cURL to fetch the proof with the download link make sure to specify \&quot;application/octet-stream\&quot; in the \&quot;Accept\&quot; header.
        /// </summary>
        /// <exception cref="OriginStamp.Client.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authorization">A valid API key is essential for authorization to handle the request.</param>
        /// <param name="proofRequestUrl">Information needed to return the proof.</param>
        /// <returns>Task of DefaultOfDownloadLinkResponse</returns>
        public async System.Threading.Tasks.Task <DefaultOfDownloadLinkResponse> GetProofAsync(string authorization, ProofRequest proofRequestUrl)
        {
            ApiResponse <DefaultOfDownloadLinkResponse> localVarResponse = await GetProofAsyncWithHttpInfo(authorization, proofRequestUrl);

            return(localVarResponse.Data);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Proof Generates the download URL for Proof (Seed / Merkle Tree). This interface must be used to obtain the proof or certificate of your tamper-proof timestamp. The parameters are as follows: Cryptocurrency (e.g., Bitcoin, Ethereum,..), type of evidence (e.g., certificate, merkle tree) and the associated hash. The entries are analyzed, e.g., whether a valid timestamp exists for the hash. Then the URL and the filename are returned, with which your proof can be saved. Please note that the download link is only valid for 5 minutes. When using cURL to fetch the proof with the download link make sure to specify \&quot;application/octet-stream\&quot; in the \&quot;Accept\&quot; header.
        /// </summary>
        /// <exception cref="OriginStamp.Client.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authorization">A valid API key is essential for authorization to handle the request.</param>
        /// <param name="proofRequestUrl">Information needed to return the proof.</param>
        /// <returns>Task of ApiResponse (DefaultOfDownloadLinkResponse)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <DefaultOfDownloadLinkResponse> > GetProofAsyncWithHttpInfo(string authorization, ProofRequest proofRequestUrl)
        {
            // verify the required parameter 'authorization' is set
            if (authorization == null)
            {
                throw new ApiException(400, "Missing required parameter 'authorization' when calling ProofApi->GetProof");
            }
            // verify the required parameter 'proofRequestUrl' is set
            if (proofRequestUrl == null)
            {
                throw new ApiException(400, "Missing required parameter 'proofRequestUrl' when calling ProofApi->GetProof");
            }

            var    localVarPath         = "/v3/timestamp/proof/url";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (authorization != null)
            {
                localVarHeaderParams.Add("Authorization", this.Configuration.ApiClient.ParameterToString(authorization));                        // header parameter
            }
            if (proofRequestUrl != null && proofRequestUrl.GetType() != typeof(byte[]))
            {
                localVarPostBody = this.Configuration.ApiClient.Serialize(proofRequestUrl); // http body (model) parameter
            }
            else
            {
                localVarPostBody = proofRequestUrl; // byte array
            }

            // authentication (API Key Authorization) required
            if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization")))
            {
                localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization");
            }

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                            Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                            localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("GetProof", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <DefaultOfDownloadLinkResponse>(localVarStatusCode,
                                                                   localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                                   (DefaultOfDownloadLinkResponse)this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(DefaultOfDownloadLinkResponse))));
        }
Exemplo n.º 22
0
        public async Task CreateProofRequestFromProposal()
        {
            var events = 0;

            _eventAggregator.GetEventByType <ServiceMessageProcessingEvent>()
            .Where(_ => (_.MessageType == MessageTypes.PresentProofNames.ProposePresentation ||
                         _.MessageType == MessageTypes.PresentProofNames.RequestPresentation ||
                         _.MessageType == MessageTypes.IssueCredentialNames.RequestCredential ||
                         _.MessageType == MessageTypes.IssueCredentialNames.IssueCredential))
            .Subscribe(_ =>
            {
                events++;
            });

            // Setup secure connection between issuer and holder
            var(issuerConnection, holderConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _issuerWallet, _holderWallet);

            var(issuerCredential, holderCredential) = await Scenarios.IssueCredentialAsync(
                _schemaService, _credentialService, _messages, issuerConnection,
                holderConnection, _issuerWallet, _holderWallet, await _holderWallet.Pool, TestConstants.DefaultMasterSecret, false, new List <CredentialPreviewAttribute>
            {
                new CredentialPreviewAttribute("first_name", "Test"),
                new CredentialPreviewAttribute("last_name", "Test"),
                new CredentialPreviewAttribute("salary", "100000"),
                new CredentialPreviewAttribute("age", "25"),
                new CredentialPreviewAttribute("wellbeing", "100")
            });



            Assert.Equal(issuerCredential.State, holderCredential.State);
            Assert.Equal(CredentialState.Issued, issuerCredential.State);
            var(message, record) = await _proofService.CreateProposalAsync(_holderWallet, new ProofProposal
            {
                Comment            = "Hello, World",
                ProposedAttributes = new List <ProposedAttribute>
                {
                    new ProposedAttribute
                    {
                        Name = "first_name",
                        CredentialDefinitionId = holderCredential.CredentialDefinitionId,
                        Referent = "Proof of Name",
                        Value    = "Joe"
                    },
                    new ProposedAttribute
                    {
                        Name = "last_name",
                        CredentialDefinitionId = holderCredential.CredentialDefinitionId,
                        Referent = "Proof of Name",
                        Value    = "Shmoe"
                    },
                    new ProposedAttribute
                    {
                        Name = "age",
                        CredentialDefinitionId = holderCredential.CredentialDefinitionId,
                        Referent = "Proof of Age",
                        Value    = "Shmoe"
                    }
                },
                ProposedPredicates = new List <ProposedPredicate>
                {
                    new ProposedPredicate
                    {
                        Name = "salary",
                        CredentialDefinitionId = holderCredential.CredentialDefinitionId,
                        Predicate = ">",
                        Threshold = 99999,
                        Referent  = "Proof of Salary > $99,999"
                    },
                    new ProposedPredicate
                    {
                        Name = "wellbeing",
                        CredentialDefinitionId = holderCredential.CredentialDefinitionId,
                        Referent  = "Proof of Wellbeing",
                        Predicate = "<",
                        Threshold = 99999
                    }
                }
            }, holderConnection.Id);

            Assert.NotNull(message);

            // Process Proposal
            record = await _proofService.ProcessProposalAsync(_issuerWallet, message, issuerConnection);

            //
            RequestPresentationMessage requestMessage;

            (requestMessage, record) = await _proofService.CreateRequestFromProposalAsync(_issuerWallet, new ProofRequestParameters
            {
                Name       = "Test",
                Version    = "1.0",
                NonRevoked = null
            }, record.Id, issuerConnection.Id);

            Assert.NotNull(requestMessage);
            Assert.NotNull(record);

            var actualProofRequest   = record.RequestJson.ToObject <ProofRequest>();
            var expectedProofRequest = new ProofRequest
            {
                Name                = "Test",
                Version             = "1.0",
                Nonce               = actualProofRequest.Nonce,
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                {
                    {
                        "Proof of Name", new ProofAttributeInfo
                        {
                            Name         = null,
                            Names        = new string[] { "first_name", "last_name" },
                            NonRevoked   = null,
                            Restrictions = new List <AttributeFilter>
                            {
                                new AttributeFilter
                                {
                                    CredentialDefinitionId = holderCredential.CredentialDefinitionId
                                }
                            }
                        }
                    },
                    {
                        "Proof of Age", new ProofAttributeInfo
                        {
                            Name         = "age",
                            Names        = null,
                            NonRevoked   = null,
                            Restrictions = new List <AttributeFilter>
                            {
                                new AttributeFilter
                                {
                                    CredentialDefinitionId = holderCredential.CredentialDefinitionId
                                }
                            }
                        }
                    }
                },
                RequestedPredicates = new Dictionary <string, ProofPredicateInfo>
                {
                    {
                        "Proof of Salary > $99,999", new ProofPredicateInfo
                        {
                            Name           = "salary",
                            Names          = null,
                            NonRevoked     = null,
                            PredicateType  = ">",
                            PredicateValue = 99999,
                            Restrictions   = new List <AttributeFilter>
                            {
                                new AttributeFilter
                                {
                                    CredentialDefinitionId = holderCredential.CredentialDefinitionId
                                }
                            }
                        }
                    },
                    {
                        "Proof of Wellbeing", new ProofPredicateInfo
                        {
                            Name           = "wellbeing",
                            Names          = null,
                            NonRevoked     = null,
                            PredicateType  = "<",
                            PredicateValue = 99999,
                            Restrictions   = new List <AttributeFilter>
                            {
                                new AttributeFilter
                                {
                                    CredentialDefinitionId = holderCredential.CredentialDefinitionId
                                }
                            }
                        }
                    }
                }
            };
            var expectedProofRecord = new ProofRecord
            {
                State       = ProofState.Requested,
                RequestJson = expectedProofRequest.ToJson(),
            };

            actualProofRequest.Should().BeEquivalentTo(expectedProofRequest);
        }
        /// <inheritdoc />
        public virtual async Task SendProofRequestAsync(Wallet wallet, string connectionId, ProofRequest proofRequest)
        {
            Logger.LogInformation(LoggingEvents.SendProofRequest, "ConnectionId {0}", connectionId);

            var connection = await ConnectionService.GetAsync(wallet, connectionId);

            var request = await CreateProofRequestAsync(wallet, connectionId, proofRequest);

            await RouterService.ForwardAsync(new ForwardEnvelopeMessage
            {
                Content = request.ToJson(),
                Type    = MessageUtils.FormatDidMessageType(connection.TheirDid, MessageTypes.Forward)
            }, connection.Endpoint);
        }
        /// <inheritdoc />
        public virtual async Task <List <Credential> > ListCredentialsForProofRequestAsync(Wallet wallet,
                                                                                           ProofRequest proofRequest, string attributeReferent)
        {
            using (var search =
                       await AnonCreds.ProverSearchCredentialsForProofRequestAsync(wallet, proofRequest.ToJson()))
            {
                var searchResult = await search.NextAsync(attributeReferent, 100);

                return(JsonConvert.DeserializeObject <List <Credential> >(searchResult));
            }
        }
Exemplo n.º 25
0
        public static async Task ProofProtocolConnectionlessAsync(MockAgent requestor, MockAgent holder, ProofRequest proofRequest, bool useDidKeyFormat)
        {
            var proofService = requestor.GetService <IProofService>();

            var(requestMsg, requestorRecord) = await proofService.CreateRequestAsync(requestor.Context, proofRequest, useDidKeyFormat : useDidKeyFormat);

            var requestAttachment = requestMsg.Requests.FirstOrDefault(x => x.Id == "libindy-request-presentation-0")
                                    ?? throw new ArgumentException("Presentation request attachment not found.");

            var requestJson = requestAttachment.Data.Base64.GetBytesFromBase64().GetUTF8String();
            var request     = JsonConvert.DeserializeObject <ProofRequest>(requestJson);

            var requestedCredentials =
                await ProofServiceUtils.GetAutoRequestedCredentialsForProofCredentials(holder.Context, proofService,
                                                                                       request);

            var holderRecord = await proofService.CreatePresentationAsync(holder.Context, requestMsg, requestedCredentials);

            var requestorProofRecord = await proofService.GetAsync(requestor.Context, requestorRecord.Id);

            var holderProofRecord = await proofService.GetAsync(holder.Context, holderRecord.Id);

            Assert.True(requestorProofRecord.State == ProofState.Accepted);
            Assert.True(holderProofRecord.State == ProofState.Accepted);

            var isProofValid = await proofService.VerifyProofAsync(requestor.Context, requestorProofRecord.Id);

            Assert.True(isProofValid);
        }
Exemplo n.º 26
0
        public static async Task ProofProtocolAsync(MockAgent requester, MockAgent holder,
                                                    ConnectionRecord requesterConnection, ConnectionRecord holderConnection, ProofRequest proofRequest)
        {
            var proofService   = requester.GetService <IProofService>();
            var messageService = requester.GetService <IMessageService>();

            // Hook into message event
            var requestSlim = new SemaphoreSlim(0, 1);

            holder.GetService <IEventAggregator>().GetEventByType <ServiceMessageProcessingEvent>()
            .Where(x => x.MessageType == MessageTypes.PresentProofNames.RequestPresentation)
            .Subscribe(x => requestSlim.Release());

            var(requestMsg, requesterRecord) = await proofService.CreateRequestAsync(requester.Context, proofRequest, requesterConnection.Id);

            await messageService.SendAsync(requester.Context, requestMsg, requesterConnection);

            await requestSlim.WaitAsync(TimeSpan.FromSeconds(30));

            var holderRequests = await proofService.ListRequestedAsync(holder.Context);

            Assert.NotNull(holderRequests);
            Assert.True(holderRequests.Count > 0);

            // Hook into message event
            var proofSlim = new SemaphoreSlim(0, 1);

            requester.GetService <IEventAggregator>().GetEventByType <ServiceMessageProcessingEvent>()
            .Where(x => x.MessageType == MessageTypes.PresentProofNames.Presentation)
            .Subscribe(x => proofSlim.Release());

            var record  = holderRequests.FirstOrDefault();
            var request = JsonConvert.DeserializeObject <ProofRequest>(record.RequestJson);

            var requestedCredentials =
                await ProofServiceUtils.GetAutoRequestedCredentialsForProofCredentials(holder.Context, proofService,
                                                                                       request);

            var(proofMsg, holderRecord) = await proofService.CreatePresentationAsync(holder.Context, record.Id, requestedCredentials);

            await messageService.SendAsync(holder.Context, proofMsg, holderConnection);

            await proofSlim.WaitAsync(TimeSpan.FromSeconds(30));

            var requesterProofRecord = await proofService.GetAsync(requester.Context, requesterRecord.Id);

            var holderProofRecord = await proofService.GetAsync(holder.Context, holderRecord.Id);

            Assert.True(requesterProofRecord.State == ProofState.Accepted);
            Assert.True(holderProofRecord.State == ProofState.Accepted);

            var isProofValid = await proofService.VerifyProofAsync(requester.Context, requesterProofRecord.Id);

            Assert.True(isProofValid);

            var ackSlim = new SemaphoreSlim(0, 1);

            holder.GetService <IEventAggregator>().GetEventByType <ServiceMessageProcessingEvent>()
            .Where(x => x.MessageType == MessageTypes.PresentProofNames.AcknowledgePresentation)
            .Subscribe(x => ackSlim.Release());

            var acknowledgeMessage = await proofService.CreateAcknowledgeMessageAsync(requester.Context, requesterProofRecord.Id);

            await messageService.SendAsync(requester.Context, acknowledgeMessage, requesterConnection);

            await ackSlim.WaitAsync(TimeSpan.FromSeconds(30));
        }
Exemplo n.º 27
0
        /// <inheritdoc />
        public virtual async Task SendProofRequestAsync(IAgentContext agentContext, string connectionId, ProofRequest proofRequest)
        {
            Logger.LogInformation(LoggingEvents.SendProofRequest, "ConnectionId {0}", connectionId);

            var connection = await ConnectionService.GetAsync(agentContext, connectionId);

            if (connection.State != ConnectionState.Connected)
            {
                throw new AgentFrameworkException(ErrorCode.RecordInInvalidState,
                                                  $"Connection state was invalid. Expected '{ConnectionState.Connected}', found '{connection.State}'");
            }

            var(msg, id) = await CreateProofRequestAsync(agentContext, connectionId, proofRequest);

            try
            {
                await MessageService.SendAsync(agentContext.Wallet, msg, connection);
            }
            catch (Exception e)
            {
                await RecordService.DeleteAsync <ProofRecord>(agentContext.Wallet, id);

                throw new AgentFrameworkException(ErrorCode.A2AMessageTransmissionError, "Failed to send proof request message", e);
            }
        }
        public static async Task <RequestedCredentials> GetAutoRequestedCredentialsForProofCredentials(IAgentContext holderContext,
                                                                                                       IProofService proofService, ProofRequest proofRequest)
        {
            var requestedCredentials = new RequestedCredentials();

            foreach (var requestedAttribute in proofRequest.RequestedAttributes)
            {
                var credentials =
                    await proofService.ListCredentialsForProofRequestAsync(holderContext, proofRequest,
                                                                           requestedAttribute.Key);

                requestedCredentials.RequestedAttributes.Add(requestedAttribute.Key,
                                                             new RequestedAttribute
                {
                    CredentialId = credentials.First().CredentialInfo.Referent,
                    Revealed     = true
                });
            }

            foreach (var requestedAttribute in proofRequest.RequestedPredicates)
            {
                var credentials =
                    await proofService.ListCredentialsForProofRequestAsync(holderContext, proofRequest,
                                                                           requestedAttribute.Key);

                requestedCredentials.RequestedPredicates.Add(requestedAttribute.Key,
                                                             new RequestedAttribute
                {
                    CredentialId = credentials.First().CredentialInfo.Referent,
                    Revealed     = true
                });
            }

            return(requestedCredentials);
        }
Exemplo n.º 29
0
        public async Task ProcessProofInvalidState()
        {
            //Setup a connection and issue the credentials to the holder
            var(issuerConnection, holderConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _issuerWallet, _holderWallet);

            await Scenarios.IssueCredentialAsync(
                _schemaService, _credentialService, _messages, issuerConnection,
                holderConnection, _issuerWallet, _holderWallet, _pool, MasterSecretId, true);

            _messages.Clear();

            //Requestor initialize a connection with the holder
            var(_, requestorConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _holderWallet, _requestorWallet);

            // Verifier sends a proof request to prover
            {
                var proofRequestObject = new ProofRequest
                {
                    Name                = "ProofReq",
                    Version             = "1.0",
                    Nonce               = "123",
                    RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                    {
                        { "first-name-requirement", new ProofAttributeInfo {
                              Name = "first_name"
                          } }
                    }
                };

                //Requestor sends a proof request
                await _proofService.SendProofRequestAsync(_requestorWallet, requestorConnection.Id, proofRequestObject);
            }

            // Holder accepts the proof requests and builds a proof
            {
                //Holder retrives proof request message from their cloud agent
                var proofRequest = FindContentMessage <ProofRequestMessage>();
                Assert.NotNull(proofRequest);

                _holderWallet.Connection = holderConnection;
                //Holder stores the proof request
                var holderProofRequestId = await _proofService.ProcessProofRequestAsync(_holderWallet, proofRequest);

                var holderProofRecord = await _proofService.GetAsync(_holderWallet, holderProofRequestId);

                var holderProofObject =
                    JsonConvert.DeserializeObject <ProofRequest>(holderProofRecord.RequestJson);

                var requestedCredentials = new RequestedCredentials();
                foreach (var requestedAttribute in holderProofObject.RequestedAttributes)
                {
                    var credentials =
                        await _proofService.ListCredentialsForProofRequestAsync(_holderWallet, holderProofObject,
                                                                                requestedAttribute.Key);

                    requestedCredentials.RequestedAttributes.Add(requestedAttribute.Key,
                                                                 new RequestedAttribute
                    {
                        CredentialId = credentials.First().CredentialInfo.Referent,
                        Revealed     = true,
                        Timestamp    = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
                    });
                }

                foreach (var requestedAttribute in holderProofObject.RequestedPredicates)
                {
                    var credentials =
                        await _proofService.ListCredentialsForProofRequestAsync(_holderWallet, holderProofObject,
                                                                                requestedAttribute.Key);

                    requestedCredentials.RequestedPredicates.Add(requestedAttribute.Key,
                                                                 new RequestedAttribute
                    {
                        CredentialId = credentials.First().CredentialInfo.Referent,
                        Revealed     = true
                    });
                }

                //Holder accepts the proof request and sends a proof
                var proofMessage = await _proofService.AcceptProofRequestAsync(_holderWallet, holderProofRequestId,
                                                                               requestedCredentials);

                _messages.Add(proofMessage);
            }

            //Requestor retrives proof message from their cloud agent
            var proof = FindContentMessage <ProofMessage>();

            Assert.NotNull(proof);

            _requestorWallet.Connection = requestorConnection;
            //Requestor stores proof
            await _proofService.ProcessProofAsync(_requestorWallet, proof);

            var ex = await Assert.ThrowsAsync <AgentFrameworkException>(async() => await _proofService.ProcessProofAsync(_requestorWallet, proof));

            Assert.True(ex.ErrorCode == ErrorCode.RecordInInvalidState);
        }
Exemplo n.º 30
0
        public async Task CredentialProofDemo()
        {
            int events = 0;

            _eventAggregator.GetEventByType <ServiceMessageProcessingEvent>()
            .Where(_ => (_.MessageType == MessageTypes.ProofRequest ||
                         _.MessageType == MessageTypes.DisclosedProof))
            .Subscribe(_ =>
            {
                events++;
            });

            //Setup a connection and issue the credentials to the holder
            var(issuerConnection, holderConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _issuerWallet, _holderWallet);

            await Scenarios.IssueCredentialAsync(
                _schemaService, _credentialService, _messages, issuerConnection,
                holderConnection, _issuerWallet, _holderWallet, _pool, MasterSecretId, true);

            _messages.Clear();

            //Requestor initialize a connection with the holder
            var(_, requestorConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _holderWallet, _requestorWallet);

            // Verifier sends a proof request to prover
            {
                var proofRequestObject = new ProofRequest
                {
                    Name                = "ProofReq",
                    Version             = "1.0",
                    Nonce               = "123",
                    RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                    {
                        { "first-name-requirement", new ProofAttributeInfo {
                              Name = "first_name"
                          } }
                    }
                };

                //Requestor sends a proof request
                await _proofService.SendProofRequestAsync(_requestorWallet, requestorConnection.Id, proofRequestObject);
            }

            // Holder accepts the proof requests and builds a proof
            {
                //Holder retrives proof request message from their cloud agent
                var proofRequest = FindContentMessage <ProofRequestMessage>();
                Assert.NotNull(proofRequest);

                _holderWallet.Connection = holderConnection;
                //Holder stores the proof request
                var holderProofRequestId = await _proofService.ProcessProofRequestAsync(_holderWallet, proofRequest);

                var holderProofRecord = await _proofService.GetAsync(_holderWallet, holderProofRequestId);

                var holderProofObject =
                    JsonConvert.DeserializeObject <ProofRequest>(holderProofRecord.RequestJson);

                var requestedCredentials = new RequestedCredentials();
                foreach (var requestedAttribute in holderProofObject.RequestedAttributes)
                {
                    var credentials =
                        await _proofService.ListCredentialsForProofRequestAsync(_holderWallet, holderProofObject,
                                                                                requestedAttribute.Key);

                    requestedCredentials.RequestedAttributes.Add(requestedAttribute.Key,
                                                                 new RequestedAttribute
                    {
                        CredentialId = credentials.First().CredentialInfo.Referent,
                        Revealed     = true,
                        Timestamp    = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
                    });
                }

                foreach (var requestedAttribute in holderProofObject.RequestedPredicates)
                {
                    var credentials =
                        await _proofService.ListCredentialsForProofRequestAsync(_holderWallet, holderProofObject,
                                                                                requestedAttribute.Key);

                    requestedCredentials.RequestedPredicates.Add(requestedAttribute.Key,
                                                                 new RequestedAttribute
                    {
                        CredentialId = credentials.First().CredentialInfo.Referent,
                        Revealed     = true
                    });
                }

                //Holder accepts the proof request and sends a proof
                var proofMessage = await _proofService.AcceptProofRequestAsync(_holderWallet, holderProofRequestId, requestedCredentials);

                _messages.Add(proofMessage);
            }

            //Requestor retrives proof message from their cloud agent
            var proof = FindContentMessage <ProofMessage>();

            Assert.NotNull(proof);

            _requestorWallet.Connection = requestorConnection;
            //Requestor stores proof
            var requestorProofId = await _proofService.ProcessProofAsync(_requestorWallet, proof);

            //Requestor verifies proof
            var requestorVerifyResult = await _proofService.VerifyProofAsync(_requestorWallet, requestorProofId);

            ////Verify the proof is valid
            Assert.True(requestorVerifyResult);

            Assert.True(events == 2);

            ////Get the proof from both parties wallets
            //var requestorProof = await _proofService.GetProof(_requestorWallet, requestorProofId);
            //var holderProof = await _proofService.GetProof(_holderWallet, holderProofRequestId);

            ////Verify that both parties have a copy of the proof
            //Assert.Equal(requestorProof, holderProof);
        }