Exemplo n.º 1
0
        public async Task CanPerformProofProtocol()
        {
            (var issuerConnection, var holderConnection) = await AgentScenarios.EstablishConnectionAsync(_issuerAgent, _holderAgent);

            await AgentScenarios.IssueCredentialAsync(_issuerAgent, _holderAgent, issuerConnection, holderConnection, new List <CredentialPreviewAttribute>
            {
                new CredentialPreviewAttribute("first_name", "Test"),
                new CredentialPreviewAttribute("last_name", "Holder")
            });

            (var holderRequestorConnection, var requestorConnection) = await AgentScenarios.EstablishConnectionAsync(_holderAgent, _requestorAgent);

            await AgentScenarios.ProofProtocolAsync(_requestorAgent, _holderAgent, requestorConnection,
                                                    holderRequestorConnection, new ProofRequest()
            {
                Name                = "ProofReq",
                Version             = "1.0",
                Nonce               = await AnonCreds.GenerateNonceAsync(),
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                {
                    { "first-name-requirement", new ProofAttributeInfo {
                          Name = "first_name"
                      } }
                }
            });
        }
        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.º 3
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);
        }
Exemplo n.º 4
0
        public async Task CreateProofRequestConnectionNotFound()
        {
            var ex = await Assert.ThrowsAsync <AriesFrameworkException>(async() => await _proofService.CreateRequestAsync(_issuerWallet, new ProofRequest
            {
                Name  = "Test",
                Nonce = await AnonCreds.GenerateNonceAsync()
            }, "bad-connection-id"));

            Assert.True(ex.ErrorCode == ErrorCode.RecordNotFound);
        }
        /// <inheritdoc />
        public async Task <bool> IsRevokedAsync(IAgentContext context, CredentialRecord record)
        {
            if (record.RevocationRegistryId == null)
            {
                return(false);
            }
            if (record.State == CredentialState.Offered || record.State == CredentialState.Requested)
            {
                return(false);
            }
            if (record.State == CredentialState.Revoked || record.State == CredentialState.Rejected)
            {
                return(true);
            }

            var now          = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            var proofRequest = new ProofRequest
            {
                Name                = "revocation check",
                Version             = "1.0",
                Nonce               = await AnonCreds.GenerateNonceAsync(),
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                {
                    { "referent1", new ProofAttributeInfo {
                          Name = record.CredentialAttributesValues.First().Name
                      } }
                }, NonRevoked = new RevocationInterval
                {
                    From = (uint)now,
                    To   = (uint)now
                }
            };

            var proof = await CreateProofAsync(context, proofRequest, new RequestedCredentials
            {
                RequestedAttributes = new Dictionary <string, RequestedAttribute>
                {
                    { "referent1", new RequestedAttribute {
                          CredentialId = record.CredentialId, Timestamp = now, Revealed = true
                      } }
                }
            });

            var isValid = await VerifyProofAsync(context, proofRequest.ToJson(), proof);

            if (!isValid)
            {
                await record.TriggerAsync(CredentialTrigger.Revoke);

                record.SetTag("LastRevocationCheck", now.ToString());
                await RecordService.UpdateAsync(context.Wallet, record);
            }

            return(!isValid);
        }
