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

chore: request improvements #184

Merged
merged 5 commits into from
Apr 12, 2024
Merged
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
22 changes: 22 additions & 0 deletions Core Modules/WalletConnectSharp.Common/Utils/RpcPayloadId.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;

namespace WalletConnectSharp.Common.Utils;

/// <summary>
Expand All @@ -19,4 +23,22 @@ public static long Generate()
var extra = (long)Math.Floor(rng.NextDouble() * (10.0 * 10.0 * 10.0));
return date + extra;
}

public static long GenerateFromDataHash(object data)
{
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)));

// Take the first 6 bytes to stay within JavaScript's safe integer range
long id = 0;
for (var i = 0; i < 6; i++)
{
id = (id << 8) | hash[i];
}

// Ensure the id is positive
id &= 0x7FFFFFFFFFFFFF;

return id;
}
}
87 changes: 42 additions & 45 deletions Core Modules/WalletConnectSharp.Crypto/Crypto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,22 @@ namespace WalletConnectSharp.Crypto
/// </summary>
public class Crypto : ICrypto
{
private readonly string CRYPTO_CLIENT_SEED = $"client_ed25519_seed";

private const string MULTICODEC_ED25519_ENCODING = "base58btc";
private const string MULTICODEC_ED25519_BASE = "z";
private const string MULTICODEC_ED25519_HEADER = "K36";
private const int MULTICODEC_ED25519_LENGTH = 32;
private const string DID_DELIMITER = ":";
private const string DID_PREFIX = "did";
private const string DID_METHOD = "key";
private const long CRYPTO_JWT_TTL = Clock.ONE_DAY;
private const string JWT_DELIMITER = ".";
private static readonly Encoding DATA_ENCODING = Encoding.UTF8;
private static readonly Encoding JSON_ENCODING = Encoding.UTF8;

public const int TYPE_0 = 0;
public const int TYPE_1 = 1;
private const int TYPE_LENGTH = 1;
private const int IV_LENGTH = 12;
private const int KEY_LENGTH = 32;
private const string CryptoClientSeed = $"client_ed25519_seed";
private const string MulticodecEd25519Base = "z";
private const string MulticodecEd25519Header = "K36";
private const string DidDelimiter = ":";
private const string DidPrefix = "did";
private const string DidMethod = "key";
private const long CryptoJwtTtl = Clock.ONE_DAY;
private const string JwtDelimiter = ".";
private static readonly Encoding DataEncoding = Encoding.UTF8;
private static readonly Encoding JsonEncoding = Encoding.UTF8;

public const int Type0 = 0;
public const int Type1 = 1;
private const int TypeLength = 1;
private const int IvLength = 12;
private const int KeyLength = 32;

/// <summary>
/// The name of the crypto module
Expand Down Expand Up @@ -232,8 +229,8 @@ public Task DeleteSymKey(string topic)

private EncodingValidation ValidateEncoding(EncodeOptions options)
{
var type = options?.Type ?? TYPE_0;
if (type == TYPE_1)
var type = options?.Type ?? Type0;
if (type == Type1)
{
if (options == null || string.IsNullOrWhiteSpace(options.SenderPublicKey))
{
Expand Down Expand Up @@ -267,7 +264,7 @@ private EncodingValidation ValidateDecoding(string encoded, DecodeOptions option

private bool IsTypeOneEnvelope(EncodingValidation param)
{
return param.Type == TYPE_1 && !string.IsNullOrWhiteSpace(param.SenderPublicKey) &&
return param.Type == Type1 && !string.IsNullOrWhiteSpace(param.SenderPublicKey) &&
!string.IsNullOrWhiteSpace(param.ReceiverPublicKey);
}

Expand All @@ -294,7 +291,7 @@ public Task<string> Encrypt(EncryptParams @params)
rawIv = iv.HexToByteArray();
}

var type1 = @params.Type == TYPE_1;
var type1 = @params.Type == Type1;
var senderPublicKey = !string.IsNullOrWhiteSpace(@params.SenderPublicKey)
? @params.SenderPublicKey.HexToByteArray()
: null;
Expand Down Expand Up @@ -419,18 +416,18 @@ public async Task<T> Decode<T>(string topic, string encoded, DecodeOptions optio
private EncodingParams Deserialize(string encoded)
{
var bytes = Convert.FromBase64String(encoded);
var typeRaw = bytes.Take(TYPE_LENGTH).ToArray();
var slice1 = TYPE_LENGTH;
var typeRaw = bytes.Take(TypeLength).ToArray();
var slice1 = TypeLength;

var type = int.Parse(Bases.Base10.Encode(typeRaw));
if (type == TYPE_1)
if (type == Type1)
{
var slice2 = slice1 + KEY_LENGTH;
var slice3 = slice2 + IV_LENGTH;
var senderPublicKey = new ArraySegment<byte>(bytes, slice1, KEY_LENGTH);
var iv = new ArraySegment<byte>(bytes, slice2, IV_LENGTH);
var slice2 = slice1 + KeyLength;
var slice3 = slice2 + IvLength;
var senderPublicKey = new ArraySegment<byte>(bytes, slice1, KeyLength);
var iv = new ArraySegment<byte>(bytes, slice2, IvLength);
var @sealed =
new ArraySegment<byte>(bytes, slice3, bytes.Length - (TYPE_LENGTH + KEY_LENGTH + IV_LENGTH));
new ArraySegment<byte>(bytes, slice3, bytes.Length - (TypeLength + KeyLength + IvLength));

return new EncodingParams()
{
Expand All @@ -442,9 +439,9 @@ private EncodingParams Deserialize(string encoded)
}
else
{
var slice2 = slice1 + IV_LENGTH;
var iv = new ArraySegment<byte>(bytes, slice1, IV_LENGTH);
var @sealed = new ArraySegment<byte>(bytes, slice2, bytes.Length - (IV_LENGTH + TYPE_LENGTH));
var slice2 = slice1 + IvLength;
var iv = new ArraySegment<byte>(bytes, slice1, IvLength);
var @sealed = new ArraySegment<byte>(bytes, slice2, bytes.Length - (IvLength + TypeLength));

return new EncodingParams() { Type = typeRaw, Sealed = @sealed.ToArray(), Iv = iv.ToArray() };
}
Expand All @@ -463,7 +460,7 @@ public async Task<string> SignJwt(string aud)
byte[] subRaw = new byte[32];
RandomNumberGenerator.Fill(subRaw);
var sub = subRaw.ToHex();
var ttl = CRYPTO_JWT_TTL;
var ttl = CryptoJwtTtl;
var iat = Clock.Now();

// sign JWT
Expand All @@ -479,8 +476,8 @@ public async Task<string> SignJwt(string aud)
Exp = exp
};

var data = DATA_ENCODING.GetBytes(
string.Join(JWT_DELIMITER, EncodeJson(header), EncodeJson(payload))
var data = DataEncoding.GetBytes(
string.Join(JwtDelimiter, EncodeJson(header), EncodeJson(payload))
);

Ed25519Signer signer = new Ed25519Signer();
Expand All @@ -506,7 +503,7 @@ public async Task<string> GetClientId()

private string EncodeJwt(IridiumJWTSigned data)
{
return string.Join(JWT_DELIMITER,
return string.Join(JwtDelimiter,
EncodeJson(data.Header),
EncodeJson(data.Payload),
EncodeSig(data.Signature)
Expand All @@ -521,7 +518,7 @@ private string EncodeSig(byte[] signature)
private string EncodeJson<T>(T data)
{
return Base64UrlEncoder.Encode(
JSON_ENCODING.GetBytes(
JsonEncoding.GetBytes(
JsonConvert.SerializeObject(data)
)
);
Expand All @@ -530,10 +527,10 @@ private string EncodeJson<T>(T data)
private string EncodeIss(Ed25519PublicKeyParameters publicKey)
{
var publicKeyRaw = publicKey.GetEncoded();
var header = Base58Encoding.Decode(MULTICODEC_ED25519_HEADER);
var multicodec = MULTICODEC_ED25519_BASE + Base58Encoding.Encode(header.Concat(publicKeyRaw).ToArray());
var header = Base58Encoding.Decode(MulticodecEd25519Header);
var multicodec = MulticodecEd25519Base + Base58Encoding.Encode(header.Concat(publicKeyRaw).ToArray());

return string.Join(DID_DELIMITER, DID_PREFIX, DID_METHOD, multicodec);
return string.Join(DidDelimiter, DidPrefix, DidMethod, multicodec);
}

private Ed25519PrivateKeyParameters KeypairFromSeed(byte[] seed)
Expand Down Expand Up @@ -631,7 +628,7 @@ private string DeserializeAndDecrypt(string symKey, string encoded)
var @sealed = param.Sealed;
var iv = param.Iv;
var type = int.Parse(Bases.Base10.Encode(param.Type));
var isType1 = type == TYPE_1;
var isType1 = type == Type1;

var aead = new ChaCha20Poly1305();
aead.Init(false, new ParametersWithIV(new KeyParameter(symKey.HexToByteArray()), iv));
Expand Down Expand Up @@ -660,14 +657,14 @@ private async Task<byte[]> GetClientSeed()
var seed = "";
try
{
seed = await this.KeyChain.Get(CRYPTO_CLIENT_SEED);
seed = await KeyChain.Get(CryptoClientSeed);
}
catch (Exception e)
{
byte[] seedRaw = new byte[32];
RandomNumberGenerator.Fill(seedRaw);
seed = seedRaw.ToHex();
await this.KeyChain.Set(CRYPTO_CLIENT_SEED, seed);
await KeyChain.Set(CryptoClientSeed, seed);
}

return seed.HexToByteArray();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,7 @@
/// <summary>
/// Whether this websocket connection is connected
/// </summary>
public bool Connected
{
get
{
return _socket != null;
}
}
public bool Connected => _socket != null && _socket.NativeClient.State == WebSocketState.Open;

/// <summary>
/// Whether this websocket connection is currently connecting
Expand Down Expand Up @@ -305,7 +299,7 @@
}
}

public async void Dispose()

Check warning on line 302 in Core Modules/WalletConnectSharp.Network.Websocket/WebsocketConnection.cs

View workflow job for this annotation

GitHub Actions / test (unit-tests)

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Check warning on line 302 in Core Modules/WalletConnectSharp.Network.Websocket/WebsocketConnection.cs

View workflow job for this annotation

GitHub Actions / test (unit-tests)

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
Dispose(true);
GC.SuppressFinalize(this);
Expand Down
Loading
Loading