Exemplo n.º 1
0
        private async Task <IssueAssociatedBlindedAsset> IssueAssociatedAttribute(string schemeName,
                                                                                  string content,
                                                                                  byte[] blindingPointValue,
                                                                                  byte[] blindingPointRoot,
                                                                                  string issuer,
                                                                                  IStateTransactionsService transactionsService)
        {
            byte[] assetId = await _assetsService.GenerateAssetId(schemeName, content, issuer).ConfigureAwait(false);

            byte[] groupId;

            if (AttributesSchemes.AttributeSchemes.FirstOrDefault(a => a.Name == schemeName)?.ValueType == AttributeValueType.Date)
            {
                groupId = await _identityAttributesService.GetGroupId(schemeName, DateTime.ParseExact(content, "yyyy-MM-dd", null), issuer).ConfigureAwait(false);
            }
            else
            {
                groupId = schemeName switch
                {
                    AttributesSchemes.ATTR_SCHEME_NAME_PLACEOFBIRTH => await _identityAttributesService.GetGroupId(schemeName, content, issuer).ConfigureAwait(false),
                    _ => await _identityAttributesService.GetGroupId(schemeName, issuer).ConfigureAwait(false),
                };
            }

            return(transactionsService.IssueAssociatedAsset(assetId, groupId, blindingPointValue, blindingPointRoot, out byte[] originatingCommitment));
        }
Exemplo n.º 2
0
        public ServiceProviderUpdater(ulong accountId, IStateClientCryptoService clientCryptoService, IAssetsService assetsService, IDataAccessService dataAccessService, IIdentityAttributesService identityAttributesService, IBlockParsersRepositoriesRepository blockParsersRepositoriesRepository, IGatewayService gatewayService, IStateTransactionsService transactionsService, IHubContext <IdentitiesHub> idenitiesHubContext, IAppConfig appConfig, ILoggerService loggerService)
        {
            _accountId                          = accountId;
            _clientCryptoService                = clientCryptoService;
            _assetsService                      = assetsService;
            _dataAccessService                  = dataAccessService;
            _identityAttributesService          = identityAttributesService;
            _blockParsersRepositoriesRepository = blockParsersRepositoriesRepository;
            _gatewayService                     = gatewayService;
            _transactionsService                = transactionsService;
            _idenitiesHubContext                = idenitiesHubContext;
            _appConfig                          = appConfig;
            _logger = loggerService.GetLogger(nameof(ServiceProviderUpdater));

            PipeIn = new ActionBlock <PacketBase>(p =>
            {
                if (p is DocumentSignRecord documentSignRecord)
                {
                    ProcessDocumentSignRecord(documentSignRecord);
                }

                if (p is DocumentRecord documentRecord)
                {
                    ProcessDocumentRecord(documentRecord);
                }

                if (p is DocumentSignRequest documentSignRequest)
                {
                    ProcessDocumentSignRequest(documentSignRequest);
                }

                if (p is EmployeeRegistrationRequest employeeRegistrationRequest)
                {
                    ProcessEmployeeRegistrationRequest(employeeRegistrationRequest);
                }

                if (p is OnboardingRequest packet)
                {
                    ProcessOnboarding(packet);
                }

                if (p is TransitionAuthenticationProofs transitionAuthentication)
                {
                    ProcessAuthentication(transitionAuthentication);
                }

                if (p is TransitionCompromisedProofs compromisedProofs)
                {
                    ProcessCompromisedProofs(compromisedProofs);
                }

                if (p is TransferAsset transferAsset)
                {
                    ProcessTransferAsset(transferAsset);
                }
            });
        }
Exemplo n.º 3
0
        private IActionResult TransferAssetToUtxo(IStateTransactionsService transactionsService, ConfidentialAccount account, byte[] rootAssetId)
        {
            try
            {
                bool sent = transactionsService.TransferAssetToUtxo(rootAssetId, account);

                if (sent)
                {
                    return(Ok());
                }
                else
                {
                    throw new Exception("Sending failed");
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(new { ex.Message }));
            }
        }
