Skip to content

Commit

Permalink
ReCap cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
skibitsky committed Nov 13, 2024
1 parent 92e2f3b commit 90f7b97
Show file tree
Hide file tree
Showing 9 changed files with 251 additions and 285 deletions.
10 changes: 6 additions & 4 deletions src/Reown.Core.Crypto/Runtime/Crypto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,12 @@ public string Context
/// <returns>The hash of the given input as a hex string</returns>
public string HashKey(string key)
{
using (var sha256 = SHA256.Create())
{
return sha256.ComputeHash(key.HexToByteArray()).ToHex();
}
#if NET7_0_OR_GREATER
return SHA256.HashData(key.HexToByteArray()).ToHex();
#else
using var sha256 = SHA256.Create();
return sha256.ComputeHash(key.HexToByteArray()).ToHex();
#endif
}

public void Dispose()
Expand Down
33 changes: 9 additions & 24 deletions src/Reown.Sign/Runtime/Engine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -929,9 +929,7 @@ public async Task<AuthenticateData> Authenticate(AuthParams authParams)
{
"wc_sessionAuthenticate"
});

ReownLogger.Log($"Generated new pairing: {pairingData.Uri}");


var publicKey = await Client.CoreClient.Crypto.GenerateKeyPair();
var responseTopic = Client.CoreClient.Crypto.HashKey(publicKey);

Expand All @@ -946,22 +944,16 @@ await Task.WhenAll(
);

await Client.CoreClient.Relayer.Subscribe(responseTopic);

ReownLogger.Log($"Subscribed to relayer: {responseTopic}. Pairing topic: {pairingData.Topic}");


if (authParams.Methods is { Length: > 0 })
{
ReownLogger.Log("Methods provided, creating recap");

var chainId = authParams.Chains[0];
var @namespace = Core.Utils.ExtractChainNamespace(chainId);
var recapStr = ReCapUtils.CreateEncodedRecap(@namespace, "request", authParams.Methods);

ReownLogger.Log($"Created recap: {recapStr}");

var recapStr = ReCap.CreateEncodedRecap(@namespace, "request", authParams.Methods);

authParams.Resources ??= new List<string>();

if (!ReCapUtils.TryGetRecapFromResources(authParams.Resources, out var existingRecap))
if (!ReCap.TryGetRecapFromResources(authParams.Resources, out var existingRecap))
{
authParams.Resources.Add(recapStr);
}
Expand All @@ -971,7 +963,7 @@ await Task.WhenAll(
// using .RemoveAt to remove the last element given we already checked it's a recap and will replace it
authParams.Resources.RemoveAt(authParams.Resources.Count - 1);

var mergedRecap = ReCapUtils.MergeEncodedRecaps(recapStr, existingRecap);
var mergedRecap = ReCap.MergeEncodedRecaps(recapStr, existingRecap);
authParams.Resources.Add(mergedRecap);
}
}
Expand Down Expand Up @@ -1146,7 +1138,6 @@ public async Task RejectSessionAuthenticate(RejectParams rejectParams)
if (pendingRequest == null)
throw new InvalidOperationException($"No pending request found for the id {rejectParams.Id}");

// var receiverPublicKey = pendingRequest.Requester.PublicKey;
var senderPublicKey = await Client.CoreClient.Crypto.GenerateKeyPair();
var responseTopic = Client.CoreClient.Crypto.HashKey(senderPublicKey);

Expand Down Expand Up @@ -1197,10 +1188,10 @@ public async Task<SessionStruct> ApproveSessionAuthenticate(long requestId, Caca

var address = CacaoUtils.ExtractDidAddress(cacao.Payload.Iss);

if (ReCapUtils.TryGetRecapFromResources(cacao.Payload.Resources, out var recap))
if (ReCap.TryGetRecapFromResources(cacao.Payload.Resources, out var encodedRecap))
{
var methodsFromRecap = ReCapUtils.GetActionsFromRecap(recap);
var chainsFromRecap = ReCapUtils.GetChainsFromRecap(recap);
var methodsFromRecap = ReCap.GetActionsFromEncodedRecap(encodedRecap);
var chainsFromRecap = ReCap.GetChainsFromEncodedRecap(encodedRecap);

approvedMethods.UnionWith(methodsFromRecap);
approvedChains.UnionWith(chainsFromRecap);
Expand All @@ -1212,9 +1203,6 @@ public async Task<SessionStruct> ApproveSessionAuthenticate(long requestId, Caca
}
}

ReownLogger.Log($"Approved methods: {string.Join(", ", approvedMethods)}");
ReownLogger.Log($"Approved accounts: {string.Join(", ", approvedAccounts)}");

var sessionTopic = await Client.CoreClient.Crypto.GenerateSharedKey(senderPublicKey, receiverPublicKey);

SessionStruct session = default;
Expand Down Expand Up @@ -1244,15 +1232,12 @@ public async Task<SessionStruct> ApproveSessionAuthenticate(long requestId, Caca
PairingTopic = pendingRequest.PairingTopic
};

ReownLogger.Log($"Approving session with topic {sessionTopic}");
await Client.CoreClient.Relayer.Subscribe(sessionTopic);
await Client.Session.Set(sessionTopic, session);

ReownLogger.Log($"Updating session metadata for pairing topic {pendingRequest.PairingTopic}");
await Client.CoreClient.Pairing.UpdateMetadata(pendingRequest.PairingTopic, session.Peer.Metadata);
}

