Example #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="profilesDir"></param>
        /// <returns></returns>
        public static string LoadEncryptedProfile(HoardID id, string profilesDir)
        {
            if (!Directory.Exists(profilesDir))
            {
                throw new HoardException(string.Format("Profile doesn't exists: {0}", id.ToString()));
            }

            var profileFiles = Directory.GetFiles(profilesDir, "*.keystore");

            if (profileFiles.Length == 0)
            {
                throw new HoardException(string.Format("Profile doesn't exists: {0}", id.ToString()));
            }

            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>();
                    if (new HoardID(address) == id)
                    {
                        return(json);
                    }
                }
            }

            throw new HoardException(string.Format("Profile doesn't exists: {0}", id.ToString()));
        }
        public async Task SignTransaction()
        {
            HoardID to       = new HoardID("0x4bc1EF56d94c766A49153A102096E56fAE2004e1");
            var     nonce    = 324.ToBytesForRLPEncoding();
            var     gasPrice = 10000000000000.ToBytesForRLPEncoding();
            var     startGas = 21000.ToBytesForRLPEncoding();
            var     value    = 10000.ToBytesForRLPEncoding();
            var     data     = "".HexToByteArray();

            var txEncoded = new List <byte[]>();

            txEncoded.Add(RLP.EncodeElement(nonce));
            txEncoded.Add(RLP.EncodeElement(gasPrice));
            txEncoded.Add(RLP.EncodeElement(startGas));
            txEncoded.Add(RLP.EncodeElement(to.ToHexByteArray()));
            txEncoded.Add(RLP.EncodeElement(value));
            txEncoded.Add(RLP.EncodeElement(data));

            var rlpEncodedTransaction = RLP.EncodeList(txEncoded.ToArray());

            var user = await signer.RequestProfile(signer.Name + "\0");

            var signature = await user.SignTransaction(rlpEncodedTransaction);

            var account = Hoard.Utils.Helper.RecoverHoardIdFromTransaction(signature, rlpEncodedTransaction);

            Assert.Equal(user.ID, account);
        }
        public async Task SignMessage()
        {
            var message   = "Hello world";
            var byteMsg   = message.ToBytesForRLPEncoding();
            var signature = await user.SignMessage(byteMsg);

            HoardID account = Hoard.Utils.Helper.RecoverHoardIdFromMessage(byteMsg, signature);

            Assert.Equal(user.ID, account);
        }
        /// <inheritdoc/>
        public override async Task <BigInteger> GetBalanceOf(HoardID address)
        {
            var balanceData = await plasmaComm.GetBalanceData(address, contract.Address);

            if (balanceData is NFCBalanceData)
            {
                return((balanceData as NFCBalanceData).TokenIds.Length);
            }
            return(0);
        }
        /// <summary>
        ///   Clear the password from the local storage
        /// </summary>
        public void DeleteSavedPasswordFor(HoardID userID)
        {
            var pathToFile = PathToID(userID);

            if (!File.Exists(pathToFile))
            {
                throw new FileNotFoundException("Storage file not found for " + userID);
            }
            File.Delete(pathToFile);
        }
Example #6
0
        public override async Task <Profile> RequestProfile(string name)
        {
            uint accountIndex = ProfileNameToIndex(name);
            var  keyPath      = new KeyPath(DerivationPath).Derive(accountIndex);

            var output = await SendRequestAsync(EthGetAddress.Request(keyPath.Indices));

            var address = new HoardID(EthGetAddress.GetAddress(output));

            return(new HDWalletProfile(name, address, keyPath.Indices, this));
        }
Example #7
0
        /// <summary>
        /// Returns HRD balance of given account
        /// </summary>
        /// <param name="account">account to query</param>
        /// <returns></returns>
        public async Task <BigInteger> GetHRDBalance(HoardID account)
        {
            string hrdAddress = await GetHRDAddress();

            if (hrdAddress != null)
            {
                hrdAddress.RemoveHexPrefix();

                HoardTokenContract hrdContract = new HoardTokenContract(web, hrdAddress);
                return(await hrdContract.GetBalanceOf(account));
            }
            return(new BigInteger(0));
        }
Example #8
0
        /// <summary>
        /// Returns UTXO of given account, currency and amount
        /// </summary>
        /// <param name="account">account to query</param>
        /// <param name="currency">currency to query</param>
        /// <param name="data">data to query (amount or token id)</param>
        /// <returns></returns>
        public async Task <UTXOData> GetUtxo(HoardID account, string currency, BigInteger data)
        {
            var utxos = await GetUtxos(account);

            foreach (var utxo in utxos)
            {
                if (utxo.Currency == currency.EnsureHexPrefix().ToLower() && utxo.Data == data)
                {
                    return(utxo);
                }
            }
            return(null);
        }
