예제 #1
0
        static void Main(string[] args)
        {
            // The Digital Assistant, main account. When starting TestRPC, this address needs to be updated
            var ecKey      = new Nethereum.Signer.EthECKey("0xc6bd77dc9f1b685865155d05c5d5719f4e3c51bdac1d5f09172b2573773bbd04");
            var privateKey = ecKey.GetPrivateKeyAsBytes();
            var account    = new Nethereum.Web3.Accounts.Account(privateKey);

            // A new account for the agent
            var agentKey     = Nethereum.Signer.EthECKey.GenerateKey();
            var agentAccount = new Nethereum.Web3.Accounts.Account(agentKey.GetPrivateKeyAsBytes());

            Console.WriteLine($"Agent created: {agentAccount.Address}");

            // Connect to the Ethereum network in the Digital Assistant account context, to create the contract
            var web3 = new Nethereum.Web3.Web3(account);

            var transactionHash = web3.Eth.DeployContract.SendRequestAsync(abi, byteCode, account.Address, new Nethereum.Hex.HexTypes.HexBigInteger(900000), agentAccount.Address).Result;
            var receipt         = MineAndGetReceipt(web3, transactionHash);
            var contractAddress = receipt.ContractAddress;

            Console.WriteLine($"Contract created: {contractAddress}");
            Console.ReadKey();

            var actor  = ActorProxy.Create <IUserAgent>(ActorId.CreateRandom(), new Uri("fabric:/Transportation/UserAgentActorService"));
            var retval = actor.GetTransportAsync("add schedule here", agentKey.GetPrivateKeyAsBytes(), contractAddress);

            Console.WriteLine($"Result for getting transport data: {retval.Result}");
            Console.ReadKey();
        }
예제 #2
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);
        }
예제 #3
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()));
        }
예제 #4
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);
            }
        }
예제 #5
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));
        }
예제 #6
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);
        }