예제 #1
0
 public IntegrationInfo(
     BlockchainInfo blockchain,
     IReadOnlyDictionary <string, DependencyInfo> dependencies)
 {
     Blockchain   = blockchain ?? throw new ArgumentNullException(nameof(blockchain));
     Dependencies = dependencies ?? throw new ArgumentNullException(nameof(dependencies));
 }
예제 #2
0
        public async Task Get_integration_info()
        {
            //ARRANGE
            var blockchainInfo = new BlockchainInfo(123, DateTime.UtcNow);
            var dependencies   = new Dictionary <DependencyName, DependencyInfo>()
            {
                { "dependency", new DependencyInfo(new Semver("1.0.0"), new Semver("1.0.0")) }
            };

            var client = PrepareClient <AppSettings>((options) =>
            {
                var aggregator = CreateMocksAndSetupFactories(options);

                options.IntegrationName = $"{nameof(TransactionExecutorClientTests)}+{nameof(Get_integration_info)}";
                aggregator.BlockchainInfoProvider.Setup(x => x.GetInfoAsync()).ReturnsAsync(blockchainInfo);
                aggregator.DependenciesInfoProvider.Setup(x => x.GetInfoAsync()).ReturnsAsync(dependencies);
                aggregator.HealthProvider.Setup(x => x.GetDiseaseAsync()).ReturnsAsync(Disease);
            });

            //ACT
            var result = await client.GetIntegrationInfoAsync();

            //ASSERT
            var(dependencyName, dependencyInfo) = dependencies.First();
            Assert.True(result != null);
            Assert.True(result.Blockchain.LatestBlockMoment == blockchainInfo.LatestBlockMoment);
            Assert.True(result.Blockchain.LatestBlockNumber == blockchainInfo.LatestBlockNumber);
            Assert.True(result.Dependencies[dependencyName].LatestAvailableVersion.Equals(dependencyInfo.LatestAvailableVersion));
            Assert.True(result.Dependencies[dependencyName].RunningVersion.Equals(dependencyInfo.RunningVersion));
        }
예제 #3
0
        public void GetBlockchainInfo()
        {
            HttpProvider   client         = new HttpProvider("https://api.zilliqa.com/");
            BlockchainInfo blockchainInfo = client.GetBlockchainInfo().Result;

            Assert.IsNotNull(blockchainInfo);
        }
