@optimystic/db-p2p 0.1.3 → 0.2.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.
Files changed (41) hide show
  1. package/README.md +44 -0
  2. package/dist/index.min.js +17 -17
  3. package/dist/index.min.js.map +4 -4
  4. package/dist/src/cluster/client.d.ts +1 -2
  5. package/dist/src/cluster/client.d.ts.map +1 -1
  6. package/dist/src/cluster/client.js.map +1 -1
  7. package/dist/src/libp2p-key-network.d.ts.map +1 -1
  8. package/dist/src/libp2p-key-network.js +4 -4
  9. package/dist/src/libp2p-key-network.js.map +1 -1
  10. package/dist/src/libp2p-node-base.d.ts +53 -0
  11. package/dist/src/libp2p-node-base.d.ts.map +1 -0
  12. package/dist/src/libp2p-node-base.js +291 -0
  13. package/dist/src/libp2p-node-base.js.map +1 -0
  14. package/dist/src/libp2p-node-rn.d.ts +11 -0
  15. package/dist/src/libp2p-node-rn.d.ts.map +1 -0
  16. package/dist/src/libp2p-node-rn.js +19 -0
  17. package/dist/src/libp2p-node-rn.js.map +1 -0
  18. package/dist/src/libp2p-node.d.ts +3 -37
  19. package/dist/src/libp2p-node.d.ts.map +1 -1
  20. package/dist/src/libp2p-node.js +6 -287
  21. package/dist/src/libp2p-node.js.map +1 -1
  22. package/dist/src/protocol-client.d.ts +1 -2
  23. package/dist/src/protocol-client.d.ts.map +1 -1
  24. package/dist/src/protocol-client.js.map +1 -1
  25. package/dist/src/repo/client.d.ts +1 -2
  26. package/dist/src/repo/client.d.ts.map +1 -1
  27. package/dist/src/repo/client.js.map +1 -1
  28. package/dist/src/rn.d.ts +29 -0
  29. package/dist/src/rn.d.ts.map +1 -0
  30. package/dist/src/rn.js +29 -0
  31. package/dist/src/rn.js.map +1 -0
  32. package/package.json +6 -2
  33. package/src/cluster/client.ts +1 -2
  34. package/src/index.ts +0 -2
  35. package/src/libp2p-key-network.ts +5 -6
  36. package/src/libp2p-node-base.ts +386 -0
  37. package/src/libp2p-node-rn.ts +30 -0
  38. package/src/libp2p-node.ts +14 -364
  39. package/src/protocol-client.ts +3 -3
  40. package/src/repo/client.ts +1 -2
  41. package/src/rn.ts +28 -0
@@ -1,371 +1,21 @@
1
- import { createLibp2p, type Libp2p } from 'libp2p';
1
+ import type { Libp2p } from 'libp2p';
2
2
  import { tcp } from '@libp2p/tcp';
3
- import { noise } from '@chainsafe/libp2p-noise';
4
- import { yamux } from '@chainsafe/libp2p-yamux';
5
- import { identify } from '@libp2p/identify';
6
- import { ping } from '@libp2p/ping';
7
- import { gossipsub } from '@chainsafe/libp2p-gossipsub';
8
- import { bootstrap } from '@libp2p/bootstrap';
9
- import { circuitRelayServer, circuitRelayTransport } from '@libp2p/circuit-relay-v2';
10
- import { peerIdFromString } from '@libp2p/peer-id';
11
- import { clusterService } from './cluster/service.js';
12
- import { repoService } from './repo/service.js';
13
- import { StorageRepo } from './storage/storage-repo.js';
14
- import { BlockStorage } from './storage/block-storage.js';
15
- import { MemoryRawStorage } from './storage/memory-storage.js';
16
- import type { IRawStorage } from './storage/i-raw-storage.js';
17
- import { clusterMember } from './cluster/cluster-repo.js';
18
- import { coordinatorRepo } from './repo/coordinator-repo.js';
19
- import { Libp2pKeyPeerNetwork } from './libp2p-key-network.js';
20
- import { ClusterClient } from './cluster/client.js';
21
- import type { IRepo, ICluster, ITransactionValidator } from '@optimystic/db-core';
22
- import { networkManagerService } from './network/network-manager-service.js';
23
- import { fretService, Libp2pFretService } from 'p2p-fret';
24
- import { syncService } from './sync/service.js';
25
- import { SyncClient } from './sync/client.js';
26
- import type { ClusterLatestCallback } from './repo/coordinator-repo.js';
27
- import { RestorationCoordinator } from './storage/restoration-coordinator-v2.js';
28
- import { RingSelector } from './storage/ring-selector.js';
29
- import { StorageMonitor } from './storage/storage-monitor.js';
30
- import type { StorageMonitorConfig } from './storage/storage-monitor.js';
31
- import { ArachnodeFretAdapter } from './storage/arachnode-fret-adapter.js';
32
- import type { RestoreCallback } from './storage/struct.js';
33
- import type { FretService } from 'p2p-fret';
34
- import { PartitionDetector } from './cluster/partition-detector.js';
3
+ import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
4
+ import {
5
+ createLibp2pNodeBase,
6
+ type Libp2pTransports,
7
+ type NodeOptions,
8
+ type RawStorageProvider,
9
+ } from './libp2p-node-base.js';
35
10
 