Example #9
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id"></param>
 /// <param name="encryptedData"></param>
 /// <returns></returns>
 public string DecryptPassword(HoardID id, EncryptedData encryptedData)
 {
     try
     {
         byte[] decryptionKey = GenerateKey(ProvideEncryptionPhrase());
         byte[] decrypted     = Helper.AESDecrypt(decryptionKey, WhisperService.HexStringToByteArray(encryptedData.pswd), ProvideIV(), 256);
         return(Encoding.UTF8.GetString(decrypted));
     }
     catch (Exception e)
     {
         throw new HoardException("Can't decrypt password for id " + id.ToString(), e);
     }
 }
        public Task <string> RequestInput(string name, HoardID id, eUserInputType type, string description)
        {
            switch (type)
            {
            case eUserInputType.kLogin:
                return(Task.Run(() => UserName));

            case eUserInputType.kPassword:
                return(Task.Run(() => EncryptedPassword));

            default:
                throw new System.NotImplementedException("Decrypted credentials can't provide information about " + type.ToString());
            }
        }
            /// <summary>
            ///
            /// </summary>
            /// <param name="name"></param>
            /// <param name="id"></param>
            /// <param name="type"></param>
            /// <param name="description"></param>
            /// <returns></returns>
            public async Task <string> RequestInput(string name, HoardID id, eUserInputType type, string description)
            {
                await Task.Yield();

                if (type == eUserInputType.kLogin)
                {
                    return("TestUser");
                }
                else if (type == eUserInputType.kPassword)
                {
                    return("dev");
                }
                return(null);
            }
        public async Task EncryptAndSaveCredentials(HoardID userID, IUserInputProvider credentials)
        {
            var pathToFile = PathToID(userID);
            var pass       = await credentials.RequestInput("Password", userID, eUserInputType.kPassword, "");

            var encrypted = EncryptPassword(userID, pass);

            using (var file = new StreamWriter(pathToFile, true))
            {
                var converted = await Task.Run(() => JsonConvert.SerializeObject(encrypted));

                await file.WriteAsync(converted);
            }
        }
Example #13
0
        public override async Task<Profile> RequestProfile(string name)
        {
            uint accountIndex = ProfileNameToIndex(name);
            var keyPath = new KeyPath(DerivationPath).Derive(accountIndex);
            byte[] derivationData = keyPath.ToBytes();
            var output = await SendRequestAsync(EthGetAddress.Request(derivationData));
            if(IsSuccess(output.StatusCode))
            {
                var address = new HoardID(EthGetAddress.GetAddress(output.Data));
                return new HDWalletProfile(name, address, derivationData, this);
            }

            throw new Exception("HD wallet returned error: " + output.StatusCode);
        }
Example #14
0
        /// <summary>
        /// Returns UTXOs of given account in given currency
        /// </summary>
        /// <param name="account">account to query</param>
        /// <param name="currency">currency to query</param>
        /// <returns></returns>
        public async Task <UTXOData[]> GetUtxos(HoardID account, string currency)
        {
            var utxos = await GetUtxos(account);

            var result = new List <UTXOData>();

            foreach (var utxo in utxos)
            {
                if (utxo.Currency == currency.EnsureHexPrefix().ToLower())
                {
                    result.Add(utxo);
                }
            }
            return(result.ToArray());
        }
Example #15
0
        /// <inheritdoc/>
        public override async Task <GameItem[]> GetGameItems(HoardID address)
        {
            var items       = new List <GameItem>();
            var balanceData = await plasmaComm.GetBalanceData(address, contract.Address);

            if (balanceData is FCBalanceData)
            {
                string symbol = await contract.GetSymbol();

                string state = (await(contract as ERC223GameItemContract).GetTokenState()).ToHex(true);

                ERC223GameItemContract.Metadata meta = new ERC223GameItemContract.Metadata(contract.Address, (balanceData as FCBalanceData).Amount);
                items.Add(new GameItem(game, symbol, meta));
            }
            return(items.ToArray());
        }
Example #16
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="name"></param>
            /// <param name="id"></param>
            /// <param name="type"></param>
            /// <param name="description"></param>
            /// <returns></returns>
            public async Task <string> RequestInput(string name, HoardID id, eUserInputType type, string description)
            {
                await Task.Yield();

                if (type == eUserInputType.kPIN)
                {
                    var pinWindow = new PINWindow();
                    pinWindow.Text = description;
                    pinWindow.ShowDialog();
                    pinWindow.PINEnteredEvent.WaitOne();
                    pinWindow.PINEnteredEvent.Reset();
                    pinWindow.Dispose();
                    return(pinWindow.PINValue);
                }
                return(null);
            }