예제 #4
0
			public SyncInfo(BlockchainInfo bcinfo)
			{
				Guard.NotNull(nameof(bcinfo), bcinfo);
				BlockCount = (int)bcinfo.Blocks;
				int headerCount = (int)bcinfo.Headers;
				BlockchainInfoUpdated = DateTimeOffset.UtcNow;
				IsCoreSynchornized = BlockCount == headerCount;
			}
        public BlockchainInfo GetBlockchainInfo()
        {
            var info = new BlockchainInfo("B-Chain", "MainNode");

            info.Difficulty          = appSettings.Difficulty;
            info.Peers               = dbService.GetPeers().Count;
            info.PendingTransactions = dbService.GetTransactions().Count;
            info.Blocks              = dbService.GetAllBlocks().Count;
            return(info);
        }
        private async Task DownloadBlockchainAsync(long startId)
        {
            var webInfo = await LicensorClient.Instance.GetBlockchainInfoAsync().ConfigureAwait(false);

            BlockchainDataRestorer dataRestorer = new BlockchainDataRestorer();

            try
            {
                BlockchainInfo ownInfo = await BlockchainReadService.GetBlockchainInformationAsync().ConfigureAwait(false);

                List <BlockVm> newBlocks = default;
                for (long i = startId; i < webInfo.Count; i += 100)
                {
                    if (webInfo.Count - ownInfo.Count > 100)
                    {
                        newBlocks = await LicensorClient.Instance.GetBlockchainBlocksAsync(i, i + 100).ConfigureAwait(false);
                    }
                    else
                    {
                        newBlocks = await LicensorClient.Instance.GetBlockchainBlocksAsync(ownInfo.Count, webInfo.Count).ConfigureAwait(false);
                    }
                    if (newBlocks != null)
                    {
                        foreach (BlockVm block in newBlocks)
                        {
                            using (BlockchainDbContext context = new BlockchainDbContext())
                            {
                                try
                                {
                                    await context.Blocks.AddAsync(BlockBuilder.GetBlock(block)).ConfigureAwait(false);

                                    await context.SaveChangesAsync().ConfigureAwait(false);

                                    await dataRestorer.SaveBlockDataAsync(block).ConfigureAwait(false);
                                }
                                catch (Exception ex)
                                {
                                    Logger.WriteLog(ex);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
        public async Task HandleAsync()
        {
            try
            {
                BlockchainInfo info = await BlockchainReadService.GetBlockchainInformationAsync().ConfigureAwait(false);

                BlockchainInfoNodeResponse response = new BlockchainInfoNodeResponse(request.RequestId, info);
                NodeWebSocketCommunicationManager.SendResponse(response, current);
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
                NodeWebSocketCommunicationManager.SendResponse(new ResultNodeResponse(request.RequestId, ErrorCode.UnknownError), current);
            }
        }
        public async Task CheckAndSyncBlockchainAsync()
        {
            var startBlockId = await CommonBlockchainPartSearchAsync().ConfigureAwait(false);

            BlockchainInfo blockchainInfo = await BlockchainReadService.GetBlockchainInformationAsync().ConfigureAwait(false);

            var webInfo = await LicensorClient.Instance.GetBlockchainInfoAsync().ConfigureAwait(false);

            if (startBlockId < blockchainInfo.Count)
            {
                await SaveAndRemoveOldBlocksAsync(startBlockId).ConfigureAwait(false);
                await DownloadBlockchainAsync(startBlockId).ConfigureAwait(false);
                await RestoreOldBlockchainDataAsync().ConfigureAwait(false);
            }
            else if (startBlockId < webInfo.Count)
            {
                await DownloadBlockchainAsync(startBlockId).ConfigureAwait(false);
            }
        }
예제 #9
0
        private async void GetBalance()
        {
            Status      = "Updating Balances...";
            Errors      = string.Empty;
            IsReceiving = true;

            BalanceApi api = null;

            switch (SettingsInstance.SelectedBalanceApi)
            {
            case BalanceServiceNames.BlockchainInfo:
                api = new BlockchainInfo();
                break;

            case BalanceServiceNames.BlockExplorer:
                api = new BlockExplorer();
                break;

            default:
                api = new BlockchainInfo();
                break;
            }

            Response resp = await api.UpdateBalancesAsync(AddressList.ToList());

            if (resp.Errors.Any())
            {
                Errors = resp.Errors.GetErrors();
                Status = "Encountered an error!";
            }
            else
            {
                DataManager.WriteFile(AddressList, DataManager.FileType.Wallet);
                RaisePropertyChanged("BitcoinBalance");
                Status = "Balance Update Success!";
            }

            IsReceiving = false;
        }
        private async Task <long> CommonBlockchainPartSearchAsync()
        {
            using (WebClient webClient = new WebClient())
            {
                BlockchainInfo blockchainInfo = await BlockchainReadService.GetBlockchainInformationAsync().ConfigureAwait(false);

                long   blockId      = -1;
                long   tempBlockId  = blockchainInfo.BlockHashes.Min(opt => opt.FirstValue);
                byte[] responseData = await webClient.UploadDataTaskAsync(
                    $"https://{NodeSettings.Configs.LicensorUrl}/api/Blockchain/FindMatch", ObjectSerializer.ObjectToByteArray(blockchainInfo)).ConfigureAwait(false);

                blockId = BitConverter.ToInt64(responseData);
                while (blockId == -1)
                {
                    blockchainInfo = await BlockchainReadService.GetBlockchainInformationAsync(tempBlockId).ConfigureAwait(false);

                    if (!blockchainInfo.BlockHashes.Any())
                    {
                        return(1);
                    }
                    if (blockchainInfo.BlockHashes.Min(opt => opt.FirstValue) == 1)
                    {
                        return(1);
                    }
                    responseData = await webClient.UploadDataTaskAsync(
                        $"https://{NodeSettings.Configs.LicensorUrl}/api/Blockchain/FindMatch", ObjectSerializer.ObjectToByteArray(blockchainInfo)).ConfigureAwait(false);

                    blockId     = BitConverter.ToInt64(responseData);
                    tempBlockId = blockchainInfo.BlockHashes.Min(opt => opt.FirstValue);
                }
                if (blockId != -1)
                {
                    return(blockId);
                }
                return(1);
            }
        }
예제 #11
0
        public async Task <ActionResult> Restore([FromForm] BlockchainRestoreModel model)
        {
            BlockchainInfo blockchainInfo = await BlockchainReadService.GetBlockchainInformationAsync().ConfigureAwait(false);

            if (model.Start == null)
            {
                model.Start = blockchainInfo.FirstBlockTime;
            }
            if (model.End == null)
            {
                model.End = blockchainInfo.LastBlockTime;
            }
            if (model.End < model.Start)
            {
                return(BadRequest());
            }

            List <BlockVm> blocks = await BlockchainReadService.GetBlocksAsync(
                model.Start.GetValueOrDefault().ToUnixTime(),
                model.End.GetValueOrDefault().ToUnixTime(),
                BLOCKS_LIMIT).ConfigureAwait(false);

            while (blocks.Count == BLOCKS_LIMIT &&
                   blocks.LastOrDefault().Header.CreationTime < model.End.GetValueOrDefault().ToUnixTime())
            {
                foreach (var block in blocks)
                {
                    await _blockchainDataRestorer.SaveBlockDataAsync(block).ConfigureAwait(false);
                }
                blocks = await BlockchainReadService.GetBlocksAsync(
                    blocks.LastOrDefault().Header.CreationTime,
                    null,
                    BLOCKS_LIMIT).ConfigureAwait(false);
            }
            return(RedirectToAction("Index", "Configuration"));
        }
예제 #12
0
        private static void Init()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile($"appsettings.json", true, true)
                          .AddEnvironmentVariables();

            IConfigurationRoot Configuration = builder.Build();

            // Retrieve configuration from sections
            Settings.ConnectionString            = Configuration.GetSection("ConnectionString")?.Value;
            Settings.DatabaseId                  = Configuration.GetSection("DatabaseId")?.Value;
            Settings.ContractCollection          = Configuration.GetSection("ContractCollection")?.Value;
            Settings.RabbitMQUsername            = Configuration.GetSection("RabbitMQUsername")?.Value;
            Settings.RabbitMQPassword            = Configuration.GetSection("RabbitMQPassword")?.Value;
            Settings.RabbitMQHostname            = Configuration.GetSection("RabbitMQHostname")?.Value;
            Settings.RabbitMQPort                = Convert.ToInt16(Configuration.GetSection("RabbitMQPort")?.Value);
            Settings.ContractDeploymentQueueName = Configuration.GetSection("ContractDeploymentQueueName")?.Value;
            Settings.KeyVaultCertificateName     = Configuration.GetSection("KeyVaultCertificateName")?.Value;
            Settings.KeyVaultClientId            = Configuration.GetSection("KeyVaultClientId")?.Value;
            Settings.KeyVaultClientSecret        = Configuration.GetSection("KeyVaultClientSecret")?.Value;
            Settings.KeyVaultIdentifier          = Configuration.GetSection("KeyVaultIdentifier")?.Value;
            Settings.KeyVaultEncryptionKey       = Configuration.GetSection("KeyVaultEncryptionKey")?.Value;
            Settings.BlockchainRPCUrl            = Configuration.GetSection("BlockchainRPCUrl")?.Value;
            Settings.BlockchainMasterAddress     = Configuration.GetSection("BlockchainMasterAddress")?.Value;
            Settings.BlockchainMasterPrivateKey  = Configuration.GetSection("BlockchainMasterPrivateKey")?.Value;
            Settings.BlockchainContractABI       = Configuration.GetSection("BlockchainContractABI")?.Value;
            Settings.BlockchainContractByteCode  = Configuration.GetSection("BlockchainContractByteCode")?.Value;

            mongoDBConnectionInfo = new MongoDBConnectionInfo()
            {
                ConnectionString   = Settings.ConnectionString,
                DatabaseId         = Settings.DatabaseId,
                ContractCollection = Settings.ContractCollection
            };

            keyVaultConnectionInfo = new KeyVaultConnectionInfo()
            {
                CertificateName    = Settings.KeyVaultCertificateName,
                ClientId           = Settings.KeyVaultClientId,
                ClientSecret       = Settings.KeyVaultClientSecret,
                KeyVaultIdentifier = Settings.KeyVaultIdentifier
            };

            blockchainInfo = new BlockchainInfo()
            {
                RPCUrl           = Settings.BlockchainRPCUrl,
                MasterAddress    = Settings.BlockchainMasterAddress,
                MasterPrivateKey = Settings.BlockchainMasterPrivateKey,
                ContractABI      = Settings.BlockchainContractABI,
                ContractByteCode = Settings.BlockchainContractByteCode
            };

            using (KeyVaultHelper keyVaultHelper = new KeyVaultHelper(keyVaultConnectionInfo))
            {
                secret = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultEncryptionKey).Result;
            }

            account = new Account(blockchainInfo.MasterPrivateKey);
            web3    = new Web3(account, new RpcClient(new Uri(blockchainInfo.RPCUrl), null, null, new HttpClientHandler()
            {
                MaxConnectionsPerServer = 10, UseProxy = false
            }));
        }
 public BlockchainInfoNodeResponse(long requestId, BlockchainInfo information)
 {
     Information  = information;
     RequestId    = requestId;
     ResponseType = NodeResponseType.BlockchainInfo;
 }
예제 #14
0
        private async void GetBalance()
        {
            if (!AddressList.ToList().TrueForAll(x => !x.HasErrors))
            {
                Errors = "Fix the errors in addresses first!";
                return;
            }
            Status      = "Updating Balances...";
            Errors      = string.Empty;
            IsReceiving = true;

            BalanceApi api = null;

            switch (SettingsInstance.SelectedBalanceApi)
            {
            case BalanceServiceNames.BlockchainInfo:
                api = new BlockchainInfo();
                break;

            case BalanceServiceNames.BlockExplorer:
                api = new BlockExplorer();
                break;

            case BalanceServiceNames.BlockCypher:
                api = new BlockCypher();
                break;

            case BalanceServiceNames.Blockonomics:
                api = new Blockonomics();
                break;

            default:
                api = new BlockchainInfo();
                break;
            }

            // Not all exchanges support Bech32 addresses!
            // The following "if" is to solve that.
            bool hasSegWit = AddressList.Any(x => x.Address.StartsWith("bc1", System.StringComparison.InvariantCultureIgnoreCase));

            if (hasSegWit && !SettingsInstance.SelectedBalanceApi.Equals(BalanceServiceNames.Blockonomics))
            {
                BalanceApi            segApi      = new Blockonomics();
                List <BitcoinAddress> legacyAddrs = new List <BitcoinAddress>(AddressList.Where(x =>
                                                                                                !x.Address.StartsWith("bc1", System.StringComparison.OrdinalIgnoreCase)));
                List <BitcoinAddress> segWitAddrs = new List <BitcoinAddress>(AddressList.Where(x =>
                                                                                                x.Address.StartsWith("bc1", System.StringComparison.OrdinalIgnoreCase)));

                Response respSW = await segApi.UpdateBalancesAsync(segWitAddrs);

                if (respSW.Errors.Any())
                {
                    Errors = "SegWit API error: " + respSW.Errors.GetErrors();
                    Status = "Error in SegWit API! Continue updating legacy balances...";
                }
                Response resp = await api.UpdateBalancesAsync(legacyAddrs);

                if (resp.Errors.Any())
                {
                    Errors = resp.Errors.GetErrors();
                    Status = "Encountered an error!";
                }
                else
                {
                    DataManager.WriteFile(AddressList, DataManager.FileType.Wallet);
                    RaisePropertyChanged("BitcoinBalance");
                    Status = "Balance Update Success!";
                }
            }
            else
            {
                Response resp = await api.UpdateBalancesAsync(AddressList.ToList());

                if (resp.Errors.Any())
                {
                    Errors = resp.Errors.GetErrors();
                    Status = "Encountered an error!";
                }
                else
                {
                    DataManager.WriteFile(AddressList, DataManager.FileType.Wallet);
                    RaisePropertyChanged("BitcoinBalance");
                    Status = "Balance Update Success!";
                }
            }

            IsReceiving = false;
        }