Exemplo n.º 1
0
        //This function will only be used to create the initial ID object on login
        public async Task <ID> GetIDAsync(string address, string[] accessibleAttributes = null)
        {
            IDService idService  = new IDService(Web3, AccountService.PrivateKey, address);
            string    idcAddress = await idService.OwnerAsyncCall();

            IDControllerService idcService = new IDControllerService(Web3, AccountService.PrivateKey, idcAddress);

            ID newID = new ID
            {
                ControllerAddress = idcAddress,
                Address           = address,
                Owner             = await idcService.OwnerAsyncCall()
            };
            //Get attributes from the smart contract and add them to the ID object
            Dictionary <string, Attribute> attributes;

            if (accessibleAttributes != null)
            {
                attributes = await GetAttributesAsync(newID, accessibleAttributes);
            }
            else
            {
                attributes = await GetAttributesAsync(newID);
            }

            newID.Attributes = attributes;

            return(newID);
        }
 //3. Inject context in constructor
 //8. Inject automapper in constructor
 //16. Inject dapper in constructor
 //19. Inject logger in constructor
 public ProductController(CoreDatabaseContext dbContext, IMapper mapper, IDService dataService, ILogger <ProductController> logger)
 {
     this.dbContext   = dbContext;
     this.mapper      = mapper;
     this.dataService = dataService;
     this.logger      = logger;
 }
Exemplo n.º 3
0
        private void ProcessLanConnections(object no)
        {
            while (run)
            {
                List <DetectedNode> localNodes = peerFinder.Peers.ToList();

                foreach (DetectedNode peer in localNodes)
                {
                    if (peer.Address == serverNode.Location)
                    {
                        continue;
                    }

                    //If not already connected to that peer then connect
                    if (extOverlordServers.ToList().Where(o => o.Destination.Location == peer.Address).Count() == 0)
                    {
                        logger.Debug("Server connecting as client to external overlord at {0}", peer.Address);
                        var verb = new ConnectVerb();
                        verb.Address    = serverNode.Location;
                        verb.ClientType = ClientType.Overlord;
                        verb.Secret     = IDService.CreateID();

                        var uplink = new Uplink(model.LocalNode,
                                                new Node
                        {
                            ID       = peer.OverlordID,
                            Location = peer.Address,
                            NodeType = ClientType.Overlord,
                            Secret   = verb.Secret
                        });
                        extOverlordServers.Add(uplink);


                        var client = new Client(serverNode);
                        if (client.Execute(verb, peer.Address, 5000))
                        {
                            //Connected as client on an external overlord

                            uplink.OnDisconnect += uplink_OnDisconnect;

                            uplink.Start();
                            logger.Debug("Server connected to client to external overlord at {0}", peer.Address);
                            break;
                        }
                        else
                        {
                            //Failed to connect ot the external overlord
                            logger.Debug("Server failed to connect to external overlord at {0}", peer.Address);
                            peerFinder.RemovePeer(peer);
                            extOverlordServers.Remove(uplink);
                        }
                    }
                }
                Thread.Sleep(3000);
            }
        }
Exemplo n.º 4
0
        protected async Task DeployIDAsync()
        {
            string transactionHash = await IDService.DeployContractAsync(
                Web3, AddressFrom, new HexBigInteger(3905820));

            TransactionReceipt receipt = await
                                         Web3.Eth.Transactions.GetTransactionReceipt.
                                         SendRequestAsync(transactionHash);

            ID = new IDService(Web3, receipt.ContractAddress);
        }
Exemplo n.º 5
0
 public FAPServerHandler(IPAddress host, int port, Model m, MulticastClientService c, LANPeerFinderService p,
                         MulticastServerService ms)
 {
     multicastServer     = ms;
     logger              = LogManager.GetLogger("faplog");
     peerFinder          = p;
     serverNode          = new Overlord();
     serverNode.Nickname = "Overlord";
     serverNode.Host     = host.ToString();
     serverNode.Port     = port;
     serverNode.Online   = true;
     serverNode.ID       = IDService.CreateID();
     model              = m;
     m.PropertyChanged += m_PropertyChanged;
     serverNode.GenerateStrength(m.OverlordPriority);
     network         = new Entities.Network();
     multicastClient = c;
     multicastClient.OnMultiCastRX += multicastClient_OnMultiCastRX;
 }
