Program.cs
1 using ArgsUniform; 2 using Logging; 3 using Utils; 4 5 namespace TestNetRewarder 6 { 7 public class Program 8 { 9 public static CancellationToken CancellationToken; 10 private static Configuration Config = null!; 11 private static ILog Log = null!; 12 private static BotClient BotClient = null!; 13 private static Processor processor = null!; 14 private static DateTime lastCheck = DateTime.MinValue; 15 16 public static Task Main(string[] args) 17 { 18 var cts = new CancellationTokenSource(); 19 CancellationToken = cts.Token; 20 Console.CancelKeyPress += (sender, args) => cts.Cancel(); 21 22 var uniformArgs = new ArgsUniform<Configuration>(PrintHelp, args); 23 Config = uniformArgs.Parse(true); 24 25 Log = new LogSplitter( 26 new FileLog(Path.Combine(Config.LogPath, "testnetrewarder")), 27 new ConsoleLog() 28 ); 29 30 var connector = GethConnector.GethConnector.Initialize(Log); 31 if (connector == null) throw new Exception("Invalid Geth information"); 32 33 BotClient = new BotClient(Config, Log); 34 processor = new Processor(Config, BotClient, connector.GethNode, connector.CodexContracts, Log); 35 36 EnsurePath(Config.DataPath); 37 EnsurePath(Config.LogPath); 38 39 return new Program().MainAsync(); 40 } 41 42 public async Task MainAsync() 43 { 44 EnsureGethOnline(); 45 46 Log.Log("Starting TestNet Rewarder..."); 47 var segmenter = new TimeSegmenter(Log, Config.Interval, Config.HistoryStartUtc, processor); 48 await EnsureBotOnline(); 49 await processor.Initialize(); 50 51 while (!CancellationToken.IsCancellationRequested) 52 { 53 await EnsureBotOnline(); 54 await segmenter.ProcessNextSegment(); 55 await Task.Delay(100, CancellationToken); 56 } 57 } 58 59 private static void EnsureGethOnline() 60 { 61 Log.Log("Checking Geth..."); 62 var gc = GethConnector.GethConnector.Initialize(Log); 63 if (gc == null) throw new Exception("Geth input incorrect"); 64 65 var blockNumber = gc.GethNode.GetSyncedBlockNumber(); 66 if (blockNumber == null || blockNumber < 1) throw new Exception("Geth connection failed."); 67 Log.Log("Geth OK. Block number: " + blockNumber); 68 } 69 70 private static async Task EnsureBotOnline() 71 { 72 var start = DateTime.UtcNow; 73 var timeSince = start - lastCheck; 74 if (timeSince.TotalSeconds < 30.0) return; 75 76 while (! await BotClient.IsOnline() && !CancellationToken.IsCancellationRequested) 77 { 78 await Task.Delay(5000); 79 80 var elapsed = DateTime.UtcNow - start; 81 if (elapsed.TotalMinutes > 10) 82 { 83 var msg = "Unable to connect to bot for " + Time.FormatDuration(elapsed); 84 Log.Error(msg); 85 throw new Exception(msg); 86 } 87 } 88 89 lastCheck = start; 90 } 91 92 private static void PrintHelp() 93 { 94 Log.Log("TestNet Rewarder"); 95 } 96 97 private static void EnsurePath(string path) 98 { 99 if (Directory.Exists(path)) return; 100 Directory.CreateDirectory(path); 101 } 102 } 103 }