| | | 1 | | using System.Buffers; |
| | | 2 | | using System.IO.Pipes; |
| | | 3 | | using MessagePack; |
| | | 4 | | using NLightning.Domain.Channels.ValueObjects; |
| | | 5 | | |
| | | 6 | | namespace NLightning.Client.Ipc; |
| | | 7 | | |
| | | 8 | | using Domain.Bitcoin.Enums; |
| | | 9 | | using Domain.Client.Enums; |
| | | 10 | | using Domain.Money; |
| | | 11 | | using Domain.Node.ValueObjects; |
| | | 12 | | using Transport.Ipc; |
| | | 13 | | using Transport.Ipc.Requests; |
| | | 14 | | using Transport.Ipc.Responses; |
| | | 15 | | |
| | | 16 | | public sealed class NamedPipeIpcClient : IAsyncDisposable |
| | | 17 | | { |
| | | 18 | | private readonly string _namedPipeFilePath; |
| | | 19 | | private readonly string _cookieFilePath; |
| | | 20 | | private readonly string _server; |
| | | 21 | | |
| | 0 | 22 | | public NamedPipeIpcClient(string namedPipeFilePath, string cookieFilePath, string server = ".") |
| | 0 | 23 | | { |
| | 0 | 24 | | _namedPipeFilePath = namedPipeFilePath; |
| | 0 | 25 | | _cookieFilePath = cookieFilePath; |
| | 0 | 26 | | _server = server; |
| | 0 | 27 | | } |
| | | 28 | | |
| | | 29 | | public async Task<NodeInfoIpcResponse> GetNodeInfoAsync(CancellationToken ct = default) |
| | 0 | 30 | | { |
| | 0 | 31 | | var req = new NodeInfoIpcRequest(); |
| | 0 | 32 | | var payload = MessagePackSerializer.Serialize(req, cancellationToken: ct); |
| | 0 | 33 | | var env = new IpcEnvelope |
| | 0 | 34 | | { |
| | 0 | 35 | | Version = 1, |
| | 0 | 36 | | Command = ClientCommand.NodeInfo, |
| | 0 | 37 | | CorrelationId = Guid.NewGuid(), |
| | 0 | 38 | | AuthToken = await GetAuthTokenAsync(ct), |
| | 0 | 39 | | Payload = payload, |
| | 0 | 40 | | Kind = 0 |
| | 0 | 41 | | }; |
| | | 42 | | |
| | 0 | 43 | | var respEnv = await SendAsync(env, ct); |
| | 0 | 44 | | if (respEnv.Kind != IpcEnvelopeKind.Error) |
| | 0 | 45 | | return MessagePackSerializer.Deserialize<NodeInfoIpcResponse>(respEnv.Payload, cancellationToken: ct); |
| | | 46 | | |
| | 0 | 47 | | var err = MessagePackSerializer.Deserialize<IpcError>(respEnv.Payload, cancellationToken: ct); |
| | 0 | 48 | | throw new InvalidOperationException($"IPC error {err.Code}: {err.Message}"); |
| | 0 | 49 | | } |
| | | 50 | | |
| | | 51 | | public async Task<ConnectPeerIpcResponse> ConnectPeerAsync(string address, CancellationToken ct = default) |
| | 0 | 52 | | { |
| | 0 | 53 | | var req = new ConnectPeerIpcRequest |
| | 0 | 54 | | { |
| | 0 | 55 | | Address = new PeerAddressInfo(address) |
| | 0 | 56 | | }; |
| | 0 | 57 | | var payload = MessagePackSerializer.Serialize(req, cancellationToken: ct); |
| | 0 | 58 | | var env = new IpcEnvelope |
| | 0 | 59 | | { |
| | 0 | 60 | | Version = 1, |
| | 0 | 61 | | Command = ClientCommand.ConnectPeer, |
| | 0 | 62 | | CorrelationId = Guid.NewGuid(), |
| | 0 | 63 | | AuthToken = await GetAuthTokenAsync(ct), |
| | 0 | 64 | | Payload = payload, |
| | 0 | 65 | | Kind = 0 |
| | 0 | 66 | | }; |
| | | 67 | | |
| | 0 | 68 | | var respEnv = await SendAsync(env, ct); |
| | 0 | 69 | | if (respEnv.Kind != IpcEnvelopeKind.Error) |
| | 0 | 70 | | return MessagePackSerializer.Deserialize<ConnectPeerIpcResponse>(respEnv.Payload, cancellationToken: ct); |
| | | 71 | | |
| | 0 | 72 | | var err = MessagePackSerializer.Deserialize<IpcError>(respEnv.Payload, cancellationToken: ct); |
| | 0 | 73 | | throw new InvalidOperationException($"IPC error {err.Code}: {err.Message}"); |
| | 0 | 74 | | } |
| | | 75 | | |
| | | 76 | | public async Task<ListPeersIpcResponse> ListPeersAsync(CancellationToken ct = default) |
| | 0 | 77 | | { |
| | 0 | 78 | | var req = new ListPeersIpcRequest(); |
| | 0 | 79 | | var payload = MessagePackSerializer.Serialize(req, cancellationToken: ct); |
| | 0 | 80 | | var env = new IpcEnvelope |
| | 0 | 81 | | { |
| | 0 | 82 | | Version = 1, |
| | 0 | 83 | | Command = ClientCommand.ListPeers, |
| | 0 | 84 | | CorrelationId = Guid.NewGuid(), |
| | 0 | 85 | | AuthToken = await GetAuthTokenAsync(ct), |
| | 0 | 86 | | Payload = payload, |
| | 0 | 87 | | Kind = IpcEnvelopeKind.Request |
| | 0 | 88 | | }; |
| | | 89 | | |
| | 0 | 90 | | var respEnv = await SendAsync(env, ct); |
| | 0 | 91 | | if (respEnv.Kind != IpcEnvelopeKind.Error) |
| | 0 | 92 | | return MessagePackSerializer.Deserialize<ListPeersIpcResponse>(respEnv.Payload, cancellationToken: ct); |
| | | 93 | | |
| | 0 | 94 | | var err = MessagePackSerializer.Deserialize<IpcError>(respEnv.Payload, cancellationToken: ct); |
| | 0 | 95 | | throw new InvalidOperationException($"IPC error {err.Code}: {err.Message}"); |
| | 0 | 96 | | } |
| | | 97 | | |
| | | 98 | | public async Task<GetAddressIpcResponse> GetAddressAsync(string? addressTypeString, CancellationToken ct = default) |
| | 0 | 99 | | { |
| | 0 | 100 | | var addressType = AddressType.P2Tr; |
| | 0 | 101 | | if (!string.IsNullOrWhiteSpace(addressTypeString)) |
| | 0 | 102 | | { |
| | 0 | 103 | | addressType = addressTypeString.ToLowerInvariant() switch |
| | 0 | 104 | | { |
| | 0 | 105 | | "p2tr" => AddressType.P2Tr, |
| | 0 | 106 | | "p2wpkh" => AddressType.P2Wpkh, |
| | 0 | 107 | | "all" => AddressType.P2Tr | AddressType.P2Wpkh, |
| | 0 | 108 | | _ => throw new ArgumentOutOfRangeException(nameof(addressTypeString), addressTypeString, |
| | 0 | 109 | | "Address has to be `p2tr`, `p2wpkh`, or `all`.") |
| | 0 | 110 | | }; |
| | 0 | 111 | | } |
| | | 112 | | |
| | 0 | 113 | | var req = new GetAddressIpcRequest { AddressType = addressType }; |
| | 0 | 114 | | var payload = MessagePackSerializer.Serialize(req, cancellationToken: ct); |
| | 0 | 115 | | var env = new IpcEnvelope |
| | 0 | 116 | | { |
| | 0 | 117 | | Version = 1, |
| | 0 | 118 | | Command = ClientCommand.GetAddress, |
| | 0 | 119 | | CorrelationId = Guid.NewGuid(), |
| | 0 | 120 | | AuthToken = await GetAuthTokenAsync(ct), |
| | 0 | 121 | | Payload = payload, |
| | 0 | 122 | | Kind = IpcEnvelopeKind.Request |
| | 0 | 123 | | }; |
| | | 124 | | |
| | 0 | 125 | | var respEnv = await SendAsync(env, ct); |
| | 0 | 126 | | if (respEnv.Kind != IpcEnvelopeKind.Error) |
| | 0 | 127 | | return MessagePackSerializer.Deserialize<GetAddressIpcResponse>(respEnv.Payload, cancellationToken: ct); |
| | | 128 | | |
| | 0 | 129 | | var err = MessagePackSerializer.Deserialize<IpcError>(respEnv.Payload, cancellationToken: ct); |
| | 0 | 130 | | throw new InvalidOperationException($"IPC error {err.Code}: {err.Message}"); |
| | 0 | 131 | | } |
| | | 132 | | |
| | | 133 | | public async Task<WalletBalanceIpcResponse> GetWalletBalance(CancellationToken ct) |
| | 0 | 134 | | { |
| | 0 | 135 | | var req = new WalletBalanceIpcRequest(); |
| | 0 | 136 | | var payload = MessagePackSerializer.Serialize(req, cancellationToken: ct); |
| | 0 | 137 | | var env = new IpcEnvelope |
| | 0 | 138 | | { |
| | 0 | 139 | | Version = 1, |
| | 0 | 140 | | Command = ClientCommand.WalletBalance, |
| | 0 | 141 | | CorrelationId = Guid.NewGuid(), |
| | 0 | 142 | | AuthToken = await GetAuthTokenAsync(ct), |
| | 0 | 143 | | Payload = payload, |
| | 0 | 144 | | Kind = 0 |
| | 0 | 145 | | }; |
| | | 146 | | |
| | 0 | 147 | | var respEnv = await SendAsync(env, ct); |
| | 0 | 148 | | if (respEnv.Kind != IpcEnvelopeKind.Error) |
| | 0 | 149 | | return MessagePackSerializer.Deserialize<WalletBalanceIpcResponse>(respEnv.Payload, cancellationToken: ct); |
| | | 150 | | |
| | 0 | 151 | | var err = MessagePackSerializer.Deserialize<IpcError>(respEnv.Payload, cancellationToken: ct); |
| | 0 | 152 | | throw new InvalidOperationException($"IPC error {err.Code}: {err.Message}"); |
| | 0 | 153 | | } |
| | | 154 | | |
| | | 155 | | public async Task<OpenChannelIpcResponse> OpenChannelAsync(string nodeInfo, string amountSats, |
| | | 156 | | CancellationToken ct = default) |
| | 0 | 157 | | { |
| | 0 | 158 | | var req = new OpenChannelIpcRequest |
| | 0 | 159 | | { |
| | 0 | 160 | | NodeInfo = nodeInfo, |
| | 0 | 161 | | Amount = LightningMoney.Satoshis(Convert.ToInt64(amountSats)) |
| | 0 | 162 | | }; |
| | 0 | 163 | | var payload = MessagePackSerializer.Serialize(req, cancellationToken: ct); |
| | 0 | 164 | | var env = new IpcEnvelope |
| | 0 | 165 | | { |
| | 0 | 166 | | Version = 1, |
| | 0 | 167 | | Command = ClientCommand.OpenChannel, |
| | 0 | 168 | | CorrelationId = Guid.NewGuid(), |
| | 0 | 169 | | AuthToken = await GetAuthTokenAsync(ct), |
| | 0 | 170 | | Payload = payload, |
| | 0 | 171 | | Kind = 0 |
| | 0 | 172 | | }; |
| | | 173 | | |
| | 0 | 174 | | var respEnv = await SendAsync(env, ct); |
| | 0 | 175 | | if (respEnv.Kind != IpcEnvelopeKind.Error) |
| | 0 | 176 | | return MessagePackSerializer.Deserialize<OpenChannelIpcResponse>(respEnv.Payload, cancellationToken: ct); |
| | | 177 | | |
| | 0 | 178 | | var err = MessagePackSerializer.Deserialize<IpcError>(respEnv.Payload, cancellationToken: ct); |
| | 0 | 179 | | throw new InvalidOperationException($"IPC error {err.Code}: {err.Message}"); |
| | 0 | 180 | | } |
| | | 181 | | |
| | | 182 | | public async Task<OpenChannelSubscriptionIpcResponse> OpenChannelSubscriptionAsync( |
| | | 183 | | ChannelId channelId, CancellationToken ct = default) |
| | 0 | 184 | | { |
| | 0 | 185 | | var req = new OpenChannelSubscriptionIpcRequest |
| | 0 | 186 | | { |
| | 0 | 187 | | ChannelId = channelId |
| | 0 | 188 | | }; |
| | 0 | 189 | | var payload = MessagePackSerializer.Serialize(req, cancellationToken: ct); |
| | 0 | 190 | | var env = new IpcEnvelope |
| | 0 | 191 | | { |
| | 0 | 192 | | Version = 1, |
| | 0 | 193 | | Command = ClientCommand.OpenChannelSubscription, |
| | 0 | 194 | | CorrelationId = Guid.NewGuid(), |
| | 0 | 195 | | AuthToken = await GetAuthTokenAsync(ct), |
| | 0 | 196 | | Payload = payload, |
| | 0 | 197 | | Kind = 0 |
| | 0 | 198 | | }; |
| | | 199 | | |
| | 0 | 200 | | var respEnv = await SendAsync(env, ct); |
| | 0 | 201 | | if (respEnv.Kind != IpcEnvelopeKind.Error) |
| | 0 | 202 | | return MessagePackSerializer.Deserialize<OpenChannelSubscriptionIpcResponse>( |
| | 0 | 203 | | respEnv.Payload, cancellationToken: ct); |
| | | 204 | | |
| | 0 | 205 | | var err = MessagePackSerializer.Deserialize<IpcError>(respEnv.Payload, cancellationToken: ct); |
| | 0 | 206 | | throw new InvalidOperationException($"IPC error {err.Code}: {err.Message}"); |
| | 0 | 207 | | } |
| | | 208 | | |
| | | 209 | | private async Task<IpcEnvelope> SendAsync(IpcEnvelope envelope, CancellationToken ct) |
| | 0 | 210 | | { |
| | 0 | 211 | | await using var client = |
| | 0 | 212 | | new NamedPipeClientStream(_server, _namedPipeFilePath, PipeDirection.InOut, PipeOptions.Asynchronous); |
| | | 213 | | |
| | | 214 | | try |
| | 0 | 215 | | { |
| | 0 | 216 | | await client.ConnectAsync(TimeSpan.FromSeconds(2), ct); |
| | 0 | 217 | | } |
| | 0 | 218 | | catch (TimeoutException) |
| | 0 | 219 | | { |
| | 0 | 220 | | throw new IOException( |
| | 0 | 221 | | "Could not connect to NLightning node IPC pipe. Ensure the node is running and listening for IPC."); |
| | | 222 | | } |
| | | 223 | | |
| | | 224 | | // Send request |
| | 0 | 225 | | var bytes = MessagePackSerializer.Serialize(envelope, cancellationToken: ct); |
| | 0 | 226 | | var lenPrefix = BitConverter.GetBytes(bytes.Length); |
| | 0 | 227 | | await client.WriteAsync(lenPrefix, ct); |
| | 0 | 228 | | await client.WriteAsync(bytes, ct); |
| | 0 | 229 | | await client.FlushAsync(ct); |
| | | 230 | | |
| | | 231 | | // Read response length |
| | 0 | 232 | | var header = new byte[4]; |
| | 0 | 233 | | await ReadExactAsync(client, header, ct); |
| | 0 | 234 | | var respLen = BitConverter.ToInt32(header, 0); |
| | 0 | 235 | | if (respLen is <= 0 or > 10_000_000) |
| | 0 | 236 | | throw new IOException("Invalid IPC response length."); |
| | | 237 | | |
| | | 238 | | // Read payload |
| | 0 | 239 | | var respBuf = ArrayPool<byte>.Shared.Rent(respLen); |
| | | 240 | | try |
| | 0 | 241 | | { |
| | 0 | 242 | | await ReadExactAsync(client, respBuf.AsMemory(0, respLen), ct); |
| | 0 | 243 | | var env = MessagePackSerializer.Deserialize<IpcEnvelope>(respBuf.AsMemory(0, respLen), |
| | 0 | 244 | | cancellationToken: ct); |
| | 0 | 245 | | return env; |
| | | 246 | | } |
| | | 247 | | finally |
| | 0 | 248 | | { |
| | 0 | 249 | | ArrayPool<byte>.Shared.Return(respBuf); |
| | 0 | 250 | | } |
| | 0 | 251 | | } |
| | | 252 | | |
| | | 253 | | private static async Task ReadExactAsync(Stream stream, Memory<byte> buffer, CancellationToken ct) |
| | 0 | 254 | | { |
| | 0 | 255 | | var total = 0; |
| | 0 | 256 | | while (total < buffer.Length) |
| | 0 | 257 | | { |
| | 0 | 258 | | var read = await stream.ReadAsync(buffer[total..], ct); |
| | 0 | 259 | | if (read == 0) throw new EndOfStreamException(); |
| | 0 | 260 | | total += read; |
| | 0 | 261 | | } |
| | 0 | 262 | | } |
| | | 263 | | |
| | | 264 | | private static async Task ReadExactAsync(Stream stream, byte[] buffer, CancellationToken ct) |
| | 0 | 265 | | => await ReadExactAsync(stream, buffer.AsMemory(), ct); |
| | | 266 | | |
| | | 267 | | private async Task<string> GetAuthTokenAsync(CancellationToken ct) |
| | 0 | 268 | | { |
| | 0 | 269 | | if (!File.Exists(_cookieFilePath)) |
| | 0 | 270 | | throw new IOException( |
| | 0 | 271 | | "Authentication cookie file not found. Ensure the node is running and the cookie file path is correct.") |
| | | 272 | | |
| | 0 | 273 | | var content = await File.ReadAllTextAsync(_cookieFilePath, ct); |
| | 0 | 274 | | return content.Trim(); |
| | 0 | 275 | | } |
| | | 276 | | |
| | | 277 | | public ValueTask DisposeAsync() |
| | 0 | 278 | | => ValueTask.CompletedTask; |
| | | 279 | | } |