private void SetupIdentityProviders(ScenarioDefinition scenarioDefinition, long scenarioSessionId) { foreach (var scenarioAccount in scenarioDefinition.Setup.Accounts.Where(a => a.AccountType == AccountType.IdentityProvider)) { long accountId = _accountsService.Create(AccountType.IdentityProvider, scenarioAccount.AccountInfo, "qqq", true); _dataAccessService.AddScenarionSessionAccount(scenarioSessionId, accountId); AccountDescriptor accountDescriptor = _accountsService.Authenticate(accountId, "qqq"); _executionContextManager.InitializeStateExecutionServices(accountId, accountDescriptor.SecretSpendKey); foreach (var attributeScheme in scenarioAccount.IdentityScheme) { long schemeId = _dataAccessService.AddAttributeToScheme(accountDescriptor.PublicSpendKey.ToHexString(), attributeScheme.AttributeName, attributeScheme.AttributeSchemeName, attributeScheme.Alias, null); if (attributeScheme.CanBeRoot) { _dataAccessService.ToggleOnRootAttributeScheme(schemeId); } } IdentitiesScheme rootScheme = _dataAccessService.GetRootIdentityScheme(accountDescriptor.PublicSpendKey.ToHexString()); foreach (var identity in scenarioAccount.Identities) { IEnumerable <(string attributeName, string content)> attrs = GetAttribitesAndContent(identity, accountDescriptor); Identity identityDb = _dataAccessService.CreateIdentity(accountDescriptor.AccountId, identity.Alias, attrs.ToArray()); } } }
private string FuncPublicSpendKey(string[] args) { string accountNameStr = args[0]; AccountDescriptor account = _accountsService.GetAll().FirstOrDefault(a => a.AccountInfo == accountNameStr); return(account?.PublicSpendKey.ToHexString()); }
public IActionResult ResetCompromisedAccount(long accountId, string password) { AccountDescriptor accountDescriptor = _accountsService.Authenticate(accountId, password); if (accountDescriptor != null) { _accountsService.ResetAccount(accountId, password); _executionContextManager.UnregisterExecutionServices(accountId); accountDescriptor = _accountsService.Authenticate(accountId, password); if (accountDescriptor.AccountType == AccountType.User) { _executionContextManager.InitializeUtxoExecutionServices(accountId, accountDescriptor.SecretSpendKey, accountDescriptor.SecretViewKey, accountDescriptor.PwdHash); } else { _executionContextManager.InitializeStateExecutionServices(accountId, accountDescriptor.SecretSpendKey); } return(Ok()); } else { throw new AccountAuthenticationFailedException(accountId); } }
public async Task <IActionResult> GetDocumentSignatures(long spId) { AccountDescriptor account = _accountsService.GetById(spId); IEnumerable <DocumentDto> documents = await Task.WhenAll(_dataAccessService.GetSpDocuments(spId) .Select(async d => new DocumentDto { DocumentId = d.SpDocumentId, DocumentName = d.DocumentName, Hash = d.Hash, AllowedSigners = (d.AllowedSigners?.Select(s => new AllowedSignerDto { AllowedSignerId = s.SpDocumentAllowedSignerId, GroupName = s.GroupName, GroupOwner = s.GroupIssuer }) ?? Array.Empty <AllowedSignerDto>()).ToList(), Signatures = ((await Task.WhenAll(d.DocumentSignatures?.Select(async s => new DocumentSignatureDto { DocumentId = d.SpDocumentId, DocumentHash = d.Hash, SignatureId = s.SpDocumentSignatureId, DocumentRecordHeight = s.DocumentRecordHeight, SignatureRecordHeight = s.SignatureRecordHeight, SignatureVerification = await _documentSignatureVerifier.Verify(account.PublicSpendKey, d.Hash.HexStringToByteArray(), s.DocumentRecordHeight, s.SignatureRecordHeight).ConfigureAwait(false) })).ConfigureAwait(false)) ?? Array.Empty <DocumentSignatureDto>()).ToList() })).ConfigureAwait(false); return(Ok(documents)); }
public ScenarioSession ResumeScenario(string userSubject, int id) { _logger.Info($"{nameof(ResumeScenario)}({userSubject}, {id})"); try { ScenarioSession scenarioSession = _dataAccessService.GetScenarioSessions(userSubject).FirstOrDefault(s => s.ScenarioId == id); if (scenarioSession == null) { throw new ScenarioSessionNotFoundException(userSubject, id); } bool needInitialize = false; if (!_activeScenarios.TryGetValue(userSubject, out ScenarioMonitoringData scenarioMonitoringData)) { needInitialize = true; } else if (scenarioMonitoringData.ScenarioId != id) { needInitialize = true; } if (needInitialize) { scenarioMonitoringData = new ScenarioMonitoringData { ScenarioId = id, ScenarioSessionId = scenarioSession.ScenarioSessionId, ActivationTime = scenarioSession.StartTime, LastUseTime = DateTime.UtcNow }; _activeScenarios.AddOrUpdate(userSubject, scenarioMonitoringData, (k, v) => v); ScenarioDefinition scenarioDefinition = _scenarios[id]; IEnumerable <Client.DataLayer.Model.Scenarios.ScenarioAccount> scenarioAccounts = _dataAccessService.GetScenarioAccounts(scenarioSession.ScenarioSessionId); foreach (var scenarioAccount in scenarioAccounts) { AccountDescriptor account = _accountsService.GetById(scenarioAccount.AccountId); if (account.AccountType == AccountType.IdentityProvider || account.AccountType == AccountType.ServiceProvider) { AccountDescriptor accountDescriptor = _accountsService.Authenticate(scenarioAccount.AccountId, "qqq"); _executionContextManager.InitializeStateExecutionServices(accountDescriptor.AccountId, accountDescriptor.SecretSpendKey); } } } else { scenarioMonitoringData.LastUseTime = DateTime.UtcNow; } return(scenarioSession); } catch (Exception ex) { _logger.Error($"Failed {nameof(ResumeScenario)}({userSubject}, {id})", ex); throw; } }
public AccountDescriptor Authenticate(ulong accountId, string password) { Account account = _dataAccessService.GetAccount(accountId); if (account == null) { throw new AccountNotFoundException(accountId); } AccountDescriptor accountDescriptor = null; if (account.AccountType == AccountType.User) { accountDescriptor = AuthenticateUtxoAccount(new AuthenticationInput { Password = password, Account = account }); } else { accountDescriptor = AuthenticateStateAccount(new AuthenticationInput { Password = password, Account = account }); } return(accountDescriptor); }
public JournalLine Build() { var account = _accountDescriptor ?? AccountDescriptor.As(_accountSourceId, _accountCode, _accountName); return(new JournalLine(_amount, _date, account) { Description = _decription ?? string.Empty }); }
public IActionResult GetSessionInfo(long spId) { string nonce = ConfidentialAssetsHelper.GetRandomSeed().ToHexString(); AccountDescriptor spAccount = _accountsService.GetById(spId); return(Ok(new { publicKey = spAccount.PublicSpendKey.ToHexString(), sessionKey = nonce, })); }
public ActionResult <IssuerActionDetails> GetIssuanceDetails(string issuer) { AccountDescriptor account = _accountsService.GetByPublicKey(issuer.HexStringToByteArray()); IssuerActionDetails registrationDetails = new IssuerActionDetails { Issuer = account.PublicSpendKey.ToHexString(), IssuerAlias = account.AccountInfo, ActionUri = $"{Request.Scheme}://{Request.Host.ToUriComponent()}/IdentityProvider/ProcessRootIdentityRequest?issuer={issuer}".EncodeToString64() }; return(registrationDetails); }
public async Task <IActionResult> GetAttributesScheme(long accountId) { AccountDescriptor account = _accountsService.GetById(accountId); if (account == null) { throw new AccountNotFoundException(accountId); } if (account.AccountType != AccountType.IdentityProvider) { throw new UnexpectedAccountTypeException(accountId, account.AccountType); } string issuer = account.PublicSpendKey.ToHexString(); IEnumerable <AttributeDefinition> attributeDefinitions = _dataAccessService.GetAttributesSchemeByIssuer(issuer, true) .Select(a => new AttributeDefinition { SchemeId = a.IdentitiesSchemeId, AttributeName = a.AttributeName, SchemeName = a.AttributeSchemeName, Alias = a.Alias, Description = a.Description, IsActive = a.IsActive, IsRoot = a.CanBeRoot }); IdentityAttributeSchemaDto rootAttributeScheme = null; var rootAttrDefinition = attributeDefinitions.FirstOrDefault(a => a.IsRoot); if (rootAttrDefinition != null) { rootAttributeScheme = new IdentityAttributeSchemaDto { AttributeName = rootAttrDefinition.AttributeName, Alias = rootAttrDefinition.Alias }; } IdentityAttributesSchemaDto schemaDto = new IdentityAttributesSchemaDto { RootAttribute = rootAttributeScheme, AssociatedAttributes = attributeDefinitions .Where(a => !a.IsRoot && a.SchemeName != AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD) .Select(a => new IdentityAttributeSchemaDto { AttributeName = a.AttributeName, Alias = a.Alias }).ToList() }; return(Ok(schemaDto)); }
public void Initialize(CancellationToken cancellationToken) { _logger.Info($"Initializing {nameof(O10InherenceService)}"); InherenceSetting inherenceSetting = _dataAccessService.GetInherenceSetting(Name); if (inherenceSetting == null) { inherenceSetting = CreateO10Inherence(); } AccountId = inherenceSetting.AccountId; _logger.LogIfDebug(() => $"[{AccountId}]: {nameof(Initialize)} proceeding"); AccountDescriptor accountDescriptor = _accountsService.GetById(inherenceSetting.AccountId); if (accountDescriptor == null) { _dataAccessService.RemoveInherenceSetting(Name); inherenceSetting = CreateO10Inherence(); accountDescriptor = _accountsService.Authenticate(inherenceSetting.AccountId, GetDefaultO10InherencePassword()); if (accountDescriptor == null) { throw new Exception($"{nameof(O10InherenceService)} initialization failed"); } } else { accountDescriptor = _accountsService.Authenticate(inherenceSetting.AccountId, GetDefaultO10InherencePassword()); } _logger.Info($"[{AccountId}]: Invoking InitializeStateExecutionServices"); _executionContextManager .InitializeStateExecutionServices( accountDescriptor.AccountId, accountDescriptor.SecretSpendKey, new Func <long, IStateTransactionsService, IStateClientCryptoService, CancellationToken, IUpdater>( (accountId, stateTransactionsService, stateClientSryptoService, ct) => { _clientCryptoService = stateClientSryptoService; return(this); })); Target = accountDescriptor.PublicSpendKey.ToHexString(); cancellationToken.Register(() => { _executionContextManager.UnregisterExecutionServices(AccountId); }); }
private Identity CreateIdentityInDb(AccountDescriptor account, IEnumerable <AttributeIssuanceDetails> issuanceInputDetails) { var rootAttributeDetails = issuanceInputDetails.First(a => a.Definition.IsRoot); Identity identity = _dataAccessService.GetIdentityByAttribute(account.AccountId, rootAttributeDetails.Definition.AttributeName, rootAttributeDetails.Value.Value); if (identity == null) { _dataAccessService.CreateIdentity(account.AccountId, rootAttributeDetails.Value.Value, issuanceInputDetails.Select(d => (d.Definition.AttributeName, d.Value.Value)).ToArray()); identity = _dataAccessService.GetIdentityByAttribute(account.AccountId, rootAttributeDetails.Definition.AttributeName, rootAttributeDetails.Value.Value); } return(identity); }
private AccountDescriptor AuthenticateStateAccount(AuthenticationInput authenticationInput) { AccountDescriptor accountDescriptor = null; byte[] key = DecryptStateKeys(authenticationInput.Account, authenticationInput.Password); if (key != null) { accountDescriptor = new AccountDescriptor { AccountType = authenticationInput.Account.AccountType, SecretSpendKey = key, PublicSpendKey = authenticationInput.Account.PublicSpendKey, AccountInfo = authenticationInput.Account.AccountInfo, AccountId = authenticationInput.Account.AccountId }; _executionContextManager.InitializeStateExecutionServices(authenticationInput.Account.AccountId, accountDescriptor.SecretSpendKey); } return(accountDescriptor); }
public async Task <IActionResult> CreateIdentity(long accountId, [FromBody] IdentityDto identity) { //StatePersistency statePersistency = _executionContextManager.ResolveStateExecutionServices(accountId); AccountDescriptor account = _accountsService.GetById(accountId); //byte[] assetId = await _assetsService.GenerateAssetId(identity.RootAttribute.SchemeName, identity.RootAttribute.Content, account.PublicSpendKey.ToHexString()).ConfigureAwait(false); //statePersistency.TransactionsService.IssueBlindedAsset(assetId, 0UL.ToByteArray(32), out byte[] originatingCommitment); //identity.RootAttribute.OriginatingCommitment = originatingCommitment.ToHexString(); IEnumerable <(string attributeName, string content)> attrs = await GetAttribitesAndContent(identity, account).ConfigureAwait(false); Identity identityDb = _dataAccessService.CreateIdentity(account.AccountId, identity.Description, attrs.ToArray()); identity.Id = identityDb.IdentityId.ToString(CultureInfo.InvariantCulture); return(Ok(identity.Id)); }
async Task <IssuanceDetailsDto> IssueIdpAttributesAsRoot( string issuer, ConfidentialAccount confidentialAccount, Identity identity, IEnumerable <AttributeIssuanceDetails> attributeIssuanceDetails, AccountDescriptor account, StatePersistency statePersistency) { IssuanceDetailsDto issuanceDetails = new IssuanceDetailsDto(); IEnumerable <IdentitiesScheme> identitiesSchemes = _dataAccessService.GetAttributesSchemeByIssuer(issuer, true); var rootAttributeDetails = attributeIssuanceDetails.First(a => a.Definition.IsRoot); byte[] rootAssetId = await _assetsService.GenerateAssetId(rootAttributeDetails.Definition.SchemeName, rootAttributeDetails.Value.Value, issuer).ConfigureAwait(false); IdentityAttribute rootAttribute = identity.Attributes.FirstOrDefault(a => a.AttributeName == rootAttributeDetails.Definition.AttributeName); statePersistency.TransactionsService.IssueBlindedAsset(rootAssetId, 0UL.ToByteArray(32), out byte[] originatingCommitment); _dataAccessService.UpdateIdentityAttributeCommitment(rootAttribute.AttributeId, originatingCommitment); issuanceDetails.AssociatedAttributes = await IssueAssociatedAttributes( attributeIssuanceDetails.Where(a => !a.Definition.IsRoot) .ToDictionary(d => identity.Attributes.First(a => a.AttributeName == d.Definition.AttributeName).AttributeId, d => d), statePersistency.TransactionsService, issuer, rootAssetId).ConfigureAwait(false); var packet = statePersistency.TransactionsService.TransferAssetToUtxo(rootAssetId, confidentialAccount); if (packet == null) { _logger.Error($"[{account.AccountId}]: failed to transfer Root Attribute"); throw new RootAttributeTransferFailedException(); } issuanceDetails.RootAttribute = new IssuanceDetailsDto.IssuanceDetailsRoot { AttributeName = rootAttribute.AttributeName, OriginatingCommitment = packet.SurjectionProof.AssetCommitments[0].ToHexString(), AssetCommitment = packet.TransferredAsset.AssetCommitment.ToHexString(), SurjectionProof = $"{packet.SurjectionProof.Rs.E.ToHexString()}{packet.SurjectionProof.Rs.S[0].ToHexString()}" }; return(issuanceDetails); }
public void Initialize(IExecutionContextManager executionContextManager, CancellationToken cancellationToken) { _executionContextManager = executionContextManager; ConsentManagementSettings settings = _dataAccessService.GetConsentManagementSettings(); if (settings == null) { settings = CreateNewConsentManagementServiceAccount(); } AccountDescriptor accountDescriptor = _accountsService.Authenticate(settings.AccountId, GetDefaultConsentManagementPassword()); if (accountDescriptor == null) { settings = CreateNewConsentManagementServiceAccount(); accountDescriptor = _accountsService.Authenticate(settings.AccountId, GetDefaultConsentManagementPassword()); if (accountDescriptor == null) { throw new Exception("ConsentManagementService initialization failed"); } } _accountId = accountDescriptor.AccountId; _executionContextManager .InitializeUtxoExecutionServices( accountDescriptor.AccountId, accountDescriptor.SecretSpendKey, accountDescriptor.SecretViewKey, accountDescriptor.PwdHash, new Func <long, IUtxoClientCryptoService, CancellationToken, IUpdater>( (accountId, clientCryptoService, ct) => { _clientCryptoService = clientCryptoService; return(this); })); PublicSpendKey = accountDescriptor.PublicSpendKey.ToHexString(); PublicViewKey = accountDescriptor.PublicViewKey.ToHexString(); cancellationToken.Register(() => { _executionContextManager.UnregisterExecutionServices(_accountId); }); }
public IActionResult GetById(long accountId) { AccountDescriptor account = _accountsService.GetById(accountId); if (account == null) { return(BadRequest()); } var identityProvider = new IdentityProviderInfoDto { Id = account.AccountId.ToString(CultureInfo.InvariantCulture), Description = account.AccountInfo, Target = account.PublicSpendKey.ToHexString() }; return(Ok(identityProvider)); }
private AccountDescriptor AuthenticateUtxoAccount(AuthenticationInput authenticationInput) { AccountDescriptor accountDescriptor = null; Tuple <byte[], byte[]> keys = DecryptUtxoKeys(authenticationInput.Account, authenticationInput.Password); if (keys != null) { accountDescriptor = new AccountDescriptor { AccountType = authenticationInput.Account.AccountType, SecretSpendKey = keys.Item1, SecretViewKey = keys.Item2, PublicSpendKey = authenticationInput.Account.PublicSpendKey, PublicViewKey = authenticationInput.Account.PublicViewKey, AccountInfo = authenticationInput.Account.AccountInfo, AccountId = authenticationInput.Account.AccountId }; byte[] pwdBytes = Encoding.ASCII.GetBytes(authenticationInput.Password); byte[] pwdHash = ConfidentialAssetsHelper.FastHash256(pwdBytes); _executionContextManager.InitializeUtxoExecutionServices(authenticationInput.Account.AccountId, accountDescriptor.SecretSpendKey, accountDescriptor.SecretViewKey, pwdHash); } return(accountDescriptor); }
public Result Add(Amount amount, AccountDescriptor account, string description) { if (amount == null) { throw new ArgumentNullException("amount"); } if (account == null) { throw new ArgumentNullException("account"); } if (_wasPosted) { return(Result.Failure(KnownErrors.TransactionImmutable.ToString())); } _lines.Add(new JournalLine(amount, Date, account) { Description = description }); return(Result.Ok()); }
private void SetupServiceProviders(ScenarioDefinition scenarioDefinition, long scenarioSessionId) { foreach (var scenarioAccount in scenarioDefinition.Setup.Accounts.Where(a => a.AccountType == AccountType.ServiceProvider)) { long accountId = _accountsService.Create(AccountType.ServiceProvider, scenarioAccount.AccountInfo, "qqq", true); _dataAccessService.AddScenarionSessionAccount(scenarioSessionId, accountId); AccountDescriptor accountDescriptor = _accountsService.Authenticate(accountId, "qqq"); _executionContextManager.InitializeStateExecutionServices(accountId, accountDescriptor.SecretSpendKey); if (scenarioAccount.RelationGroups != null) { foreach (var scenarioRelationGroup in scenarioAccount.RelationGroups) { long groupId = _dataAccessService.AddSpEmployeeGroup(accountId, scenarioRelationGroup.GroupName); foreach (var scenarioRelation in scenarioRelationGroup.Relations) { _dataAccessService.AddSpEmployee(accountId, "", scenarioRelation.RootAttribute, groupId); } } } } }
public ActionResult <TranslationResponse> TranslateToAttributes(string issuerName, [FromBody] object json) { var provider = _dataAccessService.GetExternalIdentityProvider(issuerName); AccountDescriptor account = _accountsService.GetById(provider.AccountId); var validator = _externalIdpDataValidatorsRepository.GetInstance(issuerName); if (validator == null) { throw new Exception($"No validator found for {issuerName}"); } TranslationResponse response = new TranslationResponse { Issuer = account.PublicSpendKey.ToHexString(), ActionUri = $"{Request.Scheme}://{Request.Host}".AppendPathSegments("IdentityProvider", "IssueExternalIdpAttributes", account.PublicSpendKey.ToHexString()).ToString() }; string jsonString = json?.ToString(); switch (issuerName) { case "BlinkID-DrivingLicense": case "BlinkID-Passport": var request = JsonConvert.DeserializeObject <BlinkIdIdentityRequest>(jsonString); validator.Validate(request); var translator = _translatorsRepository.GetInstance <BlinkIdIdentityRequest, Dictionary <string, string> >(); var attributes = translator.Translate(request); response.Attributes = attributes; break; default: return(BadRequest("unknown issuer name")); } return(Ok(response)); }
public async Task <IActionResult> PushUserTransaction(long accountId, [FromBody] SpUserTransactionRequestDto spUserTransactionRequest) { AccountDescriptor account = _accountsService.GetById(accountId); string transactionId = Guid.NewGuid().ToString(); long registrationId = long.Parse(spUserTransactionRequest.RegistrationId); long userTransactionId = _dataAccessService.AddSpUserTransaction(accountId, registrationId, transactionId, spUserTransactionRequest.Description); var registration = _dataAccessService.GetServiceProviderRegistration(registrationId); TransactionConsentRequest consentRequest = new TransactionConsentRequest { RegistrationCommitment = registration.Commitment.ToHexString(), TransactionId = transactionId, WithKnowledgeProof = true, Description = spUserTransactionRequest.Description, PublicSpendKey = account.PublicSpendKey.ToHexString(), PublicViewKey = account.PublicViewKey?.ToHexString() }; await _restApiConfiguration.ConsentManagementUri .AppendPathSegments("ConsentManagement", "TransactionForConsent") .PostJsonAsync(consentRequest).ContinueWith(t => { if (!t.IsCompletedSuccessfully) { _logger.Error($"Failed to register transaction for consent. {JsonConvert.SerializeObject(consentRequest)}", t.Exception); } }, TaskScheduler.Current).ConfigureAwait(false); return(Ok(new SpUserTransactionDto { SpUserTransactionId = userTransactionId.ToString(), TransactionId = transactionId, RegistrationId = spUserTransactionRequest.RegistrationId.ToString(), Description = spUserTransactionRequest.Description })); }
internal JournalLine(Amount amount, DateTime date, AccountDescriptor accountDescriptor) { AccountDescriptor = accountDescriptor ?? throw new ArgumentNullException(nameof(accountDescriptor)); Amount = amount ?? throw new ArgumentNullException(nameof(amount)); Date = date; }
public void UpdateDescriptor(string code, string name) { AccountDescriptor = AccountDescriptor.As(AccountDescriptor.SourceId, code, name); }
private IEnumerable <(string attributeName, string content)> GetAttribitesAndContent(ScenarionIdentity identity, AccountDescriptor account) { IEnumerable <(string attributeName, string content)> attrs; IdentitiesScheme rootScheme = _dataAccessService.GetRootIdentityScheme(account.PublicSpendKey.ToHexString()); if (rootScheme != null) { string rootAttributeContent = identity.Attributes[rootScheme.AttributeName]; byte[] rootAssetId = _assetsService.GenerateAssetId(rootScheme.IdentitiesSchemeId, rootAttributeContent); if (identity.Attributes.ContainsKey(AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD)) { identity.Attributes[AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD] = rootAssetId.ToHexString(); } attrs = identity.Attributes.Select(a => (a.Key, a.Value)); if (!identity.Attributes.ContainsKey(AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD)) { attrs = attrs.Append((AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD, rootAssetId.ToHexString())); } } else { attrs = identity.Attributes.Select(a => (a.Key, a.Value)); } return(attrs); }
private async Task <IEnumerable <(string attributeName, string content)> > GetAttribitesAndContent(IdentityDto identity, AccountDescriptor account) { IEnumerable <(string attributeName, string content)> attrs; IdentitiesScheme rootScheme = _dataAccessService.GetRootIdentityScheme(account.PublicSpendKey.ToHexString()); if (rootScheme != null) { IdentityAttributeDto rootAttribute = identity.Attributes.FirstOrDefault(a => a.AttributeName == rootScheme.AttributeName); byte[] rootAssetId = await _assetsService.GenerateAssetId(rootScheme.AttributeSchemeName, rootAttribute.Content, account.PublicSpendKey.ToHexString()).ConfigureAwait(false); var protectionIdentityAttribute = identity.Attributes.FirstOrDefault(a => a.AttributeName == AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD); if (protectionIdentityAttribute != null) { protectionIdentityAttribute.Content = rootAssetId.ToHexString(); } attrs = identity.Attributes.Select(a => (a.AttributeName, a.Content)); if (protectionIdentityAttribute == null) { attrs = attrs.Append((AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD, rootAssetId.ToHexString())); } } else { attrs = identity.Attributes.Select(a => (a.AttributeName, a.Content)); } return(attrs); }
public async Task <IActionResult> GetIdentityAttributeValidationDescriptors(long accountId) { AccountDescriptor account = _accountsService.GetById(accountId); return(Ok(await _identityAttributesService.GetIdentityAttributeValidationDescriptors(account.PublicSpendKey.ToHexString(), true).ConfigureAwait(false))); }
public IActionResult GetActionInfo([FromQuery(Name = "t")] int actionType, [FromQuery(Name = "pk")] string publicKey, [FromQuery(Name = "sk")] string sessionKey, [FromQuery(Name = "rk")] string registrationKey) { AccountDescriptor spAccount = _accountsService.GetByPublicKey(publicKey.HexStringToByteArray()); bool isRegistered = false; string extraInfo = null; List <string> validations = new List <string>(); string[] details = Array.Empty <string>(); // Onboarding & Login if (actionType == 0) { ServiceProviderRegistration serviceProviderRegistration = _dataAccessService.GetServiceProviderRegistration(spAccount.AccountId, registrationKey.HexStringToByteArray()); ; isRegistered = serviceProviderRegistration != null; } // Employee registration else if (actionType == 1) { List <SpEmployee> spEmployees = _dataAccessService.GetSpEmployees(spAccount.AccountId, registrationKey.DecodeFromString64()); extraInfo = ""; foreach (SpEmployee spEmployee in spEmployees) { if (!string.IsNullOrEmpty(extraInfo)) { extraInfo += "/"; } extraInfo += $"{spAccount.AccountInfo}|{spEmployee?.SpEmployeeGroup?.GroupName}|{!string.IsNullOrEmpty(spEmployee.RegistrationCommitment)}"; } isRegistered = spEmployees.Count > 0; } // Document sign else if (actionType == 2) { SignedDocumentEntity spDocument = _dataAccessService.GetSpDocument(spAccount.AccountId, registrationKey); if (spDocument != null) { isRegistered = true; extraInfo = $"{spDocument.DocumentName}|{spDocument.Hash}|{spDocument.LastChangeRecordHeight}"; foreach (var allowedSigner in spDocument.AllowedSigners) { validations.Add($"{allowedSigner.GroupIssuer};{allowedSigner.GroupName}"); } } } bool isBiometryRequired = false; if (actionType == 0 || actionType == 1) { IEnumerable <SpIdenitityValidation> spIdenitityValidations = _dataAccessService.GetSpIdenitityValidations(spAccount.AccountId); if (spIdenitityValidations != null && spIdenitityValidations.Count() > 0) { //IEnumerable<Tuple<AttributeType, string>> attributeDescriptions = _identityAttributesService.GetAssociatedAttributeTypes(); //IEnumerable<Tuple<ValidationType, string>> validationDescriptions = _identityAttributesService.GetAssociatedValidationTypes(); foreach (SpIdenitityValidation spIdenitityValidation in spIdenitityValidations) { if (!AttributesSchemes.ATTR_SCHEME_NAME_PASSPORTPHOTO.Equals(spIdenitityValidation.SchemeName)) { validations.Add($"{spIdenitityValidation.SchemeName}:{spIdenitityValidation.ValidationType}"); } else { isBiometryRequired = true; } // if (spIdenitityValidation.AttributeType != AttributeType.DateOfBirth) //{ // validityInfo.Add(attributeDescriptions.FirstOrDefault(d => d.Item1 == spIdenitityValidation.AttributeType)?.Item2 ?? spIdenitityValidation.AttributeType.ToString()); // } // else //{ // validityInfo.Add(validationDescriptions.FirstOrDefault(d => d.Item1 == spIdenitityValidation.ValidationType)?.Item2 ?? spIdenitityValidation.ValidationType.ToString()); //} } } } ServiceProviderActionAndValidationsDto serviceProviderActionAndValidations = new ServiceProviderActionAndValidationsDto { SpInfo = spAccount.AccountInfo, IsRegistered = isRegistered, PublicKey = publicKey, SessionKey = sessionKey, ExtraInfo = extraInfo, IsBiometryRequired = isBiometryRequired, Validations = validations }; return(Ok(serviceProviderActionAndValidations)); }
public ITransactionLineBuilder WithAccount(AccountDescriptor descriptor) { _accountDescriptor = descriptor; return(this); }
public async Task <ActionResult <IEnumerable <AttributeValue> > > IssueIdpAttributes(string issuer, [FromBody] IssueAttributesRequestDTO request) { if (request is null) { throw new ArgumentNullException(nameof(request)); } AccountDescriptor account = _accountsService.GetByPublicKey(issuer.HexStringToByteArray()); StatePersistency statePersistency = _executionContextManager.ResolveStateExecutionServices(account.AccountId); IEnumerable <AttributeDefinition> attributeDefinitions = _dataAccessService.GetAttributesSchemeByIssuer(issuer, true) .Select(a => new AttributeDefinition { SchemeId = a.IdentitiesSchemeId, AttributeName = a.AttributeName, SchemeName = a.AttributeSchemeName, Alias = a.Alias, Description = a.Description, IsActive = a.IsActive, IsRoot = a.CanBeRoot }); if (!attributeDefinitions.Any(a => a.IsRoot)) { throw new NoRootAttributeSchemeDefinedException(issuer); } var issuanceInputDetails = GetValidatedIssuanceDetails(request, attributeDefinitions); Identity identity = CreateIdentityInDb(account, issuanceInputDetails); IssuanceDetailsDto issuanceDetails; if (!string.IsNullOrEmpty(request.PublicSpendKey) && !string.IsNullOrEmpty(request.PublicViewKey)) { ConfidentialAccount targetAccount = new ConfidentialAccount { PublicSpendKey = request.PublicSpendKey.HexStringToByteArray(), PublicViewKey = request.PublicViewKey.HexStringToByteArray() }; issuanceDetails = await IssueIdpAttributesAsRoot(issuer, request.Protection, identity, issuanceInputDetails, account, targetAccount, statePersistency).ConfigureAwait(false); } else { issuanceDetails = await IssueIdpAttributesAsAssociated(issuer, identity, issuanceInputDetails, statePersistency).ConfigureAwait(false); } await _idenitiesHubContext.Clients.Group(account.AccountId.ToString()).SendAsync("RequestForIssuance", issuanceDetails); IIntegrationIdP integrationService = GetIntegrationService(account.AccountId); if (integrationService != null) { IssuanceDetails issuanceIntegration = new IssuanceDetails { RootAttribute = new IssuanceDetails.IssuanceDetailsRoot { AttributeName = issuanceDetails.RootAttribute.AttributeName, AssetCommitment = issuanceDetails.RootAttribute.AssetCommitment.HexStringToByteArray(), OriginatingCommitment = issuanceDetails.RootAttribute.OriginatingCommitment.HexStringToByteArray(), SurjectionProof = issuanceDetails.RootAttribute.SurjectionProof.HexStringToByteArray() }, AssociatedAttributes = issuanceDetails.AssociatedAttributes .Select(a => new IssuanceDetails.IssuanceDetailsAssociated { AttributeName = a.AttributeName, AssetCommitment = a.AssetCommitment.HexStringToByteArray(), BindingToRootCommitment = a.BindingToRootCommitment.HexStringToByteArray() }).ToList() }; integrationService.IssueAttributes(account.AccountId, issuanceIntegration); } var attributeValues = FillAttributeValues(request.Attributes, attributeDefinitions); return(Ok(attributeValues)); #region Internal Functions IReadOnlyCollection <AttributeValue> FillAttributeValues(Dictionary <string, IssueAttributesRequestDTO.AttributeValue> attributes, IEnumerable <AttributeDefinition> attributeDefinitions) { List <AttributeValue> attributeValues = new List <AttributeValue>(); var protectionAttrDefinition = attributeDefinitions.FirstOrDefault(a => a.SchemeName == AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD); foreach (var attributeName in attributes.Keys.Where(a => protectionAttrDefinition?.AttributeName != a)) { string content = attributes[attributeName].Value; AttributeValue attributeValue = new AttributeValue { Value = content, Definition = attributeDefinitions.FirstOrDefault(d => d.AttributeName == attributeName) }; attributeValues.Add(attributeValue); } return(new ReadOnlyCollection <AttributeValue>(attributeValues)); } async Task <IssuanceDetailsDto> IssueIdpAttributesAsRoot( string issuer, IssuanceProtection protection, Identity identity, IEnumerable <AttributeIssuanceDetails> attributeIssuanceDetails, AccountDescriptor account, ConfidentialAccount targetAccount, StatePersistency statePersistency) { IssuanceDetailsDto issuanceDetails = new IssuanceDetailsDto(); IEnumerable <IdentitiesScheme> identitiesSchemes = _dataAccessService.GetAttributesSchemeByIssuer(issuer, true); var rootAttributeDetails = attributeIssuanceDetails.First(a => a.Definition.IsRoot); byte[] rootAssetId = await _assetsService.GenerateAssetId(rootAttributeDetails.Definition.SchemeName, rootAttributeDetails.Value.Value, issuer).ConfigureAwait(false); IdentityAttribute rootAttribute = identity.Attributes.FirstOrDefault(a => a.AttributeName == rootAttributeDetails.Definition.AttributeName); if (!CreateRootAttributeIfNeeded(statePersistency, rootAttribute, rootAssetId)) { var protectionAttribute = identity.Attributes.FirstOrDefault(a => a.AttributeName == AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD); bool res = VerifyProtectionAttribute(protectionAttribute, protection.SignatureE.HexStringToByteArray(), protection.SignatureS.HexStringToByteArray(), protection.SessionCommitment.HexStringToByteArray()); if (!res) { _logger.Warning($"[{account.AccountId}]: Failed to verify Surjection Proofs of the Protection Attribute"); throw new ProtectionAttributeVerificationFailedException(); } } else { issuanceDetails.AssociatedAttributes = await IssueAssociatedAttributes( attributeIssuanceDetails.Where(a => !a.Definition.IsRoot) .ToDictionary(d => identity.Attributes.First(a => a.AttributeName == d.Definition.AttributeName).AttributeId, d => d), statePersistency.TransactionsService, issuer, rootAssetId).ConfigureAwait(false); } var packet = TransferAssetToUtxo(statePersistency.TransactionsService, targetAccount, rootAssetId); if (packet == null) { _logger.Error($"[{account.AccountId}]: failed to transfer Root Attribute"); throw new RootAttributeTransferFailedException(); } _dataAccessService.AddOrUpdateIdentityTarget(identity.IdentityId, targetAccount.PublicSpendKey.ToHexString(), targetAccount.PublicViewKey.ToHexString()); issuanceDetails.RootAttribute = new IssuanceDetailsDto.IssuanceDetailsRoot { AttributeName = rootAttribute.AttributeName, OriginatingCommitment = packet.SurjectionProof.AssetCommitments[0].ToHexString(), AssetCommitment = packet.TransferredAsset.AssetCommitment.ToHexString(), SurjectionProof = $"{packet.SurjectionProof.Rs.E.ToHexString()}{packet.SurjectionProof.Rs.S[0].ToHexString()}" }; return(issuanceDetails); } async Task <IssuanceDetailsDto> IssueIdpAttributesAsAssociated( string issuer, Identity identity, IEnumerable <AttributeIssuanceDetails> attributeIssuanceDetails, StatePersistency statePersistency) { IssuanceDetailsDto issuanceDetails = new IssuanceDetailsDto(); IdentitiesScheme rootScheme = _dataAccessService.GetRootIdentityScheme(issuer); IEnumerable <IdentitiesScheme> identitiesSchemes = _dataAccessService.GetAttributesSchemeByIssuer(issuer, true); var rootAttributeDetails = attributeIssuanceDetails.First(a => a.Definition.IsRoot); var packet = await IssueAssociatedAttribute( rootScheme.AttributeSchemeName, rootAttributeDetails.Value.Value, rootAttributeDetails.Value.BlindingPointValue, rootAttributeDetails.Value.BlindingPointRoot, issuer, statePersistency.TransactionsService).ConfigureAwait(false); _dataAccessService.UpdateIdentityAttributeCommitment(identity.Attributes.FirstOrDefault(a => a.AttributeName == rootScheme.AttributeName).AttributeId, packet.AssetCommitment); byte[] rootAssetId = _assetsService.GenerateAssetId(rootScheme.IdentitiesSchemeId, rootAttributeDetails.Value.Value); issuanceDetails.AssociatedAttributes = await IssueAssociatedAttributes( attributeIssuanceDetails .ToDictionary(d => identity.Attributes.First(a => a.AttributeName == d.Definition.AttributeName).AttributeId, d => d), statePersistency.TransactionsService, issuer, rootAssetId).ConfigureAwait(false); return(issuanceDetails); }