36
- /** Factory function or instance for creating raw storage */
37
- export type RawStorageProvider = IRawStorage | (() => IRawStorage);
38
-
39
- export type NodeOptions = {
40
- port: number;
41
- bootstrapNodes: string[];
42
- networkName: string;
43
- fretProfile?: 'edge' | 'core';
44
- id?: string; // optional peer id
45
- relay?: boolean; // enable relay service
46
- /** Storage provider - either an IRawStorage instance or a factory function. Defaults to MemoryRawStorage if not provided. */
47
- storage?: RawStorageProvider;
48
- clusterSize?: number; // desired cluster size per key
49
- clusterPolicy?: {
50
- allowDownsize?: boolean;
51
- sizeTolerance?: number; // acceptable relative difference (e.g. 0.5 = +/-50%)
52
- superMajorityThreshold?: number; // fraction of peers needed for super-majority (default: 0.67)
53
- };
54
-
55
- /**
56
- * Responsibility K - the replica set size for determining cluster membership.
57
- * This is distinct from kBucketSize (DHT routing) and clusterSize (consensus quorum).
58
- * When a node receives a request, it checks if it's in the top responsibilityK
59
- * peers (by XOR distance) for the key. If not, it redirects to closer peers.
60
- * Default: 1 (only the closest peer is responsible)
61
- */
62
- responsibilityK?: number;
63
-
64
- /** Arachnode storage configuration */
65
- arachnode?: {
66
- enableRingZulu?: boolean; // default: true
67
- storage?: StorageMonitorConfig;
68
- };
69
-
70
- /** Transaction validator for cluster consensus */
71
- validator?: ITransactionValidator;
72
- };
73
-
74
- function resolveStorage(provider: RawStorageProvider | undefined): IRawStorage {
75
- if (!provider) {
76
- return new MemoryRawStorage();
77
- }
78
- return typeof provider === 'function' ? provider() : provider;
79
- }
11
+ export type { Libp2pTransports, NodeOptions, RawStorageProvider };
80
12
 
