-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathTonClient.cs
416 lines (339 loc) · 14.3 KB
/
TonClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text.Json.Nodes;
using Microsoft.Extensions.Logging;
using TonLibDotNet.Requests;
using TonLibDotNet.Types;
namespace TonLibDotNet
{
public class TonClient : ITonClient, IDisposable
{
private readonly ILogger logger;
private readonly TonOptions tonOptions;
private readonly SemaphoreSlim syncRoot = new (1);
private IntPtr? client;
private bool initialized;
private bool needReinit;
private bool isDisposed;
static TonClient()
{
TonLibResolver.Register(typeof(TonClient).Assembly);
}
public TonClient(ILogger<TonClient> logger, Microsoft.Extensions.Options.IOptions<TonOptions> options)
{
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.tonOptions = options?.Value ?? throw new ArgumentNullException(nameof(options));
}
[DllImport(TonLibResolver.DllNamePlaceholder, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr tonlib_client_json_create();
[DllImport(TonLibResolver.DllNamePlaceholder, CallingConvention = CallingConvention.Cdecl)]
private static extern void tonlib_client_json_destroy(IntPtr client);
[DllImport(TonLibResolver.DllNamePlaceholder, CallingConvention = CallingConvention.Cdecl)]
private static extern void tonlib_client_set_verbosity_level(int level);
[DllImport(TonLibResolver.DllNamePlaceholder, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr tonlib_client_json_execute(IntPtr client, [MarshalAs(UnmanagedType.LPStr)] string request);
[DllImport(TonLibResolver.DllNamePlaceholder, CallingConvention = CallingConvention.Cdecl)]
private static extern void tonlib_client_json_send(IntPtr client, [MarshalAs(UnmanagedType.LPStr)] string request);
[DllImport(TonLibResolver.DllNamePlaceholder, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr tonlib_client_json_receive(IntPtr client, double timeout);
public OptionsInfo? OptionsInfo { get; private set; }
/// <inheritdoc />
public int SyncStateCurrentSeqno { get; private set; }
/// <summary>
/// Add assembly with additional <see cref="TypeBase"/> classes for LiteServer interaction.
/// </summary>
/// <param name="assembly">Assembly to add</param>
public static void RegisterAssembly(System.Reflection.Assembly assembly)
{
TonTypeResolver.AdditionalAsseblies.Add(assembly);
}
/// <inheritdoc />
public async Task<OptionsInfo?> InitIfNeeded(CancellationToken cancellationToken = default)
{
if (needReinit)
{
logger.LogDebug("Reinitializing...");
if (!await syncRoot.WaitAsync(tonOptions.ConcurrencyTimeout, cancellationToken))
{
throw new TimeoutException("Failed while waiting for semaphore");
}
if (client != null)
{
tonlib_client_json_destroy(client.Value);
client = null;
}
initialized = false;
needReinit = false;
syncRoot.Release();
}
if (initialized)
{
return null;
}
string fullConfig;
var localConfigSource = tonOptions.UseMainnet ? tonOptions.ConfigPathLocalMainnet : tonOptions.ConfigPathLocalTestnet;
if (!string.IsNullOrEmpty(localConfigSource))
{
fullConfig = await File.ReadAllTextAsync(localConfigSource, cancellationToken);
logger.LogDebug("Used local config file: {Name}", localConfigSource);
}
else
{
var remoteConfigSource = tonOptions.UseMainnet ? tonOptions.ConfigPathMainnet : tonOptions.ConfigPathTestnet;
using var httpClient = new HttpClient();
fullConfig = await httpClient.GetStringAsync(remoteConfigSource, cancellationToken).ConfigureAwait(false);
logger.LogDebug("Used internet config file: {Url}", remoteConfigSource);
}
var jdoc = JsonNode.Parse(fullConfig);
var servers = jdoc["liteservers"].AsArray();
var choosen = tonOptions.LiteServerSelector(servers);
servers.Clear();
servers.Add(choosen);
logger.LogInformation("LiteServer choosen: ip={IP}, port={Port}, key={Key}", choosen["ip"], choosen["port"], choosen["id"]?["key"]);
tonOptions.Options.Config.ConfigJson = jdoc.ToJsonString();
OptionsInfo = await Execute(new Init(tonOptions.Options), cancellationToken);
return OptionsInfo;
}
/// <inheritdoc />
public virtual void Deinit()
{
logger.LogWarning("De-initializing.");
needReinit = true;
}
/// <inheritdoc />
public Task<OptionsInfo?> Reinit(CancellationToken cancellationToken = default)
{
Deinit();
return InitIfNeeded(cancellationToken);
}
/// <inheritdoc />
public async Task<TResponse> Execute<TResponse>(RequestBase<TResponse> request, CancellationToken cancellationToken = default)
where TResponse : TypeBase
{
if (client == null)
{
if (!await syncRoot.WaitAsync(tonOptions.ConcurrencyTimeout, cancellationToken))
{
throw new TimeoutException("Failed while waiting for semaphore");
}
try
{
if (client == null)
{
tonlib_client_set_verbosity_level(tonOptions.VerbosityLevel);
client = tonlib_client_json_create();
initialized = false;
}
}
finally
{
syncRoot.Release();
}
}
if (request.IsStatic)
{
return ExecuteInternalStatic(request);
}
if (!initialized && request is not Init)
{
throw new InvalidOperationException($"Must call {nameof(InitIfNeeded)}() first");
}
if (!await syncRoot.WaitAsync(tonOptions.ConcurrencyTimeout, cancellationToken))
{
throw new TimeoutException("Failed while waiting for semaphore");
}
try
{
var res = await ExecuteInternalAsync(request, cancellationToken);
if (request is Init)
{
initialized = true;
}
return res;
}
finally
{
syncRoot.Release();
}
}
public decimal ConvertFromNanoTon(long nano)
{
return TonUtils.Coins.FromNano(nano);
}
public long ConvertToNanoTon(decimal ton)
{
return TonUtils.Coins.ToNano(ton);
}
[return: NotNullIfNotNull("source")]
public string? EncodeStringAsBase64(string? source)
{
return TonUtils.Text.EncodeAsBase64(source);
}
public bool TryDecodeBase64AsString(string? source, [NotNullWhen(true)] out string? result)
{
return TonUtils.Text.TryDecodeBase64(source, out result);
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
~TonClient()
{
Dispose(disposing: false);
}
protected async Task<TResponse> ExecuteInternalAsync<TResponse>(RequestBase<TResponse> request, CancellationToken cancellationToken = default)
where TResponse : TypeBase
{
if (client == null)
{
throw new InvalidOperationException("Client not connected");
}
if (request.IsStatic)
{
throw new InvalidOperationException("This request must be sent as 'static'");
}
var reqText = tonOptions.Serializer.Serialize(request);
if (tonOptions.LogTextLimit > 0 && reqText.Length > tonOptions.LogTextLimit)
{
logger.LogDebug("Sending (trimmed from {Length} chars): {Text}...", reqText.Length, reqText[..tonOptions.LogTextLimit]);
}
else
{
logger.LogDebug("Sending: {Text}", reqText);
}
tonlib_client_json_send(client.Value, reqText);
var endOfLoop = DateTimeOffset.UtcNow.Add(request is Sync ? tonOptions.TonClientSyncTimeout : tonOptions.TonClientTimeout);
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var respTextPtr = tonlib_client_json_receive(client.Value, tonOptions.TonLibTimeout.TotalSeconds);
var respText = Marshal.PtrToStringAnsi(respTextPtr);
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(respText))
{
throw new TonClientException(0, "Empty response received");
}
if (tonOptions.LogTextLimit > 0 && respText.Length > tonOptions.LogTextLimit)
{
logger.LogDebug("Received (trimmed from {Length} chars): {Text}...", respText.Length, respText[..tonOptions.LogTextLimit]);
}
else
{
logger.LogDebug("Received: {Text}", respText);
}
var respObj = tonOptions.Serializer.Deserialize(respText);
if (respObj == null)
{
Deinit();
throw new TonClientException(0, "Failed to parse response as Json");
}
if (respObj is Error error)
{
if (error.Code == 500)
{
Deinit();
}
throw new TonClientException(error.Code, error.Message) { ActualAnswer = error };
}
if (respObj is UpdateSyncState uss)
{
if (uss.SyncState is UpdateSyncState.SyncStateDone)
{
// next 'receive' will give us required data!
continue;
}
if (uss.SyncState is UpdateSyncState.SyncStateInProgress ssip)
{
SyncStateCurrentSeqno = ssip.CurrentSeqno;
if (DateTimeOffset.UtcNow < endOfLoop)
{
var delay = (ssip.ToSeqno - ssip.CurrentSeqno) < 1000 ? 50 : 500;
await Task.Delay(delay, cancellationToken);
continue;
}
}
Deinit();
throw new TonClientException(0, "Failed to wait for sync to complete") { ActualAnswer = uss };
}
if (respObj is TResponse resp)
{
return resp;
}
Deinit();
throw new TonClientException(0, "Invalid (unexpected) response type") { ActualAnswer = respObj };
}
}
protected TResponse ExecuteInternalStatic<TResponse>(RequestBase<TResponse> request)
where TResponse : TypeBase
{
if (client == null)
{
throw new InvalidOperationException("Client not connected");
}
if (!request.IsStatic)
{
throw new InvalidOperationException("This request can not be sent as 'static'");
}
var reqText = tonOptions.Serializer.Serialize(request);
if (tonOptions.LogTextLimit > 0 && reqText.Length > tonOptions.LogTextLimit)
{
logger.LogDebug("Sending static (trimmed from {Length} chars): {Text}...", reqText.Length, reqText[..tonOptions.LogTextLimit]);
}
else
{
logger.LogDebug("Sending static: {Text}", reqText);
}
var respTextPtr = tonlib_client_json_execute(client.Value, reqText);
var respText = Marshal.PtrToStringAnsi(respTextPtr);
if (string.IsNullOrEmpty(respText))
{
throw new TonClientException(0, "Empty response received");
}
if (tonOptions.LogTextLimit > 0 && respText.Length > tonOptions.LogTextLimit)
{
logger.LogDebug("Received static (trimmed from {Length} chars): {Text}...", respText.Length, respText[..tonOptions.LogTextLimit]);
}
else
{
logger.LogDebug("Received static: {Text}", respText);
}
var respObj = tonOptions.Serializer.Deserialize(respText);
if (respObj == null)
{
Deinit();
throw new TonClientException(0, "Failed to parse response as Json");
}
if (respObj is Error error)
{
if (error.Code == 500)
{
Deinit();
}
throw new TonClientException(error.Code, error.Message) { ActualAnswer = error };
}
if (respObj is TResponse resp)
{
return resp;
}
Deinit();
throw new TonClientException(0, "Invalid (unexpected) response type") { ActualAnswer = respObj };
}
protected virtual void Dispose(bool disposing)
{
if (!isDisposed)
{
if (disposing)
{
// Dispose managed state (managed objects)
}
if (client != null)
{
tonlib_client_json_destroy(client.Value);
client = null;
}
isDisposed = true;
}
}
}
}