コード例 #1
0
        public void onDeleteWallet(object sender, EventArgs e)
        {
            if (IxianHandler.getWalletStorage().deleteWallet())
            {
                // Also delete the account
                onDeleteAccount(sender, e);

                // Stop network activity
                Node.stop();

                Application.Current.Properties.Remove("onboardingComplete");
                Application.Current.Properties.Remove("lockenabled");
                Application.Current.Properties.Remove("waletpass");
                Application.Current.SavePropertiesAsync();  // Force-save properties for compatibility with WPF

                SpixiLocalization.addCustomString("OnboardingComplete", "false");

                Node.localStorage.deleteTransactionCacheFile();
                TransactionCache.clearAllTransactions();
                Node.tiv.clearCache();

                // Show the launch page
                Navigation.PushAsync(new LaunchPage(), Config.defaultXamarinAnimations);

                // Remove the settings page
                Navigation.RemovePage(this);

                // Todo: also remove the parent page without causing memory leaks
            }
            else
            {
                displaySpixiAlert(SpixiLocalization._SL("settings-deletew-error-title"), SpixiLocalization._SL("settings-deletew-error-text"), SpixiLocalization._SL("global-dialog-ok"));
            }
        }
コード例 #2
0
ファイル: APIServer.cs プロジェクト: requin38/Taams-DLT
        // returns statistics about the unspent transactions
        private JsonResponse onGetTxOutsetInfo()
        {
            Block block = IxianHandler.getLastBlock();

            Transaction[] unapplied_txs = TransactionPool.getUnappliedTransactions();

            long      txouts       = 0;
            IxiNumber total_amount = new IxiNumber(0);

            foreach (Transaction tx in unapplied_txs)
            {
                txouts       += tx.toList.Count();
                total_amount += tx.amount + tx.fee;
            }

            Dictionary <string, Object> result_array = new Dictionary <string, Object>
            {
                { "height", block.blockNum },                              // Block height
                { "bestblock", Crypto.hashToString(block.blockChecksum) }, // Block checksum
                { "transactions", unapplied_txs.LongCount() },             // Number of transactions
                { "txouts", txouts },                                      // Number of transaction outputs
                { "total_amount", total_amount.ToString() } // Total amount
            };

            return(new JsonResponse {
                result = result_array, error = null
            });
        }
コード例 #3
0
        public static void acceptFile(Friend friend, string uid)
        {
            using (MemoryStream m = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(m))
                {
                    writer.Write(uid);
                }

                FileTransfer transfer = getIncomingTransfer(uid);
                if (transfer == null)
                {
                    return;
                }

                Logging.info("Accepting file {0}", transfer.fileName);

                transfer.lastTimeStamp = Clock.getTimestamp();

                transfer.filePath = Path.Combine(downloadsPath, transfer.fileName + "." + uid + ".ixipart");

                transfer.fileStream = File.Create(transfer.filePath);
                transfer.fileStream.SetLength((long)transfer.fileSize);

                SpixiMessage spixi_message = new SpixiMessage(SpixiMessageCode.acceptFile, m.ToArray());

                StreamMessage message = new StreamMessage();
                message.type      = StreamMessageCode.data;
                message.recipient = friend.walletAddress;
                message.sender    = IxianHandler.getWalletStorage().getPrimaryAddress();
                message.data      = spixi_message.getBytes();

                StreamProcessor.sendMessage(friend, message);
            }
        }
コード例 #4
0
        private static void queueLoop(List <QueueMessageRecv> queue)
        {
            // Prepare an special message object to use while receiving and parsing, without locking up the queue messages
            QueueMessageRecv active_message = new QueueMessageRecv();

            while (!shouldStop)
            {
                TLC.Report();
                bool message_found = false;
                lock (queue)
                {
                    if (queue.Count > 0)
                    {
                        // Pick the oldest message
                        active_message = queue[0];
                        message_found  = true;
                        // Remove it from the queue
                        queue.RemoveAt(0);
                    }
                }

                if (message_found)
                {
                    Logging.trace("Received {0} ({1}B) - {2}...", active_message.code, active_message.data.Length, Crypto.hashToString(active_message.data.Take(60).ToArray()));
                    // Active message set, attempt to parse it
                    IxianHandler.parseProtocolMessage(active_message.code, active_message.data, active_message.endpoint);
                }
                else
                {
                    // Sleep for 10ms to prevent cpu waste
                    Thread.Sleep(10);
                }
            }
            Logging.info("Network queue thread stopped.");
        }
