Ejemplo n.º 1
0
        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));
        }
Ejemplo n.º 2
0
        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));
        }
Ejemplo n.º 3
0
        public IActionResult SendRelationsProofs([FromBody] RelationsProofsDto relationsProofs)
        {
            ulong           accountId       = ulong.Parse(User.Identity.Name, CultureInfo.InvariantCulture);
            UtxoPersistency utxoPersistency = _executionContextManager.ResolveUtxoExecutionServices(accountId);

            byte[] target                 = relationsProofs.Target.HexStringToByteArray();
            byte[] targetViewKey          = relationsProofs.TargetViewKey.HexStringToByteArray();
            byte[] issuer                 = relationsProofs.Source.HexStringToByteArray();
            byte[] assetId                = relationsProofs.AssetId.HexStringToByteArray();
            byte[] originalBlindingFactor = relationsProofs.OriginalBlindingFactor.HexStringToByteArray();
            byte[] originalCommitment     = relationsProofs.OriginalCommitment.HexStringToByteArray();
            byte[] lastTransactionKey     = relationsProofs.LastTransactionKey.HexStringToByteArray();
            byte[] lastBlindingFactor     = relationsProofs.LastBlindingFactor.HexStringToByteArray();
            byte[] lastCommitment         = relationsProofs.LastCommitment.HexStringToByteArray();
            byte[] lastDestinationKey     = relationsProofs.LastDestinationKey.HexStringToByteArray();
            byte[] imageContent           = Convert.FromBase64String(relationsProofs.ImageContent);

            string sessionKey = _gatewayService.PushRelationProofSession(
                new RelationProofSession
            {
                ImageContent    = relationsProofs.ImageContent,
                RelationEntries = relationsProofs.Relations.Select(r => new RelationEntry {
                    RelatedAssetOwnerName = r.GroupOwnerName, RelatedAssetOwnerKey = r.GroupOwnerKey, RelatedAssetName = r.GroupName
                }).ToArray()
            });

            RelationsProofsInput requestInput = new RelationsProofsInput
            {
                AssetId = assetId,
                EligibilityBlindingFactor = originalBlindingFactor,
                EligibilityCommitment     = originalCommitment,
                Issuer = issuer,
                PrevAssetCommitment = lastCommitment,
                PrevBlindingFactor  = lastBlindingFactor,
                PrevDestinationKey  = lastDestinationKey,
                PrevTransactionKey  = lastTransactionKey,
                Target        = target,
                TargetViewKey = targetViewKey,
                Payload       = sessionKey.HexStringToByteArray(),
                ImageHash     = ConfidentialAssetsHelper.FastHash256(imageContent),
                Relations     = relationsProofs.Relations.Select(r => new Relation {
                    RelatedAssetOwner = r.GroupOwnerKey.HexStringToByteArray(), RelatedAssetId = _assetsService.GenerateAssetId(AttributeType.EmployeeGroup, r.GroupOwnerKey + r.GroupName)
                }).ToArray()
            };

            OutputModel[] outputModels        = _gatewayService.GetOutputs(_portalConfiguration.RingSize + 1);
            byte[][]      issuanceCommitments = _gatewayService.GetIssuanceCommitments(issuer, _portalConfiguration.RingSize + 1);

            utxoPersistency.TransactionsService.SendRelationsProofs(requestInput, outputModels, issuanceCommitments);

            return(Ok());
        }
