コード例 #1
0
 public override void Mutate(State.State state)
 {
     if (state.Cargo.Ingredients.ContainsKey(Name))
     {
         state.Cargo.IncrementCargo(Name, Count);
     }
 }
コード例 #2
0
ファイル: SaveLoadScreen.cs プロジェクト: husathap/Charlotte
        /// <summary>
        /// Create a new Load/Save Screen.
        /// </summary>
        /// <param name="NextState">Depending whether the game is loading or saving.
        /// If the game is loading, then the it is the state the game will go to if the operation is cancelled.
        /// If the game is saving, this state will be reached regardless.</param>
        /// <param name="SaveMode">True for saving, false for loading.</param>
        public SaveLoadScreen(State.State NextState, bool SaveMode)
        {
            this.NextState = NextState;
            this.SaveMode  = SaveMode;

            if (SaveMode)
            {
                LogsSelection = new Selection(50, 130, new string[] {
                    "1: ", "2: ", "3: ", "4: ", "5: ", "6: ", "7: ", "8: ", "Cancel"
                });
            }
            else
            {
                LogsSelection = new Selection(50, 130, new string[] {
                    "1: ", "2: ", "3: ", "4: ", "5: ", "6: ", "7: ", "8: ", "Autosave", "Cancel"
                });
            }

            for (int i = 0; i < 8; i++)
            {
                if (Properties.Settings.Default.Logs[i] == "0")
                {
                    LogsSelection.Choices[i] += "-";
                }
                else
                {
                    LogsSelection.Choices[i] += Properties.Settings.Default.Logs[i];
                }
            }
        }
コード例 #3
0
 public override void Mutate(State.State state)
 {
     foreach (var ingredient in _changes)
     {
         state.IncrementCargo(ingredient.Key, ingredient.Value);
     }
 }
コード例 #4
0
ファイル: DumpOperation.cs プロジェクト: willyb321/EDEngineer
        public override void Mutate(State.State state)
        {
            var dump = DumpOperations
                       .GroupBy(m => m.MaterialName)
                       .ToDictionary(m => m.Key, m => m.First().Size);

            foreach (var item in state.Cargo.Ingredients.Where(item => ResetFilter.Contains(item.Value.Data.Kind)).ToList())
            {
                var currentValue = item.Value.Count;

                if (dump.TryGetValue(item.Key, out var toSetValue))
                {
                    if (currentValue != toSetValue)
                    {
                        state.Cargo.IncrementCargo(item.Key, toSetValue - currentValue);
                    }
                }
                else if (currentValue != 0)
                {
                    state.Cargo.IncrementCargo(item.Key, -1 * currentValue);
                }
            }

            var names = state.Cargo.Ingredients.Keys.ToHashSet();

            foreach (var item in DumpOperations.Where(op => !names.Contains(op.MaterialName)))
            {
                state.Cargo.IncrementCargo(item.MaterialName, item.Size);
            }
        }
コード例 #5
0
        public string Ejecutar(DateTime _dtFechaEntrega, DateTime _dtHoy, State.State _entPedido)
        {
            TimeSpan dtDiferencia      = _dtFechaEntrega.Subtract(_dtHoy);
            int      iTotalHoras       = Math.Abs(Convert.ToInt32(dtDiferencia.TotalHours));
            int      iCantidad         = 0;
            string   cDiferenciaTiempo = "";

            if (iTotalHoras < 1)
            {
                iCantidad         = (iTotalHoras / 60);
                cDiferenciaTiempo = $"{iCantidad} Minutos";
            }
            if (iTotalHoras >= 1 && iTotalHoras <= 23)
            {
                iCantidad         = iTotalHoras;
                cDiferenciaTiempo = $"{iCantidad} Horas";
            }
            if (iTotalHoras > 23)
            {
                iCantidad         = (iTotalHoras / 23);
                cDiferenciaTiempo = $"{iCantidad} Días";
            }
            if (iTotalHoras >= 690)
            {
                iCantidad         = (iCantidad / 30);
                cDiferenciaTiempo = $"{iCantidad} Meses";
            }

            return(cDiferenciaTiempo);
        }
