internal ETHTaskTransferResponse ETH_Sign(int[] SecretSalt, int[] SecretPW, BitfiWallet.NOXWS.NoxTxnProcess tproc)
        {
            ETHTaskTransferResponse taskTransferResponse = new ETHTaskTransferResponse();

            byte[] keybytes = HDDerriveKey(SecretSalt, SecretPW, 0, "eth");

            EthECKey key = new EthECKey(keybytes, true);

            Sclear.EraseBytes(keybytes);

            string ethadr = key.GetPublicAddress();

            if (ethadr != tproc.NoxAddress.BTCAddress)
            {
                taskTransferResponse.Error = "Invalid information.";
                return(taskTransferResponse);
            }


            //TO DO
            if (tproc.ETCToken != null)
            {
                var contractAddress = tproc.ETCToken.EnsureHexPrefix();
                var to       = tproc.ToAddress.EnsureHexPrefix();
                var amount   = NumUtils.Utils.ParseMoney(tproc.Amount, 18);
                var nonce    = System.Numerics.BigInteger.Parse(tproc.ETCNonce);
                var gasPrice = NumUtils.Utils.ParseMoney(tproc.FeeValue, 18);
                var gasLimit = new System.Numerics.BigInteger(Int64.Parse(tproc.ETCGasUsed));
                var tx       = new EthereumLibrary.Signer.Transaction(contractAddress, to, amount, nonce, gasPrice, gasLimit);
                tx.Sign(key);
                var signedHex = tx.ToHex();
                key = null;
                taskTransferResponse.TxnHex = signedHex;
                return(taskTransferResponse);
            }
            else
            {
                var to       = tproc.ToAddress.EnsureHexPrefix();
                var amount   = NumUtils.Utils.ParseMoney(tproc.Amount, 18);
                var nonce    = System.Numerics.BigInteger.Parse(tproc.ETCNonce);
                var gasPrice = NumUtils.Utils.ParseMoney(tproc.FeeValue, 18);
                var gasLimit = new System.Numerics.BigInteger(Int64.Parse(tproc.ETCGasUsed));

                var tx = new EthereumLibrary.Signer.Transaction(to, amount, nonce, gasPrice, gasLimit);
                tx.Sign(key);
                var signedHex = tx.ToHex();
                key = null;
                taskTransferResponse.TxnHex = signedHex;
                return(taskTransferResponse);
            }
        }
    public void InstantiateWalletAndSaveOnDisk(String wordsChain, String password)
    {
        m_wallet = new Wallet(wordsChain, null);

        SetCurrentAddress(EthECKey.GetPublicAddress(ProviderManager.instance.m_wallet.GetWalletPrivateKeyAsString()));

        KeyStoreService m_keystoreService = new KeyStoreService();

        Debug.Log(Application.persistentDataPath);

        string keystoreJSON = m_keystoreService.EncryptAndGenerateDefaultKeyStoreAsJson(password, ProviderManager.instance.m_wallet.GetWalletPrivateKeyAsByte(), accountAddress);

        SaveJSONOnDisk(keystoreJSON, Application.persistentDataPath + "/keystore.ks");
    }
示例#3
0
        /// <summary>
        /// Sends a message to an ethereum smart contract with the intent to change a part of the contract on the blockchain.
        /// </summary>
        /// <typeparam name="TFunc"> The <see cref="FunctionMessage"/> to execute on the blockchain given the contract address. </typeparam>
        /// <param name="function"> The function to execute. </param>
        /// <param name="contractAddress"> The contract address to execute the <see cref="FunctionMessage"/> on. </param>
        /// <param name="privateKey"> The private key of the address sending the transaction. </param>
        /// <param name="gasPrice"> The <see cref="BigInteger"/> gas price to use with the transaction. </param>
        /// <returns> Promise of the transaction result of sending the contract message. </returns>
        public static EthTransactionPromise SendContractMessage <TFunc>(
            TFunc function,
            string contractAddress,
            string privateKey,
            BigInteger gasPrice) where TFunc : FunctionMessage
        {
            EthECKey ethKey  = new EthECKey(privateKey);
            var      promise = new EthTransactionPromise();

            GasUtils.EstimateContractGasLimit(function, contractAddress, ethKey.GetPublicAddress())
            .OnSuccess(gasLimit => _SendContractMessageCoroutine(function, promise, contractAddress, privateKey, gasPrice, gasLimit).StartCoroutine());

            return(promise);
        }
