/// <summary> /// /// </summary> /// <param name="token"></param> /// <returns></returns> public async Task <bool> Connect(CancellationToken token) { try { TimeoutCounter = TimeOut; Socket = SocketCreate(Url); while (SocketState(Socket) == 0) { await Task.Yield(); TimeoutCounter -= Time.unscaledDeltaTime; if (TimeoutCounter < 0.0f) { ErrorCallbackProvider.ReportError("Connection timeout!"); return(false); } } } catch (TimeoutException) { ErrorCallbackProvider.ReportError("Connection timeout!"); return(false); } if (SocketState(Socket) != 1) { ErrorCallbackProvider.ReportError("Cannot connect to destination host: " + Url); return(false); } ErrorCallbackProvider.ReportInfo("Connection established"); return(true); }
/// <summary> /// Returns the translated text for the Selected language. /// </summary> public static string GetTranslation(string entry, string languageCode = null) { if (languageCode == null) { languageCode = languageDictionary == null ? throw new System.ArgumentException("No standard language selected") : languageDictionary.lang; } else if (languageDictionary == null) { if (fullLockit.languages.ContainsKey(languageCode)) { languageDictionary = fullLockit.languages[languageCode]; } } if (languageDictionary == null) { ErrorCallbackProvider.ReportError(string.Format("Language of code {0}: not existent in dictionary ", languageCode)); return(entry); } if (!languageDictionary.EntriesDictionary.ContainsKey(entry)) { return(entry); } return(languageDictionary.EntriesDictionary[entry]); }
/// <summary> /// /// </summary> /// <param name="profilesDir"></param> /// <param name="enumFunc"></param> /// <returns></returns> public static async Task EnumerateProfiles(string profilesDir, Func <string, Task> enumFunc) { ErrorCallbackProvider.ReportInfo(string.Format("Loading profiles from path: {0}", profilesDir)); if (!Directory.Exists(profilesDir)) { ErrorCallbackProvider.ReportWarning("Not found any profile files."); return; } var accountsFiles = Directory.GetFiles(profilesDir, "*.keystore"); if (accountsFiles.Length == 0) { ErrorCallbackProvider.ReportWarning("Not found any profiles files."); return; } foreach (var fullPath in accountsFiles) { string fileName = Path.GetFileName(fullPath); if ((fileName != null) && (fileName != System.String.Empty)) { await enumFunc(fileName); } } }
/// <summary> /// Registers existing Hoard game. This game must exist on Hoard platform. /// This function performs initial setup of game contract. /// </summary> /// <param name="game">[in/out] game object must contain valid ID. Other fields will be retrieved from platform</param> /// <returns></returns> public async Task RegisterHoardGame(GameID game) { if (gameContracts.ContainsKey(game)) { ErrorCallbackProvider.ReportWarning("Game already registered!"); return; } string gameAddress = await gameCenter.GetGameContractAsync(game.ID); if (gameAddress != Eth.Utils.EMPTY_ADDRESS && gameAddress != "0x") { GameContract gameContract = new GameContract(web, gameAddress); string url = await gameContract.GetGameServerURLAsync(); game.Name = await gameContract.GetName(); game.GameOwner = await gameContract.GetOwner(); if ((url != null) && (url.Length > 0)) { game.Url = !url.StartsWith("http") ? "http://" + url : url; } gameContracts.Add(game, gameContract); return; } throw new HoardException($"Game is not registered in Hoard Game Center: game = {game.ID}!"); }
public void TestCryptoKittyProvider() { hoardFixture.InitializeFromConfig(); HoardService hoard = hoardFixture.HoardService; if (hoard.DefaultGame != GameID.kInvalidID) { ErrorCallbackProvider.ReportInfo("\tName: " + hoard.DefaultGame.Name); ErrorCallbackProvider.ReportInfo("\tBackend Url: " + hoard.DefaultGame.Url); ErrorCallbackProvider.ReportInfo("\tGameID: " + hoard.DefaultGame.ID); } //Hoard.PlayerID myId = new PlayerID("0x5d0774af3a8f7656dc61bcf30e383056275911b7",""); //Assert.True(myId != PlayerID.kInvalidID, "ERROR: Invalid player ID!"); //ErrorCallbackProvider.ReportInfo(string.Format("Current player is: {0}", myId.ID)); GameID myGame = GameID.FromName("mygame"); try { hoard.RegisterGame(myGame, new CKGameItemProvider(myGame)); GameItem[] items = hoard.GetPlayerItems(hoardFixture.UserIDs[0], myGame).Result; ErrorCallbackProvider.ReportInfo("Shutting down HOARD..."); hoard.Shutdown(); } catch (Exception) { Assert.True(false); } }
private static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { // Collect the sort command output. if (!string.IsNullOrEmpty(outLine.Data)) { ErrorCallbackProvider.ReportInfo(outLine.Data); } }
/// <summary> /// Closes top view but not go back to previous view. /// </summary> public static void CloseTopView() { if (stackedControlers.Count == 0) { ErrorCallbackProvider.ReportWarning(string.Format("Attempt to call {0} when controllers count is 0. Check code logic")); return; } var view = stackedControlers.Pop(); view.CloseAndDisable(); }
/// <summary> /// Creates BCComm object. /// </summary> /// <param name="client">JsonRpc client implementation</param> /// <param name="gameCenterContract">game center contract address</param> public BCComm(Nethereum.JsonRpc.Client.IClient client, string gameCenterContract) { web = new Web3(client); if (gameCenterContract == null) { ErrorCallbackProvider.ReportError("Game center contract cannot be null!"); } gameCenter = (GameCenterContract)GetContract(typeof(GameCenterContract), gameCenterContract); }
/// <summary> /// Loads account information for the user /// </summary> /// <param name="userInputProvider">Provider with user credentials</param> /// <param name="filename">filename of the file with account to load</param> /// <param name="profilesDir">folder where the key store files are stored</param> /// <returns>description making an account</returns> public static async Task <ProfileDesc> LoadProfile(IUserInputProvider userInputProvider, string filename, string profilesDir) { if (!Directory.Exists(profilesDir)) { throw new HoardException(string.Format("Profile doesn't exists: {0:1}", profilesDir, filename)); } var profileFiles = Directory.GetFiles(profilesDir, filename); if (profileFiles.Length == 0) { throw new HoardException(string.Format("Profile doesn't exists: {0:1}", profilesDir, filename)); } ErrorCallbackProvider.ReportInfo(string.Format("Loading profiles {0}", profileFiles[0])); string json = null; using (var reader = File.OpenText(profileFiles[0])) { json = await reader.ReadToEndAsync(); } var details = JObject.Parse(json); if (details == null) { throw new HoardException(string.Format("Can't parse json: {0}", json)); } string address = details["address"].Value <string>(); string name = ""; if (details["name"] != null) { name = details["name"].Value <string>(); } string password = await userInputProvider.RequestInput(name, new HoardID(address), eUserInputType.kPassword, address); var keyStoreService = new Nethereum.KeyStore.KeyStoreService(); Nethereum.Signer.EthECKey key = null; try { key = new Nethereum.Signer.EthECKey(keyStoreService.DecryptKeyStoreFromJson(password, json), true); return(new ProfileDesc(name, key.GetPublicAddress(), key.GetPrivateKeyAsBytes())); } catch (Exception e) { throw new HoardException("Incorrect password", e); } }
/// <summary> /// Connects to Hoard Game Server /// </summary> /// <returns></returns> public async Task Connect() { //1. connect to REST server if (!string.IsNullOrEmpty(Game.Url)) { await ConnectToGameServer(); } else { ErrorCallbackProvider.ReportWarning("Game.Url is empty - all data will be provided by BlockChain provider!"); } //2. check also fallback connector if (SecureProvider != null) { await SecureProvider.Connect(); } }
/// <summary> /// /// </summary> /// <param name="token"></param> /// <returns></returns> public async Task <byte[]> Receive(CancellationToken token) { await Task.Yield(); if (IsConnectionOpen() == false) { return(null); } int length = SocketRecvLength(Socket); if (length == 0) { JObject jobj = new JObject(); return(Encoding.UTF8.GetBytes(jobj.ToString())); } byte[] buffer = new byte[length]; SocketRecv(Socket, buffer, length); ErrorCallbackProvider.ReportInfo(Encoding.UTF8.GetString(buffer)); return(buffer); }
/// <summary> /// Reads the profiles from the storage and store them in AvailableProfileNames property /// </summary> public void GetProfiles() { // Enumerate all *.keystore files located in ProfilesDir directory. /// NOTE That is hardly easy to use ErrorCallbackProvider.ReportWarning("Reading from : " + ProfilesDir); Hoard.Utils.KeyStoreUtils.EnumerateProfiles(ProfilesDir, (Func <string, Task>)(async(fileName) => { await Task.Yield(); StreamReader jsonReader = new StreamReader(Path.Combine(ProfilesDir, fileName)); JObject jobj = JObject.Parse(jsonReader.ReadToEnd()); jsonReader.Close(); JToken valueAddress; JToken valueName; // Valid keystore file should contain address and name. if (jobj.TryGetValue("address", out valueAddress) && jobj.TryGetValue("name", out valueName)) { AvailableProfileNames.Add(new ProfileDescription((string)valueName.Value <string>(), (HoardID) new HoardID((string)valueAddress.Value <string>()))); } })).ContinueGUISynch(x => Initialized = true); }
public void TestHoardGames() { hoardFixture.InitializeFromConfig(); HoardService = hoardFixture.HoardService; //ulong amount = (ulong)HoardService.GetHRDAmount(HoardService.DefaultPlayer); if (HoardService.DefaultGame != GameID.kInvalidID) { ErrorCallbackProvider.ReportInfo("\tName: " + HoardService.DefaultGame.Name); ErrorCallbackProvider.ReportInfo("\tBackend Url: " + HoardService.DefaultGame.Url); ErrorCallbackProvider.ReportInfo("\tGameID: " + HoardService.DefaultGame.ID); } ErrorCallbackProvider.ReportInfo("Getting Hoard games..."); GameID[] games = HoardService.GetAllHoardGames().Result; ErrorCallbackProvider.ReportInfo(string.Format("Found {0} Hoard games.", games.Length)); foreach (GameID game in games) { //Register hoard provider for this gam ErrorCallbackProvider.ReportInfo(string.Format("Registering Hoard game {0}", game.Name)); HoardService.RegisterHoardGame(game); ErrorCallbackProvider.ReportInfo(string.Format("Getting player items for game {0}", game.Name)); GameItem[] items = HoardService.GetPlayerItems(hoardFixture.UserIDs[0], game).Result; ErrorCallbackProvider.ReportInfo(string.Format("Found {0} items.", items.Length)); foreach (GameItem gi in items) { //assume we need to populate properties //TODO: if properties is not null we would need to compare state with some cached data and if there is mismatch update too ErrorCallbackProvider.ReportInfo(string.Format("Getting properties for item {0}:{1}...", gi.Symbol, gi.State)); if (gi.Properties == null) { HoardService.FetchItemProperties(gi); } //TODO: enumerate properties... } } // Check exchange IExchangeService exchange = HoardService.ExchangeService; if (exchange != null) { var orders = exchange.ListOrders(null, null, null).Result; ErrorCallbackProvider.ReportInfo(string.Format("Found {0} exchange orders.", orders.Length)); foreach (Order order in orders) { ErrorCallbackProvider.ReportInfo(string.Format("Order: Buy {0} {1} for {2} {3}.", order.amountGive, order.gameItemGive.Symbol, order.amountGet, order.gameItemGet.Symbol )); } // test trade: /*if (orders.Length > 1) * { * Order order = orders[0]; * bool result = exchange.Deposit(order.gameItemGet, order.amountGet).Result; * result = exchange.Trade(order, order.amountGet).Result; * result = exchange.Withdraw(order.gameItemGive, order.amountGive).Result; * }*/ } ErrorCallbackProvider.ReportInfo("Shutting down HOARD..."); HoardService.Shutdown(); }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="inner"></param> public HoardException(string message, Exception inner) : base(message, inner) { ErrorCallbackProvider.ReportError(message); }
/// <summary> /// /// </summary> /// <param name="userInputProvider"></param> /// <param name="addressOrName"></param> /// <param name="profilesDir"></param> /// <param name="password"></param> /// <returns></returns> public static async Task <ProfileDesc> RequestProfile(IUserInputProvider userInputProvider, string addressOrName, string profilesDir, string password = null) { if (!Directory.Exists(profilesDir)) { throw new HoardException(string.Format("Profile doesn't exists: {0}", addressOrName)); } var profileFiles = Directory.GetFiles(profilesDir, "*.keystore"); if (profileFiles.Length == 0) { throw new HoardException(string.Format("Profile doesn't exists: {0}", addressOrName)); } string providedAddress = addressOrName; if (!providedAddress.StartsWith("0x")) { providedAddress = "0x" + providedAddress; } bool isValidAddress = Nethereum.Util.AddressUtil.Current.IsValidEthereumAddressHexFormat(providedAddress); if (isValidAddress == false) { throw new HoardException(string.Format("{0} is not a valid ethereum address", providedAddress)); } foreach (var fullPath in profileFiles) { string fileName = Path.GetFileName(fullPath); if ((fileName != null) && (fileName != System.String.Empty)) { string json = File.ReadAllText(fullPath); var details = JObject.Parse(json); if (details == null) { continue; } string address = details["address"].Value <string>(); string profileName = ""; if (details["name"] != null) { profileName = details["name"].Value <string>(); } if (((isValidAddress == true) && (address == providedAddress)) || ((isValidAddress == false) && (profileName == addressOrName))) { ErrorCallbackProvider.ReportInfo(string.Format("Loading account {0}", fileName)); string pswd = null; if (password == null) { pswd = await userInputProvider.RequestInput(profileName, new HoardID(address), eUserInputType.kPassword, address); } else { pswd = password; } var keyStoreService = new Nethereum.KeyStore.KeyStoreService(); Nethereum.Signer.EthECKey key = null; try { key = new Nethereum.Signer.EthECKey(keyStoreService.DecryptKeyStoreFromJson(pswd, json), true); return(new ProfileDesc(profileName, key.GetPublicAddress(), key.GetPrivateKeyAsBytes())); } catch (Exception e) { throw new HoardException("Incorrect password", e); } } } } throw new HoardException(string.Format("Failed to request profile: {0}", providedAddress)); }