コード例 #6
0
ファイル: SaveLoadScreen.cs プロジェクト: husathap/Charlotte
        /// <summary>
        /// Create a new Load/Save Screen.
        /// </summary>
        /// <param name="NextState">Depending whether the game is loading or saving.
        /// If the game is loading, then the it is the state the game will go to if the operation is cancelled.
        /// If the game is saving, this state will be reached regardless.</param>
        /// <param name="SaveMode">True for saving, false for loading.</param>
        public SaveLoadScreen(State.State NextState, bool SaveMode)
        {
            this.NextState = NextState;
            this.SaveMode = SaveMode;

            if (SaveMode)
            {
                LogsSelection = new Selection(50, 130, new string[] {
                    "1: ", "2: ", "3: ", "4: ", "5: ", "6: ", "7: ", "8: ", "Cancel"});
            }
            else
            {
                LogsSelection = new Selection(50, 130, new string[] {
                    "1: ", "2: ", "3: ", "4: ", "5: ", "6: ", "7: ", "8: ", "Autosave", "Cancel"});
            }

            for (int i = 0; i < 8; i++)
            {
                if (Properties.Settings.Default.Logs[i] == "0")
                {
                    LogsSelection.Choices[i] += "-";
                }
                else
                {
                    LogsSelection.Choices[i] += Properties.Settings.Default.Logs[i];
                }
            }
        }
コード例 #7
0
 public override void Mutate(State.State state)
 {
     foreach (var reward in CommodityRewards)
     {
         reward.Mutate(state);
     }
 }
コード例 #8
0
 public Computer(int id, int price, string brand)
 {
     this.Id       = id;
     this.Price    = price;
     this.Brand    = brand;
     computerState = new FreeState(this);
     this.Name     = null;
     Hours         = 0;
 }
コード例 #9
0
        public override void Mutate(State.State state)
        {
            foreach (var ingredient in IngredientsConsumed)
            {
                state.IncrementCargo(ingredient.Entry.Data.Name, -1 * ingredient.Size);
            }

            state.OnBlueprintCrafted(this);
        }
コード例 #10
0
        /// <summary>
        /// Given a block, enters the initialization state for handling a block.
        /// </summary>
        /// <param name="state">The state to set.</param>
        /// <param name="block">The block which will be processed.</param>
        public override void Initialize(State.State state, Block.Block block)
        {
            // We enter our initialization state
            state.BlockGasUsed = 0;
            state.Bloom        = 0;
            state.TransactionReceipts.Clear();

            // Set our current block
            state.UpdateCurrentBlock(block);

            // TODO: Handle DAO fork transfer
        }
コード例 #11
0
        public void SetComputerState(EStateType state)
        {
            switch (state)
            {
            case EStateType.Free:
                this.computerState = new FreeState(this);
                return;

            case EStateType.Occupied:
                this.computerState = new OccupiedState(this);
                return;
            }
        }
コード例 #12
0
        public override void Mutate(State.State state)
        {
            var blueprint = state.Blueprints.FirstOrDefault(x => x.BlueprintName == EquipmentName && x.Grade == Class);

            if (blueprint != null)
            {
                foreach (var item in blueprint.Ingredients)
                {
                    state.IncrementCargo(item.Entry.Data.Name, -item.Size);
                    changes.Add(item.Entry.Data.Name, -item.Size);
                }
            }
        }
コード例 #13
0
ファイル: SaveLoadScreen.cs プロジェクト: husathap/Charlotte
        public override void UpdateFinal(GameTime gt)
        {
            if (SaveMode)
            {
                if (LogsSelection.SelectedIndex >= 0 && LogsSelection.SelectedIndex <= 7)
                {
                    Properties.Settings.Default.Logs[LogsSelection.SelectedIndex] =
                        Properties.Settings.Default.Temp;
                    Properties.Settings.Default.Save();
                }

                Main.ChangeCurrentState(this.NextState);
            }
            else
            {
                //TODO: Add navigational code here.
                if (LogsSelection.SelectedIndex >= 0 && LogsSelection.SelectedIndex <= 7)
                {
                    switch (Properties.Settings.Default.Logs[LogsSelection.SelectedIndex])
                    {
                    case "Scene II":
                        this.NextState = new Scene2();
                        break;

                    case "Scene II - Boss":
                        this.NextState = new BossBanter2();
                        break;

                    case "Scene III":
                        this.NextState = new Scene3();
                        break;

                    case "Scene III - Boss":
                        this.NextState = new BossBanter3();
                        break;

                    case "Scene IV":
                        this.NextState = new Scene4();
                        break;

                    case "Scene IV - Boss":
                        this.NextState = new BossBanter4();
                        break;
                    }
                }

                Main.ChangeCurrentState(this.NextState);
            }
        }
