Example #1
0
        public void onRequest(byte[] recipient_address)
        {
            try
            {
                if (Address.validateChecksum(recipient_address) == false)
                {
                    displaySpixiAlert("Invalid checksum", "Please make sure you typed the address correctly.", "OK");
                    return;
                }

                if (recipient_address.SequenceEqual(Node.walletStorage.getPrimaryAddress()))
                {
                    displaySpixiAlert("Cannot add yourself", "The address you have entered is your own address.", "OK");
                    return;
                }

                if (FriendList.getFriend(recipient_address) != null)
                {
                    displaySpixiAlert("Already exists", "This contact is already in your contacts list.", "OK");
                    return;
                }

                Friend friend = FriendList.addFriend(recipient_address, null, Base58Check.Base58CheckEncoding.EncodePlain(recipient_address), null, null, 0);

                FriendList.saveToStorage();

                StreamProcessor.sendContactRequest(friend);
            }catch (Exception)
            {
            }

            Navigation.PopAsync(Config.defaultXamarinAnimations);
        }
        public void onCreateAccount(string nick, string pass)
        {
            // Generate the account on a different thread
            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                // Aquire the wake lock
                bool wake_lock = DependencyService.Get <IPowerManager>().AquireLock();

                if (Node.generateWallet(pass))
                {
                    Node.start();

                    Node.localStorage.nickname = nick;
                    Node.localStorage.writeAccountFile();

                    // TODO: encrypt the password
                    Application.Current.Properties["walletpass"] = pass;
                    Application.Current.SavePropertiesAsync();  // Force-save properties for compatibility with WPF

                    // Release the wake lock
                    if (wake_lock)
                    {
                        DependencyService.Get <IPowerManager>().ReleaseLock();
                    }

                    Device.BeginInvokeOnMainThread(() => {
                        Navigation.PushAsync(HomePage.Instance(), Config.defaultXamarinAnimations);
                        Navigation.RemovePage(this);
                    });

                    Friend friend = FriendList.addFriend(Base58Check.Base58CheckEncoding.DecodePlain("419jmKRKVFcsjmwpDF1XSZ7j1fez6KWaekpiawHvrpyZ8TPVmH1v6bhT2wFc1uddV"), null, "Spixi Group Chat", null, null, 0);

                    FriendList.saveToStorage();

                    StreamProcessor.sendContactRequest(friend);
                }
                else
                {
                    // Release the wake lock
                    if (wake_lock)
                    {
                        DependencyService.Get <IPowerManager>().ReleaseLock();
                    }

                    Device.BeginInvokeOnMainThread(() => {
                        displaySpixiAlert("Error", "Cannot generate new wallet. Please try again.", "Ok");
                    });
                    return;
                }
            }).Start();
        }
Example #3
0
        private static int cooldownPeriod = 60; // cooldown period in seconds


        public static bool sendPushMessage(StreamMessage msg, bool push)
        {
            string receiver = Base58Check.Base58CheckEncoding.EncodePlain(msg.recipient);
            string sender   = Base58Check.Base58CheckEncoding.EncodePlain(msg.sender);
            string data     = HttpUtility.UrlEncode(Convert.ToBase64String(msg.getBytes()));

            string pub_key = "";

            if (msg.id.Length == 1 && msg.id[0] == 1)
            {
                pub_key = HttpUtility.UrlEncode(Convert.ToBase64String(Node.walletStorage.getPrimaryPublicKey()));
            }


            Friend f = FriendList.getFriend(msg.recipient);

            if (f == null)
            {
                return(true); // return true to skip sending this message and remove it from the queue
            }
            string URI        = String.Format("{0}/push.php", Config.pushServiceUrl);
            string parameters = String.Format("tag={0}&data={1}&pk={2}&push={3}&fa={4}", receiver, data, pub_key, push, sender);

            using (WebClient client = new WebClient())
            {
                try
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    string htmlCode = client.UploadString(URI, parameters);
                    if (htmlCode.Equals("OK"))
                    {
                        if (msg.id.Length == 1 && msg.id[0] >= f.handshakeStatus)
                        {
                            f.handshakePushed = true;

                            FriendList.saveToStorage();
                        }
                        return(true);
                    }
                }catch (Exception e)
                {
                    Logging.error("Exception occured in sendPushMessage: " + e);
                }
            }
            return(false);
        }
