Skip to content

Commit cf460bb

Browse files
authored
Merge pull request #16 from DanGould/style/pj
Style/pj sync from days ago, pw protect hidden service start, fix request amount
2 parents f77fdd3 + 2cf09e0 commit cf460bb

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+512
-1241
lines changed

Chaincase.Common/Global.cs

+27-11
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@ public class Global
7272

7373
public Global(INotificationManager notificationManager, ITorManager torManager, IDataDirProvider dataDirProvider)
7474
{
75-
TorManager = torManager;
76-
NotificationManager = notificationManager;
77-
using (BenchmarkLogger.Measure())
75+
TorManager = torManager;
76+
NotificationManager = notificationManager;
77+
using (BenchmarkLogger.Measure())
7878
{
7979
StoppingCts = new CancellationTokenSource();
8080
DataDir = dataDirProvider.Get();
@@ -118,7 +118,7 @@ public void SetDefaultWallet()
118118

119119
private CancellationTokenSource StoppingCts { get; set; }
120120

121-
public async Task InitializeNoWalletAsync(CancellationToken cancellationToken = default)
121+
public async Task InitializeNoWalletAsync(CancellationToken cancellationToken = default)
122122
{
123123
AddressManager = null;
124124
Logger.LogDebug($"Global.InitializeNoWalletAsync(): Waiting for a lock");
@@ -483,7 +483,8 @@ private void WalletManager_WalletRelevantTransactionProcessed(object sender, Pro
483483
else if (incoming > Money.Zero)
484484
{
485485
NotifyAndLog($"{amountString} BTC", "Receive Confirmed", NotificationType.Information, e);
486-
if (P2EPServer.HiddenServiceIsOn) {
486+
if (P2EPServer.HiddenServiceIsOn)
487+
{
487488
var cts = new CancellationToken();
488489
P2EPServer.StopAsync(cts);
489490
}
@@ -540,12 +541,13 @@ private void NotifyAndLog(string message, string title, NotificationType notific
540541

541542
public async Task OnResuming()
542543
{
544+
KeepHiddenServiceAlive.Cancel();
543545
if (IsResuming)
544-
{
546+
{
545547
Logger.LogDebug($"Global.OnResuming(): SleepCts.Cancel()");
546548
SleepCts.Cancel();
547549
return;
548-
}
550+
}
549551

550552
try
551553
{
@@ -567,7 +569,7 @@ public async Task OnResuming()
567569
var addrManTask = InitializeAddressManagerBehaviorAsync();
568570
AddressManagerBehavior addressManagerBehavior = await addrManTask.ConfigureAwait(false);
569571
connectionParameters.TemplateBehaviors.Add(addressManagerBehavior);
570-
572+
571573
if (TorManager?.State != TorState.Started && TorManager.State != TorState.Connected)
572574
{
573575
await TorManager.StartAsync(false, DataDir);
@@ -602,7 +604,8 @@ public async Task OnResuming()
602604
}
603605
}
604606

605-
private protected CancellationTokenSource SleepCts { get; set; } = new CancellationTokenSource();
607+
private protected CancellationTokenSource KeepHiddenServiceAlive { get; set; } = new CancellationTokenSource();
608+
private protected CancellationTokenSource SleepCts { get; set; } = new CancellationTokenSource();
606609
private protected bool IsGoingToSleep = false;
607610

608611
public async Task OnSleeping()
@@ -616,9 +619,22 @@ public async Task OnSleeping()
616619

617620
try
618621
{
619-
Logger.LogDebug($"Global.OnSleeping(): Waiting for a lock");
620622
SleepCts.Dispose();
621623
SleepCts = new CancellationTokenSource();
624+
625+
if (P2EPServer.HiddenServiceIsOn)
626+
{
627+
KeepHiddenServiceAlive.Dispose();
628+
KeepHiddenServiceAlive = new CancellationTokenSource();
629+
// wait 20 seconds
630+
for (int i = 0; i < 20; i++)
631+
{
632+
await Task.Delay(1_000); //
633+
if (KeepHiddenServiceAlive.IsCancellationRequested || !P2EPServer.HiddenServiceIsOn) return;
634+
}
635+
await P2EPServer.StopAsync(SleepCts.Token);
636+
}
637+
Logger.LogDebug($"Global.OnSleeping(): Waiting for a lock");
622638
using (await LifeCycleMutex.LockAsync(SleepCts.Token))
623639
{
624640
#region CriticalSection
@@ -629,7 +645,7 @@ public async Task OnSleeping()
629645
// don't ever cancel Init. use an ephemeral token
630646
await WaitForInitializationCompletedAsync(new CancellationToken());
631647

632-
648+
633649
if (TorManager?.State != TorState.Stopped) // OnionBrowser && Dispose@Global
634650
{
635651
//TorManager.CreateHiddenServiceAsync();

Chaincase.Common/Services/P2EPRequestHandler.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33
using System.Linq;
44
using System.Reflection;
@@ -29,7 +29,7 @@ public P2EPRequestHandler(Network network, WalletManager walletManager, int priv
2929
NotificationManager = notificationManager;
3030
}
3131

32-
public Task<string> HandleAsync(string body, CancellationToken cancellationToken)
32+
public Task<string> HandleAsync(string body, CancellationToken cancellationToken, string password)
3333
{
3434
if (!PSBT.TryParse(body, Network, out var psbt))
3535
{
@@ -56,7 +56,7 @@ public Task<string> HandleAsync(string body, CancellationToken cancellationToken
5656
input.WitScript = WitScript.Empty;
5757
}
5858
// Get prv key for signature
59-
var serverCoinKey = toUse.KeyManager.GetSecrets("chaincase", toUse.coin.ScriptPubKey).First();
59+
var serverCoinKey = toUse.KeyManager.GetSecrets(password, toUse.coin.ScriptPubKey).First();
6060
var serverCoin = toUse.coin.GetCoin();
6161

6262
paymentTx.Inputs.Add(serverCoin.Outpoint);

Chaincase.Common/Services/P2EPServer.cs

+6-3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ public class P2EPServer : BackgroundService
1818
public string PaymentEndpoint => $"http://{ServiceId}.onion:37129";
1919
public bool HiddenServiceIsOn { get; private set; }
2020

21+
public string Password { private get; set; }
22+
2123
public P2EPServer(Global global)
2224
{
2325
Global = global;
@@ -45,6 +47,7 @@ public override async Task StartAsync(CancellationToken cancellationToken)
4547

4648
public override async Task StopAsync(CancellationToken cancellationToken)
4749
{
50+
Password = null;
4851
await base.StopAsync(cancellationToken).ConfigureAwait(false);
4952
Listener.Stop();
5053
var serviceId = ServiceId;
@@ -58,7 +61,7 @@ public override async Task StopAsync(CancellationToken cancellationToken)
5861

5962
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
6063
{
61-
var handler = new P2EPRequestHandler(Global.Network, Global.WalletManager, Global.Config.PrivacyLevelSome, Global.NotificationManager);
64+
var handler = new P2EPRequestHandler(Global.Network, Global.WalletManager, 1, Global.NotificationManager);
6265

6366
while (!stoppingToken.IsCancellationRequested)
6467
{
@@ -75,7 +78,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
7578

7679
try
7780
{
78-
var result = await handler.HandleAsync(body, stoppingToken).ConfigureAwait(false);
81+
var result = await handler.HandleAsync(body, stoppingToken, Password).ConfigureAwait(false);
7982

8083
var output = response.OutputStream;
8184
var buffer = Encoding.UTF8.GetBytes(result);
@@ -120,4 +123,4 @@ private async Task<HttpListenerContext> GetHttpContextAsync(CancellationToken ca
120123
return await getHttpContextTask.ConfigureAwait(false);
121124
}
122125
}
123-
}
126+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
using System;
2+
using System.IO;
3+
using System.Net;
4+
using System.Text;
5+
using System.Threading;
6+
using System.Threading.Tasks;
7+
using Microsoft.Extensions.Hosting;
8+
using Chaincase.Common.Contracts;
9+
10+
namespace Chaincase.Common.Services
11+
{
12+
public class P2EPServer : BackgroundService
13+
{
14+
private ITorManager TorManager => Global.TorManager;
15+
private HttpListener Listener { get; }
16+
public string ServiceId { get; private set; }
17+
public Global Global { get; }
18+
public string PaymentEndpoint => $"http://{ServiceId}.onion:37129";
19+
public bool HiddenServiceIsOn { get; private set; }
20+
21+
public string Password { private get; set; }
22+
23+
public P2EPServer(Global global)
24+
{
25+
Global = global;
26+
Listener = new HttpListener();
27+
Listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
28+
Listener.Prefixes.Add($"http://*:37129/");
29+
}
30+
31+
public override async Task StartAsync(CancellationToken cancellationToken)
32+
{
33+
// Assummming running
34+
//while (!Tor)
35+
//{
36+
// await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
37+
//}
38+
ServiceId = TorManager.CreateHiddenServiceAsync();
39+
HiddenServiceIsOn = true;
40+
41+
//await TorControlClient.ConnectAsync().ConfigureAwait(false);
42+
//await TorControlClient.AuthenticateAsync("MyLittlePonny").ConfigureAwait(false);
43+
44+
Listener.Start();
45+
await base.StartAsync(cancellationToken).ConfigureAwait(false);
46+
}
47+
48+
public override async Task StopAsync(CancellationToken cancellationToken)
49+
{
50+
Password = null;
51+
await base.StopAsync(cancellationToken).ConfigureAwait(false);
52+
Listener.Stop();
53+
var serviceId = ServiceId;
54+
if (!string.IsNullOrWhiteSpace(serviceId))
55+
{
56+
TorManager.DestroyHiddenServiceAsync(serviceId);
57+
HiddenServiceIsOn = false;
58+
ServiceId = "";
59+
}
60+
}
61+
62+
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
63+
{
64+
<<<<<<< HEAD
65+
var handler = new P2EPRequestHandler(Global.Network, Global.WalletManager, 1);
66+
||||||| 7c7699f58
67+
var handler = new P2EPRequestHandler(Global.Network, Global.WalletManager, Global.Config.PrivacyLevelSome);
68+
=======
69+
var handler = new P2EPRequestHandler(Global.Network, Global.WalletManager, Global.Config.PrivacyLevelSome, Global.NotificationManager);
70+
>>>>>>> 3f4a8aef96f744b9775891c1ed602ee2509b0de2
71+
72+
while (!stoppingToken.IsCancellationRequested)
73+
{
74+
try
75+
{
76+
var context = await GetHttpContextAsync(stoppingToken).ConfigureAwait(false);
77+
var request = context.Request;
78+
var response = context.Response;
79+
80+
if (request.HttpMethod == "POST")
81+
{
82+
using var reader = new StreamReader(request.InputStream);
83+
string body = await reader.ReadToEndAsync().ConfigureAwait(false);
84+
85+
try
86+
{
87+
var result = await handler.HandleAsync(body, stoppingToken, Password).ConfigureAwait(false);
88+
89+
var output = response.OutputStream;
90+
var buffer = Encoding.UTF8.GetBytes(result);
91+
await output.WriteAsync(buffer, 0, buffer.Length, stoppingToken).ConfigureAwait(false);
92+
await output.FlushAsync(stoppingToken).ConfigureAwait(false);
93+
}
94+
catch (Exception e)
95+
{
96+
response.StatusCode = (int)HttpStatusCode.BadRequest;
97+
response.StatusDescription = e.Message;
98+
}
99+
}
100+
else
101+
{
102+
response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
103+
}
104+
//response.ContentType = "text/html; charset=UTF-8";
105+
response.Close();
106+
}
107+
catch (OperationCanceledException)
108+
{
109+
break;
110+
}
111+
catch (Exception ex)
112+
{
113+
}
114+
}
115+
}
116+
117+
private async Task<HttpListenerContext> GetHttpContextAsync(CancellationToken cancellationToken)
118+
{
119+
var getHttpContextTask = Listener.GetContextAsync();
120+
var tcs = new TaskCompletionSource<bool>();
121+
using (cancellationToken.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(true), tcs))
122+
{
123+
var firstTaskToComplete = await Task.WhenAny(getHttpContextTask, tcs.Task).ConfigureAwait(false);
124+
if (getHttpContextTask != firstTaskToComplete)
125+
{
126+
cancellationToken.ThrowIfCancellationRequested();
127+
}
128+
}
129+
return await getHttpContextTask.ConfigureAwait(false);
130+
}
131+
}
132+
}

Chaincase.UI/Chaincase.UI.csproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="3.1.12" />
1212
<PackageReference Include="BlazorIonic" Version="1.0.14" />
1313
<PackageReference Include="ZXing.Net.Mobile" Version="2.4.1" />
14-
<PackageReference Include="LiveSharp" Version="1.6.54" />
14+
<PackageReference Include="LiveSharp" Version="1.6.59" />
1515
<PackageReference Include="Microsoft.AspNetCore.Components" Version="3.1.12" />
1616
<PackageReference Include="ReactiveUI" Version="13.2.2" />
1717
<PackageReference Include="ReactiveUI.Blazor" Version="13.2.2" />

0 commit comments

Comments
 (0)