ReownLogger.Log("Sending response to session authenticate request");
await MessageHandler.SendResult<SessionAuthenticate, AuthenticateResponse>(requestId, responseTopic, new AuthenticateResponse
{
Cacaos = auths,
Expand Down
12 changes: 3 additions & 9 deletions src/Reown.Sign/Runtime/Internals/EngineHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -391,10 +391,10 @@ async Task IEnginePrivate.OnAuthenticateResponse(string topic, JsonRpcResponse<A
var approvedChains = new HashSet<string>();
var parsedAddress = CacaoUtils.ExtractDidAddress(cacao.Payload.Iss);

if (ReCapUtils.TryGetRecapFromResources(cacao.Payload.Resources, out var recapStr))
if (ReCap.TryGetRecapFromResources(cacao.Payload.Resources, out var recapStr))
{
var methodsFromRecap = ReCapUtils.GetActionsFromRecap(recapStr);
var chainsFromRecap = ReCapUtils.GetChainsFromRecap(recapStr);
var methodsFromRecap = ReCap.GetActionsFromEncodedRecap(recapStr);
var chainsFromRecap = ReCap.GetChainsFromEncodedRecap(recapStr);
approvedMethods.UnionWith(methodsFromRecap);
approvedChains.UnionWith(chainsFromRecap);
}
Expand Down Expand Up @@ -431,12 +431,6 @@ async Task IEnginePrivate.OnAuthenticateResponse(string topic, JsonRpcResponse<A
await Client.CoreClient.Relayer.Subscribe(sessionTopic);
await Client.Session.Set(sessionTopic, session);

// TODO: pairing topic
// if (!string.IsNullOrWhiteSpace(topic))
// {
// await Client.CoreClient.Pairing.UpdateMetadata(topic, responder.Metadata);
// }

session = Client.Session.Get(sessionTopic);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Reown.Sign/Runtime/Internals/EngineTasks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace Reown.Sign
{
public partial class Engine
{
async Task IEnginePrivate.DeletePendingSessionRequest(long id, Error reason, bool expirerHasDeleted = false)
async Task IEnginePrivate.DeletePendingSessionRequest(long id, Error reason, bool expirerHasDeleted)
{
await Task.WhenAll(
Client.PendingRequests.Delete(id, reason),
Expand Down
38 changes: 19 additions & 19 deletions src/Reown.Sign/Runtime/Models/AuthPayloadParams.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,46 +11,46 @@ namespace Reown.Sign.Models
public class AuthPayloadParams
{
[JsonProperty("chains")]
public string[] Chains;
public string[] Chains { get; set; }

[JsonProperty("domain")]
public string Domain;
public string Domain { get; set; }

[JsonProperty("nonce")]
public string Nonce;
public string Nonce { get; set; }

[JsonProperty("aud", NullValueHandling = NullValueHandling.Include)]
public string? Aud;
public string? Aud { get; set; }

[JsonProperty("type", NullValueHandling = NullValueHandling.Include)]
public string? Type;
public string? Type { get; set; }

[JsonProperty("nbf", NullValueHandling = NullValueHandling.Include)]
public string? Nbf;
public string? Nbf { get; set; }

[JsonProperty("exp", NullValueHandling = NullValueHandling.Include)]
public string? Exp;
public string? Exp { get; set; }

[JsonProperty("iat", NullValueHandling = NullValueHandling.Include)]
public string? Iat;
public string? Iat { get; set; }

[JsonProperty("statement", NullValueHandling = NullValueHandling.Include)]
public string? Statement;
public string? Statement { get; set; }

[JsonProperty("requestId", NullValueHandling = NullValueHandling.Ignore)]
public long? RequestId;
public long? RequestId { get; set; }

[JsonProperty("resources", NullValueHandling = NullValueHandling.Ignore)]
public List<string>? Resources;
public List<string>? Resources { get; set; }

[JsonProperty("pairingTopic", NullValueHandling = NullValueHandling.Ignore)]
public string? PairingTopic;
public string? PairingTopic { get; set; }

[JsonProperty("methods", NullValueHandling = NullValueHandling.Ignore)]
public string[]? Methods;
public string[]? Methods { get; set; }

[JsonProperty("version", NullValueHandling = NullValueHandling.Ignore)]
public string? Version;
public string? Version { get; set; }


public AuthPayloadParams()
Expand Down Expand Up @@ -85,28 +85,28 @@ public void Populate(ICollection<string> supportedCains, ICollection<string> sup

var statement = Statement ?? string.Empty;

if (!ReCapUtils.TryGetDecodedRecapFromResources(Resources, out var recap))
if (!ReCap.TryGetDecodedRecapFromResources(Resources, out var recap))
throw new InvalidOperationException("Recap not found in resources");

var actionsFromRecap = ReCapUtils.GetActionsFromRecap(recap);
var actionsFromRecap = recap.GetActions();
var approvedActions = actionsFromRecap.Intersect(supportedMethods).ToArray();
if (approvedActions.Length == 0)
throw new InvalidOperationException($"Supported methods don't satisfy the requested: {string.Join(", ", actionsFromRecap)}. "
+ $"Supported methods: {string.Join(", ", supportedMethods)}");

var updatedResources = Resources ?? new List<string>();
var formattedActions = ReCapUtils.AssignAbilityToActions("request", approvedActions, new Dictionary<string, object>
var formattedActions = ReCap.AssignAbilityToActions("request", approvedActions, new Dictionary<string, object>
{
{ "chains", approvedChains }
});

recap.AddResources("eip115", formattedActions);

updatedResources.RemoveAt(updatedResources.Count - 1);
updatedResources.Add(ReCapUtils.EncodeRecap(recap));
updatedResources.Add(recap.Encode());
Chains = approvedChains;
Methods = approvedActions;
Statement = ReCapUtils.FormatStatementFromRecap(recap, statement);
Statement = recap.FormatStatement(statement);
Resources = updatedResources;
}
}
Expand Down
28 changes: 14 additions & 14 deletions src/Reown.Sign/Runtime/Models/Cacao/CacaoPayload.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,37 +10,37 @@ namespace Reown.Sign.Models.Cacao
public class CacaoPayload
{
[JsonProperty("domain")]
public readonly string Domain;
public string Domain { get; }

[JsonProperty("iss")]
public readonly string Iss; // did:pkh
public string Iss { get; } // did:pkh

[JsonProperty("aud")]
public readonly string Aud;
public string Aud { get; }

[JsonProperty("version")]
public readonly string Version;
public string Version { get; }

[JsonProperty("nonce")]
public readonly string Nonce;
public string Nonce { get; }

[JsonProperty("iat")]
public readonly string IssuedAt;
public string IssuedAt { get; }

[JsonProperty("nbf")]
public readonly string? NotBefore;
public string? NotBefore { get; }

[JsonProperty("exp")]
public readonly string? Expiration;
public string? Expiration { get; }

[JsonProperty("statement", NullValueHandling = NullValueHandling.Ignore)]
public readonly string? Statement;
public string? Statement { get; }

[JsonProperty("requestId", NullValueHandling = NullValueHandling.Ignore)]
public readonly string? RequestId;
public string? RequestId { get; }

[JsonProperty("resources", NullValueHandling = NullValueHandling.Ignore)]
public readonly string[]? Resources;
public string[]? Resources { get; }

public CacaoPayload(
string domain,
Expand Down Expand Up @@ -106,10 +106,10 @@ public string FormatMessage()
? $"Resources:\n{string.Join('\n', Resources.Select(resource => $"- {resource}"))}"
: null;

if (ReCapUtils.TryGetRecapFromResources(Resources, out var recapStr))
if (ReCap.TryGetRecapFromResources(Resources, out var recapStr))
{
var decoded = ReCapUtils.DecodeRecap(recapStr);
statement ??= ReCapUtils.FormatStatementFromRecap(decoded, statement);
var decoded = ReCap.Decode(recapStr);
statement ??= decoded.FormatStatement(statement);
}

var message = string.Join('\n', new[]
Expand Down
Loading

0 comments on commit 90f7b97

Please sign in to comment.