Ejemplo n.º 4
0
        public RelationProofsValidationResults VerifyRelationProofs(GroupsRelationsProofs relationsProofs, IUtxoClientCryptoService clientCryptoService)
        {
            //TODO: need to add eligibility proofs

            RelationProofsValidationResults validationResults = new RelationProofsValidationResults();

            clientCryptoService.DecodeEcdhTuple(relationsProofs.EcdhTuple, relationsProofs.TransactionPublicKey, out byte[] sessionKey, out byte[] imageHash);

            RelationProofSession proofSession = _gatewayService.PopRelationProofSession(sessionKey.ToHexString());

            byte[] image = Convert.FromBase64String(proofSession.ImageContent);
            validationResults.ImageContent = proofSession.ImageContent;
            byte[] imageHashFromSession = ConfidentialAssetsHelper.FastHash256(image);

            validationResults.IsImageCorrect = imageHashFromSession.Equals32(imageHash);

            foreach (var relationEntry in proofSession.RelationEntries)
            {
                bool isRelationContentMatching = false;

                foreach (var relationProof in relationsProofs.RelationProofs)
                {
                    byte[] registrationCommitment = relationProof.RelationProof.AssetCommitments[0];
                    byte[] groupNameCommitment    = _gatewayService.GetEmployeeRecordGroup(relationProof.GroupOwner, registrationCommitment);
                    bool   isRelationProofCorrect = groupNameCommitment != null?ConfidentialAssetsHelper.VerifySurjectionProof(relationProof.RelationProof, relationsProofs.AssetCommitment) : false;

                    if (isRelationProofCorrect)
                    {
                        byte[] relationAssetId = _assetsService.GenerateAssetId(AttributeType.EmployeeGroup, relationProof.GroupOwner.ToHexString() + relationEntry.RelatedAssetName);
                        if (ConfidentialAssetsHelper.VerifyIssuanceSurjectionProof(relationProof.GroupNameProof, groupNameCommitment, new byte[][] { relationAssetId }))
                        {
                            isRelationContentMatching = true;
                            break;
                        }
                    }
                }

                validationResults.ValidationResults.Add(new RelationProofValidationResult {
                    RelatedAttributeOwner = relationEntry.RelatedAssetOwnerName, RelatedAttributeContent = relationEntry.RelatedAssetName, IsRelationCorrect = isRelationContentMatching
                });
            }

            return(validationResults);
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
        public BlockBase CreateUtxoRegisterBlock(UtxoConfidentialBase confidentialBase, byte[] otsk, int actualAssetPos)
        {
            byte[] msg = ConfidentialAssetsHelper.FastHash256(confidentialBase.RawData.ToArray());

            RegistryRegisterUtxoConfidentialBlock registryRegisterUtxoConfidentialBlock = new RegistryRegisterUtxoConfidentialBlock
            {
                SyncBlockHeight      = confidentialBase.SyncBlockHeight,
                Nonce                = confidentialBase.Nonce,
                PowHash              = confidentialBase.PowHash,
                ReferencedPacketType = confidentialBase.PacketType,
                ReferencedBlockType  = confidentialBase.BlockType,
                DestinationKey       = confidentialBase.DestinationKey,
                KeyImage             = confidentialBase.KeyImage,
                ReferencedBodyHash   = _hashCalculation.CalculateHash(confidentialBase.RawData),
                TransactionPublicKey = confidentialBase.TransactionPublicKey,
                TagId                = confidentialBase.TagId,
                PublicKeys           = confidentialBase.PublicKeys,
                Signatures           = ConfidentialAssetsHelper.GenerateRingSignature(msg, confidentialBase.KeyImage.Value.ToArray(), confidentialBase.PublicKeys.Select(p => p.Value.ToArray()).ToArray(), otsk, actualAssetPos)
            };

            return(registryRegisterUtxoConfidentialBlock);
        }
Ejemplo n.º 7
0
        private BlockBase CreateNonQuantitativeTransitionAssetTransferBlock(Account receiver, byte[] assetId, byte[] prevTransactionKey, byte[] prevCommitment, byte[] prevDestinationKey, int ringSize, ulong tagId, out byte[] otsk, out int pos)
        {
            if (!_clientState.IsConfidential())
            {
                otsk = null;
                pos  = -1;
                return(null);
            }

            byte[] otskAsset = ConfidentialAssetsHelper.GetOTSK(prevTransactionKey, _clientState.GetSecretViewKey(), _clientState.GetSecretSpendKey());
            otsk = otskAsset;
            byte[] keyImage        = ConfidentialAssetsHelper.GenerateKeyImage(otskAsset);
            byte[] secretKey       = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] transactionKey  = ConfidentialAssetsHelper.GetTrancationKey(secretKey);
            byte[] destinationKey  = _hashCalculation.CalculateHash(receiver.PublicKey);
            byte[] blindingFactor  = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] assetCommitment = ConfidentialAssetsHelper.GetAssetCommitment(assetId, blindingFactor);

            byte[] msg = ConfidentialAssetsHelper.FastHash256(BitConverter.GetBytes(tagId), keyImage, destinationKey, transactionKey, assetCommitment);

            Random random = new Random(BitConverter.ToInt32(secretKey, 0));

            GetCommitmentAndProofs(prevCommitment, prevDestinationKey, ringSize, tagId, random, out int actualAssetPos, out byte[][] assetCommitments, out byte[][] assetPubs);
            pos = actualAssetPos;

            UtxoUnspentBlock idCardBlock = _dataAccessService.GetUtxoUnspentBlocksByTagId(_idCardTagId).First();

            byte[] otskAffiliation            = ConfidentialAssetsHelper.GetOTSK(idCardBlock.TransactionKey, _clientState.GetSecretViewKey(), _clientState.GetSecretSpendKey());
            byte[] affiliationBlindingFactor  = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] affiliationAssetCommitment = ConfidentialAssetsHelper.GetAssetCommitment(idCardBlock.AssetId, affiliationBlindingFactor);
            GetCommitmentAndProofs(idCardBlock.Output.Commitment, idCardBlock.Output.DestinationKey, ringSize, _idCardTagId, random, out int actualAffiliationPos, out byte[][] affiliationCommitments, out byte[][] affiliationPubs);

            BorromeanRingSignature borromeanRingSignature = ConfidentialAssetsHelper.GenerateBorromeanRingSignature(msg, affiliationPubs, actualAffiliationPos, otskAffiliation);

            SurjectionProof assetSurjectionProof       = ConfidentialAssetsHelper.CreateAssetRangeProof(assetCommitment, assetCommitments, actualAssetPos, blindingFactor);
            SurjectionProof affilaitionSurjectionProof = ConfidentialAssetsHelper.CreateAssetRangeProof(affiliationAssetCommitment, affiliationCommitments, actualAffiliationPos, affiliationBlindingFactor);

            List <TransactionalIncomingBlock> incomingBlocks    = _dataAccessService.GetIncomingBlocksByBlockType(BlockTypes.Transaction_IssueAssets);
            List <IssueAssetsBlock>           issueAssetsBlocks = incomingBlocks.Where(b => b.TagId == _idCardTagId).ToList().Select(b =>
            {
                return((IssueAssetsBlock)_blockParsersRepositoriesRepository.GetBlockParsersRepository(PacketType.Transactional).GetInstance(b.BlockType).Parse(b.Content));
            }).ToList();

            List <byte[]> rawIdCardAssetIds = issueAssetsBlocks.SelectMany(b => b.IssuedAssetIds).ToList();

            SurjectionProof affiliationEvidenceSurjectionProof = ConfidentialAssetsHelper.CreateNewIssuanceSurjectionProof(affiliationAssetCommitment, rawIdCardAssetIds.ToArray(), rawIdCardAssetIds.FindIndex(b => b.Equals32(idCardBlock.AssetId)), affiliationBlindingFactor);

            NonQuantitativeTransitionAssetTransferBlock block = new NonQuantitativeTransitionAssetTransferBlock
            {
                TagId                              = tagId,
                KeyImage                           = _identityKeyProvider.GetKey(keyImage),
                DestinationKey                     = destinationKey,
                TransactionPublicKey               = transactionKey,
                AssetCommitment                    = assetCommitment,
                SurjectionProof                    = assetSurjectionProof,
                AffiliationCommitment              = affiliationAssetCommitment,
                AffiliationPseudoKeys              = affiliationPubs,
                AffiliationSurjectionProof         = affilaitionSurjectionProof,
                AffiliationBorromeanSignature      = borromeanRingSignature,
                AffiliationEvidenceSurjectionProof = affiliationEvidenceSurjectionProof,
                EcdhTuple                          = ConfidentialAssetsHelper.CreateEcdhTupleCA(blindingFactor, assetId, secretKey, receiver.PublicKey),
                PublicKeys                         = assetPubs.Select(p => _identityKeyProvider.GetKey(p)).ToArray(),
                Signatures                         = ConfidentialAssetsHelper.GenerateRingSignature(msg, keyImage, assetPubs, otskAsset, actualAssetPos)
            };

            FillSyncData(block);
            FillRawData(block);

            return(block);
        }