Beispiel #1
0
        public Task <BlockContent> ReadBlockAsync(BigInteger blockHeight)
        {
            BlockContent blockContent = _blocks.FirstOrDefault(x => x.BlockModel.Number == blockHeight);
            BlockContent copy         = Force.DeepCloner.DeepClonerExtensions.DeepClone(blockContent);

            return(Task.FromResult(copy));
        }
Beispiel #2
0
 public override void Apply(BlockContent block)
 {
     if (block.entity)
     {
         block.entity.current.health += heal;
     }
 }
Beispiel #3
0
 public Block(string blockIri, BlockHeader blockHeader, BlockContent blockContent, bool genesisBlock)
 {
     BlockIri       = blockIri;
     BlockHeader    = blockHeader;
     BlockContent   = blockContent;
     IsGenesisBlock = genesisBlock;
 }
Beispiel #4
0
        public static PreEvaluationBlock <T> MineNext <T>(
            Block <T> previousBlock,
            HashAlgorithmGetter hashAlgorithmGetter,
            IReadOnlyList <Transaction <T> > txs = null,
            byte[] nonce           = null,
            long difficulty        = 1,
            PublicKey miner        = null,
            TimeSpan?blockInterval = null,
            int protocolVersion    = Block <T> .CurrentProtocolVersion
            )
            where T : IAction, new()
        {
            var content = new BlockContent <T>
            {
                Index           = previousBlock.Index + 1,
                Difficulty      = difficulty,
                TotalDifficulty = previousBlock.TotalDifficulty + difficulty,
                Miner           = miner?.ToAddress() ?? previousBlock.Miner,
                PublicKey       = protocolVersion < 2 ? null : miner ?? previousBlock.PublicKey,
                PreviousHash    = previousBlock.Hash,
                Timestamp       = previousBlock.Timestamp.Add(blockInterval ?? TimeSpan.FromSeconds(15)),
                Transactions    = txs ?? Array.Empty <Transaction <T> >(),
                ProtocolVersion = protocolVersion,
            };

            HashAlgorithmType hashAlgorithm = hashAlgorithmGetter(previousBlock.Index + 1);
            var preEval = nonce is byte[] nonceBytes
                ? new PreEvaluationBlock <T>(content, hashAlgorithm, new Nonce(nonceBytes))
                : content.Mine(hashAlgorithm);

            preEval.ValidateTimestamp();
            return(preEval);
        }
Beispiel #5
0
    public BlockContent with(Entity entity)
    {
        BlockContent newOne = (BlockContent)this.MemberwiseClone();

        newOne.entity = entity;
        return(newOne);
    }
Beispiel #6
0
        private void CreateGenesisBlock()
        {
            string dataGraphIri = DEFAULT_GENESIS_BLOCK_DATA_GRAPH_IRI;
            string newIndex     = "0";
            string newBlockIri  = _chainGraphIri + "/" + newIndex;

            var deserializedModel = _dotNetRdfSerializationHandler.DeserializeGraph(dataGraphIri, GetRawContentOfGcoOntology(), RdfFormat.TURTLE);
            var triples           = _dotNetRdfMapper.GraphToTriples(deserializedModel);

            string previousBlock = newBlockIri;
            string previousHash  = DEFAULT_GENESIS_BLOCK_PREVIOUS_HASH;
            string timestamp     = DEFAULT_GENESIS_BLOCK_TIME_STAMP;

            string dataHash = _hashingService.CalculateHash(triples);
            string stringToCalculateHash = (newIndex + newBlockIri + previousHash + timestamp + dataGraphIri + dataHash).Trim();
            string hash = _hashCalculator.CalculateHash(stringToCalculateHash).ToLower();

            BlockHeader blockHeader = new BlockHeader(
                dataGraphIri,
                dataHash,
                hash,
                newIndex,
                previousBlock,
                previousHash,
                timestamp);
            BlockContent blockContent = new BlockContent(dataGraphIri, triples);
            Block        genesisBlock = new Block(newBlockIri, blockHeader, blockContent, true);

            PersistBlock(genesisBlock, true);
        }
Beispiel #7
0
        public static string ToJson(List <Models.Block> blocks, BlockContent include, bool FormatIntended)
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = FormatIntended,
            };

            options.Converters.Add(new JsonConverters.HashConverter());
            options.Converters.Add(new JsonConverters.PublicKeyConverter());
            options.Converters.Add(new JsonConverters.SignatureConverter());
            options.Converters.Add(new JsonConverters.MoneyConverter());
            options.Converters.Add(new JsonConverters.BytesConverter());
            options.Converters.Add(new JsonConverters.UserFieldBytesConverter());
            options.Converters.Add(new JsonConverters.UserFieldMoneyConverter());
            options.Converters.Add(new JsonConverters.UserFieldIntegerConverter());

            List <Models.Block> json_content;

            if (include.All)
            {
                json_content = blocks;
            }
            else
            {
                json_content = new List <Block>();
                // remove
                foreach (var src_block in blocks)
                {
                    json_content.Add(GetBlockService.CopyFrom(src_block, include));
                }
            }

            return(JsonSerializer.Serialize(json_content, options));
        }
