Example #1
0
        /// <inheritdoc />
        public virtual async Task <(ProofRequestMessage, string)> CreateProofRequestAsync(IAgentContext agentContext, string connectionId,
                                                                                          string proofRequestJson)
        {
            Logger.LogInformation(LoggingEvents.CreateProofRequest, "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 proofJobj = JObject.Parse(proofRequestJson);

            var proofRecord = new ProofRecord
            {
                Id           = Guid.NewGuid().ToString(),
                ConnectionId = connection.Id,
                RequestJson  = proofRequestJson
            };

            proofRecord.SetTag(TagConstants.Nonce, proofJobj["nonce"].ToObject <string>());
            proofRecord.SetTag(TagConstants.Role, TagConstants.Requestor);

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

            return(new ProofRequestMessage {
                ProofRequestJson = proofRequestJson
            }, proofRecord.Id);
        }
        /// <inheritdoc />
        public virtual async Task <ProofRequestMessage> CreateProofRequestAsync(Wallet wallet, string connectionId,
                                                                                string proofRequestJson)
        {
            Logger.LogInformation(LoggingEvents.CreateProofRequest, "ConnectionId {0}", connectionId);

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

            var proofJobj = JObject.Parse(proofRequestJson);

            var proofRecord = new ProofRecord
            {
                Id           = Guid.NewGuid().ToString(),
                ConnectionId = connection.ConnectionId,
                RequestJson  = proofRequestJson
            };

            proofRecord.Tags[TagConstants.Nonce]        = proofJobj["nonce"].ToObject <string>();
            proofRecord.Tags[TagConstants.ConnectionId] = connection.GetId();
            proofRecord.Tags[TagConstants.Role]         = TagConstants.Requestor;

            await RecordService.AddAsync(wallet, proofRecord);

            var proofRequest = await MessageSerializer.PackSealedAsync <ProofRequestMessage>(
                new ProofRequestDetails { ProofRequestJson = proofRequestJson },
                wallet,
                connection.MyVk,
                connection.TheirVk);

            proofRequest.Type = MessageUtils.FormatDidMessageType(connection.TheirDid, MessageTypes.ProofRequest);

            return(proofRequest);
        }
        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();
        }
Example #4
0
        /// <inheritdoc />
        public virtual async Task <string> ProcessProofRequestAsync(IAgentContext agentContext,
                                                                    ProofRequestMessage proofRequest, ConnectionRecord connection)
        {
            var requestJson = proofRequest.ProofRequestJson;

            // Write offer record to local wallet
            var proofRecord = new ProofRecord
            {
                Id           = Guid.NewGuid().ToString(),
                RequestJson  = requestJson,
                ConnectionId = connection.Id,
                State        = ProofState.Requested
            };

            proofRecord.SetTag(TagConstants.LastThreadId, proofRequest.GetThreadId());
            proofRecord.SetTag(TagConstants.Role, TagConstants.Holder);

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

            EventAggregator.Publish(new ServiceMessageProcessingEvent
            {
                RecordId    = proofRecord.Id,
                MessageType = proofRequest.Type,
                ThreadId    = proofRequest.GetThreadId()
            });

            return(proofRecord.Id);
        }
        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>();
        }
Example #6
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);
        }
 /// <summary>
 /// This constructor is used when proof request details are fetched from mediator
 /// </summary>
 public ProofRequestViewModel(IUserDialogs userDialogs,
                              INavigationService navigationService,
                              IAgentProvider agentContextProvider,
                              IProofService proofService,
                              ILifetimeScope scope,
                              ICredentialService credentialService,
                              IConnectionService connectionService,
                              IEventAggregator eventAggregator,
                              IMessageService messageService,
                              ProofRecord proofRecord,
                              ConnectionRecord connection) : base("Proof Request Detail", userDialogs, navigationService)
 {
     this.userDialogs          = userDialogs;
     this.navigationService    = navigationService;
     this.agentContextProvider = agentContextProvider;
     this.proofService         = proofService;
     this.scope             = scope;
     this.credentialService = credentialService;
     this.connectionService = connectionService;
     this.eventAggregator   = eventAggregator;
     this.messageService    = messageService;
     this.proofRecord       = proofRecord;
     this.connection        = connection;
     ConnectionLogo         = connection.Alias.ImageUrl;
     ConnectionName         = connection.Alias.Name;
     ProofRequest           = JsonConvert.DeserializeObject <ProofRequest>(proofRecord.RequestJson);
     ProofRequestName       = ProofRequest?.Name;
     RequestedAttributes    = new ObservableCollection <ProofRequestAttributeViewModel>();
     HasLogo = !string.IsNullOrWhiteSpace(ConnectionLogo);
 }
