public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var item = value as byte[]; if (item == null) return null; return NetworkConverter.ToHexString(item); }
public void FromHexString() { Random random = new Random(); string value; { byte[] buffer = new byte[32]; random.NextBytes(buffer); value = NetworkConverter.ToHexString(buffer); } Stopwatch sw1 = new Stopwatch(); Stopwatch sw2 = new Stopwatch(); var flags = new int[] { 0, 1 }; for (int i = 0; i < 1024 * 1024 * 2; i++) { byte[] result1 = null; byte[] result2 = null; random.Shuffle(flags); foreach (var index in flags) { if (index == 0) { sw1.Start(); result1 = NetworkConverter.FromHexString(value); sw1.Stop(); } else if (index == 1) { sw2.Start(); result2 = NetworkConverter.FromHexString_2(value); sw2.Stop(); } } Assert.IsTrue(Unsafe.Equals(result1, result2)); } StringBuilder sb = new StringBuilder(); sb.AppendLine("FromHexString: " + sw1.Elapsed.ToString()); sb.AppendLine("FromHexString_2: " + sw2.Elapsed.ToString()); Console.WriteLine(sb.ToString()); }
public void Test_NetworkConverter() { Assert.IsTrue(NetworkConverter.ToHexString(new byte[] { 0x00, 0x9e, 0x0f }) == "009e0f", "ToHexString"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.FromHexString("1af4b"), new byte[] { 0x01, 0xaf, 0x4b }), "FromHexString"); Assert.IsTrue(NetworkConverter.ToBoolean(new byte[] { 0x01 }), "ToBoolean"); Assert.IsTrue(NetworkConverter.ToChar(new byte[] { 0x00, 0x41 }) == 'A', "ToChar"); Assert.IsTrue(NetworkConverter.ToInt16(new byte[] { 0x74, 0xab }) == 0x74ab, "ToInt16"); Assert.IsTrue(NetworkConverter.ToUInt16(new byte[] { 0x74, 0xab }) == 0x74ab, "ToUInt16"); Assert.IsTrue(NetworkConverter.ToInt32(new byte[] { 0x74, 0xab, 0x05, 0xc1 }) == 0x74ab05c1, "ToInt32"); Assert.IsTrue(NetworkConverter.ToUInt32(new byte[] { 0x74, 0xab, 0x05, 0xc1 }) == 0x74ab05c1, "ToUInt32"); Assert.IsTrue(NetworkConverter.ToInt64(new byte[] { 0x74, 0xab, 0xa5, 0xbb, 0xf5, 0x39, 0x7b, 0x15 }) == 0x74aba5bbf5397b15, "ToInt64"); Assert.IsTrue(NetworkConverter.ToUInt64(new byte[] { 0x74, 0xab, 0xa5, 0xbb, 0xf5, 0x39, 0x7b, 0x15 }) == 0x74aba5bbf5397b15, "ToUInt64"); Assert.IsTrue(NetworkConverter.ToSingle(new byte[] { 0x4a, 0x8a, 0xd0, 0x64 }) == 4548658.0, "ToSingle"); Assert.IsTrue(NetworkConverter.ToDouble(new byte[] { 0x41, 0xb8, 0xa6, 0xb9, 0x83, 0x27, 0x97, 0xa3 }) == 413579651.15465754, "ToDouble"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes(true), new byte[] { 0x01 }), "GetBytes #bool"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((char)'A'), new byte[] { 0x00, 0x41 }), "GetBytes #char"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((short)0x74ab), new byte[] { 0x74, 0xab }), "GetBytes #short"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((ushort)0x74ab), new byte[] { 0x74, 0xab }), "GetBytes #ushort"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((int)0x74ab05c1), new byte[] { 0x74, 0xab, 0x05, 0xc1 }), "GetBytes #int"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((uint)0x74ab05c1), new byte[] { 0x74, 0xab, 0x05, 0xc1 }), "GetBytes #uint"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((long)0x74aba5bbf5397b15), new byte[] { 0x74, 0xab, 0xa5, 0xbb, 0xf5, 0x39, 0x7b, 0x15 }), "GetBytes #long"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((ulong)0x74aba5bbf5397b15), new byte[] { 0x74, 0xab, 0xa5, 0xbb, 0xf5, 0x39, 0x7b, 0x15 }), "GetBytes #ulong"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((float)4548658.0), new byte[] { 0x4a, 0x8a, 0xd0, 0x64 }), "GetBytes #float"); Assert.IsTrue(CollectionUtilities.Equals(NetworkConverter.GetBytes((double)413579651.15465754), new byte[] { 0x41, 0xb8, 0xa6, 0xb9, 0x83, 0x27, 0x97, 0xa3 }), "GetBytes #double"); Assert.IsTrue(NetworkConverter.ToInt32(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x74, 0xab, 0x05, 0xc1 }, 4) == 0x74ab05c1, "ToInt32"); for (int i = 0; i < 1024; i++) { byte[] buffer = new byte[_random.Next(0, 128)]; _random.NextBytes(buffer); var s = NetworkConverter.ToBase64UrlString(buffer); Assert.IsTrue(CollectionUtilities.Equals(buffer, NetworkConverter.FromBase64UrlString(s))); } for (int i = 0; i < 1024; i++) { byte[] buffer = new byte[_random.Next(0, 128)]; _random.NextBytes(buffer); var s = NetworkConverter.ToHexString(buffer); Assert.IsTrue(CollectionUtilities.Equals(buffer, NetworkConverter.FromHexString(s))); } }
public void ToHexString() { Random random = new Random(); byte[] value = new byte[32]; random.NextBytes(value); Stopwatch sw1 = new Stopwatch(); Stopwatch sw2 = new Stopwatch(); var flags = new int[] { 0, 1 }; for (int i = 0; i < 1024 * 1024 * 2; i++) { string result1 = null; string result2 = null; random.Shuffle(flags); foreach (var index in flags) { if (index == 0) { sw1.Start(); result1 = NetworkConverter.ToHexString(value, 0, value.Length); sw1.Stop(); } else if (index == 1) { sw2.Start(); result2 = NetworkConverter.ToHexString_2(value, 0, value.Length); sw2.Stop(); } } Assert.IsTrue(result1 == result2); } StringBuilder sb = new StringBuilder(); sb.AppendLine("ToHexString: " + sw1.Elapsed.ToString()); sb.AppendLine("ToHexString_2: " + sw2.Elapsed.ToString()); Console.WriteLine(sb.ToString()); }
public void Test_HmacSha256() { // http://tools.ietf.org/html/rfc4868#section-2.7.1 { var key = NetworkConverter.FromHexString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); var value = NetworkConverter.FromHexString("4869205468657265"); using (MemoryStream stream = new MemoryStream(value)) { var s = NetworkConverter.ToHexString(HmacSha256.ComputeHash(stream, key)); } using (HMACSHA256 hmacSha256 = new HMACSHA256(key)) { var s = NetworkConverter.ToHexString(hmacSha256.ComputeHash(value)); } } var list = new List <int>(); list.Add(1); list.Add(64); list.Add(128); byte[] buffer = new byte[1024 * 32]; _random.NextBytes(buffer); for (int i = 0; i < list.Count; i++) { byte[] key = new byte[list[i]]; _random.NextBytes(key); using (MemoryStream stream1 = new MemoryStream(buffer)) using (MemoryStream stream2 = new MemoryStream(buffer)) { using (HMACSHA256 hmacSha256 = new HMACSHA256(key)) { Assert.IsTrue(Unsafe.Equals(hmacSha256.ComputeHash(stream1), HmacSha256.ComputeHash(stream2, key))); } } } }
public bool Run() { try { // スリープを禁止する。 NativeMethods.SetThreadExecutionState(NativeMethods.ExecutionState.Continuous); // カレントディレクトリをexeと同じディレクトリパスへ変更。 Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); // ハンドルしていない例外をログ出力させる。 Thread.GetDomain().UnhandledException += this.Program_UnhandledException; string sessionId = NetworkConverter.ToHexString(Sha256.Compute(Path.GetFullPath(Assembly.GetEntryAssembly().Location))); // 多重起動防止 { _mutex = new Mutex(false, sessionId); if (!_mutex.WaitOne(0)) { return(false); } } // 既定のフォルダを作成する。 { foreach (var propertyInfo in typeof(AmoebaEnvironment.PathsEnvironment).GetProperties()) { string path = propertyInfo.GetValue(AmoebaEnvironment.Paths) as string; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } } // Tempフォルダを環境変数に登録。 { // Tempフォルダ内を掃除。 try { foreach (string path in Directory.GetFiles(AmoebaEnvironment.Paths.TempDirectoryPath, "*", SearchOption.AllDirectories)) { File.Delete(path); } foreach (string path in Directory.GetDirectories(AmoebaEnvironment.Paths.TempDirectoryPath, "*", SearchOption.AllDirectories)) { Directory.Delete(path, true); } } catch (Exception) { } Environment.SetEnvironmentVariable("TMP", Path.GetFullPath(AmoebaEnvironment.Paths.TempDirectoryPath), EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable("TEMP", Path.GetFullPath(AmoebaEnvironment.Paths.TempDirectoryPath), EnvironmentVariableTarget.Process); } // ログファイルを設定する。 this.Setting_Log(); // アップデート { // 一時的に作成された"Amoeba.Update.exe"を削除する。 { string tempUpdateExeFilePath = Path.Combine(AmoebaEnvironment.Paths.WorkDirectoryPath, "Amoeba.Update.exe"); if (File.Exists(tempUpdateExeFilePath)) { File.Delete(tempUpdateExeFilePath); } } if (Directory.Exists(AmoebaEnvironment.Paths.UpdateDirectoryPath)) { string zipFilePath = null; // 最新のバージョンのzipを検索。 { var map = new Dictionary <string, Version>(); var regex = new Regex(@"Amoeba.+?((\d*)\.(\d*)\.(\d*)).*?\.zip", RegexOptions.Compiled); foreach (string path in Directory.GetFiles(AmoebaEnvironment.Paths.UpdateDirectoryPath)) { var match = regex.Match(Path.GetFileName(path)); if (!match.Success) { continue; } var version = new Version(match.Groups[1].Value); if (version < AmoebaEnvironment.Version) { continue; } map.Add(path, version); } if (map.Count > 0) { var sortedList = map.ToList(); sortedList.Sort((x, y) => y.Value.CompareTo(x.Value)); zipFilePath = sortedList.First().Key; } } if (zipFilePath != null) { string tempUpdateDirectoryPath = Path.Combine(AmoebaEnvironment.Paths.WorkDirectoryPath, "Update"); if (Directory.Exists(tempUpdateDirectoryPath)) { Directory.Delete(tempUpdateDirectoryPath, true); } using (var zipfile = new ZipFile(zipFilePath)) { zipfile.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently; zipfile.ExtractAll(tempUpdateDirectoryPath); } if (File.Exists(zipFilePath)) { File.Delete(zipFilePath); } string tempUpdateExeFilePath = Path.Combine(AmoebaEnvironment.Paths.WorkDirectoryPath, "Amoeba.Update.exe"); File.Copy("Amoeba.Update.exe", tempUpdateExeFilePath); var startInfo = new ProcessStartInfo(); startInfo.FileName = Path.GetFullPath(tempUpdateExeFilePath); startInfo.Arguments = string.Format("\"{0}\" \"{1}\" \"{2}\" \"{3}\"", sessionId, Path.GetFullPath(Path.Combine(tempUpdateDirectoryPath, "Core")), Path.GetFullPath(AmoebaEnvironment.Paths.CoreDirectoryPath), Path.GetFullPath(Assembly.GetEntryAssembly().Location)); startInfo.WorkingDirectory = Path.GetFullPath(Path.GetDirectoryName(tempUpdateExeFilePath)); Process.Start(startInfo); return(false); } } } // マイグレーション { if (AmoebaEnvironment.Config.Version <= new Version(5, 0, 60)) { try { var basePath = Path.Combine(AmoebaEnvironment.Paths.ConfigDirectoryPath, @"Service\Core\Cache"); if (!Directory.Exists(Path.Combine(basePath, "Blocks"))) { Directory.CreateDirectory(Path.Combine(basePath, "Blocks")); } var renameList = new List <(string oldPath, string newPath)>(); renameList.Add((@"CacheInfos.json.gz", @"ContentInfos.json.gz")); renameList.Add((@"Size.json.gz", @"Blocks\Size.json.gz")); renameList.Add((@"ClusterIndex.json.gz", @"Blocks\ClusterIndex.json.gz")); foreach (var(oldPath, newPath) in renameList) { if (File.Exists(Path.Combine(basePath, newPath)) || !File.Exists(Path.Combine(basePath, oldPath))) { continue; } File.Copy(Path.Combine(basePath, oldPath), Path.Combine(basePath, newPath)); } } catch (Exception e) { Log.Error(e); } } if (AmoebaEnvironment.Config.Version <= new Version(5, 1, 1)) { try { var sourcePath = Path.Combine(AmoebaEnvironment.Paths.ConfigDirectoryPath, @"View\Settings"); var destPath = Path.Combine(AmoebaEnvironment.Paths.ConfigDirectoryPath, @"Control\Settings"); if (Directory.Exists(sourcePath)) { if (!Directory.Exists(destPath)) { Directory.CreateDirectory(destPath); } foreach (var oldPath in Directory.GetFiles(sourcePath)) { var newPath = Path.Combine(destPath, Path.GetFileName(oldPath)); if (File.Exists(newPath) || !File.Exists(oldPath)) { continue; } File.Copy(oldPath, newPath); } } } catch (Exception e) { Log.Error(e); } try { var basePath = Path.Combine(AmoebaEnvironment.Paths.ConfigDirectoryPath, @"Control\Settings"); var renameList = new List <(string oldPath, string newPath)>(); renameList.Add((@"AccountInfo.json.gz", @"AccountSetting.json.gz")); renameList.Add((@"UpdateInfo.json.gz", @"UpdateSetting.json.gz")); foreach (var(oldPath, newPath) in renameList .Select(tuple => (Path.Combine(basePath, tuple.oldPath), Path.Combine(basePath, tuple.newPath)))) { if (File.Exists(newPath) || !File.Exists(oldPath)) { continue; } File.Copy(oldPath, newPath); } } catch (Exception e) { Log.Error(e); } } } #if !DEBUG // デーモンプロセス起動。 { var daemonExeFilePath = Path.Combine(AmoebaEnvironment.Paths.DaemonDirectoryPath, "Amoeba.Daemon.exe"); var daemonConfigFilePath = Path.Combine(AmoebaEnvironment.Paths.ConfigDirectoryPath, "Daemon.toml"); if (!File.Exists(daemonConfigFilePath)) { // 「Amoeba/Core/Daemon」のような階層を想定。 var basePath = "../../"; var config = new DaemonConfig( new Version(0, 0, 0), new DaemonConfig.CommunicationConfig("tcp:127.0.0.1:4040"), new DaemonConfig.CacheConfig(Path.Combine(basePath, "Config", "Cache.blocks")), new DaemonConfig.PathsConfig( Path.Combine(basePath, "Temp"), Path.Combine(basePath, "Config", "Service"), Path.Combine(basePath, "Log"))); var tomlSettings = TomlSettings.Create(builder => builder .ConfigureType <Version>(type => type .WithConversionFor <TomlString>(convert => convert .ToToml(tt => tt.ToString()) .FromToml(ft => Version.Parse(ft.Value))))); Toml.WriteFile(config, daemonConfigFilePath, tomlSettings); } var startInfo = new ProcessStartInfo(); startInfo.FileName = daemonExeFilePath; startInfo.Arguments = string.Format("-c \"{0}\"", daemonConfigFilePath); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; try { _process = Process.Start(startInfo); } catch (Exception) { return(false); } } #endif return(true); } catch (Exception ex) { Log.Error(ex); return(false); } }
private void Application_Startup(object sender, StartupEventArgs e) { try { string sessionId = NetworkConverter.ToHexString(Sha256.Compute(Path.GetFullPath(Assembly.GetEntryAssembly().Location))); // 多重起動防止 { _mutex = new Mutex(false, sessionId); if (!_mutex.WaitOne(0)) { this.Shutdown(); return; } } // アップデート { // 一時的に作成された"Amoeba.Update.exe"を削除する。 { string tempUpdateExeFilePath = Path.Combine(AmoebaEnvironment.Paths.WorkPath, "Amoeba.Update.exe"); if (File.Exists(tempUpdateExeFilePath)) { File.Delete(tempUpdateExeFilePath); } } if (Directory.Exists(AmoebaEnvironment.Paths.UpdatePath)) { string zipFilePath = null; // 最新のバージョンのzipを検索。 { var map = new Dictionary <string, Version>(); var regex = new Regex(@"Amoeba.+?((\d*)\.(\d*)\.(\d*)).*?\.zip", RegexOptions.Compiled); foreach (string path in Directory.GetFiles(AmoebaEnvironment.Paths.UpdatePath)) { var match = regex.Match(Path.GetFileName(path)); if (!match.Success) { continue; } var version = new Version(match.Groups[1].Value); if (version < AmoebaEnvironment.Version) { continue; } map.Add(path, version); } if (map.Count > 0) { var sortedList = map.ToList(); sortedList.Sort((x, y) => y.Value.CompareTo(x.Value)); zipFilePath = sortedList.First().Key; } } if (zipFilePath != null) { string tempUpdateDirectoryPath = Path.Combine(AmoebaEnvironment.Paths.WorkPath, "Update"); if (Directory.Exists(tempUpdateDirectoryPath)) { Directory.Delete(tempUpdateDirectoryPath, true); } using (var zipfile = new ZipFile(zipFilePath)) { zipfile.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently; zipfile.ExtractAll(tempUpdateDirectoryPath); } if (File.Exists(zipFilePath)) { File.Delete(zipFilePath); } string tempUpdateExeFilePath = Path.Combine(AmoebaEnvironment.Paths.WorkPath, "Amoeba.Update.exe"); File.Copy("Amoeba.Update.exe", tempUpdateExeFilePath); var startInfo = new ProcessStartInfo(); startInfo.FileName = Path.GetFullPath(tempUpdateExeFilePath); startInfo.Arguments = string.Format("\"{0}\" \"{1}\" \"{2}\" \"{3}\"", sessionId, Path.Combine(tempUpdateDirectoryPath, "Core"), Directory.GetCurrentDirectory(), Path.Combine(Directory.GetCurrentDirectory(), "Amoeba.Interface.exe")); startInfo.WorkingDirectory = Path.GetFullPath(Path.GetDirectoryName(tempUpdateExeFilePath)); Process.Start(startInfo); this.Shutdown(); return; } } } // 既定のフォルダを作成する。 { foreach (var propertyInfo in typeof(AmoebaEnvironment.EnvironmentPaths).GetProperties()) { string path = propertyInfo.GetValue(AmoebaEnvironment.Paths) as string; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } } // Tempフォルダを環境変数に登録。 { // Tempフォルダ内を掃除。 try { foreach (string path in Directory.GetFiles(AmoebaEnvironment.Paths.TempPath, "*", SearchOption.AllDirectories)) { File.Delete(path); } foreach (string path in Directory.GetDirectories(AmoebaEnvironment.Paths.TempPath, "*", SearchOption.AllDirectories)) { Directory.Delete(path, true); } } catch (Exception) { } Environment.SetEnvironmentVariable("TMP", Path.GetFullPath(AmoebaEnvironment.Paths.TempPath), EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable("TEMP", Path.GetFullPath(AmoebaEnvironment.Paths.TempPath), EnvironmentVariableTarget.Process); } // アップグレード処理。 { if (AmoebaEnvironment.Config.Version <= new Version(5, 0, 60)) { var basePath = Path.Combine(AmoebaEnvironment.Paths.ConfigPath, @"Service\Core\Cache"); Directory.CreateDirectory(Path.Combine(basePath, "Blocks")); var renameList = new List <(string oldPath, string newPath)>(); renameList.Add((@"CacheInfos.json.gz", @"ContentInfos.json.gz")); renameList.Add((@"Size.json.gz", @"Blocks\Size.json.gz")); renameList.Add((@"ClusterIndex.json.gz", @"Blocks\ClusterIndex.json.gz")); foreach (var(oldPath, newPath) in renameList) { File.Copy(Path.Combine(basePath, oldPath), Path.Combine(basePath, newPath)); } } } this.StartupUri = new Uri("Mvvm/Windows/Main/MainWindow.xaml", UriKind.Relative); } catch (Exception ex) { Log.Error(ex); this.Shutdown(); return; } }
public byte[] Create_1(byte[] value, int limit, TimeSpan computationTime) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 32) { throw new ArgumentOutOfRangeException("value"); } var info = new ProcessStartInfo(_path); info.CreateNoWindow = true; info.UseShellExecute = false; info.RedirectStandardOutput = true; { if (limit < 0) { limit = -1; } int timeout; if (computationTime < TimeSpan.Zero) { timeout = -1; } else { timeout = (int)computationTime.TotalSeconds; } info.Arguments = string.Format( "hashcash1 create {0} {1} {2}", NetworkConverter.ToHexString(value), limit, timeout); } using (var process = Process.Start(info)) { _processes.Add(process); try { process.PriorityClass = ProcessPriorityClass.Idle; try { var result = process.StandardOutput.ReadLine(); process.WaitForExit(); if (process.ExitCode != 0) { throw new MinerException(); } return(NetworkConverter.FromHexString(result)); } catch (MinerException) { throw; } catch (Exception e) { throw new MinerException(e.Message, e); } } finally { _processes.Remove(process); } } }