Beispiel #8
0
        private void ValidateNextBlockInvalidIndex()
        {
            _blockChain.Append(_validNext);

            Block <DumbAction> prev = _blockChain.Tip;
            Block <DumbAction> blockWithAlreadyUsedIndex = new BlockContent <DumbAction>
            {
                Index           = prev.Index,
                Difficulty      = 1,
                TotalDifficulty = 1 + prev.TotalDifficulty,
                PublicKey       = _fx.Miner.PublicKey,
                PreviousHash    = prev.Hash,
                Timestamp       = prev.Timestamp.AddDays(1),
                Transactions    = _emptyTransaction,
            }.Mine(_fx.GetHashAlgorithm(prev.Index)).Evaluate(_fx.Miner, _blockChain);

            Assert.Throws <InvalidBlockIndexException>(
                () => _blockChain.Append(blockWithAlreadyUsedIndex)
                );

            Block <DumbAction> blockWithIndexAfterNonexistentIndex = new BlockContent <DumbAction>
            {
                Index           = prev.Index + 2,
                Difficulty      = 1,
                TotalDifficulty = 1 + prev.TotalDifficulty,
                PublicKey       = _fx.Miner.PublicKey,
                PreviousHash    = prev.Hash,
                Timestamp       = prev.Timestamp.AddDays(1),
                Transactions    = _emptyTransaction,
            }.Mine(_fx.GetHashAlgorithm(prev.Index + 2)).Evaluate(_fx.Miner, _blockChain);

            Assert.Throws <InvalidBlockIndexException>(
                () => _blockChain.Append(blockWithIndexAfterNonexistentIndex)
                );
        }
Beispiel #9
0
        public async void Query()
        {
            var privateKey = new PrivateKey();
            var preEval    = new BlockContent <NullAction>
            {
                Index           = 1,
                Difficulty      = 1,
                TotalDifficulty = 1,
                PublicKey       = privateKey.PublicKey,
                PreviousHash    = new BlockHash(TestUtils.GetRandomBytes(HashDigest <SHA256> .Size)),
                Timestamp       = DateTimeOffset.UtcNow,
            }.Mine(HashAlgorithmType.Of <SHA256>());
            var stateRootHash =
                new HashDigest <SHA256>(TestUtils.GetRandomBytes(HashDigest <SHA256> .Size));
            var block = new Block <NullAction>(
                preEval,
                stateRootHash,
                preEval.MakeSignature(privateKey, stateRootHash)
                );
            var query =
                @"{
                    index
                    hash
                    nonce
                    difficulty
                    totalDifficulty
                    miner
                    publicKey
                    timestamp
                    stateRootHash
                    signature
                }";

            ExecutionResult result =
                await ExecuteQueryAsync <BlockType <NullAction> >(query, source : block);

            Dictionary <string, object> resultData = (Dictionary <string, object>)result.Data;

            Assert.Null(result.Errors);
            Assert.Equal(block.Index, resultData["index"]);
            Assert.Equal(
                ByteUtil.Hex(block.Hash.ToByteArray()),
                resultData["hash"]);
            Assert.Equal(block.Difficulty, resultData["difficulty"]);
            Assert.Equal(
                block.TotalDifficulty,
                resultData["totalDifficulty"]);
            Assert.Equal(
                block.Miner.ToString(),
                resultData["miner"]);
            Assert.Equal(
                ByteUtil.Hex(block.Nonce.ToByteArray()),
                resultData["nonce"]);
            Assert.Equal(
                new DateTimeOffsetGraphType().Serialize(block.Timestamp),
                resultData["timestamp"]);
            Assert.Equal(
                ByteUtil.Hex(block.StateRootHash.ToByteArray()),
                resultData["stateRootHash"]);
        }