コード例 #14
0
        /// <summary>
        /// Given a chain and state, obtains all possible uncle candidates for the next block.
        /// </summary>
        /// <param name="chain">The chain we are currently operating on.</param>
        /// <param name="state">The state we are currently operating on.</param>
        /// <returns>Returns a list of possible uncle candidates for the next block.</returns>
        public override List <BlockHeader> GetUncleCandidates(ChainPoW chain, State.State state)
        {
            // Create our uncles list.
            List <BlockHeader> uncles = new List <BlockHeader>();

            // Uncles cannot be ancestors, and also can only be included once every max uncle depth.
            Dictionary <Memory <byte>, bool> invalidUncleList = new Dictionary <Memory <byte>, bool>(new MemoryComparer <byte>());

            foreach (byte[][] uncleHashes in state.RecentUncleHashes.Values)
            {
                foreach (byte[] uncleHash in uncleHashes)
                {
                    invalidUncleList[uncleHash] = true;
                }
            }

            // We'll want to make sure all previous headers can't be uncles
            int previousHeaderCount = Math.Min(state.Configuration.MaxUncleDepth, state.PreviousHeaders.Count);

            for (int i = 0; i < previousHeaderCount; i++)
            {
                invalidUncleList[state.PreviousHeaders[i].GetHash()] = true;
            }

            // Now we can populate our uncles
            for (int i = 0; i < previousHeaderCount; i++)
            {
                // Get all child hashes for the previous header
                byte[][] childHashes = chain.GetChildHashes(state.PreviousHeaders[i].GetHash());
                foreach (byte[] childHash in childHashes)
                {
                    // Verify it's a valid uncle, then add it.
                    if (!invalidUncleList.ContainsKey(childHash))
                    {
                        uncles.Add(chain.GetBlock(childHash).Header);
                    }

                    // If we reached our desired uncle count, we stop
                    if (uncles.Count == state.Configuration.MaxUncles)
                    {
                        return(uncles);
                    }
                }
            }

            // Return what uncles we could obtain.
            return(uncles);
        }
コード例 #15
0
        public string Ejecutar(DateTime _dtFechaEntrega, DateTime _dtHoy, State.State _entPedido)
        {
            int    result    = DateTime.Compare(_dtFechaEntrega, _dtHoy);
            string cConcepto = "";

            if (result < 0)
            {
                _entPedido.EntregarPedido();
                cConcepto = "tuvó";
            }
            else
            {
                cConcepto = "tendrá";
            }

            return(cConcepto);
        }
コード例 #16
0
        public string ObtenerMejorOpcion(List <lEmpresas> lstEmpresas, lEmpresas empresa, State.State entPedido, decimal dCostoEnvio)
        {
            string cMejorOpcion = "";

            for (int i = 0; i <= lstEmpresas.Count - 1; i++)
            {
                if (lstEmpresas[i] != empresa)
                {
                    if (lstEmpresas[i].lstEnvios.Contains(entPedido.cMedioTransporte))
                    {
                        State.State entPedidoAux = entPedido;
                        entPedidoAux.cPaqueteria = lstEmpresas[i];
                        decimal costo = lstEmpresas[i].CostoEnvio(entPedidoAux);
                        System.Console.ForegroundColor = ConsoleColor.Blue;
                        cMejorOpcion = $"Si hubieras pedido en {entPedidoAux.cPaqueteria.cNombre} te hubiera costado { (dCostoEnvio - costo)} mas barato";
                    }
                }
            }
            return(cMejorOpcion);
        }
