public byte[] Serialize()
        {
            byte[] command = null;

            try
            {
                command = System.Text.Encoding.ASCII.GetBytes(GetCommand());
            }
            catch (EncoderFallbackException)
            {
                // Probably contains non-ASCII characters
            }

            if (command == null || command.Length > CommandSize)
            {
                throw new Exception($"{nameof(GetCommand)} should return an ASCII string containing a maximum of {CommandSize} characters");
            }


            var payload  = GetPayload() ?? new byte[] { };
            var checksum = DoubleSHA256.ComputeChecksum(payload);

            return(Magic
                   .Concat(command)
                   .Concat(Enumerable.Repeat((byte)0, CommandSize - command.Length))
                   .Concat(payload.Length)
                   .Concat(checksum)
                   .Concat(payload)
                   .ToArray());
        }
Esempio n. 2
0
        //  Returns null if the checksum is invalid
        private static byte[] VerifyAndRemoveCheckSum(byte[] data)
        {
            var result          = data.Take(data.Length - DoubleSHA256.ChecksumSize).ToArray();
            var givenCheckSum   = data.Skip(data.Length - DoubleSHA256.ChecksumSize).Take(DoubleSHA256.ChecksumSize).ToArray();
            var correctCheckSum = DoubleSHA256.ComputeChecksum(result);  // TODO: Use a new VerifyChecksum method

            return(givenCheckSum.SequenceEqual(correctCheckSum) ? result : null);
        }
        static Base58CheckTests()
        {
            testValue        = Utils.HexStringToBytes("000111D38E5FC9071FFCD20B4A763CC9AE4F252BB4E48FD66A835E252ADA93FF480D6DD43DC62A641155A5"); // Should match the base58 alphabet when encoded
            testValueEncoded = Base58Check.Alphabet;

            var testValueChecksum = DoubleSHA256.ComputeChecksum(testValue);

            testValueWithChecksumEncoded = Base58Check.EncodePlain(testValue.Concat(testValueChecksum).ToArray());
        }
        public void CalculateDoubleSHA256Hash1()
        {
            var inputString = "hello";
            var hashString  = "9595c9df90075148eb06860365df33584b75bff782a510c6cd4883a419833d50";

            var input = inputString.ToByteArray();

            var hashProvider = new DoubleSHA256();
            var computedHash = hashProvider.ComputeHash(input);

            Assert.AreEqual(hashString, computedHash.ToHexString());
        }
        public void CalculateDoubleSHA256Hash()
        {
            var inputString = "02000000019b69251560ea1143de610b3c6630dcf94e12000ceba7d40b136bfb67f5a9e4eb000000006b483045022100a52f6c484072528334ac4aa5605a3f440c47383e01bc94e9eec043d5ad7e2c8002206439555804f22c053b89390958083730d6a66c1b711f6b8669a025dbbf5575bd012103abc7f1683755e94afe899029a8acde1480716385b37d4369ba1bed0a2eb3a0c5feffffff022864f203000000001976a914a2420e28fbf9b3bd34330ebf5ffa544734d2bfc788acb1103955000000001976a9149049b676cf05040103135c7342bcc713a816700688ac3bc50700".ToLowerInvariant();
            var hashString  = "74d350ca44c324f4643274b98801f9a023b2b8b72e8e895879fd9070a68f7f1f";

            var input = inputString.TransactionHexToByteArray();

            var hashProvider = new DoubleSHA256();
            var computedHash = hashProvider.ComputeHash(input);

            Assert.AreEqual(hashString, computedHash.ToHexTransactionId());
        }
