|
| 1 | +/** |
| 2 | + * @lambda-foundation/mesh - IPFS-Enabled Lambda Mesh Node |
| 3 | + * |
| 4 | + * "Memory is eternal. What the network learns, the network never forgets." |
| 5 | + * |
| 6 | + * Phase 1: Single node (Monarch) |
| 7 | + * Phase 2: Network consensus (Diplomat) |
| 8 | + * Phase 3: Permanent storage (Historian) |
| 9 | + */ |
| 10 | + |
| 11 | +import { P2PLambdaMeshNode } from './P2PLambdaMeshNode.js'; |
| 12 | +import { IpfsStorage, type IpfsStorageConfig } from './storage/IpfsStorage.js'; |
| 13 | +import type { |
| 14 | + MorphismAnnounceMessage, |
| 15 | + MorphismSyncRequestMessage, |
| 16 | + MorphismSyncResponseMessage, |
| 17 | +} from './storage/types.js'; |
| 18 | +import type { |
| 19 | + MeshConfig, |
| 20 | + CanonicalMorphism, |
| 21 | + LambdaExpr, |
| 22 | + VerifyResponse, |
| 23 | +} from './types.js'; |
| 24 | +import type { MeshMessage } from './network/types.js'; |
| 25 | + |
| 26 | +export interface IpfsMeshConfig extends MeshConfig { |
| 27 | + ipfs?: IpfsStorageConfig; |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * IPFS-enabled Lambda Mesh Node |
| 32 | + * |
| 33 | + * Extends P2P node with permanent IPFS storage |
| 34 | + */ |
| 35 | +export class IpfsLambdaMeshNode extends P2PLambdaMeshNode { |
| 36 | + private storage: IpfsStorage; |
| 37 | + |
| 38 | + constructor(config: IpfsMeshConfig) { |
| 39 | + super(config); |
| 40 | + |
| 41 | + this.storage = new IpfsStorage(config.ipfs ?? {}); |
| 42 | + |
| 43 | + // Setup storage event handlers |
| 44 | + this.storage.on('stored', ({ morphism, cid }) => { |
| 45 | + this.handleMorphismStored(morphism, cid); |
| 46 | + }); |
| 47 | + |
| 48 | + this.storage.on('synced', ({ morphism, cid }) => { |
| 49 | + this.handleMorphismSynced(morphism, cid); |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Start IPFS-enabled node |
| 55 | + */ |
| 56 | + async start(): Promise<void> { |
| 57 | + // Start P2P layer first |
| 58 | + await super.start(); |
| 59 | + |
| 60 | + // Connect to IPFS |
| 61 | + await this.storage.connect(); |
| 62 | + |
| 63 | + const stats = this.storage.getStats(); |
| 64 | + console.log(` IPFS: ${stats.connected ? 'Connected' : 'Local fallback'}`); |
| 65 | + console.log(` Cache: ${stats.localCacheSize} morphisms\n`); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Verify lambda expression with IPFS storage |
| 70 | + * |
| 71 | + * After consensus, store accepted morphisms on IPFS |
| 72 | + */ |
| 73 | + async verifyLambda(expr: string, metadata?: LambdaExpr['metadata']): Promise<VerifyResponse> { |
| 74 | + // Get consensus result from P2P layer |
| 75 | + const result = await super.verifyLambda(expr, metadata); |
| 76 | + |
| 77 | + // If new morphism created (201), store on IPFS |
| 78 | + if (result.status === 201 && result.newMorphism) { |
| 79 | + await this.storeMorphismOnIpfs(result.newMorphism); |
| 80 | + } |
| 81 | + |
| 82 | + return result; |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Store morphism on IPFS and announce to peers |
| 87 | + */ |
| 88 | + private async storeMorphismOnIpfs(morphism: CanonicalMorphism): Promise<void> { |
| 89 | + console.log(` 💾 Storing on IPFS...`); |
| 90 | + |
| 91 | + try { |
| 92 | + const cid = await this.storage.store(morphism); |
| 93 | + |
| 94 | + // Announce to all peers that we have this morphism |
| 95 | + this.announceMorphism(cid, morphism); |
| 96 | + } catch (err) { |
| 97 | + console.error(` ❌ IPFS storage failed: ${err}`); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Announce morphism to peers |
| 103 | + */ |
| 104 | + private announceMorphism(cid: string, morphism: CanonicalMorphism): void { |
| 105 | + const message: MorphismAnnounceMessage = { |
| 106 | + type: 'MORPHISM_ANNOUNCE', |
| 107 | + from: this.nodeId, |
| 108 | + timestamp: Date.now(), |
| 109 | + cid, |
| 110 | + morphismHash: morphism.hash, |
| 111 | + morphismName: morphism.name, |
| 112 | + }; |
| 113 | + |
| 114 | + console.log(` 📢 Announcing to network: ${morphism.name} (CID: ${cid.slice(0, 16)}...)`); |
| 115 | + this.broadcastMessage(message); |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * Handle morphism stored event |
| 120 | + */ |
| 121 | + private handleMorphismStored(morphism: CanonicalMorphism, cid: string): void { |
| 122 | + this.emit('morphism-stored-ipfs', { morphism, cid }); |
| 123 | + } |
| 124 | + |
| 125 | + /** |
| 126 | + * Handle morphism synced from peer |
| 127 | + */ |
| 128 | + private handleMorphismSynced(morphism: CanonicalMorphism, cid: string): void { |
| 129 | + // Add to local registry |
| 130 | + this.morphisms.set(morphism.hash, morphism); |
| 131 | + |
| 132 | + console.log(` ✅ Morphism synced to local registry: ${morphism.name}`); |
| 133 | + this.emit('morphism-synced', { morphism, cid }); |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Handle storage-related network messages |
| 138 | + */ |
| 139 | + protected async handleStorageMessage(message: MeshMessage): Promise<void> { |
| 140 | + switch (message.type) { |
| 141 | + case 'MORPHISM_ANNOUNCE': |
| 142 | + await this.handleMorphismAnnounce(message as MorphismAnnounceMessage); |
| 143 | + break; |
| 144 | + |
| 145 | + case 'MORPHISM_SYNC_REQUEST': |
| 146 | + await this.handleMorphismSyncRequest(message as MorphismSyncRequestMessage); |
| 147 | + break; |
| 148 | + |
| 149 | + case 'MORPHISM_SYNC_RESPONSE': |
| 150 | + await this.handleMorphismSyncResponse(message as MorphismSyncResponseMessage); |
| 151 | + break; |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + /** |
| 156 | + * Handle morphism announcement from peer |
| 157 | + */ |
| 158 | + private async handleMorphismAnnounce(message: MorphismAnnounceMessage): Promise<void> { |
| 159 | + const { cid, morphismHash, morphismName, from } = message; |
| 160 | + |
| 161 | + console.log(`\n📢 Morphism announced by ${from}: ${morphismName}`); |
| 162 | + console.log(` CID: ${cid.slice(0, 16)}...`); |
| 163 | + |
| 164 | + // Check if we already have this morphism |
| 165 | + if (this.morphisms.has(morphismHash)) { |
| 166 | + console.log(` ✓ Already have this morphism`); |
| 167 | + return; |
| 168 | + } |
| 169 | + |
| 170 | + // Sync from IPFS |
| 171 | + console.log(` 🔄 Syncing from IPFS...`); |
| 172 | + const morphism = await this.storage.syncFromPeer(cid); |
| 173 | + |
| 174 | + if (morphism) { |
| 175 | + // Add to local registry |
| 176 | + this.morphisms.set(morphism.hash, morphism); |
| 177 | + console.log(` ✅ Synced and added to registry`); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + /** |
| 182 | + * Handle sync request from peer |
| 183 | + */ |
| 184 | + private async handleMorphismSyncRequest(message: MorphismSyncRequestMessage): Promise<void> { |
| 185 | + const { cid, from } = message; |
| 186 | + |
| 187 | + console.log(`\n🔄 Sync request from ${from} for CID: ${cid.slice(0, 16)}...`); |
| 188 | + |
| 189 | + const morphism = await this.storage.retrieve(cid); |
| 190 | + |
| 191 | + if (morphism) { |
| 192 | + const response: MorphismSyncResponseMessage = { |
| 193 | + type: 'MORPHISM_SYNC_RESPONSE', |
| 194 | + from: this.nodeId, |
| 195 | + timestamp: Date.now(), |
| 196 | + cid, |
| 197 | + morphism, |
| 198 | + }; |
| 199 | + |
| 200 | + this.sendMessageToPeer(from, response); |
| 201 | + console.log(` ✅ Sent morphism to ${from}`); |
| 202 | + } else { |
| 203 | + console.log(` ❌ Morphism not found`); |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + /** |
| 208 | + * Handle sync response from peer |
| 209 | + */ |
| 210 | + private async handleMorphismSyncResponse(message: MorphismSyncResponseMessage): Promise<void> { |
| 211 | + const { morphism, cid, from } = message; |
| 212 | + |
| 213 | + console.log(`\n📦 Received morphism from ${from}: ${morphism.name}`); |
| 214 | + |
| 215 | + // Store locally |
| 216 | + this.morphisms.set(morphism.hash, morphism); |
| 217 | + await this.storage.store(morphism); |
| 218 | + |
| 219 | + console.log(` ✅ Stored locally`); |
| 220 | + } |
| 221 | + |
| 222 | + /** |
| 223 | + * Broadcast message to all peers (helper) |
| 224 | + */ |
| 225 | + private broadcastMessage(message: MeshMessage): void { |
| 226 | + // Access protected transport through any cast |
| 227 | + const transport = (this as any).transport; |
| 228 | + if (transport) { |
| 229 | + transport.broadcast(message); |
| 230 | + } |
| 231 | + } |
| 232 | + |
| 233 | + /** |
| 234 | + * Send message to specific peer (helper) |
| 235 | + */ |
| 236 | + private sendMessageToPeer(peerId: string, message: MeshMessage): void { |
| 237 | + const transport = (this as any).transport; |
| 238 | + if (transport) { |
| 239 | + transport.sendToPeer(peerId, message); |
| 240 | + } |
| 241 | + } |
| 242 | + |
| 243 | + /** |
| 244 | + * Get storage statistics |
| 245 | + */ |
| 246 | + getStorageStats() { |
| 247 | + return this.storage.getStats(); |
| 248 | + } |
| 249 | + |
| 250 | + /** |
| 251 | + * Stop IPFS-enabled node |
| 252 | + */ |
| 253 | + async stop(): Promise<void> { |
| 254 | + await this.storage.disconnect(); |
| 255 | + await super.stop(); |
| 256 | + } |
| 257 | +} |
0 commit comments