Example #1
0
 public virtual void UpdateClient(string objectId, string propertyName, object value)
 {
     if (!IsReadied)
     {
         return;
     }
     if (objectId == null)
     {
         return;
     }
     if (_dicByObjectId.TryGetValue(objectId, out ClientData clientData))
     {
         PropertyInfo propertyInfo = typeof(ClientData).GetProperty(propertyName);
         if (propertyInfo != null)
         {
             value = VirtualRoot.ConvertValue(propertyInfo.PropertyType, value);
             var oldValue = propertyInfo.GetValue(clientData, null);
             if (oldValue != value)
             {
                 propertyInfo.SetValue(clientData, value, null);
                 DoUpdateSave(MinerData.Create(clientData));
             }
         }
     }
 }
Example #2
0
        public void ReportSpeed(SpeedDto speedDto, string minerIp, bool isFromWsServerNode)
        {
            if (!IsReadied)
            {
                return;
            }
            if (speedDto == null || speedDto.ClientId == Guid.Empty)
            {
                return;
            }
            if (string.IsNullOrEmpty(minerIp))
            {
                return;
            }
            if (!isFromWsServerNode)
            {
                _speedDataRedis.SetAsync(new SpeedData(speedDto, DateTime.Now));
            }
            ClientData clientData = GetByClientId(speedDto.ClientId);

            if (clientData == null)
            {
                clientData = ClientData.Create(speedDto, minerIp);
                Add(clientData);
            }
            else
            {
                clientData.Update(speedDto, minerIp, out bool isMinerDataChanged);
                if (isMinerDataChanged)
                {
                    DoUpdateSave(MinerData.Create(clientData));
                }
            }
        }
Example #3
0
 protected override void DoRemoveSave(MinerData minerData)
 {
     using (LiteDatabase db = CreateLocalDb()) {
         var col = db.GetCollection <MinerData>();
         col.Delete(minerData.Id);
     }
 }
Example #4
0
        public void ReportState(ReportState state, string minerIp, bool isFromWsServerNode)
        {
            if (!IsReadied)
            {
                return;
            }
            if (state == null || state.ClientId == Guid.Empty)
            {
                return;
            }
            if (string.IsNullOrEmpty(minerIp))
            {
                return;
            }
            ClientData clientData = GetByClientId(state.ClientId);

            if (clientData == null)
            {
                clientData = ClientData.Create(state, minerIp);
                Add(clientData);
            }
            else
            {
                clientData.Update(state, minerIp, out bool isMinerDataChanged);
                if (isMinerDataChanged)
                {
                    DoUpdateSave(MinerData.Create(clientData));
                }
            }
            if (!isFromWsServerNode)
            {
                var speedData = clientData.ToSpeedData();
                _speedDataRedis.SetAsync(speedData);
            }
        }
    void Start () {
        Data = MinerSaveGame.Instance.Current;

        healthBarInner = GameObject.Find("HealthBarInner");
        healthBarText = GameObject.Find("HealthBarText");
        foodBarInner = GameObject.Find("FoodBarInner");
        foodBarText = GameObject.Find("FoodBarText");
        moralBarInner = GameObject.Find("MoralBarInner");
        moralBarText = GameObject.Find("MoralBarText");
        moral = GameObject.Find("Moral");
        gameOver = GameObject.Find("GameOver");
        timeBarInner = GameObject.Find("TimeBarInner");
        experienceBarInner = GameObject.Find("ExperienceBarInner");
        experienceBarText = GameObject.Find("ExperienceBarText");
        moneyBarText = GameObject.Find("MoneyBarText");
        sun = GameObject.Find("Sun");
        inventory = GameObject.Find("Inventory");
        inventoryBackground = GameObject.Find("InventoryBackground");
        inGameMenu = GameObject.Find("InGameMenu");
        elevatorLabel = GameObject.Find("ElevatorLabel");
        level = GameObject.Find("Level");
        dayCount = GameObject.Find("DayCount");
        cuCount = GameObject.Find("CuCount");
        agCount = GameObject.Find("AgCount");
        auCount = GameObject.Find("AuCount");
        ptCount = GameObject.Find("PtCount");
        gemCount = GameObject.Find("GemCount");
        inventoryText = GameObject.Find("InventoryText");

        arrSky = new GameObject[4];
        for (int ii = 0; ii < 4; ii++)
        {
            arrSky[ii] = GameObject.Find("world sky" + ii);
        }

        gameOver.SetActive(false);
        inventory.SetActive(false);
        inGameMenu.SetActive(false);

        UpdateBars();
        UpdateSun(true);
        HandleInventorySelection();
        UpdateExperienceBar();
        UpdateMoneyBar();
        UpdateInventoryText();

        transform.position = new Vector3(Data.X, Data.Y, transform.position.z);
        target = transform.position;
        elevator.transform.position = new Vector3(Data.ElevatorX, Data.ElevatorY, elevator.transform.position.z);

        InvokeRepeating("reduceFood", 12, 12);
        InvokeRepeating("UpdateHealth", 1, 1);
        InvokeRepeating("UpdateMoral", 1, 1);
        InvokeRepeating("save", 60, 60);

        LanguageManager languageManager = LanguageManager.Instance;
        SmartCultureInfo deviceCulture = languageManager.GetDeviceCultureIfSupported();
        languageManager.OnChangeLanguage += OnChangeLanguage;
        languageManager.ChangeLanguage(deviceCulture);
    }