Exemplo n.º 6
0
        private bool Connect(Domain.Entities.Network net, DetectedNode n)
        {
            try
            {
                LogManager.GetLogger("faplog").Info("Client connecting to {0}", n.Address);
                net.State = ConnectionState.Connecting;

                var verb = new ConnectVerb();
                verb.ClientType = ClientType.Client;
                verb.Address    = model.LocalNode.Location;
                verb.Secret     = IDService.CreateID();
                var client = new Client(model.LocalNode);

                transmitted.Data.Clear();
                foreach (var info in model.LocalNode.Data.ToList())
                {
                    transmitted.SetData(info.Key, info.Value);
                }

                net.Overlord          = new Node();
                net.Overlord.Location = n.Address;
                net.Overlord.Secret   = verb.Secret;
                LogManager.GetLogger("faplog").Debug("Client using secret {0}", verb.Secret);
                if (client.Execute(verb, n.Address))
                {
                    net.State       = ConnectionState.Connected;
                    net.Overlord.ID = verb.OverlordID;
                    LogManager.GetLogger("faplog").Info("Client connected");
                    return(true);
                }
                else
                {
                    net.Overlord = new Node();
                }
            }
            catch
            {
                net.State = ConnectionState.Disconnected;
            }
            return(false);
        }
        public async Task <ActionResult <LoginResponse> > Auth([FromBody] LoginRequest loginRequest, [FromQuery] string ApiKey)
        {
            //todo: ApiKey should be generated by hash and checked
            if (ApiKey is not hrApiKey && ApiKey is not acApiKey)
            {
                return(BadRequest("Wrong ApiKey!!"));
            }


            Result <(string authToken, Domain.UserModel user)> res = await _authService.Login(loginRequest);

            if (res.IsSuccess)
            {
                return(Ok(new LoginResponse()
                {
                    Email = res.Value.user.Email,
                    Key = IDService.Encode("sk", res.Value.user.Id) + "_" + BCrypt.Net.BCrypt.HashPassword(ApiKey),
                }));
            }

            //return BadRequest(new LoginResponse());
            return(BadRequest(new { Error = res.Errors.FirstOrDefault() }));
        }
Exemplo n.º 8
0
        private void ProcessLanConnection(object o)
        {
            mserver.SendMessage(WhoVerb.CreateRequest());
            Domain.Entities.Network network = model.Network;
            network.PropertyChanged += network_PropertyChanged;
            while (run)
            {
                if (network.State != ConnectionState.Connected)
                {
                    //Not connected so connect automatically..

                    //Regenerate local secret to stop any updates if we reconnecting..
                    network.Overlord        = new Node();
                    network.Overlord.Secret = IDService.CreateID();
                    //Clear old peers
                    network.Nodes.Clear();

                    //Build up a prioritised server list
                    var availibleNodes = new List <DetectedNode>();

                    List <DetectedNode> detectedPeers = peerFinder.Peers.ToList();

                    //Prioritise a server we havent connected to already
                    foreach (DetectedNode peer in detectedPeers)
                    {
                        if (attemptedPeers.Where(s => s.Node == peer).Count() == 0)
                        {
                            availibleNodes.Add(peer);
                        }
                    }
                    foreach (LanPeer peer in attemptedPeers.OrderByDescending(x => x.LastConnectionTime))
                    {
                        availibleNodes.Add(peer.Node);
                    }

                    while (network.State != ConnectionState.Connected && availibleNodes.Count > 0)
                    {
                        DetectedNode node = availibleNodes[0];
                        availibleNodes.RemoveAt(0);
                        if (!Connect(network, node))
                        {
                            peerFinder.RemovePeer(node);
                        }
                    }
                }
                if (network.State == ConnectionState.Connected)
                {
                    CheckModelChanges();
                    //Check for network timeout

                    if ((Environment.TickCount - model.Network.Overlord.LastUpdate) > Model.UPLINK_TIMEOUT)
                    {
                        //We havent recently sent/recieved so went a noop so check we are still connected.
                        var req = new NetworkRequest
                        {
                            Verb     = "NOOP",
                            SourceID = model.LocalNode.ID,
                            AuthKey  = model.Network.Overlord.Secret
                        };
                        var client = new Client(model.LocalNode);
                        if (!client.Execute(req, model.Network.Overlord, 4000))
                        {
                            if (network.State == ConnectionState.Connected)
                            {
                                Disconnect();
                            }
                        }
                    }

                    workerEvent.WaitOne(10000);
                }
                else
                {
                    workerEvent.WaitOne(100);
                }
            }
        }