Example #17
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id"></param>
 /// <param name="password"></param>
 /// <returns></returns>
 public EncryptedData EncryptPassword(HoardID id, string password)
 {
     try
     {
         byte[]        encryptionKey = GenerateKey(ProvideEncryptionPhrase());
         byte[]        _iv           = ProvideIV();
         byte[]        encryptedData = Helper.AESEncrypt(encryptionKey, Encoding.UTF8.GetBytes(password), _iv, 256);
         string        hashedId      = Helper.Keccak256HexHashString(id.ToString());
         EncryptedData data          = new EncryptedData();
         data.pswd = BitConverter.ToString(encryptedData).Replace("-", string.Empty);
         return(data);
     }
     catch (Exception e)
     {
         throw new HoardException("Can't encrypt password for id " + id.ToString(), e);
     }
 }
        /// <summary>
        ///   Decrypts the password
        /// </summary>
        public async Task <string> DecryptPasswordFor(HoardID userID)
        {
            var pathToFile = PathToID(userID);

            if (!File.Exists(pathToFile))
            {
                throw new FileNotFoundException("Storage file not found for " + userID);
            }

            using (var file = new StreamReader(pathToFile, true))
            {
                var buffer = await file.ReadToEndAsync();

                var encrypted = JsonConvert.DeserializeObject <EncryptedData>(buffer);
                var decrypted = DecryptPassword(userID, encrypted);

                return(decrypted);
            }
        }
Example #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userInputProvider"></param>
        /// <param name="id"></param>
        /// <param name="profilesDir"></param>
        /// <param name="passwordNeeded"></param>
        /// <returns></returns>
        public static async Task DeleteProfile(IUserInputProvider userInputProvider, HoardID id, string profilesDir, bool passwordNeeded)
        {
            if (!Directory.Exists(profilesDir))
            {
                throw new HoardException(string.Format("Profile doesn't exists: {0}", id.ToString()));
            }

            string[] files           = Directory.GetFiles(profilesDir, "*.keystore");
            var      keyStoreService = new Nethereum.KeyStore.KeyStoreService();

            foreach (string file in files)
            {
                StreamReader jsonReader = new StreamReader(file);
                JObject      jobj       = JObject.Parse(jsonReader.ReadToEnd());
                jsonReader.Close();
                JToken valueAddress;
                if (jobj.TryGetValue("address", out valueAddress))
                {
                    HoardID actualId = new HoardID(valueAddress.Value <string>());
                    if (id == actualId)
                    {
                        Nethereum.Signer.EthECKey key = null;
                        if (passwordNeeded)
                        {
                            string password = await userInputProvider.RequestInput(null, id, eUserInputType.kPassword, valueAddress.Value <string>());

                            try
                            {
                                key = new Nethereum.Signer.EthECKey(keyStoreService.DecryptKeyStoreFromJson(password, jobj.ToString()), true);
                            }
                            catch (Exception e)
                            {
                                throw new HoardException("Incorrect password", e);
                            }
                        }
                        File.Delete(file);
                        return;
                    }
                }
            }

            throw new HoardException(string.Format("Profile doesn't exists: {0}", id.ToString()));
        }
Example #20
0
        private async Task <GameItem[]> GetItemsClientRequest(HoardID accountId = null, string itemType = null, ulong?page = null, ulong?itemsPerPage = null)
        {
            var request = new RestRequest("items/", Method.GET);

            if (accountId != null)
            {
                request.AddQueryParameter("owner_address", accountId.ToString().EnsureHexPrefix());
            }

            if (itemType != null)
            {
                request.AddQueryParameter("item_type", itemType);
            }

            if (page.HasValue)
            {
                request.AddQueryParameter("page", page.Value.ToString());
                if (itemsPerPage != null)
                {
                    request.AddQueryParameter("per_page", itemsPerPage.Value.ToString());
                }
            }

            var response = await Client.ExecuteTaskAsync(request).ConfigureAwait(false);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var gameItems = new List <GameItem>();

                var result = JArray.Parse(response.Content);
                foreach (var item in result.Children <JObject>())
                {
                    gameItems.AddRange(JsonConvert.DeserializeObject <List <GameItem> >(
                                           item.GetValue("items").ToString(),
                                           new JsonConverter[] { new GameItemsConverter() }
                                           ));
                }

                return(gameItems.ToArray());
            }

            return(null);
        }