Example #6
0
 protected override void DoUpdateSave(MinerData minerData)
 {
     using (LiteDatabase db = CreateLocalDb()) {
         var col = db.GetCollection <MinerData>();
         col.Upsert(minerData);
     }
 }
Example #7
0
        public Task <List <MinerData> > GetAllAsync()
        {
            var       db        = _redis.RedisConn.GetDatabase();
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            return(db.HashGetAllAsync(_redisKeyMinerById).ContinueWith(t => {
                stopwatch.Stop();
                string text = $"{nameof(ReadOnlyMinerDataRedis)}的redis方法HashGetAllAsync耗时 {stopwatch.GetElapsedSeconds().ToString("f2")} 秒";
                NTMinerConsole.UserInfo(text);
                stopwatch.Restart();
                List <MinerData> list = new List <MinerData>();
                foreach (var item in t.Result)
                {
                    if (item.Value.HasValue)
                    {
                        MinerData data = VirtualRoot.JsonSerializer.Deserialize <MinerData>(item.Value);
                        if (data != null)
                        {
                            list.Add(data);
                        }
                    }
                }
                stopwatch.Stop();
                NTMinerConsole.UserInfo($"反序列化和装配MinerData列表耗时 {stopwatch.GetElapsedSeconds().ToString("f2")} 秒");
                return list;
            }));
        }
Example #8
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="propertyName">propertyName是客户端传入的白名单属性</param>
 /// <param name="values"></param>
 public override void UpdateClients(string propertyName, Dictionary <string, object> values)
 {
     if (!IsReadied)
     {
         return;
     }
     if (values.Count == 0)
     {
         return;
     }
     if (ClientData.TryGetReflectionUpdateProperty(propertyName, out PropertyInfo propertyInfo))
     {
         values.ChangeValueType(propertyInfo.PropertyType);
         List <MinerData> minerDatas = new List <MinerData>();
         foreach (var kv in values)
         {
             string objectId = kv.Key;
             object value    = kv.Value;
             if (_dicByObjectId.TryGetValue(objectId, out ClientData clientData))
             {
                 var oldValue = propertyInfo.GetValue(clientData, null);
                 if (oldValue != value)
                 {
                     propertyInfo.SetValue(clientData, value, null);
                     minerDatas.Add(MinerData.Create(clientData));
                 }
             }
         }
         DoUpdateSave(minerDatas);
     }
 }
 public async Task PostMinerData(MinerData newMinerData)
 {
     using (var db = new BEMainDBContext()) {
         db.MinerData.Add(newMinerData);
         await db.SaveChangesAsync();
     }
 }
 public async Task UpdateMinerData(MinerData updatedMinerData)
 {
     using (var db = new BEMainDBContext()) {
         db.MinerData.AddOrUpdate(updatedMinerData);
         await db.SaveChangesAsync();
     }
 }
        protected override List<uint> ScanHash_CryptoPP(MinerData md, UInt256 target)
        {
            uint nonce = (uint)md.nHashesDone;
            List<uint> results = new List<uint>(1);

            UInt256 hashResult = new UInt256();

            byte[] tmp = new byte[16 * 4];

            DateTime endLhutc = DateTime.UtcNow + new TimeSpan(0, 0, 1);
            long count = 0;
            while (true)
            {
                count++;
                Single(md, hashResult, nonce, tmp);

                var lastInt = BitConverter.ToInt32(hashResult.bytes, 7*4);
                if (lastInt == 0 && hashResult.CompareTo(target) < 0)
                    results.Add(nonce);

                nonce++;

                if (DateTime.UtcNow >= endLhutc || nonce == 0)
                    break;
            }

            md.nHashesDone += count;
            HashedSome(count);

            return results;
        }
