@originals/sdk 1.8.0 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/dist/utils/hash.js +1 -0
  2. package/package.json +6 -5
  3. package/src/adapters/FeeOracleMock.ts +9 -0
  4. package/src/adapters/index.ts +5 -0
  5. package/src/adapters/providers/OrdHttpProvider.ts +126 -0
  6. package/src/adapters/providers/OrdMockProvider.ts +101 -0
  7. package/src/adapters/types.ts +66 -0
  8. package/src/bitcoin/BitcoinManager.ts +329 -0
  9. package/src/bitcoin/BroadcastClient.ts +54 -0
  10. package/src/bitcoin/OrdinalsClient.ts +120 -0
  11. package/src/bitcoin/PSBTBuilder.ts +106 -0
  12. package/src/bitcoin/fee-calculation.ts +38 -0
  13. package/src/bitcoin/providers/OrdNodeProvider.ts +92 -0
  14. package/src/bitcoin/providers/OrdinalsProvider.ts +56 -0
  15. package/src/bitcoin/providers/types.ts +59 -0
  16. package/src/bitcoin/transactions/commit.ts +465 -0
  17. package/src/bitcoin/transactions/index.ts +13 -0
  18. package/src/bitcoin/transfer.ts +43 -0
  19. package/src/bitcoin/utxo-selection.ts +322 -0
  20. package/src/bitcoin/utxo.ts +113 -0
  21. package/src/cel/ExternalReferenceManager.ts +87 -0
  22. package/src/cel/OriginalsCel.ts +460 -0
  23. package/src/cel/algorithms/createEventLog.ts +68 -0
  24. package/src/cel/algorithms/deactivateEventLog.ts +109 -0
  25. package/src/cel/algorithms/index.ts +11 -0
  26. package/src/cel/algorithms/updateEventLog.ts +99 -0
  27. package/src/cel/algorithms/verifyEventLog.ts +306 -0
  28. package/src/cel/algorithms/witnessEvent.ts +87 -0
  29. package/src/cel/cli/create.ts +330 -0
  30. package/src/cel/cli/index.ts +383 -0
  31. package/src/cel/cli/inspect.ts +549 -0
  32. package/src/cel/cli/migrate.ts +473 -0
  33. package/src/cel/cli/verify.ts +249 -0
  34. package/src/cel/hash.ts +71 -0
  35. package/src/cel/index.ts +16 -0
  36. package/src/cel/layers/BtcoCelManager.ts +408 -0
  37. package/src/cel/layers/PeerCelManager.ts +371 -0
  38. package/src/cel/layers/WebVHCelManager.ts +361 -0
  39. package/src/cel/layers/index.ts +27 -0
  40. package/src/cel/serialization/cbor.ts +189 -0
  41. package/src/cel/serialization/index.ts +10 -0
  42. package/src/cel/serialization/json.ts +209 -0
  43. package/src/cel/types.ts +160 -0
  44. package/src/cel/witnesses/BitcoinWitness.ts +184 -0
  45. package/src/cel/witnesses/HttpWitness.ts +241 -0
  46. package/src/cel/witnesses/WitnessService.ts +51 -0
  47. package/src/cel/witnesses/index.ts +11 -0
  48. package/src/contexts/credentials-v1.json +237 -0
  49. package/src/contexts/credentials-v2-examples.json +5 -0
  50. package/src/contexts/credentials-v2.json +340 -0
  51. package/src/contexts/credentials.json +237 -0
  52. package/src/contexts/data-integrity-v2.json +81 -0
  53. package/src/contexts/dids.json +58 -0
  54. package/src/contexts/ed255192020.json +93 -0
  55. package/src/contexts/ordinals-plus.json +23 -0
  56. package/src/contexts/originals.json +22 -0
  57. package/src/core/OriginalsSDK.ts +420 -0
  58. package/src/crypto/Multikey.ts +194 -0
  59. package/src/crypto/Signer.ts +262 -0
  60. package/src/crypto/noble-init.ts +138 -0
  61. package/src/did/BtcoDidResolver.ts +231 -0
  62. package/src/did/DIDManager.ts +705 -0
  63. package/src/did/Ed25519Verifier.ts +68 -0
  64. package/src/did/KeyManager.ts +239 -0
  65. package/src/did/WebVHManager.ts +499 -0
  66. package/src/did/createBtcoDidDocument.ts +60 -0
  67. package/src/did/providers/OrdinalsClientProviderAdapter.ts +68 -0
  68. package/src/events/EventEmitter.ts +222 -0
  69. package/src/events/index.ts +19 -0
  70. package/src/events/types.ts +331 -0
  71. package/src/examples/basic-usage.ts +78 -0
  72. package/src/examples/create-module-original.ts +435 -0
  73. package/src/examples/full-lifecycle-flow.ts +514 -0
  74. package/src/examples/run.ts +60 -0
  75. package/src/index.ts +204 -0
  76. package/src/kinds/KindRegistry.ts +320 -0
  77. package/src/kinds/index.ts +74 -0
  78. package/src/kinds/types.ts +470 -0
  79. package/src/kinds/validators/AgentValidator.ts +257 -0
  80. package/src/kinds/validators/AppValidator.ts +211 -0
  81. package/src/kinds/validators/DatasetValidator.ts +242 -0
  82. package/src/kinds/validators/DocumentValidator.ts +311 -0
  83. package/src/kinds/validators/MediaValidator.ts +269 -0
  84. package/src/kinds/validators/ModuleValidator.ts +225 -0
  85. package/src/kinds/validators/base.ts +276 -0
  86. package/src/kinds/validators/index.ts +12 -0
  87. package/src/lifecycle/BatchOperations.ts +381 -0
  88. package/src/lifecycle/LifecycleManager.ts +2156 -0
  89. package/src/lifecycle/OriginalsAsset.ts +524 -0
  90. package/src/lifecycle/ProvenanceQuery.ts +280 -0
  91. package/src/lifecycle/ResourceVersioning.ts +163 -0
  92. package/src/migration/MigrationManager.ts +587 -0
  93. package/src/migration/audit/AuditLogger.ts +176 -0
  94. package/src/migration/checkpoint/CheckpointManager.ts +112 -0
  95. package/src/migration/checkpoint/CheckpointStorage.ts +101 -0
  96. package/src/migration/index.ts +33 -0
  97. package/src/migration/operations/BaseMigration.ts +126 -0
  98. package/src/migration/operations/PeerToBtcoMigration.ts +105 -0
  99. package/src/migration/operations/PeerToWebvhMigration.ts +62 -0
  100. package/src/migration/operations/WebvhToBtcoMigration.ts +105 -0
  101. package/src/migration/rollback/RollbackManager.ts +170 -0
  102. package/src/migration/state/StateMachine.ts +92 -0
  103. package/src/migration/state/StateTracker.ts +156 -0
  104. package/src/migration/types.ts +356 -0
  105. package/src/migration/validation/BitcoinValidator.ts +107 -0
  106. package/src/migration/validation/CredentialValidator.ts +62 -0
  107. package/src/migration/validation/DIDCompatibilityValidator.ts +151 -0
  108. package/src/migration/validation/LifecycleValidator.ts +64 -0
  109. package/src/migration/validation/StorageValidator.ts +79 -0
  110. package/src/migration/validation/ValidationPipeline.ts +213 -0
  111. package/src/resources/ResourceManager.ts +655 -0
  112. package/src/resources/index.ts +21 -0
  113. package/src/resources/types.ts +202 -0
  114. package/src/storage/LocalStorageAdapter.ts +64 -0
  115. package/src/storage/MemoryStorageAdapter.ts +29 -0
  116. package/src/storage/StorageAdapter.ts +25 -0
  117. package/src/storage/index.ts +3 -0
  118. package/src/types/bitcoin.ts +98 -0
  119. package/src/types/common.ts +92 -0
  120. package/src/types/credentials.ts +89 -0
  121. package/src/types/did.ts +31 -0
  122. package/src/types/external-shims.d.ts +53 -0
  123. package/src/types/index.ts +7 -0
  124. package/src/types/network.ts +178 -0
  125. package/src/utils/EventLogger.ts +298 -0
  126. package/src/utils/Logger.ts +324 -0
  127. package/src/utils/MetricsCollector.ts +358 -0
  128. package/src/utils/bitcoin-address.ts +132 -0
  129. package/src/utils/cbor.ts +31 -0
  130. package/src/utils/encoding.ts +135 -0
  131. package/src/utils/hash.ts +12 -0
  132. package/src/utils/retry.ts +46 -0
  133. package/src/utils/satoshi-validation.ts +196 -0
  134. package/src/utils/serialization.ts +102 -0
  135. package/src/utils/telemetry.ts +44 -0
  136. package/src/utils/validation.ts +123 -0
  137. package/src/vc/CredentialManager.ts +955 -0
  138. package/src/vc/Issuer.ts +105 -0
  139. package/src/vc/Verifier.ts +54 -0
  140. package/src/vc/cryptosuites/bbs.ts +253 -0
  141. package/src/vc/cryptosuites/bbsSimple.ts +21 -0
  142. package/src/vc/cryptosuites/eddsa.ts +99 -0
  143. package/src/vc/documentLoader.ts +81 -0
  144. package/src/vc/proofs/data-integrity.ts +33 -0
  145. package/src/vc/utils/jsonld.ts +18 -0
