Beispiel #1
0
        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);
        }
Beispiel #2
0
        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);
        }
Beispiel #3
0
        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();
            }
        }
Beispiel #4
0
        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);
        }
Beispiel #5
0
        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());
        }
Beispiel #6
0
        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)));
        }
Beispiel #7
0
        public string InitiateRelationProofsSession(ProofsRequest proofsRequest)
        {
            string sessionKey = ConfidentialAssetsHelper.GetRandomSeed().ToHexString();

            _relationProofSessions.AddOrUpdate(sessionKey, new RelationProofsSession {
                ProofsRequest = proofsRequest
            }, (k, v) => v);
            return(sessionKey);
        }
Beispiel #8
0
        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());
        }
Beispiel #9
0
        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());
        }
Beispiel #10
0
        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
        }
Beispiel #11
0
        public IActionResult GetSessionInfo(long spId)
        {
            string            nonce     = ConfidentialAssetsHelper.GetRandomSeed().ToHexString();
            AccountDescriptor spAccount = _accountsService.GetById(spId);

            return(Ok(new
            {
                publicKey = spAccount.PublicSpendKey.ToHexString(),
                sessionKey = nonce,
            }));
        }
Beispiel #12
0
        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));
        }
Beispiel #13
0
        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());
            }
        }
Beispiel #14
0
        public IActionResult AddAllowedSigner(ulong documentId, [FromBody] AllowedSignerDto allowedSigner)
        {
            ulong accountId = ulong.Parse(User.Identity.Name, CultureInfo.InvariantCulture);

            byte[] groupAssetId    = _assetsService.GenerateAssetId(AttributeType.EmployeeGroup, allowedSigner.GroupOwner + allowedSigner.GroupName);
            byte[] blindingFactor  = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] groupCommitment = ConfidentialAssetsHelper.GetAssetCommitment(groupAssetId, blindingFactor);

            allowedSigner.AllowedSignerId = _dataAccessService.AddSpDocumentAllowedSigner(accountId, documentId, allowedSigner.GroupOwner, allowedSigner.GroupName, groupCommitment.ToHexString(), blindingFactor.ToHexString());

            SpDocument document = _dataAccessService.GetSpDocument(accountId, documentId);

            StatePersistency statePersistency = _executionContextManager.ResolveStateExecutionServices(accountId);

            statePersistency.TransactionsService.IssueDocumentRecord(document.Hash.HexStringToByteArray(), document.AllowedSigners.Select(s => s.GroupCommitment.HexStringToByteArray()).ToArray());

            return(Ok(allowedSigner));
        }
Beispiel #15
0
        public TestBase()
        {
            _transactionHashKeyProvider         = Substitute.For <IIdentityKeyProvider>();
            _identityKeyProvider                = Substitute.For <IIdentityKeyProvider>();
            _identityKeyProvidersRegistry       = Substitute.For <IIdentityKeyProvidersRegistry>();
            _hashCalculationRepository          = Substitute.For <IHashCalculationsRepository>();
            _blockParsersRepositoriesRepository = Substitute.For <IBlockParsersRepositoriesRepository>();
            _blockParsersRepository             = Substitute.For <IBlockParsersRepository>();
            _signingService = Substitute.For <ISigningService>();

            _identityKeyProvidersRegistry.GetInstance().Returns(_identityKeyProvider);
            _identityKeyProvidersRegistry.GetTransactionsIdenityKeyProvider().Returns(_transactionHashKeyProvider);
            _identityKeyProvider.GetKey(null).ReturnsForAnyArgs(c => new Key32()
            {
                Value = c.Arg <Memory <byte> >()
            });
            _transactionHashKeyProvider.GetKey(null).ReturnsForAnyArgs(c => new Key16()
            {
                Value = c.Arg <Memory <byte> >()
            });
            _hashCalculationRepository.Create(HashType.MurMur).Returns(new MurMurHashCalculation());
            _blockParsersRepositoriesRepository.GetBlockParsersRepository(PacketType.Registry).ReturnsForAnyArgs(_blockParsersRepository);

            _privateKey     = ConfidentialAssetsHelper.GetRandomSeed();
            _privateViewKey = ConfidentialAssetsHelper.GetRandomSeed();
            Ed25519.KeyPairFromSeed(out _publicKey, out _expandedPrivateKey, _privateKey);

            _signingService.WhenForAnyArgs(s => s.Sign(null, null)).Do(c =>
            {
                ((SignedPacketBase)c.ArgAt <IPacket>(0)).Signer    = new Key32(_publicKey);
                ((SignedPacketBase)c.ArgAt <IPacket>(0)).Signature = Ed25519.Sign(((SignedPacketBase)c.ArgAt <IPacket>(0)).BodyBytes.ToArray(), _expandedPrivateKey);
            });
            _signingService.PublicKeys.Returns(new IKey[] { new Key32()
                                                            {
                                                                Value = _publicKey
                                                            } });

            _utxoSigningService = new UtxoSigningService(_identityKeyProvidersRegistry);
            _utxoSigningService.Initialize(_privateKey, _privateViewKey);


            ServiceLocator.Current.GetInstance <IUnityContainer>().RegisterInstance(_blockParsersRepositoriesRepository);
        }
Beispiel #16
0
        public SignedEcCommitment GenerateDerivedCommitment(long pollId, SelectionCommitmentRequest request)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            EcPollRecord poll = _dataAccessService.GetEcPoll(pollId);

            byte[][] assetIds = poll.Candidates.Select(c => c.AssetId.HexStringToByteArray()).ToArray();

            bool res1 = ConfidentialAssetsHelper.VerifySurjectionProof(request.CandidateCommitmentProofs, request.Commitment);

            if (!res1)
            {
                throw new ArgumentException("Verification to candidate commitments failed");
            }

            foreach (var candidateCommitment in request.CandidateCommitments)
            {
                bool res2 = ConfidentialAssetsHelper.VerifyIssuanceSurjectionProof(candidateCommitment.IssuanceProof, candidateCommitment.Commitment, assetIds);
                if (!res2)
                {
                    throw new ArgumentException($"Verification of candidate's {candidateCommitment.Commitment.ToHexString()} issuance proof failed");
                }
            }

            byte[] ecBlindingFactor = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] ecCommitment     = ConfidentialAssetsHelper.BlindAssetCommitment(request.Commitment, ecBlindingFactor);

            _dataAccessService.AddPollSelection(pollId, ecCommitment.ToHexString(), ecBlindingFactor.ToHexString());

            var persistency = _executionContextManager.ResolveStateExecutionServices(poll.AccountId);
            var signature   = persistency.ClientCryptoService.Sign(ecCommitment);

            return(new SignedEcCommitment
            {
                EcCommitment = ecCommitment,
                Signature = signature
            });
        }
