// Serializes an object to a byte array
        private byte[] SerializeObjectAsBinary(object Value)
        {
            // Create an output array
            byte[] Output = new byte[0];

            // Object is an integer
            if (Value.GetType().GetInterfaces().Contains(typeof(IConvertible)))
            {
                // Integer is 8 bit
                if (Value.GetType() == typeof(byte) || Value.GetType() == typeof(sbyte))
                {
                    Output = Encoding.AppendToByteArray(Encoding.IntegerToByteArray(Convert.ToByte(Value)), Output);
                }

                // Integer is 16 bit
                else if (Value.GetType() == typeof(ushort) || Value.GetType() == typeof(short))
                {
                    Output = Encoding.AppendToByteArray(Encoding.IntegerToByteArray(Convert.ToUInt16(Value)), Output);
                }

                // Integer is 32 bit
                else if (Value.GetType() == typeof(uint) || Value.GetType() == typeof(int))
                {
                    Output = Encoding.AppendToByteArray(Encoding.IntegerToByteArray(Convert.ToUInt32(Value)), Output);
                }

                // Integer is 64 bit
                else if (Value.GetType() == typeof(ulong) || Value.GetType() == typeof(long))
                {
                    Output = Encoding.AppendToByteArray(Encoding.IntegerToByteArray(Convert.ToUInt64(Value)), Output);
                }
            }

            // Object is a string
            else if (Value.GetType() == typeof(string))
            {
                Output = Encoding.AppendToByteArray(SerializeVarInt(((string)Value).Length), Output);
                Output = Encoding.AppendToByteArray(Encoding.StringToByteArray((string)Value), Output);
            }

            // Object is an array
            else if (Value.GetType().IsArray)
            {
                Output = Encoding.AppendToByteArray(SerializeArrayAsBinary((Array)Value), Output);
            }

            // Property is an object
            else
            {
                // Get property list of type
                var Properties = Value.GetType().GetProperties();
                foreach (var Property in Properties)
                {
                    Output = Encoding.AppendToByteArray(SerializeObjectAsBinary(Property.GetValue(Value)), Output);
                }
            }

            // Return output array
            return(Output);
        }
        // Serializes entry table to a byte array
        public byte[] Serialize(bool IncludeHeader = true)
        {
            // Create an output array
            byte[] Output = new byte[0];

            // Write header
            if (IncludeHeader)
            {
                // Add signatures
                Output = Encoding.AppendToByteArray(Encoding.IntegerToByteArray(GlobalsConfig.STORAGE_SIGNATUREA), Output);
                Output = Encoding.AppendToByteArray(Encoding.IntegerToByteArray(GlobalsConfig.STORAGE_SIGNATUREB), Output);

                // Add version number
                Output = Encoding.AppendToByteArray(GlobalsConfig.STORAGE_FORMAT_VERSION, Output);
            }

            // Add array length
            Output = Encoding.AppendToByteArray(SerializeVarInt(Entries.Count), Output);

            // Iterate over objects
            foreach (KeyValuePair <string, object> Entry in Entries)
            {
                // Serialize object
                byte[] EntryBytes = SerializeEntry(Entry.Key, Entry.Value);

                // Add to output array
                Output = Encoding.AppendToByteArray(EntryBytes, Output);
            }

            // Return output array
            return(Output);
        }
        // Serializes an array to a byte array
        private byte[] SerializeArrayAsBinary(Array Value)
        {
            // Verify array is valid
            if (Value == null)
            {
                return(new byte[0]);
            }
            else if (!Value.GetType().IsArray)
            {
                return(new byte[0]);
            }

            // Create an output array
            byte[] Output = new byte[0];

            // Loop through all array entries
            for (int i = 0; i < Value.Length; i++)
            {
                // Encode object
                byte[] Buffer = SerializeObjectAsBinary(Value.GetValue(i));

                // Append to output array
                Output = Encoding.AppendToByteArray(Buffer, Output);
            }

            // Return output array
            return(Output);
        }
        // Adds a new entry as a raw hexstring representation of the object's raw bytes
        public bool AddEntryAsBinary(string Name, object Value)
        {
            // Verify entry is valid
            if (Value == null)
            {
                return(false);
            }

            // Create an output array
            byte[] Output = new byte[0];
            int    Size   = 0;

            if (Value.GetType().IsArray)
            {
                Type ArrayType = Value.GetType();
                foreach (object Val in (Value as Array))
                {
                    Size += Encoding.GetSizeOfObject(Val);
                }
            }
            else
            {
                Size = Encoding.GetSizeOfObject(Value);
            }
            Output = Encoding.AppendToByteArray(SerializeVarInt(Size), Output);

            // Serialize object
            Output = Encoding.AppendToByteArray(SerializeObjectAsBinary(Value), Output);

            // Add as an entry
            AddEntry(Name, Encoding.ByteArrayToString(Output));
            return(true);
        }
        // Generate a random string of letters and numbers
        public static string String(int Length = 64)
        {
            // Create a buffer
            byte[] Buffer = new byte[0];

            // Loop through and add random bytes until the string is of the desired length
            for (int i = 0; i < Length / 2; i++)
            {
                Buffer = Encoding.AppendToByteArray(Integer <byte>(), Buffer);
            }

            // Convert to a hex string
            string Output = Encoding.ByteArrayToHexString(Buffer);

            // Trim to correct size
            while (Output.Length < Length)
            {
                Output += Integer <byte>();
            }
            if (Output.Length > Length)
            {
                Output = Output.Substring(0, Length);
            }

            // Return output string
            return(Output);
        }