Exemplo n.º 4
0
        public void InitializeStateExecutionServices(ulong accountId, byte[] secretKey)
        {
            if (_statePersistencyItems.ContainsKey(accountId))
            {
                return;
            }

            IPacketsProvider          packetsProvider     = ServiceLocator.Current.GetInstance <IPacketsProvider>();
            IStateTransactionsService transactionsService = ServiceLocator.Current.GetInstance <StateTransactionsService>();
            IStateClientCryptoService clientCryptoService = ServiceLocator.Current.GetInstance <StateClientCryptoService>();
            IWalletSynchronizer       walletSynchronizer  = ServiceLocator.Current.GetInstance <StateWalletSynchronizer>();

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

            packetsProvider.Initialize(accountId, cancellationTokenSource.Token);
            clientCryptoService.Initialize(secretKey);
            transactionsService.Initialize(clientCryptoService, _gatewayService.GetLastBlockHeight(ConfidentialAssetsHelper.GetPublicKey(secretKey)));
            transactionsService.PipeOutTransactions.LinkTo(_gatewayService.PipeInTransactions);

            ServiceProviderUpdater updater = new ServiceProviderUpdater(accountId, clientCryptoService, _assetsService, _dataAccessService, _identityAttributesService, _blockParsersRepositoriesRepository, _gatewayService, transactionsService, _identitiesHubContext, _appConfig, _loggerService);

            walletSynchronizer.Initialize(accountId, clientCryptoService, _gatewayService, cancellationTokenSource.Token);

            packetsProvider.PipeOut.LinkTo(walletSynchronizer.PipeIn);
            walletSynchronizer.PipeOut.LinkTo(updater.PipeIn);

            walletSynchronizer.Start();
            packetsProvider.Start();

            var state = new StatePersistency
            {
                AccountId               = accountId,
                PacketsProvider         = packetsProvider,
                TransactionsService     = transactionsService,
                ClientCryptoService     = clientCryptoService,
                WalletSynchronizer      = walletSynchronizer,
                CancellationTokenSource = cancellationTokenSource
            };

            _statePersistencyItems.Add(accountId, state);
        }
Exemplo n.º 5
0
        private void ProcessIssuingAssociatedAttribute(IdentityAttribute identityAttribute, byte[] blindingPoint, byte[] rootAssetId, IStateTransactionsService transactionsService)
        {
            byte[] assetId = _assetsService.GenerateAssetId(identityAttribute.AttributeType, identityAttribute.Content);
            byte[] groupId = null;
            switch (identityAttribute.AttributeType)
            {
            case AttributeType.PlaceOfBirth:
                groupId = _identityAttributesService.GetGroupId(identityAttribute.AttributeType, identityAttribute.Content);
                break;

            case AttributeType.DateOfBirth:
                groupId = _identityAttributesService.GetGroupId(identityAttribute.AttributeType, DateTime.ParseExact(identityAttribute.Content, "yyyy-MM-dd", null));
                break;

            default:
                groupId = _identityAttributesService.GetGroupId(identityAttribute.AttributeType);
                break;
            }

            transactionsService.IssueAssociatedAsset(assetId, groupId, blindingPoint, rootAssetId, out byte[] originatingCommitment);

            _externalDataAccessService.UpdateAssociatedIdentityAttributeCommitment(identityAttribute.AttributeId, originatingCommitment);
        }
Exemplo n.º 6
0
        private void ProcessIssuingAssociatedAttributes(IdentityRequestDto identityRequest, IStateTransactionsService transactionsService, byte[] rootAssetId, byte[] faceImage)
        {
            byte[]   blindingPoint = identityRequest.BlindingPoint.HexStringToByteArray();
            Identity identity      = _externalDataAccessService.GetIdentityByRootAttribute(identityRequest.RootAttributeContent);

            if (identity != null)
            {
                foreach (var identityAttribute in identity.AssociatedAttributes)
                {
                    ProcessIssuingAssociatedAttribute(identityAttribute, blindingPoint, rootAssetId, transactionsService);
                }
            }
        }
