Beispiel #1
0
 public DelegateInfo GetDelegate(NodeClient client, string hash, string addr, bool forceUpdate = false, bool enqueue = false)
 {
     try
     {
         if (_tzKtUrl == null)
         {
             return(client.GetDelegateInfo(addr, hash));
         }
         var str       = client.Download(_tzKtUrl + "v1/accounts/" + addr);
         var @delegate = JsonConvert.DeserializeObject <TzKt.Account>(str);
         if (@delegate.type != "delegate")
         {
             return(null);
         }
         var str_d = client.Download(_tzKtUrl + "v1/accounts/" + addr + "/delegators");
         return(new DelegateInfo
         {
             balance = @delegate.balance - @delegate.frozenDeposits - @delegate.frozenRewards - @delegate.frozenFees,
             deactivated = [email protected],
             staking_balance = @delegate.stakingBalance,
             bond = @delegate.balance,                    //@delegate.balance ,
             Hash = hash,
             delegated_contracts = JsonConvert.DeserializeObject <TzKt.Delegator[]>(str_d).Select(d => d.address).ToList(),
             NumDelegators = @delegate.numDelegators
         });
     }
     catch
     {
         var di = client.GetDelegateInfo(addr, hash);
         di.Hash          = hash;
         di.NumDelegators = di.delegated_contracts.Count;
         return(di ?? new DelegateInfo());
     }
 }
Beispiel #2
0
        public ContractInfo GetContract(NodeClient client, string hash, string addr, bool enqueue = false)
        {
            try
            {
                if (_tzKtUrl == null)
                {
                    return(client.GetContractInfo(hash, addr));
                }

                var str      = client.Download(_tzKtUrl + "v1/accounts/" + addr);
                var contract = JsonConvert.DeserializeObject <TzKt.Account>(str);
                return(new ContractInfo
                {
                    balance = contract.balance - contract.frozenDeposits - contract.frozenRewards - contract.frozenFees,
                    @delegate = contract.@delegate?.address,
                    manager = contract.manager?.address,
                    Hash = hash
                });
            }
            catch
            {
                var ci = client.GetContractInfo(hash, addr);
                ci.Hash = hash;

                return(ci ?? new ContractInfo());
            }
        }
        public NodeManager(Node[] nodes, HttpClient http, ILogger <Node> logger)
        {
            _http   = http;
            _logger = logger;

            Nodes  = nodes;
            Active = Nodes[0];
            Client = new NodeClient(Active.Url, http, logger);
        }
Beispiel #4
0
 public static void StartNodeClient()
 {
     NodeClientConnection = new Thread(delegate()
     {
         Thread.Sleep(1000);
         NodeClient.Connect(Config.SeedNodes[0]);
     });
     NodeClientConnection.Start();
 }
Beispiel #5
0
        public async Task Connect(NodeInfo nodeInfo, Uri endPoint = null)
        {
            if (_node.HasQuit)
            {
                return;
            }

            if (nodeInfo == null)
            {
                return;
            }

            var accept = false;

            lock (_lock)
                accept = _outgoingConnections.Count <= _maxOutgoingConnections;

            if (!accept)
            {
                return;
            }

            if (IsConnected(nodeInfo, true))
            {
                return;
            }

            if (endPoint == null)
            {
                endPoint = nodeInfo.PublicEndPoint;
            }

            var client = new NodeClient(endPoint);

            var connection = await client.OpenNodeConnection();

            if (connection.Connected)
            {
                if (Log.LogTrace)
                {
                    Log.Trace($"NodeServer ({_kademlia.LocalNodeInfo.PublicEndPoint}) connecting {nodeInfo.PublicEndPoint}");
                }

                connection.NodeInfo              = nodeInfo;
                connection.OutgoingConnection    = true;
                connection.ConnectionClosedEvent = ConnectionClosed;
                connection.ConnectionList        = _pendingConnections;

                lock (_lock)
                    _pendingConnections.Add(connection);

                TaskRunner.Run(() => connection.Receive(this));

                await connection.Send(new NodeInfoMessage(_kademlia.NodeConfiguration, nodeInfo.NodeId) { SignKey = _kademlia.LocalKey });
            }
        }
Beispiel #6
0
        public void TestMethod1()
        {
            Debug.Flush();
            var server = new NodeServer(new MessageEncoding(new MessageFactory()));
            var client = new NodeClient(new MessageEncoding(new MessageFactory()));

            server.Start();
            client.SendMessage();

            Thread.Sleep(1000);
        }