Exemplo n.º 6
0
        public async Task CreateProofRequestConnectionInvalidState()
        {
            var connectionId = Guid.NewGuid().ToString();

            await _connectionService.CreateInvitationAsync(_issuerWallet,
                                                           new InviteConfiguration { ConnectionId = connectionId });

            var ex = await Assert.ThrowsAsync <AriesFrameworkException>(async() => await _proofService.CreateRequestAsync(_issuerWallet, new ProofRequest
            {
                Name  = "Test",
                Nonce = await AnonCreds.GenerateNonceAsync()
            }, connectionId));

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

            _eventAggregator.GetEventByType <ServiceMessageProcessingEvent>()
            .Where(_ => (_.MessageType == MessageTypes.PresentProofNames.RequestPresentation ||
                         _.MessageType == MessageTypes.PresentProofNames.Presentation))
            .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, 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(holderRequestorConnection, requestorConnection) = await Scenarios.EstablishConnectionAsync(
                _connectionService, _messages, _holderWallet, _requestorWallet);

            await Scenarios.ProofProtocolAsync(_proofService, _messages, holderRequestorConnection, requestorConnection,
                                               _holderWallet, _requestorWallet, new ProofRequest()
            {
                Name                = "ProofReq",
                Version             = "1.0",
                Nonce               = await AnonCreds.GenerateNonceAsync(),
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                {
                    { "first-name-requirement", new ProofAttributeInfo {
                          Name = "first_name"
                      } }
                }
            });

            _messages.Clear();

            Assert.True(events == 2);
        }
Exemplo n.º 8
0
        /// <inheritdoc />
        public virtual async Task <(EphemeralChallengeMessage, EphemeralChallengeRecord)> CreateChallengeAsync(IAgentContext agentContext,
                                                                                                               string challengeConfigId)
        {
            var config = await GetChallengeConfigAsync(agentContext, challengeConfigId);

            EphemeralChallengeRecord challengeRecord = new EphemeralChallengeRecord
            {
                Id = Guid.NewGuid().ToString()
            };
            EphemeralChallengeMessage challengeMessage = new EphemeralChallengeMessage();

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

            challengeMessage.ChallengerName     = provisioning.Owner?.Name;
            challengeMessage.ChallengerImageUrl = provisioning.Owner?.ImageUrl;

            challengeMessage.ServiceEndpoint = provisioning.Endpoint.Uri;
            challengeMessage.RecipientKeys   = new[] { provisioning.Endpoint.Verkey };

            if (config.Type == ChallengeType.Proof)
            {
                var proofRequestConfig = config.Contents.ToObject <ProofRequestConfiguration>();
                (var proofRequest, var _) = await ProofService.CreateProofRequestAsync(agentContext, new ProofRequest
                {
                    Name                = config.Name,
                    Version             = "1.0",
                    Nonce               = await AnonCreds.GenerateNonceAsync(),
                    RequestedAttributes = proofRequestConfig.RequestedAttributes,
                    RequestedPredicates = proofRequestConfig.RequestedPredicates,
                    NonRevoked          = proofRequestConfig.NonRevoked
                });

                challengeRecord.Challenge = new EphemeralChallengeContents
                {
                    Type     = ChallengeType.Proof,
                    Contents = JsonConvert.DeserializeObject <JObject>(proofRequest.ProofRequestJson)
                };
                challengeMessage.Challenge = challengeRecord.Challenge;
            }

            challengeRecord.SetTag(TagConstants.Role, TagConstants.Requestor);
            challengeRecord.SetTag(TagConstants.LastThreadId, challengeMessage.Id);
            await RecordService.AddAsync(agentContext.Wallet, challengeRecord);

            return(challengeMessage,
                   challengeRecord);
        }
