public void TestWalk() { using (var tempDir = new TemporaryDirectory("unit-tests")) { string subDirPath = Path.Combine(tempDir, "subdir"); Directory.CreateDirectory(subDirPath); string filePath = Path.Combine(subDirPath, "file"); File.WriteAllText(filePath, ""); string symlinkPath = Path.Combine(tempDir, "symlink"); if (UnixUtils.IsUnix) { UnixUtils.CreateSymlink(symlinkPath, "."); } else { Directory.CreateDirectory(symlinkPath); } // Set up delegate mocks var dirCallbackMock = new Mock <IActionSimulator <string> >(MockBehavior.Strict); // ReSharper disable once AccessToDisposedClosure dirCallbackMock.Setup(x => x.Execute(tempDir)).Verifiable(); dirCallbackMock.Setup(x => x.Execute(subDirPath)).Verifiable(); dirCallbackMock.Setup(x => x.Execute(symlinkPath)).Verifiable(); var fileCallbackMock = new Mock <IActionSimulator <string> >(MockBehavior.Strict); fileCallbackMock.Setup(x => x.Execute(filePath)).Verifiable(); new DirectoryInfo(tempDir).Walk( dir => dirCallbackMock.Object.Execute(dir.FullName), file => fileCallbackMock.Object.Execute(file.FullName)); dirCallbackMock.Verify(); fileCallbackMock.Verify(); } }
private IEnumerable <SyncTransactionInfo> CreateTransactions(BlockInfo block, IEnumerable <DecodedRawTransaction> transactions) { var trxInfps = transactions.Select(trx => new SyncTransactionInfo { TransactionHash = trx.TxId, Timestamp = block == null ? UnixUtils.DateToUnixTimestamp(DateTime.UtcNow) : block.Time }); return(trxInfps); }
/// <summary> /// Deploys a bootstrap file for importing exported feeds and implementations. /// </summary> /// <exception cref="IOException">A problem occurred while writing the script.</exception> /// <exception cref="UnauthorizedAccessException">Write access to the script is not permitted.</exception> public void DeployImportScript() { string fileName = (_architecture.OS == OS.Windows) ? "import.cmd" : "import.sh"; string target = Path.Combine(_destination, fileName); typeof(Exporter).CopyEmbeddedToFile(fileName, target); if (UnixUtils.IsUnix) { UnixUtils.SetExecutable(target, executable: true); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (long.TryParse(reader.Value.ToString(), out long ret)) { return(ret); } if (DateTime.TryParse(reader.Value.ToString(), out DateTime dt)) { return(UnixUtils.DateToUnixTimestamp(dt)); } return(ret); }
private void DeployBootstrap([NotNull] ITaskHandler handler, [NotNull] string mode) { string appName = _selections.Name ?? "application"; string fileName = (_architecture.OS == OS.Windows) ? mode + " " + appName + ".exe" : mode + "-" + appName.ToLowerInvariant().Replace(" ", "-") + ".sh"; var source = new Uri("https://0install.de/bootstrap/" + "?platform=" + (_architecture.OS == OS.Windows ? "windows" : "linux") + "&mode=" + mode + "&name=" + HttpUtility.UrlEncode(appName) + "&uri=" + HttpUtility.UrlEncode(_selections.InterfaceUri.ToStringRfc())); string target = Path.Combine(_destination, fileName); handler.RunTask(new DownloadFile(source, target)); if (UnixUtils.IsUnix) { UnixUtils.SetExecutable(target, executable: true); } }
private IEnumerable <SyncTransactionAddressItem> SelectAddressWithPool(SyncBlockInfo current, string address, bool availableOnly) { FilterDefinitionBuilder <MapTransactionAddress> builder = Builders <MapTransactionAddress> .Filter; var addressFiler = new List <string> { address }; FilterDefinition <MapTransactionAddress> filter = builder.AnyIn(transactionAddress => transactionAddress.Addresses, addressFiler); if (availableOnly) { // we only want spendable transactions filter = filter & builder.Eq(info => info.SpendingTransactionId, null); } watch.Restart(); SortDefinition <MapTransactionAddress> sort = Builders <MapTransactionAddress> .Sort.Descending(info => info.BlockIndex); var addrs = MapTransactionAddress.Find(filter).Sort(sort).ToList(); watch.Stop(); log.LogInformation($"Select: Seconds = {watch.Elapsed.TotalSeconds} - UnspentOnly = {availableOnly} - Addr = {address} - Items = {addrs.Count()}"); // this creates a copy of the collection (to avoid thread issues) ICollection <Transaction> pool = MemoryTransactions.Values; if (pool.Any()) { // mark trx in output as spent if they exist in the pool List <MapTransactionAddress> addrsupdate = addrs; GetPoolOutputs(pool).ForEach(f => { MapTransactionAddress adr = addrsupdate.FirstOrDefault(a => a.TransactionId == f.Item1.PrevOut.Hash.ToString() && a.Index == f.Item1.PrevOut.N); if (adr != null) { adr.SpendingTransactionId = f.Item2; } }); // if only spendable transactions are to be returned we need to remove // any that have been marked as spent by a transaction in the pool if (availableOnly) { addrs = addrs.Where(d => d.SpendingTransactionId == null).ToList(); } // add all pool transactions to main output var paddr = PoolToMapTransactionAddress(pool, address).ToList(); addrs = addrs.OrderByDescending(s => s.BlockIndex).Concat(paddr).ToList(); } // map to return type and calculate confirmations return(addrs.Select(s => new SyncTransactionAddressItem { Address = address, Index = s.Index, TransactionHash = s.TransactionId, BlockIndex = s.BlockIndex == -1 ? default(long?) : s.BlockIndex, Value = s.Value, Confirmations = s.BlockIndex == -1 ? 0 : current.BlockIndex - s.BlockIndex + 1, SpendingTransactionHash = s.SpendingTransactionId, SpendingBlockIndex = s.SpendingBlockIndex, CoinBase = s.CoinBase, CoinStake = s.CoinStake, ScriptHex = new Script(Encoders.Hex.DecodeData(s.ScriptHex)).ToString(), Type = StandardScripts.GetTemplateFromScriptPubKey(new Script(Encoders.Hex.DecodeData(s.ScriptHex)))?.Type.ToString(), Time = s.BlockIndex == -1 ? UnixUtils.DateToUnixTimestamp(DateTime.UtcNow) : current.BlockTime })); }
public async Task <CoinInfo> CoinInformation() { long index = storage.GetLatestBlock()?.BlockIndex ?? 0; //SyncConnection connection = syncConnection; //BitcoinClient client = CryptoClientFactory.Create(connection.ServerDomain, connection.RpcAccessPort, connection.User, connection.Password, connection.Secure); var coinInfo = new CoinInfo { BlockHeight = index, Name = chainConfiguration.Name, Symbol = chainConfiguration.Symbol, Description = chainConfiguration.Description, Url = chainConfiguration.Url, Logo = chainConfiguration.Logo, Icon = chainConfiguration.Icon }; Statistics statitics = await Statistics(); coinInfo.Node = statitics; // If we have network type available, we'll extend with extra metadata. if (syncConnection.HasNetworkType) { Network network = syncConnection.Network; IConsensus consensus = network.Consensus; coinInfo.Configuration = new NetworkInfo { DefaultAPIPort = network.DefaultAPIPort, DefaultMaxInboundConnections = network.DefaultMaxInboundConnections, DefaultMaxOutboundConnections = network.DefaultMaxOutboundConnections, DefaultPort = network.DefaultPort, DefaultRPCPort = network.DefaultRPCPort, DNSSeeds = network.DNSSeeds.Select(s => s.Host).ToList(), FallbackFee = network.FallbackFee, GenesisDate = UnixUtils.UnixTimestampToDate(network.GenesisTime).ToUniversalDateTime(), // Returns Kind.Unspecified, so translate. GenesisHash = network.GenesisHash.ToString(), MinRelayTxFee = network.MinRelayTxFee, MinTxFee = network.MinTxFee, Name = network.Name, NetworkType = network.NetworkType, SeedNodes = network.SeedNodes.Select(s => s.Endpoint.ToString()).ToList(), Consensus = new ConsensusInfo { CoinbaseMaturity = consensus.CoinbaseMaturity, MaxReorgLength = consensus.MaxReorgLength, CoinType = consensus.CoinType, IsProofOfStake = consensus.IsProofOfStake, LastPOWBlock = consensus.LastPOWBlock, MaxMoney = consensus.MaxMoney, PremineReward = consensus.PremineReward.ToUnit(NBitcoin.MoneyUnit.BTC), ProofOfStakeReward = consensus.ProofOfStakeReward.ToUnit(NBitcoin.MoneyUnit.BTC), ProofOfWorkReward = consensus.ProofOfWorkReward.ToUnit(NBitcoin.MoneyUnit.BTC), TargetSpacing = consensus.TargetSpacing } }; } return(coinInfo); }
/// <inheritdoc/> protected override void OnStage() { if (!Directory.Exists(DestinationPath)) { Directory.CreateDirectory(DestinationPath); _createdDirectories.Push(DestinationPath); } if (FileUtils.DetermineTimeAccuracy(DestinationPath) > 0) { throw new IOException(Resources.InsufficientFSTimeAccuracy); } string manifestPath = System.IO.Path.Combine(DestinationPath, Manifest.ManifestFile); string tempManifestPath = Randomize(manifestPath); _pendingFileRenames.Push(new KeyValuePair <string, string>(tempManifestPath, manifestPath)); Manifest.Save(tempManifestPath); Handler.RunTask(ForEachTask.Create(Resources.CopyFiles, ElementPaths, pair => { string sourcePath = System.IO.Path.Combine(Path, pair.Key); string destinationPath = System.IO.Path.Combine(DestinationPath, pair.Key); if (pair.Value is ManifestDirectory) { if (!Directory.Exists(destinationPath)) { Directory.CreateDirectory(destinationPath); _createdDirectories.Push(destinationPath); } } else { string tempPath = Randomize(destinationPath); _pendingFileRenames.Push(new KeyValuePair <string, string>(tempPath, destinationPath)); switch (pair.Value) { case ManifestFileBase file: File.Copy(sourcePath, tempPath); File.SetLastWriteTimeUtc(tempPath, file.ModifiedTime); if (UnixUtils.IsUnix) { FileUtils.SetExecutable(tempPath, file is ManifestExecutableFile); } break; case ManifestSymlink _: if (UnixUtils.IsUnix) { if (UnixUtils.IsSymlink(sourcePath, out string?symlinkTarget)) { UnixUtils.CreateSymlink(tempPath, symlinkTarget); } } break; } } })); }