예제 #1
0
        private static string CreateAccountKeyStoreFile(Nethereum.Signer.EthECKey ecKey, string password, string name, string path)
        {
            //Get the public address (derivied from the public key)
            var address = ecKey.GetPublicAddress();

            //Create a store service, to encrypt and save the file using the web3 standard
            var service      = new HoardKeyStoreScryptService();
            var encryptedKey = service.EncryptAndGenerateKeyStoreAsJson(password, ecKey.GetPrivateKeyAsBytes(), address).ToLower();

            if (encryptedKey == null)
            {
                throw new HoardException("Failed to encrypt kyestore");
            }
            var keystoreJsonObject = JObject.Parse(encryptedKey);

            if (keystoreJsonObject == null)
            {
                throw new HoardException("Failed to parse json file: " + encryptedKey);
            }
            keystoreJsonObject.Add("name", name);
            encryptedKey = keystoreJsonObject.ToString();
            string id       = keystoreJsonObject["id"].Value <string>();
            var    fileName = id + ".keystore";

            //save the File
            using (var newfile = File.CreateText(Path.Combine(path, fileName)))
            {
                newfile.Write(encryptedKey);
                newfile.Flush();
            }

            return(fileName);
        }
        /// <summary>
        /// Helper function to create Profile object based on privateKey
        /// </summary>
        /// <param name="name">name of profile</param>
        /// <param name="privateKey">private key of account</param>
        /// <returns></returns>
        public static Profile CreateProfileDirect(string name, string privateKey)
        {
            ErrorCallbackProvider.ReportInfo("Generating user account.");
            var     ecKey   = new Nethereum.Signer.EthECKey(privateKey);
            Profile profile = new KeyStoreProfile(name, new HoardID(ecKey.GetPublicAddress()), privateKey.HexToByteArray());

            return(profile);
        }
        public static SignedCertificate CreateCertificate(string userAddress, string testCentreId, string privateKey, string photoUserId)
        {
            var ethEcKey      = new Nethereum.Signer.EthECKey(privateKey);
            var signer        = new Nethereum.Signer.EthereumMessageSigner();
            var signerAddress = ethEcKey.GetPublicAddress();
            var signature     = signer.EncodeUTF8AndSign(SignedCertificate.GetRawCertificate(userAddress, signerAddress, testCentreId, photoUserId), ethEcKey);

            return(new SignedCertificate(userAddress, signerAddress, testCentreId, photoUserId, signature));
        }
예제 #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <param name="privKey"></param>
        /// <param name="profilesDir"></param>
        /// <returns></returns>
        public static Tuple <string, byte[]> CreateProfile(string name, string password, string privKey, string profilesDir)
        {
            if (!Directory.Exists(profilesDir))
            {
                Directory.CreateDirectory(profilesDir);
            }

            var    ecKey       = new Nethereum.Signer.EthECKey(privKey);
            string accountFile = CreateAccountKeyStoreFile(ecKey, password, name, profilesDir);

            return(new Tuple <string, byte[]>(ecKey.GetPublicAddress(), ecKey.GetPrivateKeyAsBytes()));
        }
예제 #5
0
#pragma warning restore IDE0044 // Add readonly modifier

        //Create new account, returns account address
        public string CreateNew(string path, string password)
        {
            Nethereum.Signer.EthECKey ecKey = Nethereum.Signer.EthECKey.GenerateKey();
            string          address         = ecKey.GetPublicAddress();
            KeyStoreService service         = new KeyStoreService();
            string          encryptedKey    = service.EncryptAndGenerateDefaultKeyStoreAsJson(password, ecKey.GetPrivateKeyAsBytes(), address);
            string          filename        = service.GenerateUTCFileName(address);

            SaveToKeystore(path, filename, encryptedKey);

            return(address);
        }
예제 #6
0
        /// <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);
            }
        }
예제 #7
0
 void Update()
 {
     if (worker_ != null)
     {
         Thread.MemoryBarrier();
         if (worker_.result_ != 0)
         {
             if (worker_.result_ < 0)
             {
                 Error = new System.Exception(
                     "AccountInitializer fails with code:" + worker_.result_);
                                 #if UNITY_EDITOR
                 UnityEditor.EditorApplication.isPlaying = false;
                                 #else
                 Application.Quit();
                                 #endif
             }
             else
             {
                 var ks = worker_.keyStore_;
                 if (!string.IsNullOrEmpty(ks))
                 {
                     PlayerPrefs.SetString(KEY_PREFIX + "_key_store", ks);
                     PlayerPrefs.SetInt(KEY_PREFIX + "_key_store_encyption",
                                        (int)(encyption_ ? Encyption.On : Encyption.Off));
                     PlayerPrefs.Save();
                 }
                 //Get the public address (derivied from the public key)
                 address_ = key_.GetPublicAddress();
                 subject_.OnNext(new Event {
                     Type = EventType.InitSuccess
                 });
                 Debug.Log("wallet address:" + address_ + " pkey:" + key_.GetPrivateKey());
             }
             worker_ = null;
         }
     }
 }
예제 #8
0
        /// <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));
        }