public Web3Interface(string web3ApiPath, string contractAddress, string minerAddress, string privateKey, float gasToMine, string abiFileName, int updateInterval)
        {
            m_updateInterval         = updateInterval;
            m_submittedChallengeList = new List <string>();
            Nethereum.JsonRpc.Client.ClientBase.ConnectionTimeout = MAX_TIMEOUT * 1000;

            if (string.IsNullOrWhiteSpace(contractAddress))
            {
                Program.Print("[INFO] Contract address not specified, default 0xBTC");
                contractAddress = Defaults.Contract0xBTC_mainnet;
            }

            var addressUtil = new AddressUtil();

            if (!addressUtil.IsValidAddressLength(contractAddress))
            {
                throw new Exception("Invalid contract address provided, ensure address is 42 characters long (including '0x').");
            }
            else if (!addressUtil.IsChecksumAddress(contractAddress))
            {
                throw new Exception("Invalid contract address provided, ensure capitalization is correct.");
            }

            if (!string.IsNullOrWhiteSpace(privateKey))
            {
                m_account    = new Account(privateKey);
                minerAddress = m_account.Address;
            }

            if (!addressUtil.IsValidAddressLength(minerAddress))
            {
                throw new Exception("Invalid miner address provided, ensure address is 42 characters long (including '0x').");
            }
            else if (!addressUtil.IsChecksumAddress(minerAddress))
            {
                throw new Exception("Invalid miner address provided, ensure capitalization is correct.");
            }

            Program.Print("[INFO] Miner's address : " + minerAddress);

            m_minerAddress = minerAddress;

            m_web3 = new Web3(string.IsNullOrWhiteSpace(web3ApiPath) ? DEFAULT_WEB3_API : web3ApiPath);

            var abi = File.ReadAllText(Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), abiFileName));

            m_contract = m_web3.Eth.GetContract(abi, contractAddress);

            if (!string.IsNullOrWhiteSpace(privateKey))
            {
                m_mintMethod = m_contract.GetFunction("mint");

                m_transferMethod = m_contract.GetFunction("transfer");

                m_gasToMine = gasToMine;
                Program.Print(string.Format("[INFO] Gas to mine:", m_gasToMine));
            }
        }
示例#2
0
        public static void AddressStringToByte20Array(string addressString, ref byte[] address, string type = null, bool isChecksum = true)
        {
            if (!m_addressUtil.IsValidAddressLength(addressString))
            {
                throw new Exception(string.Format("Invalid {0} provided, ensure address is 42 characters long (including '0x').",
                                                  string.IsNullOrWhiteSpace(type) ? "address" : type));
            }

            else if (isChecksum && !m_addressUtil.IsChecksumAddress(addressString))
            {
                throw new Exception(string.Format("Invalid {0} provided, ensure capitalization is correct.",
                                                  string.IsNullOrWhiteSpace(type) ? "address" : type));
            }

            var bytePosition     = -1;
            var addressLength    = Miner.MinerBase.ADDRESS_LENGTH * 2;
            var addressLowerCase = addressString.Replace("0x", string.Empty).ToLowerInvariant();

            for (var i = 0; i < addressLength; i += 2)
            {
                var valueStr = string.Concat(addressLowerCase.Skip(i).Take(2));
                var value    = (byte)Array.IndexOf(ASCII, valueStr);

                bytePosition++;
                address[bytePosition] = value;
            }
        }
示例#3
0
        /// <summary>
        /// Ensure that input address is a valid Recent address.
        /// </summary>
        /// <param name="address">Requested address</param>
        /// <returns>Formats input address, throw Exception when not a valid address</returns>
        public string ensureValidAddress(string address)
        {
            address = address.Replace("ethereum:", "");
            Nethereum.Util.AddressUtil AddrUtil = new AddressUtil();
            if (!AddrUtil.IsValidAddressLength(address))
            {
                throw new Exception("Invalid address");
            }

            return(address.EnsureHexPrefix());
        }