コード例 #5
0
        /// <summary>
        /// Subscribes client to transactionFrom, transactionTo and balance
        /// </summary>
        /// <remarks>
        ///  This function is used to ensure that the remote endpoing has listed the correct IP and port information for their `PresenceList` entry.
        /// </remarks>
        /// <param name="endpoint">Target endpoint to verify for connectivity.</param>
        public static void subscribeToEvents(RemoteEndpoint endpoint)
        {
            if (endpoint.presenceAddress.type != 'M')
            {
                return;
            }

            // TODO TODO TODO events can be optimized as there is no real need to subscribe them to every connected node

            // Subscribe to transaction events, for own addresses
            var    my_addresses = IxianHandler.getWalletStorage().getMyAddresses();
            Cuckoo filter       = new Cuckoo(my_addresses.Count());

            foreach (var addr in my_addresses)
            {
                filter.Add(addr.address);
            }
            byte[] filter_data = filter.getFilterBytes();
            byte[] event_data  = NetworkEvents.prepareEventMessageData(NetworkEvents.Type.transactionFrom, filter_data);
            endpoint.sendData(ProtocolMessageCode.attachEvent, event_data);

            event_data = NetworkEvents.prepareEventMessageData(NetworkEvents.Type.transactionTo, filter_data);
            endpoint.sendData(ProtocolMessageCode.attachEvent, event_data);

            event_data = NetworkEvents.prepareEventMessageData(NetworkEvents.Type.balance, filter_data);
            endpoint.sendData(ProtocolMessageCode.attachEvent, event_data);
        }
コード例 #6
0
        static public void sendTransaction(string address, IxiNumber amount)
        {
            Node.getBalance();

            if (Node.balance.balance < amount)
            {
                Console.WriteLine("Insufficient funds.\n");
                return;
            }

            SortedDictionary <byte[], IxiNumber> to_list = new SortedDictionary <byte[], IxiNumber>(new ByteArrayComparer());

            IxiNumber fee = ConsensusConfig.transactionPrice;

            byte[] from   = IxianHandler.getWalletStorage().getPrimaryAddress();
            byte[] pubKey = IxianHandler.getWalletStorage().getPrimaryPublicKey();
            to_list.AddOrReplace(Base58Check.Base58CheckEncoding.DecodePlain(address), amount);
            Transaction transaction = new Transaction((int)Transaction.Type.Normal, fee, to_list, from, null, pubKey, IxianHandler.getHighestKnownNetworkBlockHeight());

            if (IxianHandler.addTransaction(transaction, true))
            {
                Console.WriteLine("Sending transaction, txid: {0}\n", Transaction.txIdV8ToLegacy(transaction.id));
            }
            else
            {
                Console.WriteLine("Could not send transaction\n");
            }
        }
コード例 #7
0
        private void onDecline()
        {
            if (requestMsg != null)
            {
                // send decline
                if (!requestMsg.message.StartsWith(":"))
                {
                    string msg_id = Crypto.hashToString(requestMsg.id);

                    SpixiMessage spixi_message = new SpixiMessage(SpixiMessageCode.requestFundsResponse, Encoding.UTF8.GetBytes(msg_id));

                    requestMsg.message = "::" + requestMsg.message;

                    StreamMessage message = new StreamMessage();
                    message.type      = StreamMessageCode.info;
                    message.recipient = friend.walletAddress;
                    message.sender    = IxianHandler.getWalletStorage().getPrimaryAddress();
                    message.data      = spixi_message.getBytes();

                    StreamProcessor.sendMessage(friend, message);

                    Node.localStorage.requestWriteMessages(friend.walletAddress, 0);

                    if (friend.chat_page != null)
                    {
                        friend.chat_page.updateRequestFundsStatus(requestMsg.id, null, SpixiLocalization._SL("chat-payment-status-declined"));
                    }
                }
            }
            Navigation.PopAsync(Config.defaultXamarinAnimations);
        }
コード例 #8
0
        public void scanForLostAddresses()
        {
            bool new_address_found = false;

            foreach (var key in myKeys)
            {
                Address primary_address = new Address(key.Value.addressBytes);
                byte[]  last_nonce      = key.Value.lastNonceBytes;
                for (int i = 0; i < 100; i++)
                {
                    Address new_address = generateNewAddress(primary_address, last_nonce, false, false);
                    if (IxianHandler.getWalletBalance(new_address.address) > 0)
                    {
                        new_address_found = true;
                        for (int j = 0; j <= i; j++)
                        {
                            generateNewAddress(primary_address, null, true, false);
                        }
                        i = 0;
                    }
                    last_nonce = new_address.nonce;
                }
            }
            if (new_address_found)
            {
                writeWallet(walletPassword);
            }
        }