Beispiel #10
0
 public BlockContext(string jobId, int jobVersion, string indexerId, BlockContent blockContent)
 {
     IndexerId    = indexerId;
     JobId        = jobId;
     JobVersion   = jobVersion;
     BlockContent = blockContent;
 }
        public void TransactionsWithInconsistentGenesisHashes()
        {
            var key = PrivateKey.FromString(
                "2ed05de0b35d93e4ae801ae40c8bb4257a771ff67c1e5d1754562e4191953710"
                );
            var differentGenesisHash = BlockHash.FromString(
                "76942b42f99c28da02ed916ebd2fadb189415e8288a4bd87f9ae3594127b79e6"
                );
            var txWithDifferentGenesis = new Transaction <Arithmetic>(
                nonce: 0L,
                signer: key.ToAddress(),
                publicKey: key.PublicKey,
                genesisHash: differentGenesisHash,
                updatedAddresses: ImmutableHashSet <Address> .Empty,
                timestamp: new DateTimeOffset(2021, 9, 7, 12, 1, 12, 345, TimeSpan.FromHours(9)),
                actions: Array.Empty <Arithmetic>(),
                signature: ByteUtil.ParseHex(
                    "304402202027a31e4298c685daaa944b1d120b4e6894f3bfffa13563331c0a7071a04b" +
                    "310220167507575e982d47d7c6753b782a5f1beb6415af96e7db3ccaf83b516d5133d1"
                    )
                );
            BlockContent <Arithmetic> block = Block1.Copy();

            Transaction <Arithmetic>[] inconsistentTxs =
                block.Transactions.Append(txWithDifferentGenesis).ToArray();
            InvalidTxGenesisHashException e = Assert.Throws <InvalidTxGenesisHashException>(
                () => block.Transactions = inconsistentTxs
                );

            Assert.Equal(Block1.Transactions[0].GenesisHash, e.ExpectedGenesisHash);
            Assert.Equal(differentGenesisHash, e.ImproperGenesisHash);
            Assert.Equal(Block1.Transactions, block.Transactions);
        }
    public void leftClickCloneBtn() {
        

        if(myButton.interactable == true) {
            OpenBlock();
            playSound();
            if (Protocol.m_gameMode == Protocol.gameMode.STORY_MODE) { 
                if(m_posX == Protocol.endPosX && m_posY == Protocol.endPosY)
                {
                    MapManager.Instance.setFinished(true);
                    return;
                }
            }

            m_recX = transform.position.x;
            m_recY = transform.position.y;

            if (myState == MapManager.BlockState.UNKNOW) { 
                if (!myMapManager.isMapContextExist()) {
                    myMapManager.buildRandomMapContent(m_posX,m_posY);
                }

                myButtonContent = myMapManager.pressCloneBtn(m_posX, m_posY,this);
                if(myButtonContent.getType() != BlockType.Type.MONSTER)
                    showContent();
                Debug.Log("Press " + myButtonContent.toString());
                if(myButtonContent.getType() != BlockType.Type.TERRAIN)
                    MapManager.Instance.activeCloneBtnAround(m_posX, m_posY);
            }
        }
    }
        public void AddBlock(BlockHeader blockHeader, BlockContent blockContent)
        {
            var   blockIri     = GenerateNewBlockIri(blockHeader.GetIndexAsInt());
            Block blockToStore = new Block(blockIri, blockHeader, blockContent);

            _repositoryManager.PersistBlock(blockToStore, false);
            _lastIndex++;
        }
Beispiel #14
0
 public override void Apply(BlockContent block)
 {
     if (block.entity)
     {
         block.entity.current.health -= damage;
     }
     block.effect = effect;
 }
        public Block CreateBlock(string dataGraphIri, string rawRdf, RdfFormat rdfFormat)
        {
            _logger.LogDebug("Creating block with graphIri '{0}' and rdfFormat '{1}'...", dataGraphIri, rdfFormat.GetJenaName());

            try
            {
                HashSet <Triple> triples = GetTriplesFromSerializedModel(rawRdf, rdfFormat);

                long   newIndex    = GenerateNewIndex();
                string newBlockIri = GenerateNewBlockIri(newIndex);

                LastBlockInfo lastBlockInfo         = _repositoryManager.GetLastBlockInfo();
                string        previousBlock         = lastBlockInfo.BlockIri;
                string        previousHash          = lastBlockInfo.BlockHash;
                string        timestamp             = TimestampCreator.CreateTimestampString();
                string        dataHash              = _hashingService.CalculateHash(triples);
                string        stringToCalculateHash = (newIndex + previousBlock + previousHash + timestamp + dataGraphIri + dataHash).Trim();
                string        hash = _hashCalculator.CalculateHash(stringToCalculateHash).ToLower();

                BlockHeader blockHeader = new BlockHeader(
                    dataGraphIri,
                    dataHash,
                    hash,
                    newIndex.ToString(),
                    previousBlock,
                    previousHash,
                    timestamp);
                BlockContent blockContent = new BlockContent(dataGraphIri, triples);

                Block blockToStore = new Block(newBlockIri, blockHeader, blockContent);

                _repositoryManager.PersistBlock(blockToStore, true);

                // MAYBE: Maybe this should be obtained from Triple Store in order to avoid some kind of inconsistency.
                _lastIndex++;

                return(GetBlock(newIndex.ToString()));
            }
            catch (ReadingBlockException ex)
            {
                string msg = "Exception was thrown while getting information about the last block.";
                throw new CreatingBlockException(msg, ex);
            }
            catch (RdfSerializationException ex)
            {
                string msg = String.Format("Exception was thrown while deserializing RDF model from '{0}' format.", rdfFormat);
                throw new CreatingBlockException(msg, ex);
            }
            catch (CalculatingHashException ex)
            {
                throw new CreatingBlockException("Exception was thrown while calculating hash.", ex);
            }
        }