Example #12
0
        public Task UpdateAsync(MinerSign minerSign)
        {
            if (minerSign == null)
            {
                return(TaskEx.CompletedTask);
            }
            var db = _redis.GetDatabase();

            return(db.HashGetAsync(_redisKeyMinerById, minerSign.Id).ContinueWith(t => {
                MinerData minerData = null;
                if (t.Result.HasValue)
                {
                    minerData = VirtualRoot.JsonSerializer.Deserialize <MinerData>(t.Result);
                    minerData?.Update(minerSign);
                }
                else
                {
                    minerData = MinerData.Create(minerSign);
                }
                if (minerData != null)
                {
                    db.HashSetAsync(_redisKeyMinerById, minerSign.Id, VirtualRoot.JsonSerializer.Serialize(minerSign));
                }
            }));
        }
Example #13
0
 void InitializeMinerData()
 {
     minerData               = new MinerData();
     minerData.fatigue       = 0;
     minerData.goldInPockets = 0;
     minerData.thirst        = 0;
 }
Example #14
0
 protected override void DoUpdateSave(MinerData minerData)
 {
     if (!IsReadied)
     {
         return;
     }
     _minerRedis.SetAsync(minerData);
 }
        // Called before the Miner starts its job (mainMineAsync)
        protected virtual async Task onMineBeginAsync()
        {
            // Initialize the MinerData for this Execution
            BESearchRequest theSearchRequest = await GetTheSearchRequest();

            MinerData theMinerData = new MinerData(theSearchRequest.ActiveExecutionID, TheSourceID);

            await SaveTheMinerData(theMinerData);
        }
Example #16
0
        public void ReportSpeed(SpeedDto speedDto, string minerIp, bool isFromWsServerNode)
        {
            if (!IsReadied)
            {
                return;
            }
            if (speedDto == null || speedDto.ClientId == Guid.Empty)
            {
                return;
            }
            if (string.IsNullOrEmpty(minerIp))
            {
                return;
            }
            if (!isFromWsServerNode)
            {
                _speedDataRedis.SetAsync(new SpeedData(speedDto, DateTime.Now));
            }
            ClientData clientData = GetByClientId(speedDto.ClientId);

            if (clientData == null)
            {
                clientData = ClientData.Create(speedDto, minerIp);
                if (speedDto.IsOuterUserEnabled && !string.IsNullOrEmpty(speedDto.ReportOuterUserId))
                {
                    UserData userData = AppRoot.UserSet.GetUser(UserId.Create(speedDto.ReportOuterUserId));
                    if (userData != null)
                    {
                        clientData.LoginName = userData.LoginName;
                    }
                }
                Add(clientData);
            }
            else
            {
                bool   isLoginNameChanged = false;
                string oldLoginName       = clientData.LoginName;
                if (speedDto.IsOuterUserEnabled &&
                    !string.IsNullOrEmpty(speedDto.ReportOuterUserId) &&
                    (string.IsNullOrEmpty(clientData.LoginName) || clientData.OuterUserId != speedDto.ReportOuterUserId))
                {
                    UserData userData = AppRoot.UserSet.GetUser(UserId.Create(speedDto.ReportOuterUserId));
                    if (userData != null)
                    {
                        isLoginNameChanged   = true;
                        clientData.LoginName = userData.LoginName;
                        UpdateClientDatasCache(oldLoginName, userData.LoginName, clientData);
                    }
                }
                clientData.Update(speedDto, minerIp, out bool isMinerDataChanged);
                if (isMinerDataChanged || isLoginNameChanged)
                {
                    DoUpdateSave(MinerData.Create(clientData));
                }
            }
        }
Example #17
0
        public Task SetAsync(MinerData data)
        {
            if (data == null || string.IsNullOrEmpty(data.Id))
            {
                return(TaskEx.CompletedTask);
            }
            var db = _redis.GetDatabase();

            return(db.HashSetAsync(_redisKeyMinerById, data.Id, VirtualRoot.JsonSerializer.Serialize(data)));
        }
Example #18
0
        public Task DeleteAsync(MinerData data)
        {
            if (data == null || string.IsNullOrEmpty(data.Id))
            {
                return(TaskEx.CompletedTask);
            }
            var db = _redis.GetDatabase();

            return(db.HashDeleteAsync(_redisKeyMinerById, data.Id));
        }
Example #19
0
 protected override void DoRemoveSave(MinerData minerData)
 {
     if (!IsReadied)
     {
         return;
     }
     _minerRedis.DeleteAsync(minerData).ContinueWith(t => {
         _mqSender.SendMinerDataRemoved(minerData.Id);
     });
 }