コード例 #9
0
        public static void sendNickname(byte[] recipient, byte[] contact_address)
        {
            if (contact_address != null && contact_address.Length > 1)
            {
                if (!Node.users.hasUser(contact_address))
                {
                    return;
                }
                byte[] nickData = Node.users.getUser(contact_address).nickData;
                if (nickData != null)
                {
                    sendMessage(recipient, new StreamMessage(nickData));
                }

                return;
            }

            SpixiMessage reply_spixi_message = new SpixiMessage(SpixiMessageCode.nick, Encoding.UTF8.GetBytes(Config.botName));

            byte[] sender = IxianHandler.getWalletStorage().getPrimaryAddress();

            // Send the nickname message to friend
            StreamMessage reply_message = new StreamMessage();

            reply_message.type           = StreamMessageCode.info;
            reply_message.recipient      = recipient;
            reply_message.sender         = sender;
            reply_message.data           = reply_spixi_message.getBytes();
            reply_message.encryptionType = StreamMessageEncryptionCode.none;
            reply_message.id             = new byte[] { 5 };

            reply_message.sign(IxianHandler.getWalletStorage().getPrimaryPrivateKey());

            sendMessage(recipient, reply_message);
        }
コード例 #10
0
ファイル: WIXISentPage.xaml.cs プロジェクト: tomaszlt/Spixi
        // Retrieve the transaction from local cache storage
        private void checkTransaction()
        {
            string      confirmed_text = SpixiLocalization._SL("wallet-sent-confirmed");
            Transaction ctransaction   = TransactionCache.getTransaction(transaction.id);

            if (ctransaction == null || ctransaction.applied == 0)
            {
                ctransaction   = transaction;
                confirmed_text = SpixiLocalization._SL("wallet-sent-unconfirmed");
            }

            IxiNumber amount = ctransaction.amount;

            // Convert unix timestamp
            string time = Utils.UnixTimeStampToString(Convert.ToDouble(ctransaction.timeStamp));

            byte[] addr = new Address(ctransaction.pubKey).address;
            if (addr.SequenceEqual(IxianHandler.getWalletStorage().getPrimaryAddress()))
            {
                // this is a sent payment

                foreach (var entry in ctransaction.toList)
                {
                    //Utils.sendUiCommand(webView, "addSender", Base58Check.Base58CheckEncoding.EncodePlain(entry.Key) + ": " + entry.Value.ToString(), time);
                    Utils.sendUiCommand(webView, "addSender", Encoding.ASCII.GetString(ctransaction.data) + ": " + entry.Value.ToString(), time);
                }
            }

            Utils.sendUiCommand(webView, "setData", amount.ToString(), ctransaction.fee.ToString(),
                                time, confirmed_text, (ctransaction.fee / ctransaction.amount).ToString() + "%", Transaction.txIdV8ToLegacy(transaction.id));
            return;
        }
コード例 #11
0
        public static void sendAcceptAdd(byte[] recipient, byte[] pub_key)
        {
            Node.users.setPubKey(recipient, pub_key, false);
            var user = Node.users.getUser(recipient);

            if (user != null && user.status != BotContactStatus.banned)
            {
                user.status = BotContactStatus.normal;
            }

            SpixiMessage spixi_message = new SpixiMessage(SpixiMessageCode.acceptAddBot, null);

            StreamMessage message = new StreamMessage();

            message.type           = StreamMessageCode.info;
            message.recipient      = recipient;
            message.sender         = IxianHandler.getWalletStorage().getPrimaryAddress();
            message.data           = spixi_message.getBytes();
            message.encryptionType = StreamMessageEncryptionCode.none;
            message.id             = new byte[] { 1 };

            message.sign(IxianHandler.getWalletStorage().getPrimaryPrivateKey());

            sendMessage(recipient, message);
        }
コード例 #12
0
        public static void onMsgDelete(byte[] msg_id, int channel, RemoteEndpoint endpoint)
        {
            StreamMessage msg = Messages.getMessage(msg_id, channel);

            if (msg == null)
            {
                return;
            }

            if (isAdmin(endpoint.presence.wallet) || msg.sender.SequenceEqual(endpoint.presence.wallet))
            {
                Messages.removeMessage(msg_id, channel);

                SpixiMessage spixi_message = new SpixiMessage(SpixiMessageCode.msgDelete, msg_id, channel);

                StreamMessage message = new StreamMessage();
                message.type           = StreamMessageCode.info;
                message.sender         = IxianHandler.getWalletStorage().getPrimaryAddress();
                message.recipient      = message.sender;
                message.data           = spixi_message.getBytes();
                message.encryptionType = StreamMessageEncryptionCode.none;

                message.sign(IxianHandler.getWalletStorage().getPrimaryPrivateKey());

                Messages.addMessage(message, channel, false);

                NetworkServer.forwardMessage(ProtocolMessageCode.s2data, message.getBytes());
            }
        }