Beispiel #16
0
        public void Evaluate()
        {
            Address address     = _contents.Tx0InBlock1.Signer;
            var     blockAction = new SetStatesAtBlock(address, (Bencodex.Types.Integer) 123, 0);
            var     policy      = new BlockPolicy <Arithmetic>(
                blockAction: blockAction,
                blockInterval: TimeSpan.FromMilliseconds(3 * 60 * 60 * 1000),
                minimumDifficulty: 2,
                difficultyStability: 1
                );
            var stagePolicy = new VolatileStagePolicy <Arithmetic>();

            PreEvaluationBlock <Arithmetic> preEvalGenesis =
                _contents.Genesis.Mine(policy.GetHashAlgorithm(0));

            using (var fx = new DefaultStoreFixture())
            {
                Block <Arithmetic> genesis =
                    preEvalGenesis.Evaluate(_contents.GenesisKey, blockAction, fx.StateStore);
                AssertPreEvaluationBlocksEqual(preEvalGenesis, genesis);
                _output.WriteLine("#1: {0}", genesis);

                var blockChain = new BlockChain <Arithmetic>(
                    policy,
                    stagePolicy,
                    fx.Store,
                    fx.StateStore,
                    genesis
                    );
                AssertBencodexEqual((Bencodex.Types.Integer) 123, blockChain.GetState(address));

                HashDigest <SHA256> identicalGenesisStateRootHash =
                    preEvalGenesis.DetermineStateRootHash(blockChain);
                AssertBytesEqual(genesis.StateRootHash, identicalGenesisStateRootHash);

                BlockContent <Arithmetic> content1 = _contents.Block1;
                content1.PreviousHash = genesis.Hash;
                content1.Difficulty   = 2;
                content1.Transactions = new[] { _contents.Tx0InBlock1 };
                PreEvaluationBlock <Arithmetic> preEval1 = content1.Mine(policy.GetHashAlgorithm(1));

                Block <Arithmetic> block1 = preEval1.Evaluate(_contents.Block1Key, blockChain);
                AssertPreEvaluationBlocksEqual(preEval1, block1);
                _output.WriteLine("#1: {0}", block1);

                HashDigest <SHA256> identicalBlock1StateRootHash =
                    preEval1.DetermineStateRootHash(blockChain);
                AssertBytesEqual(block1.StateRootHash, identicalBlock1StateRootHash);

                blockChain.Append(block1);
                AssertBencodexEqual((Bencodex.Types.Integer) 158, blockChain.GetState(address));
            }
        }
Beispiel #17
0
        public override void UnsafeConstructor()
        {
            BlockContent <Arithmetic> content = _contents.Genesis.Copy();
            var preEvalBlock =
                new PreEvaluationBlock <Arithmetic>(content, _sha256, _validGenesisProof);

            AssertBlockContentsEqual(content, preEvalBlock);
            AssertBytesEqual(_validGenesisProof.Nonce, preEvalBlock.Nonce);
            Assert.Same(_sha256, preEvalBlock.HashAlgorithm);
            AssertBytesEqual(_validGenesisProof.PreEvaluationHash, preEvalBlock.PreEvaluationHash);

            content      = _contents.Block1.Copy();
            preEvalBlock = new PreEvaluationBlock <Arithmetic>(content, _sha256, _validBlock1Proof);
            AssertBlockContentsEqual(content, preEvalBlock);
            AssertBytesEqual(_validBlock1Proof.Nonce, preEvalBlock.Nonce);
            Assert.Same(_sha256, preEvalBlock.HashAlgorithm);
            AssertBytesEqual(_validBlock1Proof.PreEvaluationHash, preEvalBlock.PreEvaluationHash);

            Assert.Throws <InvalidBlockNonceException>(
                () => new PreEvaluationBlock <Arithmetic>(content, _sha256, _invalidBlock1Proof)
                );

            content = _contents.Block1.Copy();
            content.PreviousHash = null;
            Assert.Throws <InvalidBlockPreviousHashException>(
                () => new PreEvaluationBlock <Arithmetic>(content, _sha256, _validBlock1Proof)
                );

            content = _contents.Genesis.Copy();
            content.PreviousHash = _contents.GenesisHash;
            Assert.Throws <InvalidBlockPreviousHashException>(
                () => new PreEvaluationBlock <Arithmetic>(content, _sha256, _validGenesisProof)
                );

            content            = _contents.Block1.Copy();
            content.Difficulty = 0L;
            Assert.Throws <InvalidBlockDifficultyException>(
                () => new PreEvaluationBlock <Arithmetic>(content, _sha256, _validBlock1Proof.Nonce)
                );

            content            = _contents.Genesis.Copy();
            content.Difficulty = 1L;
            Assert.Throws <InvalidBlockDifficultyException>(
                () => new PreEvaluationBlock <Arithmetic>(content, _sha256, _validGenesisProof)
                );

            content = _contents.Genesis.Copy();
            content.TotalDifficulty = 1;
            Assert.Throws <InvalidBlockTotalDifficultyException>(
                () => new PreEvaluationBlock <Arithmetic>(content, _sha256, _validGenesisProof)
                );
        }
 public void DeriveTxHash()
 {
     Assert.Null(
         BlockContent <Arithmetic> .DeriveTxHash(Array.Empty <Transaction <Arithmetic> >())
         );
     AssertBytesEqual(
         BlockMetadata1.TxHash,
         BlockContent <Arithmetic> .DeriveTxHash(Block1.Transactions)
         );
     Assert.Throws <ArgumentException>(
         () => BlockContent <Arithmetic> .DeriveTxHash(Block1.Transactions.Reverse())
         );
 }
        private void ValidateNextBlockProtocolVersion()
        {
            Block <DumbAction> block1 = new BlockContent <DumbAction>
            {
                Index           = 1,
                Difficulty      = 1024,
                TotalDifficulty = _fx.GenesisBlock.TotalDifficulty + 1024,
                PublicKey       = _fx.Miner.PublicKey,
                PreviousHash    = _fx.GenesisBlock.Hash,
                Timestamp       = _fx.GenesisBlock.Timestamp.AddDays(1),
                Transactions    = _emptyTransaction,
                ProtocolVersion = _blockChain.Tip.ProtocolVersion,
            }.Mine(_fx.GetHashAlgorithm(1)).Evaluate(_fx.Miner, _blockChain);

            _blockChain.Append(block1);

            PreEvaluationBlock <DumbAction> preEvalblock2 = new BlockContent <DumbAction>
            {
                Index           = 2,
                Difficulty      = 1024,
                TotalDifficulty = block1.TotalDifficulty + 1024,
                Miner           = _fx.GenesisBlock.Miner,
                PreviousHash    = block1.Hash,
                Timestamp       = _fx.GenesisBlock.Timestamp.AddDays(1),
                Transactions    = _emptyTransaction,
                ProtocolVersion = _blockChain.Tip.ProtocolVersion - 1,
            }.Mine(_fx.GetHashAlgorithm(2));
            Block <DumbAction> block2 = new Block <DumbAction>(
                preEvalblock2,
                preEvalblock2.DetermineStateRootHash(_blockChain),
                null
                );

            Assert.Throws <InvalidBlockProtocolVersionException>(() => _blockChain.Append(block2));

            Assert.Throws <InvalidBlockProtocolVersionException>(() =>
            {
                Block <DumbAction> block3 = new BlockContent <DumbAction>
                {
                    Index           = 2,
                    Difficulty      = 1024,
                    TotalDifficulty = block1.TotalDifficulty + 1024,
                    PublicKey       = _fx.Miner.PublicKey,
                    PreviousHash    = block1.Hash,
                    Timestamp       = _fx.GenesisBlock.Timestamp.AddDays(1),
                    Transactions    = _emptyTransaction,
                    ProtocolVersion = BlockMetadata.CurrentProtocolVersion + 1,
                }.Mine(_fx.GetHashAlgorithm(2)).Evaluate(_fx.Miner, _blockChain);
                _blockChain.Append(block3);
            });
        }
        public void ReplaceBlockchain(List <BlockHeader> blockHeaders, List <BlockContent> blockContents)
        {
            _logger.LogDebug("Attempting to replace the whole blockchain.");
            var blocksToPersist = new List <Block>();

            foreach (BlockHeader blockHeader in blockHeaders)
            {
                var          blockIri     = GenerateNewBlockIri(blockHeader.GetIndexAsInt());
                BlockContent blockContent = FindBlockContentByBlockHeader(blockContents, blockHeader);
                blocksToPersist.Add(new Block(blockIri, blockHeader, blockContent));
            }
            _logger.LogDebug("Ready to persist the following blocks: {}.", blocksToPersist);
            _repositoryManager.ClearBlockchainAndPersistBlocks(blocksToPersist);
        }