示例#4
0
        private bool IsValidAddress(string address)
        {
            var addressUtil = new AddressUtil();

            if (addressUtil.IsAnEmptyAddress(address) ||
                !addressUtil.IsValidAddressLength(address) ||
                !addressUtil.IsValidEthereumAddressHexFormat(address))
            {
                return(false);
            }

            return(true);
        }
        private static string ParseAddress(string name, string normalizedValue)
        {
            var addressUtil = new AddressUtil();

            if (!M_HexRegex.IsMatch(normalizedValue) || !addressUtil.IsValidAddressLength(normalizedValue))
            {
                throw new ArgumentParsingException(name, normalizedValue, "not an Ethereum address");
            }
            if (normalizedValue.ToLowerInvariant() != normalizedValue &&
                !addressUtil.IsChecksumAddress(normalizedValue))
            {
                throw new ArgumentParsingException(name, normalizedValue, "invalid address checksum");
            }
            return(normalizedValue);
        }
 public static bool ValidateAddress(string address)
 {
     try
     {
         if (!_addressUtil.IsValidAddressLength(address))
         {
             return(false);
         }
         address = _addressUtil.ConvertToChecksumAddress(address);
         return(_addressUtil.IsChecksumAddress(address));
     }
     catch
     {
         return(false);
     }
 }
示例#7
0
        /// <summary>
        /// Creates an Address instance from a hex string representing an address.
        /// </summary>
        /// <param name="localAddress">Hex encoded string, may start with "0x".</param>
        /// <param name="chainId">Identifier of a DAppChain.</param>
        public Address(string localAddress, string chainId = kDefaultChainId)
        {
            if (String.IsNullOrWhiteSpace(localAddress))
            {
                throw new ArgumentException("Non-empty string expected", nameof(localAddress));
            }

            if (!addressUtil.IsValidAddressLength(localAddress))
            {
                throw new ArgumentException("Address must a be 40-character hex string (not including the 0x prefix)", nameof(localAddress));
            }

            if (String.IsNullOrWhiteSpace(chainId))
            {
                throw new ArgumentException("Non-empty string expected", nameof(chainId));
            }

            LocalAddress = addressUtil.ConvertToChecksumAddress(localAddress);
            ChainId      = chainId;
        }
示例#8
0
 public static bool IsValidAddress(string address)
 {
     return(!string.IsNullOrEmpty(address) && _addressUtil.IsValidAddressLength(address));
 }