Exemplo n.º 9
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.º 10
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);
        }
        public async Task TestCredentialIssuanceV1()
        {
            var pair = await InProcAgent.CreatePairedAsync(true);

            var credentialService1 = pair.Agent1.Provider.GetService <ICredentialService>();
            var credentialService2 = pair.Agent2.Provider.GetService <ICredentialService>();
            var proofService1      = pair.Agent1.Provider.GetService <IProofService>();
            var proofService2      = pair.Agent2.Provider.GetService <IProofService>();

            var context1        = pair.Agent1.Context;
            var context2        = pair.Agent2.Context;
            var messageService2 = pair.Agent2.Provider.GetService <IMessageService>();
            var messageService1 = pair.Agent1.Provider.GetRequiredService <IMessageService>();

            // Configure agent1 as issuer
            var issuerConfiguration = await pair.Agent1.Provider.GetRequiredService <IProvisioningService>()
                                      .GetProvisioningAsync(context1.Wallet);

            await PromoteTrustAnchor(issuerConfiguration.IssuerDid, issuerConfiguration.IssuerVerkey);

            var schemaId = await pair.Agent1.Provider.GetRequiredService <ISchemaService>()
                           .CreateSchemaAsync(
                context: context1,
                issuerDid: issuerConfiguration.IssuerDid,
                name: $"test-schema-{Guid.NewGuid()}",
                version: "1.0",
                attributeNames: new[] { "name", "age" });

            var definitionWithRevocationId = await pair.Agent1.Provider.GetRequiredService <ISchemaService>()
                                             .CreateCredentialDefinitionAsync(
                context: context1,
                new CredentialDefinitionConfiguration
            {
                SchemaId                  = schemaId,
                EnableRevocation          = true,
                RevocationRegistryBaseUri = "http://localhost",
                Tag = "revoc"
            });

            var definitionId = await pair.Agent1.Provider.GetRequiredService <ISchemaService>()
                               .CreateCredentialDefinitionAsync(
                context: context1,
                new CredentialDefinitionConfiguration
            {
                SchemaId                  = schemaId,
                EnableRevocation          = false,
                RevocationRegistryBaseUri = "http://localhost",
                Tag = "norevoc"
            });

            // Send offer for two credentials
            var(offer, record) = await credentialService1
                                 .CreateOfferAsync(context1, new OfferConfiguration
            {
                CredentialDefinitionId = definitionWithRevocationId,
                IssuerDid = issuerConfiguration.IssuerDid,
                CredentialAttributeValues = new[]
                {
                    new CredentialPreviewAttribute("name", "random"),
                    new CredentialPreviewAttribute("age", "22")
                }
            });

            await messageService1.SendAsync(context1, offer, pair.Connection1);

            var issuerCredentialWithRevocationId = record.Id;

            (offer, record) = await credentialService1
                              .CreateOfferAsync(context1, new OfferConfiguration
            {
                CredentialDefinitionId = definitionId,
                IssuerDid = issuerConfiguration.IssuerDid,
                CredentialAttributeValues = new[]
                {
                    new CredentialPreviewAttribute("name", "random"),
                    new CredentialPreviewAttribute("age", "22")
                }
            });

            await messageService1
            .SendAsync(context1, offer, pair.Connection1);

            // Find credential for Agent 2 and accept all offers

            var credentials = await credentialService2.ListAsync(context2);

            foreach (var credential in credentials.Where(x => x.State == CredentialState.Offered))
            {
                var(request, _) = await credentialService2.CreateRequestAsync(context2, credential.Id);

                await messageService2.SendAsync(context2, request, pair.Connection2);
            }

            // Issue credential
            credentials = await credentialService1.ListRequestsAsync(context1);

            foreach (var credential in credentials)
            {
                var(issue, _) = await credentialService1.CreateCredentialAsync(context1, credential.Id);

                await messageService1.SendAsync(context1, issue, pair.Connection1);
            }

            // Assert
            foreach (var credential in await credentialService1.ListAsync(context1))
            {
                Assert.Equal(CredentialState.Issued, credential.State);
            }
            foreach (var credential in await credentialService2.ListAsync(context2))
            {
                Assert.Equal(CredentialState.Issued, credential.State);
            }


            // Verification - without revocation
            var(requestPresentationMessage, proofRecordIssuer) = await proofService1
                                                                 .CreateRequestAsync(context1, new ProofRequest
            {
                Name                = "Test Verification",
                Version             = "1.0",
                Nonce               = await AnonCreds.GenerateNonceAsync(),
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                {
                    { "id-verification", new ProofAttributeInfo {
                          Names = new [] { "name", "age" }
                      } }
                }
            });

            var proofRecordHolder = await proofService2.ProcessRequestAsync(context2, requestPresentationMessage, pair.Connection2);

            var availableCredentials = await proofService2.ListCredentialsForProofRequestAsync(context2, proofRecordHolder.RequestJson.ToObject <ProofRequest>(), "id-verification");

            var(presentationMessage, _) = await proofService2.CreatePresentationAsync(
                context2, proofRecordHolder.Id, new RequestedCredentials
            {
                RequestedAttributes = new Dictionary <string, RequestedAttribute>
                {
                    { "id-verification", new RequestedAttribute
                      {
                          CredentialId = availableCredentials.First().CredentialInfo.Referent,
                          Revealed     = true
                      } }
                }
            });

            proofRecordIssuer = await proofService1.ProcessPresentationAsync(context1, presentationMessage);

            var valid = await proofService1.VerifyProofAsync(context1, proofRecordIssuer.Id);

            Assert.True(valid);

            // Verification - with revocation
            var now = (uint)DateTimeOffset.Now.ToUnixTimeSeconds();

            (requestPresentationMessage, proofRecordIssuer) = await proofService1
                                                              .CreateRequestAsync(context1, new ProofRequest
            {
                Name                = "Test Verification",
                Version             = "1.0",
                Nonce               = await AnonCreds.GenerateNonceAsync(),
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                {
                    { "id-verification", new ProofAttributeInfo {
                          Names = new [] { "name", "age" }
                      } }
                },
                NonRevoked = new RevocationInterval
                {
                    From = 0,
                    To   = now
                }
            });

            proofRecordHolder = await proofService2
                                .ProcessRequestAsync(context2, requestPresentationMessage, pair.Connection2);

            availableCredentials = await proofService2
                                   .ListCredentialsForProofRequestAsync(context2, proofRecordHolder.RequestJson.ToObject <ProofRequest>(), "id-verification");

            (presentationMessage, _) = await proofService2
                                       .CreatePresentationAsync(context2, proofRecordHolder.Id, new RequestedCredentials
            {
                RequestedAttributes = new Dictionary <string, RequestedAttribute>
                {
                    { "id-verification", new RequestedAttribute
                      {
                          CredentialId = availableCredentials.First().CredentialInfo.Referent,
                          Revealed     = true
                      } }
                }
            });

            proofRecordIssuer = await proofService1
                                .ProcessPresentationAsync(context1, presentationMessage);

            valid = await proofService1
                    .VerifyProofAsync(context1, proofRecordIssuer.Id);

            Assert.True(valid);

            Assert.False(await proofService2.IsRevokedAsync(context2, availableCredentials.First().CredentialInfo.Referent));

            // Revoke the credential
            await pair.Agent1.Provider.GetService <ICredentialService>()
            .RevokeCredentialAsync(context1, issuerCredentialWithRevocationId);

            await Task.Delay(TimeSpan.FromSeconds(5));

            now = (uint)DateTimeOffset.Now.ToUnixTimeSeconds();

            (requestPresentationMessage, proofRecordIssuer) = await proofService1
                                                              .CreateRequestAsync(context1, new ProofRequest
            {
                Name                = "Test Verification",
                Version             = "1.0",
                Nonce               = await AnonCreds.GenerateNonceAsync(),
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                {
                    { "id-verification", new ProofAttributeInfo {
                          Names = new [] { "name", "age" }
                      } }
                },
                NonRevoked = new RevocationInterval
                {
                    From = 0,
                    To   = now
                }
            });

            proofRecordHolder = await proofService2
                                .ProcessRequestAsync(context2, requestPresentationMessage, pair.Connection2);

            availableCredentials = await proofService2
                                   .ListCredentialsForProofRequestAsync(context2, proofRecordHolder.RequestJson.ToObject <ProofRequest>(), "id-verification");

            (presentationMessage, _) = await proofService2
                                       .CreatePresentationAsync(context2, proofRecordHolder.Id, new RequestedCredentials
            {
                RequestedAttributes = new Dictionary <string, RequestedAttribute>
                {
                    { "id-verification", new RequestedAttribute
                      {
                          CredentialId = availableCredentials.First().CredentialInfo.Referent,
                          Revealed     = true
                      } }
                }
            });

            proofRecordIssuer = await proofService1
                                .ProcessPresentationAsync(context1, presentationMessage);

            valid = await proofService1
                    .VerifyProofAsync(context1, proofRecordIssuer.Id);

            Assert.False(valid);

            Assert.True(await proofService2.IsRevokedAsync(context2, availableCredentials.First().CredentialInfo.Referent));

            // Issue new credential after revoking previous one
            {
                (offer, record) = await credentialService1
                                  .CreateOfferAsync(context1, new OfferConfiguration
                {
                    CredentialDefinitionId = definitionWithRevocationId,
                    IssuerDid = issuerConfiguration.IssuerDid,
                    CredentialAttributeValues = new[]
                    {
                        new CredentialPreviewAttribute("name", "random"),
                        new CredentialPreviewAttribute("age", "22")
                    }
                });

                await messageService1.SendAsync(context1, offer, pair.Connection1);

                string holderCredentialId = null;

                credentials = await credentialService2.ListAsync(context2);

                foreach (var credential in credentials.Where(x => x.State == CredentialState.Offered))
                {
                    var(request, _) = await credentialService2.CreateRequestAsync(context2, credential.Id);

                    holderCredentialId = credential.Id;

                    await messageService2.SendAsync(context2, request, pair.Connection2);
                }

                // Issue credential

                credentials = await credentialService1.ListRequestsAsync(context1);

                foreach (var credential in credentials)
                {
                    var(issue, _) = await credentialService1.CreateCredentialAsync(context1, credential.Id);

                    await messageService1.SendAsync(context1, issue, pair.Connection1);
                }

                await Task.Delay(TimeSpan.FromSeconds(15));

                // Verify latest issued credential with non-revocation proof

                now = (uint)DateTimeOffset.Now.ToUnixTimeSeconds();

                (requestPresentationMessage, proofRecordIssuer) = await proofService1
                                                                  .CreateRequestAsync(context1, new ProofRequest
                {
                    Name                = "Test Verification",
                    Version             = "1.0",
                    Nonce               = await AnonCreds.GenerateNonceAsync(),
                    RequestedAttributes = new Dictionary <string, ProofAttributeInfo>
                    {
                        { "id-verification", new ProofAttributeInfo {
                              Names = new [] { "name", "age" }
                          } }
                    },
                    NonRevoked = new RevocationInterval
                    {
                        From = 0,
                        To   = now
                    }
                });

                proofRecordHolder = await proofService2.ProcessRequestAsync(context2, requestPresentationMessage, pair.Connection2);

                (presentationMessage, _) = await proofService2.CreatePresentationAsync(
                    context2, proofRecordHolder.Id, new RequestedCredentials
                {
                    RequestedAttributes = new Dictionary <string, RequestedAttribute>
                    {
                        { "id-verification", new RequestedAttribute
                          {
                              CredentialId = holderCredentialId,
                              Revealed     = true
                          } }
                    }
                });

                proofRecordIssuer = await proofService1.ProcessPresentationAsync(context1, presentationMessage);

                valid = await proofService1.VerifyProofAsync(context1, proofRecordIssuer.Id);

                Assert.True(valid);
            }
        }
        /// <inheritdoc />
        public async Task <(RequestPresentationMessage, ProofRecord)> CreateRequestFromProposalAsync(IAgentContext agentContext, ProofRequestParameters requestParams,
                                                                                                     string proofRecordId, string connectionId)
        {
            Logger.LogInformation(LoggingEvents.CreateProofRequest, "ConnectionId {0}", connectionId);

            if (proofRecordId == null)
            {
                throw new ArgumentNullException(nameof(proofRecordId), "You must provide proof record Id");
            }
            if (connectionId != null)
            {
                var connection = await ConnectionService.GetAsync(agentContext, connectionId);

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

            var proofRecord = await RecordService.GetAsync <ProofRecord>(agentContext.Wallet, proofRecordId);

            var proofProposal = proofRecord.ProposalJson.ToObject <ProofProposal>();


            // Build Proof Request from Proposal info
            var proofRequest = new ProofRequest
            {
                Name                = requestParams.Name,
                Version             = requestParams.Version,
                Nonce               = await AnonCreds.GenerateNonceAsync(),
                RequestedAttributes = new Dictionary <string, ProofAttributeInfo>(),
                NonRevoked          = requestParams.NonRevoked
            };

            var attributesByReferent = new Dictionary <string, List <ProposedAttribute> >();

            foreach (var proposedAttribute in proofProposal.ProposedAttributes)
            {
                if (proposedAttribute.Referent == null)
                {
                    proposedAttribute.Referent = Guid.NewGuid().ToString();
                }

                if (attributesByReferent.TryGetValue(proposedAttribute.Referent, out var referentAttributes))
                {
                    referentAttributes.Add(proposedAttribute);
                }
                else
                {
                    attributesByReferent.Add(proposedAttribute.Referent, new List <ProposedAttribute> {
                        proposedAttribute
                    });
                }
            }

            foreach (var referent in attributesByReferent.AsEnumerable())
            {
                var proposedAttributes = referent.Value;
                var attributeName      = proposedAttributes.Count() == 1 ? proposedAttributes.Single().Name : null;
                var attributeNames     = proposedAttributes.Count() > 1 ? proposedAttributes.ConvertAll <string>(r => r.Name).ToArray() : null;


                var requestedAttribute = new ProofAttributeInfo()
                {
                    Name         = attributeName,
                    Names        = attributeNames,
                    Restrictions = new List <AttributeFilter>
                    {
                        new AttributeFilter {
                            CredentialDefinitionId = proposedAttributes.First().CredentialDefinitionId,
                            SchemaId  = proposedAttributes.First().SchemaId,
                            IssuerDid = proposedAttributes.First().IssuerDid
                        }
                    }
                };
                proofRequest.RequestedAttributes.Add(referent.Key, requestedAttribute);
                Console.WriteLine($"Added Attribute to Proof Request \n {proofRequest.ToString()}");
            }

            foreach (var pred in proofProposal.ProposedPredicates)
            {
                if (pred.Referent == null)
                {
                    pred.Referent = Guid.NewGuid().ToString();
                }
                var predicate = new ProofPredicateInfo()
                {
                    Name           = pred.Name,
                    PredicateType  = pred.Predicate,
                    PredicateValue = pred.Threshold,
                    Restrictions   = new List <AttributeFilter>
                    {
                        new AttributeFilter {
                            CredentialDefinitionId = pred.CredentialDefinitionId,
                            SchemaId  = pred.SchemaId,
                            IssuerDid = pred.IssuerDid
                        }
                    }
                };
                proofRequest.RequestedPredicates.Add(pred.Referent, predicate);
            }

            proofRecord.RequestJson = proofRequest.ToJson();
            await proofRecord.TriggerAsync(ProofTrigger.Request);

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

            var message = new RequestPresentationMessage
            {
                Id       = proofRecord.Id,
                Requests = new[]
                {
                    new Attachment
                    {
                        Id       = "libindy-request-presentation-0",
                        MimeType = CredentialMimeTypes.ApplicationJsonMimeType,
                        Data     = new AttachmentContent
                        {
                            Base64 = proofRequest
                                     .ToJson()
                                     .GetUTF8Bytes()
                                     .ToBase64String()
                        }
                    }
                }
            };

            message.ThreadFrom(proofRecord.GetTag(TagConstants.LastThreadId));
            return(message, proofRecord);
        }
Exemplo n.º 13
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);
        }