Beispiel #21
0
        public async Task BroadcastIgnoreFromDifferentGenesisHash()
        {
            var receiverKey = new PrivateKey();
            Swarm <DumbAction>      receiverSwarm = CreateSwarm(receiverKey);
            BlockChain <DumbAction> receiverChain = receiverSwarm.BlockChain;
            var seedStateStore = new TrieStateStore(new MemoryKeyValueStore());
            IBlockPolicy <DumbAction> policy            = receiverChain.Policy;
            Block <DumbAction>        mismatchedGenesis = new BlockContent <DumbAction>
            {
                PublicKey = receiverKey.PublicKey,
                Timestamp = DateTimeOffset.MinValue,
            }
            .Mine(policy.GetHashAlgorithm(0))
            .Evaluate(receiverKey, policy.BlockAction, seedStateStore);
            BlockChain <DumbAction> seedChain = TestUtils.MakeBlockChain(
                policy,
                new DefaultStore(path: null),
                seedStateStore,
                genesisBlock: mismatchedGenesis);
            var seedMiner = new PrivateKey();
            Swarm <DumbAction> seedSwarm = CreateSwarm(seedChain, seedMiner);

            try
            {
                await StartAsync(receiverSwarm);
                await StartAsync(seedSwarm);

                await receiverSwarm.AddPeersAsync(new[] { seedSwarm.AsPeer }, null);

                Block <DumbAction> block = await seedChain.MineBlock(seedMiner);

                seedSwarm.BroadcastBlock(block);
                while (!((NetMQTransport)receiverSwarm.Transport).MessageHistory
                       .Any(msg => msg is BlockHeaderMessage))
                {
                    await Task.Delay(100);
                }

                await Task.Delay(100);

                Assert.NotEqual(seedChain.Tip, receiverChain.Tip);
            }
            finally
            {
                await StopAsync(seedSwarm);
                await StopAsync(receiverSwarm);

                seedSwarm.Dispose();
            }
        }
