|
| 1 | +using System.Net.Http.Json; |
| 2 | +using System.Text; |
| 3 | +using System.Text.Json; |
| 4 | +using System.Text.Json.Serialization; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using NArk.Abstractions.Blockchain; |
| 7 | +using NBitcoin; |
| 8 | + |
| 9 | +namespace NArk.Blockchain.Esplora; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// Broadcasts transactions via Esplora REST API. |
| 13 | +/// Supports single tx broadcast and package relay. |
| 14 | +/// </summary> |
| 15 | +public class EsploraOnchainBroadcaster : IOnchainBroadcaster |
| 16 | +{ |
| 17 | + private readonly HttpClient _httpClient; |
| 18 | + private readonly ILogger? _logger; |
| 19 | + |
| 20 | + public EsploraOnchainBroadcaster(Uri baseUri, ILogger<EsploraOnchainBroadcaster>? logger = null) |
| 21 | + { |
| 22 | + _httpClient = new HttpClient { BaseAddress = baseUri }; |
| 23 | + _logger = logger; |
| 24 | + } |
| 25 | + |
| 26 | + public EsploraOnchainBroadcaster(HttpClient httpClient, ILogger<EsploraOnchainBroadcaster>? logger = null) |
| 27 | + { |
| 28 | + _httpClient = httpClient; |
| 29 | + _logger = logger; |
| 30 | + } |
| 31 | + |
| 32 | + public async Task<bool> BroadcastAsync(Transaction tx, CancellationToken cancellationToken = default) |
| 33 | + { |
| 34 | + try |
| 35 | + { |
| 36 | + var content = new StringContent(tx.ToHex(), Encoding.UTF8, "text/plain"); |
| 37 | + var response = await _httpClient.PostAsync("tx", content, cancellationToken); |
| 38 | + |
| 39 | + if (!response.IsSuccessStatusCode) |
| 40 | + { |
| 41 | + var error = await response.Content.ReadAsStringAsync(cancellationToken); |
| 42 | + _logger?.LogWarning("Esplora broadcast failed for tx {Txid}: {Error}", |
| 43 | + tx.GetHash(), error); |
| 44 | + return false; |
| 45 | + } |
| 46 | + |
| 47 | + return true; |
| 48 | + } |
| 49 | + catch (Exception ex) |
| 50 | + { |
| 51 | + _logger?.LogWarning(0, ex, "Failed to broadcast tx {Txid} via Esplora", tx.GetHash()); |
| 52 | + return false; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public async Task<bool> BroadcastPackageAsync( |
| 57 | + Transaction parent, Transaction child, CancellationToken cancellationToken = default) |
| 58 | + { |
| 59 | + try |
| 60 | + { |
| 61 | + var package = new[] { parent.ToHex(), child.ToHex() }; |
| 62 | + var response = await _httpClient.PostAsJsonAsync("txs/package", package, cancellationToken); |
| 63 | + |
| 64 | + if (!response.IsSuccessStatusCode) |
| 65 | + { |
| 66 | + var error = await response.Content.ReadAsStringAsync(cancellationToken); |
| 67 | + _logger?.LogWarning("Esplora package broadcast failed: {Error}", error); |
| 68 | + return false; |
| 69 | + } |
| 70 | + |
| 71 | + return true; |
| 72 | + } |
| 73 | + catch (Exception ex) |
| 74 | + { |
| 75 | + _logger?.LogWarning(0, ex, "Failed to broadcast package via Esplora"); |
| 76 | + return false; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + public async Task<TxStatus> GetTxStatusAsync( |
| 81 | + uint256 txid, CancellationToken cancellationToken = default) |
| 82 | + { |
| 83 | + try |
| 84 | + { |
| 85 | + var response = await _httpClient.GetAsync( |
| 86 | + $"tx/{txid}/status", cancellationToken); |
| 87 | + |
| 88 | + if (!response.IsSuccessStatusCode) |
| 89 | + return new TxStatus(false, null, false); |
| 90 | + |
| 91 | + var status = await response.Content.ReadFromJsonAsync<EsploraTxStatus>( |
| 92 | + cancellationToken: cancellationToken); |
| 93 | + |
| 94 | + if (status is null) |
| 95 | + return new TxStatus(false, null, false); |
| 96 | + |
| 97 | + return new TxStatus( |
| 98 | + status.Confirmed, |
| 99 | + status.Confirmed ? (uint?)status.BlockHeight : null, |
| 100 | + !status.Confirmed); |
| 101 | + } |
| 102 | + catch |
| 103 | + { |
| 104 | + return new TxStatus(false, null, false); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + public async Task<FeeRate> EstimateFeeRateAsync( |
| 109 | + int confirmTarget = 6, CancellationToken cancellationToken = default) |
| 110 | + { |
| 111 | + try |
| 112 | + { |
| 113 | + var response = await _httpClient.GetAsync("fee-estimates", cancellationToken); |
| 114 | + response.EnsureSuccessStatusCode(); |
| 115 | + |
| 116 | + var estimates = await response.Content.ReadFromJsonAsync<Dictionary<string, double>>( |
| 117 | + cancellationToken: cancellationToken); |
| 118 | + |
| 119 | + if (estimates is null) |
| 120 | + return new FeeRate(Money.Satoshis(2)); |
| 121 | + |
| 122 | + // Find the closest target |
| 123 | + var targetStr = confirmTarget.ToString(); |
| 124 | + if (estimates.TryGetValue(targetStr, out var rate)) |
| 125 | + return new FeeRate(Money.Satoshis((long)Math.Ceiling(rate))); |
| 126 | + |
| 127 | + // Fallback to nearest available target |
| 128 | + var closest = estimates |
| 129 | + .Select(kvp => (Target: int.TryParse(kvp.Key, out var t) ? t : int.MaxValue, Rate: kvp.Value)) |
| 130 | + .Where(x => x.Target != int.MaxValue) |
| 131 | + .OrderBy(x => Math.Abs(x.Target - confirmTarget)) |
| 132 | + .FirstOrDefault(); |
| 133 | + |
| 134 | + return closest.Rate > 0 |
| 135 | + ? new FeeRate(Money.Satoshis((long)Math.Ceiling(closest.Rate))) |
| 136 | + : new FeeRate(Money.Satoshis(2)); |
| 137 | + } |
| 138 | + catch (Exception ex) |
| 139 | + { |
| 140 | + _logger?.LogWarning(0, ex, "Failed to estimate fee rate via Esplora, using fallback"); |
| 141 | + return new FeeRate(Money.Satoshis(2)); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + private class EsploraTxStatus |
| 146 | + { |
| 147 | + [JsonPropertyName("confirmed")] |
| 148 | + public bool Confirmed { get; set; } |
| 149 | + |
| 150 | + [JsonPropertyName("block_height")] |
| 151 | + public long BlockHeight { get; set; } |
| 152 | + } |
| 153 | +} |
0 commit comments