Beispiel #17
0
        private static ISigningService GetRandomCryptoService()
        {
            ISigningService signingService = Substitute.For <ISigningService>();

            byte[] privateKey = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] expandedPrivateKey;
            byte[] publicKey;
            Ed25519.KeyPairFromSeed(out publicKey, out expandedPrivateKey, privateKey);
            signingService.WhenForAnyArgs(s => s.Sign(null, null)).Do(c =>
            {
                ((SignedPacketBase)c.ArgAt <IPacket>(0)).Signer = new Key32()
                {
                    Value = publicKey
                };
                ((SignedPacketBase)c.ArgAt <IPacket>(0)).Signature = Ed25519.Sign(c.Arg <byte[]>(), expandedPrivateKey);
            });
            signingService.PublicKeys.Returns(new IKey[] { new Key32()
                                                           {
                                                               Value = publicKey
                                                           } });
            return(signingService);
        }
Beispiel #18
0
        private void SetupIdentities()
        {
            IEnumerable <IKey> keys = DataAccessService.Instance.GetAllAccountIdentities();

            int targetKeyNumber = 5 - keys.Count();

            List <IKey> keysToAdd = new List <IKey>();

            while (targetKeyNumber > 0)
            {
                byte[] seed     = ConfidentialAssetsHelper.GetRandomSeed();
                byte[] keyBytes = Ed25519.PublicKeyFromSeed(seed);
                IKey   key      = _identityKeyProvider.GetKey(keyBytes);

                DataAccessService.Instance.GetOrAddIdentity(key);

                if (DataAccessService.Instance.AddSeed(key, seed))
                {
                    targetKeyNumber--;
                }
            }

            keys = DataAccessService.Instance.GetAllAccountIdentities();
        }
Beispiel #19
0
        public void MemPool_AddedNonUniqueTransactions_NotAllContained()
        {
            SynchronizationDescriptor synchronizationDescriptor = new SynchronizationDescriptor(1, new byte[Globals.DEFAULT_HASH_SIZE], DateTime.Now, DateTime.Now, 1);
            IHash                         transactionKeyHash    = HashFactory.Hash128.CreateMurmur3_128();
            ILogger                       logger                       = Substitute.For <ILogger>();
            ILoggerService                loggerService                = Substitute.For <ILoggerService>();
            IIdentityKeyProvider          identityKeyProvider          = new TransactionRegistryKeyProvider();
            IIdentityKeyProvidersRegistry identityKeyProvidersRegistry = Substitute.For <IIdentityKeyProvidersRegistry>();
            IHashCalculationsRepository   hashCalculationsRepository   = Substitute.For <IHashCalculationsRepository>();
            ISigningService               signingService               = Substitute.For <ISigningService>();
            SynchronizationContext        synchronizationContext       = new SynchronizationContext(loggerService);

            synchronizationContext.UpdateLastSyncBlockDescriptor(synchronizationDescriptor);
            IStatesRepository statesRepository = Substitute.For <IStatesRepository>();

            hashCalculationsRepository.Create(HashType.MurMur).Returns(new MurMurHashCalculation());

            logger.WhenForAnyArgs(l => l.Error(null)).DoNotCallBase();
            logger.WhenForAnyArgs(l => l.Warning(null)).DoNotCallBase();
            logger.WhenForAnyArgs(l => l.Info(null)).DoNotCallBase();
            loggerService.GetLogger(null).Returns(logger);

            identityKeyProvidersRegistry.GetTransactionsIdenityKeyProvider().ReturnsForAnyArgs(identityKeyProvider);
            //identityKeyProvider.GetKey(null).ReturnsForAnyArgs(c => new Key16() { Value = c.Arg<Memory<byte>>() });

            statesRepository.GetInstance <ISynchronizationContext>().Returns(synchronizationContext);

            byte[] privateKey = ConfidentialAssetsHelper.GetRandomSeed();
            Ed25519.KeyPairFromSeed(out byte[] publicKey, out byte[] expandedPrivateKey, privateKey);

            signingService.WhenForAnyArgs(s => s.Sign(null, null)).Do(c =>
            {
                ((SignedPacketBase)c.ArgAt <IPacket>(0)).Signer    = new Key32(publicKey);
                ((SignedPacketBase)c.ArgAt <IPacket>(0)).Signature = Ed25519.Sign(c.Arg <byte[]>(), expandedPrivateKey);
            });
            signingService.PublicKeys.ReturnsForAnyArgs(new IKey[] { new Key32(publicKey) });

            TransactionRegistryMemPool transactionRegistryMemPool = new TransactionRegistryMemPool(loggerService, identityKeyProvidersRegistry, statesRepository, hashCalculationsRepository);

            SortedList <ushort, RegistryRegisterBlock> expectedBlocks = new SortedList <ushort, RegistryRegisterBlock>();

            ulong[] heights = new ulong[] { 1, 2, 2, 5, 4, 3, 4, 3, 4, 5, 3 };

            HashSet <ulong> addedHeights = new HashSet <ulong>();
            ushort          order        = 0;

            for (ulong i = 0; i < (ulong)heights.Length; i++)
            {
                RegistryRegisterBlock transactionRegisterBlock = PacketsBuilder.GetTransactionRegisterBlock(synchronizationContext.LastBlockDescriptor.BlockHeight, 1, null,
                                                                                                            heights[i], PacketType.Transactional, BlockTypes.Transaction_TransferFunds, new byte[Globals.POW_HASH_SIZE], new byte[Globals.DEFAULT_HASH_SIZE], privateKey);

                RegistryRegisterBlockSerializer serializer = new RegistryRegisterBlockSerializer();
                serializer.Initialize(transactionRegisterBlock);
                serializer.SerializeBody();
                signingService.Sign(transactionRegisterBlock);
                serializer.SerializeFully();

                if (!addedHeights.Contains(heights[i]))
                {
                    expectedBlocks.Add(order++, transactionRegisterBlock);
                    addedHeights.Add(heights[i]);
                }

                transactionRegistryMemPool.EnqueueTransactionWitness(transactionRegisterBlock);
            }

            SortedList <ushort, RegistryRegisterBlock> actualBlocks = transactionRegistryMemPool.DequeueStateWitnessBulk();

            Assert.Equal(expectedBlocks.Count, actualBlocks.Count);
            for (ushort i = 0; i < (ushort)expectedBlocks.Count; i++)
            {
                Assert.Equal(expectedBlocks[i].BlockHeight, actualBlocks[i].BlockHeight);
            }
        }
