Beispiel #1
0
        internal RawBlock ToRawBlock(
            bool includeHash,
            bool includeTransactionData
            )
        {
            IEnumerable transactions =
                Transactions.Select(
                    tx => includeTransactionData ?
                    tx.ToRawTransaction(true) as object :
                    tx.Id.ToByteArray() as object
                    );
            var rawBlock = new RawBlock(
                index: Index,
                timestamp: Timestamp.ToString(TimestampFormat),
                nonce: Nonce.ToByteArray(),
                miner: Miner?.ToByteArray(),
                difficulty: Difficulty,
                transactions: transactions,
                previousHash: PreviousHash?.ToByteArray()
                );

            if (includeHash)
            {
                rawBlock = rawBlock.AddHash(Hash.ToByteArray());
            }

            return(rawBlock);
        }
Beispiel #2
0
        internal BlockHeader GetBlockHeader()
        {
            string timestampAsString = Timestamp.ToString(
                BlockHeader.TimestampFormat,
                CultureInfo.InvariantCulture
                );
            ImmutableArray <byte> previousHashAsArray =
                PreviousHash?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty;
            ImmutableArray <byte> actionsHashAsArray =
                EvaluationDigest?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty;

            if (PreviousHash.Equals(EvaluationDigest))
            {
                Console.WriteLine();
            }

            // FIXME: When hash is not assigned, should throw an exception.
            return(new BlockHeader(
                       index: Index,
                       timestamp: timestampAsString,
                       nonce: Nonce.ToByteArray().ToImmutableArray(),
                       miner: Miner?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty,
                       difficulty: Difficulty,
                       totalDifficulty: TotalDifficulty,
                       previousHash: previousHashAsArray,
                       txHash: TxHash?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty,
                       hash: Hash.ToByteArray().ToImmutableArray(),
                       preEvaluationHash: PreEvaluationHash.ToByteArray().ToImmutableArray(),
                       evaluationDigest: actionsHashAsArray
                       ));
        }
Beispiel #3
0
        /// <summary>
        /// Gets <see cref="Bencodex.Types.Dictionary"/> representation of
        /// <see cref="BlockHeader"/>.
        /// </summary>
        /// <returns><see cref="Bencodex.Types.Dictionary"/> representation of
        /// <see cref="BlockHeader"/>.</returns>
        public Bencodex.Types.Dictionary ToBencodex()
        {
            var dict = Bencodex.Types.Dictionary.Empty
                       .Add(IndexKey, Index)
                       .Add(TimestampKey, Timestamp)
                       .Add(DifficultyKey, Difficulty)
                       .Add(TotalDifficultyKey, (IValue)(Bencodex.Types.Integer)TotalDifficulty)
                       .Add(NonceKey, Nonce.ToArray())
                       .Add(HashKey, Hash.ToArray());

            if (Miner.Any())
            {
                dict = dict.Add(MinerKey, Miner.ToArray());
            }

            if (PreviousHash.Any())
            {
                dict = dict.Add(PreviousHashKey, PreviousHash.ToArray());
            }

            if (TxHash.Any())
            {
                dict = dict.Add(TxHashKey, TxHash.ToArray());
            }

            return(dict);
        }
Beispiel #4
0
        internal RawBlock ToRawBlock(
            bool includeHash,
            bool includeTransactionData
            )
        {
            IEnumerable <byte[]> transactions =
                Transactions.OrderBy(tx => tx.Id).Select(
                    tx => includeTransactionData
                        ? tx.Serialize(true)
                        : tx.Id.ToByteArray()
                    );
            var rawBlock = new RawBlock(
                index: Index,
                timestamp: Timestamp.ToString(TimestampFormat, CultureInfo.InvariantCulture),
                nonce: Nonce.ToByteArray(),
                miner: Miner?.ToByteArray(),
                difficulty: Difficulty,
                transactions: transactions,
                previousHash: PreviousHash?.ToByteArray()
                );

            if (includeHash)
            {
                rawBlock = rawBlock.AddHash(Hash.ToByteArray());
            }

            return(rawBlock);
        }