コード例 #17
0
        /// <summary>
        /// Given a block, enters the finalization state for handling a block.
        /// </summary>
        /// <param name="state">The state to set.</param>
        /// <param name="block">The block which will be processed.</param>
        public override void Finalize(State.State state, Block.Block block)
        {
            // Obtain the rewards accordingly
            BigInteger blockReward  = 0;
            BigInteger nephewReward = 0;

            if (state.Configuration.Version >= Configuration.EthereumRelease.Byzantium)
            {
                blockReward  = state.Configuration.BlockRewardByzantium;
                nephewReward = state.Configuration.NephewRewardByzantium;
            }
            else
            {
                blockReward  = state.Configuration.BlockReward;
                nephewReward = state.Configuration.NephewReward;
            }

            // Calculate our total reward, which is our reward for the immediate block, plus rewards for each uncle processed.
            BigInteger totalReward = blockReward + (nephewReward * block.Uncles.Length);

            // Award the money to the coinbase
            state.ModifyBalanceDelta(state.CurrentBlock.Header.Coinbase, totalReward);

            // Next, we'll want to factor in our depth penalty factor for our uncles, depending on their distance from the current block.
            foreach (BlockHeader uncle in block.Uncles)
            {
                // We apply our factor to our uncle distance from the current block to obtain a multiplier for reward which takes into account penalty, which we multiply the reward by.
                BigInteger uncleReward = blockReward * (state.Configuration.UncleDepthPenaltyFactor + (uncle.BlockNumber - state.CurrentBlock.Header.BlockNumber)) / state.Configuration.UncleDepthPenaltyFactor;

                // Award our reward to the uncle's coinbase.
                state.ModifyBalanceDelta(uncle.Coinbase, uncleReward);
            }

            // We'll want to remove any recent uncles past our max after finalizing this block.
            BigInteger lastUncleBlockNumber = state.CurrentBlock.Header.BlockNumber - state.Configuration.MaxUncleDepth;

            // Check if this uncle is in our recent uncle list
            state.RecentUncleHashes.Remove(lastUncleBlockNumber);
        }
コード例 #18
0
ファイル: Main.cs プロジェクト: husathap/Charlotte
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);


            Selection.LoadSelectionContent(graphics.GraphicsDevice, Content);

            PersistentContent.AddFont("Selection",
                                      Content.Load <SpriteFont>("Fonts/Selection"));
            PersistentContent.AddFont("Slide",
                                      Content.Load <SpriteFont>("Fonts/Slide"));

            Texture2D Temp = new Texture2D(Main.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);

            Temp.SetData(new[] { Color.White });

            PersistentContent.AddTexture("Blank", Temp);
            PersistentContent.AddTexture("LoadingScreen",
                                         Texture2D.FromStream(Main.GraphicsDevice, File.OpenRead(Main.ContentManager.RootDirectory +
                                                                                                 "/Textures/LoadingScreen.dat")));
            PersistentContent.AddTexture("SaveLoad",
                                         Texture2D.FromStream(Main.GraphicsDevice, File.OpenRead(Main.ContentManager.RootDirectory +
                                                                                                 "/Textures/SaveLoad.dat")));
            PersistentContent.AddTexture("Explosion",
                                         Texture2D.FromStream(Main.GraphicsDevice, File.OpenRead(Main.ContentManager.RootDirectory +
                                                                                                 "/Textures/Explosion.dat")));

            PersistentContent.AddFont("Small", Content.Load <SpriteFont>("Fonts/Small"));
            PersistentContent.AddFont("Normal", Content.Load <SpriteFont>("Fonts/Normal"));
            PersistentContent.AddFont("Large", Content.Load <SpriteFont>("Fonts/Large"));
            PersistentContent.AddFont("XLarge", Content.Load <SpriteFont>("Fonts/XLarge"));

            //CurrentState = new IO.SaveLoadScreen(null, false);
            //CurrentState = new Title();
            //CurrentState = new Slide.TestSlide();
            CurrentState = new Title();
        }