Exemplo n.º 7
0
        public ServiceProviderUpdater(long accountId,
                                      IStateClientCryptoService clientCryptoService,
                                      IAssetsService assetsService,
                                      ISchemeResolverService schemeResolverService,
                                      IDataAccessService dataAccessService,
                                      IIdentityAttributesService identityAttributesService,
                                      IBlockParsersRepositoriesRepository blockParsersRepositoriesRepository,
                                      IGatewayService gatewayService,
                                      IStateTransactionsService transactionsService,
                                      ISpValidationsService spValidationsService,
                                      IHubContext <IdentitiesHub> idenitiesHubContext,
                                      ILoggerService loggerService,
                                      IConsentManagementService consentManagementService,
                                      IUniversalProofsPool universalProofsPool,
                                      CancellationToken cancellationToken)
        {
            _accountId                          = accountId;
            _clientCryptoService                = clientCryptoService;
            _assetsService                      = assetsService;
            _schemeResolverService              = schemeResolverService;
            _dataAccessService                  = dataAccessService;
            _identityAttributesService          = identityAttributesService;
            _blockParsersRepositoriesRepository = blockParsersRepositoriesRepository;
            _gatewayService                     = gatewayService;
            _transactionsService                = transactionsService;
            _spValidationsService               = spValidationsService;
            _idenitiesHubContext                = idenitiesHubContext;
            _consentManagementService           = consentManagementService;
            _universalProofsPool                = universalProofsPool;
            _cancellationToken                  = cancellationToken;
            _logger = loggerService.GetLogger(nameof(ServiceProviderUpdater));

            _cancellationToken.Register(() =>
            {
                PipeIn?.Complete();
                PipInNotifications?.Complete();
            });

            PipeIn = new ActionBlock <PacketBase>(async p =>
            {
                if (p == null)
                {
                    _logger.Error($"[{_accountId}]: Obtained NULL packet");
                    return;
                }

                _logger.Info($"[{_accountId}]: Obtained {p.GetType().Name} packet");

                try
                {
                    if (p is DocumentSignRecord documentSignRecord)
                    {
                        ProcessDocumentSignRecord(documentSignRecord);
                    }

                    if (p is DocumentRecord documentRecord)
                    {
                        ProcessDocumentRecord(documentRecord);
                    }

                    if (p is DocumentSignRequest documentSignRequest)
                    {
                        ProcessDocumentSignRequest(documentSignRequest);
                    }

                    if (p is EmployeeRegistrationRequest employeeRegistrationRequest)
                    {
                        ProcessEmployeeRegistrationRequest(employeeRegistrationRequest);
                    }

                    if (p is IdentityProofs packet)
                    {
                        await ProcessIdentityProofs(packet).ConfigureAwait(false);
                    }

                    if (p is TransitionCompromisedProofs compromisedProofs)
                    {
                        ProcessCompromisedProofs(new Key32(compromisedProofs.CompromisedKeyImage));
                    }

                    if (p is TransferAsset transferAsset)
                    {
                        ProcessTransferAsset(transferAsset);
                    }

                    if (p is UniversalTransport universalTransport)
                    {
                        await ProcessUniversalTransport(universalTransport).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error($"[{_accountId}]: Failed to process packet {p.GetType().Name}", ex);
                }
            });
        }
Exemplo n.º 8
0
        public void InitializeStateExecutionServices(long accountId, byte[] secretKey, Func <long, IStateTransactionsService, IStateClientCryptoService, CancellationToken, IUpdater> updaterFactory = null)
        {
            lock (_statePersistencyItems)
            {
                if (_statePersistencyItems.ContainsKey(accountId))
                {
                    _logger.Info($"[{accountId}]: Account with id {accountId} already registered at StatePersistency");
                    return;
                }

                _logger.Info($"[{accountId}]: {nameof(InitializeStateExecutionServices)} for account with id {accountId}");

                try
                {
                    IWitnessPackagesProvider  packetsProvider       = _witnessPackagesProviderRepository.GetInstance(_restApiConfiguration.WitnessProviderName);
                    IStateTransactionsService transactionsService   = ActivatorUtilities.CreateInstance <StateTransactionsService>(_serviceProvider);
                    IStateClientCryptoService clientCryptoService   = ActivatorUtilities.CreateInstance <StateClientCryptoService>(_serviceProvider);
                    IWalletSynchronizer       walletSynchronizer    = ActivatorUtilities.CreateInstance <StateWalletSynchronizer>(_serviceProvider);
                    StatePacketsExtractor     statePacketsExtractor = ActivatorUtilities.CreateInstance <StatePacketsExtractor>(_serviceProvider);

                    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                    packetsProvider.Initialize(accountId, cancellationTokenSource.Token);
                    clientCryptoService.Initialize(secretKey);
                    transactionsService.AccountId = accountId;
                    ulong lastBlockHeight = AsyncUtil.RunSync(() => _gatewayService.GetLastBlockHeight(ConfidentialAssetsHelper.GetPublicKey(Ed25519.SecretKeyFromSeed(secretKey))));
                    transactionsService.Initialize(clientCryptoService, lastBlockHeight);
                    transactionsService.PipeOutTransactions.LinkTo(_gatewayService.PipeInTransactions);
                    statePacketsExtractor.Initialize(clientCryptoService);
                    statePacketsExtractor.AccountId = accountId;

                    IUpdater updater = updaterFactory != null?updaterFactory(accountId, transactionsService, clientCryptoService, cancellationTokenSource.Token) : CreateStateUpdater(accountId, transactionsService, clientCryptoService, cancellationTokenSource.Token);

                    walletSynchronizer.Initialize(accountId, clientCryptoService);

                    packetsProvider.PipeOut.LinkTo(statePacketsExtractor.PipeIn);
                    statePacketsExtractor.PipeOutPackets.LinkTo(walletSynchronizer.PipeInPackets);
                    statePacketsExtractor.PipeOutProcessed.LinkTo(walletSynchronizer.PipeInPackage);

                    foreach (var externalUpdater in _externalUpdatersRepository.GetInstances())
                    {
                        externalUpdater.Initialize(accountId);
                    }

                    walletSynchronizer.PipeOutPackets.LinkTo(
                        new ActionBlock <PacketBase>(async p =>
                    {
                        var tasks = new List <Task>
                        {
                            updater.PipeIn.SendAsync(p)
                        };

                        foreach (var externalUpdater in _externalUpdatersRepository.GetInstances())
                        {
                            tasks.Add(externalUpdater.PipeIn.SendAsync(p));
                        }

                        await Task.WhenAll(tasks).ConfigureAwait(false);
                    }));

                    packetsProvider.Start();

                    var state = new StatePersistency
                    {
                        AccountId               = accountId,
                        PacketsProvider         = packetsProvider,
                        TransactionsService     = transactionsService,
                        PacketsExtractor        = statePacketsExtractor,
                        ClientCryptoService     = clientCryptoService,
                        WalletSynchronizer      = walletSynchronizer,
                        CancellationTokenSource = cancellationTokenSource
                    };

                    _statePersistencyItems.Add(accountId, state);
                }
                catch (Exception ex)
                {
                    _logger.Error($"[{accountId}]: Failure during {nameof(InitializeStateExecutionServices)} for account with id {accountId}", ex);
                    throw;
                }
            }
        }
Exemplo n.º 9
0
 private IUpdater CreateStateUpdater(long accountId, IStateTransactionsService transactionsService, IStateClientCryptoService clientCryptoService,
                                     CancellationToken cancellationToken)
 => new ServiceProviderUpdater(accountId, clientCryptoService, _assetsService, _schemeResolverService, _dataAccessService, _identityAttributesService,
                               _blockParsersRepositoriesRepository, _gatewayService, transactionsService, _spValidationsService,
                               _identitiesHubContext, _loggerService, _consentManagementService, _universalProofsPool, _serviceProvider.GetService <IElectionCommitteeService>(), cancellationToken);
Exemplo n.º 10
0
        private async Task <IEnumerable <IssuanceDetailsDto.IssuanceDetailsAssociated> > IssueAssociatedAttributes(Dictionary <long, AttributeIssuanceDetails> attributes, IStateTransactionsService transactionsService, string issuer, byte[] rootAssetId = null)
        {
            List <IssuanceDetailsDto.IssuanceDetailsAssociated> issuanceDetails = new List <IssuanceDetailsDto.IssuanceDetailsAssociated>();

            if (attributes.Any(kv => kv.Value.Definition.IsRoot))
            {
                var rootKv = attributes.FirstOrDefault(kv => kv.Value.Definition.IsRoot);
                var packet = await IssueAssociatedAttribute(rootKv.Value.Definition.SchemeName, rootKv.Value.Value.Value, rootKv.Value.Value.BlindingPointValue, rootKv.Value.Value.BlindingPointRoot, issuer, transactionsService).ConfigureAwait(false);

                _dataAccessService.UpdateIdentityAttributeCommitment(rootKv.Key, packet.AssetCommitment);
                issuanceDetails.Add(new IssuanceDetailsDto.IssuanceDetailsAssociated
                {
                    AttributeName           = rootKv.Value.Definition.AttributeName,
                    AssetCommitment         = packet.AssetCommitment.ToHexString(),
                    BindingToRootCommitment = packet.RootAssetCommitment.ToHexString()
                });
                rootAssetId = _assetsService.GenerateAssetId(rootKv.Value.Definition.SchemeId, rootKv.Value.Value.Value);
            }

            if (rootAssetId == null)
            {
                throw new ArgumentException("Either rootAssetId must be provided outside or one of attributes must be root one");
            }

            foreach (var kv in attributes.Where(a => !a.Value.Definition.IsRoot))
            {
                byte[] rootCommitment = _assetsService.GetCommitmentBlindedByPoint(rootAssetId, kv.Value.Value.BlindingPointRoot);

                var packet = await IssueAssociatedAttribute(kv.Value.Definition.SchemeName, kv.Value.Value.Value, kv.Value.Value.BlindingPointValue, rootCommitment, issuer, transactionsService).ConfigureAwait(false);

                issuanceDetails.Add(new IssuanceDetailsDto.IssuanceDetailsAssociated
                {
                    AttributeName           = kv.Value.Definition.AttributeName,
                    AssetCommitment         = packet.AssetCommitment.ToHexString(),
                    BindingToRootCommitment = packet.RootAssetCommitment.ToHexString()
                });
                _dataAccessService.UpdateIdentityAttributeCommitment(kv.Key, packet.AssetCommitment);
            }

            return(issuanceDetails);
        }