Beispiel #5
0
 public override string ToString()
 {
     return($"Hash     :{BitConverter.ToString(Hash.ToArray()).Replace("-", "")}\n" +
            $"Pre Hash :{BitConverter.ToString(PreviousHash.ToArray()).Replace("-", "")}\n" +
            $"Nonce    :{Nonce}\n" +
            $"Timestamp:{Timestamp:yyyy/MM/dd HH:mm:ss.fff}\n\r");
 }
Beispiel #6
0
        public bool Equals(Block other)
        {
            bool isEqual = Timestamp == other.Timestamp &&
                           PreviousHash.SequenceEqual(other.PreviousHash) &&
                           Hash.SequenceEqual(other.Hash) &&
                           Data.SequenceEqual(other.Data);

            return(isEqual);
        }
Beispiel #7
0
        public byte[] GetBlockData()
        {
            string data = Number.ToString();

            data += Nonce.ToString();
            data += PreviousHash?.ToString();
            data += Data?.ToString();

            return(Encoding.ASCII.GetBytes(data));
        }
Beispiel #8
0
        public bool HasValidPreviousHash(IAuthDataBlock previousAuthDataBlock)
        {
            if (previousAuthDataBlock == null)
            {
                throw new ArgumentNullException(nameof(previousAuthDataBlock));
            }

            var previousBlockHash = previousAuthDataBlock.GenerateHash();

            return(previousAuthDataBlock.HasValidHash() && PreviousHash.SequenceEqual(previousBlockHash));
        }
Beispiel #9
0
        public override int GetHashCode()
        {
            unchecked
            {
                int hash = 17;

                hash = hash * 23 + Index;
                hash = hash * 23 + PreviousHash?.GetHashCode() ?? 0;
                hash = hash * 23 + Timestamp.GetHashCode();
                hash = hash * 23 + Data?.GetHashCode() ?? 0;
                hash = hash * 23 + Hash?.GetHashCode() ?? 0;

                return(hash);
            }
        }
Beispiel #10
0
        internal BlockHeader GetBlockHeader()
        {
            // FIXME: When hash is not assigned, should throw an exception.
            return(new BlockHeader(
                       index: Index,
                       timestamp: Timestamp.ToString(TimestampFormat, CultureInfo.InvariantCulture),
                       nonce: Nonce.ToByteArray().ToImmutableArray(),
                       miner: Miner?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty,
                       difficulty: Difficulty,
#pragma warning disable MEN002 // line is too long
                       previousHash: PreviousHash?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty,
#pragma warning restore MEN002 // line is too long
                       txHash: TxHash?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty,
                       hash: Hash.ToByteArray().ToImmutableArray()
                       ));
        }
Beispiel #11
0
        public List <byte> GenerateHash()
        {
            var sha256 = new SHA256Managed();

            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                {
                    writer.Write(Data.ToBytesArray());
                    writer.Write(Nonce);
                    writer.Write(Timestamp.ToBinary());
                    writer.Write(PreviousHash.ToArray());
                    var streamArray = stream.ToArray();
                    return(sha256.ComputeHash(streamArray).ToList());
                }
            }
        }
Beispiel #12
0
 public bool AddTransaction(Transaction transaction)
 {
     if (transaction == null)
     {
         return(false);
     }
     if (!PreviousHash.Equals(NoobChaiN.FirstBlockHash))
     {
         if (!transaction.Process())
         {
             Console.WriteLine("Wrong Transaction Aborted!");
             return(false);
         }
     }
     Transactions.Add(transaction);
     return(true);
 }
