private async Task AcceptProofRequest() { if (_proofRecord.State != ProofState.Requested) { await DialogService.AlertAsync(string.Format(AppResources.ProofStateShouldBeMessage, ProofStateTranslator.Translate(ProofState.Requested))); return; } RequestedCredentials requestedCredentials = new RequestedCredentials() { RequestedAttributes = new Dictionary <string, RequestedAttribute>(), RequestedPredicates = new Dictionary <string, RequestedAttribute>() }; foreach (ProofAttributeViewModel proofAttribute in Attributes) { if (proofAttribute.IsPredicate) { requestedCredentials.RequestedPredicates.Add(proofAttribute.Id, new RequestedAttribute { CredentialId = proofAttribute.CredentialId, Revealed = proofAttribute.IsRevealed }); } else { requestedCredentials.RequestedAttributes.Add(proofAttribute.Id, new RequestedAttribute { CredentialId = proofAttribute.CredentialId, Revealed = proofAttribute.IsRevealed }); } } // TODO: Mettre le Timestamp à null car lorsqu'il est présent, la création de la preuve ne marche pas. Pourquoi? //foreach (var keyValue in requestedCredentials.RequestedAttributes.Values) //{ // keyValue.Timestamp = null; //} var context = await _agentContextProvider.GetContextAsync(); ProofRecord proofRecord = await _recordService.GetAsync <ProofRecord>(context.Wallet, _proofRecord.Id); var(msg, rec) = await _proofService.CreatePresentationAsync(context, proofRecord.Id, requestedCredentials); if (string.IsNullOrEmpty(proofRecord.ConnectionId)) { await _messageService.SendAsync(context.Wallet, msg, proofRecord.GetTag("RecipientKey"), proofRecord.GetTag("ServiceEndpoint")); } else { ConnectionRecord connectionRecord = await _recordService.GetAsync <ConnectionRecord>(context.Wallet, proofRecord.ConnectionId); await _messageService.SendAsync(context.Wallet, msg, connectionRecord); } _eventAggregator.Publish(new ApplicationEvent { Type = ApplicationEventType.ProofRequestUpdated }); await NavigationService.PopModalAsync(); }
private async Task <string> CreateProofJsonAsync(IAgentContext agentContext, RequestedCredentials requestedCredentials, string requestJson) { 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, requestJson, requestedCredentials.ToJson(), provisioningRecord.MasterSecretId, schemas, definitions, revocationStates); return(proofJson); }
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); }
private async Task <string> BuildRevocationStatesAsync(Pool pool, IEnumerable <CredentialInfo> credentialObjects, RequestedCredentials requestedCredentials) { var allCredentials = new List <RequestedAttribute>(); allCredentials.AddRange(requestedCredentials.RequestedAttributes.Values); allCredentials.AddRange(requestedCredentials.RequestedPredicates.Values); var result = new Dictionary <string, Dictionary <string, JObject> >(); foreach (var requestedCredential in allCredentials) { // ReSharper disable once PossibleMultipleEnumeration var credential = credentialObjects.First(x => x.Referent == requestedCredential.CredentialId); if (credential.RevocationRegistryId == null) { continue; } var timestamp = requestedCredential.Timestamp ?? throw new Exception( "Timestamp must be provided for credential that supports revocation"); if (result.ContainsKey(credential.RevocationRegistryId) && result[credential.RevocationRegistryId].ContainsKey($"{timestamp}")) { continue; } var registryDefinition = await LedgerService.LookupRevocationRegistryDefinitionAsync(pool, null, credential.RevocationRegistryId); var delta = await LedgerService.LookupRevocationRegistryDeltaAsync(pool, credential.RevocationRegistryId, -1, timestamp); var tailsfile = await TailsService.EnsureTailsExistsAsync(pool, credential.RevocationRegistryId); var tailsReader = await TailsService.OpenTailsAsync(tailsfile); var state = await AnonCreds.CreateRevocationStateAsync(tailsReader, registryDefinition.ObjectJson, delta.ObjectJson, (long)delta.Timestamp, credential.CredentialRevocationId); if (!result.ContainsKey(credential.RevocationRegistryId)) { result.Add(credential.RevocationRegistryId, new Dictionary <string, JObject>()); } result[credential.RevocationRegistryId].Add($"{timestamp}", JObject.Parse(state)); // TODO: Revocation state should provide the state between a certain period // that can be requested in the proof request in the 'non_revocation' field. } return(result.ToJson()); }
/// <summary> /// Reference https://github.com/hyperledger/aries-framework-dotnet/blob/master/src/Hyperledger.Aries.TestHarness/AgentScenarios.cs#L214 /// </summary> private async Task CreatePresentation() { base.IsBusy = true; var dialog = UserDialogs.Instance.Loading("Presenting Proof..."); try { var requestedCredentials = new RequestedCredentials(); var requestedAttributes = RequestedAttributes.Where(x => x.SelectedCredential != null && !x.IsPredicate) .Select(y => new KeyValuePair <string, RequestedAttribute>(y.AttributeReferent, new RequestedAttribute { CredentialId = y.SelectedCredential.Credential.CredentialInfo.Referent, Revealed = true }) ).ToDictionary(z => z.Key, z => z.Value); //TODO: Implement Predicate related functionlity if (requestedAttributes != null && requestedAttributes.Count > 0) { requestedCredentials.RequestedAttributes = requestedAttributes; var context = await agentContextProvider.GetContextAsync(); if (requestPresentationMessage != null) { var result = await proofService.CreatePresentationAsync(context, requestPresentationMessage, requestedCredentials); } else { var(proofMsg, holderRecord) = await proofService.CreatePresentationAsync(context, proofRecord.Id, requestedCredentials); await messageService.SendAsync(context, proofMsg, connection); } } eventAggregator.Publish(new ApplicationEvent() { Type = ApplicationEventType.RefreshProofRequests }); await NavigationService.NavigateBackAsync(); } catch (Exception exception) { await Application.Current.MainPage.DisplayAlert("Error", exception.Message, "Ok"); } finally { base.IsBusy = false; dialog?.Hide(); dialog?.Dispose(); } }
/// <inheritdoc /> public virtual async Task <ProofMessage> CreateProofAsync(Wallet wallet, Pool pool, string proofRequestId, RequestedCredentials requestedCredentials) { var record = await RecordService.GetAsync <ProofRecord>(wallet, proofRequestId); var connection = await ConnectionService.GetAsync(wallet, record.ConnectionId); var provisioningRecord = await ProvisioningService.GetProvisioningAsync(wallet); var credentialObjects = new List <CredentialInfo>(); foreach (var credId in requestedCredentials.GetCredentialIdentifiers()) { credentialObjects.Add( JsonConvert.DeserializeObject <CredentialInfo>( await AnonCreds.ProverGetCredentialAsync(wallet, credId))); } var schemas = await BuildSchemasAsync(pool, credentialObjects .Select(x => x.SchemaId) .Distinct()); var definitions = await BuildCredentialDefinitionsAsync(pool, credentialObjects .Select(x => x.CredentialDefinitionId) .Distinct()); var revocationStates = await BuildRevocationStatesAsync(pool, credentialObjects, requestedCredentials); var proofJson = await AnonCreds.ProverCreateProofAsync(wallet, record.RequestJson, requestedCredentials.ToJson(), provisioningRecord.MasterSecretId, schemas, definitions, revocationStates); record.ProofJson = proofJson; await record.TriggerAsync(ProofTrigger.Accept); await RecordService.UpdateAsync(wallet, record); var proof = await MessageSerializer.PackSealedAsync <ProofMessage>( new ProofDetails { ProofJson = proofJson, RequestNonce = JsonConvert.DeserializeObject <ProofRequest>(record.RequestJson).Nonce }, wallet, connection.MyVk, connection.TheirVk); proof.Type = MessageUtils.FormatDidMessageType(connection.TheirDid, MessageTypes.DisclosedProof); return(proof); }
/// <inheritdoc /> public virtual async Task <ProofMessage> CreateProofAsync(IAgentContext agentContext, string proofRequestId, RequestedCredentials requestedCredentials) { var record = await GetAsync(agentContext, proofRequestId); if (record.State != ProofState.Requested) { throw new AgentFrameworkException(ErrorCode.RecordInInvalidState, $"Proof state was invalid. Expected '{ProofState.Requested}', found '{record.State}'"); } 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(agentContext.Pool, credentialObjects .Select(x => x.SchemaId) .Distinct()); var definitions = await BuildCredentialDefinitionsAsync(agentContext.Pool, credentialObjects .Select(x => x.CredentialDefinitionId) .Distinct()); var revocationStates = await BuildRevocationStatesAsync(agentContext.Pool, credentialObjects, requestedCredentials); var proofJson = await AnonCreds.ProverCreateProofAsync(agentContext.Wallet, record.RequestJson, requestedCredentials.ToJson(), provisioningRecord.MasterSecretId, schemas, definitions, revocationStates); record.ProofJson = proofJson; await record.TriggerAsync(ProofTrigger.Accept); await RecordService.UpdateAsync(agentContext.Wallet, record); return(new ProofMessage { ProofJson = proofJson, RequestNonce = JsonConvert.DeserializeObject <ProofRequest>(record.RequestJson).Nonce }); }
/// <inheritdoc /> public virtual async Task AcceptProofRequestAsync(Wallet wallet, Pool pool, string proofRequestId, RequestedCredentials requestedCredentials) { var request = await RecordService.GetAsync <ProofRecord>(wallet, proofRequestId); var connection = await ConnectionService.GetAsync(wallet, request.ConnectionId); var proof = await CreateProofAsync(wallet, pool, proofRequestId, requestedCredentials); await RouterService.ForwardAsync(new ForwardEnvelopeMessage { Content = proof.ToJson(), Type = MessageUtils.FormatDidMessageType(connection.TheirDid, MessageTypes.Forward) }, connection.Endpoint); }
public async Task <IActionResult> SendProof(string proofRecordId) { var agentContext = await _agentProvider.GetContextAsync(); var proofRecord = await _proofService.GetAsync(agentContext, proofRecordId); var connectionRecord = await _connectionService.GetAsync(agentContext, proofRecord.ConnectionId); var request = JsonConvert.DeserializeObject <ProofRequest>(proofRecord.RequestJson); var requestedCredentials = new RequestedCredentials(); foreach (var requestedAttribute in request.RequestedAttributes) { var credentials = await _proofService.ListCredentialsForProofRequestAsync(agentContext, request, requestedAttribute.Key); requestedCredentials.RequestedAttributes.Add(requestedAttribute.Key, new RequestedAttribute { CredentialId = credentials.First().CredentialInfo.Referent, Revealed = true }); } foreach (var requestedAttribute in request.RequestedPredicates) { var credentials = await _proofService.ListCredentialsForProofRequestAsync(agentContext, request, requestedAttribute.Key); requestedCredentials.RequestedPredicates.Add(requestedAttribute.Key, new RequestedAttribute { CredentialId = credentials.First().CredentialInfo.Referent, Revealed = false }); } var(proofMsg, record) = await _proofService.CreatePresentationAsync(agentContext, proofRecordId, requestedCredentials); await _messageService.SendAsync(agentContext.Wallet, proofMsg, connectionRecord); return(RedirectToAction("Index")); }
/// <inheritdoc /> public virtual async Task <ProofMessage> AcceptProofRequestAsync(IAgentContext agentContext, string proofRequestId, RequestedCredentials requestedCredentials) { var request = await GetAsync(agentContext, proofRequestId); if (request.State != ProofState.Requested) { throw new AgentFrameworkException(ErrorCode.RecordInInvalidState, $"Proof record state was invalid. Expected '{ProofState.Requested}', found '{request.State}'"); } var connection = await ConnectionService.GetAsync(agentContext, request.ConnectionId); if (connection.State != ConnectionState.Connected) { throw new AgentFrameworkException(ErrorCode.RecordInInvalidState, $"Connection state was invalid. Expected '{ConnectionState.Connected}', found '{connection.State}'"); } return(await CreateProofAsync(agentContext, proofRequestId, requestedCredentials)); }
public async Task <RequestedCredentials> buildCredentials() { var _proofService = App.Container.Resolve <IProofService>() as DefaultProofService; var _credentialService = App.Container.Resolve <ICredentialService>(); var requestedCredentials = new RequestedCredentials(); var context = await _contextProvider.GetContextAsync(); var proofRequest = JsonConvert.DeserializeObject <ProofRequest>(_proofRequestTransport.Record.RequestJson); foreach (var requestedAttribute in proofRequest.RequestedAttributes) { var credentials = await _proofService.ListCredentialsForProofRequestAsync(context, proofRequest, requestedAttribute.Key); string credentialId = ""; if (credentials.Any()) { credentialId = credentials.First().CredentialInfo.Referent; } else { credentialId = _credential.Id; } if (credentialId != null) { requestedCredentials.RequestedAttributes.Add(requestedAttribute.Key, new RequestedAttribute { CredentialId = credentialId, Revealed = true }); } } return(requestedCredentials); }
/// <inheritdoc /> public virtual async Task <EphemeralChallengeResponseMessage> CreateProofChallengeResponseAsync(IAgentContext agentContext, EphemeralChallengeMessage message, RequestedCredentials credentials) { if (message.Challenge.Type != ChallengeType.Proof) { throw new AgentFrameworkException(ErrorCode.InvalidMessage, "Challenge.Type != Proof"); } var challengeResponse = new EphemeralChallengeResponseMessage { Id = Guid.NewGuid().ToString(), Status = EphemeralChallengeResponseStatus.Accepted }; var proofRequest = message.Challenge.Contents.ToObject <ProofRequest>(); var proof = await ProofService.CreateProofAsync(agentContext, proofRequest, credentials); challengeResponse.Response = new EphemeralChallengeContents { Type = ChallengeType.Proof, Contents = JsonConvert.DeserializeObject <JObject>(proof) }; challengeResponse.ThreadFrom(message); return(challengeResponse); }
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.CreateRequestAsync(_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 <RequestPresentationMessage>(); Assert.NotNull(proofRequest); //Holder stores the proof request var holderProofRequestId = await _proofService.ProcessRequestAsync(_holderWallet, proofRequest, holderConnection); var holderProofRecord = await _proofService.GetAsync(_holderWallet, holderProofRequestId.Id); 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.CreatePresentationAsync(_holderWallet, holderProofRequestId.Id, requestedCredentials); var ex = await Assert.ThrowsAsync <AriesFrameworkException>(async() => await _proofService.CreatePresentationAsync(_holderWallet, holderProofRequestId.Id, requestedCredentials)); Assert.True(ex.ErrorCode == ErrorCode.RecordInInvalidState); }
/// <inheritdoc /> public virtual async Task <(ProofMessage, ConnectionRecord)> CreateProofAsync(IAgentContext agentContext, string proofRequestId, RequestedCredentials requestedCredentials) { var record = await GetAsync(agentContext, proofRequestId); var connection = await ConnectionService.GetAsync(agentContext, record.ConnectionId); if (record.State != ProofState.Requested) { throw new AgentFrameworkException(ErrorCode.RecordInInvalidState, $"Proof state was invalid. Expected '{ProofState.Requested}', found '{record.State}'"); } var proofJson = await CreateProofJsonAsync(agentContext, requestedCredentials, record.RequestJson); if (proofJson.Contains("\"rev_reg_id\":null")) { String[] separator = { "\"rev_reg_id\":null" }; String[] proofJsonList = proofJson.Split(separator, StringSplitOptions.None); proofJson = proofJsonList[0] + "\"rev_reg_id\":null,\"timestamp\":null}]}"; } record.ProofJson = proofJson; await record.TriggerAsync(ProofTrigger.Accept); await RecordService.UpdateAsync(agentContext.Wallet, record); var threadId = record.GetTag(TagConstants.LastThreadId); var proofMsg = new ProofMessage { ProofJson = proofJson }; proofMsg.ThreadFrom(threadId); return(proofMsg, connection); }
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); }
public async Task CanConductChallengeFlow() { //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(); // Challenger sends a challenge { var challengeConfig = new EphemeralChallengeConfiguration { Name = "Test", Type = ChallengeType.Proof, Contents = new ProofRequestConfiguration { RequestedAttributes = new Dictionary <string, ProofAttributeInfo> { { "first-name-requirement", new ProofAttributeInfo { Name = "first_name" } } } } }; var challengeConfigId = await _ephemeralChallengeService.CreateChallengeConfigAsync(_requestorWallet, challengeConfig); (var challenge, var record) = await _ephemeralChallengeService.CreateChallengeAsync(_requestorWallet, challengeConfigId); Assert.True(!string.IsNullOrEmpty(challenge.ChallengerName)); Assert.True(challenge.RecipientKeys.Count() == 1); Assert.True(challenge.RecipientKeys.First() == TestConstants.DefaultVerkey); Assert.True(challenge.ServiceEndpoint == TestConstants.DefaultMockUri); _messages.Add(challenge); var result = await _ephemeralChallengeService.GetChallengeStateAsync(_requestorWallet, record.Id); Assert.True(result == ChallengeState.Challenged); } //Challenge responder recieves challenge { var challengeMessage = _messages.OfType <EphemeralChallengeMessage>().First(); var proofRequest = challengeMessage.Challenge.Contents.ToObject <ProofRequest>(); var requestedCredentials = new RequestedCredentials(); foreach (var requestedAttribute in proofRequest.RequestedAttributes) { var credentials = await _proofService.ListCredentialsForProofRequestAsync(_holderWallet, 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(_holderWallet, proofRequest, requestedAttribute.Key); requestedCredentials.RequestedPredicates.Add(requestedAttribute.Key, new RequestedAttribute { CredentialId = credentials.First().CredentialInfo.Referent, Revealed = true }); } var challenge = await _ephemeralChallengeService.CreateProofChallengeResponseAsync( _holderWallet, challengeMessage, requestedCredentials); _messages.Add(challenge); } //Challenger recieves challenge response and verifies it { var challengeResponseMessage = _messages.OfType <EphemeralChallengeResponseMessage>().First(); var id = await _ephemeralChallengeService.ProcessChallengeResponseAsync(_requestorWallet, challengeResponseMessage); var result = await _ephemeralChallengeService.GetChallengeStateAsync(_requestorWallet, id); Assert.True(result == ChallengeState.Accepted); } }
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, _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 await _proofService.AcceptProofRequestAsync(_holderWallet, holderProofRequestId, requestedCredentials); var ex = await Assert.ThrowsAsync <AgentFrameworkException>(async() => await _proofService.AcceptProofRequestAsync(_holderWallet, holderProofRequestId, requestedCredentials)); Assert.True(ex.ErrorCode == ErrorCode.RecordInInvalidState); }
private async Task CreateRequestedCredential() { var requestedCredentials = new RequestedCredentials(); var context = await _agentProvider.GetContextAsync(); _proofRequestAndCredentialMaps.Clear(); RangeEnabledObservableCollection <ProofRequestAndCredentialMap> proofRequestMapList = new RangeEnabledObservableCollection <ProofRequestAndCredentialMap>(); foreach (var requestedAttribute in ProofRequestObject.RequestedAttributes) { ProofRequestAndCredentialMap proofCredMap = new ProofRequestAndCredentialMap(); proofCredMap.ProofKey = requestedAttribute.Key; var credentials = await _proofService.ListCredentialsForProofRequestAsync(context, _proofRequest, requestedAttribute.Key); if (credentials.Count != 0) { var firstSuitableCredential = credentials.First(); _isSatisfied = true; proofCredMap.Referent = firstSuitableCredential.CredentialInfo.Referent; var key = this.RemoveAllSpaceAndToLower(requestedAttribute.Value.Name); var proofKeyAndCredentialMap = firstSuitableCredential.CredentialInfo.Attributes.ToDictionary(k => RemoveAllSpaceAndToLower(k.Key), v => new KeyValuePair <string, string>(v.Key, v.Value)); if (proofKeyAndCredentialMap.ContainsKey(key)) { var value = proofKeyAndCredentialMap[key].Value; var credKey = proofKeyAndCredentialMap[key].Key; KeyValuePair <string, string> keyValuePair = new KeyValuePair <string, string>(credKey, value); proofCredMap.CredentialAttribute = keyValuePair; } requestedCredentials.RequestedAttributes.Add(requestedAttribute.Key, new RequestedAttribute { CredentialId = firstSuitableCredential.CredentialInfo.Referent, Revealed = true }); } else { _isSatisfied = false; proofCredMap.Referent = "Unavailable"; var key = requestedAttribute.Value.Name; var value = "Unavailable"; KeyValuePair <string, string> keyValuePair = new KeyValuePair <string, string>(key, value); proofCredMap.CredentialAttribute = keyValuePair; requestedCredentials.RequestedAttributes.Add(requestedAttribute.Key, new RequestedAttribute { CredentialId = "Unavailable", Revealed = true }); } proofRequestMapList.Add(proofCredMap); //requestedCredentials.RequestedAttributes. //proofAndCredentialAttributesMapping.Add(requestedAttribute, credentials.First().CredentialInfo.Attributes.) } foreach (var requestedAttribute in ProofRequestObject.RequestedPredicates) { var credentials = await _proofService.ListCredentialsForProofRequestAsync(context, ProofRequestObject, requestedAttribute.Key); ProofRequestAndCredentialMap proofCredMap = new ProofRequestAndCredentialMap(); if (credentials.Count != 0) { var firstSuitableCredential = credentials.First(); _isSatisfied = true; proofCredMap.Referent = firstSuitableCredential.CredentialInfo.Referent; var key = this.RemoveAllSpaceAndToLower(requestedAttribute.Value.Name); var proofKeyAndCredentialMap = firstSuitableCredential.CredentialInfo.Attributes.ToDictionary(k => RemoveAllSpaceAndToLower(k.Key), v => new KeyValuePair <string, string>(v.Key, v.Value)); if (proofKeyAndCredentialMap.ContainsKey(key)) { var value = proofKeyAndCredentialMap[key].Value; var credKey = proofKeyAndCredentialMap[key].Key; KeyValuePair <string, string> keyValuePair = new KeyValuePair <string, string>(credKey, value); proofCredMap.CredentialAttribute = keyValuePair; } requestedCredentials.RequestedPredicates.Add(requestedAttribute.Key, new RequestedAttribute { CredentialId = firstSuitableCredential.CredentialInfo.Referent, Revealed = true }); } else { _isSatisfied = false; proofCredMap.ProofKey = requestedAttribute.Key; proofCredMap.Referent = "Unavailable"; var key = requestedAttribute.Value.Name; var value = "Unavailable"; KeyValuePair <string, string> keyValuePair = new KeyValuePair <string, string>(key, value); proofCredMap.CredentialAttribute = keyValuePair; requestedCredentials.RequestedPredicates.Add(requestedAttribute.Key, new RequestedAttribute { CredentialId = "Unavailable", Revealed = true }); } proofRequestMapList.Add(proofCredMap); } ProofRequestAndCredentialMaps = proofRequestMapList; RequestedCredentials = requestedCredentials; }
private async Task SelectCredentialsForProofAsync(IAgentContext agentContext, ProofRecord proof, ConnectionRecord connection) { var requestJson = (JObject)JsonConvert.DeserializeObject(proof.RequestJson); JObject _requestedAttributes = (JObject)requestJson["requested_attributes"]; JObject _requestedPredicates = (JObject)requestJson["requested_predicates"]; IList <string> _requestedAttributesKeys = _requestedAttributes?.Properties().Select(p => p.Name).ToList(); IList <string> _requestedPredicatesKeys = _requestedPredicates?.Properties().Select(p => p.Name).ToList(); JToken cred_def_id = null; try { cred_def_id = _requestedAttributes[_requestedAttributesKeys[0]]["restrictions"][0]["cred_def_id"]; } catch (Exception) { cred_def_id = null; } var credentials = new List <CredentialRecord>(); if (cred_def_id != null) { credentials = await RecordService.SearchAsync <CredentialRecord>(agentContext.Wallet, SearchQuery.And(SearchQuery.Equal(nameof(CredentialRecord.State), CredentialState.Issued.ToString("G")), SearchQuery.Equal(nameof(CredentialRecord.CredentialDefinitionId), cred_def_id.ToString())), null, 100); } else { credentials = await RecordService.SearchAsync <CredentialRecord>(agentContext.Wallet, SearchQuery.Equal(nameof(CredentialRecord.State), CredentialState.Issued.ToString("G")), null, 100); } bool credentialFound = false; if (credentials.Count > 0) { Dictionary <string, RequestedAttribute> requestedAttributes = new Dictionary <string, RequestedAttribute>(); Dictionary <string, RequestedAttribute> requestedPredicates = new Dictionary <string, RequestedAttribute>(); foreach (var credential in credentials) { if (!credentialFound) { IEnumerable <CredentialAttribute> Attributes = credential.CredentialAttributesValues .Select(p => new CredentialAttribute() { Name = p.Name, Value = p.Value?.ToString(), Type = "Text" }) .ToList(); foreach (var item in _requestedAttributesKeys) { foreach (var attrib in Attributes) { if (_requestedAttributes[item]["name"].ToString() == attrib.Name) { RequestedAttribute requestedAttribute = new RequestedAttribute(); requestedAttribute.CredentialId = credential.CredentialId; requestedAttribute.Revealed = true; requestedAttribute.Timestamp = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeMilliseconds(); requestedAttributes.Add(item, requestedAttribute); credentialFound = true; } } if (!credentialFound) { requestedAttributes.Clear(); } } foreach (var item in _requestedPredicatesKeys) { RequestedAttribute requestedAttribute = new RequestedAttribute(); requestedAttribute.CredentialId = credential.CredentialId; requestedAttribute.Timestamp = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeMilliseconds(); requestedPredicates.Add(item, requestedAttribute); } } } if (credentialFound) { RequestedCredentials requestedCredentials = new RequestedCredentials(); requestedCredentials.RequestedAttributes = requestedAttributes; requestedCredentials.RequestedPredicates = requestedPredicates; var proofJson = await CreateProofJsonAsync(agentContext, requestedCredentials, proof.RequestJson); var threadId = proof.GetTag(TagConstants.LastThreadId); var proofMsg = new ProofMessage { ProofJson = proofJson }; proofMsg.ThreadFrom(threadId); await MessageService.SendAsync(agentContext.Wallet, proofMsg, connection); } } }