Beispiel #20
0
        public void IssueAssetsBlockSerializerTest()
        {
            ulong syncBlockHeight = 1;
            uint  nonce           = 4;

            byte[] powHash     = BinaryHelper.GetPowHash(1234);
            ushort version     = 1;
            ulong  blockHeight = 9;

            byte[] body;

            ulong  uptodateFunds = 10001;
            ushort ownedNonBlindedAssetGroupsCount = 3, ownedBlindedAssetGroupsCount = 3;
            ushort ownedNonBlindedAssetIdsCount = 5, ownedAssetCommitmentsCount = 5;

            uint[]     nonBlindedGroupIds    = new uint[ownedNonBlindedAssetGroupsCount];
            byte[][][] ownedAssetIds         = new byte[ownedNonBlindedAssetGroupsCount][][];
            ulong[][]  ownedAssetAmounts     = new ulong[ownedNonBlindedAssetGroupsCount][];
            uint[]     blindedGroupIds       = new uint[ownedBlindedAssetGroupsCount];
            byte[][][] ownedAssetCommitments = new byte[ownedBlindedAssetGroupsCount][][];

            ushort issuanceNonBlindedGroupsCount = 2, issuanceBlindedGroupsCount = 2;
            ushort issuedNonBlindedAssetsCount = 10, issuedBlindedAssetsCount = 10;

            uint[]     issuanceNonBlindedGroupIds = new uint[issuanceNonBlindedGroupsCount], issuanceBlindedGroupIds = new uint[issuanceBlindedGroupsCount];
            byte[][][] issuedNonBlindedAssetIds   = new byte[issuanceNonBlindedGroupsCount][][];
            string[][] issuedNonBlindedAssetInfos = new string[issuanceNonBlindedGroupsCount][];

            byte[][][] issuedAssetCommitments  = new byte[issuanceBlindedGroupsCount][][];
            byte[][][] issuedBlindedAssetIds   = new byte[issuanceNonBlindedGroupsCount][][];
            string[][] issuedBlindedAssetInfos = new string[issuanceNonBlindedGroupsCount][];

            byte[][][] surjectionProofCommitments = new byte[issuanceBlindedGroupsCount][][];
            byte[][][] surjectionProofE           = new byte[issuanceBlindedGroupsCount][][];
            byte[][][] surjectionProofS           = new byte[issuanceBlindedGroupsCount][][];
            byte[][][] issuanceProofMask          = new byte[issuanceBlindedGroupsCount][][];

            for (int i = 0; i < issuanceNonBlindedGroupsCount; i++)
            {
                issuanceNonBlindedGroupIds[i] = (uint)i;
                issuedNonBlindedAssetIds[i]   = new byte[issuedNonBlindedAssetsCount][];
                issuedNonBlindedAssetInfos[i] = new string[issuedNonBlindedAssetsCount];

                for (int j = 0; j < issuedNonBlindedAssetsCount; j++)
                {
                    issuedNonBlindedAssetIds[i][j]   = ConfidentialAssetsHelper.GetRandomSeed();
                    issuedNonBlindedAssetInfos[i][j] = $"Issued Asset #{i}_{j}";
                }
            }

            for (int i = 0; i < issuanceBlindedGroupsCount; i++)
            {
                issuanceBlindedGroupIds[i]    = (uint)i + 10;
                issuedAssetCommitments[i]     = new byte[issuedBlindedAssetsCount][];
                issuedBlindedAssetIds[i]      = new byte[issuedBlindedAssetsCount][];
                issuedBlindedAssetInfos[i]    = new string[issuedBlindedAssetsCount];
                surjectionProofCommitments[i] = new byte[issuedBlindedAssetsCount][];
                surjectionProofE[i]           = new byte[issuedBlindedAssetsCount][];
                surjectionProofS[i]           = new byte[issuedBlindedAssetsCount][];
                issuanceProofMask[i]          = new byte[issuedBlindedAssetsCount][];

                for (int j = 0; j < issuedBlindedAssetsCount; j++)
                {
                    issuedAssetCommitments[i][j]     = ConfidentialAssetsHelper.GetRandomSeed();
                    issuedBlindedAssetIds[i][j]      = ConfidentialAssetsHelper.GetRandomSeed();
                    issuedBlindedAssetInfos[i][j]    = $"Issued Blinded Asset #{i}_{j}";
                    surjectionProofCommitments[i][j] = ConfidentialAssetsHelper.GetRandomSeed();
                    surjectionProofE[i][j]           = ConfidentialAssetsHelper.GetRandomSeed();
                    surjectionProofS[i][j]           = ConfidentialAssetsHelper.GetRandomSeed();
                    issuanceProofMask[i][j]          = ConfidentialAssetsHelper.GetRandomSeed();
                }
            }

            string issuanceInfo = "Issuance Info";

            Random random = new Random();

            for (int i = 0; i < ownedNonBlindedAssetGroupsCount; i++)
            {
                nonBlindedGroupIds[i] = (uint)i;
                ownedAssetIds[i]      = new byte[ownedNonBlindedAssetIdsCount][];
                ownedAssetAmounts[i]  = new ulong[ownedNonBlindedAssetIdsCount];

                for (int j = 0; j < ownedNonBlindedAssetIdsCount; j++)
                {
                    ownedAssetIds[i][j]     = ConfidentialAssetsHelper.GetRandomSeed();
                    ownedAssetAmounts[i][j] = (ulong)random.Next();
                }
            }

            for (int i = 0; i < ownedBlindedAssetGroupsCount; i++)
            {
                blindedGroupIds[i]       = (uint)i + 10;
                ownedAssetCommitments[i] = new byte[ownedAssetCommitmentsCount][];

                for (int j = 0; j < ownedAssetCommitmentsCount; j++)
                {
                    ownedAssetCommitments[i][j] = ConfidentialAssetsHelper.GetRandomSeed();
                }
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(uptodateFunds);

                    bw.Write(issuanceNonBlindedGroupsCount);
                    bw.Write(issuanceBlindedGroupsCount);

                    for (int i = 0; i < issuanceNonBlindedGroupsCount; i++)
                    {
                        bw.Write(issuanceNonBlindedGroupIds[i]);
                        bw.Write(issuedNonBlindedAssetsCount);

                        for (int j = 0; j < issuedNonBlindedAssetsCount; j++)
                        {
                            bw.Write(issuedNonBlindedAssetIds[i][j]);
                            byte strLen = (byte)issuedNonBlindedAssetInfos[i][j].Length;
                            bw.Write(strLen);
                            bw.Write(Encoding.ASCII.GetBytes(issuedNonBlindedAssetInfos[i][j]));
                        }
                    }

                    for (int i = 0; i < issuanceBlindedGroupsCount; i++)
                    {
                        bw.Write(issuanceBlindedGroupIds[i]);
                        bw.Write(issuedBlindedAssetsCount);

                        for (int j = 0; j < issuedBlindedAssetsCount; j++)
                        {
                            bw.Write(issuedAssetCommitments[i][j]);
                        }

                        for (int j = 0; j < issuedBlindedAssetsCount; j++)
                        {
                            bw.Write(issuedBlindedAssetIds[i][j]);
                            byte strLen = (byte)issuedBlindedAssetInfos[i][j].Length;
                            bw.Write(strLen);
                            bw.Write(Encoding.ASCII.GetBytes(issuedBlindedAssetInfos[i][j]));
                        }

                        for (int j = 0; j < issuedBlindedAssetsCount; j++)
                        {
                            bw.Write((ushort)1);
                            bw.Write(surjectionProofCommitments[i][j]);
                            bw.Write(surjectionProofE[i][j]);
                            bw.Write(surjectionProofS[i][j]);
                            bw.Write(issuanceProofMask[i][j]);
                        }
                    }

                    bw.Write((byte)issuanceInfo.Length);
                    bw.Write(Encoding.ASCII.GetBytes(issuanceInfo));

                    bw.Write(ownedNonBlindedAssetGroupsCount);
                    bw.Write(ownedBlindedAssetGroupsCount);

                    for (int i = 0; i < ownedNonBlindedAssetGroupsCount; i++)
                    {
                        bw.Write(nonBlindedGroupIds[i]);
                        bw.Write(ownedNonBlindedAssetIdsCount);

                        for (int j = 0; j < ownedNonBlindedAssetIdsCount; j++)
                        {
                            bw.Write(ownedAssetIds[i][j]);
                        }

                        for (int j = 0; j < ownedNonBlindedAssetIdsCount; j++)
                        {
                            bw.Write(ownedAssetAmounts[i][j]);
                        }
                    }

                    for (int i = 0; i < ownedBlindedAssetGroupsCount; i++)
                    {
                        bw.Write(blindedGroupIds[i]);
                        bw.Write(ownedAssetCommitmentsCount);

                        for (int j = 0; j < ownedAssetCommitmentsCount; j++)
                        {
                            bw.Write(ownedAssetCommitments[i][j]);
                        }
                    }
                }

                body = ms.ToArray();
            }

            byte[] expectedPacket = BinaryHelper.GetSignedPacket(PacketType.Transactional, syncBlockHeight, nonce, powHash, version,
                                                                 BlockTypes.Transaction_IssueGroupedAssets, blockHeight, null, body, _privateKey, out byte[] expectedSignature);

            AssetsIssuanceGroup[] assetsIssuanceGroups = new AssetsIssuanceGroup[issuanceNonBlindedGroupsCount];
            for (int i = 0; i < issuanceNonBlindedGroupsCount; i++)
            {
                assetsIssuanceGroups[i] = new AssetsIssuanceGroup
                {
                    GroupId        = issuanceNonBlindedGroupIds[i],
                    AssetIssuances = new AssetIssuance[issuedNonBlindedAssetsCount]
                };

                for (int j = 0; j < issuedNonBlindedAssetsCount; j++)
                {
                    assetsIssuanceGroups[i].AssetIssuances[j] = new AssetIssuance
                    {
                        AssetId         = issuedNonBlindedAssetIds[i][j],
                        IssuedAssetInfo = issuedNonBlindedAssetInfos[i][j]
                    };
                }
            }

            BlindedAssetsIssuanceGroup[] blindedAssetsIssuanceGroups = new BlindedAssetsIssuanceGroup[issuanceBlindedGroupsCount];
            for (int i = 0; i < issuanceBlindedGroupsCount; i++)
            {
                blindedAssetsIssuanceGroups[i] = new BlindedAssetsIssuanceGroup
                {
                    GroupId          = issuanceBlindedGroupIds[i],
                    AssetCommitments = issuedAssetCommitments[i],
                    AssetIssuances   = new AssetIssuance[issuedBlindedAssetsCount],
                    IssuanceProofs   = new IssuanceProof[issuedBlindedAssetsCount]
                };

                for (int j = 0; j < issuedBlindedAssetsCount; j++)
                {
                    blindedAssetsIssuanceGroups[i].AssetIssuances[j] = new AssetIssuance
                    {
                        AssetId         = issuedBlindedAssetIds[i][j],
                        IssuedAssetInfo = issuedBlindedAssetInfos[i][j]
                    };

                    blindedAssetsIssuanceGroups[i].IssuanceProofs[j] = new IssuanceProof
                    {
                        SurjectionProof = new SurjectionProof
                        {
                            AssetCommitments = new byte[][] { surjectionProofCommitments[i][j] },
                            Rs = new BorromeanRingSignature
                            {
                                E = surjectionProofE[i][j],
                                S = new byte[][] { surjectionProofS[i][j] }
                            }
                        },
                        Mask = issuanceProofMask[i][j]
                    };
                }
            }

            AssetsGroup[] assetsGroups = new AssetsGroup[ownedNonBlindedAssetGroupsCount];
            for (int i = 0; i < ownedNonBlindedAssetGroupsCount; i++)
            {
                assetsGroups[i] = new AssetsGroup
                {
                    GroupId      = nonBlindedGroupIds[i],
                    AssetIds     = ownedAssetIds[i],
                    AssetAmounts = ownedAssetAmounts[i]
                };
            }

            BlindedAssetsGroup[] blindedAssetsGroups = new BlindedAssetsGroup[ownedBlindedAssetGroupsCount];
            for (int i = 0; i < ownedBlindedAssetGroupsCount; i++)
            {
                blindedAssetsGroups[i] = new BlindedAssetsGroup
                {
                    GroupId          = blindedGroupIds[i],
                    AssetCommitments = ownedAssetCommitments[i]
                };
            }

            IssueGroupedAssets block = new IssueGroupedAssets
            {
                SyncBlockHeight             = syncBlockHeight,
                Nonce                       = nonce,
                PowHash                     = powHash,
                BlockHeight                 = blockHeight,
                UptodateFunds               = uptodateFunds,
                AssetsIssuanceGroups        = assetsIssuanceGroups,
                BlindedAssetsIssuanceGroups = blindedAssetsIssuanceGroups,
                AssetsGroups                = assetsGroups,
                BlindedAssetsGroups         = blindedAssetsGroups,
                IssuanceInfo                = issuanceInfo
            };

            IssueAssetsSerializer serializer = new IssueAssetsSerializer();

            serializer.Initialize(block);
            serializer.SerializeBody();
            _signingService.Sign(block);

            byte[] actualPacket = serializer.GetBytes();

            Assert.Equal(expectedPacket, actualPacket);
        }
