Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using a proxy for tonClient #121

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions TonSdk.Client/src/HttpApi/HttpsApi.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using TonSdk.Core;
using TonSdk.Core.Block;
Expand All @@ -15,7 +17,7 @@ public class HttpApiParameters
public int? Timeout { get; set; }
public string ApiKey { get; set; }
}

public class HttpApi : IDisposable
{
private readonly HttpClient _httpClient;
Expand All @@ -27,7 +29,35 @@ internal HttpApi(HttpParameters httpApiParameters)
throw new ArgumentNullException("Endpoint field in Http options cannot be null.");
}

_httpClient = new HttpClient();
if (httpApiParameters.Proxy != null)
{
WebProxy webProxy = new WebProxy
{
Address = new Uri( httpApiParameters.Proxy.ProxyType switch
{
ProxyType.HTTP => "http://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
ProxyType.HTTPS => "https://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
ProxyType.Socks4 => "socks4://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
ProxyType.Socks5 => "socks5://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
_ => throw new ArgumentOutOfRangeException()
}),
Credentials = new NetworkCredential(
userName: httpApiParameters.Proxy.UserName,
password: httpApiParameters.Proxy.Password
)
};
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = webProxy
};

_httpClient = new HttpClient(httpClientHandler);

}
else
{
_httpClient = new HttpClient();
}

_httpClient.Timeout = TimeSpan.FromMilliseconds(Convert.ToDouble(httpApiParameters.Timeout ?? 30000));
//httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
Expand Down
30 changes: 29 additions & 1 deletion TonSdk.Client/src/HttpApi/HttpsApiV3.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using TonSdk.Client.Stack;
Expand All @@ -23,8 +24,35 @@ public HttpApiV3(HttpParameters httpApiParameters)
throw new ArgumentNullException("Endpoint field in Http options cannot be null.");
}

_httpClient = new HttpClient();
if (httpApiParameters.Proxy != null)
{
WebProxy webProxy = new WebProxy
{
Address = new Uri( httpApiParameters.Proxy.ProxyType switch
{
ProxyType.HTTP => "http://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
ProxyType.HTTPS => "https://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
ProxyType.Socks4 => "socks4://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
ProxyType.Socks5 => "socks5://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
_ => throw new ArgumentOutOfRangeException()
Comment on lines +33 to +37
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Как будто бы можно объединить повторяющийся код "protocol://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port.
Мб UriBuilder

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partial, в данном случае, выглядит удобнее всего. В Models.cs у нас указываются только поля и их типы в разных классах. Реализация работы методов, на мой взгляд, там не к месту.

На счет логики сравнения прокси. А как по-другому указывать тип прокси? Как-то из enum доставать? Я просто не знаю)

}),
Credentials = new NetworkCredential(
userName: httpApiParameters.Proxy.UserName,
password: httpApiParameters.Proxy.Password
)
};
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = webProxy
};
Comment on lines +27 to +47
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно вынести в приватный метод по типу:

private HttpClient CreateHttpClient(HttpApiParameters httpApiParameters)

и там можно будет повысить читаемость кода (понизим вложенность и облегчим чуть конструктор)

if (httpApiParameters.Proxy == null)
{
    return new HttpClient();
}

var proxyAddress = BuildProxyAddress(httpApiParameters.Proxy);
var webProxy = new WebProxy {};

var httpClientHandler = new HttpClientHandler
{
    Proxy = webProxy
};

return new HttpClient(httpClientHandler);

+мб можно вынести и переиспользовать для других типов хттп клиентов

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кстати да, факты, так было бы удобней


_httpClient = new HttpClient(httpClientHandler);

}
else
{
_httpClient = new HttpClient();
}
_httpClient.Timeout = TimeSpan.FromMilliseconds(Convert.ToDouble(httpApiParameters.Timeout ?? 30000));

_httpClient.DefaultRequestHeaders.Accept.Clear();
Expand Down
30 changes: 29 additions & 1 deletion TonSdk.Client/src/HttpApi/HttpsWhales.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using TonSdk.Core;
Expand All @@ -21,8 +22,35 @@ internal HttpWhales(HttpParameters httpApiParameters)
throw new ArgumentNullException("Endpoint field in Http options cannot be null.");
}

_httpClient = new HttpClient();
if (httpApiParameters.Proxy != null)
{
WebProxy webProxy = new WebProxy
{
Address = new Uri( httpApiParameters.Proxy.ProxyType switch
{
ProxyType.HTTP => "http://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
ProxyType.HTTPS => "https://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
ProxyType.Socks4 => "socks4://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
ProxyType.Socks5 => "socks5://" + httpApiParameters.Proxy.Ip + ":" + httpApiParameters.Proxy.Port,
_ => throw new ArgumentOutOfRangeException()
}),
Credentials = new NetworkCredential(
userName: httpApiParameters.Proxy.UserName,
password: httpApiParameters.Proxy.Password
)
};
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = webProxy
};

_httpClient = new HttpClient(httpClientHandler);

}
else
{
_httpClient = new HttpClient();
}
_httpClient.Timeout = TimeSpan.FromMilliseconds(Convert.ToDouble(httpApiParameters.Timeout ?? 30000));
//httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");