Beispiel #6
0
        // Adds checksum value
        public static byte[] AddCheckSum(byte[] Data)
        {
            // Get checksum of data
            byte[] CheckSum = GetCheckSum(Data);

            // Output input data with checksum appended to it
            return(Encoding.AppendToByteArray(CheckSum, Data));
        }
        // Serializes an entry to a byte array
        private byte[] SerializeEntry(string Name, object Value)
        {
            // Serialize name
            byte[] NameLength = new byte[] { (byte)Name.Length };
            byte[] NameBytes  = Encoding.StringToByteArray(Name);
            NameBytes = Encoding.AppendToByteArray(NameBytes, NameLength);

            // Serialize object
            byte[] ObjectBytes = SerializeObject(Value);

            // Return output array
            return(Encoding.AppendToByteArray(ObjectBytes, NameBytes));
        }
        // Serializes an array to a byte array
        private byte[] SerializeArray(Array Value)
        {
            // Create an output array
            byte[] Output = new byte[0];

            // Add array size
            Output = SerializeVarInt(Value.LongLength);

            // Loop through each array object
            for (int i = 0; i < Value.Length; i++)
            {
                // Read object
                object Child = Value.GetValue(i);

                // Add bytes
                Output = Encoding.AppendToByteArray(SerializeObject(Child), Output);
            }

            // Return output array
            return(Output);
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            // Parse commandline arguments
            if (args.Length >= 1)
            {
                Port = int.Parse(args[0]);
            }

            // Set log level and start logger
            Logger.LogLevel = Level.DEBUG;
            Logger.Start();

            // Add logger to server
            Server.Logger = Logger;

            // Bind event handlers
            Server.OnStart          = ServerStarted;
            Server.OnStop           = ServerStopped;
            Server.OnDataReceived  += DataReceived;
            Server.OnDataSent      += DataSent;
            Server.OnError         += ServerError;
            Server.OnPeerConnected += PeerConnected;

            // Start server
            Server.Start(Port);

            // Enter into a loop
            int MenuSelection = 0;

            while (MenuSelection != 4)
            {
                // Manually connect to a peer
                if (MenuSelection == 1)
                {
                    Logger.Log(Level.INFO, "Enter a URL:");
                    string Url = Console.ReadLine();
                    Logger.Log(Level.INFO, "Enter a port:");
                    int Port = int.Parse(Console.ReadLine());
                    Server.Connect(new Connection(Url, Port, ""));
                }

                // Broadcast a test packet
                else if (MenuSelection == 2)
                {
                    // Create a response
                    Handshake.Request Request = new Handshake.Request
                    {
                        NodeData = new NodeData()
                        {
                            NetworkId = GlobalsConfig.NETWORK_ID,
                            Version   = 1,
                            Port      = 8090,
                            LocalTime = GeneralUtilities.GetTimestamp(),
                            PeerId    = Server.PeerId
                        },
                        PayloadData = new CoreSyncData()
                        {
                            CurrentHeight = Globals.DAEMON_BLOCK_HEIGHT,
                            TopId         = Globals.DAEMON_TOP_ID
                        }
                    };

                    // Get body bytes
                    byte[] BodyBytes = Request.Serialize();

                    // Create a header
                    BucketHead2 Header = new BucketHead2
                    {
                        Signature        = GlobalsConfig.LEVIN_SIGNATURE,
                        ResponseRequired = false,
                        PayloadSize      = (ulong)BodyBytes.Length,
                        CommandCode      = (uint)Handshake.Id,
                        ProtocolVersion  = GlobalsConfig.LEVIN_VERSION,
                        Flags            = LevinProtocol.LEVIN_PACKET_RESPONSE,
                        ReturnCode       = LevinProtocol.LEVIN_RETCODE_SUCCESS
                    };

                    Logger?.Log(Level.DEBUG, "[OUT] Sending Handshake Request:");
                    Logger?.Log(Level.DEBUG, "- Node Data:");
                    Logger?.Log(Level.DEBUG, "  - Network ID: {0}", Encoding.StringToHexString(Request.NodeData.NetworkId));
                    Logger?.Log(Level.DEBUG, "  - Peer ID: {0}", Request.NodeData.PeerId);
                    Logger?.Log(Level.DEBUG, "  - Version: {0}", Request.NodeData.Version);
                    Logger?.Log(Level.DEBUG, "  - Local Time: {0}", Request.NodeData.LocalTime);
                    Logger?.Log(Level.DEBUG, "  - Port: {0}", Request.NodeData.Port);
                    Logger?.Log(Level.DEBUG, "- Core Sync Data:");
                    Logger?.Log(Level.DEBUG, "  - Current Height: {0}", Request.PayloadData.CurrentHeight);
                    Logger?.Log(Level.DEBUG, "  - Top ID: {0}", Encoding.StringToHexString(Request.PayloadData.TopId));

                    // Send notification
                    Server.Broadcast(Encoding.AppendToByteArray(BodyBytes, Header.Serialize()));
                }

                // Show peer list
                else if (MenuSelection == 3)
                {
                    Server.Prune();
                    string Peers = "";
                    List <PeerConnection> PeerList = Server.GetPeerList();
                    foreach (PeerConnection Peer in PeerList)
                    {
                        Peers += Peer.Address + " ";
                    }
                    Logger.Log(Level.DEBUG, "Peers:");
                    Logger.Log(Level.DEBUG, Peers);
                }

                // Write menu
                Logger.Log(Level.INFO, "Menu:");
                Logger.Log(Level.INFO, " 1\tConnect to a Server");
                Logger.Log(Level.INFO, " 2\tTest Packet");
                Logger.Log(Level.INFO, " 3\tShow Peer List");
                Logger.Log(Level.INFO, " 4\tExit");
                Logger.Log(Level.INFO, "Enter Selection:");

                // Get menu selection
                MenuSelection = int.Parse(Console.ReadLine());
            }

            // Close all connections
            Server.Close();

            // Close logger
            Logger.Stop();
        }
        // Decodes an object packed into a byte array
        private T DeserializeObjectFromBinary <T>(byte[] Data)
        {
            // Create an output object
            T Output = default(T);

            // Object is an integer
            if (typeof(T).GetInterfaces().Contains(typeof(IConvertible)))
            {
                // Create a generic method wrapper to access deserialization
                MethodInfo MethodInfo = typeof(Encoding).GetMethod("ByteArrayToInteger", new[] { typeof(byte[]), typeof(int) });
                Type[]     Args       = new Type[] { typeof(T) };
                MethodInfo Method     = MethodInfo.MakeGenericMethod(Args);

                // Deserialize integer
                Output = (T)Method.Invoke(null, new object[] { Data, 0 });
            }

            // Object is a string
            else if (typeof(T) == typeof(string))
            {
                // Deserialize string length
                int Length = DeserializeVarInt <int>(Data, 0, out int Offset);

                // Deserialize string
                Output = (T)Convert.ChangeType(Encoding.ByteArrayToString(Encoding.SplitByteArray(Data, Offset, Length)), typeof(T));
            }

            // Object is an array
            else if (typeof(T).IsArray)
            {
                // Create a generic method wrapper to access deserialization
                MethodInfo MethodInfo = typeof(PortableStorage).GetMethod("DeserializeArrayFromBinary");
                Type[]     Args       = new Type[] { typeof(T) };
                MethodInfo Method     = MethodInfo.MakeGenericMethod(Args);

                // Deserialize integer
                Output = (T)Method.Invoke(null, new object[] { Data });
            }

            // Property is an object
            else
            {
                // Get property list of type
                var Properties = typeof(T).GetProperties();

                // Create a buffer
                byte[] Buffer = Encoding.AppendToByteArray(Data, new byte[0]);

                // Loop through object properties
                foreach (PropertyInfo Property in Properties)
                {
                    // Create a generic method wrapper to access deserialization
                    MethodInfo MethodInfo = typeof(PortableStorage).GetMethod("DeserializeObjectFromBinary");
                    Type[]     Args       = new Type[] { Property.PropertyType };
                    MethodInfo Method     = MethodInfo.MakeGenericMethod(Args);

                    // Set object parameter value
                    var    Param = Method.Invoke(null, new object[] { Buffer });
                    object Temp  = Output;
                    Property.SetValue(Temp, Convert.ChangeType(Param, Property.PropertyType));
                    Output = (T)Convert.ChangeType(Temp, typeof(T));

                    // Resize buffer
                    Buffer = Encoding.SplitByteArray(Buffer, Encoding.GetSizeOfObject(Property.GetValue(Output)), Buffer.Length - Encoding.GetSizeOfObject(Property.GetValue(Output)));
                }
            }

            // Return output
            return(Output);
        }
        // Serializes an object to a byte array
        private byte[] SerializeObject(object Value, bool IncludeType = true)
        {
            // Create an output array
            byte[] Output = new byte[0];

            // Add object type
            SerializationType Type = GetType(Value);

            if (IncludeType)
            {
                Output = new byte[] { (byte)Type }
            }
            ;

            // Create entry bytes buffer
            byte[] EntryBytes = new byte[0];

            // Type is 64 bit
            if (Value.GetType() == typeof(long) || Value.GetType() == typeof(ulong))
            {
                // Encode bytes
                ulong Input = Convert.ToUInt64(Value);
                EntryBytes = Encoding.IntegerToByteArray(Input);
            }

            // Type is 32 bit
            else if (Value.GetType() == typeof(int) || Value.GetType() == typeof(uint))
            {
                // Encode bytes
                uint Input = Convert.ToUInt32(Value);
                EntryBytes = Encoding.IntegerToByteArray(Input);
            }

            // Type is 16 bit
            else if (Value.GetType() == typeof(short) || Value.GetType() == typeof(ushort))
            {
                // Encode bytes
                ushort Input = Convert.ToUInt16(Value);
                EntryBytes = Encoding.IntegerToByteArray(Input);
            }

            // Type is 8 bit
            else if (Value.GetType() == typeof(byte) || Value.GetType() == typeof(sbyte))
            {
                // Encode bytes
                byte Input = Convert.ToByte(Value);
                EntryBytes = Encoding.IntegerToByteArray(Input);
            }

            // Type is double
            else if (Value.GetType() == typeof(double))
            {
                // Encode bytes
                double Input = Convert.ToDouble(Value);
                EntryBytes = Encoding.IntegerToByteArray(Input);
            }

            // Type is string
            else if (Value.GetType() == typeof(string))
            {
                // Check string length
                if (((string)Value).Length > MAX_STRING_LENGTH)
                {
                    EntryBytes = new byte[0];
                }

                // Encode bytes
                EntryBytes = Encoding.StringToByteArray((string)Value);

                // Add string length
                EntryBytes = Encoding.AppendToByteArray(EntryBytes, SerializeVarInt(((string)Value).Length));
            }

            // Type is bool
            else if (Value.GetType() == typeof(bool))
            {
                // Encode bytes
                EntryBytes = new byte[1] {
                    (bool)Value ? (byte)1 : (byte)0
                };
            }

            // Type is array
            else if (Value.GetType().IsArray)
            {
                // Encode bytes
                EntryBytes = SerializeArray((Array)Value);
            }

            // Type is object
            else
            {
                // Check if object has serialization method
                Type       ObjectType = Value.GetType();
                MethodInfo Method     = ObjectType.GetMethod("Serialize");
                if (Method == null)
                {
                    throw new Exception("Could not serialize object: No Serialize() method found in object type " + ObjectType.Name);
                }

                // Encode bytes
                EntryBytes = (byte[])Method.Invoke(Value, null);
            }

            // Return result
            if (EntryBytes.Length > 0)
            {
                return(Encoding.AppendToByteArray(EntryBytes, Output));
            }
            else
            {
                return(new byte[0]);
            }
        }
