-
Notifications
You must be signed in to change notification settings - Fork 3
/
DynamicEncryptionRouter.ts
245 lines (233 loc) · 8.53 KB
/
DynamicEncryptionRouter.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
import { MessageKey } from '../content';
import { symmetricEncrypt } from '../crypto';
import { PublicKeyType } from '../primitives';
import { EncryptionPublicKey } from '../primitives/EncryptionPublicKey';
import { YlideError, YlideErrorType } from '../errors';
import { randomBytes, box as naclbox } from 'tweetnacl';
import type { Uint256 } from '../primitives/Uint256';
import type { IExtraEncryptionStrateryEntry, PublicKey } from '../primitives';
import type { YlideCore } from '../core';
import type { MessageSecureContext } from '../content/MessageSecureContext';
import type { AbstractBlockchainController } from '../abstracts';
export interface IAvailableStrategy {
type: string;
blockchainController: AbstractBlockchainController;
data: { ylide: true; publicKey: PublicKey } | IExtraEncryptionStrateryEntry;
}
export class DynamicEncryptionRouter {
static async findEncyptionRoute(
core: YlideCore,
recipients: {
keyAddress: Uint256;
keyAddressOriginal: string;
address: Uint256;
}[],
blockchainControllers: AbstractBlockchainController[],
preferredStrategy = 'ylide',
) {
const recipientsMap = await this.identifyEncryptionStrategies(
core,
recipients.map(r => ({ address: r.keyAddress, original: r.keyAddressOriginal })),
blockchainControllers,
);
return this.findBestEncryptionRouting(recipients, recipientsMap, blockchainControllers, preferredStrategy);
}
private static panic(): never {
throw new YlideError(YlideErrorType.MUST_NEVER_HAPPEN, 'Panic: must never happen');
}
static async executeEncryption(
route: ReturnType<(typeof DynamicEncryptionRouter)['findBestEncryptionRouting']>,
secureContext: MessageSecureContext,
) {
const ylideEphemeral = naclbox.keyPair.fromSecretKey(randomBytes(32));
const ylideEphemeralPublic = new EncryptionPublicKey(PublicKeyType.YLIDE, ylideEphemeral.publicKey);
const publicKeys: EncryptionPublicKey[] = [];
const result: { address: Uint256; messageKey: MessageKey }[] = [];
for (const entity of route) {
if (entity.type === 'ylide') {
const pkIdx = publicKeys.push(ylideEphemeralPublic) - 1;
result.push(
...entity.entries.map((entry, idx) => ({
address: entity.recipients[idx].address,
messageKey: new MessageKey(
pkIdx,
entry.ylide ? entry.publicKey.signature : this.panic(),
entry.ylide
? symmetricEncrypt(
secureContext.key,
naclbox.before(entry.publicKey.keyBytes, ylideEphemeral.secretKey),
)
: this.panic(),
),
})),
);
} else {
const entries: IExtraEncryptionStrateryEntry[] = entity.entries as IExtraEncryptionStrateryEntry[];
const bulk = await entity.blockchainController.prepareExtraEncryptionStrategyBulk(entries);
let pkIdx: number | null = null;
if (bulk.addedPublicKey) {
pkIdx = publicKeys.push(bulk.addedPublicKey.key) - 1;
}
const temp = await entity.blockchainController.executeExtraEncryptionStrategy(
entries,
bulk,
pkIdx,
secureContext.key,
);
result.push(
...temp.map((t, idx) => ({
address: entity.blockchainController.addressToUint256(entries[idx].address),
messageKey: t,
})),
);
}
}
return {
processedRecipients: result,
publicKeys,
};
}
private static async identifyEncryptionStrategies(
core: YlideCore,
recipients: { address: Uint256; original: string }[],
blockchainControllers: AbstractBlockchainController[],
) {
const recipientsMap: Record<Uint256, IAvailableStrategy[]> = {};
const ylideKeys = await core.getAddressesKeys(recipients.map(r => r.original));
for (const recipient of recipients) {
for (const blockchainController of blockchainControllers) {
if (!blockchainController.isAddressValid(recipient.original)) {
continue;
}
const arr = recipientsMap[recipient.address] || [];
const strategies = [];
const ylideKey = ylideKeys[recipient.original].freshestKey;
if (ylideKey) {
strategies.push({
type: 'ylide',
blockchainController,
data: { ylide: true as const, publicKey: ylideKey.publicKey },
});
}
const nativeStrategies = await blockchainController.getExtraEncryptionStrategiesFromAddress(
recipient.original,
);
strategies.push(
...nativeStrategies.map(ns => ({
type: ns.type,
blockchainController,
data: ns,
})),
);
arr.push(...strategies);
recipientsMap[recipient.address] = arr;
}
}
return recipientsMap;
}
private static getStrategiesFrequency(strategies: string[][]): Record<string, number> {
const result: Record<string, number> = {};
for (const recipientStrategies of strategies) {
for (const strategy of recipientStrategies) {
result[strategy] = (result[strategy] || 0) + 1;
}
}
return result;
}
private static getMostFrequent(frequencies: Record<string, number>): string {
const reverseMap = Object.keys(frequencies).map(strategy => ({
strategy,
frequency: frequencies[strategy],
}));
reverseMap.sort((a, b) => b.frequency - a.frequency); // desc
return reverseMap[0].strategy;
}
private static findBestEncryptionRouting(
recipients: { keyAddress: Uint256; keyAddressOriginal: string; address: Uint256 }[],
recipientsMap: Record<Uint256, IAvailableStrategy[]>,
blockchainControllers: AbstractBlockchainController[],
preferredStrategy = 'ylide',
) {
const usedStrategies: Record<string, boolean> = {};
const selectedStrategyMap: Record<Uint256, IAvailableStrategy | null> = {};
const uniqueRecipientStrategies: Record<Uint256, string[]> = {};
const badBoys: Record<Uint256, boolean> = {};
let ambigiousRecipients = [];
for (const recipient of recipients) {
const map = recipientsMap[recipient.keyAddress];
if (map.length === 0) {
badBoys[recipient.keyAddress] = true;
selectedStrategyMap[recipient.keyAddress] = null;
}
const uniqueStrategies = map.map(ns => ns.type).filter((e, i, a) => a.indexOf(e) === i);
if (uniqueStrategies.length === 0) {
badBoys[recipient.keyAddress] = true;
selectedStrategyMap[recipient.keyAddress] = null;
// should never happen, actually
} else if (uniqueStrategies.length === 1) {
usedStrategies[uniqueStrategies[0]] = true;
selectedStrategyMap[recipient.keyAddress] = map.find(s => s.type === uniqueStrategies[0])!;
} else {
uniqueRecipientStrategies[recipient.keyAddress] = uniqueStrategies;
}
}
for (const recipient of recipients) {
if (selectedStrategyMap[recipient.keyAddress] || badBoys[recipient.keyAddress]) {
continue;
}
const uniqueStrategies = uniqueRecipientStrategies[recipient.keyAddress];
const availableStrategy = uniqueStrategies.find(uS => usedStrategies[uS]);
if (!availableStrategy) {
if (uniqueStrategies.includes(preferredStrategy)) {
usedStrategies[preferredStrategy] = true;
selectedStrategyMap[recipient.keyAddress] = recipientsMap[recipient.keyAddress].find(
s => s.type === preferredStrategy,
)!;
} else {
ambigiousRecipients.push(recipient);
}
continue;
}
selectedStrategyMap[recipient.keyAddress] = recipientsMap[recipient.keyAddress].find(
s => s.type === availableStrategy,
)!;
}
while (ambigiousRecipients.length) {
const frequencies = this.getStrategiesFrequency(
ambigiousRecipients.map(r => uniqueRecipientStrategies[r.keyAddress]),
);
const mostFrequent = this.getMostFrequent(frequencies);
const newAmbigiousRecipients = [];
for (const rec of ambigiousRecipients) {
const strats = uniqueRecipientStrategies[rec.keyAddress];
if (strats.includes(mostFrequent)) {
usedStrategies[mostFrequent] = true;
selectedStrategyMap[rec.keyAddress] = recipientsMap[rec.keyAddress].find(
s => s.type === mostFrequent,
)!;
} else {
newAmbigiousRecipients.push(rec);
}
}
ambigiousRecipients = newAmbigiousRecipients;
}
const strategiesList = Object.keys(usedStrategies);
const strategiesControllers: Record<string, AbstractBlockchainController> = {};
for (const strategy of strategiesList) {
strategiesControllers[strategy] = blockchainControllers.find(c =>
c.getSupportedExtraEncryptionStrategies().includes(strategy),
)!;
}
const route = strategiesList.map(strategy => {
const recs = recipients.filter(r => selectedStrategyMap[r.keyAddress]?.type === strategy);
return {
type: strategy,
blockchainController: strategiesControllers[strategy] || null,
recipients: recs,
entries: recs.map(r => selectedStrategyMap[r.keyAddress]!.data),
};
});
route.sort((a, b) => b.recipients.length - a.recipients.length); // desc
return route;
}
}