public IEnumerable <PollResult> CalculateResults(long pollId) { var poll = _dataAccessService.GetEcPoll(pollId, true, true); Dictionary <byte[], PollResult> votes = new Dictionary <byte[], PollResult>(new Byte32EqualityComparer()); foreach (var candidate in poll.Candidates) { byte[] assetId = candidate.AssetId.HexStringToByteArray(); byte[] commitment = ConfidentialAssetsHelper.GetNonblindedAssetCommitment(assetId); votes.Add(commitment, new PollResult { Candidate = _translatorsRepository.GetInstance <EcCandidateRecord, Candidate>().Translate(candidate), Votes = 0 }); } foreach (var vote in poll.PollSelections.Where(s => !string.IsNullOrEmpty(s.VoterBlindingFactor))) { byte[] ecCommitment = vote.EcCommitment.HexStringToByteArray(); byte[] ecBf = vote.EcBlindingFactor.HexStringToByteArray(); byte[] voterBf = vote.VoterBlindingFactor.HexStringToByteArray(); byte[] bf = ConfidentialAssetsHelper.SumScalars(ecBf, voterBf); byte[] blindingPoint = ConfidentialAssetsHelper.GetPublicKey(bf); byte[] commitment = ConfidentialAssetsHelper.SubCommitments(ecCommitment, blindingPoint); if (votes.ContainsKey(commitment)) { votes[commitment].Votes++; } } return(votes.Select(d => d.Value)); }
public IActionResult RequestForIdentity([FromBody] RequestForIdentityDto requestForIdentity) { ulong accountId = ulong.Parse(User.Identity.Name, CultureInfo.InvariantCulture); Account account = _accountsService.GetById(accountId); string blindingFactorSeedString = $"{requestForIdentity.IdCardContent}{requestForIdentity.Password}"; byte[] blindingFactorSeed = ConfidentialAssetsHelper.FastHash256(Encoding.ASCII.GetBytes(blindingFactorSeedString)); byte[] blindingFactor = ConfidentialAssetsHelper.ReduceScalar32(blindingFactorSeed); byte[] blindingPoint = ConfidentialAssetsHelper.GetPublicKey(blindingFactor); IdentityRequestDto identityRequest = new IdentityRequestDto { RequesterPublicSpendKey = account.PublicSpendKey.ToHexString(), RequesterPublicViewKey = account.PublicViewKey.ToHexString(), RootAttributeContent = requestForIdentity.IdCardContent, BlindingPoint = blindingPoint.ToHexString(), FaceImageContent = requestForIdentity.ImageContent }; byte[] b = Convert.FromBase64String(requestForIdentity.Target); string uri = Encoding.UTF8.GetString(b); HttpResponseMessage httpResponse = uri.PostJsonAsync(identityRequest).Result; if (httpResponse.IsSuccessStatusCode) { //TODO: this step should be done if Identity Provider API returned OK _dataAccessService.UpdateUserAssociatedAttributes(accountId, new List <Tuple <AttributeType, string> > { new Tuple <AttributeType, string>(AttributeType.PassportPhoto, requestForIdentity.ImageContent) }); return(Ok()); } return(BadRequest(httpResponse.Content.ReadAsAsync <string>().Result)); }
private ulong StoreEncryptedAccount(AccountType accountType, string accountInfo, string passphrase) { byte[] secretSpendKey = ConfidentialAssetsHelper.GetRandomSeed(); byte[] secretViewKey = (accountType == AccountType.User) ? ConfidentialAssetsHelper.GetRandomSeed() : null; byte[] publicSpendKey = (accountType == AccountType.User) ? ConfidentialAssetsHelper.GetPublicKey(secretSpendKey) : ConfidentialAssetsHelper.GetPublicKey(Ed25519.SecretKeyFromSeed(secretSpendKey)); byte[] publicViewKey = (accountType == AccountType.User) ? ConfidentialAssetsHelper.GetPublicKey(secretViewKey) : null; byte[] secretSpendKeyEnc = null; byte[] secretViewKeyEnc = null; using (var aes = Aes.Create()) { aes.IV = _dataAccessService.GetAesInitializationVector(); byte[] passphraseBytes = Encoding.ASCII.GetBytes(passphrase); aes.Key = SHA256.Create().ComputeHash(passphraseBytes); aes.Padding = PaddingMode.None; secretSpendKeyEnc = aes.CreateEncryptor().TransformFinalBlock(secretSpendKey, 0, secretSpendKey.Length); if (accountType == AccountType.User) { secretViewKeyEnc = aes.CreateEncryptor().TransformFinalBlock(secretViewKey, 0, secretViewKey.Length); } else { secretViewKeyEnc = null; } } ulong accountId = _dataAccessService.AddAccount((byte)accountType, accountInfo, secretSpendKeyEnc, secretViewKeyEnc, publicSpendKey, publicViewKey, _gatewayService.GetLastRegistryCombinedBlock().Height); return(accountId); }
public IActionResult SendOnboardingWithValidationsRequest([FromBody] UserAttributeTransferWithValidationsDto userAttributeTransferWithValidations) { ulong accountId = ulong.Parse(User.Identity.Name, CultureInfo.InvariantCulture); bool res = false; UtxoPersistency utxoPersistency = _executionContextManager.ResolveUtxoExecutionServices(accountId); var rootAttribute = _dataAccessService.GetUserAttributes(accountId).FirstOrDefault(u => !u.IsOverriden && u.AttributeType == _identityAttributesService.GetRootAttributeType().Item1); string blindingFactorSeedString = $"{rootAttribute.Content}{userAttributeTransferWithValidations.Password}"; byte[] blindingFactorSeed = ConfidentialAssetsHelper.FastHash256(Encoding.ASCII.GetBytes(blindingFactorSeedString)); byte[] blindingFactor = ConfidentialAssetsHelper.ReduceScalar32(blindingFactorSeed); byte[] blindingPoint = ConfidentialAssetsHelper.GetPublicKey(blindingFactor); byte[] rootNonBlindedCommitment = ConfidentialAssetsHelper.GetNonblindedAssetCommitment(rootAttribute.AssetId); byte[] rootOriginatingCommitment = ConfidentialAssetsHelper.SumCommitments(rootNonBlindedCommitment, blindingPoint); byte[] target = userAttributeTransferWithValidations.UserAttributeTransfer.Target.HexStringToByteArray(); _dataAccessService.GetAccountId(target, out ulong spAccountId); AssociatedProofPreparation[] associatedProofPreparations = null; IEnumerable <SpIdenitityValidation> spIdenitityValidations = _dataAccessService.GetSpIdenitityValidations(spAccountId); if (spIdenitityValidations != null && spIdenitityValidations.Count() > 0) { associatedProofPreparations = new AssociatedProofPreparation[spIdenitityValidations.Count()]; var associatedAttributes = _dataAccessService.GetUserAssociatedAttributes(accountId); int index = 0; foreach (var validation in spIdenitityValidations) { string attrContent = associatedAttributes.FirstOrDefault(a => a.Item1 == validation.AttributeType)?.Item2 ?? string.Empty; byte[] groupId = _identityAttributesService.GetGroupId(validation.AttributeType); byte[] assetId = validation.AttributeType != AttributeType.DateOfBirth ? _assetsService.GenerateAssetId(validation.AttributeType, attrContent) : rootAttribute.AssetId; byte[] associatedBlindingFactor = validation.AttributeType != AttributeType.DateOfBirth ? ConfidentialAssetsHelper.GetRandomSeed() : null; byte[] associatedCommitment = validation.AttributeType != AttributeType.DateOfBirth ? ConfidentialAssetsHelper.GetAssetCommitment(assetId, associatedBlindingFactor) : null; byte[] associatedNonBlindedCommitment = ConfidentialAssetsHelper.GetNonblindedAssetCommitment(assetId); byte[] associatedOriginatingCommitment = ConfidentialAssetsHelper.SumCommitments(associatedNonBlindedCommitment, blindingPoint); AssociatedProofPreparation associatedProofPreparation = new AssociatedProofPreparation { GroupId = groupId, Commitment = associatedCommitment, CommitmentBlindingFactor = associatedBlindingFactor, OriginatingAssociatedCommitment = associatedOriginatingCommitment, OriginatingBlindingFactor = blindingFactor, OriginatingRootCommitment = rootOriginatingCommitment }; associatedProofPreparations[index++] = associatedProofPreparation; } } SendOnboardingRequest(userAttributeTransferWithValidations.UserAttributeTransfer, utxoPersistency.TransactionsService, associatedProofPreparations); return(Ok(res)); }
private Tuple <byte[], byte[]> DecryptUtxoKeys(Account account, string passphrase) { byte[] publicSpendKeyBuf, publicViewKeyBuf; Tuple <byte[], byte[]> keys = GetSecretKeys(account, passphrase); publicSpendKeyBuf = ConfidentialAssetsHelper.GetPublicKey(keys.Item1); publicViewKeyBuf = ConfidentialAssetsHelper.GetPublicKey(keys.Item2); bool res = publicSpendKeyBuf.Equals32(account.PublicSpendKey) && publicViewKeyBuf.Equals32(account.PublicViewKey); return(res ? keys : null); }
public virtual void Initialize(params byte[][] secretKeys) { if (secretKeys == null) { throw new ArgumentNullException(nameof(secretKeys)); } if (secretKeys.Length != 2) { throw new WrongSecretKeysNumberException(nameof(AccountSigningService), 2); } _secretSpendKey = secretKeys[0]; _secretViewKey = secretKeys[1]; PublicKeys[0] = _identityKeyProvider.GetKey(ConfidentialAssetsHelper.GetPublicKey(_secretSpendKey)); PublicKeys[1] = _identityKeyProvider.GetKey(ConfidentialAssetsHelper.GetPublicKey(_secretViewKey)); }
private byte[] DecryptStateKeys(Account account, string passphrase) { byte[] secretSpendKey; using (var aes = Aes.Create()) { aes.IV = _dataAccessService.GetAesInitializationVector(); byte[] passphraseBytes = Encoding.ASCII.GetBytes(passphrase); aes.Key = SHA256.Create().ComputeHash(passphraseBytes); aes.Padding = PaddingMode.None; secretSpendKey = aes.CreateDecryptor().TransformFinalBlock(account.SecretSpendKey, 0, account.SecretSpendKey.Length); } byte[] publicSpendKeyBuf = ConfidentialAssetsHelper.GetPublicKey(Ed25519.SecretKeyFromSeed(secretSpendKey)); bool res = publicSpendKeyBuf.Equals32(account.PublicSpendKey); return(res ? secretSpendKey : null); }
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; } } }
public void TransitionAssetProofSerializerTest() { ulong syncBlockHeight = 1; uint nonce = 4; byte[] powHash = BinaryHelper.GetPowHash(1234); ushort version = 1; byte[] body; byte[] transactionPublicKey = ConfidentialAssetsHelper.GetRandomSeed(); byte[] destinationKey = ConfidentialAssetsHelper.GetRandomSeed(); byte[] destinationKey2 = ConfidentialAssetsHelper.GetRandomSeed(); byte[] keyImage = BinaryHelper.GetRandomPublicKey(); byte[] assetCommitment = ConfidentialAssetsHelper.GetRandomSeed(); byte[] mask = ConfidentialAssetsHelper.GetRandomSeed(); byte[] assetId = ConfidentialAssetsHelper.GetRandomSeed(); byte[] assetIssuer = ConfidentialAssetsHelper.GetRandomSeed(); byte[] payload = ConfidentialAssetsHelper.GetRandomSeed(); ushort pubKeysCount = 10; byte[][] ownershipAssetCommitments = new byte[pubKeysCount][]; byte[][] pubKeys = new byte[pubKeysCount][]; byte[] secretKey = null; ushort secretKeyIndex = 5; byte[] e = ConfidentialAssetsHelper.GetRandomSeed(); byte[][] s = new byte[pubKeysCount][]; ushort eligibilityCommitmentsCount = 7; byte[][] eligibilityCommitments = new byte[eligibilityCommitmentsCount][]; byte[] eligibilityE = ConfidentialAssetsHelper.GetRandomSeed(); byte[][] eligibilityS = new byte[eligibilityCommitmentsCount][]; for (int i = 0; i < pubKeysCount; i++) { if (i == secretKeyIndex) { secretKey = ConfidentialAssetsHelper.GetOTSK(transactionPublicKey, _privateViewKey, _privateKey); pubKeys[i] = ConfidentialAssetsHelper.GetPublicKey(secretKey); keyImage = ConfidentialAssetsHelper.GenerateKeyImage(secretKey); } else { pubKeys[i] = BinaryHelper.GetRandomPublicKey(out byte[] secretKeyTemp); } ownershipAssetCommitments[i] = ConfidentialAssetsHelper.GetRandomSeed(); s[i] = ConfidentialAssetsHelper.GetRandomSeed(); } for (int i = 0; i < eligibilityCommitmentsCount; i++) { eligibilityCommitments[i] = ConfidentialAssetsHelper.GetRandomSeed(); eligibilityS[i] = ConfidentialAssetsHelper.GetRandomSeed(); } using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(assetCommitment); bw.Write(mask); bw.Write(assetId); bw.Write(assetIssuer); bw.Write(payload); bw.Write(pubKeysCount); for (int i = 0; i < pubKeysCount; i++) { bw.Write(ownershipAssetCommitments[i]); } bw.Write(e); for (int i = 0; i < pubKeysCount; i++) { bw.Write(s[i]); } bw.Write(eligibilityCommitmentsCount); for (int i = 0; i < eligibilityCommitmentsCount; i++) { bw.Write(eligibilityCommitments[i]); } bw.Write(eligibilityE); for (int i = 0; i < eligibilityCommitmentsCount; i++) { bw.Write(eligibilityS[i]); } } body = ms.ToArray(); } byte[] expectedPacket = BinaryHelper.GetUtxoConfidentialPacket(PacketType.UtxoConfidential, syncBlockHeight, nonce, powHash, version, BlockTypes.UtxoConfidential_TransitionOnboardingDisclosingProofs, keyImage, destinationKey, destinationKey2, transactionPublicKey, body, pubKeys, secretKey, secretKeyIndex, out RingSignature[] ringSignatures); TransitionOnboardingDisclosingProofs block = new TransitionOnboardingDisclosingProofs { SyncBlockHeight = syncBlockHeight, Nonce = nonce, PowHash = powHash, DestinationKey = destinationKey, DestinationKey2 = destinationKey2, KeyImage = new Key32(keyImage), TransactionPublicKey = transactionPublicKey, AssetCommitment = assetCommitment, EcdhTuple = new EcdhTupleProofs { Mask = mask, AssetId = assetId, AssetIssuer = assetIssuer, Payload = payload }, OwnershipProof = new SurjectionProof { AssetCommitments = ownershipAssetCommitments, Rs = new BorromeanRingSignature { E = e, S = s } }, EligibilityProof = new SurjectionProof { AssetCommitments = eligibilityCommitments, Rs = new BorromeanRingSignature { E = eligibilityE, S = eligibilityS } } }; TransitionOnboardingDisclosingProofsSerializer serializer = new TransitionOnboardingDisclosingProofsSerializer(); serializer.Initialize(block); serializer.SerializeBody(); _utxoSigningService.Sign(block, new UtxoSignatureInput(transactionPublicKey, pubKeys, secretKeyIndex)); byte[] actualPacket = serializer.GetBytes(); Span <byte> expectedSpan = new Span <byte>(expectedPacket); Span <byte> actualSpan = new Span <byte>(actualPacket); Assert.Equal(expectedSpan.Slice(0, expectedPacket.Length - pubKeysCount * 64).ToArray(), actualSpan.Slice(0, actualPacket.Length - pubKeysCount * 64).ToArray()); }
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); }