Exemplo n.º 9
0
        public static void TestV2()
        {
            IMyContainerV2 container = new MyContainerV2();

            container.AddScoped <IAService, AService>();
            container.AddTransient <IDService, DService>();
            container.AddSingleton <IDALService, MySqlDALServce>();
            container.AddPerThread <IEService, EService>();
            container.AddPerThread <IFService, FService>();

            int loop = 100;

            // test singleton and transient
            for (int i = 0; i < loop; i++)
            {
                Task <IDService> dTask  = Task.Run(() => container.Resolve <IDService>());
                Task <IDService> dTask2 = Task.Run(() => container.Resolve <IDService>());
                Task.WaitAll(dTask, dTask2); // blocking here
                IDService d  = dTask.Result;
                IDService d2 = dTask2.Result;

                // test singleton
                bool same = ReferenceEquals(d.DAL, d2.DAL); // should be true
                if (!same)
                {
                    Console.WriteLine($"loop {i} -- error for DAL in d: d.DAL != d2.DAL");
                }

                // test transient
                bool diff = ReferenceEquals(d, d2); // should be false
                if (diff)
                {
                    Console.WriteLine($"loop {i} -- error: d == d2");
                }
            }

            // test scoped
            for (int i = 0; i < loop; i++)
            {
                Task <IAService[]> request = Task.Run(async() =>
                {
                    IMyContainerV2 childContainer = container.CreateChildContainer();
                    Task <IAService> aTask        = Task.Run(() => childContainer.Resolve <IAService>());
                    Task <IAService> a2Task       = Task.Run(() => childContainer.Resolve <IAService>());
                    return(await Task.WhenAll(aTask, a2Task));
                });

                Task <IAService[]> request2 = Task.Run(async() =>
                {
                    IMyContainerV2 childContainer = container.CreateChildContainer();
                    Task <IAService> aTask        = Task.Run(() => childContainer.Resolve <IAService>());
                    return(await Task.WhenAll(aTask));
                });

                Task.WaitAll(request, request);
                bool sameA = ReferenceEquals(request.Result[0], request.Result[1]); // should be true
                if (!sameA)
                {
                    Console.WriteLine($"loop {i} -- error for A in the same request: a[0] != a[1]");
                }

                bool diffA = ReferenceEquals(request.Result[0], request2.Result[0]); // should be false
                if (diffA)
                {
                    Console.WriteLine($"loop {i} -- error for A in different requests: a[0] == a2[0]");
                }

                bool sameDal = ReferenceEquals(request.Result[0].DAL, request2.Result[0].DAL); // should be true
                if (!sameDal)
                {
                    Console.WriteLine($"loop {i} -- error for DAL in a: different DAL");
                }
            }

            // test per thread
            for (int i = 0; i < 5; i++)
            {
                Task <IEService[]> t = Task.Run(() =>
                {
                    Console.WriteLine($"t thread: {Thread.CurrentThread.ManagedThreadId}");
                    IEService e = container.Resolve <IEService>();
                    IFService f = container.Resolve <IFService>();
                    Thread.Sleep(100);
                    return(new IEService[] { e, f.E });
                });
                Task <IEService[]> t2 = Task.Run(() =>
                {
                    Console.WriteLine($"t2 thread: {Thread.CurrentThread.ManagedThreadId}");
                    IEService e = container.Resolve <IEService>();
                    return(new IEService[] { e });
                });
                Task.WaitAll(t, t2);

                bool sameE = ReferenceEquals(t.Result[0], t.Result[1]); // should be true
                if (!sameE)
                {
                    Console.WriteLine($"error for E in the same thread: e[0] != e[1]");
                }

                bool diffE = ReferenceEquals(t.Result[0], t2.Result[0]); // should be false
                if (diffE)
                {
                    Console.WriteLine($"error for A in different threads: e[0] == e2[0]");
                }
            }
        }