コード例 #19
0
        /// <summary>
        /// Obtains a State instance that represents the state after the block with the given hash was processed.
        /// </summary>
        /// <param name="blockHash">The hash of the block to obtain post-processed state of.</param>
        /// <returns>Returns a State instance that represents the state after the block with the given hash was processed.</returns>
        public State.State GetPostBlockState(byte[] blockHash)
        {
            // Obtain the block.
            Block.Block block = GetBlock(blockHash);
            if (block == null)
            {
                return(null);
            }

            // Otherwise we obtain the state with the block's given state root hash and set the current block.
            State.State state = new State.State(Configuration, block.Header.StateRootHash);
            state.UpdateCurrentBlock(block);
            state.BlockGasUsed = block.Header.GasUsed;

            // We'll want to populate our previous block hashes for this state (and one for this block)
            Block.Block currentBlock = block;
            for (int i = 0; i < Configuration.PreviousHashDepth + 1; i++)
            {
                // Add our previous header
                state.PreviousHeaders.Add(currentBlock.Header);

                // If our index is less than our max uncle depth, we add our uncles
                if (i < Configuration.MaxUncleDepth)
                {
                    state.UpdateUncleHashes(currentBlock);
                }

                // Iterate to the previous block.
                currentBlock = GetParentBlock(currentBlock);
                if (currentBlock == null)
                {
                    break;
                }
            }

            return(state);
        }
コード例 #20
0
ファイル: Main.cs プロジェクト: husathap/Charlotte
 /// <summary>
 /// Exit the game.
 /// </summary>
 public static void Quit()
 {
     CurrentState = null;
 }
コード例 #21
0
ファイル: Main.cs プロジェクト: husathap/Charlotte
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            Selection.LoadSelectionContent(graphics.GraphicsDevice, Content);

            PersistentContent.AddFont("Selection",
                Content.Load<SpriteFont>("Fonts/Selection"));
            PersistentContent.AddFont("Slide",
                Content.Load<SpriteFont>("Fonts/Slide"));

            Texture2D Temp =  new Texture2D(Main.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            Temp.SetData(new[] { Color.White });

            PersistentContent.AddTexture("Blank", Temp);
            PersistentContent.AddTexture("LoadingScreen",
                Texture2D.FromStream(Main.GraphicsDevice, File.OpenRead(Main.ContentManager.RootDirectory +
                "/Textures/LoadingScreen.dat")));
            PersistentContent.AddTexture("SaveLoad",
                Texture2D.FromStream(Main.GraphicsDevice, File.OpenRead(Main.ContentManager.RootDirectory +
                "/Textures/SaveLoad.dat")));
            PersistentContent.AddTexture("Explosion",
                Texture2D.FromStream(Main.GraphicsDevice, File.OpenRead(Main.ContentManager.RootDirectory +
                "/Textures/Explosion.dat")));

            PersistentContent.AddFont("Small", Content.Load<SpriteFont>("Fonts/Small"));
            PersistentContent.AddFont("Normal", Content.Load<SpriteFont>("Fonts/Normal"));
            PersistentContent.AddFont("Large", Content.Load<SpriteFont>("Fonts/Large"));
            PersistentContent.AddFont("XLarge", Content.Load<SpriteFont>("Fonts/XLarge"));

            //CurrentState = new IO.SaveLoadScreen(null, false);
            //CurrentState = new Title();
            //CurrentState = new Slide.TestSlide();
            CurrentState = new Title();
        }
コード例 #22
0
 public void setInstance(State.State s)
 {
     _instance = s;
 }
コード例 #23
0
 public Game()
 {
     _instance = Deal.instance();
 }
コード例 #24
0
ファイル: Account.cs プロジェクト: Paulmcl78/PatternPractice
 public Account(string owner)
 {
     // New accounts are 'Silver' by default
     _owner = owner;
     _state = new SilverState(0.0, this);
 }
コード例 #25
0
 public override void Mutate(State.State state)
 {
     Operation?.Mutate(state);
 }
