public void SynchronizationRegistryCombinedBlockSerializerTest() { ulong syncBlockHeight = 1; uint nonce = 4; byte[] powHash = BinaryHelper.GetPowHash(1234); ushort version = 1; ulong blockHeight = 9; byte[] prevHash = BinaryHelper.GetDefaultHash(1234); byte[] body; DateTime expectedDateTime = DateTime.Now; byte[][] expectedHashes = new byte[2][] { ConfidentialAssetsHelper.GetRandomSeed(), ConfidentialAssetsHelper.GetRandomSeed() }; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(expectedDateTime.ToBinary()); bw.Write((ushort)2); bw.Write(expectedHashes[0]); bw.Write(expectedHashes[1]); } body = ms.ToArray(); } byte[] expectedPacket = BinaryHelper.GetSignedPacket( PacketType.Synchronization, syncBlockHeight, nonce, powHash, version, BlockTypes.Synchronization_RegistryCombinationBlock, blockHeight, prevHash, body, _privateKey, out byte[] expectedSignature); SynchronizationRegistryCombinedBlock block = new SynchronizationRegistryCombinedBlock { SyncBlockHeight = syncBlockHeight, Nonce = nonce, PowHash = powHash, BlockHeight = blockHeight, HashPrev = prevHash, ReportedTime = expectedDateTime, BlockHashes = expectedHashes }; SynchronizationRegistryCombinedBlockSerializer serializer = new SynchronizationRegistryCombinedBlockSerializer(); serializer.Initialize(block); serializer.SerializeBody(); _signingService.Sign(block); byte[] actualPacket = serializer.GetBytes(); Trace.WriteLine(expectedPacket.ToHexString()); Trace.WriteLine(actualPacket.ToHexString()); Assert.Equal(expectedPacket, actualPacket); }
private void ProcessAuthentication(TransitionAuthenticationProofs transitionAuthentication) { _clientCryptoService.DecodeEcdhTuple(transitionAuthentication.EncodedPayload, transitionAuthentication.TransactionPublicKey, out byte[] bf, out byte[] assetId, out byte[] issuer, out byte[] payload); string sessionKey = payload.ToHexString(); bool isAuthenticationProofValid = ConfidentialAssetsHelper.VerifySurjectionProof(transitionAuthentication.AuthenticationProof, transitionAuthentication.AssetCommitment); if (isAuthenticationProofValid && _dataAccessService.GetServiceProviderRegistrationId(_accountId, transitionAuthentication.AuthenticationProof.AssetCommitments[0], out ulong id)) { bool isEligibilityCorrect = CheckEligibilityProofs(transitionAuthentication.AssetCommitment, transitionAuthentication.EligibilityProof, issuer); if (isEligibilityCorrect) { ProceedCorrectAuthentication(transitionAuthentication, sessionKey); } else { _idenitiesHubContext.Clients.Group(sessionKey).SendAsync("PushSpAuthorizationFailed", new { Code = 2, Message = "Eligibility proofs were wrong" }); } } else { _idenitiesHubContext.Clients.Group(sessionKey).SendAsync("PushSpAuthorizationFailed", new { Code = 1, Message = "User is not registered" }); } }
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); }
private async Task VerifyProofToAssociatedAttributeKnowledge(UniversalProofs universalProofs, string schemeName) { AttributeProofs attr = universalProofs.IssuersAttributes?.FirstOrDefault(a => a.Issuer.Equals(universalProofs.Issuer))?.Attributes.FirstOrDefault(a => a.SchemeName == schemeName); if (attr == null) { throw new AssociatedAttrProofsAreMissingException(schemeName); } if (attr.CommitmentProof.SurjectionProof.AssetCommitments.Length != attr.BindingProof.AssetCommitments.Length) { throw new AssociatedAttrProofsMalformedException(schemeName); } if (!ConfidentialAssetsHelper.VerifySurjectionProof(attr.CommitmentProof.SurjectionProof, attr.Commitment.ArraySegment.Array)) { throw new AssociatedAttrProofToValueKnowledgeIncorrectException(schemeName); } IKey commitmentKey = universalProofs.IssuersAttributes.FirstOrDefault(a => a.Issuer.Equals(universalProofs.Issuer))?.RootAttribute.Commitment; byte[] commitment = ConfidentialAssetsHelper.SumCommitments(commitmentKey.Value.Span, attr.Commitment.Value.Span); if (!ConfidentialAssetsHelper.VerifySurjectionProof(attr.BindingProof, commitment)) { throw new AssociatedAttrProofToBindingIncorrectException(schemeName); } (Memory <byte> issuanceCommitment, Memory <byte> commitmentToRoot)[] attrs = new (Memory <byte>, Memory <byte>)[attr.BindingProof.AssetCommitments.Length];
public void Sign(IPacket packet, object args = null) { if (!(packet is UtxoSignedPacketBase packetBase)) { throw new ArgumentOutOfRangeException(nameof(packet), string.Format(Resources.ERR_WRONG_PACKET_BASE_TYPE, nameof(UtxoSigningService), typeof(UtxoSignedPacketBase).FullName)); } UtxoSignatureInput signatureInput = args as UtxoSignatureInput; byte[][] publicKeys = signatureInput.PublicKeys; int index = signatureInput.KeyPosition; byte[] otsk = ConfidentialAssetsHelper.GetOTSK(signatureInput.SourceTransactionKey, _secretViewKey, _secretSpendKey); byte[] keyImage = ConfidentialAssetsHelper.GenerateKeyImage(otsk); packetBase.KeyImage = _identityKeyProvider.GetKey(keyImage); byte[] msg = new byte[packet.BodyBytes.Length + keyImage.Length]; Array.Copy(packet.BodyBytes.ToArray(), 0, msg, 0, packet.BodyBytes.Length); Array.Copy(keyImage, 0, msg, packet.BodyBytes.Length, keyImage.Length); RingSignature[] ringSignatures = ConfidentialAssetsHelper.GenerateRingSignature(msg, keyImage, publicKeys, otsk, index); packetBase.PublicKeys = signatureInput.PublicKeys.Select(p => _identityKeyProvider.GetKey(p)).ToArray(); packetBase.Signatures = ringSignatures; }
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 BlockBase CreateTransferAssetToUtxoBlock(byte[][] assetIds, int index, ulong tagId, ConfidentialAccount receiver, byte[] sk = null) { byte[] assetId = assetIds[index]; byte[] secretKey = sk ?? ConfidentialAssetsHelper.GetRandomSeed(); byte[] transactionKey = ConfidentialAssetsHelper.GetTrancationKey(secretKey); byte[] destinationKey = ConfidentialAssetsHelper.GetDestinationKey(secretKey, receiver.PublicViewKey, receiver.PublicSpendKey); byte[] blindingFactor = ConfidentialAssetsHelper.GetRandomSeed(); byte[] assetCommitment = ConfidentialAssetsHelper.GetAssetCommitment(assetId, blindingFactor); ulong[] assetAmounts = new ulong[assetIds.Length]; for (int i = 0; i < assetAmounts.Length; i++) { assetAmounts[i] = 1; } TransferAssetToUtxoBlock transferAssetToUtxoBlock = new TransferAssetToUtxoBlock { TagId = tagId, AssetIds = assetIds, AssetAmounts = assetAmounts, TransactionPublicKey = transactionKey, DestinationKey = destinationKey, AssetId = assetId, AssetCommitment = assetCommitment, SurjectionProof = ConfidentialAssetsHelper.CreateNewIssuanceSurjectionProof(assetCommitment, assetIds, index, blindingFactor), EcdhTuple = ConfidentialAssetsHelper.CreateEcdhTupleCA(blindingFactor, assetId, secretKey, receiver.PublicViewKey) }; FillHeightInfo(transferAssetToUtxoBlock); FillSyncData(transferAssetToUtxoBlock); FillRawData(transferAssetToUtxoBlock); return(transferAssetToUtxoBlock); }
public void IssueAssetTest() { ulong tagId = 147; ulong syncBlockHeight = 1; uint nonce = 4; byte[] powHash = BinaryHelper.GetPowHash(1234); ushort version = 1; ulong blockHeight = 9; byte[] body; ulong uptodateFunds = 10001; byte[] assetId = ConfidentialAssetsHelper.GetRandomSeed(); byte[] assetCommitment = ConfidentialAssetsHelper.GetRandomSeed(); byte[] mask = ConfidentialAssetsHelper.GetRandomSeed(); byte[] maskedAssetId = ConfidentialAssetsHelper.GetRandomSeed(); using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(tagId); bw.Write(uptodateFunds); bw.Write(assetId); bw.Write(assetCommitment); bw.Write(mask); bw.Write(maskedAssetId); } body = ms.ToArray(); } }
protected byte[] GetRandomTargetAddress() { byte[] seedTarget = "1F0B7DBB567EFC99060EC69DD60130B4364E36B7A88248DD234285B3860F63C3".HexStringToByteArray();// GetRandomSeed(); byte[] targetKeyBytes = ConfidentialAssetsHelper.GetPublicKeyFromSeed(seedTarget); byte[] targetHash = _hashCalculation.CalculateHash(targetKeyBytes); return(targetHash); }
public void RegistryRegisterBlockParserTransitionalTest() { ulong syncBlockHeight = 1; uint nonce = 4; byte[] powHash = BinaryHelper.GetPowHash(1234); ushort version = 1; ulong blockHeight = 9; byte[] prevHash = null; PacketType expectedReferencedPacketType = PacketType.Transactional; ushort expectedReferencedBlockType = BlockTypes.Transaction_TransferAssetToUtxo; byte[] expectedReferencedBodyHash = BinaryHelper.GetDefaultHash(473826643); byte[] expectedTarget = BinaryHelper.GetDefaultHash(BinaryHelper.GetRandomPublicKey()); byte[] transactionKey = ConfidentialAssetsHelper.GetRandomSeed(); byte[] body; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write((ushort)expectedReferencedPacketType); bw.Write(expectedReferencedBlockType); bw.Write(expectedReferencedBodyHash); bw.Write(expectedTarget); bw.Write(transactionKey); } body = ms.ToArray(); } byte[] packet = BinaryHelper.GetSignedPacket( PacketType.Registry, syncBlockHeight, nonce, powHash, version, BlockTypes.Registry_Register, blockHeight, prevHash, body, _privateKey, out byte[] expectedSignature); RegistryRegisterBlockParser registryRegisterBlockParser = new RegistryRegisterBlockParser(_identityKeyProvidersRegistry); RegistryRegisterBlock block = (RegistryRegisterBlock)registryRegisterBlockParser.Parse(packet); Assert.Equal(syncBlockHeight, block.SyncBlockHeight); Assert.Equal(nonce, block.Nonce); Assert.Equal(powHash, block.PowHash); Assert.Equal(version, block.Version); Assert.Equal(blockHeight, block.BlockHeight); Assert.Equal(expectedReferencedPacketType, block.ReferencedPacketType); Assert.Equal(expectedReferencedBlockType, block.ReferencedBlockType); Assert.Equal(expectedReferencedBodyHash, block.ReferencedBodyHash); Assert.Equal(expectedTarget, block.ReferencedTarget); Assert.Equal(transactionKey, block.ReferencedTransactionKey); Assert.Equal(_publicKey, block.Signer.Value.ToArray()); Assert.Equal(expectedSignature, block.Signature.ToArray()); }
public Candidate AddCandidateToPoll(long pollId, string name) { IKey assetId = _identityKeyProvider.GetKey(ConfidentialAssetsHelper.GetRandomSeed()); var id = _dataAccessService.AddCandidateToPoll(pollId, name, assetId.ToString()); return(_translatorsRepository.GetInstance <EcCandidateRecord, Candidate>().Translate(_dataAccessService.GetCandidateRecord(id))); }
public string InitiateRelationProofsSession(ProofsRequest proofsRequest) { string sessionKey = ConfidentialAssetsHelper.GetRandomSeed().ToHexString(); _relationProofSessions.AddOrUpdate(sessionKey, new RelationProofsSession { ProofsRequest = proofsRequest }, (k, v) => v); return(sessionKey); }
public void IssueBlindedAssetParserTest() { byte[] groupId = ConfidentialAssetsHelper.GetRandomSeed(); ulong syncBlockHeight = 1; uint nonce = 4; byte[] powHash = BinaryHelper.GetPowHash(1234); ushort version = 1; ulong blockHeight = 9; byte[] body; ulong uptodateFunds = 10001; byte[] assetCommitment = ConfidentialAssetsHelper.GetRandomSeed(); byte[] mask = ConfidentialAssetsHelper.GetRandomSeed(); byte[] maskedAssetId = ConfidentialAssetsHelper.GetRandomSeed(); byte[] keyImage = ConfidentialAssetsHelper.GetRandomSeed(); byte[] c = ConfidentialAssetsHelper.GetRandomSeed(); byte[] r = ConfidentialAssetsHelper.GetRandomSeed(); using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(uptodateFunds); bw.Write(groupId); bw.Write(assetCommitment); //bw.Write(mask); //bw.Write(maskedAssetId); bw.Write(keyImage); bw.Write(c); bw.Write(r); } body = ms.ToArray(); } byte[] packet = BinaryHelper.GetSignedPacket(PacketType.Transactional, syncBlockHeight, nonce, powHash, version, BlockTypes.Transaction_TransferGroupedAssetsToUtxo, blockHeight, null, body, _privateKey, out byte[] expectedSignature); IssueBlindedAssetParser parser = new IssueBlindedAssetParser(_identityKeyProvidersRegistry); IssueBlindedAsset block = (IssueBlindedAsset)parser.Parse(packet); Assert.Equal(syncBlockHeight, block.SyncBlockHeight); Assert.Equal(nonce, block.Nonce); Assert.Equal(powHash, block.PowHash); Assert.Equal(version, block.Version); Assert.Equal(blockHeight, block.BlockHeight); Assert.Equal(uptodateFunds, block.UptodateFunds); Assert.Equal(groupId, block.GroupId); Assert.Equal(assetCommitment, block.AssetCommitment); Assert.Equal(keyImage, block.KeyImage); Assert.Equal(c, block.UniquencessProof.C); Assert.Equal(r, block.UniquencessProof.R); Assert.Equal(expectedSignature, block.Signature.ToArray()); }
public void SynchronizationRegistryCombinedBlockParserTest() { ulong syncBlockHeight = 1; uint nonce = 4; byte[] powHash = BinaryHelper.GetPowHash(1234); ushort version = 1; ulong blockHeight = 9; byte[] prevHash = BinaryHelper.GetDefaultHash(1234); byte[] body; DateTime expectedDateTime = DateTime.Now; byte[][] expectedHashes = new byte[2][] { ConfidentialAssetsHelper.GetRandomSeed(), ConfidentialAssetsHelper.GetRandomSeed() }; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(expectedDateTime.ToBinary()); bw.Write((ushort)2); bw.Write(expectedHashes[0]); bw.Write(expectedHashes[1]); } body = ms.ToArray(); } byte[] packet = BinaryHelper.GetSignedPacket( PacketType.Synchronization, syncBlockHeight, nonce, powHash, version, BlockTypes.Synchronization_RegistryCombinationBlock, blockHeight, prevHash, body, _privateKey, out byte[] expectedSignature); SynchronizationRegistryCombinedBlockParser parser = new SynchronizationRegistryCombinedBlockParser(_identityKeyProvidersRegistry); SynchronizationRegistryCombinedBlock block = (SynchronizationRegistryCombinedBlock)parser.Parse(packet); Assert.Equal(syncBlockHeight, block.SyncBlockHeight); Assert.Equal(nonce, block.Nonce); Assert.Equal(powHash, block.PowHash); Assert.Equal(version, block.Version); Assert.Equal(blockHeight, block.BlockHeight); Assert.Equal(expectedHashes.Length, block.BlockHashes.Length); for (int i = 0; i < expectedHashes.Length; i++) { Assert.Equal(expectedHashes[i], block.BlockHashes[i]); } Assert.Equal(_publicKey, block.Signer.Value.ToArray()); Assert.Equal(expectedSignature, block.Signature.ToArray()); }
static void Main(string[] args) { //int minWorkerThreads, minCompletionPortThreads; //int maxWorkerThreads, maxCompletionPortThreads; //ThreadPool.GetMinThreads(out minWorkerThreads, out minCompletionPortThreads); //ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionPortThreads); //ThreadPool.SetMaxThreads(minWorkerThreads * 100, minCompletionPortThreads); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); XmlConfigurator.Configure(_log.Logger.Repository); _log.Info("===== NODE STARTED ====="); ConfigureUnhandledExceptions(); string secretKey = null; if ((args?.Length ?? 0) == 0) { if (Debugger.IsAttached) { byte[] seed = ConfidentialAssetsHelper.GetRandomSeed(); secretKey = seed.ToHexString(); } else { throw new NoSecretKeyProvidedException(); } } else { secretKey = args[0]; } Dictionary <string, string> bootArgs = new Dictionary <string, string> { { "secretKey", secretKey } }; NodeBootstrapper nodeBootstrapper = new NodeBootstrapper(cancellationTokenSource.Token); nodeBootstrapper.Run(bootArgs); string command = null; do { command = System.Console.ReadLine(); } while (command?.ToLower() != "exit"); cancellationTokenSource.Cancel(); //TODO: add code for graceful shutdown }
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 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)); }
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()); }
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 bool Verify(IPacket packet) { if (!(packet is UtxoSignedPacketBase packetBase)) { throw new ArgumentOutOfRangeException(nameof(packet), string.Format(Resources.ERR_WRONG_PACKET_BASE_TYPE, nameof(UtxoSigningService), typeof(UtxoSignedPacketBase).FullName)); } byte[] msg = packetBase.BodyBytes.ToArray(); byte[] keyImage = packetBase.KeyImage.Value.ToArray(); IKey[] publicKeys = packetBase.PublicKeys; RingSignature[] signatures = packetBase.Signatures; return(ConfidentialAssetsHelper.VerifyRingSignature(msg, keyImage, publicKeys.Select(p => p.Value.ToArray()).ToArray(), signatures)); }
public bool CheckTarget(params byte[][] targetValues) { if (targetValues == null) { throw new ArgumentNullException(nameof(targetValues)); } if (targetValues.Length != 2) { throw new ArgumentOutOfRangeException(nameof(targetValues)); } return(ConfidentialAssetsHelper.IsDestinationKeyMine(targetValues[0], targetValues[1], _secretViewKey, PublicKeys[0].Value.ToArray())); }
public static byte[] GetUtxoConfidentialPacket(PacketType packetType, ulong syncBlockHeight, uint nonce, byte[] powHash, ushort version, ushort blockType, ulong tagId, byte[] keyImage, byte[] destinationKey, byte[] transactionPublicKey, byte[] body, byte[][] pubKeys, byte[] secretKey, int secIndex, out RingSignature[] ringSignatures) { byte[] bodyBytes = null; byte[] result = null; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(version); bw.Write(blockType); bw.Write(tagId); bw.Write(keyImage); bw.Write(destinationKey); bw.Write(transactionPublicKey); bw.Write(body); } bodyBytes = ms.ToArray(); } ringSignatures = ConfidentialAssetsHelper.GenerateRingSignature(bodyBytes, keyImage, pubKeys, secretKey, secIndex); using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write((ushort)packetType); bw.Write(syncBlockHeight); bw.Write(nonce); bw.Write(powHash); bw.Write(bodyBytes); bw.Write((ushort)ringSignatures.Length); for (int i = 0; i < pubKeys.Length; i++) { bw.Write(pubKeys[i]); } for (int i = 0; i < pubKeys.Length; i++) { bw.Write(ringSignatures[i].C); bw.Write(ringSignatures[i].R); } } result = ms.ToArray(); } return(result); }
public IActionResult BindingKey([FromBody] BindingKeyRequestDto bindingKeyRequest) { var accountDescriptor = _accountsService.Authenticate(bindingKeyRequest.AccountId, bindingKeyRequest.Password); if (accountDescriptor == null) { throw new AccountAuthenticationFailedException(bindingKeyRequest.AccountId); } var persistency = _executionContextManager.ResolveUtxoExecutionServices(bindingKeyRequest.AccountId); persistency.BindingKeySource.SetResult(ConfidentialAssetsHelper.PasswordHash(bindingKeyRequest.Password)); return(Ok()); }
public async Task <IActionResult> SignPersonFaceVerification([FromBody] BiometricPersonDataForSignatureDto biometricPersonData) { byte[] imageSource = Convert.FromBase64String(biometricPersonData.ImageSource); byte[] imageTarget = Convert.FromBase64String(biometricPersonData.ImageTarget); byte[] assetId = await _assetsService.GenerateAssetId(AttributesSchemes.ATTR_SCHEME_NAME_PASSPORTPHOTO, biometricPersonData.ImageSource, null).ConfigureAwait(false); byte[] sourceImageCommitment = biometricPersonData.SourceImageCommitment.HexStringToByteArray(); SurjectionProof surjectionProof = new SurjectionProof { AssetCommitments = new byte[][] { biometricPersonData.SourceImageProofCommitment.HexStringToByteArray() }, Rs = new BorromeanRingSignature { E = biometricPersonData.SourceImageProofSignatureE.HexStringToByteArray(), S = new byte[][] { biometricPersonData.SourceImageProofSignatureS.HexStringToByteArray() } } }; if (!ConfidentialAssetsHelper.VerifyIssuanceSurjectionProof(surjectionProof, sourceImageCommitment, new byte[][] { assetId })) { return(BadRequest("Surjection proofs validation failed")); } //byte[] auxBytes = null; // Convert.FromBase64String(biometricPersonData.AuxMessage); //byte[] msg = new byte[sourceImageCommitment.Length + auxBytes?.Length ?? 0]; //Array.Copy(sourceImageCommitment, 0, msg, 0, sourceImageCommitment.Length); //if ((auxBytes?.Length ?? 0) > 0) //{ // Array.Copy(auxBytes, 0, msg, sourceImageCommitment.Length, auxBytes.Length); //} bool res = await _facesService.VerifyFaces(imageSource, imageTarget).ConfigureAwait(false); if (res) { Tuple <byte[], byte[]> signRes = _facesService.Sign(sourceImageCommitment); return(Ok(new BiometricSignedVerificationDto { PublicKey = signRes.Item1.ToHexString(), Signature = signRes.Item2.ToHexString() })); } return(BadRequest()); }
public SurjectionProof CalculateEcCommitmentProof(long pollId, EcSurjectionProofRequest proofRequest) { if (proofRequest is null) { throw new ArgumentNullException(nameof(proofRequest)); } string ecCommitment = proofRequest.EcCommitment.ToHexString(); var pollSelection = _dataAccessService.GetPollSelection(pollId, ecCommitment); byte[] ecBf = pollSelection.EcBlindingFactor.HexStringToByteArray(); byte[] bf = ConfidentialAssetsHelper.SumScalars(ecBf, proofRequest.PartialBlindingFactor); var sp = ConfidentialAssetsHelper.CreateSurjectionProof(proofRequest.EcCommitment, proofRequest.CandidateCommitments, proofRequest.Index, bf); return(sp); }
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)); }
public async Task <IActionResult> AddAllowedSigner(long spId, long documentId, [FromBody] AllowedSignerDto allowedSigner) { byte[] groupAssetId = await _assetsService.GenerateAssetId(AttributesSchemes.ATTR_SCHEME_NAME_EMPLOYEEGROUP, allowedSigner.GroupOwner + allowedSigner.GroupName, allowedSigner.GroupOwner).ConfigureAwait(false); byte[] blindingFactor = ConfidentialAssetsHelper.GetRandomSeed(); byte[] groupCommitment = ConfidentialAssetsHelper.GetAssetCommitment(blindingFactor, groupAssetId); allowedSigner.AllowedSignerId = _dataAccessService.AddSpDocumentAllowedSigner(spId, documentId, allowedSigner.GroupOwner, allowedSigner.GroupName, groupCommitment.ToHexString(), blindingFactor.ToHexString()); SpDocument document = _dataAccessService.GetSpDocument(spId, documentId); StatePersistency statePersistency = _executionContextManager.ResolveStateExecutionServices(spId); statePersistency.TransactionsService.IssueDocumentRecord(document.Hash.HexStringToByteArray(), document.AllowedSigners.Select(s => s.GroupCommitment.HexStringToByteArray()).ToArray()); return(Ok(allowedSigner)); }
public async Task CheckEligibilityProofs(Memory <byte> assetCommitment, SurjectionProof eligibilityProofs, Memory <byte> issuer) { Contract.Requires(eligibilityProofs != null); bool isCommitmentCorrect = ConfidentialAssetsHelper.VerifySurjectionProof(eligibilityProofs, assetCommitment.Span); if (!isCommitmentCorrect) { throw new CommitmentNotEligibleException(); } bool res = await _gatewayService.AreRootAttributesValid(issuer, eligibilityProofs.AssetCommitments.Select(a => new Memory <byte>(a))).ConfigureAwait(false); if (!res) { throw new CommitmentNotEligibleException(); } }
private void SetupLocalAsNode() { IEnumerable <NodeRecord> nodes = DataAccessService.Instance.GetAllNodes(); if (!nodes.Any(n => "127.0.0.1".Equals(new IPAddress(n.IPAddress).ToString()))) { byte[] seed = ConfidentialAssetsHelper.GetRandomSeed(); byte[] publicKey = Ed25519.PublicKeyFromSeed(seed); IKey key = _identityKeyProvider.GetKey(publicKey); DataAccessService.Instance.AddNode(key, NodeRole.TransactionsRegistrationLayer, IPAddress.Parse("127.0.0.1")); DataAccessService.Instance.AddNode(key, NodeRole.StorageLayer, IPAddress.Parse("127.0.0.1")); DataAccessService.Instance.AddNode(key, NodeRole.SynchronizationLayer, IPAddress.Parse("127.0.0.1")); Console.WriteLine($"Please copy carefully aside seed below for providing as input argument to Node executable:"); Console.WriteLine(seed.ToHexString()); } }