public async Task <IActionResult> Edit(int id, [Bind("ID,Day,Corp,Pilot,OreType,Amount,Volumen,EstimatedValue,OreID,SystemID")] MiningJob miningJob)
        {
            if (id != miningJob.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(miningJob);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MiningJobExists(miningJob.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(miningJob));
        }
Example #2
0
        public MiningJob GetMiningJob(string minerAddress)
        {
            Block blockCandidate = this.CreateBlockCandidate(minerAddress);

            if (blockCandidate == null)
            {
                throw new Exception("Cannot create block candidate");
            }

            bool additionSuccessful = this.dataService.MiningJobs.TryAdd(blockCandidate.BlockDataHash, blockCandidate);

            if (!additionSuccessful)
            {
                throw new Exception("Adding new mining job to the list was not successful");
            }

            var miningJob = new MiningJob()
            {
                BlockIndex           = blockCandidate.Index,
                TransactionsIncluded = blockCandidate.Transactions.Count,
                Difficulty           = this.dataService.NodeInfo.Difficulty,
                ExpectedReward       = this.dataService.MinerReward + blockCandidate.Transactions.Sum(t => t.Fee),
                RewardAddress        = minerAddress,
                BlockDataHash        = blockCandidate.BlockDataHash
            };

            return(miningJob);
        }
        public async Task <IActionResult> Create([Bind("ID,Day,Corp,Pilot,OreType,Amount,Volumen,EstimatedValue,OreID,SystemID")] MiningJob miningJob)
        {
            if (ModelState.IsValid)
            {
                _context.Add(miningJob);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(miningJob));
        }
Example #4
0
        public IActionResult GetMiningJob(string minerAddress)
        {
            if (string.IsNullOrWhiteSpace(minerAddress))
            {
                return(BadRequest(new Error("Invalid miner address.")));
            }

            Block     candidate = NodeService.CreateCandidateBlock(minerAddress);
            MiningJob job       = candidate.ToMiningJob();

            return(Ok(job));
        }
Example #5
0
        private static bool ProofOfWork(MiningJob miningJob, string blockHash)
        {
            //int sum = 0;
            //for (int i = 0; i < miningJob.Difficulty; i++)
            //{
            //    sum += blockHash[i];
            //}

            //int expectedSum = 48 * miningJob.Difficulty;

            //return sum == expectedSum;

            return(blockHash.StartsWith(new string('0', miningJob.Difficulty)));
        }
Example #6
0
        public static void PostRequestToNode(long nonce, MiningJob miningJob)
        {
            Config.Conf();
            var nodeUrl = Config.Configuration["nodeUrl"];
            var address = Config.Configuration["address"];

            var obj = new MinedHash()
            {
                MiningJobId = miningJob.Id,
                Nonce       = nonce,
            };

            byte[] blockFoundData = Encoding.UTF8.GetBytes(obj.ToString());
            int    retries        = 0;

            HttpStatusCode statusCode = HttpStatusCode.OK;

            try
            {
                statusCode = HttpStatusCode.RequestTimeout;

                string     requestUrl = string.Format("{0}/api/MiningJobs/complete?jobId={1}&nonce={2}", nodeUrl, miningJob.Id.ToString("N"), nonce);
                WebRequest request    = WebRequest.Create(requestUrl);
                request.Method = "POST";
                //request.Timeout = 3000;
                //request.ContentType = "application/json; charset=utf-8";

                //var dataStream = request.GetRequestStream();
                //dataStream.Write(blockFoundData, 0, blockFoundData.Length);
                //dataStream.Close();

                WebResponse response = request.GetResponse();
                statusCode = ((HttpWebResponse)response).StatusCode;

                Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                response.Close();
            }
            catch (WebException e)
            {
                Console.WriteLine("WebException raised!");
                Console.WriteLine("{0}\n", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception raised!");
                Console.WriteLine("Source : {0}", e.Source);
                Console.WriteLine("Message : {0}\n", e.Message);
            }
        }
Example #7
0
        public MiningJob GetMiningJob(string rewardAddress)
        {
            var job = new MiningJob()
            {
                Id         = Guid.NewGuid(),
                Difficulty = Difficulty,
                Index      = this.MinedBlock.Height,
                DataHash   = this.hashLibrary.GetHash(this.MinedBlock),
                NonceFrom  = MiningDivisions * this.miningIteration,
                NonceTo    = MiningDivisions * (this.miningIteration + 1),
            };

            this.miningJobs.Add(job.Id, job);

            // TODO: lock threads
            var transactions = new List <SignedTransaction>();

            foreach (SignedTransaction transaction in this.MinedBlock.Transactions)
            {
                transactions.Add(transaction);
            }

            var block = new Block()
            {
                Difficulty   = this.MinedBlock.Difficulty,
                TimeStamp    = this.MinedBlock.TimeStamp,
                Height       = this.MinedBlock.Height,
                ParentHash   = this.MinedBlock.ParentHash,
                Transactions = transactions,
            };

            block.DataHash = this.hashLibrary.GetHash(block);
            this.blockForMiningJob.Add(job.Id, block);

            this.miningIteration++;
            if (miningIteration > (1 << 60))
            {
                this.miningIteration = 0;
                this.RefreshNextBlock();
            }

            return(job);
        }
Example #8
0
    public override State OnDuring()
    {
        logger.Log("Picking a job");
        IJob job;

        if (MoveItemRequestPool.Instance.HasRequests())
        {
            logger.Log("Got a MoveItemJob!");
            job = new MoveItemJob(actor, MoveItemRequestPool.Instance.GetRequest(actor), logger);
        }
        else if (MiningRequestPool.Instance.HasRequests())
        {
            logger.Log("Got a MiningJob!");
            job = new MiningJob(actor, MiningRequestPool.Instance.GetRequest(actor), logger);
        }
        else
        {
            logger.Log("Found no job, will walk randomly");
            job = new WalkRandomlyJob(actor, logger);
        }
        return(new DoJobState(job, actor, logger));
    }
        public IActionResult GetBlock(string minerAddress)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            // TODO: Generate BlockDataHash from BlockCandidate, add the BlockCandidate to the MiningJobs dictionary
            // minerAddress - To field in the coinbase transaction

            MiningJob miningJob = null;

            try
            {
                miningJob = this.nodeService.GetMiningJob(minerAddress);
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok(miningJob));
        }
Example #10
0
        static void Main(string[] args)
        {
            while (true)
            {
                string responseFromNode = MinerToNode.GetRequestToNode();

                MiningJob miningJob = JsonConvert.DeserializeObject <MiningJob>(responseFromNode);

                Console.WriteLine("\nStart new task:");
                Console.WriteLine($"Index of block to mine: {miningJob.Index}");
                // Console.WriteLine($"Expected Reward: {blockTemplate.ExpectedReward}");
                Console.WriteLine($"TransactionsHash: { miningJob.DataHash}");
                // Console.WriteLine($"PrevBlockHash: {blockTemplate.PrevBlockHash}");
                Console.WriteLine($"Difficulty: {miningJob.Difficulty}\n");


                for (long nonce = miningJob.NonceFrom; nonce <= miningJob.NonceTo; nonce++)
                {
                    string data = miningJob.DataHash + nonce;
                    // string blockHash = BytesArrayToHexString(Sha256(Encoding.UTF8.GetBytes(data)));

                    string blockHash = GetHash(data);

                    bool isPoW = ProofOfWork(miningJob, blockHash);
                    if (isPoW)
                    {
                        Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                        Console.WriteLine("Found Block !!!");
                        Console.WriteLine($"Block Hash: {blockHash}\n");

                        MinerToNode.PostRequestToNode(nonce, miningJob);
                        break;
                    }
                }
            }
        }
        private static async Task MainAsync(string[] args)
        {
            string nodeBaseUrl;
            string minerAddress;

            if (args.Length < 2)
            {
                nodeBaseUrl  = "http://localhost:64149";
                minerAddress = "9a9f082f37270ff54c5ca4204a0e4da6951fe917";
            }
            else
            {
                nodeBaseUrl  = args[0];
                minerAddress = args[1];
            }

            TimeSpan    maxJobDuration = new TimeSpan(0, 0, 5);
            INodeClient nodeClient     = new NodeClient(nodeBaseUrl);
            Stopwatch   stopwatch      = new Stopwatch();

            do
            {
                stopwatch.Start();

                MiningJob job = await GetMiningJob(nodeClient, minerAddress).ConfigureAwait(false);

                string   difficultyCheck = new string('0', job.Difficulty);
                DateTime dateCreated     = DateTime.UtcNow;
                ulong    nonce           = 0;

                while (nonce < ulong.MaxValue)
                {
                    string guess = HashUtils.ComputeBlockSha256Hash(job.BlockDataHash, dateCreated, nonce);
                    if (guess.StartsWith(difficultyCheck))
                    {
                        // block found, send it to the node
                        bool submitted = await SubmitMinedBlock(
                            nodeClient,
                            minerAddress,
                            5,
                            job.BlockDataHash,
                            dateCreated,
                            nonce,
                            guess).ConfigureAwait(false);

                        Console.WriteLine($"Submitting mining result {(submitted ? "successful" : "failed")}.");
                        break;
                    }

                    if (maxJobDuration < stopwatch.Elapsed)
                    {
                        stopwatch.Reset();
                        break;
                    }

                    // get new timestamp on every 100,000 iterations
                    if (nonce % 100000 == 0)
                    {
                        dateCreated = DateTime.UtcNow;
                    }

                    nonce++;
                }
            } while (true);
        }
Example #12
0
        //// GET: /<controller>/
        //public IActionResult Test()
        //{
        //    return RedirectToAction("Index", "MoonMining", new { message = "Dinkleberg!" });
        //}

        public IActionResult Parse(string data)
        {
            //initianlizing counters and error handling
            ViewData["LineCount"]    = 0;
            ViewData["ErrorCount"]   = 0;
            ViewData["ErrorMessage"] = "There were useless data in Lines: ";
            ViewData["ErrorList"]    = new List <int>();

            if (data == null | data == "")
            {
                JobCollection = new List <MiningJob>();
                return(View(JobCollection));
            }

            // We split the whole dump into seperate lines and count them,
            // with each line representing an entry for day, pilot and ore, they are seperated by new lines
            char[]   delimiterChars = { '\n' };
            string[] lines          = data.Split(delimiterChars); // Each Line from the mining ledger dump with the first possibly being useless

            ViewData["LineCount"] = lines.Length;
            ViewData["Message"]   = "Der Dump hatte " + ViewData["LineCount"] + " Zeilen";

            // Split each entry into it's single data points
            // There are supposed to be 9 Data Points per entry, seperated by tabs:
            string[][] entrys = new string[lines.Length][];

            // Strip each line of the HTML and try to convert the entrys into a Mining Job
            JobCollection = new List <MiningJob>();

            for (int i = 0; i < entrys.Length; i++)
            {
                entrys[i] = lines[i].Split('\t');
                string[] entry = entrys[i];
                ViewData["EntryCount" + i] = entry.Length;

                // Strip
                for (int j = 0; j < entry.Length; j++)
                {
                    entry[j] = Regex.Replace(entry[j], "<.*?>", String.Empty);
                    ViewData["Line" + i + ";" + j] = entry[j]; //nur zu testzwecken
                }

                MiningJob job = null;
                // Try to convert
                try
                {
                    job = new MiningJob(entry);
                }
                catch
                {
                    ViewData["ErrorCount"]   = (int)ViewData["ErrorCount"] + 1;
                    ViewData["ErrorMessage"] = (string)ViewData["ErrorMessage"] + i + ", ";
                    List <int> errorlist = (List <int>)ViewData["ErrorList"];
                    errorlist.Add(i);
                    ViewData["ErrorList"] = errorlist;
                }
                if (job != null)
                {
                    JobCollection.Add(job);
                }
            }

            ViewData["ListLenght"] = JobCollection.Count();

            return(View(JobCollection));
        }
Example #13
0
    void CreateMiningJob(object sender, object target)
    {
        MiningJob mj = new MiningJob((Block)target);

        AddJobToQueue(mj);
    }