@longarc/mdash 3.0.0
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.
- package/README.md +278 -0
- package/dist/checkpoint/engine.d.ts +208 -0
- package/dist/checkpoint/engine.d.ts.map +1 -0
- package/dist/checkpoint/engine.js +369 -0
- package/dist/checkpoint/engine.js.map +1 -0
- package/dist/context/engine.d.ts +197 -0
- package/dist/context/engine.d.ts.map +1 -0
- package/dist/context/engine.js +392 -0
- package/dist/context/engine.js.map +1 -0
- package/dist/core/commitment.d.ts +154 -0
- package/dist/core/commitment.d.ts.map +1 -0
- package/dist/core/commitment.js +305 -0
- package/dist/core/commitment.js.map +1 -0
- package/dist/core/crypto.d.ts +100 -0
- package/dist/core/crypto.d.ts.map +1 -0
- package/dist/core/crypto.js +243 -0
- package/dist/core/crypto.js.map +1 -0
- package/dist/index.d.ts +121 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +234 -0
- package/dist/index.js.map +1 -0
- package/dist/mcca/engine.d.ts +260 -0
- package/dist/mcca/engine.d.ts.map +1 -0
- package/dist/mcca/engine.js +518 -0
- package/dist/mcca/engine.js.map +1 -0
- package/dist/physics/engine.d.ts +165 -0
- package/dist/physics/engine.d.ts.map +1 -0
- package/dist/physics/engine.js +371 -0
- package/dist/physics/engine.js.map +1 -0
- package/dist/tee/engine.d.ts +285 -0
- package/dist/tee/engine.d.ts.map +1 -0
- package/dist/tee/engine.js +505 -0
- package/dist/tee/engine.js.map +1 -0
- package/dist/warrant/engine.d.ts +195 -0
- package/dist/warrant/engine.d.ts.map +1 -0
- package/dist/warrant/engine.js +409 -0
- package/dist/warrant/engine.js.map +1 -0
- package/dist/zk/engine.d.ts +243 -0
- package/dist/zk/engine.d.ts.map +1 -0
- package/dist/zk/engine.js +489 -0
- package/dist/zk/engine.js.map +1 -0
- package/package.json +25 -0
- package/src/__tests__/phase1.test.ts +1120 -0
- package/src/__tests__/phase2-4.test.ts +898 -0
- package/src/checkpoint/engine.ts +532 -0
- package/src/context/engine.ts +598 -0
- package/src/core/commitment.ts +438 -0
- package/src/core/crypto.ts +304 -0
- package/src/index.ts +320 -0
- package/src/mcca/engine.ts +778 -0
- package/src/physics/engine.ts +563 -0
- package/src/tee/engine.ts +810 -0
- package/src/warrant/engine.ts +625 -0
- package/src/zk/engine.ts +730 -0
- package/tsconfig.json +21 -0
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mdash v3.0 - Cryptographic Core
|
|
3
|
+
*
|
|
4
|
+
* "LLM at the edges, cryptography at the core."
|
|
5
|
+
*
|
|
6
|
+
* All cryptographic operations use Web Crypto API for:
|
|
7
|
+
* - Hardware acceleration where available
|
|
8
|
+
* - Constant-time operations (timing attack resistance)
|
|
9
|
+
* - Non-extractable key material
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
// ============================================================================
|
|
13
|
+
// BRANDED TYPES - Type safety without runtime overhead
|
|
14
|
+
// ============================================================================
|
|
15
|
+
|
|
16
|
+
export type Hash = string & { readonly __brand: 'Hash' };
|
|
17
|
+
export type Seal = string & { readonly __brand: 'Seal' };
|
|
18
|
+
export type Timestamp = string & { readonly __brand: 'Timestamp' };
|
|
19
|
+
export type FragmentId = string & { readonly __brand: 'FragmentId' };
|
|
20
|
+
export type WarrantId = string & { readonly __brand: 'WarrantId' };
|
|
21
|
+
export type CheckpointId = string & { readonly __brand: 'CheckpointId' };
|
|
22
|
+
|
|
23
|
+
// ============================================================================
|
|
24
|
+
// TYPE GUARDS
|
|
25
|
+
// ============================================================================
|
|
26
|
+
|
|
27
|
+
const HASH_REGEX = /^[a-f0-9]{64}$/;
|
|
28
|
+
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
29
|
+
const ISO_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;
|
|
30
|
+
|
|
31
|
+
export function isHash(value: unknown): value is Hash {
|
|
32
|
+
return typeof value === 'string' && HASH_REGEX.test(value);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function isSeal(value: unknown): value is Seal {
|
|
36
|
+
return typeof value === 'string' && HASH_REGEX.test(value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function isTimestamp(value: unknown): value is Timestamp {
|
|
40
|
+
return typeof value === 'string' && ISO_REGEX.test(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function isFragmentId(value: unknown): value is FragmentId {
|
|
44
|
+
return typeof value === 'string' && UUID_REGEX.test(value);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function isWarrantId(value: unknown): value is WarrantId {
|
|
48
|
+
return typeof value === 'string' && value.startsWith('w-') && value.length === 10;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function isCheckpointId(value: unknown): value is CheckpointId {
|
|
52
|
+
return typeof value === 'string' && value.startsWith('cp-') && value.length === 11;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// ============================================================================
|
|
56
|
+
// CRYPTO CONTEXT - Web Crypto API access
|
|
57
|
+
// ============================================================================
|
|
58
|
+
|
|
59
|
+
function getSubtleCrypto(): SubtleCrypto {
|
|
60
|
+
if (typeof globalThis.crypto?.subtle !== 'undefined') {
|
|
61
|
+
return globalThis.crypto.subtle;
|
|
62
|
+
}
|
|
63
|
+
throw new Error('Web Crypto API not available');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function getRandomUUID(): string {
|
|
67
|
+
if (typeof globalThis.crypto?.randomUUID === 'function') {
|
|
68
|
+
return globalThis.crypto.randomUUID();
|
|
69
|
+
}
|
|
70
|
+
throw new Error('crypto.randomUUID not available');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ============================================================================
|
|
74
|
+
// HASHING - SHA-256
|
|
75
|
+
// ============================================================================
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* SHA-256 hash of a string
|
|
79
|
+
* Returns lowercase hex (64 characters)
|
|
80
|
+
*/
|
|
81
|
+
export async function sha256(input: string): Promise<Hash> {
|
|
82
|
+
const subtle = getSubtleCrypto();
|
|
83
|
+
const encoder = new TextEncoder();
|
|
84
|
+
const data = encoder.encode(input);
|
|
85
|
+
const hashBuffer = await subtle.digest('SHA-256', data);
|
|
86
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
87
|
+
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
|
|
88
|
+
return hashHex as Hash;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* SHA-256 hash of an object using deterministic serialization
|
|
93
|
+
* Keys are sorted at all nesting levels
|
|
94
|
+
*/
|
|
95
|
+
export async function sha256Object(obj: unknown): Promise<Hash> {
|
|
96
|
+
const serialized = deterministicStringify(obj);
|
|
97
|
+
return sha256(serialized);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* SHA-256 hash of binary data
|
|
102
|
+
*/
|
|
103
|
+
export async function sha256Binary(data: ArrayBuffer): Promise<Hash> {
|
|
104
|
+
const subtle = getSubtleCrypto();
|
|
105
|
+
const hashBuffer = await subtle.digest('SHA-256', data);
|
|
106
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
107
|
+
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
|
|
108
|
+
return hashHex as Hash;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Rolling hash of multiple hashes (for Merkle tree nodes)
|
|
113
|
+
* Order matters: H(a, b) ≠ H(b, a)
|
|
114
|
+
*/
|
|
115
|
+
export async function rollingHash(hashes: Hash[]): Promise<Hash> {
|
|
116
|
+
if (hashes.length === 0) {
|
|
117
|
+
return sha256('');
|
|
118
|
+
}
|
|
119
|
+
if (hashes.length === 1) {
|
|
120
|
+
const first = hashes[0];
|
|
121
|
+
if (!first) {
|
|
122
|
+
return sha256('');
|
|
123
|
+
}
|
|
124
|
+
return first;
|
|
125
|
+
}
|
|
126
|
+
const combined = hashes.join('|');
|
|
127
|
+
return sha256(combined);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ============================================================================
|
|
131
|
+
// DETERMINISTIC SERIALIZATION
|
|
132
|
+
// ============================================================================
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* JSON.stringify with sorted keys at all nesting levels
|
|
136
|
+
* Ensures {a:1, b:2} and {b:2, a:1} produce identical output
|
|
137
|
+
*/
|
|
138
|
+
export function deterministicStringify(obj: unknown): string {
|
|
139
|
+
return JSON.stringify(obj, (_, value) => {
|
|
140
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
141
|
+
return Object.keys(value)
|
|
142
|
+
.sort()
|
|
143
|
+
.reduce((sorted: Record<string, unknown>, key) => {
|
|
144
|
+
sorted[key] = value[key];
|
|
145
|
+
return sorted;
|
|
146
|
+
}, {});
|
|
147
|
+
}
|
|
148
|
+
return value;
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ============================================================================
|
|
153
|
+
// HMAC SEALING - HMAC-SHA256
|
|
154
|
+
// ============================================================================
|
|
155
|
+
|
|
156
|
+
const HKDF_SALT = 'caret-context-primitive-engine';
|
|
157
|
+
const HKDF_INFO = 'mdash-seal-v3';
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Derive an HMAC key from a master key using HKDF
|
|
161
|
+
* The derived key is non-extractable
|
|
162
|
+
*/
|
|
163
|
+
export async function deriveKey(masterKey: string): Promise<CryptoKey> {
|
|
164
|
+
const subtle = getSubtleCrypto();
|
|
165
|
+
const encoder = new TextEncoder();
|
|
166
|
+
|
|
167
|
+
// Import master key as raw key material
|
|
168
|
+
const keyMaterial = await subtle.importKey(
|
|
169
|
+
'raw',
|
|
170
|
+
encoder.encode(masterKey),
|
|
171
|
+
'HKDF',
|
|
172
|
+
false,
|
|
173
|
+
['deriveKey']
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
// Derive HMAC key using HKDF
|
|
177
|
+
return subtle.deriveKey(
|
|
178
|
+
{
|
|
179
|
+
name: 'HKDF',
|
|
180
|
+
salt: encoder.encode(HKDF_SALT),
|
|
181
|
+
info: encoder.encode(HKDF_INFO),
|
|
182
|
+
hash: 'SHA-256',
|
|
183
|
+
},
|
|
184
|
+
keyMaterial,
|
|
185
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
186
|
+
false, // non-extractable
|
|
187
|
+
['sign', 'verify']
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Create HMAC seal of content
|
|
193
|
+
*/
|
|
194
|
+
export async function hmacSeal(content: unknown, key: CryptoKey): Promise<Seal> {
|
|
195
|
+
const subtle = getSubtleCrypto();
|
|
196
|
+
const encoder = new TextEncoder();
|
|
197
|
+
const data = encoder.encode(deterministicStringify(content));
|
|
198
|
+
const signature = await subtle.sign('HMAC', key, data);
|
|
199
|
+
const sigArray = Array.from(new Uint8Array(signature));
|
|
200
|
+
const sigHex = sigArray.map(b => b.toString(16).padStart(2, '0')).join('');
|
|
201
|
+
return sigHex as Seal;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Verify HMAC seal
|
|
206
|
+
*/
|
|
207
|
+
export async function hmacVerify(content: unknown, seal: Seal, key: CryptoKey): Promise<boolean> {
|
|
208
|
+
const subtle = getSubtleCrypto();
|
|
209
|
+
const encoder = new TextEncoder();
|
|
210
|
+
const data = encoder.encode(deterministicStringify(content));
|
|
211
|
+
|
|
212
|
+
// Convert seal hex to ArrayBuffer
|
|
213
|
+
const sealBytes = new Uint8Array(seal.match(/.{2}/g)!.map(byte => parseInt(byte, 16)));
|
|
214
|
+
|
|
215
|
+
return subtle.verify('HMAC', key, sealBytes, data);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ============================================================================
|
|
219
|
+
// CONSTANT-TIME COMPARISON
|
|
220
|
+
// ============================================================================
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Compare two strings in constant time
|
|
224
|
+
* Prevents timing attacks on seal/hash comparison
|
|
225
|
+
*/
|
|
226
|
+
export function constantTimeEqual(a: string, b: string): boolean {
|
|
227
|
+
if (a.length !== b.length) {
|
|
228
|
+
return false;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
let result = 0;
|
|
232
|
+
for (let i = 0; i < a.length; i++) {
|
|
233
|
+
result |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
234
|
+
}
|
|
235
|
+
return result === 0;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ============================================================================
|
|
239
|
+
// ID GENERATION
|
|
240
|
+
// ============================================================================
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Generate a new fragment ID (UUID v4)
|
|
244
|
+
*/
|
|
245
|
+
export function generateFragmentId(): FragmentId {
|
|
246
|
+
return getRandomUUID() as FragmentId;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Generate a new warrant ID
|
|
251
|
+
* Format: w-{8 hex chars}
|
|
252
|
+
*/
|
|
253
|
+
export function generateWarrantId(): WarrantId {
|
|
254
|
+
const bytes = new Uint8Array(4);
|
|
255
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
256
|
+
const hex = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
257
|
+
return `w-${hex}` as WarrantId;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Generate a new checkpoint ID
|
|
262
|
+
* Format: cp-{8 hex chars}
|
|
263
|
+
*/
|
|
264
|
+
export function generateCheckpointId(): CheckpointId {
|
|
265
|
+
const bytes = new Uint8Array(4);
|
|
266
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
267
|
+
const hex = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
268
|
+
return `cp-${hex}` as CheckpointId;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Generate current timestamp in ISO format
|
|
273
|
+
*/
|
|
274
|
+
export function generateTimestamp(): Timestamp {
|
|
275
|
+
return new Date().toISOString() as Timestamp;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ============================================================================
|
|
279
|
+
// PROTOTYPE POLLUTION PREVENTION
|
|
280
|
+
// ============================================================================
|
|
281
|
+
|
|
282
|
+
const DANGEROUS_KEYS = ['__proto__', 'constructor', 'prototype'];
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Sanitize an object by removing dangerous prototype keys
|
|
286
|
+
* Recursively processes nested objects and arrays
|
|
287
|
+
*/
|
|
288
|
+
export function sanitizeObject<T>(obj: T): T {
|
|
289
|
+
if (obj === null || typeof obj !== 'object') {
|
|
290
|
+
return obj;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (Array.isArray(obj)) {
|
|
294
|
+
return obj.map(sanitizeObject) as T;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const result: Record<string, unknown> = {};
|
|
298
|
+
for (const key of Object.keys(obj as object)) {
|
|
299
|
+
if (!DANGEROUS_KEYS.includes(key)) {
|
|
300
|
+
result[key] = sanitizeObject((obj as Record<string, unknown>)[key]);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return result as T;
|
|
304
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mdash v3.0 Protocol
|
|
3
|
+
*
|
|
4
|
+
* "The best defense is the fastest seal."
|
|
5
|
+
*
|
|
6
|
+
* Liability infrastructure for autonomous AI agents.
|
|
7
|
+
* Cryptographic sealing at execution speed.
|
|
8
|
+
*
|
|
9
|
+
* Architecture:
|
|
10
|
+
* - L1: Commitment Layer (<1ms)
|
|
11
|
+
* - L2: TEE Attestation (<10ms)
|
|
12
|
+
* - L3: ZK Proofs (async)
|
|
13
|
+
* - MCCA: Manifold-Constrained Context Architecture
|
|
14
|
+
*
|
|
15
|
+
* @version 3.0.0
|
|
16
|
+
* @author Long Arc Studios
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
// Re-export core primitives
|
|
20
|
+
export * from './core/crypto.js';
|
|
21
|
+
export * from './core/commitment.js';
|
|
22
|
+
|
|
23
|
+
// Re-export engines
|
|
24
|
+
export * from './warrant/engine.js';
|
|
25
|
+
export * from './checkpoint/engine.js';
|
|
26
|
+
export * from './context/engine.js';
|
|
27
|
+
export * from './physics/engine.js';
|
|
28
|
+
|
|
29
|
+
// Re-export L2 TEE Attestation
|
|
30
|
+
export * from './tee/engine.js';
|
|
31
|
+
|
|
32
|
+
// Re-export L3 ZK Proofs
|
|
33
|
+
export * from './zk/engine.js';
|
|
34
|
+
|
|
35
|
+
// Re-export MCCA v3 (excluding SourceClass which is already exported from context)
|
|
36
|
+
export {
|
|
37
|
+
MCCAEngine,
|
|
38
|
+
ManifoldRegion,
|
|
39
|
+
InfluenceBudget,
|
|
40
|
+
MCCAConfig,
|
|
41
|
+
ManifoldFragment,
|
|
42
|
+
ManifoldCommitmentProof,
|
|
43
|
+
DEFAULT_CONFIG as MCCA_DEFAULT_CONFIG
|
|
44
|
+
} from './mcca/engine.js';
|
|
45
|
+
|
|
46
|
+
// Import for runtime
|
|
47
|
+
import { CommitmentEngine, LatencyMonitor, Commitment } from './core/commitment.js';
|
|
48
|
+
import { WarrantEngine, WarrantTier, WarrantConstraints, Warrant } from './warrant/engine.js';
|
|
49
|
+
import { CheckpointEngine, Checkpoint } from './checkpoint/engine.js';
|
|
50
|
+
import { SealedContextEngine, ContextFragment } from './context/engine.js';
|
|
51
|
+
import { PhysicsEngine, PhysicsValidation, PhysicsAction } from './physics/engine.js';
|
|
52
|
+
import { TEEAttestationEngine, AttestationDocument, AttestationBridge, TEEPlatform } from './tee/engine.js';
|
|
53
|
+
import { ZKProofsEngine, ZKProofDocument, ClaimBuilder } from './zk/engine.js';
|
|
54
|
+
import { MCCAEngine, ManifoldFragment, ContextWindowManager } from './mcca/engine.js';
|
|
55
|
+
import { WarrantId, generateTimestamp } from './core/crypto.js';
|
|
56
|
+
|
|
57
|
+
// ============================================================================
|
|
58
|
+
// PROTOCOL RUNTIME
|
|
59
|
+
// ============================================================================
|
|
60
|
+
|
|
61
|
+
export interface MdashConfig {
|
|
62
|
+
sealKey: string;
|
|
63
|
+
maxTreeDepth?: number;
|
|
64
|
+
enableLatencyMonitoring?: boolean;
|
|
65
|
+
teePlatform?: TEEPlatform;
|
|
66
|
+
enableZKProofs?: boolean;
|
|
67
|
+
zkConcurrency?: number;
|
|
68
|
+
enableMCCA?: boolean;
|
|
69
|
+
maxContextTokens?: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface MdashStats {
|
|
73
|
+
commitment: ReturnType<CommitmentEngine['getStats']>;
|
|
74
|
+
warrant: ReturnType<WarrantEngine['getCacheStats']>;
|
|
75
|
+
checkpoint: ReturnType<CheckpointEngine['getStats']>;
|
|
76
|
+
context: ReturnType<SealedContextEngine['getStats']>;
|
|
77
|
+
physics: ReturnType<PhysicsEngine['getStats']>;
|
|
78
|
+
tee?: ReturnType<TEEAttestationEngine['getStats']>;
|
|
79
|
+
zk?: ReturnType<ZKProofsEngine['getStats']>;
|
|
80
|
+
mcca?: ReturnType<MCCAEngine['getStats']>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export class MdashProtocol {
|
|
84
|
+
private config: MdashConfig;
|
|
85
|
+
private initialized: boolean = false;
|
|
86
|
+
|
|
87
|
+
public readonly commitment: CommitmentEngine;
|
|
88
|
+
public readonly warrant: WarrantEngine;
|
|
89
|
+
public readonly checkpoint: CheckpointEngine;
|
|
90
|
+
public readonly context: SealedContextEngine;
|
|
91
|
+
public readonly physics: PhysicsEngine;
|
|
92
|
+
public readonly latency: LatencyMonitor;
|
|
93
|
+
public readonly tee: TEEAttestationEngine;
|
|
94
|
+
public readonly bridge: AttestationBridge;
|
|
95
|
+
public readonly zk: ZKProofsEngine | null;
|
|
96
|
+
public readonly mcca: MCCAEngine | null;
|
|
97
|
+
public readonly contextWindow: ContextWindowManager | null;
|
|
98
|
+
|
|
99
|
+
constructor(config: MdashConfig) {
|
|
100
|
+
this.config = config;
|
|
101
|
+
this.commitment = new CommitmentEngine(config.maxTreeDepth);
|
|
102
|
+
this.warrant = new WarrantEngine(this.commitment);
|
|
103
|
+
this.checkpoint = new CheckpointEngine(this.commitment);
|
|
104
|
+
this.context = new SealedContextEngine(this.commitment);
|
|
105
|
+
this.physics = new PhysicsEngine();
|
|
106
|
+
this.tee = new TEEAttestationEngine(this.commitment, { platform: config.teePlatform || 'simulated' });
|
|
107
|
+
this.bridge = new AttestationBridge(this.tee, this.commitment);
|
|
108
|
+
this.zk = config.enableZKProofs !== false ? new ZKProofsEngine(this.commitment, config.zkConcurrency || 4) : null;
|
|
109
|
+
this.mcca = config.enableMCCA !== false ? new MCCAEngine(this.commitment, { maxTokens: config.maxContextTokens || 100000 }) : null;
|
|
110
|
+
this.contextWindow = this.mcca ? new ContextWindowManager(this.mcca, config.maxContextTokens || 100000) : null;
|
|
111
|
+
this.latency = new LatencyMonitor();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async initialize(): Promise<void> {
|
|
115
|
+
const startTime = performance.now();
|
|
116
|
+
await Promise.all([
|
|
117
|
+
this.commitment.initialize(this.config.sealKey),
|
|
118
|
+
this.warrant.initialize(this.config.sealKey),
|
|
119
|
+
this.checkpoint.initialize(this.config.sealKey),
|
|
120
|
+
this.context.initialize(this.config.sealKey),
|
|
121
|
+
this.physics.initialize(this.config.sealKey),
|
|
122
|
+
]);
|
|
123
|
+
await this.tee.initialize(this.config.sealKey);
|
|
124
|
+
if (this.zk) await this.zk.initialize(this.config.sealKey);
|
|
125
|
+
if (this.mcca) await this.mcca.initialize(this.config.sealKey);
|
|
126
|
+
this.initialized = true;
|
|
127
|
+
const elapsed = performance.now() - startTime;
|
|
128
|
+
console.log(`mdash v3.0 initialized in ${elapsed.toFixed(2)}ms`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
isInitialized(): boolean { return this.initialized; }
|
|
132
|
+
|
|
133
|
+
async execute<T>(params: {
|
|
134
|
+
agentId: string;
|
|
135
|
+
action: string;
|
|
136
|
+
actionParams: Record<string, unknown>;
|
|
137
|
+
execute: () => Promise<T>;
|
|
138
|
+
generateZKProof?: boolean;
|
|
139
|
+
}): Promise<{
|
|
140
|
+
result: T;
|
|
141
|
+
warrant: Warrant;
|
|
142
|
+
startCheckpoint: Checkpoint;
|
|
143
|
+
endCheckpoint: Checkpoint;
|
|
144
|
+
validation: PhysicsValidation;
|
|
145
|
+
attestation: AttestationDocument;
|
|
146
|
+
zkProof?: ZKProofDocument;
|
|
147
|
+
}> {
|
|
148
|
+
if (!this.initialized) throw new Error('Protocol not initialized');
|
|
149
|
+
|
|
150
|
+
const authParams = {
|
|
151
|
+
agent_id: params.agentId,
|
|
152
|
+
action: params.action,
|
|
153
|
+
amount: typeof params.actionParams.amount === 'number' ? params.actionParams.amount : undefined,
|
|
154
|
+
domain: typeof params.actionParams.domain === 'string' ? params.actionParams.domain : undefined,
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const warrant = await this.warrant.checkAuthorization(authParams);
|
|
158
|
+
if (!warrant) throw new Error(`No valid warrant for agent ${params.agentId}`);
|
|
159
|
+
|
|
160
|
+
const startCheckpoint = await this.checkpoint.onActionStart({
|
|
161
|
+
agent_id: params.agentId,
|
|
162
|
+
warrant_id: warrant.id,
|
|
163
|
+
action: params.action,
|
|
164
|
+
params: params.actionParams,
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const physicsAction: PhysicsAction = {
|
|
168
|
+
action_id: `${params.action}-${Date.now()}`,
|
|
169
|
+
type: params.action,
|
|
170
|
+
agent_id: params.agentId,
|
|
171
|
+
warrant_id: warrant.id,
|
|
172
|
+
params: params.actionParams,
|
|
173
|
+
timestamp: generateTimestamp(),
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
const validation = await this.physics.validate(physicsAction, warrant);
|
|
177
|
+
if (!validation.valid) {
|
|
178
|
+
await this.checkpoint.onError({
|
|
179
|
+
agent_id: params.agentId,
|
|
180
|
+
warrant_id: warrant.id,
|
|
181
|
+
action: params.action,
|
|
182
|
+
error: `Physics validation failed`,
|
|
183
|
+
});
|
|
184
|
+
throw new Error(`Physics validation failed`);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const { attestation } = await this.bridge.commitAndAttest(
|
|
188
|
+
{ warrant_id: warrant.id, action: params.action, params: params.actionParams },
|
|
189
|
+
`action:${params.agentId}:${Date.now()}`
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
let result: T;
|
|
193
|
+
try {
|
|
194
|
+
result = await params.execute();
|
|
195
|
+
} catch (error) {
|
|
196
|
+
await this.checkpoint.onError({
|
|
197
|
+
agent_id: params.agentId,
|
|
198
|
+
warrant_id: warrant.id,
|
|
199
|
+
action: params.action,
|
|
200
|
+
error: String(error),
|
|
201
|
+
});
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const endCheckpoint = await this.checkpoint.onActionComplete({
|
|
206
|
+
agent_id: params.agentId,
|
|
207
|
+
warrant_id: warrant.id,
|
|
208
|
+
action: params.action,
|
|
209
|
+
params: params.actionParams,
|
|
210
|
+
result,
|
|
211
|
+
physics_score: validation.score,
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
let zkProof: ZKProofDocument | undefined;
|
|
215
|
+
if (params.generateZKProof && this.zk) {
|
|
216
|
+
zkProof = await this.zk.requestProof(
|
|
217
|
+
new ClaimBuilder('action_compliance')
|
|
218
|
+
.withDescription(`Action proof for ${params.action}`)
|
|
219
|
+
.withClaim('agent_id', params.agentId)
|
|
220
|
+
.withClaim('action', params.action)
|
|
221
|
+
.withClaim('warrant_id', warrant.id)
|
|
222
|
+
.withAttestations(attestation.id)
|
|
223
|
+
.build('normal')
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return { result, warrant, startCheckpoint, endCheckpoint, validation, attestation, zkProof };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async prestageWarrant(params: {
|
|
231
|
+
agentId: string;
|
|
232
|
+
policyId: string;
|
|
233
|
+
tier: WarrantTier;
|
|
234
|
+
constraints: WarrantConstraints;
|
|
235
|
+
durationMs: number;
|
|
236
|
+
issuedBy: string;
|
|
237
|
+
}): Promise<Warrant> {
|
|
238
|
+
if (!this.initialized) throw new Error('Protocol not initialized');
|
|
239
|
+
return this.warrant.createSpeculative({
|
|
240
|
+
agent_id: params.agentId,
|
|
241
|
+
policy_id: params.policyId,
|
|
242
|
+
tier: params.tier,
|
|
243
|
+
constraints: params.constraints,
|
|
244
|
+
duration_ms: params.durationMs,
|
|
245
|
+
issued_by: params.issuedBy,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async revokeWarrant(warrantId: WarrantId, reason: string, actor: { type: 'user' | 'system'; id: string }): Promise<Warrant> {
|
|
250
|
+
if (!this.initialized) throw new Error('Protocol not initialized');
|
|
251
|
+
return this.warrant.revoke(warrantId, reason, actor);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async generateAuditProof(params: {
|
|
255
|
+
description: string;
|
|
256
|
+
claim: Record<string, unknown>;
|
|
257
|
+
commitmentIds?: string[];
|
|
258
|
+
attestationIds?: string[];
|
|
259
|
+
priority?: 'low' | 'normal' | 'high';
|
|
260
|
+
}): Promise<ZKProofDocument> {
|
|
261
|
+
if (!this.zk) throw new Error('ZK proofs not enabled');
|
|
262
|
+
return this.zk.requestProof(
|
|
263
|
+
new ClaimBuilder('audit_trail')
|
|
264
|
+
.withDescription(params.description)
|
|
265
|
+
.withClaim('audit', params.claim)
|
|
266
|
+
.withCommitments(...(params.commitmentIds || []))
|
|
267
|
+
.withAttestations(...(params.attestationIds || []))
|
|
268
|
+
.build(params.priority || 'normal')
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
getStats(): MdashStats {
|
|
273
|
+
const stats: MdashStats = {
|
|
274
|
+
commitment: this.commitment.getStats(),
|
|
275
|
+
warrant: this.warrant.getCacheStats(),
|
|
276
|
+
checkpoint: this.checkpoint.getStats(),
|
|
277
|
+
context: this.context.getStats(),
|
|
278
|
+
physics: this.physics.getStats(),
|
|
279
|
+
};
|
|
280
|
+
stats.tee = this.tee.getStats();
|
|
281
|
+
if (this.zk) stats.zk = this.zk.getStats();
|
|
282
|
+
if (this.mcca) stats.mcca = this.mcca.getStats();
|
|
283
|
+
return stats;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
checkSLAs(): Record<string, { withinSLA: boolean; metrics: unknown }> {
|
|
287
|
+
const ops = ['commitment_seal', 'merkle_proof', 'context_chunk_seal', 'checkpoint_create', 'execute'];
|
|
288
|
+
const results: Record<string, { withinSLA: boolean; metrics: unknown }> = {};
|
|
289
|
+
for (const op of ops) {
|
|
290
|
+
results[op] = { withinSLA: this.latency.isWithinSLA(op), metrics: this.latency.getMetrics(op) };
|
|
291
|
+
}
|
|
292
|
+
return results;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
shutdown(): void {
|
|
296
|
+
if (this.zk) this.zk.stopProcessing();
|
|
297
|
+
console.log('mdash v3.0 shutdown complete');
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export function createMdash(config: MdashConfig): MdashProtocol {
|
|
302
|
+
return new MdashProtocol(config);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export const VERSION = {
|
|
306
|
+
protocol: '3.0.0',
|
|
307
|
+
codename: 'Sealed Execution',
|
|
308
|
+
releaseDate: '2026-01',
|
|
309
|
+
features: [
|
|
310
|
+
'L1 Commitment Layer (<1ms)',
|
|
311
|
+
'L2 TEE Attestation (AWS Nitro/SGX, <10ms)',
|
|
312
|
+
'L3 ZK Proofs (Plonky2, async)',
|
|
313
|
+
'MCCA v3 (Manifold-Constrained Context Architecture)',
|
|
314
|
+
'Speculative Warrant Issuance (<10ms activation)',
|
|
315
|
+
'Event-driven Checkpoints',
|
|
316
|
+
'Incremental Merkle Sealing',
|
|
317
|
+
'Physics Engine with Hot-swap Policies',
|
|
318
|
+
'Insurance-grade Audit Trails',
|
|
319
|
+
],
|
|
320
|
+
} as const;
|