Exemplo n.º 10
0
        public void CheckSetDefaults()
        {
            if (string.IsNullOrEmpty(LocalNode.ID))
            {
                LocalNode.ID = IDService.CreateID();
            }

            if (string.IsNullOrEmpty(LocalNode.Secret))
            {
                LocalNode.Secret = IDService.CreateID();
            }

            if (LocalNode.Port == 0)
            {
                LocalNode.Port = 30;
            }

            //If there is no avatar set then set the default
            if (string.IsNullOrEmpty(Avatar))
            {
                Stream stream =
                    Application.GetResourceStream(new Uri("Images/Default_Avatar.png", UriKind.Relative)).Stream;
                var img = new byte[stream.Length];
                stream.Read(img, 0, (int)stream.Length);
                Avatar = Convert.ToBase64String(img);
                Save();
            }
            //Set default nick
            if (string.IsNullOrEmpty(Nickname))
            {
                //Try to use the username
                string user = WindowsIdentity.GetCurrent().Name;
                if (!string.IsNullOrEmpty(user) && user.Contains('\\'))
                {
                    user = user.Substring(user.IndexOf('\\') + 1);
                }
                //If the username is a default one then use the PC name
                if (string.IsNullOrEmpty(user) ||
                    string.Equals(user, "Administrator", StringComparison.InvariantCultureIgnoreCase) ||
                    string.Equals(user, "Guest", StringComparison.InvariantCultureIgnoreCase))
                {
                    user = Dns.GetHostName();
                }
                Nickname = user;
            }

            //Set default limits
            if (MaxDownloads == 0)
            {
                MaxDownloads = 3;
            }
            if (MaxDownloadsPerUser == 0)
            {
                MaxDownloadsPerUser = 3;
            }
            if (MaxUploads == 0)
            {
                MaxUploads = 3;
            }
            if (MaxUploadsPerUser == 0)
            {
                MaxUploadsPerUser = 4;
            }

            //Set default download folder
            if (string.IsNullOrEmpty(DownloadFolder))
            {
                DownloadFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) +
                                 "\\FAP Downloads";
            }

            if (!Directory.Exists(DownloadFolder))
            {
                Directory.CreateDirectory(DownloadFolder);
            }

            //Set incomplete download folder
            if (string.IsNullOrEmpty(IncompleteFolder) || !Directory.Exists(IncompleteFolder))
            {
                IncompleteFolder = DownloadFolder + "\\Incomplete";
            }

            if (!Directory.Exists(DownloadFolder))
            {
                Directory.CreateDirectory(DownloadFolder);
            }

            if (!Directory.Exists(IncompleteFolder))
            {
                Directory.CreateDirectory(IncompleteFolder);
            }
        }
Exemplo n.º 11
0
 public IntService([MyConstParam] int i, IDService dService, [MyConstParam] int j)
 {
     GetI = i;
     d    = dService;
     GetJ = j;
 }
Exemplo n.º 12
0
 public FService()
 {
     _iDService = new DService();
 }
Exemplo n.º 13
0
 public FService(IDService iDService)
 {
     _iDService = iDService;
 }
Exemplo n.º 14
0
 public Share()
 {
     id = IDService.CreateID();
 }
Exemplo n.º 15
0
 void Start()
 {
     if(IDService.instance==null){
         IDService.instance=this;
     }
 }