fix nostr on cj plugin

This commit is contained in:
Kukks
2023-05-10 16:20:55 +02:00
parent 9960ae6aeb
commit 5d3c7bd446
3 changed files with 36 additions and 71 deletions

View File

@@ -13,7 +13,7 @@
<PropertyGroup> <PropertyGroup>
<Product>Wabisabi Coinjoin</Product> <Product>Wabisabi Coinjoin</Product>
<Description>Allows you to integrate your btcpayserver store with coinjoins.</Description> <Description>Allows you to integrate your btcpayserver store with coinjoins.</Description>
<Version>1.0.35</Version> <Version>1.0.36</Version>
</PropertyGroup> </PropertyGroup>
<!-- Plugin development properties --> <!-- Plugin development properties -->

View File

@@ -94,14 +94,8 @@ public class WabisabiCoordinatorService : PeriodicRunner
instance.TermsConditions = wabisabiCoordinatorSettings.TermsConditions; instance.TermsConditions = wabisabiCoordinatorSettings.TermsConditions;
} }
try _ = ActionAsync(CancellationToken.None);
{
await this.ActionAsync(CancellationToken.None);
}
catch (Exception e)
{
}
await _settingsRepository.UpdateSetting(wabisabiCoordinatorSettings, nameof(WabisabiCoordinatorSettings)); await _settingsRepository.UpdateSetting(wabisabiCoordinatorSettings, nameof(WabisabiCoordinatorSettings));
} }

View File