Beispiel #21
0
        public void TransferAssetToUtxoSerializerTest()
        {
            ulong syncBlockHeight = 1;
            uint  nonce           = 4;

            byte[] powHash       = BinaryHelper.GetPowHash(1234);
            ushort version       = 1;
            ulong  blockHeight   = 9;
            ulong  uptodateFunds = 10002;

            byte[] destinationKey = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] transactionKey = ConfidentialAssetsHelper.GetRandomSeed();

            byte[] body;

            byte[] assetCommitment = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] mask            = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] maskedAssetId   = ConfidentialAssetsHelper.GetRandomSeed();

            ushort assetCommitmentsCount = 10;

            byte[][] assetCommitments = new byte[assetCommitmentsCount][];
            byte[]   e = ConfidentialAssetsHelper.GetRandomSeed();
            byte[][] s = new byte[assetCommitmentsCount][];

            for (int i = 0; i < assetCommitmentsCount; i++)
            {
                assetCommitments[i] = ConfidentialAssetsHelper.GetRandomSeed();
                s[i] = ConfidentialAssetsHelper.GetRandomSeed();
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(uptodateFunds);
                    bw.Write(destinationKey);
                    bw.Write(transactionKey);
                    bw.Write(assetCommitment);
                    bw.Write(maskedAssetId);
                    bw.Write(mask);
                    bw.Write(assetCommitmentsCount);
                    for (int i = 0; i < assetCommitmentsCount; i++)
                    {
                        bw.Write(assetCommitments[i]);
                    }
                    bw.Write(e);
                    for (int i = 0; i < assetCommitmentsCount; i++)
                    {
                        bw.Write(s[i]);
                    }
                }

                body = ms.ToArray();
            }

            byte[] expectedPacket = BinaryHelper.GetSignedPacket(PacketType.Transactional, syncBlockHeight, nonce, powHash, version,
                                                                 BlockTypes.Transaction_TransferAssetToUtxo, blockHeight, null, body, _privateKey, out byte[] expectedSignature);

            TransferAssetToUtxo packet = new TransferAssetToUtxo
            {
                SyncBlockHeight      = syncBlockHeight,
                Nonce                = nonce,
                PowHash              = powHash,
                BlockHeight          = blockHeight,
                UptodateFunds        = uptodateFunds,
                DestinationKey       = destinationKey,
                TransactionPublicKey = transactionKey,
                TransferredAsset     = new EncryptedAsset
                {
                    AssetCommitment = assetCommitment,
                    EcdhTuple       = new EcdhTupleCA
                    {
                        Mask    = mask,
                        AssetId = maskedAssetId
                    }
                },
                SurjectionProof = new SurjectionProof
                {
                    AssetCommitments = assetCommitments,
                    Rs = new BorromeanRingSignature
                    {
                        E = e,
                        S = s
                    }
                }
            };

            TransferAssetToUtxoSerializer serializer = new TransferAssetToUtxoSerializer();

            serializer.Initialize(packet);
            serializer.SerializeBody();
            _signingService.Sign(packet);

            byte[] actualPacket = serializer.GetBytes();

            Assert.Equal(expectedPacket, actualPacket);
        }