コード例 #13
0
        public Node()
        {
#if DEBUG
            Logging.warn("Testing language files");
            SpixiLocalization.testLanguageFiles("en-us");
#endif

            Logging.info("Initing node constructor");

            Instance = this;

            IxianHandler.init(Config.version, this, Config.networkType);

            // Prepare the wallet
            walletStorage = new WalletStorage(Path.Combine(Config.spixiUserFolder, Config.walletFile));

            PeerStorage.init(Config.spixiUserFolder);

            // Init TIV
            tiv = new TransactionInclusion();

            Logging.info("Initing local storage");

            // Prepare the local storage
            localStorage = new SPIXI.Storage.LocalStorage(Config.spixiUserFolder);

            customAppManager = new CustomAppManager(Config.spixiUserFolder);

            FriendList.init(Config.spixiUserFolder);

            Logging.info("Node init done");
        }
コード例 #14
0
        static public void status()
        {
            Console.WriteLine("Last Block: {0}", IxianHandler.getLastBlockHeight());
            int connectionsOut = NetworkClientManager.getConnectedClients(true).Count();

            Console.WriteLine("Connections: {0}\n", connectionsOut);
        }
コード例 #15
0
        public static void sendGetMessages(Friend friend)
        {
            byte[] last_message_id = null;

            if (friend.messages.Count > 0)
            {
                last_message_id = friend.messages[friend.messages.Count - 1].id;
            }

            // Send the message to the S2 nodes
            SpixiMessage spixi_message = new SpixiMessage(new byte[] { 5 }, SpixiMessageCode.getMessages, last_message_id);


            StreamMessage message = new StreamMessage();

            message.type           = StreamMessageCode.info;
            message.sender         = IxianHandler.getWalletStorage().getPrimaryAddress();
            message.recipient      = friend.walletAddress;
            message.data           = spixi_message.getBytes();
            message.transaction    = new byte[1];
            message.sigdata        = new byte[1];
            message.encryptionType = StreamMessageEncryptionCode.none;

            StreamProcessor.sendMessage(friend, message);
        }
コード例 #16
0
        public Node()
        {
            Instance = this;

            CoreConfig.productVersion = Config.version;
            IxianHandler.setHandler(this);

            CoreConfig.isTestNet = Config.isTestNet;

            // Initialize the crypto manager
            CryptoManager.initLib();

            // Prepare the wallet
            walletStorage = new WalletStorage(Path.Combine(Config.spixiUserFolder, Config.walletFile));

            string peers_filename = "peers.ixi";

            if (CoreConfig.isTestNet)
            {
                peers_filename = "testnet-peers.ixi";
            }

            PeerStorage.init(Config.spixiUserFolder, peers_filename);

            ulong block_height = 1;

            byte[] block_checksum = null;

            if (!walletStorage.walletExists())
            {
                block_height   = Config.bakedBlockHeight;
                block_checksum = Config.bakedBlockChecksum;
            }

            string headers_path = "";

            if (!Config.isTestNet)
            {
                headers_path = Path.Combine(Config.spixiUserFolder, "headers");
            }
            else
            {
                // Temporary hack for our beta testers, remove before release
                string tmp_path = Path.Combine(Config.spixiUserFolder, "headers");
                BlockHeaderStorage.init(tmp_path);
                BlockHeaderStorage.deleteCache();
                BlockHeaderStorage.stop();
                // End of hack

                headers_path = Path.Combine(Config.spixiUserFolder, "testnet-headers");
            }
            // Init TIV
            tiv = new TransactionInclusion(headers_path, block_height, block_checksum);

            // Prepare the local storage
            localStorage = new SPIXI.Storage.LocalStorage(Config.spixiUserFolder);

            customAppManager = new CustomAppManager(Config.spixiUserFolder);
        }
