/// <summary>
        /// 通过私钥生成公钥
        /// </summary>
        /// <param name="privateKey">私钥</param>
        /// <returns>返回公钥</returns>
        public static string GeneratorPublicKeyByPrivateKey(string privateKey)
        {
            var ecKey     = new Nethereum.Signer.EthECKey(privateKey);
            var publicKey = "0x" + ecKey.GetPubKeyNoPrefix().ToHex();

            return(publicKey);
        }
Exemple #2
0
        public static Address ExtractInteropAddress(Nethereum.RPC.Eth.DTOs.Transaction tx)
        {
            //Using the transanction from RPC to build a txn for signing / signed
            var transaction = Nethereum.Signer.TransactionFactory.CreateTransaction(tx.To, tx.Gas, tx.GasPrice, tx.Value, tx.Input, tx.Nonce,
                                                                                    tx.R, tx.S, tx.V);

            //Get the account sender recovered
            Nethereum.Signer.EthECKey accountSenderRecovered = null;
            if (transaction is Nethereum.Signer.TransactionChainId)
            {
                var txnChainId = transaction as Nethereum.Signer.TransactionChainId;
                accountSenderRecovered = Nethereum.Signer.EthECKey.RecoverFromSignature(transaction.Signature, transaction.RawHash, txnChainId.GetChainIdAsBigInteger());
            }
            else
            {
                accountSenderRecovered = Nethereum.Signer.EthECKey.RecoverFromSignature(transaction.Signature, transaction.RawHash);
            }
            var pubKey = accountSenderRecovered.GetPubKey();

            var point = Cryptography.ECC.ECPoint.DecodePoint(pubKey, Cryptography.ECC.ECCurve.Secp256k1);

            pubKey = point.EncodePoint(true);

            var bytes = new byte[34];

            bytes[0] = (byte)AddressKind.User;
            ByteArrayUtils.CopyBytes(pubKey, 0, bytes, 1, 33);

            return(Address.FromBytes(bytes));
        }
Exemple #3
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();
        }
Exemple #4
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);
        }
Exemple #5
0
            void LoadOrCreateAccount()
            {
                Nethereum.Signer.EthECKey key;
                var password = account_.password_;

                if (string.IsNullOrEmpty(keyStore_))
                {
                    if (encrypted_ && string.IsNullOrEmpty(password))
                    {
                        Thread.MemoryBarrier();
                        result_ = -1;
                        return;
                    }
                    key = CreateAccount(password, encrypted_, out keyStore_);
                }
                else
                {
                    //generate ecKey from encrypted key store
                    if (encrypted_)
                    {
                        var service = new Nethereum.KeyStore.KeyStoreService();
                        key = new Nethereum.Signer.EthECKey(
                            service.DecryptKeyStoreFromJson(password, keyStore_),
                            true);
                    }
                    else
                    {
                        key = new Nethereum.Signer.EthECKey(keyStore_);
                    }
                }
                account_.key_ = key;

                Thread.MemoryBarrier();
                result_ = 1;
            }
        public async void ShouldSignCorrectly()
        {
            await Task.Yield();

            string privateKey = "0xa07cb7889ab3a164dcc72cb6103f2573c7ef2d4a855810594d2bf25df60bc39e";

            PlasmaCore.Transactions.Transaction transaction = new PlasmaCore.Transactions.Transaction();
            transaction.AddInput(2000, 0, 1);
            transaction.AddOutput("0xf86b5b1c2c8de1ea4dc737c849272340fa3561c5", "0x0000000000000000000000000000000000000000", 123);
            transaction.AddOutput("0xf86b5b1c2c8de1ea4dc737c849272340fa3561c5", "0x0000000000000000000000000000000000000000", 5555308);

            TypedDataTransactionEncoder txEncoder = new TypedDataTransactionEncoder(omgDomain);

            byte[] encodedTx      = txEncoder.EncodeRaw(transaction);
            var    rawHash        = new Sha3Keccack().CalculateHash(encodedTx);
            var    ecKey          = new Nethereum.Signer.EthECKey(privateKey);
            var    ecdsaSignature = ecKey.SignAndCalculateV(rawHash);

            string signature = Nethereum.Signer.EthECDSASignature.CreateStringSignature(ecdsaSignature);

            Assert.Equal("0xed0ff5633cb85aa0f64684759185f8a9f94fd1b654be5942d562bf64f504e3a96a83b90a5e50e50b8a75d4f711d1c0e56066519237dbd94e564084a561b8ba2f1b",
                         signature.EnsureHexPrefix());

            transaction.SetSignature(0, signature.HexToByteArray());

            var signedEncodedTx = txEncoder.EncodeSigned(transaction).ToHex(true);

            Assert.Equal("0xf9012ef843b841ed0ff5633cb85aa0f64684759185f8a9f94fd1b654be5942d562bf64f504e3a96a83b90a5e50e50b8a75d4f711d1c0e56066519237dbd94e564084a561b8ba2f1bd2c58207d08001c3808080c3808080c3808080f8b3eb94f86b5b1c2c8de1ea4dc737c849272340fa3561c59400000000000000000000000000000000000000007bee94f86b5b1c2c8de1ea4dc737c849272340fa3561c59400000000000000000000000000000000000000008354c46ceb94000000000000000000000000000000000000000094000000000000000000000000000000000000000080eb94000000000000000000000000000000000000000094000000000000000000000000000000000000000080a00000000000000000000000000000000000000000000000000000000000000000",
                         signedEncodedTx.EnsureHexPrefix());
        }
            /// <summary>
            /// Sign message with the private key
            /// </summary>
            /// <param name="input">input arguments</param>
            /// <returns>signed message string</returns>
            public override Task <string> SignMessage(byte[] input)
            {
                //CPU-bound
                var signer = new Nethereum.Signer.EthereumMessageSigner();
                var ecKey  = new Nethereum.Signer.EthECKey(DecodeLocalKey(), true);

                return(Task.FromResult(signer.Sign(input, ecKey)));
            }
        /// <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);
        }