Beispiel #12
0
        // Run daemon
        public void Start()
        {
            // Check if running
            if (!Running)
            {
                return;
            }

            /*
             *
             * This is basically all debugging still
             *
             */

            // Enter into a loop
            int MenuSelection = 0;

            while (MenuSelection != 4 && Running)
            {
                // Manually connect to a peer
                if (MenuSelection == 1)
                {
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "Enter a URL:", LogLevel.INFO);
                    string Url = Console.ReadLine();
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "Enter a port:", LogLevel.INFO);
                    int Port = int.Parse(Console.ReadLine());
                    Server.Connect(new Connection(Url, Port, ""));
                }

                // Broadcast a test packet
                else if (MenuSelection == 2)
                {
                    // Create a response
                    Handshake.Request Request = new Handshake.Request
                    {
                        NodeData = new NodeData()
                        {
                            NetworkId = GlobalsConfig.NETWORK_ID,
                            Version   = 1,
                            Port      = 8090,
                            LocalTime = GeneralUtilities.GetTimestamp(),
                            PeerId    = Server.PeerId
                        },
                        PayloadData = new CoreSyncData()
                        {
                            CurrentHeight = Globals.DAEMON_BLOCK_HEIGHT,
                            TopId         = Globals.DAEMON_TOP_ID
                        }
                    };

                    // Get body bytes
                    byte[] BodyBytes = Request.Serialize();

                    // Create a header
                    BucketHead2 Header = new BucketHead2
                    {
                        Signature        = GlobalsConfig.LEVIN_SIGNATURE,
                        ResponseRequired = false,
                        PayloadSize      = (ulong)BodyBytes.Length,
                        CommandCode      = (uint)Handshake.Id,
                        ProtocolVersion  = GlobalsConfig.LEVIN_VERSION,
                        Flags            = LevinProtocol.LEVIN_PACKET_RESPONSE,
                        ReturnCode       = LevinProtocol.LEVIN_RETCODE_SUCCESS
                    };

                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "[OUT] Sending Handshake Request:", LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "- Node Data:", LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "  - Network ID: " + Encoding.StringToHexString(Request.NodeData.NetworkId), LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "  - Peer ID: " + Request.NodeData.PeerId, LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "  - Version: " + Request.NodeData.Version, LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "  - Local Time: " + Request.NodeData.LocalTime, LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "  - Port: " + Request.NodeData.Port, LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "- Core Sync Data:", LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "  - Current Height: " + Request.PayloadData.CurrentHeight, LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "  - Top ID: " + Encoding.StringToHexString(Request.PayloadData.TopId), LogLevel.DEBUG);

                    // Send notification
                    Server.Broadcast(Encoding.AppendToByteArray(BodyBytes, Header.Serialize()));
                }

                // Show peer list
                else if (MenuSelection == 3)
                {
                    Server.Prune();
                    string Peers = "";
                    List <PeerConnection> PeerList = Server.GetPeerList();
                    foreach (PeerConnection Peer in PeerList)
                    {
                        Peers += Peer.Address + " ";
                    }
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "Peers:", LogLevel.DEBUG);
                    ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, Peers, LogLevel.DEBUG);
                }

                // Write menu
                ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "Menu:", LogLevel.INFO);
                ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, " 1\tConnect to a Server", LogLevel.INFO);
                ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, " 2\tTest Packet", LogLevel.INFO);
                ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, " 3\tShow Peer List", LogLevel.INFO);
                ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, " 4\tExit\n", LogLevel.INFO);
                ConsoleMessage.WriteLine(ConsoleMessage.DefaultColor, "Enter Selection:", LogLevel.INFO);

                // Get menu selection
                MenuSelection = int.Parse(Console.ReadLine());
            }

            // Stop daemon
            Stop();
        }