This repository has been archived by the owner on May 28, 2021. It is now read-only.
/
listener.ts
298 lines (279 loc) · 10.9 KB
/
listener.ts
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
import { RegisteredAppDetails, SupportedApplications } from "@connext/types";
import {
CreateChannelMessage,
DepositConfirmationMessage,
InstallMessage,
InstallVirtualMessage,
Node,
ProposeMessage,
ProposeVirtualMessage,
RejectInstallVirtualMessage,
UninstallMessage,
UninstallVirtualMessage,
UpdateStateMessage,
WithdrawMessage,
} from "@counterfactual/node";
import { AppInstanceInfo, Node as NodeTypes } from "@counterfactual/types";
import { bigNumberify } from "ethers/utils";
import { EventEmitter } from "events";
import { ConnextInternal } from "./connext";
import { Logger } from "./lib/logger";
import { replaceBN } from "./lib/utils";
import { appProposalValidation } from "./validation/appProposals";
// TODO: index of connext events only?
type CallbackStruct = {
[index in keyof typeof NodeTypes.EventName]: (data: any) => Promise<any> | void;
};
export class ConnextListener extends EventEmitter {
private log: Logger;
private cfModule: Node;
private connext: ConnextInternal;
// TODO: add custom parsing functions here to convert event data
// to something more usable?
private defaultCallbacks: CallbackStruct = {
COUNTER_DEPOSIT_CONFIRMED: (data: DepositConfirmationMessage): void => {
this.emitAndLog(NodeTypes.EventName.COUNTER_DEPOSIT_CONFIRMED, data.data);
},
CREATE_CHANNEL: (data: CreateChannelMessage): void => {
this.emitAndLog(NodeTypes.EventName.CREATE_CHANNEL, data.data);
},
DEPOSIT_CONFIRMED: async (data: DepositConfirmationMessage): Promise<void> => {
this.emitAndLog(NodeTypes.EventName.DEPOSIT_CONFIRMED, data);
},
DEPOSIT_FAILED: (data: any): void => {
this.emitAndLog(NodeTypes.EventName.DEPOSIT_FAILED, data);
},
DEPOSIT_STARTED: (data: any): void => {
this.log.info(`deposit for ${data.value.toString()} started. hash: ${data.txHash}`);
this.emitAndLog(NodeTypes.EventName.DEPOSIT_STARTED, data);
},
INSTALL: (data: InstallMessage): void => {
this.emitAndLog(NodeTypes.EventName.INSTALL, data.data);
},
// TODO: make cf return app instance id and app def?
INSTALL_VIRTUAL: (data: InstallVirtualMessage): void => {
this.emitAndLog(NodeTypes.EventName.INSTALL_VIRTUAL, data.data);
},
PROPOSE_INSTALL: async (data: ProposeMessage): Promise<void> => {
// validate and automatically install for the known and supported
// applications
this.emitAndLog(NodeTypes.EventName.PROPOSE_INSTALL, data.data);
// check if message is from us, return if so
// FIXME: type of ProposeMessage should extend Node.NodeMessage, which
// has a from field, but ProposeMessage does not
if ((data as any).from === this.cfModule.publicIdentifier) {
this.log.info(
`Received proposal from our own node, doing nothing: ${JSON.stringify(data)}`,
);
return;
}
// check based on supported applications
// matched app, take appropriate default actions
const matchedResult = await this.matchAppInstance(data);
if (!matchedResult) {
this.log.warn(`No matched app, doing nothing, ${JSON.stringify(data)}`);
return;
}
// matched app, take appropriate default actions
const { appInfo, matchedApp } = matchedResult;
await this.verifyAndInstallKnownApp(appInfo, matchedApp, false);
return;
},
PROPOSE_INSTALL_VIRTUAL: async (data: ProposeVirtualMessage): Promise<void> => {
// validate and automatically install for the known and supported
// applications
this.emitAndLog(NodeTypes.EventName.PROPOSE_INSTALL_VIRTUAL, data.data);
// if the from is us, ignore
// FIXME: type of ProposeVirtualMessage should extend Node.NodeMessage,
// which has a from field, but ProposeVirtualMessage does not
if ((data as any).from === this.cfModule.publicIdentifier) {
return;
}
// check based on supported applications
// matched app, take appropriate default actions
const matchedResult = await this.matchAppInstance(data);
if (!matchedResult) {
return;
}
// matched app, take appropriate default actions
const { appInfo, matchedApp } = matchedResult;
await this.verifyAndInstallKnownApp(appInfo, matchedApp);
return;
},
PROPOSE_STATE: (data: any): void => {
// TODO: validate the proposed state
// TODO: are we using this flow in any of the known/supported
// applications
this.emitAndLog(NodeTypes.EventName.PROPOSE_STATE, data);
},
PROTOCOL_MESSAGE_EVENT: (data: any): void => {
this.emitAndLog(NodeTypes.EventName.PROTOCOL_MESSAGE_EVENT, data);
},
REJECT_INSTALL: (data: any): void => {
this.emitAndLog(NodeTypes.EventName.REJECT_INSTALL, data);
},
REJECT_INSTALL_VIRTUAL: (data: RejectInstallVirtualMessage): void => {
this.emitAndLog(NodeTypes.EventName.REJECT_INSTALL_VIRTUAL, data.data);
},
REJECT_STATE: (data: any): void => {
this.emitAndLog(NodeTypes.EventName.REJECT_STATE, data);
},
UNINSTALL: (data: UninstallMessage): void => {
this.emitAndLog(NodeTypes.EventName.UNINSTALL, data.data);
},
UNINSTALL_VIRTUAL: (data: UninstallVirtualMessage): void => {
this.emitAndLog(NodeTypes.EventName.UNINSTALL_VIRTUAL, data.data);
},
UPDATE_STATE: (data: UpdateStateMessage): void => {
this.emitAndLog(NodeTypes.EventName.UPDATE_STATE, data.data);
},
WITHDRAW_EVENT: (data: any): void => {
this.emitAndLog(NodeTypes.EventName.WITHDRAW_EVENT, data);
},
WITHDRAWAL_CONFIRMED: (data: WithdrawMessage): void => {
this.emitAndLog(NodeTypes.EventName.WITHDRAWAL_CONFIRMED, data.data);
},
WITHDRAWAL_FAILED: (data: any): void => {
this.emitAndLog(NodeTypes.EventName.WITHDRAWAL_FAILED, data);
},
WITHDRAWAL_STARTED: (data: any): void => {
this.log.info(`withdrawal for ${data.value.toString()} started. hash: ${data.txHash}`);
this.emitAndLog(NodeTypes.EventName.WITHDRAWAL_STARTED, data);
},
};
constructor(cfModule: Node, connext: ConnextInternal) {
super();
this.cfModule = cfModule;
this.connext = connext;
this.log = new Logger("ConnextListener", connext.opts.logLevel);
}
public register = async (): Promise<void> => {
await this.registerAvailabilitySubscription();
this.registerDefaultCfListeners();
return;
};
public registerCfListener = (event: NodeTypes.EventName, cb: Function): void => {
// replace with new fn
this.log.info(`Registering listener for ${event}`);
// TODO: type res by obj with event as keys?
this.cfModule.on(event, async (res: any) => {
await cb(res);
this.emit(event, res);
});
};
public removeCfListener = (event: NodeTypes.EventName, cb: Function): boolean => {
this.log.info(`Removing listener for ${event}`);
try {
this.removeListener(event, cb as any);
return true;
} catch (e) {
this.log.error(
`Error trying to remove registered listener from event: ${event}. Error: ${e.message}`,
);
return false;
}
};
public registerDefaultCfListeners = (): void => {
Object.entries(this.defaultCallbacks).forEach(([event, callback]: any): any => {
this.cfModule.on(NodeTypes.EventName[event], callback);
});
};
private emitAndLog = (event: NodeTypes.EventName, data: any): void => {
this.log.info(`Emitted ${event}`);
this.emit(event, data);
};
private matchAppInstance = async (
data: ProposeVirtualMessage | ProposeMessage,
): Promise<{ matchedApp: RegisteredAppDetails; appInfo: AppInstanceInfo } | undefined> => {
const filteredApps = this.connext.appRegistry.filter((app: RegisteredAppDetails) => {
return app.appDefinitionAddress === data.data.params.appDefinition;
});
if (!filteredApps || filteredApps.length === 0) {
this.log.info(
`Proposed app not in registered applications. App: ${JSON.stringify(data, replaceBN, 2)}`,
);
return undefined;
}
if (filteredApps.length > 1) {
// TODO: throw error here?
this.log.error(
`Proposed app matched ${
filteredApps.length
} registered applications by definition address. App: ${JSON.stringify(
data,
replaceBN,
2,
)}`,
);
return undefined;
}
// matched app, take appropriate default actions
return {
appInfo: {
...data.data.params,
identityHash: data.data.appInstanceId,
initiatorDeposit: bigNumberify(data.data.params.initiatorDeposit),
initiatorDepositTokenAddress: data.data.params.initiatorDepositTokenAddress,
proposedByIdentifier: data.from,
responderDeposit: bigNumberify(data.data.params.responderDeposit),
responderDepositTokenAddress: data.data.params.responderDepositTokenAddress,
},
matchedApp: filteredApps[0],
};
};
private verifyAndInstallKnownApp = async (
appInstance: AppInstanceInfo,
matchedApp: RegisteredAppDetails,
isVirtual: boolean = true,
): Promise<void> => {
const invalidProposal = await appProposalValidation[matchedApp.name](
appInstance,
matchedApp,
isVirtual,
this.connext,
);
if (invalidProposal) {
// reject app installation
this.log.error(`Proposed app is invalid. ${invalidProposal}`);
await this.connext.rejectInstallApp(appInstance.identityHash);
return;
}
// proposal is valid, automatically install known app, but
// do not ever automatically install swap app since theres no
// way to validate the exchange in app against the rate input
// to controller
// this means the hub can only install apps, and cannot propose a swap
// and there cant easily be an automatic install swap app between users
if (matchedApp.name === SupportedApplications.SimpleTwoPartySwapApp) {
return;
}
if (matchedApp.name === SupportedApplications.UnidirectionalTransferApp) {
// request collateral in token of the app
await this.connext.requestCollateral(appInstance.initiatorDepositTokenAddress);
}
this.log.info(`Proposal for app install successful, attempting install now...`);
let res: NodeTypes.InstallResult;
if (isVirtual) {
res = await this.connext.installVirtualApp(appInstance.identityHash);
} else {
res = await this.connext.installApp(appInstance.identityHash);
}
this.log.info(`App installed, res: ${JSON.stringify(res, replaceBN, 2)}`);
return;
};
private registerAvailabilitySubscription = async (): Promise<void> => {
const subject = `online.${this.connext.publicIdentifier}`;
await this.connext.messaging.subscribe(subject, async (msg: any) => {
if (!msg.reply) {
this.log.info(`No reply found for msg: ${msg}`);
return;
}
const response = true;
this.connext.messaging.publish(msg.reply, {
err: null,
response,
});
});
this.log.info(`Connected message pattern "${subject}"`);
};
}