示例#9
0
        public Web3Interface(string web3ApiPath, string contractAddress, string minerAddress, string privateKey,
                             float gasToMine, string abiFileName, int updateInterval, int hashratePrintInterval, ulong gasLimit)
        {
            m_updateInterval         = updateInterval;
            m_submittedChallengeList = new List <string>();
            m_submitDateTimeList     = new List <DateTime>(MAX_SUBMIT_DTM_COUNT + 1);
            Nethereum.JsonRpc.Client.ClientBase.ConnectionTimeout = MAX_TIMEOUT * 1000;
            LastSubmitLatency = -1;
            Latency           = -1;

            if (string.IsNullOrWhiteSpace(contractAddress))
            {
                Program.Print("[INFO] Contract address not specified, default 0xBTC");
                contractAddress = Config.Defaults.Contract0xBTC_mainnet;
            }

            var addressUtil = new AddressUtil();

            if (!addressUtil.IsValidAddressLength(contractAddress))
            {
                throw new Exception("Invalid contract address provided, ensure address is 42 characters long (including '0x').");
            }
            else if (!addressUtil.IsChecksumAddress(contractAddress))
            {
                throw new Exception("Invalid contract address provided, ensure capitalization is correct.");
            }

            if (!string.IsNullOrWhiteSpace(privateKey))
            {
                m_account    = new Account(privateKey);
                minerAddress = m_account.Address;
            }

            if (!addressUtil.IsValidAddressLength(minerAddress))
            {
                throw new Exception("Invalid miner address provided, ensure address is 42 characters long (including '0x').");
            }
            else if (!addressUtil.IsChecksumAddress(minerAddress))
            {
                throw new Exception("Invalid miner address provided, ensure capitalization is correct.");
            }

            Program.Print("[INFO] Miner's address : " + minerAddress);

            MinerAddress = minerAddress;
            SubmitURL    = string.IsNullOrWhiteSpace(web3ApiPath) ? DEFAULT_WEB3_API : web3ApiPath;

            m_web3 = new Web3(SubmitURL);

            var erc20AbiPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "ERC-20.abi");
            var tokenAbiPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), abiFileName);

            var erc20Abi = JArray.Parse(File.ReadAllText(erc20AbiPath));
            var tokenAbi = JArray.Parse(File.ReadAllText(tokenAbiPath));

            tokenAbi.Merge(erc20Abi, new JsonMergeSettings {
                MergeArrayHandling = MergeArrayHandling.Union
            });

            m_contract = m_web3.Eth.GetContract(tokenAbi.ToString(), contractAddress);
            var         contractABI = m_contract.ContractBuilder.ContractABI;
            FunctionABI mintABI     = null;

            if (!string.IsNullOrWhiteSpace(privateKey))
            {
                m_gasToMine = gasToMine;
                Program.Print(string.Format("[INFO] Gas to mine: {0}", m_gasToMine));

                m_gasLimit = gasLimit;
                Program.Print(string.Format("[INFO] Gas limit: {0}", m_gasLimit));

                #region ERC20 methods

                m_transferMethod = m_contract.GetFunction("transfer");

                #endregion

                #region ERC918-B methods

                mintABI = contractABI.Functions.FirstOrDefault(f => f.Name == "mint");
                if (mintABI != null)
                {
                    m_mintMethod = m_contract.GetFunction(mintABI.Name);
                }

                if (contractABI.Functions.Any(f => f.Name == "getMiningDifficulty"))
                {
                    m_getMiningDifficulty = m_contract.GetFunction("getMiningDifficulty");
                }

                if (contractABI.Functions.Any(f => f.Name == "getMiningTarget"))
                {
                    m_getMiningTarget = m_contract.GetFunction("getMiningTarget");
                }

                if (contractABI.Functions.Any(f => f.Name == "getChallengeNumber"))
                {
                    m_getChallengeNumber = m_contract.GetFunction("getChallengeNumber");
                }

                if (contractABI.Functions.Any(f => f.Name == "getMiningReward"))
                {
                    m_getMiningReward = m_contract.GetFunction("getMiningReward");
                }

                #endregion

                #region ERC918 methods

                if (contractABI.Functions.Any(f => f.Name == "MAX_TARGET"))
                {
                    m_MAXIMUM_TARGET = m_contract.GetFunction("MAX_TARGET");
                }

                #endregion

                #region ABI methods checking

                if (m_mintMethod == null)
                {
                    mintABI = contractABI.Functions.
                              FirstOrDefault(f => f.Name.IndexOf("mint", StringComparison.OrdinalIgnoreCase) > -1);
                    if (mintABI == null)
                    {
                        throw new InvalidOperationException("'mint' function not found, mining cannot proceed.");
                    }

                    else if (!mintABI.InputParameters.Any())
                    {
                        throw new InvalidOperationException("'mint' function must have input parameter, mining cannot proceed.");
                    }

                    else if (mintABI.InputParameters[0].Type != "uint256")
                    {
                        throw new InvalidOperationException("'mint' function first input parameter type must be uint256, mining cannot proceed.");
                    }

                    m_mintMethod = m_contract.GetFunction(mintABI.Name);
                }

                if (m_getMiningDifficulty == null)
                {
                    var miningDifficultyABI = contractABI.Functions.
                                              FirstOrDefault(f => f.Name.IndexOf("miningDifficulty", StringComparison.OrdinalIgnoreCase) > -1);
                    if (miningDifficultyABI == null)
                    {
                        miningDifficultyABI = contractABI.Functions.
                                              FirstOrDefault(f => f.Name.IndexOf("mining_difficulty", StringComparison.OrdinalIgnoreCase) > -1);
                    }
                    if (miningDifficultyABI == null)
                    {
                        throw new InvalidOperationException("'miningDifficulty' function not found, mining cannot proceed.");
                    }

                    else if (!miningDifficultyABI.OutputParameters.Any())
                    {
                        throw new InvalidOperationException("'miningDifficulty' function must have output parameter, mining cannot proceed.");
                    }

                    else if (miningDifficultyABI.OutputParameters[0].Type != "uint256")
                    {
                        throw new InvalidOperationException("'miningDifficulty' function output parameter type must be uint256, mining cannot proceed.");
                    }

                    m_getMiningDifficulty = m_contract.GetFunction(miningDifficultyABI.Name);
                }

                if (m_getMiningTarget == null)
                {
                    var miningTargetABI = contractABI.Functions.
                                          FirstOrDefault(f => f.Name.IndexOf("miningTarget", StringComparison.OrdinalIgnoreCase) > -1);
                    if (miningTargetABI == null)
                    {
                        miningTargetABI = contractABI.Functions.
                                          FirstOrDefault(f => f.Name.IndexOf("mining_target", StringComparison.OrdinalIgnoreCase) > -1);
                    }
                    if (miningTargetABI == null)
                    {
                        throw new InvalidOperationException("'miningTarget' function not found, mining cannot proceed.");
                    }

                    else if (!miningTargetABI.OutputParameters.Any())
                    {
                        throw new InvalidOperationException("'miningTarget' function must have output parameter, mining cannot proceed.");
                    }

                    else if (miningTargetABI.OutputParameters[0].Type != "uint256")
                    {
                        throw new InvalidOperationException("'miningTarget' function output parameter type must be uint256, mining cannot proceed.");
                    }

                    m_getMiningTarget = m_contract.GetFunction(miningTargetABI.Name);
                }

                if (m_getChallengeNumber == null)
                {
                    var challengeNumberABI = contractABI.Functions.
                                             FirstOrDefault(f => f.Name.IndexOf("challengeNumber", StringComparison.OrdinalIgnoreCase) > -1);
                    if (challengeNumberABI == null)
                    {
                        challengeNumberABI = contractABI.Functions.
                                             FirstOrDefault(f => f.Name.IndexOf("challenge_number", StringComparison.OrdinalIgnoreCase) > -1);
                    }
                    if (challengeNumberABI == null)
                    {
                        throw new InvalidOperationException("'challengeNumber' function not found, mining cannot proceed.");
                    }

                    else if (!challengeNumberABI.OutputParameters.Any())
                    {
                        throw new InvalidOperationException("'challengeNumber' function must have output parameter, mining cannot proceed.");
                    }

                    else if (challengeNumberABI.OutputParameters[0].Type != "bytes32")
                    {
                        throw new InvalidOperationException("'challengeNumber' function output parameter type must be bytes32, mining cannot proceed.");
                    }

                    m_getChallengeNumber = m_contract.GetFunction(challengeNumberABI.Name);
                }

                if (m_getMiningReward == null)
                {
                    var miningRewardABI = contractABI.Functions.
                                          FirstOrDefault(f => f.Name.IndexOf("miningReward", StringComparison.OrdinalIgnoreCase) > -1);
                    if (miningRewardABI == null)
                    {
                        miningRewardABI = contractABI.Functions.
                                          FirstOrDefault(f => f.Name.IndexOf("mining_reward", StringComparison.OrdinalIgnoreCase) > -1);
                    }
                    if (miningRewardABI == null)
                    {
                        throw new InvalidOperationException("'miningReward' function not found, mining cannot proceed.");
                    }

                    else if (!miningRewardABI.OutputParameters.Any())
                    {
                        throw new InvalidOperationException("'miningReward' function must have output parameter, mining cannot proceed.");
                    }

                    else if (miningRewardABI.OutputParameters[0].Type != "uint256")
                    {
                        throw new InvalidOperationException("'miningReward' function output parameter type must be uint256, mining cannot proceed.");
                    }

                    m_getMiningReward = m_contract.GetFunction(miningRewardABI.Name);
                }

                if (m_MAXIMUM_TARGET == null)
                {
                    var maxTargetNames = new string[] { "MAX_TARGET", "MAXIMUM_TARGET", "maxTarget", "maximumTarget" };

                    // ERC541 backwards compatibility
                    if (contractABI.Functions.Any(f => f.Name == "_MAXIMUM_TARGET"))
                    {
                        m_MAXIMUM_TARGET = m_contract.GetFunction("_MAXIMUM_TARGET");
                    }
                    else
                    {
                        var maxTargetABI = contractABI.Functions.
                                           FirstOrDefault(function =>
                        {
                            return(maxTargetNames.Any(targetName =>
                            {
                                return function.Name.IndexOf(targetName, StringComparison.OrdinalIgnoreCase) > -1;
                            }));
                        });
                        if (maxTargetABI == null)
                        {
                            m_MAXIMUM_TARGET = null; // Mining still can proceed without MAX_TARGET
                        }
                        else
                        {
                            if (!maxTargetABI.OutputParameters.Any())
                            {
                                Program.Print(string.Format("[ERROR] '{0}' function must have output parameter.", maxTargetABI.Name));
                            }

                            else if (maxTargetABI.OutputParameters[0].Type != "uint256")
                            {
                                Program.Print(string.Format("[ERROR] '{0}' function output parameter type must be uint256.", maxTargetABI.Name));
                            }

                            else
                            {
                                m_MAXIMUM_TARGET = m_contract.GetFunction(maxTargetABI.Name);
                            }
                        }
                    }
                }

                m_mintMethodInputParamCount = mintABI?.InputParameters.Count() ?? 0;

                #endregion

                m_hashPrintTimer          = new Timer(hashratePrintInterval);
                m_hashPrintTimer.Elapsed += m_hashPrintTimer_Elapsed;
                m_hashPrintTimer.Start();
            }
        }