Expand Down
54 changes: 54 additions & 0 deletions TonSdk.Client/src/Models/Models.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection.Metadata;
using System.Threading.Tasks;
using TonSdk.Client.Stack;
using TonSdk.Core;
Expand All @@ -16,13 +18,22 @@ public enum TonClientType

}

public enum ProxyType
{
Socks5,
Socks4,
HTTP,
HTTPS
}

public interface ITonClientOptions {}

public class HttpParameters : ITonClientOptions
{
public string Endpoint { get; set; }
public int? Timeout { get; set; }
public string ApiKey { get; set; }
public Proxy? Proxy { get; set; }
}

public class LiteClientParameters : ITonClientOptions
Expand All @@ -38,4 +49,47 @@ public LiteClientParameters(string host, int port, string peerPublicKey)
PeerPublicKey = peerPublicKey;
}
}

/// <summary>
/// Credentials for connecting to the proxy
/// </summary>
public partial class Proxy : ITonClientOptions
{
/// <summary>
/// Ip address of the proxy server
/// </summary>
public IPAddress Ip { get; set; }

private int _port;

/// <summary>
/// Port number of the proxy server
/// </summary>
/// <exception cref="Exception">The proxy port number goes beyond 1-65536</exception>
public int Port
{
set
{
if (value < 1 || value > 65536)
throw new Exception("The proxy port number goes beyond 1-65536");
_port = value;
}
get => _port;
}

/// <summary>
/// The user's name of the credentials
/// </summary>
public string UserName { get; set; }

/// <summary>
/// The password's of the credentials
/// </summary>
public string Password { get; set; }

/// <summary>
/// Type of proxy server protocol
/// </summary>
public ProxyType ProxyType { get; set; }
}
}
30 changes: 30 additions & 0 deletions TonSdk.Client/src/Models/Proxy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using Org.BouncyCastle.Crypto.Parameters;

namespace TonSdk.Client
{
public partial class Proxy
{
public override bool Equals(object obj)
{
Proxy tmpProxy = obj as Proxy;
if (tmpProxy == null) return false;

if (Ip != tmpProxy.Ip) return false;
if (Port != tmpProxy.Port) return false;
if (UserName != tmpProxy.UserName) return false;
if (Password != tmpProxy.Password) return false;
if (ProxyType != tmpProxy.ProxyType) return false;
return true;
}

public override int GetHashCode()
{
int hashCode = Ip.GetHashCode();
hashCode = 31 * hashCode + Port.GetHashCode();
hashCode = 31 * hashCode + UserName.GetHashCode();
hashCode = 31 * hashCode + Password.GetHashCode();
hashCode = 31 * hashCode + ProxyType.GetHashCode();
return hashCode;
}
}
}
36 changes: 36 additions & 0 deletions TonSdk.Client/test/Client.test.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Net;
using System.Numerics;
using System.Threading.Tasks;
using NUnit.Framework;
Expand Down Expand Up @@ -220,4 +221,39 @@ public async Task Test_JettonGetWalletAddress()
Assert.That((await client_lite.Jetton.GetWalletAddress(new Address("EQBlqsm144Dq6SjbPI4jjZvA1hqTIP3CvHovbIfW_t-SCALE"), new Address("EQAEnqomwC3dg323OcdgUsvk3T38VvYawX8q6x38ulfnCn7b"))).Equals(new Address("EQA_d9IqxSQCSuwZIvH0RRSUMvWK4qrvl5ZH_nOHFH7Gxifq")), Is.EqualTo(true));
Assert.That((await client_lite.Jetton.GetWalletAddress(new Address("EQBlqsm144Dq6SjbPI4jjZvA1hqTIP3CvHovbIfW_t-SCALE"), new Address("EQAEnqomwC3dg323OcdgUsvk3T38VvYawX8q6x38ulfnCn7b"))).Equals(new Address("EQAEnqomwC3dg323OcdgUsvk3T38VvYawX8q6x38ulfnCn7b")), Is.EqualTo(false));
}

[Test]
public void Test_ProxyClass()
{
Proxy proxy1 = new Proxy
{
Ip = IPAddress.Parse("1.1.1.1"),
Port = 22222,
UserName = "WhoIsIt?",
Password = "54321"
};

Proxy proxy2 = new Proxy
{
Ip = IPAddress.Parse("1.1.1.1"),
Port = 22222,
UserName = "WhoIsIt?",
Password = "54321"
};

Proxy proxy3 = new Proxy
{
Ip = IPAddress.Parse("123.123.123.123"),
Port = 33333,
UserName = "ItsMe,Mario",
Password = "51423"
};

Assert.That(proxy1.GetHashCode(), Is.EqualTo(-1512725739));
Assert.That(proxy2.GetHashCode(), Is.EqualTo(-1512725739));
Assert.That(proxy3.GetHashCode(), Is.EqualTo(168523034));

Assert.That(proxy1.Equals(proxy2), Is.True);
Assert.That(proxy1.Equals(proxy3), Is.False);
}
}