Beispiel #13
0
        public bool IsValid(bool verbose = false)
        {
            BlockRepository blockRepo = new BlockRepository();

            List <Block> blocks = blockRepo.Get();

            int index = blocks.FindIndex(x => x.Id == Id);

            if (index != 0)
            {
                if (!PreviousHash.Equals(blocks[index - 1].Hash))
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #14
0
        internal BlockHeader GetBlockHeader()
        {
            string timestampAsString = Timestamp.ToString(
                BlockHeader.TimestampFormat,
                CultureInfo.InvariantCulture
                );
            ImmutableArray <byte> previousHashAsArray =
                PreviousHash?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty;

            // FIXME: When hash is not assigned, should throw an exception.
            return(new BlockHeader(
                       index: Index,
                       timestamp: timestampAsString,
                       nonce: Nonce.ToByteArray().ToImmutableArray(),
                       miner: Miner?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty,
                       difficulty: Difficulty,
                       previousHash: previousHashAsArray,
                       txHash: TxHash?.ToByteArray().ToImmutableArray() ?? ImmutableArray <byte> .Empty,
                       hash: Hash.ToByteArray().ToImmutableArray()
                       ));
        }
        public byte[] GetBytes()
        {
            using (MemoryStream headerStream = new MemoryStream(), dataStream = new MemoryStream())
            {
                BinaryWriter headerBaos = new BinaryWriter(headerStream);
                BinaryWriter dataBaos   = new BinaryWriter(dataStream);

                try
                {
                    // Version
                    headerBaos.Write(ByteUtils.ShortToBytes(_version));

                    // Id
                    int len = Id.GetLengthOrZero();
                    headerBaos.Write((byte)(len & 0xff));
                    if (len > 0)
                    {
                        dataBaos.Write(Id.GetBytesOrEmptyArray());
                    }

                    // Tag
                    len = Tag.GetLengthOrZero();
                    headerBaos.Write(ByteUtils.ShortToBytes((short)(len & 0xffff)));
                    if (len > 0)
                    {
                        dataBaos.Write(Tag.GetBytesOrEmptyArray());
                    }

                    // GroupId
                    len = GroupId.GetLengthOrZero();
                    headerBaos.Write((byte)(len & 0xff));
                    if (len > 0)
                    {
                        dataBaos.Write(GroupId.GetBytesOrEmptyArray());
                    }

                    // SequenceNumber
                    if (SequenceNumber == 0)
                    {
                        headerBaos.Write((byte)0);
                    }
                    else
                    {
                        headerBaos.Write((byte)4);
                        dataBaos.Write(ByteUtils.IntegerToBytes(SequenceNumber));
                    }

                    // SequenceTotal
                    if (SequenceTotal == 0)
                    {
                        headerBaos.Write((byte)0);
                    }
                    else
                    {
                        headerBaos.Write((byte)4);
                        dataBaos.Write(ByteUtils.IntegerToBytes(SequenceTotal));
                    }

                    // Priority
                    if (Priority == 0)
                    {
                        headerBaos.Write((byte)0);
                    }
                    else
                    {
                        headerBaos.Write((byte)1);
                        dataBaos.Write(Priority);
                    }

                    //Timestamp
                    if (Timestamp == 0)
                    {
                        headerBaos.Write((byte)0);
                    }
                    else
                    {
                        headerBaos.Write((byte)8);
                        dataBaos.Write(ByteUtils.LongToBytes(Timestamp));
                    }

                    // Publisher
                    len = Publisher.GetLengthOrZero();
                    headerBaos.Write((byte)(len & 0xff));
                    if (len > 0)
                    {
                        dataBaos.Write(Publisher.GetBytesOrEmptyArray());
                    }

                    // AuthId
                    len = AuthId.GetLengthOrZero();
                    headerBaos.Write(ByteUtils.ShortToBytes((short)(len & 0xffff)));
                    if (len > 0)
                    {
                        dataBaos.Write(AuthId.GetBytesOrEmptyArray());
                    }

                    // AuthGroup
                    len = AuthGroup.GetLengthOrZero();
                    headerBaos.Write(ByteUtils.ShortToBytes((short)(len & 0xffff)));
                    if (len > 0)
                    {
                        dataBaos.Write(AuthGroup.GetBytesOrEmptyArray());
                    }

                    // ChainPosition
                    if (ChainPosition == 0)
                    {
                        headerBaos.Write((byte)0);
                    }
                    else
                    {
                        headerBaos.Write((byte)8);
                        dataBaos.Write(ByteUtils.LongToBytes(ChainPosition));
                    }

                    // Hash
                    len = Hash.GetLengthOrZero();
                    headerBaos.Write(ByteUtils.ShortToBytes((short)(len & 0xffff)));
                    if (len > 0)
                    {
                        dataBaos.Write(Hash.GetBytesOrEmptyArray());
                    }

                    // PreviousHash
                    len = PreviousHash.GetLengthOrZero();
                    headerBaos.Write(ByteUtils.ShortToBytes((short)(len & 0xffff)));
                    if (len > 0)
                    {
                        dataBaos.Write(PreviousHash.GetBytesOrEmptyArray());
                    }

                    // Nonce
                    len = Nonce.GetLengthOrZero();
                    headerBaos.Write(ByteUtils.ShortToBytes((short)(len & 0xffff)));
                    if (len > 0)
                    {
                        dataBaos.Write(Nonce.GetBytesOrEmptyArray());
                    }

                    // DifficultyTarget
                    if (DifficultyTarget == 0)
                    {
                        headerBaos.Write((byte)0);
                    }
                    else
                    {
                        headerBaos.Write((byte)4);
                        dataBaos.Write(ByteUtils.IntegerToBytes(DifficultyTarget));
                    }

                    // InfoType
                    len = InfoType.GetLengthOrZero();
                    headerBaos.Write((byte)(len & 0xff));
                    if (len > 0)
                    {
                        dataBaos.Write(InfoType.GetBytesOrEmptyArray());
                    }

                    // InfoFormat
                    len = InfoFormat.GetLengthOrZero();
                    headerBaos.Write((byte)(len & 0xff));
                    if (len > 0)
                    {
                        dataBaos.Write(InfoFormat.GetBytesOrEmptyArray());
                    }

                    // ContextData
                    if (ContextData == null)
                    {
                        headerBaos.Write((byte)0);
                    }
                    else
                    {
                        headerBaos.Write(ByteUtils.IntegerToBytes(ContextData.Length));
                        dataBaos.Write(ContextData, 0, ContextData.Length);
                    }

                    // ContentData
                    if (ContentData == null)
                    {
                        headerBaos.Write(ByteUtils.IntegerToBytes(0));
                    }
                    else
                    {
                        headerBaos.Write(ByteUtils.IntegerToBytes(ContentData.Length));
                        dataBaos.Write(ContentData, 0, ContentData.Length);
                    }

                    var headerBytes = headerStream.ToArray();
                    var dataBytes   = dataStream.ToArray();

                    var result = new byte[headerBytes.Length + dataBytes.Length];
                    Array.Copy(headerBytes, 0, result, 0, headerBytes.Length);
                    Array.Copy(dataBytes, 0, result, headerBytes.Length, dataBytes.Length);

                    return(result);
                }
                catch (Exception)
                {
                    //TODO: log
                }
                finally
                {
                    try
                    {
                        headerBaos.Dispose();
                        dataBaos.Dispose();
                    }
                    catch (Exception)
                    {
                        // TODO: log("Error when closing byte arrays streams");
                    }
                }
            }

            return(new byte[0]);
        }
Beispiel #16
0
 public override int GetHashCode()
 {
     return(Index.GetHashCode() ^
            PreviousHash?.GetHashCode() ?? 0 ^
            Digest.GetHashCode());
 }
 public override int GetHashCode()
 {
     return(DataGraphIri.GetHashCode() + DataHash.GetHashCode() + Hash.GetHashCode() + Index.GetHashCode() + PreviousBlock.GetHashCode() + PreviousHash.GetHashCode() + Timestamp.GetHashCode());
 }
Beispiel #18
0
 public object Clone()
 {
     return(new Block(new DateTime(Timestamp.Ticks), PreviousHash.Clone() as byte[], Hash.Clone() as byte[], Data.Clone() as byte[], Difficulty, Nonce.Clone() as byte[]));
 }