Beispiel #7
0
        /// <summary>
        /// Initialize chatbot client
        /// </summary>
        /// <returns>chatbot client instance</returns>
        public AsyncDuplexStreamingCall <ClientMsg, ServerMsg> InitClient()
        {
            channel = new Channel(ServerHost, ChannelCredentials.Insecure);
            var stub   = new NodeClient(channel);
            var stream = stub.MessageLoop(cancellationToken: cancellationTokenSource.Token);

            ClientPost(Hello());
            ClientPost(Login(CookieFile, Schema, Secret));
            ClientPost(Subscribe("me"));
            return(stream);
        }
        public BlockHeader GetNodeHeader(Node node)
        {
            var client = new NodeClient(node.Url, _http, _logger);

            try
            {
                return(client.GetBlockHeader("head"));
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Beispiel #9
0
        void AddValidNode(NodeInfo nodeInfo)
        {
            if (!nodeInfo.IsPublicEndPoint)
            {
                return;
            }

            if (nodeInfo.NodeId == LocalId)
            {
                return;
            }

            if (!_bucket.Contains(nodeInfo.NodeId))
            {
                Log.Trace($"Adding new node {nodeInfo.PublicEndPoint}.", this);
            }

            var evictNode = _bucket.AddOrUpdate(nodeInfo);

            if (evictNode != null)
            {
                lock (_lock)
                {
                    if (_evictionsCount > 8)
                    {
                        return;
                    }
                    _evictionsCount++;
                }
                TaskRunner.Run(async() =>
                {
                    var client = new NodeClient(evictNode.PublicEndPoint);
                    var ni     = await client.DownloadNodeInfo();
                    if (ni.ResultType == DownloadResultTypes.Ok)
                    {
                        _bucket.AddOrUpdate(evictNode);
                    }
                    else
                    {
                        _bucket.Remove(evictNode.NodeId);
                        _bucket.AddOrUpdate(nodeInfo);
                    }

                    lock (_lock)
                    {
                        _evictionsCount--;
                    }
                });
            }
        }
        // TODO: For refactoring
        public string GetStatus(Node node)
        {
            var client = new NodeClient(node.Url, _http, _logger);

            try
            {
                var bh = client.GetBlockHeader("head");
                return($"{bh.level} ({bh.timestamp}) 🆗");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Beispiel #11
0
        async Task OnBlockData(NodeBlockDataMessage message, NodeConnection connection)
        {
            var chainType  = message.ChainType;
            var blockId    = message.BlockId;
            var chainId    = message.ChainId;
            var chainIndex = message.ChainIndex;

            var chain = _chainManager.GetChain(chainType, chainId, chainIndex);

            if (chain == null || blockId <= chain.BlockStorage.LastStoredBlockId)
            {
                return;
            }

            if (message.BlockData != null)
            {
                await _node.SyncManager.HandleBlockData(message.BlockData, new HashSet <NodeConnection> {
                    connection
                });
            }
            else
            {
                if (connection.NodeInfo.IsPublicEndPoint || connection.AutoConnect != null)
                {
                    var client    = new NodeClient(connection.NodeInfo.IsPublicEndPoint ? connection.NodeInfo.PublicEndPoint : connection.AutoConnect.EndPoint);
                    var blockData = (await client.DownloadBlockData(chainType, chainId, chainIndex, blockId)).Data;

                    if (blockData != null)
                    {
                        await _node.SyncManager.HandleBlockData(blockData, new HashSet <NodeConnection> {
                            connection
                        });

                        return;
                    }
                }

                _ = connection.Send(new NodeBlockDataRequestMessage(chainType, blockId, chain.ChainId, chainIndex)
                {
                    SignKey = _node.NodeConfiguration.LocaleNodePrivateKey
                });
            }
        }
Beispiel #12
0
        /// <summary>
        /// Initialize chatbot client
        /// </summary>
        /// <returns>chatbot client instance</returns>
        public AsyncDuplexStreamingCall <ClientMsg, ServerMsg> InitClient()
        {
            //ping / 2s and timeout 2s
            var options = new List <ChannelOption>
            {
                new ChannelOption("grpc.keepalive_time_ms", 2000),
                new ChannelOption("grpc.keepalive_timeout_ms", 2000)
            };

            channel = new Channel(ServerHost, ChannelCredentials.Insecure, options);

            var stub = new NodeClient(channel);

            var stream = stub.MessageLoop(cancellationToken: cancellationTokenSource.Token);

            ClientPost(Hello());
            ClientPost(Login(CookieFile, Schema, Secret));
            ClientPost(Subscribe("me"));
            return(stream);
        }
        private static async Task MainAsync(string[] args)
        {
            string      nodeBaseUrl = "http://localhost:64149";
            INodeClient nodeClient  = new NodeClient(nodeBaseUrl);

            CreateTransactionRequest request = CreateAndSignTransaction(
                "7e4670ae70c98d24f3662c172dc510a085578b9ccc717e6c2f4e547edd960a34",
                "f51362b7351ef62253a227a77751ad9b2302f911",
                "2018-02-10T17:53:48.972Z",
                25000,
                10,
                "funds");

            Response <Transaction> resposne =
                await nodeClient.CreateTransaction(request).ConfigureAwait(false);

            Console.WriteLine(resposne.Status);

            VerifyTransaction(request);
        }
        public ClientExampleTest(ITestOutputHelper testOutputHelper)
        {
            var    all            = Environment.GetEnvironmentVariables();
            string whisperRpcUrl  = Environment.GetEnvironmentVariable("WHISPER_RPC_URL");
            string ethereumRpcUrl = Environment.GetEnvironmentVariable("ETHEREUM_RPC_URL");

            this._fakeEnsProvider  = new FakeEnsProvider();
            this._testOutputHelper = testOutputHelper;
            this._signService      = new WhisperSignService();
            this._whisperRpc       = new WhisperRpc(new Web3(whisperRpcUrl), new WhisperMessageFormatter());

            NodeClient = new NodeClient()
            {
                EthereumRpc     = new EthereumRpc(new Web3(ethereumRpcUrl)),
                WhisperRpc      = _whisperRpc,
                TransportClient = new TransportClient(_whisperRpc, _signService, new WhisperMessageFormatter())
            };
            Settings = new VaspTestSettings()
            {
                PersonHandshakePrivateKeyHex      = "0xe7578145d518e5272d660ccfdeceedf2d55b90867f2b7a6e54dc726662aebac2",
                PersonSignaturePrivateKeyHex      = "0x790a3437381e0ca44a71123d56dc64a6209542ddd58e5a56ecdb13134e86f7c6",
                VaspSmartContractAddressPerson    = "0x6befaf0656b953b188a0ee3bf3db03d07dface61",
                VaspSmartContractAddressJuridical = "0x08FDa931D64b17c3aCFfb35C1B3902e0BBB4eE5C",
                VaspSmartContractAddressBank      = "0x4Dd7E1E2d5640a06ed81f155f171012F1CD48DAA",
                JuridicalSignaturePrivateKeyHex   = "0x6854a4e4f8945d9fa215646a820fe9a866b5635ffc7cfdac29711541f7b913f9",
                JuridicalHandshakePrivateKeyHex   = "0x502eb0b1a40d5b788b2395394bc6ae47adae61e9f0a9584c4700132914a8ed04",
                BankHandshakePrivateKeyHex        = "0x909aa47d973d34adf9bc44d6e1d755f89b9ca2972da77966336972a602a243db",
                BankSignaturePrivateKeyHex        = "0x9b3aaa8e802a1d42cf112dfc0e035440c451102d358163d345f6b3968415b077",
                PlaceOfBirth     = new PlaceOfBirth(DateTime.UtcNow, "Town X", Country.List["DE"]),
                NaturalPersonIds = new NaturalPersonId[]
                {
                    new NaturalPersonId("ID", NaturalIdentificationType.PassportNumber, Country.List["DE"]),
                },
                Bic          = "AUZDDEM1XXX",
                JuridicalIds = new JuridicalPersonId[]
                {
                    new JuridicalPersonId("ID", JuridicalIdentificationType.BankPartyIdentification, Country.List["DE"]),
                },
            };
        }
        public ClientExampleTest(ITestOutputHelper testOutputHelper)
        {
            var    all            = Environment.GetEnvironmentVariables();
            string whisperRpcUrl  = "http://144.76.25.187:8025";                                     //Environment.GetEnvironmentVariable( "WHISPER_RPC_URL");
            string ethereumRpcUrl = "https://ropsten.infura.io/v3/fb49e892176d413d85f993d0352a0971"; //Environment.GetEnvironmentVariable("ETHEREUM_RPC_URL");

            this._fakeEnsProvider  = new FakeEnsProvider();
            this._testOutputHelper = testOutputHelper;
            this._signService      = new WhisperSignService();
            this._whisperRpc       = new WhisperRpc(new Web3(whisperRpcUrl), new WhisperMessageFormatter());

            var ethRpc = new EthereumRpc(new Web3(ethereumRpcUrl));

            NodeClient = new NodeClient()
            {
                EthereumRpc     = ethRpc,
                WhisperRpc      = _whisperRpc,
                TransportClient = new TransportClient(_whisperRpc, _signService, new WhisperMessageFormatter())
            };
            Settings = new VaspTestSettings()
            {
                PersonHandshakePrivateKeyHex      = "0xe7578145d518e5272d660ccfdeceedf2d55b90867f2b7a6e54dc726662aebac2",
                PersonSignaturePrivateKeyHex      = "0x790a3437381e0ca44a71123d56dc64a6209542ddd58e5a56ecdb13134e86f7c6",
                VaspSmartContractAddressPerson    = "0x6befaf0656b953b188a0ee3bf3db03d07dface61",
                VaspSmartContractAddressJuridical = "0x08FDa931D64b17c3aCFfb35C1B3902e0BBB4eE5C",
                JuridicalSignaturePrivateKeyHex   = "0x6854a4e4f8945d9fa215646a820fe9a866b5635ffc7cfdac29711541f7b913f9",
                JuridicalHandshakePrivateKeyHex   = "0x502eb0b1a40d5b788b2395394bc6ae47adae61e9f0a9584c4700132914a8ed04",
                PlaceOfBirth     = new PlaceOfBirth(DateTime.UtcNow, "Town X", Country.List["DE"]),
                NaturalPersonIds = new NaturalPersonId[]
                {
                    new NaturalPersonId("ID", NaturalIdentificationType.PassportNumber, Country.List["DE"]),
                },
                JuridicalIds = new JuridicalPersonId[]
                {
                    new JuridicalPersonId("ID", JuridicalIdentificationType.BankPartyIdentification, Country.List["DE"]),
                },
            };
        }
        internal async void TestNodes()
        {
            while (true)
            {
                bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

                var nodes = NodeUtils.GetAllNodes();

                foreach (var n in nodes)
                {
                    Thread.Sleep(500);

                    try
                    {
                        var con = new Connection();

                        con.SetHost(n.IP);

                        con.AutoHost = false;

                        var client = new NodeClient(con);

                        var info = client.EndGetExtendedNodeInfo(client.BeginGetExtendedNodeInfo());

                        if (n.WentOffLine != null)
                        {
                            var nis = new NisClient(con);

                            if (nis.EndGetStatus(nis.BeginGetStatus()).Code != 6)
                            {
                                continue;
                            }

                            await Nofity(
                                node : n,
                                msg : "Node: " + n.Alias + "\n" + " With IP: " + n.IP +
                                "\nis back online.");

                            n.WentOffLine = null;

                            NodeUtils.UpdateNode(snode: n, chatId: n.OwnedByUser);
                        }
                        if (info.Node.endpoint.Host == n.IP)
                        {
                            ScanTests(n: n);
                        }
                    }
                    catch (Exception e)
                    {
                        if (e.Message.Contains("blocked"))
                        {
                            AccountUtils.DeleteAccountsByUser(n.OwnedByUser);

                            NodeUtils.DeleteUserNodes(n.OwnedByUser);

                            UserUtils.DeleteUser(n.OwnedByUser);

                            break;
                        }

                        if (n.WentOffLine == null)
                        {
                            try
                            {
                                await Nofity(node : n,
                                             msg : "Node: " + n.Alias + "\n" + "With IP: " + n.IP +
                                             " \nis offline or otherwise unreachable. It will be removed from your list of registered nodes in 48 hours if it is not reachable in that time.");
                            }
                            catch (Exception ex)
                            {
                                await Nofity(node : n,
                                             msg : "Node: " + n.Alias + "\n" + "With IP: " + n.IP +
                                             " \nis offline or otherwise unreachable. It will be removed from your list of registered nodes in 48 hours if it is not reachable in that time.");
                            }

                            n.WentOffLine = DateTime.Now;

                            NodeUtils.UpdateNode(snode: n, chatId: n.OwnedByUser);
                        }
                        else if (n.WentOffLine < DateTime.Now.AddDays(value: -2))
                        {
                            await Nofity(node : n,
                                         msg : "Node: " + n.IP +
                                         " has been offline or otherwise unreachable for 48 hours. It will be removed from your list of registered nodes.");

                            NodeUtils.DeleteNode(
                                chatId: (long)n.OwnedByUser,
                                nodes: new List <string> {
                                n.IP
                            });

                            AccountUtils.DeleteAccount(
                                chatId: (long)n.OwnedByUser,
                                accounts: new List <string> {
                                AccountUtils.GetAccount(add: n.DepositAddress, user: (long)n.OwnedByUser).EncodedAddress
                            }
                                );
                        }
                    }
                }
            }
        }
Beispiel #17
0
        async Task <bool> QueryEndPoint(Uri endpoint, bool querySubNodes)
        {
            try
            {
                if (endpoint == LocalNodeInfo.PublicEndPoint)
                {
                    return(false);
                }

                var client         = new NodeClient(endpoint);
                var nodeInfoResult = (await client.DownloadNodeInfo());
                if (nodeInfoResult.ResultType == DownloadResultTypes.Timeout || nodeInfoResult.ResultType == DownloadResultTypes.NotFound)
                {
                    return(false);
                }
                var nodeInfo = nodeInfoResult.Data;
                if (nodeInfo != null)
                {
                    if (nodeInfo.NetworkKey != NetworkKey)
                    {
                        Log.Info($"Queryied node not is invalid {nodeInfo.PublicEndPoint}. Wrong network key.", this);
                        return(false);
                    }


                    {
                        if (nodeInfo.NodeId == LocalId)
                        {
                            return(false);
                        }

                        var queryResult = (await client.DownloadKademliaNodes(nodeInfo.NodeKey, LocalId)).Data;
                        if (queryResult != null)
                        {
                            if (nodeInfo.IsPublicEndPoint)
                            {
                                AddValidNode(nodeInfo);
                            }
                            else
                            {
                                Log.Warn($"Node has no public endpoint {endpoint}.", this);
                            }

                            if (querySubNodes)
                            {
                                foreach (var node in queryResult.Nodes)
                                {
                                    if (node.IsPublicEndPoint)
                                    {
                                        var c2  = new NodeClient(node.PublicEndPoint);
                                        var ni2 = (await c2.DownloadNodeInfo()).Data;
                                        if (ni2 != null && ni2.NetworkKey == NetworkKey && node.NodeKey == ni2.NodeKey)
                                        {
                                            AddValidNode(ni2);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.IgnoreException(ex, this);
                Log.Error($"Node is invalid {endpoint}.", this);
            }
            return(true);
        }
        private static async Task MainAsync(string[] args)
        {
            string nodeBaseUrl;
            string minerAddress;

            if (args.Length < 2)
            {
                nodeBaseUrl  = "http://localhost:64149";
                minerAddress = "9a9f082f37270ff54c5ca4204a0e4da6951fe917";
            }
            else
            {
                nodeBaseUrl  = args[0];
                minerAddress = args[1];
            }

            TimeSpan    maxJobDuration = new TimeSpan(0, 0, 5);
            INodeClient nodeClient     = new NodeClient(nodeBaseUrl);
            Stopwatch   stopwatch      = new Stopwatch();

            do
            {
                stopwatch.Start();

                MiningJob job = await GetMiningJob(nodeClient, minerAddress).ConfigureAwait(false);

                string   difficultyCheck = new string('0', job.Difficulty);
                DateTime dateCreated     = DateTime.UtcNow;
                ulong    nonce           = 0;

                while (nonce < ulong.MaxValue)
                {
                    string guess = HashUtils.ComputeBlockSha256Hash(job.BlockDataHash, dateCreated, nonce);
                    if (guess.StartsWith(difficultyCheck))
                    {
                        // block found, send it to the node
                        bool submitted = await SubmitMinedBlock(
                            nodeClient,
                            minerAddress,
                            5,
                            job.BlockDataHash,
                            dateCreated,
                            nonce,
                            guess).ConfigureAwait(false);

                        Console.WriteLine($"Submitting mining result {(submitted ? "successful" : "failed")}.");
                        break;
                    }

                    if (maxJobDuration < stopwatch.Elapsed)
                    {
                        stopwatch.Reset();
                        break;
                    }

                    // get new timestamp on every 100,000 iterations
                    if (nonce % 100000 == 0)
                    {
                        dateCreated = DateTime.UtcNow;
                    }

                    nonce++;
                }
            } while (true);
        }
        async Task DownloadBlock(long blockId, ChainSyncItem chainSyncItem, HashSet <NodeConnection> nodeConnections, int tries = 0)
        {
            var retry = false;

            var sync = chainSyncItem.Sync;

            try
            {
                await sync.DownloadLock.WaitAsync();


                SyncDownload download;
                lock (sync.Lock)
                {
                    sync.NewBlocks.TryGetValue(blockId, out download);
                    if (download == null)
                    {
                        return;
                    }

                    if (!download.TimedOut && download.Downloading)
                    {
                        return;
                    }

                    download.Downloading  = true;
                    download.DownloadTime = DateTime.UtcNow;
                }

                nodeConnections = nodeConnections ?? new HashSet <NodeConnection>();

                foreach (var connection in nodeConnections)
                {
                    var nodeInfo = connection.NodeInfo;
                    if (nodeInfo.IsPublicEndPoint && nodeInfo.NodeId != _configuration.LocaleNodeInfo.NodeId)
                    {
                        var client    = new NodeClient(nodeInfo.PublicEndPoint);
                        var blockData = (await client.DownloadBlockData(chainSyncItem.ChainType, chainSyncItem.ChainId, chainSyncItem.ChainIndex, blockId)).Data;
                        if (blockData != null)
                        {
                            download.UpdateBlockData(blockData);
                            await HandleBlockData(blockData, nodeConnections);

                            goto end;
                        }
                        else
                        {
                            retry = true;
                        }
                    }
                }

                foreach (var endPoint in chainSyncItem.Chain.AvailableEndpoints)
                {
                    var client = new NodeClient(endPoint.EndPoint);
                    if (endPoint.NodeInfo == null)
                    {
                        endPoint.NodeInfo = (await client.DownloadNodeInfo(_configuration.NetworkPublicKey)).Data;
                    }

                    if (endPoint.NodeInfo != null && endPoint.NodeInfo.NodeId != _configuration.LocaleNodeInfo.NodeId)
                    {
                        var blockData = (await client.DownloadBlockData(chainSyncItem.ChainType, chainSyncItem.ChainId, chainSyncItem.ChainIndex, blockId)).Data;
                        if (blockData != null)
                        {
                            download.UpdateBlockData(blockData);
                            await HandleBlockData(blockData, nodeConnections);

                            goto end;
                        }
                        else
                        {
                            retry = true;
                        }
                    }
                }

                foreach (var connection in nodeConnections)
                {
                    await connection.Send(new NodeBlockDataRequestMessage(chainSyncItem.ChainType, blockId, chainSyncItem.ChainId, chainSyncItem.ChainIndex) { SignKey = _configuration.LocaleNodePrivateKey });

                    await Task.Delay(50);
                }

end:
                lock (sync.Lock)
                {
                    download.Downloading = false;
                }
            }
            catch (Exception ex)
            {
                Log.HandleException(ex);
            }
            finally
            {
                sync.DownloadLock.Release();
            }

            if (retry && tries < 10)
            {
                await Task.Delay(50 *(tries + 1));

                TaskRunner.Run(() => DownloadBlock(blockId, chainSyncItem, nodeConnections, tries + 1));
            }
        }
Beispiel #20
0
        public async Task <bool> Start(string[] args, CancellationTokenSource quiteToken)
        {
            _quitToken = quiteToken;

            if (_quitToken.IsCancellationRequested)
            {
                return(false);
            }

            var dataPath = "heleusdata";

            var genesis        = false;
            var sync           = false;
            var run            = false;
            var init           = false;
            var newChainConfig = false;

            if (args.Length == 1)
            {
                dataPath = args[0];
                run      = true;
            }
            else if (args.Length == 2)
            {
                dataPath = args[0];
                var cmd = args[1];

                if (cmd == "init")
                {
                    init = true;
                }
                else if (cmd == "run")
                {
                    run = true;
                }
                else if (cmd == "sync")
                {
                    sync = true;
                }
                else if (cmd == "chainconfig")
                {
                    newChainConfig = true;
                }
                else if (cmd == "genesis")
                {
                    genesis = true;
                }
                else
                {
                    Usage();
                    return(false);
                }
            }
            else
            {
                Usage();
                return(false);
            }

            if ((run || sync) && !File.Exists(Path.Combine(dataPath, $"{nameof(NodeConfig).ToLower()}.txt")))
            {
                Usage();
                var dp = new DirectoryInfo(dataPath);
                Log.Error($"Data path {dp.FullName} not initalized.", this);
                return(false);
            }

            Storage = new Storage(dataPath);
            if (!Storage.IsWriteable)
            {
                Log.Fatal($"Data path {Storage.Root} is not writeable!", this);
                return(false);
            }

            if (genesis)
            {
                Storage.DeleteDirectory("cache");
                Storage.DeleteDirectory("chains");
            }

            PubSub = Log.PubSub = new PubSub();

            Log.Write($"Starting Heleus Node (Version {Program.Version}).");
            Log.Trace($"PID {System.Diagnostics.Process.GetCurrentProcess().Id}");

            Log.Write($"Data path is '{Storage.Root.FullName}'.");

            var config = Config.Load <NodeConfig>(Storage);

            Log.AddIgnoreList(config.LogIgnore);
            Log.LogLevel = config.LogLevel;

            if (Program.IsDebugging)
            {
                Log.LogLevel = LogLevels.Trace;
            }

            if (newChainConfig)
            {
                var chainConfig = Config.Load <ChainConfig>(Storage, true);
                //if (chainConfig.Chains.Count == 0)
                {
                    Log.Write("Chain config generated.");

                    chainConfig.Chains.Add(new ChainConfig.ChainInfo {
                        ChainKeys = new List <ChainConfig.ChainKeyInfo> {
                            new ChainConfig.ChainKeyInfo {
                                ChainKey = string.Empty, ChainKeyPassword = string.Empty, AttachementKey = -1
                            }
                        }
                    });
                    Config.Save(chainConfig);
                }

                return(false);
            }

            if (init)
            {
                Log.Write("Config file generated.");
                return(false);
            }

            if (!genesis)
            {
                if (config.NetworkPublicKey.IsNullOrEmpty())
                {
                    Log.Write("Network key not set. Querying beacon nodes.");
                    var beacons = config.BeaconNodes;
                    foreach (var beacon in beacons)
                    {
                        Log.Write($"Querying beacon node {beacon}.");
                        var client   = new NodeClient(new Uri(beacon));
                        var nodeInfo = (await client.DownloadNodeInfo()).Data;
                        if (nodeInfo != null)
                        {
                            config.NetworkPublicKey = nodeInfo.NetworkKey.HexString;
                            Config.Save(config);
                            Log.Write($"Network key set to {config.NetworkPublicKey}.");
                            break;
                        }
                    }
                }

                if (config.NetworkPublicKey.IsNullOrEmpty())
                {
                    Log.Write("No valid network key found or set.", this);
                    return(false);
                }
            }

            NodeConfiguration = new NodeConfiguration(config, Config.Load <CoreKeyConfig>(Storage, false), Config.Load <ChainConfig>(Storage, false));
            Host = new Host(config);
            AttachementManager = new AttachementManager(this);
            ChainManager       = new ChainManager(this);
            if (!await ChainManager.Initalize())
            {
                return(false);
            }

            if (genesis)
            {
                var result = GenesisBlock.Generate(Storage);

                var blockData = new BlockData <CoreBlock>(result.Block, result.Signature);
                await ChainManager.Start(false);

                await ChainManager.CoreChain.BlockStorage.StoreBlock(blockData);

                ChainManager.ConsumeBlockData(blockData);

                Log.Write($"Genesis block and keys generated. Network public key: {result.NetworkPublicKey.HexString}.");

                var coreKeyConfig = Config.Load <CoreKeyConfig>(Storage);
                coreKeyConfig.Key      = result.NetworkVoteKey.HexString;
                coreKeyConfig.Password = result.NetworkVotePassword;

                config.NetworkPublicKey = result.NetworkPublicKey.HexString;

                Config.Save(config);
                Config.Save(coreKeyConfig);

                await ChainManager.Stop();

                await ChainManager.Start(true);

                if (result.ServiceTransactions.Count > 0)
                {
                    foreach (var serviceTransactions in result.ServiceTransactions)
                    {
                        var chainId      = serviceTransactions.Key;
                        var transactions = serviceTransactions.Value;

                        var serviceChain  = ChainManager.GetServiceChain(chainId);
                        var maintainChain = ChainManager.GetMaintainChain(chainId);
                        if (serviceChain != null)
                        {
                            var generator = new ServiceBlockGenerator(ChainManager.CoreChain, serviceChain, maintainChain, null);
                            foreach (var transaction in transactions)
                            {
                                generator.ConsumeTransaction(transaction);
                            }

                            var serviceBlock     = generator.GenerateBlock(0, 0);
                            var serviceBlockData = new BlockData <ServiceBlock>(serviceBlock, new BlockSignatures(serviceBlock));
                            await serviceChain.BlockStorage.StoreBlock(serviceBlockData);

                            serviceChain.ConsumeBlockData(serviceBlockData);
                        }
                    }
                }

                await ChainManager.Stop();

                return(false);
            }

            SyncManager = new SyncManager(this);
            await SyncManager.Start();

            //if (!await SyncManager.Start())
            //    return false;

            if (sync)
            {
                Log.Write("Sync done.");
                return(false);
            }

            AttachementManager.Start();

            Kademlia           = new Kademlia(Storage, this);
            TransactionManager = new TransactionManager(this);
            CouncilManager     = new CouncilManager(this);

            NodeServer   = new NodeServer(this, config.MaxIncomingConnections, config.MaxOutgoingConnectoins);
            ClientServer = new ClientServer(this);

            if (Host.EnableRemoteServices)
            {
                ServiceServer = new ServiceServer();
            }

            await(Host as Host).Start(this);
            return(true);
        }
Beispiel #21
0
        async Task <Dictionary <Tuple <int, uint, ChainType>, ChainSyncItem> > GetChainSyncItems()
        {
            var chains = new List <Chain.Chain> {
                _chainManager.CoreChain
            };

            chains.AddRange(_chainManager.ServiceChains.Values);
            chains.AddRange(_chainManager.DataChains.Values);
            chains.AddRange(_chainManager.MaintainChains.Values);

            var chainSyncs = new Dictionary <Tuple <int, uint, ChainType>, ChainSyncItem>();
            var remotes    = new List <RemoteSyncItem>();

            foreach (var chain in chains)
            {
                var chainType  = chain.ChainType;
                var chainId    = chain.ChainId;
                var chainIndex = chain.ChainIndex;

                var chainSync = new ChainSyncItem(chain);
                chainSyncs.Add(new Tuple <int, uint, ChainType>(chainId, chainIndex, chainType), chainSync);

                Chain.Chain.CreateRequiredDirectories(_storage, chain.ChainType, chainId, chainIndex, true);

                var endPoints = chain.AvailableEndpoints;
                foreach (var endPoint in endPoints)
                {
                    var client   = new NodeClient(endPoint.EndPoint);
                    var nodeInfo = endPoint.NodeInfo;
                    if (nodeInfo == null)
                    {
                        nodeInfo = (await client.DownloadNodeInfo(_configuration.NetworkPublicKey)).Data;
                    }

                    if (nodeInfo != null && !(nodeInfo.NodeId == _configuration.LocaleNodeInfo.NodeId))
                    {
                        if (endPoint.NodeInfo == null)
                        {
                            endPoint.NodeInfo = nodeInfo;
                        }

                        var lastBlockInfo = (await client.DownloadLastBlockInfo(chainType, chainId, chainIndex)).Data;
                        if (lastBlockInfo != null)
                        {
                            var blockSliceInfo       = (await client.DownloadBlockStorageSliceInfo(chainType, chainId, chainIndex)).Data;
                            var transactionSliceInfo = (await client.DownloadTransactionStorageSliceInfo(chainType, chainId, chainIndex)).Data;

                            var remote = new RemoteSyncItem(client, lastBlockInfo);
                            chainSync.AddRemote(remote);

                            if (blockSliceInfo != null)
                            {
                                chainSync.UpdateLowestFoundBlockSliceId(blockSliceInfo.FirstStoredSliceId);
                            }
                            if (transactionSliceInfo != null)
                            {
                                chainSync.UpdateLowestFoundTransactionSliceId(transactionSliceInfo.FirstStoredSliceId);
                            }

                            remotes.Add(remote);
                        }
                    }
                }
            }

            // get latest chain info
            foreach (var chain in chainSyncs.Values)
            {
                var chainType  = chain.ChainType;
                var chainId    = chain.ChainId;
                var chainIndex = chain.ChainIndex;

                foreach (var remote in chain.Remotes)
                {
                    var lastBlockInfo = (await remote.Client.DownloadLastBlockInfo(chainType, chainId, chainIndex)).Data;
                    chain.UpdateLastBlockInfo(lastBlockInfo);
                }
            }

            return(chainSyncs);
        }
Beispiel #22
0
 public RemoteSyncItem(NodeClient client, LastBlockInfo blockState)
 {
     Client        = client;
     LastBlockInfo = blockState;
 }
        internal async void RunBot()
        {
            var snodeClient = new SupernodeClient();

            try
            {
                // get access key from congif
                var Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);
                // insert access token

                // get "me"
                var me = Bot.MakeRequestAsync(request: new GetMe()).Result;

                // if me is null, connection failed, maybe incorrect access token
                if (me == null)
                {
                    Console.WriteLine(value: "GetMe() FAILED. Do you forget to add your AccessToken to App.config?");
                    Console.WriteLine(value: "(Press ENTER to quit)");
                    Console.ReadLine();
                    return;
                }

                // print out that connection worked
                Console.WriteLine(format: "{0} (@{1}) connected!", arg0: me.FirstName, arg1: me.Username);

                Console.WriteLine();
                Console.WriteLine(format: "Find @{0} in Telegram and send him a message - it will be displayed here",
                                  arg0: me.Username);
                Console.WriteLine(value: "(Press ENTER to stop listening and quit)");

                // set message update offset
                long offset = 0;

                // run continuously
                while (!stopMe)
                {
                    Update[] updates;

                    try
                    {
                        updates = Bot.MakeRequestAsync(request: new GetUpdates()
                        {
                            Offset = offset
                        }).Result;
                    }
                    catch (Exception)
                    {
                        Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);
                        continue;
                    }

                    // if none, start next iteration of the loop
                    if (updates == null)
                    {
                        continue;
                    }

                    // repeat following for each update
                    foreach (var update in updates)
                    {
                        // declare the first update as checked
                        offset = update.UpdateId + 1;

                        // get the message text
                        var text = update.Message?.Text;

                        // if empty or null, reiterate loop
                        if (string.IsNullOrEmpty(value: text))
                        {
                            continue;
                        }

                        // if message is to register or unregister a node do the following
                        if (text.StartsWith(value: "/registerNode:") && text != "/registerNode:" ||
                            text.StartsWith(value: "/unregisterNode:") && text != "/unregisterNode:")
                        {
                            // send message to let the user know the bot is working
                            var reqAction = new SendMessage(chatId: update.Message.Chat.Id, text: "One moment please..");

                            await Bot.MakeRequestAsync(request : reqAction);

                            var t =
                                Task.Run(
                                    action:
                                    () => new NodeManagement().ManageNodes(chat: update.Message.Chat, text: text));
                            continue;
                        }

                        if (text == "/dailySummary" || text == "/sevenDaySummary" || text == "/thirtyOneDaySummary" ||
                            text.StartsWith(value: "/customSummary:"))
                        {
                            var t =
                                Task.Run(
                                    action: () => SummaryCreator.GetSummary(text: text, chat: update.Message.Chat));

                            continue;
                        }

                        // if a user wants to register an account, not linked to a supernode
                        if (text.StartsWith(value: "/registerAccount:") && text != "/registerAccount:")
                        {
                            var t = Task.Run(action: () => new AccountTask().RegisterAccounts(message: update.Message));
                            continue;
                        }

                        // if a user wants to unregister an account
                        if (text.StartsWith(value: "/unregisterAccount:") && text != "/unregisterAccount:")
                        {
                            var t =
                                Task.Run(
                                    action:
                                    () => new AccountTask().UnregisterAccount(message: update.Message, text: text));
                            continue;
                        }

                        if (text.StartsWith(value: "/optInTxsAcc:") && text != "/optInTxsAcc:")
                        {
                            OptIOAccountUtils.OptInTx(message: update.Message);

                            continue;
                        }
                        if (text.StartsWith(value: "/optOutTxsAcc:") && text != "/optOutTxsAcc:")
                        {
                            OptIOAccountUtils.OptOutTx(message: update.Message);

                            continue;
                        }

                        if (text.StartsWith(value: "/optInHarvestingAcc:") && text != "/optInHarvestingAcc:")
                        {
                            OptIOAccountUtils.OptInHarvesting(message: update.Message);

                            continue;
                        }
                        if (text.StartsWith(value: "/optOutHarvestingAcc:") && text != "/optOutHarvestingAcc:")
                        {
                            OptIOAccountUtils.OptOutHarvesting(message: update.Message);

                            continue;
                        }

                        switch (text)
                        {
                        case "/registerAccount:":
                        {
                            var reqAction = new SendMessage(chatId: update.Message.Chat.Id,
                                                            text:
                                                            "To register an account, use the command \"/registerAccount:\" followed by a comma delimited list of accounts");

                            Bot.MakeRequestAsync(request: reqAction);

                            continue;
                        }

                        case "/unregisterAccount:":
                        {
                            var reqAction = new SendMessage(chatId: update.Message.Chat.Id,
                                                            text:
                                                            "To unregister an account, use the commmand \"/unregisterAccount:\" followed by a comma delimited list of accounts");

                            Bot.MakeRequestAsync(request: reqAction);

                            continue;
                        }

                        case "/registerNode:":
                        {
                            var reqAction = new SendMessage(chatId: update.Message.Chat.Id,
                                                            text:
                                                            "To register a node, use the command \"/registerNode:\" followed by a comma delimited list of IP addresses. Addresses consisting of characters are also supported. eg. bob.nem.ninja");

                            Bot.MakeRequestAsync(request: reqAction);

                            continue;
                        }

                        case "/unregisterNode:":
                        {
                            var reqAction = new SendMessage(chatId: update.Message.Chat.Id,
                                                            text:
                                                            "To unregister a node, use the commmand \"/unregisterNode:\" followed by a comma delimited list of IP addresses");

                            Bot.MakeRequestAsync(request: reqAction);

                            continue;
                        }

                        case "/deleteAccount":
                        {
                            UserUtils.DeleteUser(update.Message.Chat.Id);

                            var reqAction = new SendMessage(chatId: update.Message.Chat.Id,
                                                            text: "You Account has been removed");

                            Bot.MakeRequestAsync(request: reqAction);

                            continue;
                        }

                        case "/start":
                        {
                            UserUtils.AddUser(userName: update.Message.From.Username, chatId: update.Message.Chat.Id);

                            var reqAction = new SendMessage(chatId: update.Message.Chat.Id,
                                                            text: "Hello. \n\n" +
                                                            "Please start by registering a supernode or NEM acccount. \n" +
                                                            "When you register a supernode, the deposit account of the supernode is" +
                                                            " automatically registered under your username and you will start to " +
                                                            "recieve notifications about failed supernode tests, any transactions " +
                                                            "associated with the deposit account as well as any blocks the deposit account of each node harvests\n\n" +
                                                            "If you dont want to get notifications about the supernode depsoit account, simply unregister the " +
                                                            "account by using the \"/unregisterAccount:\" command followed by the account address you wish to unregister." +
                                                            "This does not unregister your supernode, rather, only the deposit account associated with it\n\n" +
                                                            "You can also in opt out of specific notification types for each node or NEM account you have registered. " +
                                                            "Check out the \"/optIO\" command for more details. You are automatically opted in for all notifications when you register a node or nem account.\n\n" +
                                                            "Use the \"/myDetails\" command to see the nodes and accounts you have registered, what notifications they are signed up for and some additional information. \n\n"
                                                            )
                            {
                                ReplyMarkup = KeyBoards.MainMenu
                            };

                            Bot.MakeRequestAsync(request: reqAction);

                            continue;
                        }

                        case "/myDetails":
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id, text: "One moment please..");

                            Bot.MakeRequestAsync(request: req);

                            var t =
                                Task.Run(action: () => new MyDetailsTask().ReturnMyDetails(message: update.Message));

                            continue;
                        }

                        case "/summary":
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text: "Use the commands below to generate a summary for your accounts. " +
                                                      "Include a number after custom summary to get a summary of any given" +
                                                      " days up to the current day")
                            {
                                ReplyMarkup = KeyBoards.SummaryMenu
                            };

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/help":
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text: "https://blog.nem.io/nem-chain-supernode-notifications-telegram-bot/")
                            {
                                ReplyMarkup = KeyBoards.MainMenu
                            };

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/back":
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id, text: "Main menu")
                            {
                                ReplyMarkup = KeyBoards.MainMenu
                            };

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/optIO":
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text:
                                                      "Use any of the commands below to opt in or out of any particular notification types. " +
                                                      "You can either opt in or out of notification types globally for all accounts registered to you" +
                                                      " or selectively per account.")
                            {
                                ReplyMarkup = KeyBoards.OptMenu
                            };

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/optInTxsAcc:":
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text:
                                                      "To opt into transaction notifications for a given account or accounts, use the \"/optInTxsAcc:\" command, " +
                                                      "followed by a list of comma delimeted addresses ");

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/optOutTxsAcc:":
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text: "To opt out of transaction notifications for a given account or accounts, " +
                                                      "use the \"/optOutTxsAcc:\" command, followed by a list of comma delimeted addresses ");

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/optInHarvestingAcc:":
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text: "To opt into harvesting notifications for a given account or accounts, " +
                                                      "use the \"/optInHarvestingAcc:\" command, followed by a list of comma delimeted addresses ");

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/optOutHarvestingAcc:":
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text: "To opt out of harvesting notifications for a given account or accounts, " +
                                                      "use the \"/optOutHarvestingAcc:\" command, followed by a list of comma delimeted addresses ");

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/optInTxsGlobal":
                        {
                            var accs = AccountUtils.GetAccountByUser(chatId: update.Message.Chat.Id);

                            foreach (var acc in accs)
                            {
                                acc.CheckTxs = true;
                            }

                            AccountUtils.UpdateAccount(accs: accs, user: update.Message.Chat.Id);

                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text: "You have opted into transaction notifications");

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/optOutTxsGlobal":
                        {
                            var accs = AccountUtils.GetAccountByUser(chatId: update.Message.Chat.Id);

                            foreach (var acc in accs)
                            {
                                acc.CheckTxs = false;
                            }

                            AccountUtils.UpdateAccount(accs: accs, user: update.Message.Chat.Id);

                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text: "You have opted out of transaction notifications");

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/optInHarvestingGlobal":
                        {
                            var accs = AccountUtils.GetAccountByUser(chatId: update.Message.Chat.Id);

                            foreach (var acc in accs)
                            {
                                acc.CheckBlocks = true;
                            }

                            AccountUtils.UpdateAccount(accs: accs, user: update.Message.Chat.Id);

                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text: "You have opted into harvesting notifications");

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/optOutHarvestingGlobal":
                        {
                            var accs = AccountUtils.GetAccountByUser(chatId: update.Message.Chat.Id);

                            foreach (var acc in accs)
                            {
                                acc.CheckBlocks = false;
                            }

                            AccountUtils.UpdateAccount(accs: accs, user: update.Message.Chat.Id);

                            var req = new SendMessage(chatId: update.Message.Chat.Id,
                                                      text: "You have opted out of harvesting notifications");

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }

                        case "/harvestingSpace":
                        {
                            var reqAction = new SendMessage(chatId: update.Message.Chat.Id,
                                                            text: "One moment please..");

                            Bot.MakeRequestAsync(request: reqAction);

                            var freeNodes = new List <string>();

                            var nodeClient = new NodeClient();

                            snodeClient.BeginGetSupernodes(ar =>
                                {
                                    var r = new Random();

                                    for (var index = r.Next(minValue: 0, maxValue: 320); index < 400; index++)
                                    {
                                        var node = ar.Content.data[index: index];

                                        nodeClient.Connection.SetHost(host: node.ip);

                                        nodeClient.BeginGetUnlockedInfo(ar2 =>
                                        {
                                            if (ar2.Content.NumUnlocked < ar2.Content.MaxUnlocked)
                                            {
                                                freeNodes.Add(item: node.ip);
                                            }
                                        }).AsyncWaitHandle.WaitOne();

                                        if (freeNodes.Count == 3)
                                        {
                                            break;
                                        }
                                    }

                                    var message = string.Join(separator: "\n", values: freeNodes);

                                    var req = new SendMessage(chatId: update.Message.Chat.Id, text: message);

                                    Bot.MakeRequestAsync(request: req);
                                }, 1);

                            continue;
                        }

                        default:
                        {
                            var req = new SendMessage(chatId: update.Message.Chat.Id, text: "Main menu")
                            {
                                ReplyMarkup = KeyBoards.MainMenu
                            };

                            Bot.MakeRequestAsync(request: req);

                            continue;
                        }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("tele scanner line 478 " + e.StackTrace);
            }
        }
Beispiel #24
0
        async Task Loop()
        {
            while (!_node.HasQuit)
            {
                try
                {
                    var count = 0;
                    for (var i = 0; i < 5; i++)
                    {
                        var nodeInfo = _kademlia.GetRandomNode();
                        if (nodeInfo != null)
                        {
                            if (!IsConnected(nodeInfo.NodeId))
                            {
                                await Connect(nodeInfo);
                            }
                            count++;
                        }
                    }

                    if (count == 0 && ConnectionCount <= 2)
                    {
                        foreach (var beacon in _node.NodeConfiguration.BeaconNodes)
                        {
                            var client   = new NodeClient(beacon);
                            var nodeInfo = (await client.DownloadNodeInfo(_kademlia.NetworkKey)).Data;
                            if (nodeInfo != null && !IsConnected(nodeInfo.NodeId))
                            {
                                await Connect(nodeInfo, beacon);
                            }
                        }
                    }

                    foreach (var item in _autoConnect)
                    {
                        if (item.NodeInfo == null)
                        {
                            var client = new NodeClient(item.EndPoint);
                            item.NodeInfo = (await client.DownloadNodeInfo(_kademlia.NetworkKey)).Data;

                            if (item.NodeInfo != null)
                            {
                                lock (_lock)
                                {
                                    _trustedNodeIds.Add(item.NodeInfo.NodeId);
                                }
                            }
                        }

                        if (item.NodeInfo != null)
                        {
                            if (!IsConnected(item.NodeInfo, true))
                            {
                                await Connect(item.NodeInfo, item.EndPoint);
                            }
                        }
                    }

                    var close = new List <NodeConnection>();
                    lock (_lock)
                    {
                        foreach (var incoming in _incomingConnections)
                        {
                            foreach (var outgoing in _outgoingConnections)
                            {
                                if (incoming.NodeInfo.NodeId == outgoing.NodeInfo.NodeId)
                                {
                                    close.Add(incoming);
                                }
                            }
                        }
                    }

                    foreach (var conn in close)
                    {
                        await conn.Close(DisconnectReasons.AlreadyConnected);
                    }

                    await Task.Delay(Time.Seconds(5), _node.QuitToken);

                    if (_node.HasQuit)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Log.IgnoreException(ex, this);
                }
            }
        }
        public static async Task CreateAndSignFaucetTransaction(string recipientAddress, long value)
        {
            Console.WriteLine("--------------------------------");
            Console.WriteLine("CREATING TRANSACTION FROM FAUCET");
            Console.WriteLine("--------------------------------\n");

            string dateTime = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

            TransactionData transactionData = new TransactionData
            {
                From         = faucetAddress,
                To           = recipientAddress,
                Value        = value,
                Fee          = 10,
                DateCreated  = dateTime,
                Data         = "faucetTX",
                SenderPubKey = faucetPublicKey
            };

            string transactionJson = JsonUtils.Serialize(transactionData, false);

            Console.WriteLine("Transaction (JSON): {0}\n\n", transactionJson);

            byte[] transactionDataHash = HashUtils.ComputeSha256(transactionJson.GetBytes());

            var tranSignature = EncryptionUtils.Sign(transactionDataHash, faucetPrivateKey);

            CreateTransactionRequest signedTransaction = CreateTransactionRequest.FromTransactionData(transactionData);

            signedTransaction.SenderSignature = new string[]
            {
                tranSignature[0].ToString(16),
                tranSignature[1].ToString(16)
            };

            string signedTranJson = JsonUtils.Serialize(signedTransaction);

            Console.WriteLine("\nSigned transaction (JSON):");
            Console.WriteLine(signedTranJson);

            var nodeClient = new NodeClient("http://localhost:64149");
            Response <Transaction> response;
            int retries = 0;

            do
            {
                response = await nodeClient.CreateTransaction(signedTransaction).ConfigureAwait(false);

                retries++;
            } while (response.Status == Status.Failed && retries <= 5);

            if (response.Status == Status.Success)
            {
                Console.WriteLine("Transaction submitted to blockchain!");
            }
            else
            {
                Console.WriteLine("Transaction unsuccessful!");
                foreach (var error in response.Errors)
                {
                    Console.WriteLine($"Error: {error}");
                }
            }
        }
Beispiel #26
0
 public decimal GetBalance(NodeClient client, string hash, string addr)
 {
     return(GetContract(client, hash, addr).balance / 1000000M);
 }