Beispiel #22
0
        public void RegistryFullBlockParserTest()
        {
            IBlockParser blockParser = new RegistryRegisterBlockParser(_identityKeyProvidersRegistry);

            _blockParsersRepository.GetInstance(0).ReturnsForAnyArgs(blockParser);

            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_TransferFunds;

            byte[] body;

            ushort expectedCount = 1;

            byte[] expectedShortBlockHash;

            RegistryRegisterBlock[]            stateWitnesses = new RegistryRegisterBlock[expectedCount];
            RegistryRegisterUtxoConfidential[] utxoWitnesses  = new RegistryRegisterUtxoConfidential[expectedCount];

            for (ushort i = 0; i < expectedCount; i++)
            {
                RegistryRegisterBlock registryRegisterBlock = new RegistryRegisterBlock
                {
                    SyncBlockHeight      = syncBlockHeight,
                    Nonce                = nonce + i,
                    PowHash              = BinaryHelper.GetPowHash(1234 + i),
                    BlockHeight          = blockHeight,
                    ReferencedPacketType = expectedReferencedPacketType,
                    ReferencedBlockType  = expectedReferencedBlockType,
                    ReferencedBodyHash   = BinaryHelper.GetDefaultHash(473826643 + i),
                    ReferencedTarget     = BinaryHelper.GetDefaultHash(BinaryHelper.GetRandomPublicKey())
                };

                RegistryRegisterBlockSerializer serializer1 = new RegistryRegisterBlockSerializer();
                serializer1.Initialize(registryRegisterBlock);
                serializer1.SerializeBody();
                _signingService.Sign(registryRegisterBlock);
                serializer1.SerializeFully();

                stateWitnesses[i] = registryRegisterBlock;

                RegistryRegisterUtxoConfidential registryRegisterUtxoConfidentialBlock = new RegistryRegisterUtxoConfidential
                {
                    SyncBlockHeight      = syncBlockHeight,
                    Nonce                = nonce + i,
                    PowHash              = BinaryHelper.GetPowHash(1234 + i),
                    KeyImage             = new Key32(ConfidentialAssetsHelper.GetRandomSeed()),
                    ReferencedPacketType = expectedReferencedPacketType,
                    ReferencedBlockType  = expectedReferencedBlockType,
                    ReferencedBodyHash   = BinaryHelper.GetDefaultHash(473826643 + i),
                    DestinationKey       = ConfidentialAssetsHelper.GetRandomSeed(),
                    DestinationKey2      = ConfidentialAssetsHelper.GetRandomSeed(),
                    TransactionPublicKey = ConfidentialAssetsHelper.GetRandomSeed(),
                    PublicKeys           = new Key32[] { new Key32(ConfidentialAssetsHelper.GetRandomSeed()), new Key32(ConfidentialAssetsHelper.GetRandomSeed()), new Key32(ConfidentialAssetsHelper.GetRandomSeed()) },
                    Signatures           = new RingSignature[]
                    {
                        new RingSignature {
                            R = ConfidentialAssetsHelper.GetRandomSeed(), C = ConfidentialAssetsHelper.GetRandomSeed()
                        },
                        new RingSignature {
                            R = ConfidentialAssetsHelper.GetRandomSeed(), C = ConfidentialAssetsHelper.GetRandomSeed()
                        },
                        new RingSignature {
                            R = ConfidentialAssetsHelper.GetRandomSeed(), C = ConfidentialAssetsHelper.GetRandomSeed()
                        }
                    }
                };

                RegistryRegisterUtxoConfidentialBlockSerializer serializer2 = new RegistryRegisterUtxoConfidentialBlockSerializer();
                serializer2.Initialize(registryRegisterUtxoConfidentialBlock);
                serializer2.SerializeFully();

                utxoWitnesses[i] = registryRegisterUtxoConfidentialBlock;
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write((ushort)stateWitnesses.Length);
                    bw.Write((ushort)utxoWitnesses.Length);

                    foreach (RegistryRegisterBlock witness in stateWitnesses)
                    {
                        bw.Write(witness.RawData.ToArray());
                    }

                    foreach (RegistryRegisterUtxoConfidential witness in utxoWitnesses)
                    {
                        bw.Write(witness.RawData.ToArray());
                    }

                    expectedShortBlockHash = BinaryHelper.GetDefaultHash(1111);
                    bw.Write(expectedShortBlockHash);
                }

                body = ms.ToArray();
            }

            byte[] packet = BinaryHelper.GetSignedPacket(
                PacketType.Registry,
                syncBlockHeight,
                nonce, powHash, version,
                BlockTypes.Registry_FullBlock, blockHeight, prevHash, body, _privateKey, out byte[] expectedSignature);

            RegistryFullBlockParser registryFullBlockParser = new RegistryFullBlockParser(_identityKeyProvidersRegistry);
            RegistryFullBlock       block = (RegistryFullBlock)registryFullBlockParser.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);

            for (int i = 0; i < expectedCount; i++)
            {
                RegistryRegisterBlock registryRegisterBlock = block.StateWitnesses[i];
                Assert.Equal(stateWitnesses[i].PacketType, registryRegisterBlock.PacketType);
                Assert.Equal(stateWitnesses[i].SyncBlockHeight, registryRegisterBlock.SyncBlockHeight);
                Assert.Equal(stateWitnesses[i].Nonce, registryRegisterBlock.Nonce);
                Assert.Equal(stateWitnesses[i].PowHash, registryRegisterBlock.PowHash);
                Assert.Equal(stateWitnesses[i].BlockHeight, registryRegisterBlock.BlockHeight);
                Assert.Equal(stateWitnesses[i].BlockType, registryRegisterBlock.BlockType);
                Assert.Equal(stateWitnesses[i].ReferencedPacketType, registryRegisterBlock.ReferencedPacketType);
                Assert.Equal(stateWitnesses[i].ReferencedBlockType, registryRegisterBlock.ReferencedBlockType);
                Assert.Equal(stateWitnesses[i].ReferencedBodyHash, registryRegisterBlock.ReferencedBodyHash);
                Assert.Equal(stateWitnesses[i].ReferencedTarget, registryRegisterBlock.ReferencedTarget);
                Assert.Equal(stateWitnesses[i].Signature.ToArray(), registryRegisterBlock.Signature.ToArray());
                Assert.Equal(stateWitnesses[i].Signer, registryRegisterBlock.Signer);

                RegistryRegisterUtxoConfidential registryRegisterUtxoConfidentialBlock = block.UtxoWitnesses[i];
                Assert.Equal(utxoWitnesses[i].PacketType, registryRegisterUtxoConfidentialBlock.PacketType);
                Assert.Equal(utxoWitnesses[i].SyncBlockHeight, registryRegisterUtxoConfidentialBlock.SyncBlockHeight);
                Assert.Equal(utxoWitnesses[i].Nonce, registryRegisterUtxoConfidentialBlock.Nonce);
                Assert.Equal(utxoWitnesses[i].PowHash, registryRegisterUtxoConfidentialBlock.PowHash);
                Assert.Equal(utxoWitnesses[i].KeyImage, registryRegisterUtxoConfidentialBlock.KeyImage);
                Assert.Equal(utxoWitnesses[i].BlockType, registryRegisterUtxoConfidentialBlock.BlockType);
                Assert.Equal(utxoWitnesses[i].ReferencedPacketType, registryRegisterUtxoConfidentialBlock.ReferencedPacketType);
                Assert.Equal(utxoWitnesses[i].ReferencedBlockType, registryRegisterUtxoConfidentialBlock.ReferencedBlockType);
                Assert.Equal(utxoWitnesses[i].DestinationKey2, registryRegisterUtxoConfidentialBlock.DestinationKey2);
                Assert.Equal(utxoWitnesses[i].ReferencedBodyHash, registryRegisterUtxoConfidentialBlock.ReferencedBodyHash);
                Assert.Equal(utxoWitnesses[i].DestinationKey, registryRegisterUtxoConfidentialBlock.DestinationKey);
            }

            Assert.Equal(expectedShortBlockHash, block.ShortBlockHash);

            Assert.Equal(_publicKey, block.Signer.Value.ToArray());
            Assert.Equal(expectedSignature, block.Signature.ToArray());
        }