81
13
  export async function createLibp2pNode(options: NodeOptions): Promise<Libp2p> {
82
- const rawStorage = resolveStorage(options.storage);
83
-
84
- // Create placeholder restore callback (will be replaced after node starts)
85
- let restoreCallback: RestoreCallback = async (_blockId, _rev?) => {
86
- return undefined;
87
- };
88
-
89
- // Create shared storage layers with restoration callback
90
- const storageRepo = new StorageRepo((blockId) =>
91
- new BlockStorage(blockId, rawStorage, restoreCallback)
92
- );
93
-
94
- let clusterImpl: ICluster | undefined;
95
- let coordinatedRepo: IRepo | undefined;
96
-
97
- const clusterProxy: ICluster = {
98
- async update(record) {
99
- if (!clusterImpl) {
100
- throw new Error('ClusterMember not initialized');
101
- }
102
- return await clusterImpl.update(record);
103
- }
104
- };
105
-
106
- const repoProxy: IRepo = {
107
- async get(blockGets, options) {
108
- const target = coordinatedRepo ?? storageRepo;
109
- return await target.get(blockGets, options);
110
- },
111
- async pend(request, options) {
112
- const target = coordinatedRepo ?? storageRepo;
113
- return await target.pend(request, options);
114
- },
115
- async cancel(trxRef, options) {
116
- const target = coordinatedRepo ?? storageRepo;
117
- return await target.cancel(trxRef, options);
118
- },
119
- async commit(request, options) {
120
- const target = coordinatedRepo ?? storageRepo;
121
- return await target.commit(request, options);
122
- }
123
- };
124
-
125
- // Parse peer ID if provided
126
- const peerId = options.id ? await peerIdFromString(options.id) : undefined;
127
-
128
- const libp2pOptions: any = {
129
- start: false,
130
- ...(peerId ? { peerId } : {}),
131
- addresses: {
132
- listen: [`/ip4/0.0.0.0/tcp/${options.port}`]
133
- },
134
- connectionManager: {
135
- autoDial: true,
136
- minConnections: 1,
137
- maxConnections: 16,
138
- inboundConnectionUpgradeTimeout: 10_000,
139
- dialQueue: { concurrency: 2, attempts: 2 }
140
- },
141
- // Add circuitRelayTransport so this node can dial through relays
14
+ const port = options.port ?? 0;
15
+ return await createLibp2pNodeBase(options, {
16
+ listenAddrs: [`/ip4/0.0.0.0/tcp/${port}`],
17
+ // Default node transports: TCP + relay transport so this node can dial through relays
142
18
  transports: [tcp(), circuitRelayTransport()],
143
- connectionEncrypters: [noise()],
144
- streamMuxers: [yamux()],
145
- services: {
146
- identify: identify({
147
- protocolPrefix: `/optimystic/${options.networkName}`
148
- }),
149
- ping: ping(),
150
- pubsub: gossipsub({
151
- allowPublishToZeroTopicPeers: true,
152
- heartbeatInterval: 7000
153
- }),
154
- // Circuit relay server - enables this node to relay connections for other peers
155
- ...(options.relay ? { relay: circuitRelayServer() } : {}),
156
-
157
- // Custom services - create wrapper factories that inject dependencies
158
- cluster: (components: any) => {
159
- const serviceFactory = clusterService({
160
- protocolPrefix: `/optimystic/${options.networkName}`,
161
- configuredClusterSize: options.clusterSize ?? 10,
162
- allowClusterDownsize: options.clusterPolicy?.allowDownsize ?? true,
163
- clusterSizeTolerance: options.clusterPolicy?.sizeTolerance ?? 0.5,
164
- responsibilityK: options.responsibilityK ?? 1
165
- });
166
- return serviceFactory({
167
- logger: components.logger,
168
- registrar: components.registrar,
169
- cluster: clusterProxy
170
- });
171
- },
172
-
173
- repo: (components: any) => {
174
- const serviceFactory = repoService({
175
- protocolPrefix: `/optimystic/${options.networkName}`,
176
- responsibilityK: options.responsibilityK ?? 1
177
- });
178
- return serviceFactory({
179
- logger: components.logger,
180
- registrar: components.registrar,
181
- repo: repoProxy
182
- });
183
- },
184
-
185
- sync: (components: any) => {
186
- const serviceFactory = syncService({
187
- protocolPrefix: `/optimystic/${options.networkName}`
188
- });
189
- return serviceFactory({
190
- logger: components.logger,
191
- registrar: components.registrar,
192
- repo: repoProxy
193
- });
194
- },
195
-
196
- networkManager: (components: any) => {
197
- const svcFactory = networkManagerService({
198
- clusterSize: options.clusterSize ?? 10,
199
- expectedRemotes: (options.bootstrapNodes?.length ?? 0) > 0,
200
- allowClusterDownsize: options.clusterPolicy?.allowDownsize ?? true,
201
- clusterSizeTolerance: options.clusterPolicy?.sizeTolerance ?? 0.5
202
- })
203
- const svc = svcFactory(components)
204
- try { (svc as any).setLibp2p?.(components.libp2p) } catch { }
205
- return svc
206
- },
207
- fret: (components: any) => {
208
- const svcFactory = fretService({
209
- k: 15,
210
- m: 8,
211
- capacity: 2048,
212
- profile: options.fretProfile ?? ((options.bootstrapNodes?.length ?? 0) > 0 ? 'core' : 'edge'),
213
- networkName: options.networkName,
214
- bootstraps: options.bootstrapNodes ?? []
215
- });
216
- const svc = svcFactory(components) as Libp2pFretService;
217
- try { svc.setLibp2p(components.libp2p); } catch { }
218
- return svc;
219
- }
220
- },
221
- // Add bootstrap nodes as needed
222
- peerDiscovery: [
223
- ...(options.bootstrapNodes?.length ? [bootstrap({ list: options.bootstrapNodes })] : [])
224
- ],
225
- };
226
-
227
- const node = await createLibp2p(libp2pOptions);
228
-
229
- // Inject libp2p reference into services that need it before start
230
- try { ((node as any).services?.fret as any)?.setLibp2p?.(node) } catch { }
231
- try { ((node as any).services?.networkManager as any)?.setLibp2p?.(node) } catch { }
232
-
233
- await node.start();
234
-
235
- // Initialize cluster coordination components
236
- const keyNetwork = new Libp2pKeyPeerNetwork(node);
237
- const protocolPrefix = `/optimystic/${options.networkName}`;
238
- const createClusterClient = (peerId: any) => ClusterClient.create(peerId, keyNetwork, protocolPrefix);
239
-
240
- // Create partition detector and get FRET service
241
- const partitionDetector = new PartitionDetector();
242
- const fretSvc = (node as any).services?.fret as FretService | undefined;
243
-
244
- clusterImpl = clusterMember({
245
- storageRepo,
246
- peerNetwork: keyNetwork,
247
- peerId: node.peerId,
248
- protocolPrefix,
249
- partitionDetector,
250
- fretService: fretSvc,
251
- validator: options.validator
252
- });
253
-
254
- const coordinatorRepoFactory = coordinatorRepo(
255
- keyNetwork,
256
- createClusterClient,
257
- {
258
- clusterSize: options.clusterSize ?? 10,
259
- superMajorityThreshold: options.clusterPolicy?.superMajorityThreshold ?? 0.67,
260
- simpleMajorityThreshold: 0.51,
261
- minAbsoluteClusterSize: 2, // Allow 2-node clusters for development/small networks
262
- allowClusterDownsize: options.clusterPolicy?.allowDownsize ?? true,
263
- clusterSizeTolerance: options.clusterPolicy?.sizeTolerance ?? 0.5,
264
- partitionDetectionWindow: 60000
265
- },
266
- fretSvc
267
- );
268
-
269
- // Create callback for querying cluster peers for their latest block revision
270
- const clusterLatestCallback: ClusterLatestCallback = async (peerId, blockId) => {
271
- const syncClient = new SyncClient(peerId, keyNetwork, protocolPrefix);
272
- try {
273
- const response = await syncClient.requestBlock({ blockId, rev: undefined });
274
- if (response.success && response.archive) {
275
- const revisions = Object.keys(response.archive.revisions).map(Number);
276
- if (revisions.length > 0) {
277
- const maxRev = Math.max(...revisions);
278
- const revisionData = response.archive.revisions[maxRev];
279
- if (revisionData?.action) {
280
- return { actionId: revisionData.action.actionId, rev: maxRev };
281
- }
282
- }
283
- }
284
- } catch {
285
- // Peer may be unreachable - return undefined to skip this peer
286
- }
287
- return undefined;
288
- };
289
-
290
- coordinatedRepo = coordinatorRepoFactory({
291
- storageRepo,
292
- localCluster: clusterImpl,
293
- localPeerId: node.peerId,
294
- clusterLatestCallback
295
19
  });
296
-
297
- // Initialize Arachnode ring membership and restoration
298
- const enableArachnode = options.arachnode?.enableRingZulu ?? true;
299
- if (enableArachnode) {
300
- const log = (node as any).logger?.forComponent?.('db-p2p:arachnode');
301
- const fret = (node as any).services?.fret as any;
302
-
303
- if (fret) {
304
- const fretAdapter = new ArachnodeFretAdapter(fret);
305
-
306
- const storageMonitor = new StorageMonitor(rawStorage, options.arachnode?.storage ?? {});
307
- const ringSelector = new RingSelector(fretAdapter, storageMonitor, {
308
- minCapacity: 100 * 1024 * 1024, // 100MB minimum
309
- thresholds: {
310
- moveOut: 0.85,
311
- moveIn: 0.40
312
- }
313
- });
314
-
315
- // Determine and announce ring membership
316
- const peerId = node.peerId.toString();
317
- const arachnodeInfo = await ringSelector.createArachnodeInfo(peerId);
318
- fretAdapter.setArachnodeInfo(arachnodeInfo);
319
-
320
- log?.('Announced Arachnode membership: Ring %d', arachnodeInfo.ringDepth);
321
-
322
- // Setup restoration coordinator with FRET adapter
323
- const restorationCoordinatorV2 = new RestorationCoordinator(
324
- fretAdapter,
325
- { connect: (pid, protocol) => node.dialProtocol(pid, [protocol]) },
326
- `/optimystic/${options.networkName}`
327
- );
328
-
329
- // Update restore callback to use new coordinator
330
- const newRestoreCallback: RestoreCallback = async (blockId, rev?) => {
331
- return await restorationCoordinatorV2.restore(blockId, rev);
332
- };
333
-
334
- // Replace the restore callback (this is a bit hacky, but works for now)
335
- // In production, we'd want to properly manage this
336
- (storageRepo as any).createBlockStorage = (blockId: string) =>
337
- new BlockStorage(blockId, rawStorage, newRestoreCallback);
338
-
339
- // Monitor capacity and adjust ring periodically
340
- const monitorInterval = setInterval(async () => {
341
- const transition = await ringSelector.shouldTransition();
342
- if (transition.shouldMove) {
343
- log?.('Ring transition needed: moving %s to Ring %d',
344
- transition.direction, transition.newRingDepth);
345
-
346
- // Update Arachnode info with new ring
347
- const updatedInfo = await ringSelector.createArachnodeInfo(peerId);
348
- fretAdapter.setArachnodeInfo(updatedInfo);
349
- }
350
- }, 60_000); // Check every minute
351
-
352
- // Cleanup on node stop
353
- const originalStop = node.stop.bind(node);
354
- node.stop = async () => {
355
- clearInterval(monitorInterval);
356
- await originalStop();
357
- };
358
- } else {
359
- log?.('FRET service not available, Arachnode disabled');
360
- }
361
- }
362
-
363
- // Skip proactive bootstrap dials; rely on discovery and minimal churn
364
-
365
- // Expose coordinated repo and storage for external use
366
- (node as any).coordinatedRepo = coordinatedRepo;
367
- (node as any).storageRepo = storageRepo;
368
- (node as any).keyNetwork = keyNetwork;
369
-
370
- return node;
371
20
  }
21
+
@@ -1,7 +1,7 @@
1
1
  import { pipe } from 'it-pipe';
2
2
  import { encode as lpEncode, decode as lpDecode } from 'it-length-prefixed';
3
- import type { PeerId } from '@libp2p/interface';
4
- import type { IPeerNetwork } from '@optimystic/db-core';
3
+ import type { Stream as Libp2pStream } from '@libp2p/interface';
4
+ import type { PeerId, IPeerNetwork } from '@optimystic/db-core';
5
5
  import { first } from './it-utility.js';
6
6
 
7
7
  /** Base class for clients that communicate via a libp2p protocol */
@@ -20,7 +20,7 @@ export class ProtocolClient {
20
20
  this.peerId,
21
21
  protocol,
22
22
  { signal: options?.signal }
23
- );
23
+ ) as unknown as Libp2pStream;
24
24
 
25
25
  try {
26
26
  // Send the request using length-prefixed encoding
@@ -1,9 +1,8 @@
1
1
  import type {
2
2
  IRepo, GetBlockResults, PendSuccess, StaleFailure, ActionBlocks, MessageOptions, CommitResult,
3
- PendRequest, CommitRequest, BlockGets, IPeerNetwork
3
+ PendRequest, CommitRequest, BlockGets, IPeerNetwork, PeerId
4
4
  } from "@optimystic/db-core";
5
5
  import type { RepoMessage } from "@optimystic/db-core";
6
- import type { PeerId } from "@libp2p/interface";
7
6
  import { ProtocolClient } from "../protocol-client.js";
8
7
  import { peerIdFromString } from "@libp2p/peer-id";
9
8
 
package/src/rn.ts ADDED
@@ -0,0 +1,28 @@
1
+ export * from './cluster/client.js';
2
+ export * from './cluster/cluster-repo.js';
3
+ export * from './cluster/service.js';
4
+ export * from './protocol-client.js';
5
+ export * from './repo/client.js';
6
+ export * from './repo/cluster-coordinator.js';
7
+ export * from './repo/coordinator-repo.js';
8
+ export * from './repo/service.js';
9
+ export * from './storage/block-storage.js';
10
+ export * from './storage/memory-storage.js';
11
+ export * from './storage/i-block-storage.js';
12
+ export * from './storage/i-raw-storage.js';
13
+ export * from './storage/struct.js';
14
+ export * from './storage/storage-repo.js';
15
+ export * from './storage/restoration-coordinator-v2.js';
16
+ export * from './storage/ring-selector.js';
17
+ export * from './storage/storage-monitor.js';
18
+ export * from './storage/arachnode-fret-adapter.js';
19
+ export * from './sync/protocol.js';
20
+ export * from './sync/client.js';
21
+ export * from './sync/service.js';
22
+ export * from './it-utility.js';
23
+ export * from './libp2p-key-network.js';
24
+ export * from './libp2p-node-rn.js';
25
+ export * from './routing/responsibility.js';
26
+ export * from './routing/libp2p-known-peers.js';
27
+ export * from './network/network-manager-service.js';
28
+ export * from './network/get-network-manager.js';