示例#10
0
        public void Start(string toAddress, bool showCancel = false)
        {
            var addressUtil = new AddressUtil();

            if (!string.IsNullOrWhiteSpace(toAddress))
            {
                if (toAddress.StartsWith("0x") && addressUtil.IsValidAddressLength(toAddress) && addressUtil.IsChecksumAddress(toAddress))
                {
                    _CancellationTokenSource = new CancellationTokenSource();
                    _Task = Task.Run(() => RunMeter(toAddress, _CancellationTokenSource.Token), _CancellationTokenSource.Token);
                    return;
                }
                else
                {
                    toAddress = null;
                    OnMessage?.Invoke(this, new MessageArgs("Invalid user defined address."));
                }
            }

            var query = new StringBuilder();

            query.AppendLine("Select Token Contract:");
            query.AppendLine("1: 0xBitcoin");
            query.AppendLine("2: 0xCatEther");
            query.AppendLine("3: KIWI Token");
            query.AppendLine("4: 0xZibit");
            query.AppendLine("or enter Contract Address (including '0x' prefix)");
            if (showCancel)
            {
                query.AppendLine("Press Ctrl-C again to quit.");
            }

            var request = new RequestUserInputArgs(query.ToString());

            while (string.IsNullOrWhiteSpace(toAddress))
            {
                OnRequestUserInput?.Invoke(this, request);

                switch (request.UserInput)
                {
                case "1":
                case "0xBitcoin":
                    toAddress = Contracts._0xBitcoin;
                    break;

                case "2":
                case "0xCatEther":
                    toAddress = Contracts._0xCatether;
                    break;

                case "3":
                case "KIWI Token":
                    toAddress = Contracts.KIWI_Token;
                    break;

                case "4":
                case "0xZibit":
                    toAddress = Contracts._0xZibit;
                    break;

                default:
                    if (request.UserInput == null)
                    {
                        break;
                    }

                    if (request.UserInput.StartsWith("0x") && addressUtil.IsValidAddressLength(request.UserInput) && addressUtil.IsChecksumAddress(request.UserInput))
                    {
                        toAddress = request.UserInput;
                    }
                    else
                    {
                        OnMessage?.Invoke(this, new MessageArgs("Invalid address."));
                        request.UserInput = null;
                    }
                    break;
                }
            }
            _CancellationTokenSource = new CancellationTokenSource();
            _Task = Task.Run(() => RunMeter(toAddress, _CancellationTokenSource.Token), _CancellationTokenSource.Token);
        }