Beispiel #23
0
        public void RegistryShortBlockParserTest()
        {
            ulong syncBlockHeight = 1;
            uint  nonce           = 4;

            byte[] powHash     = BinaryHelper.GetPowHash(1234);
            ushort version     = 1;
            ulong  blockHeight = 9;

            byte[] prevHash = null;

            byte[] body;

            ushort expectedCount = 10;

            Random random = new Random();

            WitnessStateKey[] witnessStateKeys = new WitnessStateKey[expectedCount];
            WitnessUtxoKey[]  witnessUtxoKeys  = new WitnessUtxoKey[expectedCount];
            for (ushort i = 0; i < expectedCount; i++)
            {
                witnessStateKeys[i] = new WitnessStateKey {
                    PublicKey = new Key32(ConfidentialAssetsHelper.GetRandomSeed()), Height = (ulong)random.Next(0, int.MaxValue)
                };
                witnessUtxoKeys[i] = new WitnessUtxoKey {
                    KeyImage = new Key32(ConfidentialAssetsHelper.GetRandomSeed())
                };
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write((ushort)witnessStateKeys.Length);
                    bw.Write((ushort)witnessUtxoKeys.Length);

                    foreach (WitnessStateKey witnessStateKey in witnessStateKeys)
                    {
                        bw.Write(witnessStateKey.PublicKey.Value.ToArray());
                        bw.Write(witnessStateKey.Height);
                    }

                    foreach (WitnessUtxoKey witnessUtxoKey in witnessUtxoKeys)
                    {
                        bw.Write(witnessUtxoKey.KeyImage.Value.ToArray());
                    }
                }

                body = ms.ToArray();
            }

            byte[] packet = BinaryHelper.GetSignedPacket(
                PacketType.Registry,
                syncBlockHeight,
                nonce, powHash, version,
                BlockTypes.Registry_ShortBlock, blockHeight, prevHash, body, _privateKey, out byte[] expectedSignature);

            RegistryShortBlockParser registryFullBlockParser = new RegistryShortBlockParser(_identityKeyProvidersRegistry);
            RegistryShortBlock       block = (RegistryShortBlock)registryFullBlockParser.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);

            for (int i = 0; i < witnessStateKeys.Length; i++)
            {
                Assert.Equal(witnessStateKeys[i].PublicKey, block.WitnessStateKeys[i].PublicKey);
                Assert.Equal(witnessStateKeys[i].Height, block.WitnessStateKeys[i].Height);
            }

            for (int i = 0; i < witnessUtxoKeys.Length; i++)
            {
                Assert.Equal(witnessUtxoKeys[i].KeyImage, block.WitnessUtxoKeys[i].KeyImage);
            }

            Assert.Equal(_publicKey, block.Signer.Value.ToArray());
            Assert.Equal(expectedSignature, block.Signature.ToArray());
        }
