Beispiel #1
0
 protected override void AfterMyWorkStateChanged(object sender, EventArgs e)
 {
     if (myWorkState)
     {
         AiProtocol aiProtocol = new AiProtocol()
         {
             CaseNo = GateWaySetting.CaseNo, APISetting = APISetting
         };
         AbsProtocols.Add(aiProtocol);
         StateProtocol stateProtocol = new StateProtocol()
         {
             CaseNo = GateWaySetting.CaseNo, APISetting = APISetting
         };
         AbsProtocols.Add(stateProtocol);
         ReadThread = new Thread(Analysis);
         ReadThread.Start();
     }
     else
     {
         if (ReadThread != null)
         {
             ReadThread.Abort();
         }
     }
 }
Beispiel #2
0
                public async Task <Header> GetHeaders()
                {
                    string.Format(
                        "Send getheaders to peer {0}, \n" +
                        "locator: {1} ... {2}",
                        GetID(),
                        HeaderDownload.Locator.First().Hash.ToHexString(),
                        HeaderDownload.Locator.Count > 1 ? HeaderDownload.Locator.Last().Hash.ToHexString() : "")
                    .Log(LogFile);

                    HeaderDownload.Reset();

                    await SendMessage(new GetHeadersMessage(
                                          HeaderDownload.Locator,
                                          ProtocolVersion));

                    lock (LOCK_StateProtocol)
                    {
                        State = StateProtocol.AwaitingHeader;
                    }

                    Cancellation.CancelAfter(
                        TIMEOUT_GETHEADERS_MILLISECONDS);

                    await SignalProtocolTaskCompleted
                    .ReceiveAsync(Cancellation.Token)
                    .ConfigureAwait(false);

                    lock (LOCK_StateProtocol)
                    {
                        State = StateProtocol.IDLE;
                    }

                    return(HeaderDownload.HeaderRoot);
                }
        public async void AwaitMulticastRequest()
        {
            try
            {
                //Listen on port 4568 since its Unicast and cant be bound to port 4567 (in use for multicast)
                using (var client = new UdpClient(MulticastEndPoint.Port, AddressFamily.InterNetwork))
                {
                    client.Ttl = 2;
                    client.JoinMulticastGroup(MulticastEndPoint.Address);
                    client.Client.ReceiveBufferSize = 18;
                    var ipEndPoint = new IPEndPoint(IPAddress.Loopback, MulticastEndPoint.Port);
                    while (true)
                    {
                        Debug.WriteLine("Awaiting multicast request");
                        var result = await client.ReceiveAsync();

                        var stateProtocol = StateProtocol.FromBytes(result.Buffer);

                        //Check if reply is an actual discovery reply
                        if (stateProtocol.ProtocolType == ProtocolRequest.DeviceDiscovery)
                        {
                            if (ipEndPoint.Address.Equals(IPAddress.Parse("127.0.0.1")))
                            {
                                return;
                            }

                            var robeatsDevice = new RobeatsDevice
                            {
                                Id            = stateProtocol.DeviceId,
                                Name          = stateProtocol.DeviceName,
                                EndPoint      = new IPEndPoint(ipEndPoint.Address, 4568),
                                StateProtocol = stateProtocol
                            };

                            OnDeviceDetect(new DeviceDiscoveryEventArgs {
                                RobeatsDevice = robeatsDevice
                            });
                        }
                        else
                        {
                            Debug.WriteLine("Not a reply. ignoring");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
 public void SendDiscoveryReply(RobeatsDevice device)
 {
     //Check if reply is an actual discovery reply
     if (device.StateProtocol.ProtocolType == ProtocolRequest.DeviceDiscovery)
     {
         var stateProtocolReply =
             new StateProtocol(ProtocolRequest.DeviceDiscoveryReply, device.Name, device.Id);
         var bytesReply  = stateProtocolReply.ToBytes();
         var clientReply = new UdpClient(AddressFamily.InterNetwork)
         {
             Ttl = 2
         };
         Debug.WriteLine($"Sending DR: {device.EndPoint}");
         clientReply.Send(bytesReply, bytesReply.Length, (IPEndPoint)device.EndPoint);
         clientReply.Close();
     }
     else
     {
         Debug.WriteLine("Not a discoveryRequest. ignoring");
     }
 }
        /// <summary>
        /// Send a request to a specific <see cref="IPEndPoint"/>
        /// </summary>
        /// <param name="requestType"></param>
        /// <param name="robeatsDevice"></param>
        public void SendRequest(ProtocolRequest requestType, RobeatsDevice robeatsDevice)
        {
            if (!Visible)
            {
                return;
            }
            UdpHelper udpHelper;

            if (requestType == ProtocolRequest.DeviceDiscovery)
            {
                udpHelper = new UdpHelper(MulticastEndPoint);
            }
            else
            {
                var ipEndPoint = new IPEndPoint(((IPEndPoint)robeatsDevice.EndPoint).Address, 4568);
                udpHelper = new UdpHelper(ipEndPoint);
            }

            var stateProtocol = new StateProtocol(requestType, robeatsDevice.Name, robeatsDevice.Id);

            Debug.WriteLine("Sending request of type: " + requestType);
            udpHelper.Send(stateProtocol.ToBytes());
            udpHelper.Close();
        }
        public async void AwaitDiscoveryReply()
        {
            try
            {
                using (var client = new UdpClient(4568, AddressFamily.InterNetwork))
                {
                    while (true)
                    {
                        Debug.WriteLine("Awaiting DR");

                        var result = await client.ReceiveAsync();

                        Debug.WriteLine("Received DR");
                        var stateProtocol = StateProtocol.FromBytes(result.Buffer);

                        if (stateProtocol.ProtocolType == ProtocolRequest.DeviceDiscoveryReply)
                        {
                            var robeatsDevice = new RobeatsDevice
                            {
                                Id   = stateProtocol.DeviceId,
                                Name = stateProtocol.DeviceName,
                                /*EndPoint = client.Client.RemoteEndPoint,*/
                                StateProtocol = stateProtocol
                            };
                            OnDiscoveryReply(new DeviceDiscoveryEventArgs {
                                RobeatsDevice = robeatsDevice
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
Beispiel #7
0
            public async Task StartMessageListener()
            {
                try
                {
                    while (true)
                    {
                        await ReadMessage(Cancellation.Token);

                        string.Format(
                            "{0} received message {1}",
                            GetID(),
                            Command)
                        .Log(LogFile);

                        switch (Command)
                        {
                        case "ping":
                            await SendMessage(new PongMessage(
                                                  BitConverter.ToUInt64(Payload, 0)));

                            break;

                        case "addr":
                            AddressMessage addressMessage =
                                new AddressMessage(Payload);
                            break;

                        case "sendheaders":
                            await SendMessage(new SendHeadersMessage());

                            break;

                        case "feefilter":
                            FeeFilterMessage feeFilterMessage =
                                new FeeFilterMessage(Payload);
                            FeeFilterValue = feeFilterMessage.FeeFilterValue;
                            break;

                        case "block":

                            byte[] blockBytes = Payload
                                                .Take(PayloadLength)
                                                .ToArray();

                            Block block = ParserToken.ParseBlock(blockBytes);

                            if (IsStateIdle())
                            {
                                string.Format(
                                    "{0}: Receives unsolicited block {1}.",
                                    GetID(),
                                    block.Header.Hash.ToHexString())
                                .Log(LogFile);

                                Console.Beep();

                                if (!Blockchain.TryLock())
                                {
                                    break;
                                }

                                try
                                {
                                    ProcessHeaderUnsolicited(
                                        block.Header,
                                        out bool flagHeaderExtendsChain);

                                    if (flagHeaderExtendsChain)
                                    {
                                        if (!Blockchain.TryInsertBlock(
                                                block,
                                                flagValidateHeader: true))
                                        {
                                            // Blockchain insert sollte doch einfach Ex. schmeissen
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Blockchain.ReleaseLock();

                                    throw ex;
                                }

                                Blockchain.ReleaseLock();
                            }
                            else if (IsStateAwaitingBlockDownload())
                            {
                                BlockDownload.InsertBlock(block);

                                if (BlockDownload.IsDownloadCompleted)
                                {
                                    SignalProtocolTaskCompleted.Post(true);

                                    lock (LOCK_StateProtocol)
                                    {
                                        State = StateProtocol.IDLE;
                                    }

                                    break;
                                }

                                Cancellation.CancelAfter(
                                    TIMEOUT_RESPONSE_MILLISECONDS);
                            }

                            break;

                        case "headers":

                            Header header = null;
                            int    index  = 0;

                            int countHeaders = VarInt.GetInt32(
                                Payload,
                                ref index);

                            string.Format(
                                "{0}: Receiving {1} headers.",
                                GetID(),
                                countHeaders)
                            .Log(LogFile);

                            if (IsStateIdle())
                            {
                                header = Token.ParseHeader(
                                    Payload,
                                    ref index);

                                string.Format(
                                    "Received unsolicited header {0}",
                                    header.Hash.ToHexString())
                                .Log(LogFile);

                                index += 1;

                                if (!Blockchain.TryLock())
                                {
                                    break;
                                }

                                try
                                {
                                    ProcessHeaderUnsolicited(
                                        header,
                                        out bool flagHeaderExtendsChain);

                                    if (flagHeaderExtendsChain)
                                    {
                                        List <Inventory> inventories = new()
                                        {
                                            new Inventory(
                                                InventoryType.MSG_BLOCK,
                                                header.Hash)
                                        };

                                        SendMessage(new GetDataMessage(inventories));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Blockchain.ReleaseLock();

                                    throw ex;
                                }

                                Blockchain.ReleaseLock();
                            }
                            else if (IsStateGetHeaders())
                            {
                                if (countHeaders > 0)
                                {
                                    while (index < PayloadLength)
                                    {
                                        header = Token.ParseHeader(
                                            Payload,
                                            ref index);

                                        index += 1;

                                        HeaderDownload.InsertHeader(header, Token);
                                    }
                                }

                                SignalProtocolTaskCompleted.Post(true);
                            }

                            break;

                        case "notfound":

                            Debug.WriteLine(
                                "Command notfound not implemented yet.");

                            break;

                        case "inv":

                            var invMessage = new InvMessage(Payload);

                            var getDataMessage = new GetDataMessage(
                                invMessage.Inventories);

                            break;

                        case "getdata":

                            getDataMessage = new GetDataMessage(Payload);

                            foreach (Inventory inventory in getDataMessage.Inventories)
                            {
                                if (inventory.Type == InventoryType.MSG_TX)
                                {
                                    if (Token.TryRequestTX(
                                            inventory.Hash,
                                            out byte[] tXRaw))
Beispiel #8
0
                public async Task DownloadBlocks(
                    bool flagContinueDownload)
                {
                    StopwatchDownload.Restart();

                    try
                    {
                        if (flagContinueDownload)
                        {
                            flagContinueDownload = false;
                        }
                        else
                        {
                            List <Inventory> inventories =
                                BlockDownload.HeadersExpected.Select(
                                    h => new Inventory(
                                        InventoryType.MSG_BLOCK,
                                        h.Hash))
                                .ToList();

                            await SendMessage(
                                new GetDataMessage(inventories));
                        }

                        lock (LOCK_StateProtocol)
                        {
                            State = StateProtocol.AwaitingBlock;
                        }

                        Cancellation.CancelAfter(
                            TIMEOUT_BLOCKDOWNLOAD_MILLISECONDS);

                        await SignalProtocolTaskCompleted
                        .ReceiveAsync(Cancellation.Token)
                        .ConfigureAwait(false);

                        lock (LOCK_StateProtocol)
                        {
                            State = StateProtocol.IDLE;
                        }
                    }
                    catch (Exception ex)
                    {
                        string.Format(
                            "{0} with peer {1} when downloading blockArchive {2}: \n{3}.",
                            ex.GetType().Name,
                            GetID(),
                            BlockDownload.Index,
                            ex.Message).Log(LogFile);

                        FlagDispose = true;

                        return;
                    }

                    AdjustCountBlocksLoad();

                    string.Format(
                        "{0}: Downloaded {1} blocks in download {2} in {3} ms.",
                        GetID(),
                        BlockDownload.Blocks.Count,
                        BlockDownload.Index,
                        StopwatchDownload.ElapsedMilliseconds)
                    .Log(LogFile);
                }