Example #4
0
        public static bool fetchPushMessages(bool force = false)
        {
            if (force == false && lastUpdate + cooldownPeriod > Clock.getTimestamp())
            {
                return(false);
            }

            lastUpdate = Clock.getTimestamp();

            if (pushNotificationAuthKey == null)
            {
                if (!registerWithPushNotificationServer())
                {
                    return(false);
                }
            }

            try
            {
                string receiver = Base58Check.Base58CheckEncoding.EncodePlain(Node.walletStorage.getPrimaryAddress());

                nonce++;

                byte[] sig = Crypto.sha512(UTF8Encoding.UTF8.GetBytes(nonce + pushNotificationAuthKey));

                using (WebClient client = new WebClient())
                {
                    string url      = String.Format("{0}/fetch.php?tag={1}&nonce={2}&sig={3}", Config.pushServiceUrl, receiver, nonce, Crypto.hashToString(sig));
                    string htmlCode = client.DownloadString(url);

                    if (htmlCode.StartsWith("ERROR"))
                    {
                        if (htmlCode.StartsWith("ERROR: Nonce too low "))
                        {
                            nonce = Int32.Parse(htmlCode.Substring("ERROR: Nonce too low ".Length));
                        }
                        return(false);
                    }

                    if (htmlCode == "UNREGISTERED")
                    {
                        pushNotificationAuthKey = null;
                        registerWithPushNotificationServer();
                        return(false);
                    }

                    List <string[]> jsonResponse = JsonConvert.DeserializeObject <List <string[]> >(htmlCode);

                    if (jsonResponse != null && jsonResponse.Count > 0)
                    {
                        lastUpdate = 0; // If data was available, fetch it again without cooldown
                    }

                    foreach (string[] str in jsonResponse)
                    {
                        try
                        {
                            byte[] data = Convert.FromBase64String(str[1]);
                            if (str[2] != "")
                            {
                                byte[] pk = Convert.FromBase64String(str[2]);
                                Friend f  = FriendList.getFriend(new Address(pk).address);
                                if (f != null && f.publicKey == null)
                                {
                                    f.publicKey = pk;
                                    FriendList.saveToStorage();
                                }
                            }
                            StreamProcessor.receiveData(data, null);
                        }
                        catch (Exception e)
                        {
                            Logging.error("Exception occured in fetchPushMessages while parsing the json response: {0}", e);
                        }

                        try
                        {
                            nonce++;
                            sig = Crypto.sha512(UTF8Encoding.UTF8.GetBytes(nonce + pushNotificationAuthKey));

                            string id = str[0];
                            url      = String.Format("{0}/remove.php?id={1}&nonce={2}&sig={3}", Config.pushServiceUrl, id, nonce, Crypto.hashToString(sig));
                            htmlCode = client.DownloadString(url);
                        }
                        catch (Exception e)
                        {
                            Logging.error("Exception occured in fetchPushMessages while removing the message from server: {0}", e);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logging.error("Exception occured in fetchPushMessages: {0}", e);
                return(false);
            }

            return(true);
        }
Example #5
0
        public static bool fetchPushMessages(bool force = false)
        {
            if (force == false && lastUpdate + cooldownPeriod > Clock.getTimestamp())
            {
                return(false);
            }

            lastUpdate = Clock.getTimestamp();

            try
            {
                string URI        = String.Format("{0}/fetch.php", Config.pushServiceUrl);
                string unique_uri = String.Format("{0}/uniqueid.php", Config.pushServiceUrl);

                string receiver = Base58Check.Base58CheckEncoding.EncodePlain(Node.walletStorage.getPrimaryAddress());

                WebClient uclient  = new WebClient();
                byte[]    checksum = Convert.FromBase64String(uclient.DownloadString(unique_uri));

                byte[] sig = CryptoManager.lib.getSignature(checksum, Node.walletStorage.getPrimaryPrivateKey());

                using (WebClient client = new WebClient())
                {
                    string url      = String.Format("{0}?tag={1}&sig={2}", URI, receiver, HttpUtility.UrlEncode(Convert.ToBase64String(sig)));
                    string htmlCode = client.DownloadString(url);
                    Logging.info("fetchPushMessages: {0}", htmlCode);

                    if (htmlCode == "FALSE")
                    {
                        return(false);
                    }

                    lastUpdate = 0; // If data was available, fetch it again without cooldown

                    List <string[]> jsonResponse = JsonConvert.DeserializeObject <List <string[]> >(htmlCode);

                    foreach (string[] str in jsonResponse)
                    {
                        try
                        {
                            byte[] data = Convert.FromBase64String(str[0]);
                            if (str[1] != "")
                            {
                                byte[] pk = Convert.FromBase64String(str[1]);
                                Friend f  = FriendList.getFriend(new Address(pk).address);
                                if (f != null)
                                {
                                    f.publicKey = pk;
                                }
                                FriendList.saveToStorage();
                            }
                            StreamProcessor.receiveData(data, null);
                        }
                        catch (Exception e)
                        {
                            Logging.error(string.Format("Exception occured in fetchPushMessages while parsing the json response. {0}", e));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logging.error(string.Format("Exception occured in fetchPushMessages. {0}", e));
                return(false);
            }

            return(true);
        }