Example #20
0
        // Called after the Analyser sucesfully finished its job
        protected virtual async Task onAnalyseCompleteAsync()
        {
            MinerData minerData = await GetTheMinerData();

            minerData.ThePositivesNum = await GetTheTextsNum(NewStateNames.ThePositivesNum);

            minerData.TheNegativesNum = await GetTheTextsNum(NewStateNames.TheNegativesNum);

            // Store the updated MinerData in the DB
            await dbHandlerService.UpdateMinerData(minerData);
        }
Example #21
0
 protected override void DoRemoveSave(MinerData minerData)
 {
     if (!IsReadied)
     {
         return;
     }
     _minerRedis.DeleteAsync(minerData).ContinueWith(t => {
         _mqSender.SendMinerDataRemoved(minerData.Id, minerData.ClientId);
     });
     _clientActiveOnRedis.DeleteAsync(minerData.Id);
     _speedDataRedis.DeleteByClientIdAsync(minerData.ClientId);
 }
        public async Task <MinerData> GetMinerData(int executionID, SourceOption source)
        {
            MinerData minerData = null;

            using (var db = new BEMainDBContext()) {
                minerData = db.MinerData
                            .Where(md => (md.TheExecutionID == executionID) && (md.TheSource == source))
                            .ToList()
                            .FirstOrDefault();
            }
            return(minerData);
        }