Beispiel #22
0
        public override void SafeConstructorWithPreEvaluationHash()
        {
            BlockContent <Arithmetic> content = _contents.Genesis.Copy();
            var preEvalBlock = new PreEvaluationBlock <Arithmetic>(
                content,
                hashAlgorithm: _sha256,
                nonce: _validGenesisProof.Nonce,
                preEvaluationHash: _validGenesisProof.PreEvaluationHash
                );

            AssertBlockContentsEqual(content, preEvalBlock);
            AssertBytesEqual(_validGenesisProof.Nonce, preEvalBlock.Nonce);
            Assert.Same(_sha256, preEvalBlock.HashAlgorithm);
            AssertBytesEqual(_validGenesisProof.PreEvaluationHash, preEvalBlock.PreEvaluationHash);

            content      = _contents.Block1.Copy();
            preEvalBlock = new PreEvaluationBlock <Arithmetic>(
                content,
                hashAlgorithm: _sha256,
                nonce: _validBlock1Proof.Nonce,
                preEvaluationHash: _validBlock1Proof.PreEvaluationHash
                );
            AssertBlockContentsEqual(content, preEvalBlock);
            AssertBytesEqual(_validBlock1Proof.Nonce, preEvalBlock.Nonce);
            Assert.Same(_sha256, preEvalBlock.HashAlgorithm);
            AssertBytesEqual(_validBlock1Proof.PreEvaluationHash, preEvalBlock.PreEvaluationHash);

            // Mutating the BlockContent<T> instance does not affect PreEvaluatingBlock<T> instance:
            content.Index++;
            Assert.Equal(_contents.Block1.Index, preEvalBlock.Index);

            content = _contents.Block1.Copy();
            Assert.Throws <InvalidBlockNonceException>(() =>
                                                       new PreEvaluationBlock <Arithmetic>(
                                                           content,
                                                           hashAlgorithm: _sha256,
                                                           nonce: _invalidBlock1Proof.Nonce,
                                                           preEvaluationHash: _invalidBlock1Proof.PreEvaluationHash
                                                           )
                                                       );
            Assert.Throws <InvalidBlockPreEvaluationHashException>(() =>
                                                                   new PreEvaluationBlock <Arithmetic>(
                                                                       content,
                                                                       hashAlgorithm: _sha256,
                                                                       nonce: _validBlock1Proof.Nonce,
                                                                       preEvaluationHash: _invalidBlock1Proof.PreEvaluationHash
                                                                       )
                                                                   );
        }
        public void Constructor()
        {
            DateTimeOffset before = DateTimeOffset.UtcNow;
            var            m      = new BlockContent <Arithmetic>();
            DateTimeOffset after  = DateTimeOffset.UtcNow;

            Assert.Equal(BlockMetadata.CurrentProtocolVersion, m.ProtocolVersion);
            Assert.Equal(0, m.Index);
            Assert.InRange(m.Timestamp, before, after);
            AssertBytesEqual(default(Address), m.Miner);
            Assert.Equal(0, m.Difficulty);
            Assert.Equal(0, m.TotalDifficulty);
            AssertBytesEqual(null, m.PreviousHash);
            AssertBytesEqual(null, m.TxHash);
            Assert.Empty(m.Transactions);
        }
Beispiel #24
0
        public void ValidateNextBlock()
        {
            Block <DumbAction> validNextBlock = new BlockContent <DumbAction>
            {
                Index           = 1,
                Difficulty      = 1024,
                TotalDifficulty = _fx.GenesisBlock.TotalDifficulty + 1024,
                PublicKey       = _fx.Miner.PublicKey,
                PreviousHash    = _fx.GenesisBlock.Hash,
                Timestamp       = _fx.GenesisBlock.Timestamp.AddDays(1),
                Transactions    = _emptyTransaction,
            }.Mine(_fx.GetHashAlgorithm(1)).Evaluate(_fx.Miner, _blockChain);

            _blockChain.Append(validNextBlock);
            Assert.Equal(_blockChain.Tip, validNextBlock);
        }
Beispiel #25
0
        public void NormalState()
        {
            ReceiveAsync <IndexBlockMessage>(async(message) =>
            {
                var indexerId             = message.IndexerId;
                var currentBlockNumber    = message.BlockNumber;
                int iterationVector       = 0;
                BlockContent blockContent = null;
                int transactionCount      = 0;

                await _logger.WriteInfoAsync
                (
                    "BlockIndexingJob",
                    "RunAsync",
                    indexerId,
                    $"Indexing block-{currentBlockNumber},",
                    DateTime.UtcNow
                );

                await RetryPolicy.ExecuteAsync(async() =>
                {
                    blockContent = blockContent ?? await _rpcBlockReader.ReadBlockAsync(currentBlockNumber);

                    var blockContext = new BlockContext(Id, Version, indexerId, blockContent);
                    var blockExists  = await _blockService.DoesBlockExist(blockContent.BlockModel.ParentHash);

                    transactionCount = blockContent.Transactions.Count;
                    iterationVector  = blockExists ? 1 : -1; //That is how we deal with forks

                    await _indexingService.IndexBlockAsync(blockContext);
                }, 5, 100);

                await _logger.WriteInfoAsync
                (
                    "BlockIndexingJob",
                    "RunAsync",
                    indexerId,
                    $"Indexing completed for block-{currentBlockNumber}, Vector:{iterationVector}, transaction count - {transactionCount}",
                    DateTime.UtcNow
                );

                var indexed         = currentBlockNumber;
                currentBlockNumber += iterationVector;

                Sender.Tell(Messages.Common.CreateIndexedBlockNumberMessage(indexerId, indexed, currentBlockNumber));
            });
        }
        private BlockContent FindBlockContentByBlockHeader(List <BlockContent> blockContents, BlockHeader blockHeader)
        {
            BlockContent blockContent = null;

            foreach (var currentBlockContent in blockContents)
            {
                if (currentBlockContent.DataGraphIri.Equals(blockHeader.DataGraphIri))
                {
                    blockContent = currentBlockContent;
                }
            }
            if (blockContent == null)
            {
                String msg = String.Format("Unable to find matching block content for the data graph IRI '{0}'.", blockHeader.DataGraphIri);
                throw new CreatingBlockException(msg);
            }
            return(blockContent);
        }