コード例 #26
0
ファイル: Main.cs プロジェクト: husathap/Charlotte
 /// <summary>
 /// Change the current state.
 /// </summary>
 /// <param name="NewState"></param>
 public static void ChangeCurrentState(State.State NewState)
 {
     Main.SongPlayer.Close();
     TemporaryContent.Clear();
     CurrentState = NewState;
 }
コード例 #27
0
 public override void Mutate(State.State state)
 {
     state.History.IncrementCargo(MaterialName, Size, false);
 }
コード例 #28
0
ファイル: SaveLoadScreen.cs プロジェクト: husathap/Charlotte
        public override void UpdateFinal(GameTime gt)
        {
            if (SaveMode)
            {
                if (LogsSelection.SelectedIndex >= 0 && LogsSelection.SelectedIndex <= 7)
                {
                    Properties.Settings.Default.Logs[LogsSelection.SelectedIndex] =
                        Properties.Settings.Default.Temp;
                    Properties.Settings.Default.Save();
                }

                Main.ChangeCurrentState(this.NextState);
            }
            else
            {
                //TODO: Add navigational code here.
                if (LogsSelection.SelectedIndex >= 0 && LogsSelection.SelectedIndex <= 7)
                {
                    switch (Properties.Settings.Default.Logs[LogsSelection.SelectedIndex])
                    {
                        case "Scene II":
                            this.NextState = new Scene2();
                            break;
                        case "Scene II - Boss":
                            this.NextState = new BossBanter2();
                            break;
                        case "Scene III":
                            this.NextState = new Scene3();
                            break;
                        case "Scene III - Boss":
                            this.NextState = new BossBanter3();
                            break;
                        case "Scene IV":
                            this.NextState = new Scene4();
                            break;
                        case "Scene IV - Boss":
                            this.NextState = new BossBanter4();
                            break;
                    }
                }

                Main.ChangeCurrentState(this.NextState);
            }
        }
コード例 #29
0
 public override void Mutate(State.State state)
 {
     state.UpdateLoadout(loadout);
 }
コード例 #30
0
 /// <summary>
 /// Checks that the proof for this consensus mechanism is valid. (Checks proof of work, proof of stake, etc).
 /// </summary>
 /// <param name="state">The current state we have while checking proof.</param>
 /// <param name="blockHeader">The block which we are checking proof for.</param>
 /// <returns>Returns true if proof is valid. Returns false if proof is invalid.</returns>
 public override bool CheckProof(State.State state, BlockHeader blockHeader)
 {
     // Check our proof of work.
     return(state.Configuration.IgnoreEthashVerification || MiningPoW.CheckProof(blockHeader.BlockNumber, blockHeader.GetMiningHash(), blockHeader.MixHash, blockHeader.Nonce, blockHeader.Difficulty));
 }