@@ -7,6 +7,7 @@ using System.Text.Json.Nodes;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using BTCPayServer.Services; using BTCPayServer.Services;
using LNURL;
using NBitcoin; using NBitcoin;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using NNostr.Client; using NNostr.Client;
@@ -34,43 +35,10 @@ public class Nostr
.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token) .CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token)
.Token; .Token;
var client = new NostrClient(relayUri, socket => socket.Options.Proxy = httpClientHandler?.Proxy); var client = new NostrClient(relayUri, socket => socket.Options.Proxy = httpClientHandler?.Proxy);
await client.ConnectAndWaitUntilConnected(ct); _ = client.Connect(ct);
_ = client.ListenForMessages(); await client.WaitUntilConnected(ct);
var tcs = new TaskCompletionSource();
var ids = evts.Select(evt => evt.Id).ToHashSet(); await client.SendEventsAndWaitUntilReceived(evts, ct);
client.InvalidMessageReceived += (sender, tuple) =>
{
Console.WriteLine(tuple);
};
client.OkReceived += (sender, tuple) =>
{
if (ids.RemoveWhere(s => s == tuple.eventId)> 0 && !ids.Any())
{
tcs.TrySetResult();
}
};
client.EventsReceived += (sender, tuple) =>
{
if (ids.RemoveWhere(s => tuple.events.Any(@event => @event.Id == s)) > 0 && !ids.Any())
{
tcs.TrySetResult();
}
};
await client.CreateSubscription("ack", new[]
{
new NostrSubscriptionFilter()
{
Ids = ids.ToArray()
}
}, ct);
foreach (var evt in evts)
{
await client.PublishEvent(evt, ct);
}
await tcs.Task.WithCancellation(ct);
await client.CloseSubscription("ack", ct);
client.Dispose(); client.Dispose();
} }
@@ -84,8 +52,6 @@ public class Nostr
{ {
Kind = Kind, Kind = Kind,
Content = description, Content = description,
PublicKey = privateKey.CreatePubKey().ToXOnlyPubKey().ToHex(),
CreatedAt = DateTimeOffset.UtcNow,
Tags = new List<NostrEventTag>() Tags = new List<NostrEventTag>()
{ {
new() {TagIdentifier = EndpointTagIdentifier, Data = new List<string>() {new Uri(coordinatorUri, "plugins/wabisabi-coordinator").ToString()}}, new() {TagIdentifier = EndpointTagIdentifier, Data = new List<string>() {new Uri(coordinatorUri, "plugins/wabisabi-coordinator").ToString()}},
@@ -106,27 +72,10 @@ public class Nostr
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
var nostrClient = new NostrClient(relayUri, socket => socket.Options.Proxy = httpClientHandler?.Proxy); var nostrClient = new NostrClient(relayUri, socket => socket.Options.Proxy = relayUri.IsLocalNetwork()? null: httpClientHandler?.Proxy);
await nostrClient.CreateSubscription("nostr-wabisabi-coordinators", Stopwatch stopwatch = new();
new[]
{
new NostrSubscriptionFilter()
{
Kinds = new[] {Kind}, Since = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromHours(1)),
ExtensionData = new Dictionary<string, JsonElement>()
{
["type"] = JsonSerializer.SerializeToElement(TypeTagValue),
["network"] = JsonSerializer.SerializeToElement(currentNetwork.Name.ToLower())
}
}
}, cancellationToken);
var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
await nostrClient.ConnectAndWaitUntilConnected(cts.Token);
_ = nostrClient.ListenForMessages();
var result = new List<NostrEvent>(); var result = new List<NostrEvent>();
var tcs = new TaskCompletionSource(); var tcs = new TaskCompletionSource();
Stopwatch stopwatch = new();
stopwatch.Start();
nostrClient.EoseReceived += (sender, s) => nostrClient.EoseReceived += (sender, s) =>
{ {
tcs.SetResult(); tcs.SetResult();
@@ -136,6 +85,28 @@ public class Nostr
stopwatch.Restart(); stopwatch.Restart();
result.AddRange(tuple.events); result.AddRange(tuple.events);
}; };
var network = currentNetwork.Name.ToLower();
var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
_ = nostrClient.Connect(cts.Token);
await nostrClient.WaitUntilConnected(cts.Token);
await nostrClient.CreateSubscription("nostr-wabisabi-coordinators",
new[]
{
new NostrSubscriptionFilter()
{
Kinds = new[] {Kind},
Since = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromHours(1)),
ExtensionData = new Dictionary<string, JsonElement>()
{
["#type"] = JsonSerializer.SerializeToElement(new []{TypeTagValue}),
["#network"] = JsonSerializer.SerializeToElement(new []{network})
}
}
}, cancellationToken);
stopwatch.Start();
while (!tcs.Task.IsCompleted && !cts.IsCancellationRequested && while (!tcs.Task.IsCompleted && !cts.IsCancellationRequested &&
stopwatch.ElapsedMilliseconds < 10000) stopwatch.ElapsedMilliseconds < 10000)
{ {
@@ -144,11 +115,9 @@ public class Nostr
nostrClient.Dispose(); nostrClient.Dispose();
var network = currentNetwork.Name
.ToLower();
return result.Where(@event => return result.Where(@event =>
@event.PublicKey != ourPubKey && @event.PublicKey != ourPubKey &&
@event.CreatedAt < DateTimeOffset.UtcNow.AddMinutes(15) && @event.CreatedAt >= DateTimeOffset.UtcNow.Subtract(TimeSpan.FromHours(1)) &&
@event.Verify() && @event.Verify() &&
@event.Tags.Any(tag => @event.Tags.Any(tag =>
tag.TagIdentifier == EndpointTagIdentifier && tag.TagIdentifier == EndpointTagIdentifier &&
@@ -157,8 +126,10 @@ public class Nostr
tag.TagIdentifier == TypeTagIdentifier && tag.TagIdentifier == TypeTagIdentifier &&
tag.Data.FirstOrDefault() == TypeTagValue) && tag.Data.FirstOrDefault() == TypeTagValue) &&
@event.Tags.Any(tag => @event.Tags.Any(tag =>
tag.TagIdentifier == NetworkTagIdentifier && tag.Data.FirstOrDefault() == network) tag.TagIdentifier == NetworkTagIdentifier && tag.Data.FirstOrDefault()?.Equals(network, StringComparison.InvariantCultureIgnoreCase) is true)
).Select(@event => new DiscoveredCoordinator() ).OrderByDescending(@event => @event.CreatedAt)
.DistinctBy(@event => @event.PublicKey)
.Select(@event => new DiscoveredCoordinator()
{ {
Description = @event.Content, Description = @event.Content,
Name = @event.PublicKey, Name = @event.PublicKey,