コード例 #17
0
        public bool sendKeys(int selected_key)
        {
            try
            {
                using (MemoryStream m = new MemoryStream())
                {
                    using (BinaryWriter writer = new BinaryWriter(m))
                    {
                        if (aesKey != null && selected_key != 2)
                        {
                            writer.Write(aesKey.Length);
                            writer.Write(aesKey);
                            Logging.info("Sending aes key");
                        }
                        else
                        {
                            writer.Write(0);
                        }

                        if (chachaKey != null && selected_key != 1)
                        {
                            writer.Write(chachaKey.Length);
                            writer.Write(chachaKey);
                            Logging.info("Sending chacha key");
                        }
                        else
                        {
                            writer.Write(0);
                        }

                        Logging.info("Preparing key message");

                        SpixiMessage spixi_message = new SpixiMessage(SpixiMessageCode.keys, m.ToArray());

                        // Send the key to the recipient
                        StreamMessage sm = new StreamMessage();
                        sm.type           = StreamMessageCode.info;
                        sm.recipient      = walletAddress;
                        sm.sender         = Node.walletStorage.getPrimaryAddress();
                        sm.transaction    = new byte[1];
                        sm.sigdata        = new byte[1];
                        sm.data           = spixi_message.getBytes();
                        sm.encryptionType = StreamMessageEncryptionCode.rsa;
                        sm.id             = new byte[] { 2 };

                        sm.sign(IxianHandler.getWalletStorage().getPrimaryPrivateKey());

                        StreamProcessor.sendMessage(this, sm);
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                Logging.error(String.Format("Exception during send keys: {0}", e.Message));
            }

            return(false);
        }
コード例 #18
0
ファイル: App.xaml.cs プロジェクト: tomaszlt/Spixi
 private void Application_Exit(object sender, ExitEventArgs e)
 {
     IxianHandler.shutdown();
     while (IxianHandler.status != NodeStatus.stopped)
     {
         Thread.Sleep(10);
     }
 }
コード例 #19
0
        void handleBackup()
        {
            List <byte> wallet = new List <byte>();

            wallet.AddRange(IxianHandler.getWalletStorage().getRawWallet());
            Console.WriteLine("IXIHEX" + Crypto.hashToString(wallet.ToArray()));
            Console.WriteLine("");
        }
コード例 #20
0
        public void loadTransactions()
        {
            Utils.sendUiCommand(webView, "clearRecentActivity");
            lock (TransactionCache.unconfirmedTransactions)
            {
                foreach (Transaction utransaction in TransactionCache.unconfirmedTransactions)
                {
                    byte[] from_address = new Address(utransaction.pubKey).address;
                    // Filter out unrelated transactions
                    if (from_address.SequenceEqual(friend.walletAddress) == false)
                    {
                        if (utransaction.toList.ContainsKey(friend.walletAddress) == false)
                        {
                            continue;
                        }
                    }

                    string tx_type = SpixiLocalization._SL("global-received");
                    if (from_address.SequenceEqual(IxianHandler.getWalletStorage().getPrimaryAddress()))
                    {
                        tx_type = SpixiLocalization._SL("global-sent");
                    }
                    string time = Utils.UnixTimeStampToString(Convert.ToDouble(utransaction.timeStamp));
                    Utils.sendUiCommand(webView, "addPaymentActivity", Transaction.txIdV8ToLegacy(utransaction.id), tx_type, time, utransaction.amount.ToString(), "false");
                }

                for (int i = TransactionCache.transactions.Count - 1; i >= 0; i--)
                {
                    Transaction transaction = TransactionCache.transactions[i];

                    byte[] from_address = new Address(transaction.pubKey).address;
                    // Filter out unrelated transactions
                    if (from_address.SequenceEqual(friend.walletAddress) == false)
                    {
                        if (transaction.toList.ContainsKey(friend.walletAddress) == false)
                        {
                            continue;
                        }
                    }

                    string tx_type = SpixiLocalization._SL("global-received");
                    if (from_address.SequenceEqual(IxianHandler.getWalletStorage().getPrimaryAddress()))
                    {
                        tx_type = SpixiLocalization._SL("global-sent");
                    }
                    string time = Utils.UnixTimeStampToString(Convert.ToDouble(transaction.timeStamp));

                    string confirmed = "true";
                    if (transaction.applied == 0)
                    {
                        confirmed = "error";
                    }

                    Utils.sendUiCommand(webView, "addPaymentActivity", Transaction.txIdV8ToLegacy(transaction.id), tx_type, time, transaction.amount.ToString(), confirmed);
                }
            }
        }
コード例 #21
0
ファイル: AppDelegate.cs プロジェクト: tomaszlt/Spixi
 public override void WillTerminate(UIApplication uiApplication)
 {
     IxianHandler.shutdown();
     while (IxianHandler.status != NodeStatus.stopped)
     {
         Thread.Sleep(10);
     }
     base.WillTerminate(uiApplication);
 }
コード例 #22
0
        private bool processBlockHeader(BlockHeader header)
        {
            if (lastBlockHeader != null && lastBlockHeader.blockChecksum != null && !header.lastBlockChecksum.SequenceEqual(lastBlockHeader.blockChecksum))
            {
                Logging.warn("TIV: Invalid last block checksum");

                // discard the block

                // TODO require previous block to get verifications from 3 nodes
                // if in verification mode, detect liar and flag him
                // below is an implementation that's good enough for now

                if (minBlockHeightReorg < lastBlockHeader.blockNum - 7)
                {
                    minBlockHeightReorg = lastBlockHeader.blockNum - 7;
                }

                BlockHeader prev_header = BlockHeaderStorage.getBlockHeader(minBlockHeightReorg);

                if (prev_header == null)
                {
                    return(false);
                }

                lastBlockHeader = prev_header;

                ConsensusConfig.redactedWindowSize    = ConsensusConfig.getRedactedWindowSize(lastBlockHeader.version);
                ConsensusConfig.minRedactedWindowSize = ConsensusConfig.getRedactedWindowSize(lastBlockHeader.version);

                return(false);
            }

            if (!header.calculateChecksum().SequenceEqual(header.blockChecksum))
            {
                Logging.warn("TIV: Invalid block checksum");
                return(false);
            }

            lastBlockHeader = header;

            ConsensusConfig.redactedWindowSize    = ConsensusConfig.getRedactedWindowSize(lastBlockHeader.version);
            ConsensusConfig.minRedactedWindowSize = ConsensusConfig.getRedactedWindowSize(lastBlockHeader.version);

            if (BlockHeaderStorage.saveBlockHeader(lastBlockHeader))
            {
                // Cleanup every n blocks
                if ((header.blockNum > CoreConfig.maxBlockHeadersPerDatabase * 25) && header.blockNum % CoreConfig.maxBlockHeadersPerDatabase == 0)
                {
                    BlockHeaderStorage.removeAllBlocksBefore(header.blockNum - (CoreConfig.maxBlockHeadersPerDatabase * 25));
                }
            }

            IxianHandler.receivedBlockHeader(lastBlockHeader, true);

            return(true);
        }
コード例 #23
0
ファイル: NetworkServer.cs プロジェクト: radevman/Ixian-Core
        private static void acceptConnection(Socket clientSocket)
        {
            IPEndPoint clientEndpoint = (IPEndPoint)clientSocket.RemoteEndPoint;

            // Add timeouts and set socket options
            //clientSocket.ReceiveTimeout = 5000;
            //clientSocket.SendTimeout = 5000;
            clientSocket.LingerState = new LingerOption(true, 3);
            clientSocket.NoDelay     = true;
            clientSocket.Blocking    = true;

            if (!IxianHandler.isAcceptingConnections())
            {
                Thread.Sleep(100); // wait a bit for check connectivity purposes
                clientSocket.Send(CoreProtocolMessage.prepareProtocolMessage(ProtocolMessageCode.bye, new byte[1]));
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Disconnect(true);
                return;
            }

            lastIncomingConnectionTime = DateTime.UtcNow;
            connectable = true;

            // Setup the remote endpoint
            RemoteEndpoint remoteEndpoint = new RemoteEndpoint();

            lock (connectedClients)
            {
                if (connectedClients.Count + 1 > CoreConfig.maximumServerMasterNodes)
                {
                    Logging.warn(string.Format("Maximum number of connected clients reached. Disconnecting client: {0}:{1}",
                                               clientEndpoint.Address.ToString(), clientEndpoint.Port));
                    clientSocket.Send(CoreProtocolMessage.prepareProtocolMessage(ProtocolMessageCode.bye, new byte[1]));
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Disconnect(true);
                    return;
                }

                var existing_clients = connectedClients.Where(re => re.remoteIP.Address == clientEndpoint.Address);
                if (existing_clients.Count() > 0)
                {
                    Logging.warn(String.Format("Client {0}:{1} already connected as {2}.",
                                               clientEndpoint.Address.ToString(), clientEndpoint.Port, existing_clients.First().ToString()));
                    clientSocket.Send(CoreProtocolMessage.prepareProtocolMessage(ProtocolMessageCode.bye, new byte[1]));
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Disconnect(true);
                    return;
                }

                connectedClients.Add(remoteEndpoint);

                Logging.info(String.Format("Client connection accepted: {0} | #{1}/{2}", clientEndpoint.ToString(), connectedClients.Count + 1, CoreConfig.maximumServerMasterNodes));

                remoteEndpoint.start(clientSocket);
            }
        }
コード例 #24
0
        void handleAddresses()
        {
            List <Address> address_list = IxianHandler.getWalletStorage().getMyAddresses();

            foreach (Address addr in address_list)
            {
                Console.WriteLine("{0}", addr.ToString());
            }
            Console.WriteLine("");
        }
コード例 #25
0
        private static void acceptConnection(Socket clientSocket)
        {
            IPEndPoint clientEndpoint = (IPEndPoint)clientSocket.RemoteEndPoint;

            // Add timeouts and set socket options
            //clientSocket.ReceiveTimeout = 5000;
            //clientSocket.SendTimeout = 5000;
            clientSocket.LingerState = new LingerOption(true, 3);
            clientSocket.NoDelay     = true;
            clientSocket.Blocking    = true;

            if (!IxianHandler.isAcceptingConnections())
            {
                CoreProtocolMessage.sendBye(clientSocket, ProtocolByeCode.notReady, string.Format("The node isn't ready yet, please try again later."), "");
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Disconnect(true);
                return;
            }

            lastIncomingConnectionTime = DateTime.UtcNow;
            connectable = true;

            // Setup the remote endpoint
            RemoteEndpoint remoteEndpoint = new RemoteEndpoint();

            lock (connectedClients)
            {
                if (connectedClients.Count + 1 > CoreConfig.maximumServerMasterNodes)
                {
                    Logging.warn("Maximum number of connected clients reached. Disconnecting client: {0}:{1}",
                                 clientEndpoint.Address.ToString(), clientEndpoint.Port);
                    CoreProtocolMessage.sendBye(clientSocket, ProtocolByeCode.rejected, "Too many clients already connected.", "");
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Disconnect(true);
                    return;
                }

                var existing_clients = connectedClients.Where(re => re.remoteIP.Address == clientEndpoint.Address);
                if (existing_clients.Count() > 0)
                {
                    Logging.warn("Client {0}:{1} already connected as {2}.",
                                 clientEndpoint.Address.ToString(), clientEndpoint.Port, existing_clients.First().ToString());
                    CoreProtocolMessage.sendBye(clientSocket, ProtocolByeCode.rejected, "You are already connected.", "");
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Disconnect(true);
                    return;
                }

                connectedClients.Add(remoteEndpoint);

                Logging.info("Client connection accepted: {0} | #{1}/{2}", clientEndpoint.ToString(), connectedClients.Count + 1, CoreConfig.maximumServerMasterNodes);

                remoteEndpoint.start(clientSocket);
            }
        }
コード例 #26
0
        // Generate an initial presence list
        public static void init(string initial_ip, int port, char type)
        {
            Logging.info("Generating presence list.");

            _myPublicAddress = string.Format("{0}:{1}", initial_ip, port);
            _myPresenceType  = type;

            // Initialize with the default presence state
            curNodePresenceAddress = new PresenceAddress(CoreConfig.device_id, _myPublicAddress, type, CoreConfig.productVersion, 0, null);
            curNodePresence        = new Presence(IxianHandler.getWalletStorage().getPrimaryAddress(), IxianHandler.getWalletStorage().getPrimaryPublicKey(), null, curNodePresenceAddress);
        }
コード例 #27
0
        public static void processPendingTransactions()
        {
            // TODO TODO improve to include failed transactions
            ulong last_block_height = IxianHandler.getLastBlockHeight();

            lock (PendingTransactions.pendingTransactions)
            {
                long cur_time = Clock.getTimestamp();
                List <PendingTransaction> tmp_pending_transactions = new List <PendingTransaction>(PendingTransactions.pendingTransactions);
                int idx = 0;
                foreach (var entry in tmp_pending_transactions)
                {
                    Transaction t       = entry.transaction;
                    long        tx_time = entry.addedTimestamp;

                    if (t.applied != 0)
                    {
                        PendingTransactions.pendingTransactions.RemoveAll(x => x.transaction.id.SequenceEqual(t.id));
                        continue;
                    }

                    // if transaction expired, remove it from pending transactions
                    if (last_block_height > ConsensusConfig.getRedactedWindowSize() && t.blockHeight < last_block_height - ConsensusConfig.getRedactedWindowSize())
                    {
                        ActivityStorage.updateStatus(t.id, ActivityStatus.Error, 0);
                        PendingTransactions.pendingTransactions.RemoveAll(x => x.transaction.id.SequenceEqual(t.id));
                        continue;
                    }

                    if (cur_time - tx_time > 40) // if the transaction is pending for over 40 seconds, resend
                    {
                        CoreProtocolMessage.broadcastProtocolMessage(new char[] { 'M', 'H' }, ProtocolMessageCode.transactionData, t.getBytes(), null);
                        entry.addedTimestamp = cur_time;
                        entry.confirmedNodeList.Clear();
                    }

                    if (entry.confirmedNodeList.Count() >= 3) // if we get transaction from 3 nodes, we can consider it as confirmed
                    {
                        if (entry.messageId != null)
                        {
                            StreamProcessor.confirmMessage(entry.messageId);
                        }
                        continue;
                    }

                    if (cur_time - tx_time > 20) // if the transaction is pending for over 20 seconds, send inquiry
                    {
                        CoreProtocolMessage.broadcastGetTransaction(t.id, 0, null, false);
                    }

                    idx++;
                }
            }
        }
コード例 #28
0
        void handleStatus()
        {
            Console.WriteLine("Last Block Height: {0}", IxianHandler.getLastBlockHeight());
            Console.WriteLine("Network Block Height: {0}", IxianHandler.getHighestKnownNetworkBlockHeight());

            int connectionsOut = NetworkClientManager.getConnectedClients(true).Count();

            Console.WriteLine("Connections: {0}", connectionsOut);

            Console.WriteLine("Pending transactions: {0}\n", PendingTransactions.pendingTransactionCount());
        }
コード例 #29
0
        private bool handleSignature(InventoryItem item, RemoteEndpoint endpoint)
        {
            InventoryItemSignature iis = (InventoryItemSignature)item;
            ulong last_block_height    = IxianHandler.getLastBlockHeight();

            byte[] address   = iis.address;
            ulong  block_num = iis.blockNum;

            if (block_num + 5 > last_block_height && block_num <= last_block_height + 1)
            {
                if (block_num == last_block_height + 1)
                {
                    lock (Node.blockProcessor.localBlockLock)
                    {
                        Block local_block = Node.blockProcessor.localNewBlock;
                        if (local_block == null || local_block.blockNum != block_num)
                        {
                            return(false);
                        }
                        if (!local_block.blockChecksum.SequenceEqual(iis.blockHash) ||
                            local_block.hasNodeSignature(address))
                        {
                            return(false);
                        }
                    }
                }
                else
                {
                    Block sf_block = Node.blockChain.getBlock(block_num);
                    if (!sf_block.blockChecksum.SequenceEqual(iis.blockHash) ||
                        sf_block.hasNodeSignature(address))
                    {
                        return(false);
                    }
                }
                byte[] block_num_bytes = block_num.GetIxiVarIntBytes();
                byte[] addr_len_bytes  = ((ulong)address.Length).GetIxiVarIntBytes();
                byte[] data            = new byte[block_num_bytes.Length + 1 + addr_len_bytes.Length + address.Length];
                Array.Copy(block_num_bytes, data, block_num_bytes.Length);
                data[block_num_bytes.Length] = 1;
                Array.Copy(addr_len_bytes, 0, data, block_num_bytes.Length + 1, addr_len_bytes.Length);
                Array.Copy(address, 0, data, block_num_bytes.Length + 1 + addr_len_bytes.Length, address.Length);
                if (endpoint == null)
                {
                    CoreProtocolMessage.broadcastProtocolMessageToSingleRandomNode(new char[] { 'M', 'H' }, ProtocolMessageCode.getSignatures, data, block_num);
                }
                else
                {
                    endpoint.sendData(ProtocolMessageCode.getSignatures, data, null);
                }
                return(true);
            }
            return(false);
        }
コード例 #30
0
        public static void startProtocolTest()
        {
            Logging.info("Starting spam connect test");

            if (connect())
            {
                Logging.info("Connected.");
            }



            using (MemoryStream m = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(m))
                {
                    string publicHostname = IxianHandler.getFullPublicAddress();
                    // Send the public IP address and port
                    writer.Write(publicHostname);

                    // Send the public node address
                    byte[] address = Node.walletStorage.getPrimaryAddress();
                    writer.Write(address);

                    // Send the testnet designator
                    writer.Write(CoreConfig.isTestNet);

                    // Send the node type
                    char node_type = 'M';        // This is a Master node
                    writer.Write(node_type);

                    // Send the node device id
                    writer.Write(CoreConfig.device_id);

                    // Send the wallet public key
                    writer.Write(Node.walletStorage.getPrimaryPublicKey());

                    sendData(ProtocolMessageCode.hello, m.ToArray());
                }
            }

            Transaction tx = new Transaction((int)Transaction.Type.PoWSolution, "0", "0", ConsensusConfig.foundationAddress, Node.walletStorage.getPrimaryAddress(), null, null, Node.blockChain.getLastBlockNum());

            //byte[] data = string.Format("{0}||{1}||{2}", Node.walletStorage.publicKey, 0, 1);
            //tx.data = data;

            sendData(ProtocolMessageCode.newTransaction, tx.getBytes());


            disconnect();


            Logging.info("Ending spam connect test");
        }