Example #8
0
        /// <inheritdoc />
        public virtual async Task <string> ProcessProofRequestAsync(IAgentContext agentContext, ProofRequestMessage proofRequest)
        {
            var requestJson = proofRequest.ProofRequestJson;

            var offer = JObject.Parse(requestJson);
            var nonce = offer["nonce"].ToObject <string>();

            // Write offer record to local wallet
            var proofRecord = new ProofRecord
            {
                Id           = Guid.NewGuid().ToString(),
                RequestJson  = requestJson,
                ConnectionId = agentContext.Connection.Id,
                State        = ProofState.Requested
            };

            proofRecord.SetTag(TagConstants.Nonce, nonce);
            proofRecord.SetTag(TagConstants.Role, TagConstants.Holder);

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

            EventAggregator.Publish(new ServiceMessageProcessingEvent
            {
                RecordId    = proofRecord.Id,
                MessageType = proofRequest.Type,
            });

            return(proofRecord.Id);
        }
        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);
        }
Example #10
0
        private async Task ScanInvite()
        {
            var expectedFormat = ZXing.BarcodeFormat.QR_CODE;

            var opts = new ZXing.Mobile.MobileBarcodeScanningOptions {
                PossibleFormats = new List <ZXing.BarcodeFormat> {
                    expectedFormat
                }
            };

            var context = await _agentContextProvider.GetContextAsync();

            var scanner = new ZXing.Mobile.MobileBarcodeScanner();

            var result = await scanner.Scan(opts);

            if (result == null)
            {
                return;
            }

            AgentMessage message = await MessageDecoder.ParseMessageAsync(result.Text);

            switch (message)
            {
            case ConnectionInvitationMessage invitation:
                break;

            case RequestPresentationMessage presentation:
                RequestPresentationMessage proofRequest = (RequestPresentationMessage)presentation;
                var         service     = message.GetDecorator <ServiceDecorator>(DecoratorNames.ServiceDecorator);
                ProofRecord proofRecord = await _proofService.ProcessRequestAsync(context, proofRequest, null);

                proofRecord.SetTag("RecipientKey", service.RecipientKeys.ToList()[0]);
                proofRecord.SetTag("ServiceEndpoint", service.ServiceEndpoint);
                await _recordService.UpdateAsync(context.Wallet, proofRecord);

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

            default:
                DialogService.Alert("Invalid invitation!");
                return;
            }

            Device.BeginInvokeOnMainThread(async() =>
            {
                if (message is ConnectionInvitationMessage)
                {
                    await NavigationService.NavigateToAsync <AcceptInviteViewModel>(message as ConnectionInvitationMessage, NavigationType.Modal);
                }
            });
        }
Example #11
0
        public static async Task <(ProofRecord holderProofRecord, ProofRecord RequestorProofRecord)> ProofProtocolAsync(
            IProofService proofService,
            IProducerConsumerCollection <AgentMessage> messages,
            ConnectionRecord holderConnection, ConnectionRecord requestorConnection,
            IAgentContext holderContext,
            IAgentContext requestorContext, ProofRecord requestorProofRecord)
        {
            // Holder accepts the proof requests and builds a proof
            var holderRequestPresentationMessage = FindContentMessage <RequestPresentationMessage>(messages);

            Assert.NotNull(holderRequestPresentationMessage);

            //Holder stores the proof request if they haven't created it already
            var holderProofRecord = await proofService.ProcessRequestAsync(holderContext, holderRequestPresentationMessage, holderConnection);

            Assert.Equal(ProofState.Requested, holderProofRecord.State);
            Console.WriteLine(holderProofRecord.RequestJson);


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

            // Auto satisfy 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,
                holderProofRecord.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);
        }