Beispiel #27
0
        private void ValidateNextBlockInvalidDifficulty()
        {
            _blockChain.Append(_validNext);

            Block <DumbAction> invalidDifficultyBlock = new BlockContent <DumbAction>
            {
                Index           = 2,
                Difficulty      = 1,
                TotalDifficulty = _validNext.TotalDifficulty,
                PublicKey       = _fx.Miner.PublicKey,
                PreviousHash    = _validNext.Hash,
                Timestamp       = _validNext.Timestamp.AddDays(1),
                Transactions    = _emptyTransaction,
            }.Mine(_fx.GetHashAlgorithm(2)).Evaluate(_fx.Miner, _blockChain);

            Assert.Throws <InvalidBlockDifficultyException>(() =>
                                                            _blockChain.Append(invalidDifficultyBlock));
        }
Beispiel #28
0
        private void ValidateNextBlockInvalidTimestamp()
        {
            _blockChain.Append(_validNext);

            long difficulty = _policy.GetNextBlockDifficulty(_blockChain);
            Block <DumbAction> invalidPreviousTimestamp = new BlockContent <DumbAction>
            {
                Index           = 2,
                Difficulty      = difficulty,
                TotalDifficulty = _validNext.TotalDifficulty + difficulty,
                PublicKey       = _fx.Miner.PublicKey,
                PreviousHash    = _validNext.Hash,
                Timestamp       = _validNext.Timestamp.AddSeconds(-1),
                Transactions    = _emptyTransaction,
            }.Mine(_fx.GetHashAlgorithm(2)).Evaluate(_fx.Miner, _blockChain);

            Assert.Throws <InvalidBlockTimestampException>(() =>
                                                           _blockChain.Append(invalidPreviousTimestamp));
        }
Beispiel #29
0
        private void ValidateNextBlockInvalidPreviousHash()
        {
            _blockChain.Append(_validNext);

            long difficulty = _policy.GetNextBlockDifficulty(_blockChain);
            Block <DumbAction> invalidPreviousHashBlock = new BlockContent <DumbAction>
            {
                Index           = 2,
                Difficulty      = difficulty,
                TotalDifficulty = _validNext.TotalDifficulty + difficulty,
                PublicKey       = _fx.Miner.PublicKey,
                // Wrong PreviousHash for test; it should be _validNext.Hash:
                PreviousHash = _validNext.PreviousHash,
                Timestamp    = _validNext.Timestamp.AddDays(1),
                Transactions = _emptyTransaction,
            }.Mine(_fx.GetHashAlgorithm(2)).Evaluate(_fx.Miner, _blockChain);

            Assert.Throws <InvalidBlockPreviousHashException>(() =>
                                                              _blockChain.Append(invalidPreviousHashBlock));
        }
Beispiel #30
0
        public Block GetBlockByIri(string blockIri)
        {
            try
            {
                HashSet <Triple> blockHeaderTriples = _repository.GetBlockHeaderByIri(blockIri);
                if (!blockHeaderTriples.Any())
                {
                    string msg = String.Format("Block with IRI '{0}' was not found.", blockIri);
                    throw new BlockNotFoundException(msg);
                }
                BlockHeader      blockHeader         = CreateBlockHeaderFromTriples(blockHeaderTriples);
                HashSet <Triple> blockContentTriples = _repository.GetGraphByIri(blockHeader.DataGraphIri);
                BlockContent     blockContent        = new BlockContent(blockHeader.DataGraphIri, blockContentTriples);

                return(new Block(blockIri, blockHeader, blockContent));
            }
            catch (ObtainingBlockHeaderException ex)
            {
                throw new ReadingBlockException("Exception was thrown while creating block header from triples.", ex);
            }
        }
