Skip to content

Commit 4c34e94

Browse files
author
Armin Sabouri
committed
Tor create and destroy hidden service tests
1 parent 886924e commit 4c34e94

File tree

7 files changed

+190
-5
lines changed

7 files changed

+190
-5
lines changed

Chaincase.Common/Chaincase.Common.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,6 @@
1414
</ItemGroup>
1515
<ItemGroup>
1616
<Folder Include="Models\" />
17+
<Folder Include="Services\" />
1718
</ItemGroup>
1819
</Project>

Chaincase.Common/Contracts/ITorManager.cs

+4
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,9 @@ public interface ITorManager
1717
Task StopAsync();
1818

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

Chaincase.iOS/Services/iOSTorManager.cs

+5-2
Original file line numberDiff line numberDiff line change
@@ -284,8 +284,11 @@ public async Task StopAsync()
284284

285285
public async Task CreateHiddenServiceAsync() {
286286
try
287-
{
288-
TorController.SendCommand("ADD_ONION NEW:BEST Flags=DiscardPK Port=37129,37129",null, null, null);
287+
{
288+
TorController.SendCommand("ADD_ONION", new String[] { "NEW:BEST" }, "Flags=DiscardPK Port=37129,37129",
289+
(keys, values, boolPointer) => {
290+
return true;
291+
});
289292
}
290293
catch (Exception error) {
291294

Xamarin.iOS.Tor.Tests/P2EPTest.cs

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
using System;
2+
namespace Xamarin.iOS.Tor.Tests
3+
{
4+
public class EmptyClass
5+
{
6+
public EmptyClass()
7+
{
8+
}
9+
}
10+
}

Xamarin.iOS.Tor.Tests/TORControllerTests.cs

+46-3
Original file line numberDiff line numberDiff line change
@@ -249,23 +249,66 @@ public void TestReset()
249249

250250
ewh.WaitOne();
251251
}
252+
private static string NSHomeDirectory() => Directory.GetParent(NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User).First().Path).FullName;
253+
252254

253255
[Fact]
254256
public void TestHiddenService()
255257
{
256-
EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset);
258+
CanLog();
259+
EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset);
260+
//System.Diagnostics.Debug.WriteLine(NSHomeDirectory());
261+
string serviceId = "";
262+
Exec(() =>
263+
{
264+
// ADD_ONION NEW:BEST Flags=DiscardPK Port=37129,37129"
265+
Controller.SendCommand(new NSString("ADD_ONION"), new string[] { "NEW:BEST" , "Port=37129,37129" , "Flags=DiscardPK"}, null,
266+
(keys, values, boolPointer) => {
267+
// Assert.True(keys[0] == (NSNumber)250);
268+
serviceId = values[0].ToString().Split('=')[1];
269+
270+
ewh.Set();
271+
return true;
272+
});
273+
274+
});
275+
ewh.WaitOne();
276+
277+
Exec(() =>
278+
{
279+
280+
Controller.SendCommand(new NSString("DEL_ONION"), new string[] { $"{serviceId}" }, null,
281+
(keys, values, boolPointer) =>
282+
{
283+
ewh.Set();
284+
285+
return true;
286+
});
287+
});
288+
ewh.WaitOne();
289+
}
257290

291+
292+
[Fact]
293+
public void CanDestroyHiddenService(string serviceId)
294+
{
295+
CanLog();
296+
EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset);
297+
//System.Diagnostics.Debug.WriteLine(NSHomeDirectory());
258298
Exec(() =>
259299
{
260300
// ADD_ONION NEW:BEST Flags=DiscardPK Port=37129,37129"
261-
Controller.SendCommand("ADD_ONION", new String[] { "NEW:BEST" }, "Flags=DiscardPK Port=37129,37129", (a, b, c) => { return true; });
301+
Controller.SendCommand(new NSString("DEL_ONION"), new string[] { $"SP {serviceId} CRLF" }, null,
302+
(keys, values, boolPointer) => {
303+
// Assert.True(values.)
304+
return true;
305+
});
262306
ewh.Set();
263307
});
264308

265309
ewh.WaitOne();
266310
}
267311

268-
269312
public delegate void Callback();
270313

271314
public void Exec(Callback callback)

Xamarin.iOS.Tor.Tests/Xamarin.iOS.Tor.Tests.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@
135135
<Compile Include="TORControllerTests.cs" />
136136
<Compile Include="XunitAppDelegate.cs" />
137137
<Compile Include="RunStopConnectTests.cs" />
138+
<Compile Include="P2EPTest.cs" />
138139
</ItemGroup>
139140
<ItemGroup>
140141
<ProjectReference Include="..\Xamarin.iOS.Tor\Xamarin.iOS.Tor.csproj">

0 commit comments

Comments
 (0)