Example #12
0
        private async Task DisplayRequestPresentation(string recordId)
        {
            IAgentContext context = await _agentContextProvider.GetContextAsync();

            ProofRecord proofRecord = await _proofService.GetAsync(context, recordId);

            ProofRequestViewModel proofRequest = await _proofAssembler.Assemble(proofRecord);

            await _requestPresentationFiller.Fill(proofRequest);

            await NavigationService.NavigateToAsync(proofRequest, null, NavigationType.Modal);
        }
        public async Task <GetProofResponse> Handle
        (
            GetProofRequest aGetProofRequest,
            CancellationToken aCancellationToken
        )
        {
            IAgentContext agentContext = await AgentProvider.GetContextAsync();

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

            var response = new GetProofResponse(proofRecord, aGetProofRequest.CorrelationId);

            return(await Task.Run(() => response));
        }
        /// <inheritdoc />
        public virtual async Task <string> ProcessProofRequestAsync(IAgentContext agentContext,
                                                                    ProofRequestMessage proofRequest, ConnectionRecord connection, bool isVcOidc)
        {
            var requestJson = proofRequest.ProofRequestJson;


            // Write offer record to local wallet
            var proofRecord = new ProofRecord
            {
                Id           = Guid.NewGuid().ToString(),
                RequestJson  = requestJson,
                ConnectionId = isVcOidc ? null : connection.Id,
                State        = ProofState.Requested
            };

            proofRecord.SetTag(TagConstants.LastThreadId, proofRequest.GetThreadId());
            proofRecord.SetTag(TagConstants.Role, TagConstants.Holder);

            if (!connection.Sso && !isVcOidc)
            {
                await RecordService.AddAsync(agentContext.Wallet, proofRecord);

                EventAggregator.Publish(new ServiceMessageProcessingEvent
                {
                    RecordId    = proofRecord.Id,
                    MessageType = proofRequest.Type,
                    ThreadId    = proofRequest.GetThreadId()
                });
            }
            else
            {
                if (isVcOidc)
                {
                    connection.Endpoint = new AgentEndpoint {
                        Uri = proofRequest.ServiceDecorator.ServiceEndpoint?.ToString()
                    };
                }
                await SelectCredentialsForProofAsync(agentContext, proofRecord, connection);
            }

            return(proofRecord.Id);
        }
        /// <inheritdoc />
        public virtual async Task <string> ProcessProofRequestAsync(Wallet wallet, ProofRequestMessage proofRequest)
        {
            var(didOrKey, _) = MessageUtils.ParseMessageType(proofRequest.Type);

            var connectionSearch =
                await ConnectionService.ListAsync(wallet, new SearchRecordQuery { { TagConstants.MyDid, didOrKey } });

            if (!connectionSearch.Any())
            {
                throw new Exception($"Can't find connection record for type {proofRequest.Type}");
            }
            var connection = connectionSearch.First();

            var(requestDetails, _) =
                await MessageSerializer.UnpackSealedAsync <ProofRequestDetails>(proofRequest.Content, wallet,
                                                                                connection.MyVk);

            var requestJson = requestDetails.ProofRequestJson;

            var offer = JObject.Parse(requestJson);
            var nonce = offer["nonce"].ToObject <string>();

            // Write offer record to local wallet
            var proofRecord = new ProofRecord
            {
                Id           = Guid.NewGuid().ToString(),
                RequestJson  = requestJson,
                ConnectionId = connection.GetId(),
                State        = ProofState.Requested
            };

            proofRecord.Tags[TagConstants.ConnectionId] = connection.GetId();
            proofRecord.Tags[TagConstants.Nonce]        = nonce;
            proofRecord.Tags[TagConstants.Role]         = TagConstants.Holder;

            await RecordService.AddAsync(wallet, proofRecord);

            return(proofRecord.GetId());
        }
        public ProofRequestViewModel(IUserDialogs userDialogs,
                                     INavigationService navigationService,
                                     IProofService proofService,
                                     IAgentProvider agentProvider,
                                     IMessageService messageService,
                                     IEventAggregator eventAggregator,
                                     IConnectionService connectionService, ProofRecord proofRequestRecord) : base(nameof(ProofRequestViewModel), userDialogs, navigationService)
        {
            Title               = "Proof Request";
            _proofService       = proofService;
            _agentProvider      = agentProvider;
            _messageService     = messageService;
            _connectionService  = connectionService;
            _proofRequestRecord = proofRequestRecord;
            _eventAggregator    = eventAggregator;
            _proofRequest       = _proofRequestRecord.RequestJson.ToObject <ProofRequest>();

            if (_proofRequestRecord.CreatedAtUtc != null)
            {
                IssuedDate = (DateTime)_proofRequestRecord.CreatedAtUtc;
            }
        }
Example #17
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);
        }
        public IHttpActionResult GetProofRecord(string id)
        {
            var tlist = new ProofRecord().GetProofRecord(id);

            return(Ok(tlist));
        }
        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);
                }
            }
        }
Example #20
0
 public GetProofResponse(ProofRecord aProofRecord, Guid aCorrelationId) : base(aCorrelationId)
 {
     ProofRecord = aProofRecord;
 }