Esempio n. 6
0
        public static AlertMessage Parse(byte[] payload)
        {
            // Compute checksum
            var checksum = DoubleSHA256.ComputeChecksum(payload);


            // Parse
            var reader = new PayloadReader(payload);

            var alertSize = reader.ReadVarInt();

            var alertFormatVersion = reader.ReadInt32();
            var relayUntil         = reader.ReadDateTimeOffset(longer: true);
            var expiration         = reader.ReadDateTimeOffset(longer: true);
            var alertID            = reader.ReadInt32();

            var cancel0  = reader.ReadInt32();
            var nCancel  = reader.ReadVarInt() + 1;
            var toCancel = new Int32[nCancel];

            toCancel[0] = cancel0;

            for (ulong i = 1; i < nCancel; i++)
            {
                toCancel[i] = reader.ReadInt32();
            }

            var minVersion = reader.ReadInt32();
            var maxVersion = reader.ReadInt32();

            var nSubVersions = reader.ReadVarInt();
            var subVersions  = new string[nSubVersions];

            for (ulong j = 0; j < nSubVersions; j++)
            {
                subVersions[j] = reader.ReadString();
            }

            var priority  = reader.ReadInt32();
            var comment   = reader.ReadString();
            var statusBar = reader.ReadString();
            var reserved  = reader.ReadString();

            var signature = reader.ReadArray(72);

            reader.ThrowIfNotEndReached();

            // Return
            return(new AlertMessage {
                IsFinalAlert = checksum.SequenceEqual(FinalAlertHash),
                StatusBar = statusBar
            });
        }
Esempio n. 7
0
        private static byte[] AddCheckSum(byte[] data)
        {
            var checkSum = DoubleSHA256.ComputeChecksum(data);

            return(data.Concat(checkSum).ToArray());
        }
        public static async Task <Message> ReadMessageAsync(Stream stream)
        {
            var header = new byte[HeaderSize];
            int offset = 0, nRead;

            // Read leading magic bytes
            nRead = await stream.ReadAsync(header, offset, MagicSize).ConfigureAwait(false);

            if (nRead < Magic.Length)
            {
                throw new EndOfStreamException();
            }

            offset += nRead;


            // Check magic bytes
            if (!Magic.SequenceEqual(header.Take(MagicSize)))
            {
                throw new Exception("Leading magic bytes are incorrect");
            }


            // Read message type
            nRead = await stream.ReadAsync(header, offset, CommandSize).ConfigureAwait(false);

            offset += nRead;

            string command;

            try
            {
                command = System.Text.Encoding.ASCII.GetString(header, CommandIndex, nRead).TrimEnd('\0');
            }
            catch (DecoderFallbackException exception)
            {
                throw new Exception($"Failed to decode message type as ASCII string", exception);
            }

            if (nRead < CommandSize)
            {
                throw new EndOfStreamException();
            }


            // Read payload length
            nRead = await stream.ReadAsync(header, offset, sizeof(UInt32)).ConfigureAwait(false);

            var payloadLength = BitConverter.ToUInt32(header, PayloadLengthIndex);  // TODO: Take system's endianness in consideration

            if (nRead < sizeof(UInt32))
            {
                throw new EndOfStreamException();
            }

            offset += sizeof(UInt32);
            Debug.Assert(offset == HeaderSize - DoubleSHA256.ChecksumSize);


            // Read checksum
            nRead = await stream.ReadAsync(header, offset, DoubleSHA256.ChecksumSize).ConfigureAwait(false);

            if (nRead < DoubleSHA256.ChecksumSize)
            {
                throw new EndOfStreamException();
            }

            offset += DoubleSHA256.ChecksumSize;
            Debug.Assert(offset == HeaderSize);


            // Read payload
            var payload = new byte[payloadLength];

            nRead = await stream.ReadAsync(payload, 0, Convert.ToInt32(payloadLength)).ConfigureAwait(false);

            if (nRead < payloadLength)
            {
                throw new EndOfStreamException();
            }


            // Check checksum
            var checksum = DoubleSHA256.ComputeChecksum(payload);

            if (!header.Skip(ChecksumIndex).Take(DoubleSHA256.ChecksumSize).SequenceEqual(checksum))
            {
                throw new Exception("Checksum error");
            }


            // Parse
            return(ParseMessage(command, payload));
        }