示例#11
0
        public Web3Interface(string web3ApiPath, string contractAddress, string minerAddress, string privateKey,
                             float gasToMine, string abiFileName, int updateInterval, int hashratePrintInterval, ulong gasLimit)
        {
            m_updateInterval         = updateInterval;
            m_submittedChallengeList = new List <string>();
            m_submitDateTimeList     = new List <DateTime>(MAX_SUBMIT_DTM_COUNT + 1);
            Nethereum.JsonRpc.Client.ClientBase.ConnectionTimeout = MAX_TIMEOUT * 1000;
            LastSubmitLatency = -1;
            Latency           = -1;

            if (string.IsNullOrWhiteSpace(contractAddress))
            {
                Program.Print("[INFO] Contract address not specified, default 0xBTC");
                contractAddress = Config.Defaults.Contract0xBTC_mainnet;
            }

            var addressUtil = new AddressUtil();

            if (!addressUtil.IsValidAddressLength(contractAddress))
            {
                throw new Exception("Invalid contract address provided, ensure address is 42 characters long (including '0x').");
            }
            else if (!addressUtil.IsChecksumAddress(contractAddress))
            {
                throw new Exception("Invalid contract address provided, ensure capitalization is correct.");
            }

            if (!string.IsNullOrWhiteSpace(privateKey))
            {
                m_account    = new Account(privateKey);
                minerAddress = m_account.Address;
            }

            if (!addressUtil.IsValidAddressLength(minerAddress))
            {
                throw new Exception("Invalid miner address provided, ensure address is 42 characters long (including '0x').");
            }
            else if (!addressUtil.IsChecksumAddress(minerAddress))
            {
                throw new Exception("Invalid miner address provided, ensure capitalization is correct.");
            }

            Program.Print("[INFO] Miner's address : " + minerAddress);

            MinerAddress = minerAddress;
            SubmitURL    = string.IsNullOrWhiteSpace(web3ApiPath) ? DEFAULT_WEB3_API : web3ApiPath;

            m_web3 = new Web3(SubmitURL);

            var abi = File.ReadAllText(Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), abiFileName));

            m_contract = m_web3.Eth.GetContract(abi, contractAddress);

            if (!string.IsNullOrWhiteSpace(privateKey))
            {
                m_gasToMine = gasToMine;
                Program.Print(string.Format("[INFO] Gas to mine: {0}", m_gasToMine));

                m_gasLimit = gasLimit;
                Program.Print(string.Format("[INFO] Gas limit: {0}", m_gasLimit));

                m_mintMethod          = m_contract.GetFunction("mint");
                m_transferMethod      = m_contract.GetFunction("transfer");
                m_getMiningDifficulty = m_contract.GetFunction("getMiningDifficulty");
                m_getMiningTarget     = m_contract.GetFunction("getMiningTarget");
                m_getChallengeNumber  = m_contract.GetFunction("getChallengeNumber");
                m_getMiningReward     = m_contract.GetFunction("getMiningReward");

                if (m_contract.ContractBuilder.ContractABI.Functions.Any(f => f.Name == "_MAXIMUM_TARGET"))
                {
                    m_MAXIMUM_TARGET = m_contract.GetFunction("_MAXIMUM_TARGET");
                }

                m_mintMethodInputParamCount = m_contract.ContractBuilder.
                                              ContractABI.Functions.
                                              First(f => f.Name == "mint").
                                              InputParameters.Count();

                m_hashPrintTimer          = new Timer(hashratePrintInterval);
                m_hashPrintTimer.Elapsed += m_hashPrintTimer_Elapsed;
                m_hashPrintTimer.Start();
            }
        }