-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathResolver.ts
300 lines (259 loc) · 9.75 KB
/
Resolver.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
299
300
import {
OperationType,
Multihash,
IVersionManager,
IOperationStore,
DidState,
AnchoredOperationModel,
Logger,
SidetreeError,
} from '@sidetree/common';
/**
* NOTE: Resolver cannot be versioned because it needs to be aware of `VersionManager` to fetch versioned operation processors.
*/
export default class Resolver {
public constructor(
private versionManager: IVersionManager,
private operationStore: IOperationStore
) {}
/**
* Resolve the given DID unique suffix to its latest DID state.
* @param didUniqueSuffix The unique suffix of the DID to resolve. e.g. if 'did:sidetree:abc123' is the DID, the unique suffix would be 'abc123'
* @returns Final DID state of the DID. Undefined if the unique suffix of the DID is not found or the DID state is not constructable.
*/
public async resolve(didUniqueSuffix: string): Promise<DidState | undefined> {
Logger.info(`Resolving DID unique suffix '${didUniqueSuffix}'...`);
const operations = await this.operationStore.get(didUniqueSuffix);
const operationsByType = Resolver.categorizeOperationsByType(operations);
// Find and apply a valid create operation.
let didState = await this.applyCreateOperation(
operationsByType.createOperations
);
// If can't construct an initial DID state.
if (didState === undefined) {
return undefined;
}
// Apply recovery/deactivate operations until an operation matching the next recovery commitment cannot be found.
const recoverAndDeactivateOperations = operationsByType.recoverOperations.concat(
operationsByType.deactivateOperations
);
const recoveryCommitValueToOperationMap = await this.constructCommitValueToOperationLookupMap(
recoverAndDeactivateOperations
);
didState = await this.applyRecoverAndDeactivateOperations(
didState,
recoveryCommitValueToOperationMap
);
// If the previous applied operation is a deactivate. No need to continue further.
if (didState.nextRecoveryCommitmentHash === undefined) {
return didState;
}
// Apply update operations until an operation matching the next update commitment cannot be found.
const updateCommitValueToOperationMap = await this.constructCommitValueToOperationLookupMap(
operationsByType.updateOperations
);
didState = await this.applyUpdateOperations(
didState,
updateCommitValueToOperationMap
);
return didState;
}
private static categorizeOperationsByType(
operations: AnchoredOperationModel[]
): {
createOperations: AnchoredOperationModel[];
recoverOperations: AnchoredOperationModel[];
updateOperations: AnchoredOperationModel[];
deactivateOperations: AnchoredOperationModel[];
} {
const createOperations = [];
const recoverOperations = [];
const updateOperations = [];
const deactivateOperations = [];
for (const operation of operations) {
if (operation.type === OperationType.Create) {
createOperations.push(operation);
} else if (operation.type === OperationType.Recover) {
recoverOperations.push(operation);
} else if (operation.type === OperationType.Update) {
updateOperations.push(operation);
} else {
// This is a deactivate operation.
deactivateOperations.push(operation);
}
}
return {
createOperations,
recoverOperations,
updateOperations,
deactivateOperations,
};
}
/**
* Iterate through all duplicates of creates until we can construct an initial DID state (some creates maybe incomplete. eg. without `delta`).
*/
private async applyCreateOperation(
createOperations: AnchoredOperationModel[]
): Promise<DidState | undefined> {
let didState;
for (const createOperation of createOperations) {
didState = await this.applyOperation(createOperation, undefined);
// Exit loop as soon as we can construct an initial state.
if (didState !== undefined) {
break;
}
}
return didState;
}
/**
* Apply recovery/deactivate operations until an operation matching the next recovery commitment cannot be found.
*/
private async applyRecoverAndDeactivateOperations(
startingDidState: DidState,
commitValueToOperationMap: Map<string, AnchoredOperationModel[]>
): Promise<DidState> {
let didState = startingDidState;
while (
commitValueToOperationMap.has(didState.nextRecoveryCommitmentHash!)
) {
let operationsWithCorrectRevealValue: AnchoredOperationModel[] = commitValueToOperationMap.get(
didState.nextRecoveryCommitmentHash!
)!;
// Sort using blockchain time.
operationsWithCorrectRevealValue = operationsWithCorrectRevealValue.sort(
(a, b) => a.transactionNumber - b.transactionNumber
);
const newDidState:
| DidState
| undefined = await this.applyFirstValidOperation(
operationsWithCorrectRevealValue,
didState
);
// We are done if we can't find a valid recover/deactivate operation to apply.
if (newDidState === undefined) {
break;
}
// We reach here if we have successfully computed a new DID state.
didState = newDidState;
// If the previous applied operation is a deactivate. No need to continue further.
if (didState.nextRecoveryCommitmentHash === undefined) {
return didState;
}
}
return didState;
}
/**
* Apply update operations until an operation matching the next update commitment cannot be found.
*/
private async applyUpdateOperations(
startingDidState: DidState,
commitValueToOperationMap: Map<string, AnchoredOperationModel[]>
): Promise<DidState> {
let didState = startingDidState;
while (commitValueToOperationMap.has(didState.nextUpdateCommitmentHash!)) {
let operationsWithCorrectRevealValue: AnchoredOperationModel[] = commitValueToOperationMap.get(
didState.nextUpdateCommitmentHash!
)!;
// Sort using blockchain time.
operationsWithCorrectRevealValue = operationsWithCorrectRevealValue.sort(
(a, b) => a.transactionNumber - b.transactionNumber
);
const newDidState:
| DidState
| undefined = await this.applyFirstValidOperation(
operationsWithCorrectRevealValue,
didState
);
// We are done if we can't find a valid update operation to apply.
if (newDidState === undefined) {
break;
}
// We reach here if we have successfully computed a new DID state.
didState = newDidState;
}
return didState;
}
/**
* Applies the given operation to the given DID state.
* @param operation The operation to be applied.
* @param didState The DID state to apply the operation on top of.
* @returns The resultant `DidState`. The given DID state is return if the given operation cannot be applied.
*/
private async applyOperation(
operation: AnchoredOperationModel,
didState: DidState | undefined
): Promise<DidState | undefined> {
let appliedDidState = didState;
// NOTE: MUST NOT throw error, else a bad operation can be used to denial resolution for a DID.
try {
const operationProcessor = this.versionManager.getOperationProcessor(
operation.transactionTime
);
appliedDidState = await operationProcessor.apply(
operation,
appliedDidState
);
} catch (error) {
Logger.info(
`Skipped bad operation for DID ${operation.didUniqueSuffix} at time ${
operation.transactionTime
}. Error: ${SidetreeError.stringify(error)}`
);
}
return appliedDidState;
}
/**
* @returns The new DID State if a valid operation is applied, `undefined` otherwise.
*/
private async applyFirstValidOperation(
operations: AnchoredOperationModel[],
originalDidState: DidState
): Promise<DidState | undefined> {
let newDidState = originalDidState;
// Stop as soon as an operation is applied successfully.
for (const operation of operations) {
newDidState = (await this.applyOperation(operation, newDidState))!;
// If operation matching the recovery commitment is applied.
if (
newDidState.lastOperationTransactionNumber !==
originalDidState.lastOperationTransactionNumber
) {
return newDidState;
}
}
// TODO: Issue 981 this can probably return old did state. https://github.com/decentralized-identity/sidetree/issues/981
// Else we reach the end of operations without being able to apply any of them.
return undefined;
}
/**
* Constructs a single commit value -> operation lookup map by hashing each operation's reveal value as key, then adding the result to a map.
*/
private async constructCommitValueToOperationLookupMap(
nonCreateOperations: AnchoredOperationModel[]
): Promise<Map<string, AnchoredOperationModel[]>> {
const commitValueToOperationMap = new Map<
string,
AnchoredOperationModel[]
>();
// Loop through each operation and add an entry to the commit value -> operations map.
for (const operation of nonCreateOperations) {
const operationProcessor = this.versionManager.getOperationProcessor(
operation.transactionTime
);
const multihashRevealValueBuffer = await operationProcessor.getMultihashRevealValue(
operation
);
const multihashRevealValue = Multihash.decode(multihashRevealValueBuffer);
const commitValue = Multihash.hashThenEncode(
multihashRevealValue.hash,
multihashRevealValue.algorithm
);
if (commitValueToOperationMap.has(commitValue)) {
commitValueToOperationMap.get(commitValue)!.push(operation);
} else {
commitValueToOperationMap.set(commitValue, [operation]);
}
}
return commitValueToOperationMap;
}
}