Example #23
0
        private void PullSpeedInit()
        {
            if (_isPullSpeedInited)
            {
                return;
            }
            _isPullSpeedInited = true;
            Task.Factory.StartNew(() => {
                while (true)
                {
                    DateTime now = DateTime.Now;
                    if (_getSpeedOn.AddSeconds(10) <= now)
                    {
                        NTMinerConsole.DevDebug("周期拉取数据更新拍照源数据");
                        ClientData[] clientDatas = _dicByObjectId.Values.ToArray();
                        Task[] tasks             = clientDatas.Select(CreatePullTask).ToArray();
                        Task.WaitAll(tasks, 5 * 1000);
                        _getSpeedOn = now;

                        #region 将NoSpeedSeconds秒内更新过的记录持久化到磁盘
                        List <MinerData> minerDatas = new List <MinerData>();
                        DateTime time = now.AddSeconds(-20);
                        foreach (var clientData in _dicByObjectId.Values)
                        {
                            if (clientData.MinerActiveOn > time)
                            {
                                minerDatas.Add(MinerData.Create(clientData));
                            }
                            else
                            {
                                clientData.IsMining      = false;
                                clientData.MainCoinSpeed = 0;
                                clientData.DualCoinSpeed = 0;
                                foreach (var item in clientData.GpuTable)
                                {
                                    item.MainCoinSpeed = 0;
                                    item.DualCoinSpeed = 0;
                                }
                            }
                        }
                        if (minerDatas.Count > 0)
                        {
                            DoUpdateSave(minerDatas);
                        }
                        #endregion
                    }
                    else
                    {
                        System.Threading.Thread.Sleep((int)(_getSpeedOn.AddSeconds(10) - now).TotalMilliseconds);
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }
Example #24
0
        private void PullSpeedInit()
        {
            if (_isPullSpeedInited)
            {
                return;
            }
            _isPullSpeedInited = true;
            VirtualRoot.BuildEventPath <Per10SecondEvent>("周期拉取矿机状态", LogEnum.DevConsole, this.GetType(), PathPriority.Normal, message => {
                if (RpcRoot.IsOuterNet)
                {
                    return;
                }
                Task.Factory.StartNew(() => {
                    NTMinerConsole.DevDebug("周期拉取数据更新拍照源数据");
                    ClientData[] clientDatas = _dicByObjectId.Values.ToArray();
                    Task[] tasks             = clientDatas.Select(CreatePullTask).ToArray();
                    Task.WaitAll(tasks, 5 * 1000);

                    if (RpcRoot.IsOuterNet)
                    {
                        return;
                    }

                    #region 将NoSpeedSeconds秒内更新过的记录持久化到磁盘
                    List <MinerData> minerDatas = new List <MinerData>();
                    DateTime time = message.BornOn.AddSeconds(-20);
                    foreach (var clientData in _dicByObjectId.Values)
                    {
                        if (clientData.MinerActiveOn > time)
                        {
                            minerDatas.Add(MinerData.Create(clientData));
                        }
                        else
                        {
                            clientData.IsMining      = false;
                            clientData.MainCoinSpeed = 0;
                            clientData.DualCoinSpeed = 0;
                            foreach (var item in clientData.GpuTable)
                            {
                                item.MainCoinSpeed = 0;
                                item.DualCoinSpeed = 0;
                            }
                        }
                    }
                    if (minerDatas.Count > 0)
                    {
                        DoUpdateSave(minerDatas);
                    }
                    #endregion
                });
            });
        }
Example #25
0
 public void RemoveByObjectId(string objectId)
 {
     if (!IsReadied)
     {
         return;
     }
     if (objectId == null)
     {
         return;
     }
     if (_dicByObjectId.TryGetValue(objectId, out ClientData clientData))
     {
         _dicByObjectId.Remove(objectId);
         _dicByClientId.Remove(clientData.ClientId);
         DoRemoveSave(MinerData.Create(clientData));
     }
 }
Example #26
0
 public void SetMinerSign(MinerSign minerSign)
 {
     _dicByClientId[minerSign.ClientId] = minerSign;
     _redis.GetByIdAsync(minerSign.Id).ContinueWith(t => {
         MinerData minerData = t.Result;
         if (minerData != null)
         {
             minerData.Update(minerSign);
         }
         else
         {
             minerData = MinerData.Create(minerSign);
         }
         _redis.SetAsync(minerData).ContinueWith(_ => {
             AppRoot.MinerClientMqSender.SendMinerSignSeted(minerSign);
         });
     });
 }
Example #27
0
        public void AddClient(string minerIp)
        {
            if (!IsReadied)
            {
                return;
            }
            MinerData minerData  = MinerData.Create(minerIp);
            var       clientData = ClientData.Create(minerData);

            if (!_dicByObjectId.ContainsKey(clientData.Id))
            {
                _dicByObjectId.Add(clientData.Id, clientData);
            }
            if (!_dicByClientId.ContainsKey(clientData.ClientId))
            {
                _dicByClientId.Add(clientData.ClientId, clientData);
            }
            DoUpdateSave(minerData);
        }
        public void TestMineBlockDataBlockchain()
        {
            MinerData mb2 = new MinerData();

            mb2.SetDifficulty(1);

            for (var i = 1; i <= 3; i++)
            {
                BlockData b = new BlockData(i);
                b.SetData("Hello World " + i + "!");

                mb2.Mine(b);
            }

            Assert.IsInstanceOfType(mb2.GetBlockchain(), typeof(BlockData));

            Assert.AreEqual(
                "{id:3,nonce:22,data:\"Hello World 3!\",previous:{id:2,nonce:20,data:\"Hello World 2!\",previous:{id:1,nonce:17,data:\"Hello World 1!\",previous:{id:0,nonce:0,data:\"Hello Genesis Block!\",previous:null}}}}",
                mb2.GetBlockchain().ToString());
        }
Example #29
0
        public Task <List <MinerData> > GetAllAsync()
        {
            var db = _redis.RedisConn.GetDatabase();

            return(db.HashGetAllAsync(_redisKeyMinerById).ContinueWith(t => {
                List <MinerData> list = new List <MinerData>();
                foreach (var item in t.Result)
                {
                    if (item.Value.HasValue)
                    {
                        MinerData data = VirtualRoot.JsonSerializer.Deserialize <MinerData>(item.Value);
                        if (data != null)
                        {
                            list.Add(data);
                        }
                    }
                }
                return list;
            }));
        }
Example #30
0
        public void AddMiner(string minerIp)
        {
            MinerData minerData = new MinerData {
                Id               = ObjectId.NewObjectId().ToString(),
                ClientId         = Guid.NewGuid(),
                CreatedOn        = DateTime.Now,
                GroupId          = Guid.Empty,
                MinerIp          = minerIp,
                WindowsLoginName = string.Empty,
                WindowsPassword  = String.Empty,
                WorkId           = Guid.Empty
            };
            var clientData = MinerData.CreateClientData(minerData);

            Add(clientData);
            using (LiteDatabase db = HostRoot.CreateLocalDb()) {
                var col = db.GetCollection <MinerData>();
                col.Insert(minerData);
            }
        }
Example #31
0
 private void Init()
 {
     lock (_locker) {
         if (!_isInited)
         {
             using (LiteDatabase db = HostRoot.CreateLocalDb()) {
                 var col = db.GetCollection <MinerData>();
                 foreach (var item in col.FindAll())
                 {
                     var data = MinerData.CreateClientData(item);
                     _dicByObjectId.Add(item.Id, data);
                     if (!_dicByClientId.ContainsKey(item.ClientId))
                     {
                         _dicByClientId.Add(item.ClientId, data);
                     }
                 }
             }
             _isInited = true;
         }
     }
 }
Example #32
0
        public void RemoveByObjectIds(List <string> objectIds)
        {
            if (!IsReadied)
            {
                return;
            }
            if (objectIds == null || objectIds.Count == 0)
            {
                return;
            }
            List <MinerData> minerDatas = new List <MinerData>();

            foreach (var objectId in objectIds)
            {
                if (_dicByObjectId.TryRemove(objectId, out ClientData clientData))
                {
                    minerDatas.Add(MinerData.Create(clientData));
                    _dicByClientId.TryRemove(clientData.ClientId, out _);
                }
            }
            DoRemoveSave(minerDatas.ToArray());
        }
Example #33
0
        private void Mine()
        {
            MinerData md = new MinerData();

            StratumHeaderBuilder latestWork = null;

            while (!IsStopRequested)
            {
                if ((!IsUserIdle && UserDataManager.UserData.Settings.BitcoinMinerOnlyWheUserIdle) || IsPaused)
                {
                    Thread.Sleep(1000);
                    continue;
                }

                if (md.nHashesDone > uint.MaxValue)
                {
                    latestWork.IncrementNonce2();
                    md.nHashesDone = 0;
                }

                latestWork = _stratumSession.GetLatestBuilder(latestWork);
                if (latestWork == null)
                {
                    Thread.Sleep(100);
                    continue;
                }

                md.PreCalc(latestWork.BlockHeader);

                List<uint> results = ScanHash_CryptoPP(md, latestWork.Job.Target);

                foreach (var nonce in results)
                {
                    var nonceBytes = nonce.ToBytes();
                    Buffer.BlockCopy(nonceBytes, 0, md.blockbuffer, 76, 4);

                    var hash = ComputeSha256Hash(md.blockbuffer, 0, 80);

                    if (hash.CompareTo(latestWork.Job.Target) <= 0)
                    {
                        Array.Reverse(nonceBytes);
                        var nonceHex2 = nonceBytes.ToHexString().ToLower();
                        _stratumSession.SubmitShare(latestWork, nonceHex2);
                    }
                }
            }
        }
Example #34
0
 protected abstract List<uint> ScanHash_CryptoPP(MinerData md, UInt256 target);
Example #35
0
        protected static void Single(MinerData md, UInt256 hashResult, uint nonce, byte[] tmp)
        {
            Buffer.BlockCopy(md.blockbuffer, 16 * 4, tmp, 0, 16 * 4);

            var nonceBytes = BitConverter.GetBytes(nonce);
            tmp[12] = nonceBytes[0];
            tmp[13] = nonceBytes[1];
            tmp[14] = nonceBytes[2];
            tmp[15] = nonceBytes[3];

            SHA256Transform(md.hash1buffer, tmp, md.midstatebuffer);
            md.hash1buffer.ByteReverse();
            FormatHashBlocks(md.hash1buffer, UInt256.ByteCount);// 32

            SHA256Transform(hashResult.bytes, md.hash1buffer, SHA256InitStateBytes);
            hashResult.bytes.ByteReverse();
        }
    void HandleWorkDone(MinerData.Rock rock)
    {
        //Debug.Log("Begin HandleWorkDone");
        if (rock.Type == "light")
        {
            Data.Experience += 1;
        }
        else if (rock.Type == "hard")
        {
            Data.Experience += 2;
        }
        else if (rock.Type == "granite")
        {
            Data.Experience += 10;
        }

        rock.Type = rock.AfterType;
        if (rock.Type.Contains("cave"))
        {
            rock.CounterStart = Time.time;
            rock.EnemyState = EnemyState.None;
            rock.EnemyHealth = 100;
            rock.EnemyType = EnemyType.MudGolem;
            rockGroup.GetComponent<RockGroupBehaviour>().CastEnemy(rock);
        }
        
        var rockObject = GameObject.Find("Rock_" + rock.X + "_" + rock.Y);
        string spriteName = "rock " + rock.Type;
        if (rock.Type.Contains("cave"))
        {
            int rnd = UnityEngine.Random.Range(1, 4);
            spriteName += " " + rnd.ToString().PadLeft(2, '0');
        }
        //Debug.Log(spriteName);
        var spriteAtlasIndex = rockGroup.GetComponent<RockGroupBehaviour>().SpriteAtlas[spriteName];
        rockObject.GetComponent<SpriteRenderer>().sprite = rockGroup.GetComponent<RockGroupBehaviour>().spriteCollection[spriteAtlasIndex];//Resources.Load<Sprite>(spriteName);
        UpdateExperienceBar();

        TryCastMinerals(rock);
        //Debug.Log("End HandleWorkDone");
    }
 private void TryCastMinerals(MinerData.Rock rock)
 {
     // check if there is anything at all
     float x = rock.Y;
     float y = (8.0f / 10.0f) * x + 10.0f;
     int random = UnityEngine.Random.Range(0, 100);
     if (random < y)
     {
         int countMinerals = UnityEngine.Random.Range(0, 7);
         for (int ii = 0; ii < countMinerals; ii++)
         {
             CastMineral(rock);
         }
     }
 }
 void CastMineral(MinerData.Rock rock)
 {
     var xPos = UnityEngine.Random.Range(1, 15);
     var yPos = UnityEngine.Random.Range(1, 6);
     var what = UnityEngine.Random.Range(0, 101);
     var type = "gold";
     if (rock.Y < 11)
     {
         if (what < 75)
         {
             type = "copper";
         }
         else
         {
             type = "silver";
         }
     } 
     else if (rock.Y < 29)
     {
         if (what < 50)
         {
             type = "copper";
         }
         else if (what < 80)
         {
             type = "silver";
         }
         else
         {
             type = "gold";
         }
     }
     else if (rock.Y < 44)
     {
         if (what < 40)
         {
             type = "copper";
         }
         else if (what < 70)
         {
             type = "silver";
         }
         else if (what < 90)
         {
             type = "gold";
         }
         else
         {
             type = "platinum";
         }
     }
     else
     {
         if (what < 35)
         {
             type = "copper";
         }
         else if (what < 65)
         {
             type = "gold";
         }
         else if (what < 80)
         {
             type = "silver";
         }
         else if (what < 90)
         {
             type = "platinum";
         }
         else
         {
             type = "gem";
         }
     }
     var variant = UnityEngine.Random.Range(1, type == "gem" ? 8 : 5);
     var targetPos = new Vector3(rock.X * 15 + xPos, rock.Y * -20 + yPos - 20);
     //Debug.Log(String.Format("targetPos = {0}", targetPos));
     var newResource = Instantiate(resourceTemplate, targetPos, Quaternion.identity) as Transform;
     newResource.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("resources/resources " + type + " " + variant.ToString().PadLeft(2, '0'));
     newResource.GetComponent<ResourceBehaviour>().type = type;
     RockGroupBehaviour.GetGridPosition(targetPos, false, out newResource.GetComponent<ResourceBehaviour>().gridX, out newResource.GetComponent<ResourceBehaviour>().gridY);
     //Debug.Log("Resource " + type + " added with gridX = " + newResource.GetComponent<ResourceBehaviour>().gridX + " and gridY = " + newResource.GetComponent<ResourceBehaviour>().gridY);
     AddResourceToCollect(newResource);
 }
        protected override List<uint> ScanHash_CryptoPP(MinerData md, UInt256 target)
        {
            List<uint> results = new List<uint>();
            if (!Initialized) return results;

            var localhostUtc = DateTime.UtcNow;
            DateTime endLhutc = localhostUtc + new TimeSpan(0, 0, 1);
            long count = 0;
            long countEnd = ((long)uint.MaxValue) - md.nHashesDone + 1L;

            DateTime startSearchLoop = localhostUtc;
            DateTime ticksEnd = startSearchLoop + new TimeSpan(0, 0, 10);
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

            IntPtr[] CrossFadeGlobalWorkSize = new IntPtr[1];
            IntPtr[] CrossFadeLocalWorkSize = new IntPtr[1];

            uint[] output = new uint[257];
            unsafe
            {
                fixed (uint* outputp = &output[0])
                {
                    Mem outputBuffer = OCLMan.Context.CreateBuffer(MemFlags.USE_HOST_PTR | MemFlags.WRITE_ONLY, sizeof(uint) * output.Length, outputp);
                    searchKernel.SetArg(20, outputBuffer);

                    SetupWork(md);

                    while (true)
                    {
                        watch.Start();
                        if (globalThreads > 0)
                        {
                            CrossFadeGlobalWorkSize[0] = (IntPtr)globalThreads;
                            CrossFadeLocalWorkSize[0] = (IntPtr)workGroupSize;

                            long hashCount = globalThreads;
                            uint startNumber = (uint)md.nHashesDone;
                            if (_shouldUseVectors)
                            {
                                startNumber = startNumber >> 1;
                                hashCount *= 2;
                            }
                            searchKernel.SetArg(14, startNumber);
                            md.nHashesDone += hashCount;
                            count += hashCount;

                            CommandQueue CQ = OCLMan.CQ[deviceIndex];
                            CQ.EnqueueNDRangeKernel(searchKernel, 1, null, CrossFadeGlobalWorkSize, CrossFadeLocalWorkSize);
                            CQ.EnqueueBarrier();
                            CQ.Finish();
                            CQ.EnqueueReadBuffer(outputBuffer, true, 0, (long)(sizeof(uint) * output.Length), (IntPtr)outputp);
                            CQ.Finish();

                            if (output[256] != 0)
                            {
                                for (int i = 0; i < 256; i++)
                                {
                                    if (output[i] != 0)
                                    {
                                        results.Add(output[i].ByteReverse());
                                        output[i] = 0;
                                    }
                                }
                                output[256] = 0;

                                CQ.EnqueueWriteBuffer(outputBuffer, true, 0, (long)(sizeof(uint) * output.Length), (IntPtr)outputp);
                            }
                        }

                        watch.Stop();
                        TimeSpan kt = watch.Elapsed;
                        watch.Reset();
                        float kernelTime = (float)kt.TotalSeconds;
                        FPS = 1.0f / kernelTime;

                        if (FPSLimit != 0)
                        {
                            float lower = FPSLimit * 0.95f;
                            float upper = FPSLimit * 1.05f;
                            if (FPS > lower)
                                UM++;
                            else if (FPS < upper)
                                UM--;
                            if (UM < 1) UM = 1;
                            if (UM > UMLimit) UM = UMLimit;
                        }
                        else
                        {
                            UM = UMLimit;
                        }

                        if (UsageLimitLast != UsageLimit)
                        {
                            UsageLimitLast = UsageLimit;
                            restTime = TimeSpan.Zero;
                            workTime = TimeSpan.Zero;
                        }
                        else if (UsageLimit < 100)
                        {
                            workTime += kt;
                            float fUsage = UsageLimit / 100.0f;
                            if (fUsage <= 0) fUsage = 0.001f;
                            double sleepTime = ((1 - fUsage) * workTime.TotalMilliseconds) / fUsage - restTime.TotalMilliseconds;
                            watch.Start();
                            if (sleepTime >= 10.0) System.Threading.Thread.Sleep((int)sleepTime);
                            watch.Stop();
                            restTime += watch.Elapsed;
                            watch.Reset();
                        }

                        globalThreads = (uint)(unit * UM);

                        if (count > countEnd || DateTime.UtcNow > endLhutc) break;
                    }

                    outputBuffer.Dispose();
                }
            }

            HashedSome(count);

            return results;
        }
        private void SetupWork(MinerData md)
        {
            var f = new uint[8];
            var secondHalf = new uint[3];
            Buffer.BlockCopy(md.blockbuffer, 64, secondHalf, 0, 12);
            secondHalf[0] = secondHalf[0].ByteReverse();
            secondHalf[1] = secondHalf[1].ByteReverse();
            secondHalf[2] = secondHalf[2].ByteReverse();

            var state = new uint[8];
            Buffer.BlockCopy(md.midstatebuffer, 0, state, 0, 32);
            var state2 = Sha256Computer.Partial(state, secondHalf, f);
            Sha256Computer.CalculateF(state, secondHalf, f, state2);

            searchKernel.SetArg(0, state[0]);
            searchKernel.SetArg(1, state[1]);
            searchKernel.SetArg(2, state[2]);
            searchKernel.SetArg(3, state[3]);
            searchKernel.SetArg(4, state[4]);
            searchKernel.SetArg(5, state[5]);
            searchKernel.SetArg(6, state[6]);
            searchKernel.SetArg(7, state[7]);

            searchKernel.SetArg(8, state2[1]);
            searchKernel.SetArg(9, state2[2]);
            searchKernel.SetArg(10, state2[3]);
            searchKernel.SetArg(11, state2[5]);
            searchKernel.SetArg(12, state2[6]);
            searchKernel.SetArg(13, state2[7]);

            // 14 is for the nonce

            searchKernel.SetArg(15, f[0]);
            searchKernel.SetArg(16, f[1]);
            searchKernel.SetArg(17, f[2]);
            searchKernel.SetArg(18, f[3]);
            searchKernel.SetArg(19, f[4]);

            // 20 is the output
        }
 public Transform CastEnemy(MinerData.Rock rock, bool fromSaveGame = false)
 {
     var enemy = Instantiate<Transform>(enemyTemplate);
     enemy.SetParent(this.transform.parent, false);
     enemy.GetComponent<SpriteRenderer>().sortingOrder = 10;
     enemy.GetComponent<EnemyBehaviour>().rock = rock;
     if (fromSaveGame)
     {
         //Debug.Log("Enemy Cast from SaveGame into State " + rock.EnemyState);
         enemy.transform.position = new Vector3(rock.EnemyX, rock.EnemyY);
         enemy.GetComponent<EnemyBehaviour>().target = new Vector3(rock.EnemyTargetX, rock.EnemyTargetY);
         enemy.GetComponent<EnemyBehaviour>().SetState(rock.EnemyState);
     }
     else
     {
         //Debug.Log("Enemy Cast New");
         enemy.transform.position = GetPosition(rock.X, rock.Y, true);
         enemy.GetComponent<EnemyBehaviour>().SetState(EnemyState.None);
     }
     return enemy;
 }