public static void Interpret(IPEndPoint source, byte[] bytes) { try { message = Read(bytes); } catch (Exception ex) { Debug.Log(ex); return; } if (message.SourceID == GameObject.FindObjectOfType <Network> ().NetworkCommon.ID) { // TODO message sent by self returned } else { if (message.Type == Message.MessageType.GAMEPLAY) { GameplayTranslator.Interpret(source, message, Read <GameplayMessage>(message.SerializedContent)); } else if (message.Type == Message.MessageType.NETWORK) { NetworkTranslator.Interpret(source, message, Read <NetworkMessage>(message.SerializedContent)); } } }
void Awake() { instance = this; networkTranslator = GetComponent <NetworkTranslator>(); SetConsoleParser(); }
public async Task StartAsync() { var ptcv = PrintToConsole ? 1 : 0; using var process = Start($"{NetworkTranslator.GetCommandLineArguments(Network)} -datadir={DataDir} -printtoconsole={ptcv}", false); await PidFile.SerializeAsync(process.Id).ConfigureAwait(false); CachedPid = process.Id; while (true) { var ex = await RpcClient.TestAsync().ConfigureAwait(false); if (ex is null) { break; } if (process is null || process.HasExited) { throw ex; } } }
public string?TryGetValue(string key) { var configDic = Config.ToDictionary(); return(NetworkTranslator.GetConfigPrefixesWithDots(Network) .Select(networkPrefixWithDot => configDic.TryGet($"{networkPrefixWithDot}{key}")) .LastOrDefault(x => x is { }));
public BitcoindRpcProcessBridge(IRPCClient rpc, string dataDir, bool printToConsole) : base() { RpcClient = Guard.NotNull(nameof(rpc), rpc); Network = RpcClient.Network; DataDir = Guard.NotNullOrEmptyOrWhitespace(nameof(dataDir), dataDir); PrintToConsole = printToConsole; PidFile = new PidFile(Path.Combine(DataDir, NetworkTranslator.GetDataDirPrefix(Network)), PidFileName); CachedPid = null; }
public BitcoindRpcProcessBridge(IRPCClient rpcClient, string dataDir, bool printToConsole) { RpcClient = rpcClient; Network = RpcClient.Network; DataDir = dataDir; PrintToConsole = printToConsole; PidFile = new PidFile(Path.Combine(DataDir, NetworkTranslator.GetDataDirPrefix(Network)), PidFileName); CachedPid = null; Process = null; }
private void ClientConnection() { if (!NetworkCommon.Connected) { Invoke("ClientConnection", .1f); } NetworkCommon.Send(null, MessageTranslator.ToByteArray( NetworkTranslator.createMessage(NetworkCommon.ID, 1 - NetworkCommon.ID, NetworkMessage.MessageValue.CONNECT) )); }
void Awake() { if (Instance == null) //Static 변수를 지정하고 이것이 없을경우 - PlayManage 스크립트를 저장하고 이것이 전 범위적인 싱글톤 오브젝트가 된다. { DontDestroyOnLoad(this.gameObject); Instance = this; } else if (Instance != this) { Destroy(this.gameObject); //싱글톤 오브젝트가 있을경우 다른 오브젝트를 제거. } networkTranslator = GetComponent <NetworkTranslator>(); }
public async Task StartAsync(CancellationToken cancel) { var ptcv = PrintToConsole ? 1 : 0; using var process = Start($"{NetworkTranslator.GetCommandLineArguments(Network)} -datadir=\"{DataDir}\" -printtoconsole={ptcv}", false); await PidFile.WriteFileAsync(process.Id).ConfigureAwait(false); CachedPid = process.Id; string latestFailureMessage = null; while (true) { var ex = await RpcClient.TestAsync().ConfigureAwait(false); if (ex is null) { Logger.LogInfo($"RPC connection is successfully established."); break; } else if (latestFailureMessage != ex.Message) { latestFailureMessage = ex.Message; Logger.LogInfo($"{Constants.BuiltinBitcoinNodeName} is not yet ready... Reason: {latestFailureMessage}"); } if (process is null || process.HasExited) { throw new BitcoindException($"Failed to start daemon, location: '{process?.StartInfo.FileName} {process?.StartInfo.Arguments}'", ex); } if (cancel.IsCancellationRequested) { await StopAsync(true).ConfigureAwait(false); cancel.ThrowIfCancellationRequested(); } await Task.Delay(100).ConfigureAwait(false); // So to leave some breathing room before the next check. } }
public PidFile(string dataDir, Network network) { DataDir = Guard.NotNullOrEmptyOrWhitespace(nameof(dataDir), dataDir); Network = Guard.NotNull(nameof(network), network); FilePath = Path.Combine(DataDir, NetworkTranslator.GetDataDirPrefix(Network), FileName); }
/// <summary> /// This method can be called only once. /// </summary> public async Task StartAsync(CancellationToken cancel) { int ptcv = PrintToConsole ? 1 : 0; string processPath = MicroserviceHelpers.GetBinaryPath("bitcoind"); string networkArgument = NetworkTranslator.GetCommandLineArguments(Network); string args = $"{networkArgument} -datadir=\"{DataDir}\" -printtoconsole={ptcv}"; // Start bitcoind process. Process = new ProcessAsync(ProcessStartInfoFactory.Make(processPath, args)); Process.Start(); // Store PID in PID file. await PidFile.WriteFileAsync(Process.Id).ConfigureAwait(false); CachedPid = Process.Id; try { var exceptionTracker = new LastExceptionTracker(); // Try to connect to bitcoin daemon RPC until we succeed. while (true) { try { TimeSpan timeSpan = await RpcClient.UptimeAsync(cancel).ConfigureAwait(false); Logger.LogInfo("RPC connection is successfully established."); Logger.LogDebug($"RPC uptime is: {timeSpan}."); // Bitcoin daemon is started. We are done. break; } catch (Exception ex) { ExceptionInfo exceptionInfo = exceptionTracker.Process(ex); // Don't log extensively. if (exceptionInfo.IsFirst) { Logger.LogInfo($"{Constants.BuiltinBitcoinNodeName} is not yet ready... Reason: {exceptionInfo.Exception.Message}"); } if (Process is { } p&& p.HasExited) { throw new BitcoindException($"Failed to start daemon, location: '{p.StartInfo.FileName} {p.StartInfo.Arguments}'", ex); } } if (cancel.IsCancellationRequested) { Logger.LogDebug("Bitcoin daemon was not started yet and user requested to cancel the operation."); await StopAsync(onlyOwned : true).ConfigureAwait(false); cancel.ThrowIfCancellationRequested(); } // Wait a moment before the next check. await Task.Delay(100, cancel).ConfigureAwait(false); } } catch (Exception) { Process?.Dispose(); throw; } }
public static async Task <CoreNode> CreateAsync(CoreNodeParams coreNodeParams, CancellationToken cancel) { Guard.NotNull(nameof(coreNodeParams), coreNodeParams); using (BenchmarkLogger.Measure()) { var coreNode = new CoreNode(); coreNode.DataDir = coreNodeParams.DataDir; coreNode.Network = coreNodeParams.Network; coreNode.MempoolService = coreNodeParams.MempoolService; var configPath = Path.Combine(coreNode.DataDir, "bitcoin.conf"); coreNode.Config = new CoreConfig(); if (File.Exists(configPath)) { var configString = await File.ReadAllTextAsync(configPath).ConfigureAwait(false); coreNode.Config.TryAdd(configString); } var configDic = coreNode.Config.ToDictionary(); string rpcUser = null; string rpcPassword = null; EndPoint whitebind = null; string rpcHost = null; int? rpcPort = null; string rpcCookieFilePath = null; foreach (var networkPrefixWithDot in NetworkTranslator.GetConfigPrefixesWithDots(coreNode.Network)) { var rpcc = configDic.TryGet($"{networkPrefixWithDot}rpccookiefile"); var ru = configDic.TryGet($"{networkPrefixWithDot}rpcuser"); var rp = configDic.TryGet($"{networkPrefixWithDot}rpcpassword"); var wbs = configDic.TryGet($"{networkPrefixWithDot}whitebind"); var rpst = configDic.TryGet($"{networkPrefixWithDot}rpchost"); var rpts = configDic.TryGet($"{networkPrefixWithDot}rpcport"); if (rpcc != null) { rpcCookieFilePath = rpcc; } if (ru != null) { rpcUser = ru; } if (rp != null) { rpcPassword = rp; } if (wbs != null && EndPointParser.TryParse(wbs, coreNode.Network.DefaultPort, out EndPoint wb)) { whitebind = wb; } if (rpst != null) { rpcHost = rpst; } if (rpts != null && int.TryParse(rpts, out int rpt)) { rpcPort = rpt; } } string authString; bool cookieAuth = rpcCookieFilePath != null; if (cookieAuth) { authString = $"cookiefile={rpcCookieFilePath}"; } else { rpcUser ??= Encoders.Hex.EncodeData(RandomUtils.GetBytes(21)); rpcPassword ??= Encoders.Hex.EncodeData(RandomUtils.GetBytes(21)); authString = $"{rpcUser}:{rpcPassword}"; } coreNode.P2pEndPoint = whitebind ?? coreNodeParams.P2pEndPointStrategy.EndPoint; rpcHost ??= coreNodeParams.RpcEndPointStrategy.EndPoint.GetHostOrDefault(); rpcPort ??= coreNodeParams.RpcEndPointStrategy.EndPoint.GetPortOrDefault(); EndPointParser.TryParse($"{rpcHost}:{rpcPort}", coreNode.Network.RPCPort, out EndPoint rpce); coreNode.RpcEndPoint = rpce; coreNode.RpcClient = new RPCClient($"{authString}", coreNode.RpcEndPoint.ToString(coreNode.Network.DefaultPort), coreNode.Network); if (coreNodeParams.TryRestart) { await coreNode.TryStopAsync(false).ConfigureAwait(false); } if (coreNodeParams.TryDeleteDataDir) { await IoHelpers.DeleteRecursivelyWithMagicDustAsync(coreNode.DataDir).ConfigureAwait(false); } IoHelpers.EnsureDirectoryExists(coreNode.DataDir); var configPrefix = NetworkTranslator.GetConfigPrefix(coreNode.Network); var desiredConfigLines = new List <string>() { $"{configPrefix}.server = 1", $"{configPrefix}.listen = 1", $"{configPrefix}.whitebind = {coreNode.P2pEndPoint.ToString(coreNode.Network.DefaultPort)}", $"{configPrefix}.rpchost = {coreNode.RpcEndPoint.GetHostOrDefault()}", $"{configPrefix}.rpcport = {coreNode.RpcEndPoint.GetPortOrDefault()}" }; if (!cookieAuth) { desiredConfigLines.Add($"{configPrefix}.rpcuser = {coreNode.RpcClient.CredentialString.UserPassword.UserName}"); desiredConfigLines.Add($"{configPrefix}.rpcpassword = {coreNode.RpcClient.CredentialString.UserPassword.Password}"); } if (coreNodeParams.TxIndex != null) { desiredConfigLines.Add($"{configPrefix}.txindex = {coreNodeParams.TxIndex}"); } if (coreNodeParams.Prune != null) { desiredConfigLines.Add($"{configPrefix}.prune = {coreNodeParams.Prune}"); } var sectionComment = $"# The following configuration options were added or modified by Wasabi Wallet."; // If the comment is not already present. // And there would be new config entries added. var throwAwayConfig = new CoreConfig(coreNode.Config); throwAwayConfig.AddOrUpdate(string.Join(Environment.NewLine, desiredConfigLines)); if (!coreNode.Config.ToString().Contains(sectionComment, StringComparison.Ordinal) && throwAwayConfig.Count != coreNode.Config.Count) { desiredConfigLines.Insert(0, sectionComment); } if (coreNode.Config.AddOrUpdate(string.Join(Environment.NewLine, desiredConfigLines)) || !File.Exists(configPath)) { IoHelpers.EnsureContainingDirectoryExists(configPath); await File.WriteAllTextAsync(configPath, coreNode.Config.ToString()); } // If it isn't already running, then we run it. if (await coreNode.RpcClient.TestAsync().ConfigureAwait(false) is null) { Logger.LogInfo("Bitcoin Core is already running."); }
public static async Task <CoreNode> CreateAsync(CoreNodeParams coreNodeParams, CancellationToken cancel) { Guard.NotNull(nameof(coreNodeParams), coreNodeParams); using (BenchmarkLogger.Measure()) { var coreNode = new CoreNode(); coreNode.HostedServices = coreNodeParams.HostedServices; coreNode.DataDir = coreNodeParams.DataDir; coreNode.Network = coreNodeParams.Network; coreNode.MempoolService = coreNodeParams.MempoolService; var configPath = Path.Combine(coreNode.DataDir, "bitcoin.conf"); coreNode.Config = new CoreConfig(); if (File.Exists(configPath)) { var configString = await File.ReadAllTextAsync(configPath).ConfigureAwait(false); coreNode.Config.AddOrUpdate(configString); // Bitcoin Core considers the last entry to be valid. } cancel.ThrowIfCancellationRequested(); var configTranslator = new CoreConfigTranslator(coreNode.Config, coreNode.Network); string rpcUser = configTranslator.TryGetRpcUser(); string rpcPassword = configTranslator.TryGetRpcPassword(); string rpcCookieFilePath = configTranslator.TryGetRpcCookieFile(); string rpcHost = configTranslator.TryGetRpcBind(); int? rpcPort = configTranslator.TryGetRpcPort(); WhiteBind whiteBind = configTranslator.TryGetWhiteBind(); string authString; bool cookieAuth = rpcCookieFilePath is { }; if (cookieAuth) { authString = $"cookiefile={rpcCookieFilePath}"; } else { rpcUser ??= Encoders.Hex.EncodeData(RandomUtils.GetBytes(21)); rpcPassword ??= Encoders.Hex.EncodeData(RandomUtils.GetBytes(21)); authString = $"{rpcUser}:{rpcPassword}"; } coreNode.P2pEndPoint = whiteBind?.EndPoint ?? coreNodeParams.P2pEndPointStrategy.EndPoint; rpcHost ??= coreNodeParams.RpcEndPointStrategy.EndPoint.GetHostOrDefault(); rpcPort ??= coreNodeParams.RpcEndPointStrategy.EndPoint.GetPortOrDefault(); EndPointParser.TryParse($"{rpcHost}:{rpcPort}", coreNode.Network.RPCPort, out EndPoint rpce); coreNode.RpcEndPoint = rpce; var rpcClient = new RPCClient( $"{authString}", coreNode.RpcEndPoint.ToString(coreNode.Network.DefaultPort), coreNode.Network); coreNode.RpcClient = new CachedRpcClient(rpcClient, coreNodeParams.Cache); if (coreNodeParams.TryRestart) { await coreNode.TryStopAsync(false).ConfigureAwait(false); } cancel.ThrowIfCancellationRequested(); if (coreNodeParams.TryDeleteDataDir) { await IoHelpers.DeleteRecursivelyWithMagicDustAsync(coreNode.DataDir).ConfigureAwait(false); } cancel.ThrowIfCancellationRequested(); IoHelpers.EnsureDirectoryExists(coreNode.DataDir); var configPrefix = NetworkTranslator.GetConfigPrefix(coreNode.Network); var whiteBindPermissionsPart = !string.IsNullOrWhiteSpace(whiteBind?.Permissions) ? $"{whiteBind?.Permissions}@" : ""; var desiredConfigLines = new List <string>() { $"{configPrefix}.server = 1", $"{configPrefix}.listen = 1", $"{configPrefix}.whitebind = {whiteBindPermissionsPart}{coreNode.P2pEndPoint.ToString(coreNode.Network.DefaultPort)}", $"{configPrefix}.rpcbind = {coreNode.RpcEndPoint.GetHostOrDefault()}", $"{configPrefix}.rpcallowip = {IPAddress.Loopback}", $"{configPrefix}.rpcport = {coreNode.RpcEndPoint.GetPortOrDefault()}" }; if (!cookieAuth) { desiredConfigLines.Add($"{configPrefix}.rpcuser = {coreNode.RpcClient.CredentialString.UserPassword.UserName}"); desiredConfigLines.Add($"{configPrefix}.rpcpassword = {coreNode.RpcClient.CredentialString.UserPassword.Password}"); } if (coreNodeParams.TxIndex is { })
public static async Task <CoreNode> CreateAsync(CoreNodeParams coreNodeParams, CancellationToken cancel) { Guard.NotNull(nameof(coreNodeParams), coreNodeParams); using (BenchmarkLogger.Measure()) { var coreNode = new CoreNode { DataDir = coreNodeParams.DataDir, Network = coreNodeParams.Network, MempoolService = coreNodeParams.MempoolService }; var configPath = Path.Combine(coreNode.DataDir, "bitcoin.conf"); coreNode.Config = new CoreConfig(); if (File.Exists(configPath)) { var configString = await File.ReadAllTextAsync(configPath, cancel).ConfigureAwait(false); coreNode.Config.AddOrUpdate(configString); // Bitcoin Core considers the last entry to be valid. } cancel.ThrowIfCancellationRequested(); var configTranslator = new CoreConfigTranslator(coreNode.Config, coreNode.Network); string? rpcUser = configTranslator.TryGetRpcUser(); string? rpcPassword = configTranslator.TryGetRpcPassword(); string? rpcCookieFilePath = configTranslator.TryGetRpcCookieFile(); string? rpcHost = configTranslator.TryGetRpcBind(); int? rpcPort = configTranslator.TryGetRpcPort(); WhiteBind?whiteBind = configTranslator.TryGetWhiteBind(); string authString; bool cookieAuth = rpcCookieFilePath is not null; if (cookieAuth) { authString = $"cookiefile={rpcCookieFilePath}"; } else { rpcUser ??= Encoders.Hex.EncodeData(RandomUtils.GetBytes(21)); rpcPassword ??= Encoders.Hex.EncodeData(RandomUtils.GetBytes(21)); authString = $"{rpcUser}:{rpcPassword}"; } coreNode.P2pEndPoint = whiteBind?.EndPoint ?? coreNodeParams.P2pEndPointStrategy.EndPoint; if (rpcHost is null) { coreNodeParams.RpcEndPointStrategy.EndPoint.TryGetHost(out rpcHost); } if (rpcPort is null) { coreNodeParams.RpcEndPointStrategy.EndPoint.TryGetPort(out rpcPort); } if (!EndPointParser.TryParse($"{rpcHost}:{rpcPort}", coreNode.Network.RPCPort, out EndPoint? rpce)) { throw new InvalidOperationException($"Failed to get RPC endpoint on {rpcHost}:{rpcPort}."); } coreNode.RpcEndPoint = rpce; var rpcClient = new RPCClient( $"{authString}", coreNode.RpcEndPoint.ToString(coreNode.Network.DefaultPort), coreNode.Network); coreNode.RpcClient = new CachedRpcClient(rpcClient, coreNodeParams.Cache); if (coreNodeParams.TryRestart) { await coreNode.TryStopAsync(false).ConfigureAwait(false); } cancel.ThrowIfCancellationRequested(); if (coreNodeParams.TryDeleteDataDir) { await IoHelpers.TryDeleteDirectoryAsync(coreNode.DataDir).ConfigureAwait(false); } cancel.ThrowIfCancellationRequested(); IoHelpers.EnsureDirectoryExists(coreNode.DataDir); var configPrefix = NetworkTranslator.GetConfigPrefix(coreNode.Network); var whiteBindPermissionsPart = !string.IsNullOrWhiteSpace(whiteBind?.Permissions) ? $"{whiteBind?.Permissions}@" : ""; if (!coreNode.RpcEndPoint.TryGetHost(out string?rpcBindParameter) || !coreNode.RpcEndPoint.TryGetPort(out int?rpcPortParameter)) { throw new ArgumentException("Endpoint type is not supported.", nameof(coreNode.RpcEndPoint)); } var desiredConfigLines = new List <string>() { $"{configPrefix}.server = 1", $"{configPrefix}.listen = 1", $"{configPrefix}.daemon = 0", // https://github.com/zkSNACKs/WalletWasabi/issues/3588 $"{configPrefix}.whitebind = {whiteBindPermissionsPart}{coreNode.P2pEndPoint.ToString(coreNode.Network.DefaultPort)}", $"{configPrefix}.rpcbind = {rpcBindParameter}", $"{configPrefix}.rpcallowip = {IPAddress.Loopback}", $"{configPrefix}.rpcport = {rpcPortParameter}" }; if (!cookieAuth) { desiredConfigLines.Add($"{configPrefix}.rpcuser = {coreNode.RpcClient.CredentialString.UserPassword.UserName}"); desiredConfigLines.Add($"{configPrefix}.rpcpassword = {coreNode.RpcClient.CredentialString.UserPassword.Password}"); } if (coreNodeParams.TxIndex is { })
void Awake() { networkTranslator = GetComponent <NetworkTranslator>(); }
public void initializeTables() { try { if (tcpPayloads == null) { tcpPayloads = new Dictionary <int, List <ConnectionPayload> >(); } else { tcpPayloads.Clear(); } if (udpPayloads == null) { udpPayloads = new Dictionary <int, List <ConnectionPayload> >(); } else { udpPayloads.Clear(); } TcpTable win32TcpTable = new TcpTable(); UdpTable win32UdpTable = new UdpTable(); TcpTable.MIB_TCPROW_OWNER_PID[] win32TcpRows = win32TcpTable.GetAllTcpConnections(); UdpTable.MIB_UDPROW_OWNER_PID[] win32UdpRows = win32UdpTable.GetAllUdpConnections(); if (win32TcpRows.Length != 0) { for (int i = 0; i < win32TcpRows.Length; i++) { ConnectionPayload connection = new ConnectionPayload(); connection.protocol = ConnectionPayload.NETWORK_PROTOCOL.TCP; connection.state = ((TcpTable.TCP_ROW_STATE)Enum.Parse(typeof(TcpTable.TCP_ROW_STATE), win32TcpRows[i].state.ToString())).ToString(); connection.address = NetworkTranslator.convertUintToIP(win32TcpRows[i].remoteAddr); connection.sourcePort = NetworkTranslator.convertBytesToPort(win32TcpRows[i].localPort1, win32TcpRows[i].localPort2, win32TcpRows[i].localPort3, win32TcpRows[i].localPort4); connection.destinationPort = NetworkTranslator.convertBytesToPort(win32TcpRows[i].remotePort1, win32TcpRows[i].remotePort1, win32TcpRows[i].remotePort1, win32TcpRows[i].remotePort1); connection.PID = win32TcpRows[i].owningPid; if (!tcpPayloads.ContainsKey(connection.PID)) { tcpPayloads.Add(connection.PID, new List <ConnectionPayload>()); } tcpPayloads[connection.PID].Add(connection); } } if (win32UdpRows.Length != 0) { for (int i = 0; i < win32UdpRows.Length; i++) { ConnectionPayload connection = new ConnectionPayload(); connection.protocol = ConnectionPayload.NETWORK_PROTOCOL.UDP; connection.state = UdpTable.UDP_ROW_STATE.ESTABLISHED.ToString(); connection.address = NetworkTranslator.convertUintToIP(win32UdpRows[i].LocalAddr); connection.sourcePort = NetworkTranslator.convertBytesToPort(win32UdpRows[i].localPort1, win32UdpRows[i].localPort2, win32UdpRows[i].localPort3, win32UdpRows[i].localPort4); connection.PID = win32UdpRows[i].owningPid; if (!udpPayloads.ContainsKey(connection.PID)) { udpPayloads.Add(connection.PID, new List <ConnectionPayload>()); } udpPayloads[connection.PID].Add(connection); } } } catch (Exception ex) { } }