示例#4
0
        /// <summary>
        /// Decrypt and setup wallet from Keystore
        /// </summary>
        /// <param name="PK">Password</param>
        /// <returns>The Wallet</returns>
        public WalletData importFromKeyStore(string keyStore, string password)
        {
            var service = new Nethereum.KeyStore.KeyStoreService();
            var key     = new Nethereum.Signer.EthECKey(
                service.DecryptKeyStoreFromJson(password, keyStore),
                true);

            var address = EthECKey.GetPublicAddress(key.GetPrivateKey());

            _wallet = new WalletData {
                address = address, PK = key.GetPrivateKey()
            };
            _web3 = new Web3(new Nethereum.Web3.Accounts.Account(_wallet.PK), NodeUrl);
            return(_wallet);
        }
        private string GetFirstETH(ExtKey masterKey)
        {
            ExtKey masterKeyA = masterKey.Derive(GetCurrencyIndex("eth"), hardened: true);
            ExtKey key        = masterKeyA.Derive((uint)0);

            byte[]   keybytes = key.PrivateKey.ToBytes();
            EthECKey ETHkey   = new EthECKey(keybytes, true);
            string   ethadr   = ETHkey.GetPublicAddress();

            Sclear.EraseBytes(keybytes);
            masterKeyA = null;
            key        = null;
            ETHkey     = null;
            return(ethadr);
        }
示例#6
0
 public void importAccountFromPrivateKey()
 {
     // Here we try to get the public address from the secretKey we defined
     try
     {
         var address = EthECKey.GetPublicAddress(accountPrivateKey);
         // Then we define the accountAdress private variable with the public key
         accountAddress = address;
     }
     catch (Exception e)
     {
         // If we catch some error when getting the public address, we just display the exception in the console
         Debug.Log("Error importing account from PrivateKey: " + e);
     }
 }
示例#7
0
        public WalletInfo(string keyStoreJson, string password)
        {
            if (keyStoreJson == null)
            {
                throw new ArgumentNullException(nameof(keyStoreJson));
            }
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            PrivateKey = HexHelper.ToHex(new KeyStoreService()
                                         .DecryptKeyStoreFromJson(password, keyStoreJson), true);
            Address = EthECKey.GetPublicAddress(PrivateKey);
        }
示例#8
0
    private void LoadWalletFromKeystore(string keystoreJson, string password)
    {
        if (string.IsNullOrEmpty(keystoreJson) || string.IsNullOrEmpty(password))
        {
            throw new System.InvalidOperationException("keystoreJson or password is null or empty");
        }
        var keystoreservice = new Nethereum.KeyStore.KeyStoreService();
        var privateKey      = keystoreservice.DecryptKeyStoreFromJson(password, keystoreJson);
        var ecKey           = new EthECKey(privateKey, true);
        var address         = ecKey.GetPublicAddress();

        PrivateKeyBytes  = privateKey;
        PrivateKeyString = privateKey.ToHex();
        PublicAddress    = address;
    }