Beispiel #24
0
        public static byte[] GetRandomPublicKey()
        {
            byte[] seed = ConfidentialAssetsHelper.GetRandomSeed();

            return(Ed25519.PublicKeyFromSeed(seed));
        }
Beispiel #25
0
        public void RegistryRegisterUtxoConfidentialBlockParserTest()
        {
            ulong syncBlockHeight = 1;
            uint  nonce           = 4;

            byte[] powHash = BinaryHelper.GetPowHash(1234);
            ushort version = 1;

            byte[] keyImage             = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] destinationKey       = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] transactionPublicKey = ConfidentialAssetsHelper.GetRandomSeed();

            PacketType expectedReferencedPacketType = PacketType.Transactional;
            ushort     expectedReferencedBlockType  = BlockTypes.Transaction_TransferFunds;

            byte[] destinationKey2            = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] expectedReferencedBodyHash = BinaryHelper.GetDefaultHash(473826643);

            int ringSize    = 3;
            int outputIndex = 0;

            byte[][] secretKeys = new byte[ringSize][];
            byte[][] pubkeys    = new byte[ringSize][];

            byte[] body;

            for (int i = 0; i < ringSize; i++)
            {
                pubkeys[i] = BinaryHelper.GetRandomPublicKey(out secretKeys[i]);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write((ushort)expectedReferencedPacketType);
                    bw.Write(expectedReferencedBlockType);
                    bw.Write(expectedReferencedBodyHash);
                }

                body = ms.ToArray();
            }

            byte[] packet = BinaryHelper.GetUtxoConfidentialPacket(
                PacketType.Registry, syncBlockHeight, nonce, powHash, version,
                BlockTypes.Registry_RegisterUtxoConfidential, keyImage, destinationKey, destinationKey2, transactionPublicKey, body, pubkeys, secretKeys[outputIndex], outputIndex, out RingSignature[] expectedSignatures);

            RegistryRegisterUtxoConfidentialBlockParser registryRegisterBlockParser = new RegistryRegisterUtxoConfidentialBlockParser(_identityKeyProvidersRegistry);
            RegistryRegisterUtxoConfidential            block = (RegistryRegisterUtxoConfidential)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(expectedReferencedPacketType, block.ReferencedPacketType);
            Assert.Equal(expectedReferencedBlockType, block.ReferencedBlockType);
            Assert.Equal(destinationKey2, block.DestinationKey2);
            Assert.Equal(expectedReferencedBodyHash, block.ReferencedBodyHash);
            Assert.Equal(new Key32(keyImage), block.KeyImage);
            Assert.Equal(destinationKey, block.DestinationKey);
            Assert.Equal(transactionPublicKey, block.TransactionPublicKey);
        }
Beispiel #26
0
        public static byte[] GetRandomPublicKey(out byte[] secretKey)
        {
            secretKey = ConfidentialAssetsHelper.GetRandomSeed();

            return(Ed25519.PublicKeyFromSeed(secretKey));
        }
Beispiel #27
0
        public void TransferGroupedAssetsToUtxoBlockSerializerTest()
        {
            ulong syncBlockHeight = 1;
            uint  nonce           = 4;

            byte[] powHash     = BinaryHelper.GetPowHash(1234);
            ushort version     = 1;
            ulong  blockHeight = 9;

            byte[] body;

            ulong uptodateFunds = 10001;

            byte[] transactionPublicKey = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] destinationKey       = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] assetId                  = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] assetCommitment          = ConfidentialAssetsHelper.GetRandomSeed();
            ushort blindedAssetsGroupsCount = 2;
            ushort assetsCount              = 10;

            uint[]     groupIds = new uint[blindedAssetsGroupsCount];
            byte[][][] ownedAssetCommitments     = new byte[blindedAssetsGroupsCount][][];
            byte[][]   surjectionAssetCommitment = new byte[blindedAssetsGroupsCount * assetsCount + 1][];
            byte[][]   e    = new byte[blindedAssetsGroupsCount * assetsCount + 1][];
            byte[][][] s    = new byte[blindedAssetsGroupsCount * assetsCount + 1][][];
            byte[]     mask = ConfidentialAssetsHelper.GetRandomSeed();

            Random random = new Random();

            for (int i = 0; i < blindedAssetsGroupsCount; i++)
            {
                groupIds[i] = (uint)i;
                ownedAssetCommitments[i] = new byte[assetsCount][];
                for (int j = 0; j < assetsCount; j++)
                {
                    ownedAssetCommitments[i][j] = ConfidentialAssetsHelper.GetRandomSeed();
                }
            }

            for (int i = 0; i < blindedAssetsGroupsCount * assetsCount + 1; i++)
            {
                surjectionAssetCommitment[i] = ConfidentialAssetsHelper.GetRandomSeed();
                e[i] = ConfidentialAssetsHelper.GetRandomSeed();
                s[i] = new byte[blindedAssetsGroupsCount * assetsCount + 1][];
                for (int j = 0; j < blindedAssetsGroupsCount * assetsCount + 1; j++)
                {
                    s[i][j] = ConfidentialAssetsHelper.GetRandomSeed();
                }
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(uptodateFunds);

                    bw.Write(destinationKey);
                    bw.Write(transactionPublicKey);

                    // TransferredAsset
                    // ==============================
                    bw.Write(assetCommitment);
                    bw.Write(assetId);
                    bw.Write(mask);
                    // ==============================

                    bw.Write(blindedAssetsGroupsCount);
                    for (int i = 0; i < blindedAssetsGroupsCount; i++)
                    {
                        bw.Write(groupIds[i]);
                        bw.Write(assetsCount);
                        for (int j = 0; j < assetsCount; j++)
                        {
                            bw.Write(ownedAssetCommitments[i][j]);
                        }
                    }

                    for (int i = 0; i < blindedAssetsGroupsCount * assetsCount + 1; i++)
                    {
                        bw.Write(surjectionAssetCommitment[i]);
                        bw.Write(e[i]);
                        bw.Write((ushort)(blindedAssetsGroupsCount * assetsCount + 1));

                        for (int j = 0; j < blindedAssetsGroupsCount * assetsCount + 1; j++)
                        {
                            bw.Write(s[i][j]);
                        }
                    }
                }

                body = ms.ToArray();
            }

            byte[] expectedPacket = BinaryHelper.GetSignedPacket(PacketType.Transactional, syncBlockHeight, nonce, powHash, version,
                                                                 BlockTypes.Transaction_TransferGroupedAssetsToUtxo, blockHeight, null, body, _privateKey, out byte[] expectedSignature);

            EncryptedAsset transferredAsset = new EncryptedAsset
            {
                AssetCommitment = assetCommitment,
                EcdhTuple       = new EcdhTupleCA
                {
                    AssetId = assetId,
                    Mask    = mask
                }
            };

            BlindedAssetsGroup[] blindedAssetsGroups = new BlindedAssetsGroup[blindedAssetsGroupsCount];
            for (int i = 0; i < blindedAssetsGroupsCount; i++)
            {
                blindedAssetsGroups[i] = new BlindedAssetsGroup
                {
                    GroupId          = groupIds[i],
                    AssetCommitments = ownedAssetCommitments[i]
                };
            }

            InversedSurjectionProof[] inversedSurjectionProofs = new InversedSurjectionProof[blindedAssetsGroupsCount * assetsCount + 1];
            for (int i = 0; i < blindedAssetsGroupsCount * assetsCount + 1; i++)
            {
                inversedSurjectionProofs[i] = new InversedSurjectionProof
                {
                    AssetCommitment = surjectionAssetCommitment[i],
                    Rs = new BorromeanRingSignature
                    {
                        E = e[i],
                        S = s[i]
                    }
                };
            }

            TransferGroupedAssetToUtxo block = new TransferGroupedAssetToUtxo
            {
                SyncBlockHeight          = syncBlockHeight,
                Nonce                    = nonce,
                PowHash                  = powHash,
                BlockHeight              = blockHeight,
                UptodateFunds            = uptodateFunds,
                DestinationKey           = destinationKey,
                TransactionPublicKey     = transactionPublicKey,
                TransferredAsset         = transferredAsset,
                BlindedAssetsGroups      = blindedAssetsGroups,
                InversedSurjectionProofs = inversedSurjectionProofs
            };

            TransferGroupedAssetsToUtxoSerializer serializer = new TransferGroupedAssetsToUtxoSerializer();

            serializer.Initialize(block);
            serializer.SerializeBody();
            _signingService.Sign(block);

            byte[] actualPacket = serializer.GetBytes();

            Assert.Equal(expectedPacket, actualPacket);
        }