Beispiel #31
0
        public override void DontCheckPreEvaluationHashWithProtocolVersion0()
        {
            // Since PreEvaluationHash comparison between the actual and the expected was not
            // implemented in ProtocolVersion == 0, we need to maintain this bug on
            // ProtocolVersion < 1 for backward compatibility:
            BlockContent <Arithmetic> contentPv0 = _contents.Block1.Copy();

            contentPv0.ProtocolVersion = 0;
            contentPv0.PublicKey       = null;
            contentPv0.Timestamp      += TimeSpan.FromSeconds(1);
            var preEvalBlockPv0 = new PreEvaluationBlock <Arithmetic>(
                contentPv0,
                hashAlgorithm: _sha256,
                nonce: _validBlock1Proof.Nonce,
                preEvaluationHash: _validBlock1Proof.PreEvaluationHash
                );

            AssertBlockContentsEqual(contentPv0, preEvalBlockPv0);
            AssertBytesEqual(_validBlock1Proof.Nonce, preEvalBlockPv0.Nonce);
            Assert.Same(_sha256, preEvalBlockPv0.HashAlgorithm);
            AssertBytesEqual(
                _validBlock1Proof.PreEvaluationHash,
                preEvalBlockPv0.PreEvaluationHash
                );

            // However, such bug must be fixed after ProtocolVersion > 0:
            BlockContent <Arithmetic> contentPv1 = _contents.Block1.Copy();

            contentPv1.PublicKey  = null;
            contentPv1.Timestamp += TimeSpan.FromSeconds(1);
            Assert.Throws <InvalidBlockPreEvaluationHashException>(() =>
                                                                   new PreEvaluationBlock <Arithmetic>(
                                                                       contentPv1,
                                                                       hashAlgorithm: _sha256,
                                                                       nonce: _validBlock1Proof.Nonce,
                                                                       preEvaluationHash: _validBlock1Proof.PreEvaluationHash
                                                                       )
                                                                   );
        }
 public KnowedBlock(int myX, int myY, BlockContent myContent)
 {
     x = myX;
     y = myY;
     content = myContent;
 }
    /// <summary>
    /// 建立空的contentMap
    /// </summary>
    /// <returns>建立好的contentMap</returns>
    public BlockContent[,] buildEmptyMapContent()
    {
        BlockContent[,] result = new BlockContent[width, height];

        //建立空格子
        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                result[i, j] = new BlockContent(i,j);
            }
        }

        return result;
    }
    public void showContent() {
        
        myButtonContent = myMapManager.getCloneBtnContent(m_posX, m_posY);

        switch (myButtonContent.getType())
        {
            case BlockContent.Type.NUM:
                ComboBonusSystem.Instance.resetCombo();
                NumBlock myNumBlock = (NumBlock)myButtonContent;
                if (myNumBlock.getNumber() > 0)
                {
                    myText.text = "" + myNumBlock.getNumber();

                    myText.color = new Color(myNumBlock.getR(), myNumBlock.getG(), myNumBlock.getB());
                }
                break;
            case BlockContent.Type.MONSTER:
                
                MonsterBlock myMonsterBlock = (MonsterBlock)myButtonContent;
                myImage.sprite = Resources.Load("Textures/Character/monster_" + Protocol.Instance.getMonsterInfoByID(myMonsterBlock.getID()).getID(), typeof(Sprite)) as Sprite;

                switch (Protocol.Instance.getMonsterInfoByID(myMonsterBlock.getID()).getMonsterType())
                {
                    case Protocol.Type.FIRE:
                        myText.color = new Color(255, 0, 0);
                        break;
                    case Protocol.Type.GRASS:
                        myText.color = new Color(0, 255, 0);
                        break;
                    case Protocol.Type.WATER:
                        myText.color = new Color(0, 0, 255);
                        break;
                }
                break;
            case BlockContent.Type.TERRAIN:
                ComboBonusSystem.Instance.resetCombo();
                TerrainBlock myTerrainBlock = (TerrainBlock)myButtonContent;
                myImage.sprite = Resources.Load("Textures/UI/terrain_" + myTerrainBlock.getTextureID(), typeof(Sprite)) as Sprite;
                if (m_posX != Protocol.endPosX || m_posY != Protocol.endPosY)
                    MapManager.Instance.setCloneBtnState(m_posX, m_posY, MapManager.BlockState.PRESS_CLEAR);
                break;
        }
        Debug.Log("Press "+ myButtonContent.ToString());
        myButton.interactable = false;
    }
    public List<BlockContent> getAroundBlockByType(int x, int y, BlockContent.Type type) {
        List<BlockContent> result = new List<BlockContent>();

        if (x - 1 >= 0 && y - 1 >= 0 && contentMap[x - 1, y - 1].getType() == type)
        {
            result.Add(contentMap[x - 1, y - 1]); //左上
        }

        if (y - 1 >= 0 && contentMap[x, y - 1].getType() == type)
        {
            result.Add(contentMap[x, y - 1]);//上
        }

        if (x + 1 < width && y - 1 >= 0 && contentMap[x + 1, y - 1].getType() == type)
        {
            result.Add(contentMap[x + 1, y - 1]);//右上
        }

        if (x - 1 >= 0 && contentMap[x - 1, y].getType() == type)
        {
            result.Add(contentMap[x - 1, y]);//左
        }

        if (x + 1 < width && contentMap[x + 1, y].getType() == type)
        {
            result.Add(contentMap[x + 1, y]);//右
        }

        if (x - 1 >= 0 && y + 1 < height && contentMap[x - 1, y + 1].getType() == type)
        {
            result.Add(contentMap[x - 1, y + 1]);//左下
        }

        if (y + 1 < height && contentMap[x, y + 1].getType() == type)
        {
            result.Add(contentMap[x, y + 1]);//下
        }

        if (x + 1 < width && y + 1 < height && contentMap[x + 1, y + 1].getType() == type)
        {
            result.Add(contentMap[x + 1, y + 1]);//右下
        }

        return result;
    }