| | | 1 | | using System.Text.Json; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | |
| | | 5 | | namespace NLightning.Infrastructure.Bitcoin.Services; |
| | | 6 | | |
| | | 7 | | using Domain.Bitcoin.Interfaces; |
| | | 8 | | using Domain.Money; |
| | | 9 | | using Options; |
| | | 10 | | |
| | | 11 | | public class FeeService : IFeeService |
| | | 12 | | { |
| | | 13 | | private const string FeeCacheFileName = "fee_cache.bin"; |
| | 4 | 14 | | private static readonly TimeSpan s_defaultCacheExpiration = TimeSpan.FromMinutes(5); |
| | | 15 | | |
| | 20 | 16 | | private DateTime _lastFetchTime = DateTime.MinValue; |
| | 20 | 17 | | private readonly LightningMoney _cachedFeeRate = LightningMoney.Zero; |
| | | 18 | | private Task? _feeTask; |
| | | 19 | | private CancellationTokenSource? _cts; |
| | | 20 | | |
| | | 21 | | private readonly HttpClient _httpClient; |
| | | 22 | | private readonly ILogger<FeeService> _logger; |
| | | 23 | | private readonly TimeSpan _cacheTimeExpiration; |
| | | 24 | | private readonly string _cacheFilePath; |
| | | 25 | | private readonly FeeEstimationOptions _feeEstimationOptions; |
| | | 26 | | |
| | 20 | 27 | | public FeeService(IOptions<FeeEstimationOptions> feeOptions, HttpClient httpClient, ILogger<FeeService> logger) |
| | | 28 | | { |
| | 20 | 29 | | _feeEstimationOptions = feeOptions.Value; |
| | 20 | 30 | | _httpClient = httpClient; |
| | 20 | 31 | | _logger = logger; |
| | | 32 | | |
| | 20 | 33 | | _cacheFilePath = ParseFilePath(_feeEstimationOptions); |
| | 20 | 34 | | _cacheTimeExpiration = ParseCacheTime(_feeEstimationOptions.CacheExpiration); |
| | | 35 | | |
| | | 36 | | // Try to load from the file initially |
| | 20 | 37 | | _ = LoadFromFileAsync(); |
| | 20 | 38 | | } |
| | | 39 | | |
| | | 40 | | public async Task StartAsync(CancellationToken cancellationToken) |
| | | 41 | | { |
| | 4 | 42 | | _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | | 43 | | |
| | | 44 | | // Start the background task |
| | 4 | 45 | | _feeTask = RunPeriodicRefreshAsync(_cts.Token); |
| | | 46 | | |
| | | 47 | | // If the cache from the file is not valid, refresh immediately |
| | 4 | 48 | | if (!IsCacheValid()) |
| | | 49 | | { |
| | 0 | 50 | | await RefreshFeeRateAsync(_cts.Token); |
| | | 51 | | } |
| | 4 | 52 | | } |
| | | 53 | | |
| | | 54 | | public async Task StopAsync() |
| | | 55 | | { |
| | 4 | 56 | | if (_cts is null) |
| | | 57 | | { |
| | 0 | 58 | | throw new InvalidOperationException("Service is not running"); |
| | | 59 | | } |
| | | 60 | | |
| | 4 | 61 | | await _cts.CancelAsync(); |
| | | 62 | | |
| | 4 | 63 | | if (_feeTask is not null) |
| | | 64 | | { |
| | | 65 | | try |
| | | 66 | | { |
| | 4 | 67 | | await _feeTask; |
| | 4 | 68 | | } |
| | 0 | 69 | | catch (OperationCanceledException) |
| | | 70 | | { |
| | | 71 | | // Expected during cancellation |
| | 0 | 72 | | } |
| | | 73 | | } |
| | 4 | 74 | | } |
| | | 75 | | |
| | | 76 | | public async Task<LightningMoney> GetFeeRatePerKwAsync(CancellationToken cancellationToken = default) |
| | | 77 | | { |
| | 12 | 78 | | if (IsCacheValid()) |
| | | 79 | | { |
| | 4 | 80 | | return _cachedFeeRate; |
| | | 81 | | } |
| | | 82 | | |
| | 8 | 83 | | using var linkedCts = CancellationTokenSource |
| | 8 | 84 | | .CreateLinkedTokenSource(cancellationToken, _cts?.Token ?? CancellationToken.None); |
| | | 85 | | |
| | 8 | 86 | | await RefreshFeeRateAsync(linkedCts.Token); |
| | 8 | 87 | | return _cachedFeeRate; |
| | 12 | 88 | | } |
| | | 89 | | |
| | | 90 | | public LightningMoney GetCachedFeeRatePerKw() |
| | | 91 | | { |
| | 0 | 92 | | return _cachedFeeRate; |
| | | 93 | | } |
| | | 94 | | |
| | | 95 | | public async Task RefreshFeeRateAsync(CancellationToken cancellationToken) |
| | | 96 | | { |
| | | 97 | | try |
| | | 98 | | { |
| | 24 | 99 | | var feeRate = await FetchFeeRateFromApiAsync(cancellationToken); |
| | 8 | 100 | | _cachedFeeRate.Satoshi = feeRate; |
| | 8 | 101 | | _lastFetchTime = DateTime.UtcNow; |
| | 8 | 102 | | await SaveToFileAsync(); |
| | 8 | 103 | | } |
| | 4 | 104 | | catch (OperationCanceledException) |
| | | 105 | | { |
| | | 106 | | // Ignore cancellation |
| | 4 | 107 | | } |
| | 12 | 108 | | catch (Exception e) |
| | | 109 | | { |
| | 12 | 110 | | _logger.LogError(e, "Error fetching fee rate from API"); |
| | 12 | 111 | | } |
| | 24 | 112 | | } |
| | | 113 | | |
| | | 114 | | private async Task<long> FetchFeeRateFromApiAsync(CancellationToken cancellationToken) |
| | | 115 | | { |
| | | 116 | | HttpResponseMessage response; |
| | | 117 | | |
| | | 118 | | try |
| | | 119 | | { |
| | 24 | 120 | | if (_feeEstimationOptions.Method.Equals("GET", StringComparison.CurrentCultureIgnoreCase)) |
| | | 121 | | { |
| | 24 | 122 | | response = await _httpClient.GetAsync(_feeEstimationOptions.Url, cancellationToken); |
| | | 123 | | } |
| | | 124 | | else // POST |
| | | 125 | | { |
| | 0 | 126 | | var content = new StringContent( |
| | 0 | 127 | | _feeEstimationOptions.Body, |
| | 0 | 128 | | System.Text.Encoding.UTF8, |
| | 0 | 129 | | _feeEstimationOptions.ContentType); |
| | | 130 | | |
| | 0 | 131 | | response = await _httpClient.PostAsync(_feeEstimationOptions.Url, content, cancellationToken); |
| | | 132 | | } |
| | 16 | 133 | | } |
| | 8 | 134 | | catch (Exception e) |
| | | 135 | | { |
| | 8 | 136 | | throw new InvalidOperationException("Error fetching from API", e); |
| | | 137 | | } |
| | | 138 | | |
| | 16 | 139 | | response.EnsureSuccessStatusCode(); |
| | 16 | 140 | | var jsonResponseStream = await response.Content.ReadAsStreamAsync(cancellationToken); |
| | | 141 | | |
| | | 142 | | // Parse the JSON response |
| | 16 | 143 | | using var document = |
| | 16 | 144 | | await JsonDocument.ParseAsync(jsonResponseStream, cancellationToken: cancellationToken); |
| | 8 | 145 | | var root = document.RootElement; |
| | | 146 | | |
| | | 147 | | // Extract the preferred fee rate from the JSON response |
| | 8 | 148 | | if (!root.TryGetProperty(_feeEstimationOptions.PreferredFeeRate, out var feeRateElement)) |
| | | 149 | | { |
| | 0 | 150 | | throw new InvalidOperationException( |
| | 0 | 151 | | $"Could not extract {_feeEstimationOptions.PreferredFeeRate} from API response."); |
| | | 152 | | } |
| | | 153 | | |
| | | 154 | | // Parse the fee rate value |
| | 8 | 155 | | if (!feeRateElement.TryGetDecimal(out var feeRate)) |
| | | 156 | | { |
| | 0 | 157 | | throw new InvalidOperationException( |
| | 0 | 158 | | $"Could not extract {_feeEstimationOptions.PreferredFeeRate} from API response."); |
| | | 159 | | } |
| | | 160 | | |
| | | 161 | | // Apply the multiplier to convert to sat/kw |
| | 8 | 162 | | if (decimal.TryParse(_feeEstimationOptions.RateMultiplier, out var multiplier)) |
| | | 163 | | { |
| | 8 | 164 | | return (long)(feeRate * multiplier); |
| | | 165 | | } |
| | | 166 | | |
| | 0 | 167 | | throw new InvalidOperationException( |
| | 0 | 168 | | $"Could not extract {_feeEstimationOptions.PreferredFeeRate} from API response."); |
| | 8 | 169 | | } |
| | | 170 | | |
| | | 171 | | private async Task RunPeriodicRefreshAsync(CancellationToken cancellationToken) |
| | | 172 | | { |
| | | 173 | | try |
| | | 174 | | { |
| | 12 | 175 | | while (!cancellationToken.IsCancellationRequested) |
| | | 176 | | { |
| | | 177 | | // Refresh if it's not canceled |
| | 12 | 178 | | if (!cancellationToken.IsCancellationRequested) |
| | | 179 | | { |
| | 12 | 180 | | await RefreshFeeRateAsync(cancellationToken); |
| | | 181 | | |
| | | 182 | | // Wait for the cache time or until cancellation |
| | 12 | 183 | | await Task.Delay(_cacheTimeExpiration, cancellationToken); |
| | | 184 | | } |
| | | 185 | | } |
| | 0 | 186 | | } |
| | 4 | 187 | | catch (OperationCanceledException) |
| | | 188 | | { |
| | 4 | 189 | | _logger.LogInformation("Stopping fee service"); |
| | 4 | 190 | | } |
| | 0 | 191 | | catch (Exception ex) |
| | | 192 | | { |
| | 0 | 193 | | _logger.LogError(ex, "Unhandled exception in fee service"); |
| | 0 | 194 | | } |
| | 4 | 195 | | } |
| | | 196 | | |
| | | 197 | | private Task SaveToFileAsync() |
| | | 198 | | { |
| | 8 | 199 | | _logger.LogDebug("Saving fee rate to file {filePath}", _cacheFilePath); |
| | | 200 | | |
| | 8 | 201 | | return Task.CompletedTask; |
| | | 202 | | // try |
| | | 203 | | // { |
| | | 204 | | // var cacheData = new FeeRateCacheData |
| | | 205 | | // { |
| | | 206 | | // FeeRate = _cachedFeeRate, |
| | | 207 | | // LastFetchTime = _lastFetchTime |
| | | 208 | | // }; |
| | | 209 | | // |
| | | 210 | | // await using var fileStream = File.OpenWrite(_cacheFilePath); |
| | | 211 | | // await MessagePackSerializer.SerializeAsync(fileStream, cacheData, cancellationToken: CancellationToken.No |
| | | 212 | | // } |
| | | 213 | | // catch (Exception e) |
| | | 214 | | // { |
| | | 215 | | // _logger.LogError(e, "Error saving fee rate to file"); |
| | | 216 | | // } |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | private Task LoadFromFileAsync() |
| | | 220 | | { |
| | 20 | 221 | | _logger.LogDebug("Loading fee rate from file {filePath}", _cacheFilePath); |
| | | 222 | | |
| | 20 | 223 | | return Task.CompletedTask; |
| | | 224 | | // try |
| | | 225 | | // { |
| | | 226 | | // if (!File.Exists(_cacheFilePath)) |
| | | 227 | | // { |
| | | 228 | | // _logger.LogDebug("Fee rate cache file does not exist. Skipping load."); |
| | | 229 | | // return; |
| | | 230 | | // } |
| | | 231 | | // |
| | | 232 | | // await using var fileStream = File.OpenRead(_cacheFilePath); |
| | | 233 | | // var cacheData = |
| | | 234 | | // await MessagePackSerializer.DeserializeAsync<FeeRateCacheData?>(fileStream, |
| | | 235 | | // cancellationToken: cancellationToken); |
| | | 236 | | // |
| | | 237 | | // if (cacheData == null) |
| | | 238 | | // { |
| | | 239 | | // _logger.LogDebug("Fee rate cache file is empty. Skipping load."); |
| | | 240 | | // return; |
| | | 241 | | // } |
| | | 242 | | // |
| | | 243 | | // _cachedFeeRate = cacheData.FeeRate; |
| | | 244 | | // _lastFetchTime = cacheData.LastFetchTime; |
| | | 245 | | // } |
| | | 246 | | // catch (OperationCanceledException) |
| | | 247 | | // { |
| | | 248 | | // // Ignore cancellation |
| | | 249 | | // } |
| | | 250 | | // catch (Exception e) |
| | | 251 | | // { |
| | | 252 | | // _logger.LogError(e, "Error loading fee rate from file"); |
| | | 253 | | // } |
| | | 254 | | } |
| | | 255 | | |
| | | 256 | | private bool IsCacheValid() |
| | | 257 | | { |
| | 16 | 258 | | return !_cachedFeeRate.IsZero && DateTime.UtcNow.Subtract(_lastFetchTime).CompareTo(_cacheTimeExpiration) <= 0; |
| | | 259 | | } |
| | | 260 | | |
| | | 261 | | private static TimeSpan ParseCacheTime(string cacheTime) |
| | | 262 | | { |
| | | 263 | | try |
| | | 264 | | { |
| | | 265 | | // Parse formats like "5m", "1hour", "30s" |
| | 20 | 266 | | var valueStr = new string(cacheTime.Where(char.IsDigit).ToArray()); |
| | 20 | 267 | | var unit = new string(cacheTime.Where(char.IsLetter).ToArray()).ToLowerInvariant(); |
| | | 268 | | |
| | 20 | 269 | | if (!int.TryParse(valueStr, out var value)) |
| | 0 | 270 | | return s_defaultCacheExpiration; |
| | | 271 | | |
| | 20 | 272 | | return unit switch |
| | 20 | 273 | | { |
| | 4 | 274 | | "s" or "second" or "seconds" => TimeSpan.FromSeconds(value), |
| | 16 | 275 | | "m" or "minute" or "minutes" => TimeSpan.FromMinutes(value), |
| | 0 | 276 | | "h" or "hour" or "hours" => TimeSpan.FromHours(value), |
| | 0 | 277 | | "d" or "day" or "days" => TimeSpan.FromDays(value), |
| | 0 | 278 | | _ => TimeSpan.FromMinutes(5) |
| | 20 | 279 | | }; |
| | | 280 | | } |
| | 0 | 281 | | catch |
| | | 282 | | { |
| | 0 | 283 | | return s_defaultCacheExpiration; // Default on error |
| | | 284 | | } |
| | 20 | 285 | | } |
| | | 286 | | |
| | | 287 | | private static string ParseFilePath(FeeEstimationOptions feeEstimationOptions) |
| | | 288 | | { |
| | 20 | 289 | | var filePath = feeEstimationOptions.CacheFile; |
| | 20 | 290 | | if (string.IsNullOrWhiteSpace(filePath)) |
| | | 291 | | { |
| | 0 | 292 | | return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FeeCacheFileName); |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | // Check if the file path is absolute or relative |
| | 20 | 296 | | return Path.IsPathRooted(filePath) |
| | 20 | 297 | | ? filePath |
| | 20 | 298 | | : Path.Combine(Directory.GetCurrentDirectory(), |
| | 20 | 299 | | filePath); // If it's relative, combine it with the current directory |
| | | 300 | | } |
| | | 301 | | } |