コード例 #31
0
        /// <summary>
        /// Verifies all uncles in a given block to be processed.
        /// </summary>
        /// <param name="state">The state which accompanied the block to verify the uncles of.</param>
        /// <param name="block">The block to verify the uncles of.</param>
        /// <returns>Returns true if verification succeeded, returns false or throws an exception otherwise.</returns>
        public override bool VerifyUncles(State.State state, Block.Block block)
        {
            // Verify our uncles hash matches
            if (!block.Header.UnclesHash.ValuesEqual(block.CalculateUnclesHash()))
            {
                throw new BlockException("Block validation failed due to a hash mismatch when validating uncles.");
            }

            // Verify our uncle hash count did not exceed the maximum uncle count
            if (block.Uncles.Length > state.Configuration.MaxUncleDepth)
            {
                throw new BlockException("Block validation failed because the amount of uncles attached exceeded the maximum uncle count.");
            }

            // By definition, any uncle should be lower block number than the given block, since its only included as an uncle after it fails to be included at its desired block number.
            foreach (BlockHeader uncle in block.Uncles)
            {
                if (uncle.BlockNumber >= block.Header.BlockNumber)
                {
                    throw new BlockException("Block validation failed because an uncle's block number was not less than the block number it was included in.");
                }
            }

            // Obtain our list of ancestors.
            BlockHeader[] ancestors = new BlockHeader[Math.Min(state.Configuration.MaxUncleDepth + 1, state.PreviousHeaders.Count) + 1];
            ancestors[0] = block.Header;
            for (int i = 1; i < ancestors.Length; i++)
            {
                ancestors[i] = state.PreviousHeaders[i - 1];
            }

            // Create our valid ancestor list, the uncle header could've been
            Dictionary <byte[], BlockHeader> validUncleParents = new Dictionary <byte[], BlockHeader>();

            for (int i = 2; i < ancestors.Length; i++)
            {
                validUncleParents[ancestors[i].GetHash()] = ancestors[i];
            }

            // Uncles cannot be ancestors, and also can only be included once every max uncle depth.
            Dictionary <byte[], bool> invalidUncleList = new Dictionary <byte[], bool>(new ArrayComparer <byte[]>());

            foreach (var recentUncleHashes in state.RecentUncleHashes)
            {
                // Verify this uncle list comes from a block number before the current block.
                if (state.CurrentBlock.Header.BlockNumber <= recentUncleHashes.Key)
                {
                    continue;
                }

                // Verify this uncle list comes at a block number not past our max uncle depth from our current block number.
                if (recentUncleHashes.Key < state.CurrentBlock.Header.BlockNumber - state.Configuration.MaxUncleDepth)
                {
                    continue;
                }

                // Add our uncle hash to our list.
                foreach (byte[] uncleHash in recentUncleHashes.Value)
                {
                    invalidUncleList[uncleHash] = true;
                }
            }

            // Loop for all this current blocks uncles
            foreach (BlockHeader uncle in block.Uncles)
            {
                // Verify uncle's parent is part of our valid list
                if (!validUncleParents.TryGetValue(uncle.PreviousHash, out var parent))
                {
                    throw new BlockException("Block validation failed because uncles previous hash referenced a block that was not deemed a valid uncle parent.");
                }

                // Verify our difficulty
                BigInteger calculatedDifficulty = Block.Block.CalculateDifficulty(parent, uncle.Timestamp, state.Configuration);
                if (uncle.Difficulty != calculatedDifficulty)
                {
                    throw new BlockException($"Block validation failed because uncle had a difficulty mismatch. Expected = {calculatedDifficulty}, Actual = {uncle.Difficulty}");
                }

                // Verify block number
                if (uncle.BlockNumber != parent.BlockNumber + 1)
                {
                    throw new BlockException("Block validation failed because uncle's block number was not sequentially following its parent.");
                }

                // Verify timestamp
                if (uncle.Timestamp < parent.Timestamp)
                {
                    throw new BlockException($"Block validation failed because uncle's timestamp was less than its parent. Uncle = {uncle.Timestamp}, Parent={parent.Timestamp}");
                }

                // Verify our uncle isn't in our invalid list
                byte[] uncleHash = uncle.GetHash();
                if (invalidUncleList.ContainsKey(uncleHash))
                {
                    throw new BlockException("Block validation failed because uncle was also a direct ancestor or didn't meet depth requirements.");
                }

                // Verify our uncle didn't use more gas than the limit
                if (uncle.GasUsed > uncle.GasLimit)
                {
                    throw new BlockException("Block validation failed because uncle gas used exceeded the uncle gas limit.");
                }

                // Check the proof for our uncle
                if (!CheckProof(state, uncle))
                {
                    throw new BlockException("Block validation failed because uncle has a proof of work check failure!");
                }

                // Add this uncle to in invalid uncle list, as there should be no duplicates going forward.
                invalidUncleList[uncleHash] = true;
            }

            // Return our boolean indicating we succeeded.
            return(true);
        }
コード例 #32
0
        // Overloaded constructors

        public GoldState(State.State state) : this(state.Balance, state.Account)
        {
        }
コード例 #33
0
 public void SetUp()
 {
     _state = new State.State();
 }
コード例 #34
0
 public StateResponse(State.State state)
 {
     State = state;
 }
コード例 #35
0
 public override void Mutate(State.State state)
 {
     state.IncrementCargo(DataName, Size);
 }
コード例 #36
0
ファイル: NoOperation.cs プロジェクト: williamrice/EDEngineer
 public override void Mutate(State.State state)
 {
     // NOP
 }