Example #21
0
        /// <summary>
        /// Returns balance of given account and currency
        /// </summary>
        /// <param name="account">account to query</param>
        /// <param name="currency">currency to query</param>
        /// <returns></returns>
        protected async Task <BigInteger> GetBalance(HoardID account, string currency)
        {
            var balances = await GetBalanceData(account);

            var utxoData = balances.FirstOrDefault(x => x.Currency == currency.EnsureHexPrefix().ToLower());

            if (utxoData != null)
            {
                if (utxoData is FCBalanceData)
                {
                    return((utxoData as FCBalanceData).Amount);
                }
                if (utxoData is NFCBalanceData)
                {
                    return((utxoData as NFCBalanceData).TokenIds.Length);
                }
            }
            return(0);
        }
Example #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <param name="profilesDir"></param>
        /// <returns></returns>
        public static string ChangePassword(HoardID id, string oldPassword, string newPassword, string profilesDir)
        {
            if (!Directory.Exists(profilesDir))
            {
                throw new HoardException(string.Format("Profile doesn't exists: {0}", id.ToString()));
            }

            string[] files           = Directory.GetFiles(profilesDir, "*.keystore");
            var      keyStoreService = new Nethereum.KeyStore.KeyStoreService();

            foreach (string file in files)
            {
                StreamReader jsonReader = new StreamReader(file);
                JObject      jobj       = JObject.Parse(jsonReader.ReadToEnd());
                jsonReader.Close();
                JToken valueAddress;
                JToken name;
                if (jobj.TryGetValue("address", out valueAddress) && jobj.TryGetValue("name", out name))
                {
                    HoardID actualId = new HoardID(valueAddress.Value <string>());
                    if (id == actualId)
                    {
                        string newFile = null;
                        try
                        {
                            var key = new Nethereum.Signer.EthECKey(keyStoreService.DecryptKeyStoreFromJson(oldPassword, jobj.ToString()), true);
                            newFile = CreateAccountKeyStoreFile(key, newPassword, name.Value <string>(), profilesDir);
                        }
                        catch (Exception e)
                        {
                            throw new HoardException("Incorrect password", e);
                        }
                        if (newFile != null)
                        {
                            File.Delete(file);
                        }
                        return(newFile);
                    }
                }
            }
            throw new HoardException(string.Format("Profile doesn't exists: {0}", id.ToString()));
        }
Example #23
0
        private async Task <ulong> GetItemsAmountClientRequest(HoardID accountId, string itemType = null)
        {
            var request = new RestRequest("items/balance/", Method.GET);

            request.AddQueryParameter("owner_address", accountId.ToString().EnsureHexPrefix());

            if (itemType != null)
            {
                request.AddQueryParameter("item_type", itemType);
            }

            var response = await Client.ExecuteTaskAsync(request).ConfigureAwait(false);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var result = JObject.Parse(response.Content);
                return(result.GetValue("balance").Value <ulong>());
            }

            return(0);
        }
Example #24
0
        /// <inheritdoc/>
        public override async Task <GameItem[]> GetGameItems(HoardID address)
        {
            var items       = new List <GameItem>();
            var balanceData = await plasmaComm.GetBalanceData(address, contract.Address);

            if (balanceData is NFCBalanceData)
            {
                string symbol = await contract.GetSymbol();

                foreach (var tokenId in (balanceData as NFCBalanceData).TokenIds)
                {
                    ERC721GameItemContract.Metadata meta = new ERC721GameItemContract.Metadata(contract.Address, tokenId);
                    GameItem gameItem = new GameItem(game, symbol, meta);
                    gameItem.State = await plasmaComm.GetTokenState(contract.Address, tokenId);

                    items.Add(gameItem);
                }
            }

            return(items.ToArray());
        }
Example #25
0
        /// <inheritdoc/>
        public async Task <BigInteger> GetBalance(HoardID account)
        {
            var ver = new Nethereum.RPC.Eth.EthGetBalance(web.Client);

            return((await ver.SendRequestAsync(account)).Value);
        }
Example #26
0
 public HDWalletProfile(string name, HoardID id, uint[] indices, EthTrezorWallet wallet)
     : base(name, id)
 {
     Wallet            = wallet;
     DerivationIndices = indices;
 }
 private string PathToID(HoardID userID)
 => Path.Combine(StoragePath, userID.ToString()) + ".hse";
Example #28
0
 /// <summary>
 /// Returns total amount of items given account owns
 /// </summary>
 /// <param name="address">Account address of the owner</param>
 /// <returns></returns>
 public abstract Task <BigInteger> GetBalanceOf(HoardID address);
 /// <summary>
 ///   Has the user it's password saved?
 /// </summary>
 public bool HasPasswordSaved(HoardID userID)
 => File.Exists(PathToID(userID));
Example #30
0
 public HDWalletProfile(string name, HoardID id, byte[] data, EthLedgerWallet wallet)
     :base(name, id)
 {
     Wallet = wallet;
     DerivationData = data;
 }