示例#9
0
        public void ShouldSignEncodeTransactionAndRecoverPublicAddress()
        {
            var privateKey     = "b5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7";
            var sendersAddress = "12890d2cce102216644c59daE5baed380d84830c";
            var publicKey      =
                "87977ddf1e8e4c3f0a4619601fc08ac5c1dcf78ee64e826a63818394754cef52457a10a599cb88afb7c5a6473b7534b8b150d38d48a11c9b515dd01434cceb08";

            var key       = new EthECKey(privateKey.HexToByteArray(), true);
            var hash      = "test".ToHexUTF8().HexToByteArray();
            var signature = key.Sign(hash);

            Assert.True(key.Verify(hash, signature));
            Assert.Equal(key.GetPubKeyNoPrefix().ToHex(), publicKey);
            Assert.Equal(sendersAddress.EnsureHexPrefix().ToLower(), key.GetPublicAddress().EnsureHexPrefix().ToLower());
        }
        public static async Task <string> GetEthereumBalance(User user)
        {
            user.PublicKey = EthECKey.GetPublicAddress(user.PrivateKey);
            var    contractFunctions = Globals.GetInstance().ContractFunctions;
            string res;

            try
            {
                res = await contractFunctions.GetUserBalance(user.PublicKey, user.PrivateKey);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
            return(res);
        }
        public static async Task <string> GetTokenBalance(User user)
        {
            user.PublicKey = EthECKey.GetPublicAddress(user.PrivateKey);
            ulong res;
            var   contractFunctions = Globals.GetInstance().ContractFunctions;

            try
            {
                res = await contractFunctions.CallFunctionByName <UInt64>(user.PublicKey, user.PrivateKey, FunctionNames.Balance, user.PublicKey);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
            return(res.ToString());
        }
示例#12
0
        public static string Create(UInt64 id, CreatePaymentPattern req, User user)
        {
            user.PublicKey = EthECKey.GetPublicAddress(user.PrivateKey);
            TransactionReceipt result;

            try
            {
                result = TokenFunctionsResults <int> .InvokeByTransaction(user, FunctionNames.CreatePayment, req.Gas, new object[] { id, req.Value });
            }
            catch (Exception e)
            {
                return(JsonConvert.SerializeObject(e.Message));
            }

            return(JsonConvert.SerializeObject(result));
        }
        public static string DepositToContract(DepositPattern req, User user)
        {
            user.PublicKey = EthECKey.GetPublicAddress(user.PrivateKey);
            TransactionReceipt result;

            try
            {
                result = TokenFunctionsResults <UInt64> .InvokeByTransaction(user, FunctionNames.Deposit, Value : req.Value, Gas : req.Gas);
            }
            catch (Exception e)
            {
                return(JsonConvert.SerializeObject(e.Message));
            }

            return(JsonConvert.SerializeObject(result));
        }
        public static string DisApprove(UInt64 id, DefaultControllerPattern req, User user)
        {
            user.PublicKey = EthECKey.GetPublicAddress(user.PrivateKey);
            TransactionReceipt result;

            try
            {
                result = TokenFunctionsResults <int> .InvokeByTransaction(user, FunctionNames.DisApproveRefund, req.Gas, funcParametrs : id);
            }
            catch (Exception e)
            {
                return(JsonConvert.SerializeObject(e.Message));
            }

            return(JsonConvert.SerializeObject(result));
        }
        public void ShouldCreateASignedTransaction()
        {
            var privateKey     = "b5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7";
            var sendersAddress = "12890d2cce102216644c59daE5baed380d84830c";
            var publicKey      =
                "87977ddf1e8e4c3f0a4619601fc08ac5c1dcf78ee64e826a63818394754cef52457a10a599cb88afb7c5a6473b7534b8b150d38d48a11c9b515dd01434cceb08";

            //data use for other tools for comparison
            Debug.WriteLine(new HexBigInteger(10000).HexValue);
            Debug.WriteLine(new HexBigInteger(324).HexValue);
            Debug.WriteLine(new HexBigInteger(10000000000000).HexValue);
            Debug.WriteLine(new HexBigInteger(21000).HexValue);

            //Create a transaction from scratch
            var tx = new Transaction("0x13f022d72158410433cbd66f5dd8bf6d2d129924", 10000, 324, 10000000000000, 21000);

            tx.Sign(new ECKey(privateKey.HexToByteArray(), true));

            var encoded = tx.GetRLPEncoded();
            var rlp     =
                "f8698201448609184e72a0008252089413f022d72158410433cbd66f5dd8bf6d2d129924822710801ca0b1874eb8dab80e9072e57b746f8f0f281890568fd655488b0a1f5556a117775ea06ea87e03a9131cae14b5420cbfeb984bb2641d76fb32327d87cf0c9c0ee8f234";

            Assert.Equal(rlp, encoded.ToHex());
            //data used for other tools for comparison
            Debug.WriteLine(encoded.ToHex());

            Assert.Equal(EthECKey.GetPublicAddress(privateKey), tx.Key.GetPublicAddress());

            var tx3 = new Transaction(rlp.HexToByteArray());

            Assert.Equal(tx.Data, tx3.Data);

            Debug.WriteLine(tx.ToJsonHex());

            var tx2 = new Transaction(tx.GetRLPEncoded());

            Assert.Equal(EthECKey.GetPublicAddress(privateKey), tx2.Key.GetPublicAddress());

            Assert.Equal(tx.GasLimit.ToHex(), tx3.GasLimit.ToHex());
            Assert.Equal(tx.Nonce.ToHex(), tx3.Nonce.ToHex());
            Assert.Equal(tx.GasPrice.ToHex(), tx3.GasPrice.ToHex());
            Assert.Equal(tx.Value.ToHex(), tx3.Value.ToHex());
            Assert.Equal(tx.RawHash.ToHex(), tx3.RawHash.ToHex());
            Assert.Equal(tx3.Key.GetPublicAddress(), tx.Key.GetPublicAddress());
            Assert.Equal(tx2.RawHash.ToHex(), tx3.RawHash.ToHex());
            Assert.Equal(tx2.Key.GetPublicAddress(), tx.Key.GetPublicAddress());
        }
示例#16
0
    public void LoadAccount()
    {
        var encryptedJson = PlayerPrefs.GetString("encryptedJson");

        Debug.Log("encryptedJson " + encryptedJson);
        var password        = "******";
        var keystoreservice = new Nethereum.KeyStore.KeyStoreService();
        var privateKey      = keystoreservice.DecryptKeyStoreFromJson(password, encryptedJson);
        var ecKey           = new EthECKey(privateKey, true);
        var address         = ecKey.GetPublicAddress();

        Debug.Log("address: " + address + "\n privateKey: " + privateKey.ToString());

        accountAddress    = address;
        accountPrivateKey = privateKey.ToHex();
        Debug.Log("accountAddress: " + accountAddress + "\n accountPrivateKey: " + accountPrivateKey);
    }
示例#17
0
        /// <summary>
        /// Decrypt and setup wallet from Keystore
        /// </summary>
        /// <param name="keyStore">Encrypted Keystore</param>
        /// <param name="password">Password used on encryption</param>
        /// <returns>The Wallet</returns>
        public WalletData importFromKeyStore(string keyStore, string password)
        {
            var service = new Nethereum.KeyStore.KeyStoreService();
            var key     = new Nethereum.Signer.EthECKey(
                service.DecryptKeyStoreFromJson(password, keyStore),
                true);

            var address = EthECKey.GetPublicAddress(key.GetPrivateKey());

            _wallet = new WalletData {
                address = address, PK = key.GetPrivateKey()
            };
            _web3 = new Web3(new Nethereum.Web3.Accounts.Account(_wallet.PK, _chainId), _nodeUrl);
            _paymentChannelsContract = _web3.Eth.GetContract(PaymentChannelsABI, _paymentChannelsContractAddress);
            _validatorsContract      = _web3.Eth.GetContract(ValidatorsABI, _validatorsContractAddress);
            return(_wallet);
        }
示例#18
0
        public void TestTransactionFromUnSignedRLP()
        {
            var tx = new Transaction(RLP_ENCODED_UNSIGNED_TX.HexToByteArray());

            Assert.Equal(RLP_ENCODED_UNSIGNED_TX, tx.GetRLPEncoded().ToHex());
            Assert.Equal(BigInteger.Zero, tx.Nonce.ToBigIntegerFromRLPDecoded());
            Assert.Equal(testGasPrice.ToBigIntegerFromRLPDecoded(), tx.GasPrice.ToBigIntegerFromRLPDecoded());
            Assert.Equal(testGasLimit.ToBigIntegerFromRLPDecoded(), tx.GasLimit.ToBigIntegerFromRLPDecoded());
            Assert.Equal(testReceiveAddress.ToHex(), tx.ReceiveAddress.ToHex());
            Assert.Equal(testValue.ToBigIntegerFromRLPDecoded(), tx.Value.ToBigIntegerFromRLPDecoded());

            Assert.Equal(HASH_TX, tx.RawHash.ToHex());

            tx.Sign(new EthECKey(KEY.HexToByteArray(), true));
            tx.Key.Verify(tx.RawHash, tx.Signature);
            Assert.Equal(EthECKey.GetPublicAddress(KEY), tx.Key.GetPublicAddress());
        }
        public static async Task <string> GetCommision(ComissionControllerPattern req, User user)
        {
            user.PublicKey = EthECKey.GetPublicAddress(user.PrivateKey);
            ContractFunctions  contractFunctions = Globals.GetInstance().ContractFunctions;
            TransactionReceipt res;

            try
            {
                res = await contractFunctions.CallFunctionByNameSendTransaction(user.PublicKey, user.PrivateKey, FunctionNames.SetComission, req.Gas, parametrsOfFunction : req.Comission);
            }
            catch (Exception e)
            {
                return(JsonConvert.SerializeObject(e.Message));
            }

            return(JsonConvert.SerializeObject(res));
        }
示例#20
0
    private string GetPrivateKeyFromKeystore(string pass)
    {
        if (keystoreJSON == null || keystoreJSON == "" || pass == null || pass == "")
        {
            return("");
        }

        byte[]   b     = m_keystoreService.DecryptKeyStoreFromJson(pass, keystoreJSON);
        EthECKey myKey = new EthECKey(b, true);

        if (myKey.GetPublicAddress() != accountAddress)
        {
            return("");
        }

        return(myKey.GetPrivateKey());
    }
        private static void Main(string[] args)
        {
            string            input          = File.ReadAllText("../../../Input.json");
            EthereumSignature inputSignature = JsonConvert.DeserializeObject <EthereumSignature>(input);

            byte[] messageBytes = Utils.GetBytes(inputSignature.Message);
            byte[] messageHash  = new Sha3Keccack().CalculateHash(messageBytes);
            int    recId        = inputSignature.V.HexToByteArray()[0];

            EthECDSASignature signature = EthECDSASignatureFactory.FromComponents(
                inputSignature.R.HexToByteArray(),
                inputSignature.S.HexToByteArray());

            EthECKey publicKey = EthECKey.RecoverFromSignature(signature, recId, messageHash);

            Console.WriteLine("Public address: {0}", publicKey.GetPublicAddress());
        }
 public TransactionSignedUnityRequest(string url, string privateKey, BigInteger?chainId = null, Dictionary <string, string> requestHeaders = null)
 {
     _chainId                   = chainId;
     _url                       = url;
     _account                   = EthECKey.GetPublicAddress(privateKey);
     _privateKey                = privateKey;
     _transactionSigner         = new LegacyTransactionSigner();
     _ethSendTransactionRequest = new EthSendRawTransactionUnityRequest(_url);
     _ethSendTransactionRequest.RequestHeaders = requestHeaders;
     _transactionCountRequest = new EthGetTransactionCountUnityRequest(_url);
     _transactionCountRequest.RequestHeaders    = requestHeaders;
     _ethEstimateGasUnityRequest                = new EthEstimateGasUnityRequest(_url);
     _ethEstimateGasUnityRequest.RequestHeaders = requestHeaders;
     _ethGasPriceUnityRequest = new EthGasPriceUnityRequest(_url);
     _ethGasPriceUnityRequest.RequestHeaders = requestHeaders;
     Fee1559SuggestionStrategy = new SimpleFeeSuggestionUnityRequestStrategy(url, requestHeaders);
 }
示例#23
0
        public static async Task <string> GetById(UInt64 id, User user)
        {
            user.PublicKey = EthECKey.GetPublicAddress(user.PrivateKey);
            ContractFunctions contractFunctions = Globals.GetInstance().ContractFunctions;

            TokenAPI.Payment res;
            try
            {
                res = await contractFunctions.DeserializePaymentById(user.PublicKey, user.PrivateKey, id);
            }
            catch (Exception e)
            {
                return(JsonConvert.SerializeObject(e.Message));
            }

            return(JsonConvert.SerializeObject(res));
        }
示例#24
0
        public static async Task <string> DeployContract(DefaultControllerPattern req, User user)
        {
            user.PublicKey = EthECKey.GetPublicAddress(user.PrivateKey);
            TransactionReceipt contractReceipt;
            ContractFunctions  contractFunctions;

            try
            {
                contractFunctions = Globals.GetInstance().ContractFunctions;
                contractReceipt   = await contractFunctions.DeployContract(user.PublicKey, user.PrivateKey, req.Gas);
            }
            catch (Exception e)
            {
                return(JsonConvert.SerializeObject(e.Message));
            }

            return(JsonConvert.SerializeObject(contractReceipt));
        }
示例#25
0
    public void RetrieveWallet()
    {
        //Loader.instance.StartLoad();

        string wordsChain = Words[0].text + " " + Words[1].text + " " + Words[2].text + " " + Words[3].text + " " + Words[4].text + " " + Words[5].text + " " + Words[6].text + " " + Words[7].text + " " + Words[8].text + " " + Words[9].text + " " + Words[10].text + " " + Words[11].text;

        m_wallet = new Wallet(wordsChain, null);

        accountAddress = EthECKey.GetPublicAddress(m_wallet.GetWalletPrivateKeyAsString());

        keystoreJSON = m_keystoreService.EncryptAndGenerateDefaultKeyStoreAsJson(Password.text, m_wallet.GetWalletPrivateKeyAsByte(), accountAddress);
        SaveJSONOnDisk();

        Canvas.SetActive(false);
        //LobbyManager.instance.Activate("Account", CreateBlocky());

        //Loader.instance.StopLoad();
    }
示例#26
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IMaintenanceService>(sp =>
            {
                var key        = Configuration["PrivateKey"];
                var privateKey = new EthECKey(key);
                var address    = privateKey.GetPublicAddress();
                var account    = new Account(privateKey);
                var web3       = new Web3(account, Configuration["GatewayUrl"]);

                return(new EthereumMaintenanceService(web3,
                                                      privateKey,
                                                      Configuration["SmartContractAddress"],
                                                      Configuration["Abi"]));
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
示例#27
0
        public void ShouldCreateASignedTransaction()
        {
            var privateKey = "b5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7";

            //data use for other tools for comparison
            Debug.WriteLine(new HexBigInteger(10000).HexValue);
            Debug.WriteLine(new HexBigInteger(324).HexValue);
            Debug.WriteLine(new HexBigInteger(10000000000000).HexValue);
            Debug.WriteLine(new HexBigInteger(21000).HexValue);

            //Create a transaction from scratch
            var tx = new Transaction("0x13f022d72158410433cbd66f5dd8bf6d2d129924", 10000, 324, 10000000000000, 21000);

            tx.Sign(new EthECKey(privateKey.HexToByteArray(), true));

            var encoded = tx.GetRLPEncoded();
            var rlp     =
                "f8698201448609184e72a0008252089413f022d72158410433cbd66f5dd8bf6d2d129924822710801ca0b1874eb8dab80e9072e57b746f8f0f281890568fd655488b0a1f5556a117775ea06ea87e03a9131cae14b5420cbfeb984bb2641d76fb32327d87cf0c9c0ee8f234";

            Assert.Equal(rlp, encoded.ToHex());
            //data used for other tools for comparison
            Debug.WriteLine(encoded.ToHex());

            Assert.Equal(EthECKey.GetPublicAddress(privateKey), tx.Key.GetPublicAddress());

            var tx3 = new Transaction(rlp.HexToByteArray());

            Assert.Equal(tx.Data, tx3.Data ?? new byte[] { });

            Debug.WriteLine(tx.ToJsonHex());

            var tx2 = new Transaction(tx.GetRLPEncoded());

            Assert.Equal(EthECKey.GetPublicAddress(privateKey), tx2.Key.GetPublicAddress());

            Assert.Equal(tx.GasLimit.ToHex(), tx3.GasLimit.ToHex());
            Assert.Equal(tx.Nonce.ToHex(), tx3.Nonce.ToHex());
            Assert.Equal(tx.GasPrice.ToHex(), tx3.GasPrice.ToHex());
            Assert.Equal(tx.Value.ToHex(), tx3.Value.ToHex());
            Assert.Equal(tx.RawHash.ToHex(), tx3.RawHash.ToHex());
            Assert.Equal(tx3.Key.GetPublicAddress(), tx.Key.GetPublicAddress());
            Assert.Equal(tx2.RawHash.ToHex(), tx3.RawHash.ToHex());
            Assert.Equal(tx2.Key.GetPublicAddress(), tx.Key.GetPublicAddress());
        }
示例#28
0
        public ExecTransactionFunction BuildTransaction(
            EncodeTransactionDataFunction transactionData,
            BigInteger chainId,
            params string[] privateKeySigners)
        {
            var signer        = new Eip712TypedDataSigner();
            var messageSigner = new MessageSigner();

            var domain = new Domain
            {
                VerifyingContract = this.ContractHandler.ContractAddress,
                ChainId           = chainId
            };

            var encodedMessage = signer.EncodeTypedData(transactionData, domain, "SafeTx");
            var hashEncoded    = Util.Sha3Keccack.Current.CalculateHash(encodedMessage);
            var signatures     = new List <SafeSignature>();

            foreach (var privateKey in privateKeySigners)
            {
                var publicAddress = EthECKey.GetPublicAddress(privateKey);
                var signature     = messageSigner.Sign(hashEncoded, privateKey);
                signatures.Add(new SafeSignature()
                {
                    Address = publicAddress, Signature = signature
                });
            }

            var fullSignature = GetCombinedSignaturesInOrder(signatures);

            return(new ExecTransactionFunction()
            {
                To = transactionData.To,
                Value = transactionData.Value,
                Data = transactionData.Data,
                Operation = transactionData.Operation,
                SafeTxGas = transactionData.SafeTxGas,
                BaseGas = transactionData.BaseGas,
                SafeGasPrice = transactionData.SafeGasPrice,
                GasToken = transactionData.GasToken,
                RefundReceiver = transactionData.RefundReceiver,
                Signatures = fullSignature
            });
        }
        ///////////////////////////////////////////////////////////////////////////////////////


        public static async Task <string> SendToken(string PrivateKeyFrom, string PublicKeyTo, float value)
        {
            //get the function
            var function = meaToken.Contract.GetFunction("transfer");
            //get the data
            var data = function.GetData(new object[] { PublicKeyTo, new BigInteger(value) });
            // var estimatedGaz = await function.EstimateGasAsync(new object[] { PublicKeyTo, new BigInteger(value) });

            //Console.WriteLine("Estimated Gaz : " + estimatedGaz);

            //nonce
            var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(EthECKey.GetPublicAddress(PrivateKeyFrom), BlockParameter.CreatePending());

            //signing the transaction
            var encoded = transactionSigner.SignTransaction(PrivateKeyFrom, meaToken.Contract.Address, 1, txCount.Value, 1000000000000L, 900000, data);

            //estimate gaz
            var GasEstimated = await web3.Eth.TransactionManager.EstimateGasAsync(new CallInput("0x" + encoded, PublicKeyTo));

            Console.WriteLine("Estimated Gas is : " + GasEstimated.Value.ToString());

            Console.WriteLine("My balance : " + web3.Eth.GetBalance.SendRequestAsync(EthECKey.GetPublicAddress(PrivateKeyFrom)).Result.Value.ToString());


            //transaction hash

            var bal = await  get_MeaToken_Account_Balance(EthECKey.GetPublicAddress(PrivateKeyFrom));

            Console.WriteLine("bal : " + bal);


            var txId = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encoded);

            //verify transaction
            var status = transactionSigner.VerifyTransaction(encoded);

            Console.WriteLine("Status : " + status);
            //returning transaction hash

            isMined(txId);
            return(txId);
        }
示例#30
0
        /// <summary>
        /// Coroutine which sends a message to an ethereum smart contract.
        /// </summary>
        /// <typeparam name="TFunc"> The <see cref="FunctionMessage"/> to execute on the blockchain given the contract address. </typeparam>
        /// <param name="function"> The function to execute. </param>
        /// <param name="promise"> Promise of the transaction result of sending the contract message. </param>
        /// <param name="contractAddress"> The contract address to execute the <see cref="FunctionMessage"/> on. </param>
        /// <param name="privateKey"> The private key of the address sending the transaction. </param>
        /// <param name="gasPrice"> The <see cref="BigInteger"/> gas price to use with the transaction. </param>
        /// <param name="gasLimit"> The <see cref="BigInteger"/> gas limit to use with the transaction. </param>
        private static IEnumerator _SendContractMessageCoroutine <TFunc>(
            TFunc function,
            EthTransactionPromise promise,
            string contractAddress,
            string privateKey,
            BigInteger gasPrice,
            BigInteger gasLimit) where TFunc : FunctionMessage
        {
            EthECKey ethKey = new EthECKey(privateKey);

            function.SetDefaultFromAddressIfNotSet(ethKey.GetPublicAddress());
            function.Gas      = gasLimit;
            function.GasPrice = gasPrice;

            TransactionSignedUnityRequest unityRequest = new TransactionSignedUnityRequest(NetworkProvider.GetNetworkChainUrl(), privateKey, ethKey.GetPublicAddress());

            yield return(unityRequest.SignAndSendTransaction(function.CreateTransactionInput(contractAddress)));

            promise.Build(unityRequest, () => unityRequest.Result, NetworkProvider.GetNetworkChainUrl);
        }