@@ -0,0 +1,356 @@
1
+ /**
2
+ * Migration system types and interfaces
3
+ * Defines all types used across the migration infrastructure
4
+ */
5
+
6
+ import { DIDDocument, VerifiableCredential } from '../types';
7
+
8
+ /**
9
+ * DID layer types
10
+ */
11
+ export type DIDLayer = 'peer' | 'webvh' | 'btco';
12
+
13
+ /**
14
+ * Migration state enum
15
+ */
16
+ export enum MigrationStateEnum {
17
+ PENDING = 'pending', // Migration queued
18
+ VALIDATING = 'validating', // Running validation pipeline
19
+ CHECKPOINTED = 'checkpointed', // Checkpoint created
20
+ IN_PROGRESS = 'in_progress', // Active migration
21
+ ANCHORING = 'anchoring', // Bitcoin anchoring (btco only)
22
+ COMPLETED = 'completed', // Successfully completed
23
+ FAILED = 'failed', // Failed, rollback initiated
24
+ ROLLED_BACK = 'rolled_back', // Rolled back successfully
25
+ QUARANTINED = 'quarantined' // Rollback failed, needs manual intervention
26
+ }
27
+
28
+ /**
29
+ * Migration error types
30
+ */
31
+ export enum MigrationErrorType {
32
+ VALIDATION_ERROR = 'validation_error', // Pre-migration validation failed
33
+ STORAGE_ERROR = 'storage_error', // Storage adapter failure
34
+ BITCOIN_ERROR = 'bitcoin_error', // Bitcoin anchoring failed
35
+ CREDENTIAL_ERROR = 'credential_error', // Credential re-issuance failed
36
+ NETWORK_ERROR = 'network_error', // Network/connectivity failure
37
+ ROLLBACK_ERROR = 'rollback_error', // Rollback failed (critical)
38
+ TIMEOUT_ERROR = 'timeout_error', // Operation timeout
39
+ UNKNOWN_ERROR = 'unknown_error' // Unexpected error
40
+ }
41
+
42
+ /**
43
+ * Migration options for initiating a migration
44
+ */
45
+ export interface MigrationOptions {
46
+ sourceDid: string; // Source DID to migrate from
47
+ targetLayer: DIDLayer; // Target layer
48
+ credentialIssuance?: boolean; // Require VC issuance (default: true)
49
+ batchMode?: boolean; // Batch operation flag
50
+ partialMode?: { // For large files
51
+ chunkSize: number; // Bytes per chunk
52
+ resumable: boolean; // Support resume
53
+ };
54
+ estimateCostOnly?: boolean; // Return cost estimate without migrating
55
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
+ metadata?: Record<string, any>; // Additional migration metadata
57
+ domain?: string; // For webvh migrations
58
+ satoshi?: string; // For btco migrations
59
+ feeRate?: number; // For btco migrations
60
+ }
61
+
62
+ /**
63
+ * Batch migration options
64
+ */
65
+ export interface BatchMigrationOptions extends MigrationOptions {
66
+ maxConcurrent?: number; // Max concurrent migrations
67
+ continueOnError?: boolean; // Continue batch if individual migration fails
68
+ }
69
+
70
+ /**
71
+ * Cost estimate for a migration
72
+ */
73
+ export interface CostEstimate {
74
+ storageCost: number; // Storage cost in currency units
75
+ networkFees: number; // Bitcoin network fees (btco only)
76
+ totalCost: number; // Total cost
77
+ currency: string; // Currency unit (e.g., 'sats', 'USD')
78
+ }
79
+
80
+ /**
81
+ * Validation error
82
+ */
83
+ export interface ValidationError {
84
+ code: string;
85
+ message: string;
86
+ field?: string;
87
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
88
+ details?: any;
89
+ }
90
+
91
+ /**
92
+ * Validation warning
93
+ */
94
+ export interface ValidationWarning {
95
+ code: string;
96
+ message: string;
97
+ field?: string;
98
+ }
99
+
100
+ /**
101
+ * Migration validation result
102
+ */
103
+ export interface MigrationValidationResult {
104
+ valid: boolean;
105
+ errors: ValidationError[]; // Blocking errors
106
+ warnings: ValidationWarning[]; // Non-blocking issues
107
+ estimatedCost: CostEstimate;
108
+ estimatedDuration: number; // milliseconds
109
+ }
110
+
111
+ /**
112
+ * Migration checkpoint data
113
+ */
114
+ export interface MigrationCheckpoint {
115
+ checkpointId?: string;
116
+ migrationId: string;
117
+ timestamp: number;
118
+ sourceDid: string;
119
+ sourceLayer: DIDLayer;
120
+ didDocument: DIDDocument;
121
+ credentials: VerifiableCredential[];
122
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
123
+ storageReferences: Record<string, any>;
124
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
125
+ lifecycleState: any;
126
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
127
+ ownershipProofs: any[];
128
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
129
+ metadata: Record<string, any>;
130
+ }
131
+
132
+ /**
133
+ * Rollback result
134
+ */
135
+ export interface RollbackResult {
136
+ success: boolean;
137
+ migrationId: string;
138
+ checkpointId?: string;
139
+ restoredState: MigrationStateEnum;
140
+ duration: number; // milliseconds
141
+ errors?: MigrationError[];
142
+ }
143
+
144
+ /**
145
+ * Migration state tracking
146
+ */
147
+ export interface MigrationState {
148
+ migrationId: string;
149
+ state: MigrationStateEnum;
150
+ sourceDid: string;
151
+ sourceLayer: DIDLayer;
152
+ targetDid?: string;
153
+ targetLayer: DIDLayer;
154
+ progress: number; // 0-100
155
+ currentOperation: string;
156
+ startTime: number;
157
+ endTime?: number;
158
+ error?: MigrationError;
159
+ checkpointId?: string;
160
+ }
161
+
162
+ /**
163
+ * Migration error details
164
+ */
165
+ export interface MigrationError {
166
+ type: MigrationErrorType;
167
+ code: string;
168
+ message: string;
169
+ technicalDetails?: string;
170
+ suggestedRecovery?: string;
171
+ migrationId?: string;
172
+ sourceDid?: string;
173
+ targetDid?: string;
174
+ timestamp: number;
175
+ stack?: string;
176
+ }
177
+
178
+ /**
179
+ * Migration audit record
180
+ */
181
+ export interface MigrationAuditRecord {
182
+ migrationId: string;
183
+ timestamp: number;
184
+ initiator: string; // User/system identifier
185
+ sourceDid: string;
186
+ sourceLayer: DIDLayer;
187
+ targetDid: string | null; // null if failed before creation
188
+ targetLayer: DIDLayer;
189
+ finalState: MigrationStateEnum;
190
+ validationResults: MigrationValidationResult;
191
+ costActual: CostEstimate; // Actual costs incurred
192
+ duration: number; // milliseconds
193
+ checkpointId?: string; // For rollback reference
194
+ errors: MigrationError[]; // Any errors encountered
195
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
196
+ metadata: Record<string, any>; // Custom metadata
197
+ signature?: string; // Cryptographic signature
198
+ }
199
+
200
+ /**
201
+ * Migration result
202
+ */
203
+ export interface MigrationResult {
204
+ migrationId: string;
205
+ success: boolean;
206
+ sourceDid: string;
207
+ targetDid?: string;
208
+ sourceLayer: DIDLayer;
209
+ targetLayer: DIDLayer;
210
+ state: MigrationStateEnum;
211
+ duration: number;
212
+ cost: CostEstimate;
213
+ auditRecord?: MigrationAuditRecord; // Optional - undefined when AuditLogger disabled (v1.0)
214
+ error?: MigrationError;
215
+ }
216
+
217
+ /**
218
+ * Batch migration result
219
+ */
220
+ export interface BatchMigrationResult {
221
+ batchId: string;
222
+ total: number;
223
+ completed: number;
224
+ failed: number;
225
+ inProgress: number;
226
+ results: Map<string, MigrationResult>; // sourceDid → result
227
+ overallProgress: number; // 0-100
228
+ startTime: number;
229
+ endTime?: number;
230
+ errors: MigrationError[];
231
+ }
232
+
233
+ /**
234
+ * Partial migration progress
235
+ */
236
+ export interface PartialMigrationProgress {
237
+ totalChunks: number;
238
+ completedChunks: number;
239
+ currentChunk: number;
240
+ bytesTransferred: number;
241
+ totalBytes: number;
242
+ percentComplete: number;
243
+ estimatedTimeRemaining: number; // milliseconds
244
+ }
245
+
246
+ /**
247
+ * Migration event types
248
+ */
249
+ export type MigrationEventType =
250
+ | 'migration:started'
251
+ | 'migration:validated'
252
+ | 'migration:checkpointed'
253
+ | 'migration:in_progress'
254
+ | 'migration:anchoring'
255
+ | 'migration:completed'
256
+ | 'migration:failed'
257
+ | 'migration:rolledback'
258
+ | 'migration:quarantine'
259
+ | 'batch:progress';
260
+
261
+ /**
262
+ * Migration event payload
263
+ */
264
+ export interface MigrationEvent {
265
+ type: MigrationEventType;
266
+ migrationId: string;
267
+ timestamp: number;
268
+ state: MigrationStateEnum;
269
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
270
+ data?: any;
271
+ }
272
+
273
+ /**
274
+ * Storage migration context
275
+ */
276
+ export interface StorageMigrationContext {
277
+ sourceDid: string;
278
+ targetDid: string;
279
+ sourceLayer: DIDLayer;
280
+ targetLayer: DIDLayer;
281
+ resources: Array<{
282
+ id: string;
283
+ hash: string;
284
+ contentType: string;
285
+ size: number;
286
+ url?: string;
287
+ }>;
288
+ }
289
+
290
+ /**
291
+ * Bitcoin anchoring context
292
+ */
293
+ export interface BitcoinAnchoringContext {
294
+ didDocument: DIDDocument;
295
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
296
+ migrationMetadata: Record<string, any>;
297
+ network: 'mainnet' | 'testnet' | 'signet';
298
+ feeRate?: number;
299
+ satoshi?: string;
300
+ }
301
+
302
+ /**
303
+ * Lifecycle migration context
304
+ */
305
+ export interface LifecycleMigrationContext {
306
+ sourceDid: string;
307
+ targetDid: string;
308
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
309
+ currentState: any;
310
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
311
+ eventHistory: any[];
312
+ migrationId: string;
313
+ }
314
+
315
+ /**
316
+ * Validator interface
317
+ */
318
+ export interface IValidator {
319
+ validate(options: MigrationOptions): Promise<MigrationValidationResult>;
320
+ }
321
+
322
+ /**
323
+ * Checkpoint manager interface
324
+ */
325
+ export interface ICheckpointManager {
326
+ createCheckpoint(migrationId: string, options: MigrationOptions): Promise<MigrationCheckpoint>;
327
+ getCheckpoint(checkpointId: string): Promise<MigrationCheckpoint | null>;
328
+ deleteCheckpoint(checkpointId: string): Promise<void>;
329
+ }
330
+
331
+ /**
332
+ * Rollback manager interface
333
+ */
334
+ export interface IRollbackManager {
335
+ rollback(migrationId: string, checkpointId: string): Promise<RollbackResult>;
336
+ }
337
+
338
+ /**
339
+ * State tracker interface
340
+ */
341
+ export interface IStateTracker {
342
+ createMigration(options: MigrationOptions): Promise<MigrationState>;
343
+ updateState(migrationId: string, updates: Partial<MigrationState>): Promise<void>;
344
+ getState(migrationId: string): Promise<MigrationState | null>;
345
+ queryStates(filters: Partial<MigrationState>): Promise<MigrationState[]>;
346
+ }
347
+
348
+ /**
349
+ * Audit logger interface
350
+ */
351
+ export interface IAuditLogger {
352
+ logMigration(record: MigrationAuditRecord): Promise<void>;
353
+ getMigrationHistory(did: string): Promise<MigrationAuditRecord[]>;
354
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
355
+ getSystemMigrationLogs(filters: any): Promise<MigrationAuditRecord[]>;
356
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * BitcoinValidator - Validates Bitcoin network requirements for btco migrations
3
+ */
4
+
5
+ import {
6
+ MigrationOptions,
7
+ MigrationValidationResult,
8
+ ValidationError,
9
+ ValidationWarning,
10
+ IValidator
11
+ } from '../types';
12
+ import { OriginalsConfig } from '../../types';
13
+ import { BitcoinManager } from '../../bitcoin/BitcoinManager';
14
+
15
+ export class BitcoinValidator implements IValidator {
16
+ constructor(
17
+ private config: OriginalsConfig,
18
+ private bitcoinManager: BitcoinManager
19
+ ) {}
20
+
21
+ async validate(options: MigrationOptions): Promise<MigrationValidationResult> {
22
+ const errors: ValidationError[] = [];
23
+ const warnings: ValidationWarning[] = [];
24
+
25
+ try {
26
+ // Only validate for btco migrations
27
+ if (options.targetLayer !== 'btco') {
28
+ return this.createResult(true, errors, warnings, 0, 0);
29
+ }
30
+
31
+ // Check if Bitcoin provider is configured
32
+ const ordinalsProvider = this.config.ordinalsProvider;
33
+ if (!ordinalsProvider) {
34
+ errors.push({
35
+ code: 'BITCOIN_PROVIDER_REQUIRED',
36
+ message: 'Ordinals provider is required for btco migrations',
37
+ details: { targetLayer: options.targetLayer }
38
+ });
39
+ return this.createResult(false, errors, warnings, 0, 0);
40
+ }
41
+
42
+ // Estimate Bitcoin network fees
43
+ let networkFees = 0;
44
+ let estimatedDuration = 600000; // 10 minutes default
45
+
46
+ try {
47
+ // Estimate fee for a typical inscription (assume 1KB data)
48
+ const estimatedSize = 1024; // bytes
49
+ const feeRate = options.feeRate || 10; // sats/vB
50
+ networkFees = estimatedSize * feeRate;
51
+
52
+ // Check if fee is within reasonable limits
53
+ if (feeRate > 1000) {
54
+ warnings.push({
55
+ code: 'HIGH_FEE_RATE',
56
+ message: `Fee rate of ${feeRate} sat/vB is unusually high`,
57
+ field: 'feeRate'
58
+ });
59
+ }
60
+ } catch (error) {
61
+ warnings.push({
62
+ code: 'FEE_ESTIMATION_FAILED',
63
+ message: `Could not estimate Bitcoin network fees: ${error instanceof Error ? error.message : String(error)}`
64
+ });
65
+ networkFees = 10240; // Default fallback: ~1KB at 10 sat/vB
66
+ }
67
+
68
+ // Validate network (should be signet for testnet)
69
+ if (this.config.network !== 'mainnet' && this.config.network !== 'signet') {
70
+ warnings.push({
71
+ code: 'NETWORK_MISMATCH',
72
+ message: `Network '${this.config.network}' will use signet for Bitcoin anchoring`
73
+ });
74
+ }
75
+
76
+ return this.createResult(true, errors, warnings, networkFees, estimatedDuration);
77
+ } catch (error) {
78
+ errors.push({
79
+ code: 'BITCOIN_VALIDATION_ERROR',
80
+ message: 'Error validating Bitcoin requirements',
81
+ details: { error: error instanceof Error ? error.message : String(error) }
82
+ });
83
+ return this.createResult(false, errors, warnings, 0, 0);
84
+ }
85
+ }
86
+
87
+ private createResult(
88
+ valid: boolean,
89
+ errors: ValidationError[],
90
+ warnings: ValidationWarning[],
91
+ networkFees: number,
92
+ duration: number
93
+ ): MigrationValidationResult {
94
+ return {
95
+ valid,
96
+ errors,
97
+ warnings,
98
+ estimatedCost: {
99
+ storageCost: 0,
100
+ networkFees,
101
+ totalCost: networkFees,
102
+ currency: 'sats'
103
+ },
104
+ estimatedDuration: duration
105
+ };
106
+ }
107
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * CredentialValidator - Validates credential compatibility for migration
3
+ */
4
+
5
+ import {
6
+ MigrationOptions,
7
+ MigrationValidationResult,
8
+ ValidationError,
9
+ ValidationWarning,
10
+ IValidator
11
+ } from '../types';
12
+ import { OriginalsConfig } from '../../types';
13
+ import { CredentialManager } from '../../vc/CredentialManager';
14
+
15
+ export class CredentialValidator implements IValidator {
16
+ constructor(
17
+ private config: OriginalsConfig,
18
+ private credentialManager: CredentialManager
19
+ ) {}
20
+
21
+ async validate(options: MigrationOptions): Promise<MigrationValidationResult> {
22
+ const errors: ValidationError[] = [];
23
+ const warnings: ValidationWarning[] = [];
24
+
25
+ try {
26
+ // Credential validation is optional if credentialIssuance is false
27
+ if (options.credentialIssuance === false) {
28
+ return this.createResult(true, errors, warnings);
29
+ }
30
+
31
+ // All credential types are compatible with all layers
32
+ // This validator primarily checks that credential issuance is possible
33
+
34
+ // For now, credentials are always compatible
35
+ // Future enhancements could include schema validation
36
+
37
+ return this.createResult(true, errors, warnings);
38
+ } catch (error) {
39
+ errors.push({
40
+ code: 'CREDENTIAL_VALIDATION_ERROR',
41
+ message: 'Error validating credential compatibility',
42
+ details: { error: error instanceof Error ? error.message : String(error) }
43
+ });
44
+ return this.createResult(false, errors, warnings);
45
+ }
46
+ }
47
+
48
+ private createResult(valid: boolean, errors: ValidationError[], warnings: ValidationWarning[]): MigrationValidationResult {
49
+ return {
50
+ valid,
51
+ errors,
52
+ warnings,
53
+ estimatedCost: {
54
+ storageCost: 0,
55
+ networkFees: 0,
56
+ totalCost: 0,
57
+ currency: 'sats'
58
+ },
59
+ estimatedDuration: 50 // Credential validation typically takes ~50ms
60
+ };
61
+ }
62
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * DIDCompatibilityValidator - Validates DID document compatibility between layers
3
+ */
4
+
5
+ import {
6
+ MigrationOptions,
7
+ MigrationValidationResult,
8
+ ValidationError,
9
+ ValidationWarning,
10
+ IValidator
11
+ } from '../types';
12
+ import { OriginalsConfig } from '../../types';
13
+ import { DIDManager } from '../../did/DIDManager';
14
+
15
+ export class DIDCompatibilityValidator implements IValidator {
16
+ constructor(
17
+ private config: OriginalsConfig,
18
+ private didManager: DIDManager
19
+ ) {}
20
+
21
+ async validate(options: MigrationOptions): Promise<MigrationValidationResult> {
22
+ const errors: ValidationError[] = [];
23
+ const warnings: ValidationWarning[] = [];
24
+
25
+ try {
26
+ // Resolve source DID
27
+ const sourceDid = await this.didManager.resolveDID(options.sourceDid);
28
+ if (!sourceDid) {
29
+ errors.push({
30
+ code: 'SOURCE_DID_NOT_FOUND',
31
+ message: `Could not resolve source DID: ${options.sourceDid}`,
32
+ field: 'sourceDid'
33
+ });
34
+ return this.createResult(false, errors, warnings);
35
+ }
36
+
37
+ // Extract source layer from DID
38
+ const sourceLayer = this.extractLayer(options.sourceDid);
39
+ if (!sourceLayer) {
40
+ errors.push({
41
+ code: 'INVALID_SOURCE_DID_FORMAT',
42
+ message: 'Source DID has unsupported format',
43
+ field: 'sourceDid',
44
+ details: { did: options.sourceDid }
45
+ });
46
+ return this.createResult(false, errors, warnings);
47
+ }
48
+
49
+ // Validate migration path
50
+ const pathErrors = this.validateMigrationPath(sourceLayer, options.targetLayer);
51
+ errors.push(...pathErrors);
52
+
53
+ if (errors.length > 0) {
54
+ return this.createResult(false, errors, warnings);
55
+ }
56
+
57
+ // Validate verification methods compatibility
58
+ if (sourceDid.verificationMethod && Array.isArray(sourceDid.verificationMethod)) {
59
+ for (const vm of sourceDid.verificationMethod) {
60
+ if (!this.isVerificationMethodCompatible(vm, options.targetLayer)) {
61
+ warnings.push({
62
+ code: 'VERIFICATION_METHOD_INCOMPATIBLE',
63
+ message: `Verification method ${vm.id} may not be compatible with ${options.targetLayer}`,
64
+ field: 'verificationMethod'
65
+ });
66
+ }
67
+ }
68
+ }
69
+
70
+ // Validate service endpoints
71
+ if (sourceDid.service && Array.isArray(sourceDid.service)) {
72
+ if (options.targetLayer === 'peer' && sourceDid.service.length > 0) {
73
+ warnings.push({
74
+ code: 'SERVICE_ENDPOINTS_ON_PEER',
75
+ message: 'Service endpoints on peer DIDs may have limited discoverability'
76
+ });
77
+ }
78
+ }
79
+
80
+ return this.createResult(true, errors, warnings);
81
+ } catch (error) {
82
+ errors.push({
83
+ code: 'DID_VALIDATION_ERROR',
84
+ message: 'Error validating DID compatibility',
85
+ details: { error: error instanceof Error ? error.message : String(error) }
86
+ });
87
+ return this.createResult(false, errors, warnings);
88
+ }
89
+ }
90
+
91
+ private extractLayer(did: string): string | null {
92
+ if (did.startsWith('did:peer:')) return 'peer';
93
+ if (did.startsWith('did:webvh:')) return 'webvh';
94
+ if (did.startsWith('did:btco:')) return 'btco';
95
+ return null;
96
+ }
97
+
98
+ private validateMigrationPath(sourceLayer: string, targetLayer: string): ValidationError[] {
99
+ const errors: ValidationError[] = [];
100
+
101
+ // Check for invalid reverse migrations
102
+ const layerOrder = { peer: 0, webvh: 1, btco: 2 };
103
+ const sourceOrder = layerOrder[sourceLayer as keyof typeof layerOrder];
104
+ const targetOrder = layerOrder[targetLayer as keyof typeof layerOrder];
105
+
106
+ if (sourceOrder === undefined || targetOrder === undefined) {
107
+ errors.push({
108
+ code: 'INVALID_LAYER',
109
+ message: 'Invalid source or target layer',
110
+ details: { sourceLayer, targetLayer }
111
+ });
112
+ return errors;
113
+ }
114
+
115
+ if (sourceOrder >= targetOrder) {
116
+ errors.push({
117
+ code: 'INVALID_MIGRATION_PATH',
118
+ message: `Cannot migrate from ${sourceLayer} to ${targetLayer}. Migrations must move forward through layers (peer → webvh → btco)`,
119
+ details: { sourceLayer, targetLayer }
120
+ });
121
+ }
122
+
123
+ return errors;
124
+ }
125
+
126
+ private isVerificationMethodCompatible(vm: any, targetLayer: string): boolean {
127
+ // All verification method types are compatible with all layers
128
+ // This is a placeholder for more sophisticated compatibility checks
129
+ if (!vm.type) return false;
130
+
131
+ // Common types that are widely supported
132
+ const supportedTypes = ['Multikey', 'Ed25519VerificationKey2020', 'EcdsaSecp256k1VerificationKey2019'];
133
+
134
+ return supportedTypes.includes(vm.type);
135
+ }
136
+
137
+ private createResult(valid: boolean, errors: ValidationError[], warnings: ValidationWarning[]): MigrationValidationResult {
138
+ return {
139
+ valid,
140
+ errors,
141
+ warnings,
142
+ estimatedCost: {
143
+ storageCost: 0,
144
+ networkFees: 0,
145
+ totalCost: 0,
146
+ currency: 'sats'
147
+ },
148
+ estimatedDuration: 100 // DID validation typically takes ~100ms
149
+ };
150
+ }
151
+ }