-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathEngineHandler.cs
354 lines (324 loc) · 13.4 KB
/
EngineHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WalletConnectSharp.Common.Logging;
using WalletConnectSharp.Common.Model.Errors;
using WalletConnectSharp.Common.Utils;
using WalletConnectSharp.Core.Models.Expirer;
using WalletConnectSharp.Network.Models;
using WalletConnectSharp.Sign.Interfaces;
using WalletConnectSharp.Sign.Models;
using WalletConnectSharp.Sign.Models.Engine.Events;
using WalletConnectSharp.Sign.Models.Engine.Methods;
namespace WalletConnectSharp.Sign
{
public partial class Engine
{
async void ExpiredCallback(object sender, ExpirerEventArgs e)
{
var target = new ExpirerTarget(e.Target);
if (target.Id != null && this.Client.PendingRequests.Keys.Contains((long)target.Id))
{
await PrivateThis.DeletePendingSessionRequest((long)target.Id,
Error.FromErrorType(ErrorType.EXPIRED), true);
return;
}
if (!string.IsNullOrWhiteSpace(target.Topic))
{
var topic = target.Topic;
if (!this.Client.Session.Keys.Contains(topic))
{
return;
}
var session = this.Client.Session.Get(topic);
await PrivateThis.DeleteSession(topic);
this.SessionExpired?.Invoke(this, session);
this.SessionDeleted?.Invoke(this, new SessionEvent()
{
Topic = topic
});
}
else if (target.Id != null)
{
await PrivateThis.DeleteProposal((long) target.Id);
}
}
async Task IEnginePrivate.OnSessionProposeRequest(string topic, JsonRpcRequest<SessionPropose> payload)
{
var @params = payload.Params;
var id = payload.Id;
try
{
var expiry = Clock.CalculateExpiry(Clock.FIVE_MINUTES);
var proposal = new ProposalStruct()
{
Id = id,
PairingTopic = topic,
Expiry = expiry,
Proposer = @params.Proposer,
Relays = @params.Relays,
RequiredNamespaces = @params.RequiredNamespaces,
OptionalNamespaces = @params.OptionalNamespaces,
SessionProperties = @params.SessionProperties,
};
await PrivateThis.SetProposal(id, proposal);
var hash = HashUtils.HashMessage(JsonConvert.SerializeObject(payload));
var verifyContext = await this.VerifyContext(hash, proposal.Proposer.Metadata);
this.SessionProposed?.Invoke(this, new SessionProposalEvent()
{
Id = id,
Proposal = proposal,
VerifiedContext = verifyContext
});
}
catch (WalletConnectException e)
{
await MessageHandler.SendError<SessionPropose, SessionProposeResponseAutoReject>(id, topic,
Error.FromException(e));
}
}
async Task IEnginePrivate.OnSessionProposeResponse(string topic, JsonRpcResponse<SessionProposeResponse> payload)
{
var id = payload.Id;
logger.Log($"Got session propose response with id {id}");
if (payload.IsError)
{
logger.LogError("response was error");
await this.Client.Proposal.Delete(id, Error.FromErrorType(ErrorType.USER_DISCONNECTED));
this.SessionConnectionErrored?.Invoke(this, payload.Error.ToException());
}
else
{
logger.Log("response was success");
var result = payload.Result;
var proposal = this.Client.Proposal.Get(id);
var selfPublicKey = proposal.Proposer.PublicKey;
var peerPublicKey = result.ResponderPublicKey;
var sessionTopic = await this.Client.Core.Crypto.GenerateSharedKey(
selfPublicKey,
peerPublicKey
);
await this.Client.Core.Pairing.Activate(topic);
logger.Log($"pairing activated for topic {topic}");
// try to do this a couple of times .. do it until it works?
int attempts = 5;
do
{
try
{
_ = await Client.Core.Relayer.Subscribe(sessionTopic);
return;
}
catch (Exception e)
{
WCLogger.LogError($"Got error subscribing to topic, attempts left: {attempts}");
WCLogger.LogError(e);
attempts--;
await Task.Yield();
}
} while (attempts > 0);
throw new IOException($"Could not subscribe to session topic {sessionTopic}");
}
}
async Task IEnginePrivate.OnSessionSettleRequest(string topic, JsonRpcRequest<SessionSettle> payload)
{
var id = payload.Id;
var @params = payload.Params;
logger.Log($"got session settle request with {id}");
try
{
await PrivateThis.IsValidSessionSettleRequest(@params);
var pairingTopic = @params.PairingTopic;
var relay = @params.Relay;
var controller = @params.Controller;
var expiry = @params.Expiry;
var namespaces = @params.Namespaces;
var session = new SessionStruct()
{
Topic = topic,
PairingTopic = pairingTopic,
Relay = relay,
Expiry = expiry,
Namespaces = namespaces,
Acknowledged = true,
Controller = controller.PublicKey,
Self = new Participant()
{
Metadata = this.Client.Metadata,
PublicKey = ""
},
Peer = new Participant()
{
PublicKey = controller.PublicKey,
Metadata = controller.Metadata
},
#pragma warning disable S6602
RequiredNamespaces = Client.Proposal.Values.FirstOrDefault(p => p.PairingTopic == pairingTopic).RequiredNamespaces
#pragma warning restore S6602
};
await MessageHandler.SendResult<SessionSettle, bool>(payload.Id, topic, true);
this.SessionConnected?.Invoke(this, session);
}
catch (WalletConnectException e)
{
logger.LogError("got error while performing session settle");
logger.LogError(e);
await MessageHandler.SendError<SessionSettle, bool>(id, topic, Error.FromException(e));
}
}
async Task IEnginePrivate.OnSessionSettleResponse(string topic, JsonRpcResponse<bool> payload)
{
var id = payload.Id;
var session = this.Client.Session.Get(topic);
if (payload.IsError)
{
var error = Error.FromErrorType(ErrorType.USER_DISCONNECTED);
await this.Client.Session.Delete(topic, error);
this.SessionRejected?.Invoke(this, session);
// Still used do not remove
_sessionEventsHandlerMap[$"session_approve{id}"](this, payload);
}
else
{
await this.Client.Session.Update(topic, new SessionStruct()
{
Acknowledged = true
});
this.SessionApproved?.Invoke(this, session);
_sessionEventsHandlerMap[$"session_approve{id}"](this, payload);
}
}
async Task IEnginePrivate.OnSessionUpdateRequest(string topic, JsonRpcRequest<SessionUpdate> payload)
{
var @params = payload.Params;
var id = payload.Id;
try
{
await PrivateThis.IsValidUpdate(topic, @params.Namespaces);
await this.Client.Session.Update(topic, new SessionStruct()
{
Namespaces = @params.Namespaces
});
await MessageHandler.SendResult<SessionUpdate, bool>(id, topic, true);
this.SessionUpdateRequest?.Invoke(this, new SessionUpdateEvent()
{
Id = id,
Topic = topic,
Params = @params
});
}
catch (WalletConnectException e)
{
await MessageHandler.SendError<SessionUpdate, bool>(id, topic, Error.FromException(e));
}
}
async Task IEnginePrivate.OnSessionUpdateResponse(string topic, JsonRpcResponse<bool> payload)
{
var id = payload.Id;
this.SessionUpdated?.Invoke(this, new SessionEvent()
{
Id = id,
Topic = topic,
});
// Still used, do not remove
_sessionEventsHandlerMap[$"session_update{id}"](this, payload);
}
async Task IEnginePrivate.OnSessionExtendRequest(string topic, JsonRpcRequest<SessionExtend> payload)
{
var id = payload.Id;
try
{
await PrivateThis.IsValidExtend(topic);
await PrivateThis.SetExpiry(topic, Clock.CalculateExpiry(SessionExpiry));
await MessageHandler.SendResult<SessionExtend, bool>(id, topic, true);
this.SessionExtendRequest?.Invoke(this, new SessionEvent()
{
Id = id,
Topic = topic
});
}
catch (WalletConnectException e)
{
await MessageHandler.SendError<SessionExtend, bool>(id, topic, Error.FromException(e));
}
}
async Task IEnginePrivate.OnSessionExtendResponse(string topic, JsonRpcResponse<bool> payload)
{
var id = payload.Id;
this.SessionExtended?.Invoke(this, new SessionEvent()
{
Topic = topic,
Id = id
});
// Still used, do not remove
_sessionEventsHandlerMap[$"session_extend{id}"](this, payload);
}
async Task IEnginePrivate.OnSessionPingRequest(string topic, JsonRpcRequest<SessionPing> payload)
{
var id = payload.Id;
try
{
await PrivateThis.IsValidPing(topic);
await MessageHandler.SendResult<SessionPing, bool>(id, topic, true);
this.SessionPinged?.Invoke(this, new SessionEvent()
{
Id = id,
Topic = topic
});
}
catch (WalletConnectException e)
{
await MessageHandler.SendError<SessionPing, bool>(id, topic, Error.FromException(e));
}
}
async Task IEnginePrivate.OnSessionPingResponse(string topic, JsonRpcResponse<bool> payload)
{
var id = payload.Id;
// put at the end of the stack to avoid a race condition
// where session_ping listener is not yet initialized
await Task.Delay(500);
this.SessionPinged?.Invoke(this, new SessionEvent()
{
Id = id,
Topic = topic
});
// Still used, do not remove
_sessionEventsHandlerMap[$"session_ping{id}"](this, payload);
}
async Task IEnginePrivate.OnSessionDeleteRequest(string topic, JsonRpcRequest<SessionDelete> payload)
{
var id = payload.Id;
try
{
await PrivateThis.IsValidDisconnect(topic, payload.Params);
await MessageHandler.SendResult<SessionDelete, bool>(id, topic, true);
await PrivateThis.DeleteSession(topic);
this.SessionDeleted?.Invoke(this, new SessionEvent()
{
Topic = topic,
Id = id
});
}
catch (WalletConnectException e)
{
await MessageHandler.SendError<SessionDelete, bool>(id, topic, Error.FromException(e));
}
}
async Task IEnginePrivate.OnSessionEventRequest(string topic, JsonRpcRequest<SessionEvent<JToken>> payload)
{
var @params = payload.Params;
var id = payload.Id;
try
{
var eventData = @params.Event;
var eventName = eventData.Name;
await PrivateThis.IsValidEmit(topic, eventData, @params.ChainId);
_customSessionEventsHandlerMap[eventName]?.Invoke(this, @params);
await MessageHandler.SendResult<SessionEvent<EventData<JToken>>, bool>(id, topic, true);
}
catch (WalletConnectException e)
{
await MessageHandler.SendError<SessionEvent<JToken>, bool>(id, topic, Error.FromException(e));
}
}
}
}