Beispiel #1
0
 /// <summary>
 /// Get a prevoius Hash.
 /// </summary>
 /// <returns>Return with a last block's hash.</returns>
 private string GetPreviousHash()
 => Chain.GetBlockchain().Last().Hash;
        //TODO Überprüfung einfügen, ob Chain eingefügt werden soll oder nicht (Collision Management)
        //TODO Rückgabewert auf Chain ändern, und alle Blocks zurück geben, die gelöscht werden
        public List <Block> Add(Chain chain)
        {
            List <Block> ret = new List <Block>();

            //If chain is currently empty, set Blockhead to inserted chain's Blockhead and return true
            if (Blockhead == null)
            {
                Blockhead = chain.Blockhead;
                return(ret);
            }

            if (chain.Blockhead.Index <= Blockhead.Index)
            {
                return(ret);
            }

            //Get first block in chain
            var firstBlock = chain.Blockhead;

            while (firstBlock.PreviousBlock != null)
            {
                firstBlock = firstBlock.PreviousBlock;
            }

            //Add chain directly if hashes and indexes match to Blockhead
            if ((firstBlock.PreviousHash == Blockhead.Hash && firstBlock.Index == Blockhead.Index + 1))
            {
                firstBlock.PreviousBlock = Blockhead;
                Blockhead = chain.Blockhead;

                return(ret);
            }
            else
            {
                //Search matching block if the chain replaces previous blocks
                var referenceBlock = Blockhead;

                while (referenceBlock != null &&
                       firstBlock.PreviousHash != referenceBlock.Hash &&
                       firstBlock.Index >= referenceBlock.Index)
                {
                    ret.Add(referenceBlock);
                    referenceBlock = referenceBlock.PreviousBlock;
                }

                //Attach chain at correct position if possible
                if (referenceBlock != null &&
                    firstBlock.PreviousHash == referenceBlock.Hash &&
                    firstBlock.Index == referenceBlock.Index + 1)
                {
                    firstBlock.PreviousBlock = referenceBlock;
                    firstBlock.ValidateSequence();
                    Blockhead = chain.Blockhead;

                    return(ret);
                }
            }

            //If no matching position is found in the blockchain, return false
            return(new List <Block>());
        }