Exemple #9
0
        public static string GetAddress(string privateKey, Web3 web3 = null)
        {
            string abi             = Resources.DecentraverseABI;
            string contractAddress = Resources.ContractAddress;
            var    privKey         = new Nethereum.Signer.EthECKey(privateKey);
            var    account         = new Nethereum.Web3.Accounts.Account(privKey);

            return(account.Address);
        }
Exemple #10
0
        public static Web3 GetWeb3(string privateKey)
        {
            var privKey = new Nethereum.Signer.EthECKey(privateKey);
            var account = new Nethereum.Web3.Accounts.Account(privKey);

            var web3 = new Web3(account, "https://ropsten.infura.io/v3/2105932667224bc4a18e97688178ad03");

            return(web3);
        }
            /// <summary>
            /// Sign transaction with the private key
            /// </summary>
            /// <param name="input">input arguments</param>
            /// <returns>transaction signature string</returns>
            public override Task <string> SignTransaction(byte[] input)
            {
                //CPU-bound
                var ecKey     = new Nethereum.Signer.EthECKey(DecodeLocalKey(), true);
                var rawHash   = new Sha3Keccack().CalculateHash(input);
                var signature = ecKey.SignAndCalculateV(rawHash);

                return(Task.FromResult(Nethereum.Signer.EthECDSASignature.CreateStringSignature(signature)));
            }
        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));
        }
Exemple #13
0
        public static Contract GetContract(string privateKey, Web3 _web3 = null)
        {
            string abi             = Resources.DecentraverseABI;
            string contractAddress = Resources.ContractAddress;
            var    privKey         = new Nethereum.Signer.EthECKey(privateKey);
            var    account         = new Nethereum.Web3.Accounts.Account(privKey);
            var    web3            = _web3 ?? new Web3(account, "https://ropsten.infura.io/v3/2105932667224bc4a18e97688178ad03");
            var    contract        = web3.Eth.GetContract(abi, contractAddress);

            return(contract);
        }
Exemple #14
0
        public static string Sign(ITransactionEncoder txEncoder, Transaction transaction, string address, string privateKey)
        {
            byte[] encodedTx      = txEncoder.EncodeRaw(transaction);
            var    rawHash        = new Sha3Keccack().CalculateHash(encodedTx);
            var    ecKey          = new Nethereum.Signer.EthECKey(privateKey);
            var    ecdsaSignature = ecKey.SignAndCalculateV(rawHash);
            string signature      = Nethereum.Signer.EthECDSASignature.CreateStringSignature(ecdsaSignature);

            transaction.SetSignature(address, signature.HexToByteArray());
            return(txEncoder.EncodeSigned(transaction).ToHex(true));
        }
Exemple #15
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()));
        }
Exemple #16
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);
        }
Exemple #17
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);
            }
        }
Exemple #18
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()));
        }
Exemple #19
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()));
        }
Exemple #20
0
        public static Address ExtractInteropAddress(Nethereum.RPC.Eth.DTOs.Transaction tx, Logger logger)
        {
            //Using the transanction from RPC to build a txn for signing / signed
            var transaction = Nethereum.Signer.TransactionFactory.CreateTransaction(tx.To, tx.Gas, tx.GasPrice, tx.Value, tx.Input, tx.Nonce,
                                                                                    tx.R, tx.S, tx.V);

            //Get the account sender recovered
            Nethereum.Signer.EthECKey accountSenderRecovered = null;
            // TODO To be used with Nethereum 4:
            // 1) CreateLegacyTransaction()/LegacyTransactionChainId
            // or
            // 2) var signature = new Nethereum.Signer.EthECDSASignature(new Org.BouncyCastle.Math.BigInteger(tx.R.Replace("0x", ""), 16), new Org.BouncyCastle.Math.BigInteger(tx.S.Replace("0x", ""), 16), new Org.BouncyCastle.Math.BigInteger(tx.V.Replace("0x", ""), 16).ToByteArray());
            // accountSenderRecovered = Nethereum.Signer.EthECKey.RecoverFromSignature(signature, System.Text.Encoding.UTF8.GetBytes(tx.TransactionHash.Replace("0x", "")));

            if (transaction is Nethereum.Signer.TransactionChainId)
            {
                var txnChainId = transaction as Nethereum.Signer.TransactionChainId;
                accountSenderRecovered = Nethereum.Signer.EthECKey.RecoverFromSignature(transaction.Signature, transaction.RawHash, txnChainId.GetChainIdAsBigInteger());
            }
            else
            {
                accountSenderRecovered = Nethereum.Signer.EthECKey.RecoverFromSignature(transaction.Signature, transaction.RawHash);
            }
            var pubKey = accountSenderRecovered.GetPubKey();

            var point = Cryptography.ECC.ECPoint.DecodePoint(pubKey, Cryptography.ECC.ECCurve.Secp256k1);

            pubKey = point.EncodePoint(true);

            var bytes = new byte[34];

            bytes[0] = (byte)AddressKind.User;
            ByteArrayUtils.CopyBytes(pubKey, 0, bytes, 1, 33);

            var address = Address.FromBytes(bytes);

            return(address);
        }
Exemple #21
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));
        }