Beispiel #28
0
        public void IssueBlindedAssetSerializerTest()
        {
            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[] 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(keyImage);
                    bw.Write(c);
                    bw.Write(r);
                }

                body = ms.ToArray();
            }

            byte[] expectedPacket = BinaryHelper.GetSignedPacket(PacketType.Transactional, syncBlockHeight, nonce, powHash, version,
                                                                 BlockTypes.Transaction_IssueBlindedAsset, blockHeight, null, body, _privateKey, out byte[] expectedSignature);

            IssueBlindedAsset issueBlindedAsset = new IssueBlindedAsset
            {
                SyncBlockHeight  = syncBlockHeight,
                Nonce            = nonce,
                PowHash          = powHash,
                BlockHeight      = blockHeight,
                GroupId          = groupId,
                UptodateFunds    = uptodateFunds,
                AssetCommitment  = assetCommitment,
                KeyImage         = keyImage,
                UniquencessProof = new RingSignature
                {
                    C = c,
                    R = r
                }
            };

            IssueBlindedAssetSerializer serializer = new IssueBlindedAssetSerializer();

            serializer.Initialize(issueBlindedAsset);
            serializer.SerializeBody();
            _signingService.Sign(issueBlindedAsset);

            byte[] actualPacket = serializer.GetBytes();

            Assert.Equal(expectedPacket, actualPacket);
        }
Beispiel #29
0
        public void SynchronizationConfirmedBlockParserTest()
        {
            byte signersCount = 10;

            byte[] body;
            ushort round           = 1;
            ulong  syncBlockHeight = 1;
            uint   nonce           = 4;
            ushort version         = 1;
            ulong  blockHeight     = 9;

            byte[][] expectedSignerPKs        = new byte[signersCount][];
            byte[][] expectedSignerSignatures = new byte[signersCount][];

            DateTime expectedDateTime = DateTime.Now;

            byte[] powHash  = BinaryHelper.GetPowHash(1234);
            byte[] prevHash = BinaryHelper.GetDefaultHash(1234);

            for (int i = 0; i < signersCount; i++)
            {
                byte[] privateSignerKey = ConfidentialAssetsHelper.GetRandomSeed();
                Ed25519.KeyPairFromSeed(out byte[] publicSignerKey, out byte[] expandedSignerKey, privateSignerKey);

                expectedSignerPKs[i] = publicSignerKey;

                byte[] roundBytes = BitConverter.GetBytes(round);

                byte[] signerSignature = Ed25519.Sign(roundBytes, expandedSignerKey);

                expectedSignerSignatures[i] = signerSignature;
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(expectedDateTime.ToBinary());
                    bw.Write(round);
                    bw.Write(signersCount);

                    for (int i = 0; i < signersCount; i++)
                    {
                        bw.Write(expectedSignerPKs[i]);
                        bw.Write(expectedSignerSignatures[i]);
                    }
                }

                body = ms.ToArray();
            }

            byte[] packet = BinaryHelper.GetSignedPacket(
                PacketType.Synchronization,
                syncBlockHeight,
                nonce, powHash, version,
                BlockTypes.Synchronization_ConfirmedBlock, blockHeight, prevHash, body, _privateKey, out byte[] expectedSignature);
            string packetExpectedString = packet.ToHexString();

            SynchronizationConfirmedBlockParser synchronizationConfirmedBlockParser = new SynchronizationConfirmedBlockParser(_identityKeyProvidersRegistry);
            SynchronizationConfirmedBlock       block = (SynchronizationConfirmedBlock)synchronizationConfirmedBlockParser.Parse(packet);

            string packetActualString = block.RawData.ToHexString();

            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(prevHash, block.HashPrev);
            Assert.Equal(expectedDateTime, block.ReportedTime);
            Assert.Equal(round, block.Round);

            for (int i = 0; i < signersCount; i++)
            {
                Assert.Equal(expectedSignerPKs[i], block.PublicKeys[i]);
                Assert.Equal(expectedSignerSignatures[i], block.Signatures[i]);
            }

            Assert.Equal(_publicKey, block.Signer.Value.ToArray());
            Assert.Equal(expectedSignature, block.Signature.ToArray());
        }
Beispiel #30
0
        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());
        }