@aztec/p2p 0.79.0 → 0.81.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 (52) hide show
  1. package/dest/bootstrap/bootstrap.d.ts.map +1 -1
  2. package/dest/bootstrap/bootstrap.js +5 -5
  3. package/dest/client/p2p_client.d.ts +2 -1
  4. package/dest/client/p2p_client.d.ts.map +1 -1
  5. package/dest/client/p2p_client.js +14 -3
  6. package/dest/config.d.ts +11 -16
  7. package/dest/config.d.ts.map +1 -1
  8. package/dest/config.js +13 -17
  9. package/dest/enr/generate-enr.d.ts +1 -1
  10. package/dest/enr/generate-enr.d.ts.map +1 -1
  11. package/dest/enr/generate-enr.js +2 -2
  12. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  13. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +13 -7
  14. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -1
  15. package/dest/msg_validators/tx_validator/data_validator.js +5 -5
  16. package/dest/msg_validators/tx_validator/tx_proof_validator.js +2 -2
  17. package/dest/services/discv5/discV5_service.d.ts +4 -3
  18. package/dest/services/discv5/discV5_service.d.ts.map +1 -1
  19. package/dest/services/discv5/discV5_service.js +36 -21
  20. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  21. package/dest/services/libp2p/libp2p_service.js +8 -11
  22. package/dest/test-helpers/make-enrs.d.ts.map +1 -1
  23. package/dest/test-helpers/make-enrs.js +3 -4
  24. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  25. package/dest/test-helpers/make-test-p2p-clients.js +2 -6
  26. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  27. package/dest/test-helpers/reqresp-nodes.js +7 -8
  28. package/dest/testbench/worker_client_manager.d.ts +0 -4
  29. package/dest/testbench/worker_client_manager.d.ts.map +1 -1
  30. package/dest/testbench/worker_client_manager.js +3 -13
  31. package/dest/types/index.d.ts +2 -1
  32. package/dest/types/index.d.ts.map +1 -1
  33. package/dest/types/index.js +1 -0
  34. package/dest/util.d.ts +2 -7
  35. package/dest/util.d.ts.map +1 -1
  36. package/dest/util.js +12 -57
  37. package/package.json +10 -10
  38. package/src/bootstrap/bootstrap.ts +6 -5
  39. package/src/client/p2p_client.ts +24 -6
  40. package/src/config.ts +24 -32
  41. package/src/enr/generate-enr.ts +3 -2
  42. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +12 -7
  43. package/src/msg_validators/tx_validator/data_validator.ts +9 -7
  44. package/src/msg_validators/tx_validator/tx_proof_validator.ts +2 -2
  45. package/src/services/discv5/discV5_service.ts +36 -23
  46. package/src/services/libp2p/libp2p_service.ts +8 -9
  47. package/src/test-helpers/make-enrs.ts +3 -4
  48. package/src/test-helpers/make-test-p2p-clients.ts +2 -7
  49. package/src/test-helpers/reqresp-nodes.ts +6 -7
  50. package/src/testbench/worker_client_manager.ts +8 -17
  51. package/src/types/index.ts +1 -0
  52. package/src/util.ts +12 -72
@@ -18,9 +18,11 @@ export class DataTxValidator implements TxValidator<Tx> {
18
18
  ];
19
19
  if (callRequests.length !== tx.enqueuedPublicFunctionCalls.length) {
20
20
  this.#log.warn(
21
- `Rejecting tx ${Tx.getHash(tx)} because of mismatch number of execution requests for public calls. Expected ${
22
- callRequests.length
23
- }. Got ${tx.enqueuedPublicFunctionCalls.length}.`,
21
+ `Rejecting tx ${await Tx.getHash(
22
+ tx,
23
+ )} because of mismatch number of execution requests for public calls. Expected ${callRequests.length}. Got ${
24
+ tx.enqueuedPublicFunctionCalls.length
25
+ }.`,
24
26
  );
25
27
  return { result: 'invalid', reason: ['Wrong number of execution requests for public calls'] };
26
28
  }
@@ -66,7 +68,7 @@ export class DataTxValidator implements TxValidator<Tx> {
66
68
  const hashedContractClasslogs = await Promise.all(tx.contractClassLogs.map(l => l.hash()));
67
69
  if (contractClassLogsHashes.length !== hashedContractClasslogs.length) {
68
70
  this.#log.warn(
69
- `Rejecting tx ${Tx.getHash(tx)} because of mismatched number of contract class logs. Expected ${
71
+ `Rejecting tx ${await Tx.getHash(tx)} because of mismatched number of contract class logs. Expected ${
70
72
  contractClassLogsHashes.length
71
73
  }. Got ${hashedContractClasslogs.length}.`,
72
74
  );
@@ -78,14 +80,14 @@ export class DataTxValidator implements TxValidator<Tx> {
78
80
  if (hashedContractClasslogs.some(l => logHash.value.equals(l))) {
79
81
  const matchingLogIndex = hashedContractClasslogs.findIndex(l => logHash.value.equals(l));
80
82
  this.#log.warn(
81
- `Rejecting tx ${Tx.getHash(
83
+ `Rejecting tx ${await Tx.getHash(
82
84
  tx,
83
85
  )} because of mismatched contract class logs indices. Expected ${i} from the kernel's log hashes. Got ${matchingLogIndex} in the tx.`,
84
86
  );
85
87
  return { result: 'invalid', reason: ['Incorrectly sorted contract class logs'] };
86
88
  } else {
87
89
  this.#log.warn(
88
- `Rejecting tx ${Tx.getHash(tx)} because of mismatched contract class logs. Expected hash ${
90
+ `Rejecting tx ${await Tx.getHash(tx)} because of mismatched contract class logs. Expected hash ${
89
91
  logHash.value
90
92
  } from the kernels. Got ${hashedLog} in the tx.`,
91
93
  );
@@ -94,7 +96,7 @@ export class DataTxValidator implements TxValidator<Tx> {
94
96
  }
95
97
  if (logHash.logHash.length !== tx.contractClassLogs[i].getEmittedLength()) {
96
98
  this.#log.warn(
97
- `Rejecting tx ${Tx.getHash(tx)} because of mismatched contract class logs length. Expected ${
99
+ `Rejecting tx ${await Tx.getHash(tx)} because of mismatched contract class logs length. Expected ${
98
100
  logHash.logHash.length
99
101
  } from the kernel's log hashes. Got ${tx.contractClassLogs[i].getEmittedLength()} in the tx.`,
100
102
  );
@@ -9,10 +9,10 @@ export class TxProofValidator implements TxValidator<Tx> {
9
9
 
10
10
  async validateTx(tx: Tx): Promise<TxValidationResult> {
11
11
  if (!(await this.verifier.verifyProof(tx))) {
12
- this.#log.warn(`Rejecting tx ${Tx.getHash(tx)} for invalid proof`);
12
+ this.#log.warn(`Rejecting tx ${await Tx.getHash(tx)} for invalid proof`);
13
13
  return { result: 'invalid', reason: ['Invalid proof'] };
14
14
  }
15
- this.#log.trace(`Accepted ${Tx.getHash(tx)} with valid proof`);
15
+ this.#log.trace(`Accepted ${await Tx.getHash(tx)} with valid proof`);
16
16
  return { result: 'valid' };
17
17
  }
18
18
  }
@@ -3,7 +3,7 @@ import { sleep } from '@aztec/foundation/sleep';
3
3
  import { type ComponentsVersions, checkCompressedComponentVersion } from '@aztec/stdlib/versioning';
4
4
  import { OtelMetricsAdapter, type TelemetryClient, getTelemetryClient } from '@aztec/telemetry-client';
5
5
 
6
- import { Discv5, type Discv5EventEmitter } from '@chainsafe/discv5';
6
+ import { Discv5, type Discv5EventEmitter, type IDiscv5CreateOptions } from '@chainsafe/discv5';
7
7
  import { ENR, SignableENR } from '@chainsafe/enr';
8
8
  import type { PeerId } from '@libp2p/interface';
9
9
  import { type Multiaddr, multiaddr } from '@multiformats/multiaddr';
@@ -30,9 +30,6 @@ export class DiscV5Service extends EventEmitter implements PeerDiscoveryService
30
30
  /** Version identifiers. */
31
31
  private versions: ComponentsVersions;
32
32
 
33
- /** UDP listen addr */
34
- private listenMultiAddrUdp: Multiaddr;
35
-
36
33
  private currentState = PeerDiscoveryState.STOPPED;
37
34
 
38
35
  public readonly bootstrapNodes: string[] = [];
@@ -41,14 +38,21 @@ export class DiscV5Service extends EventEmitter implements PeerDiscoveryService
41
38
 
42
39
  private startTime = 0;
43
40
 
41
+ private handlers = {
42
+ onMultiaddrUpdated: this.onMultiaddrUpdated.bind(this),
43
+ onDiscovered: this.onDiscovered.bind(this),
44
+ onEnrAdded: this.onEnrAdded.bind(this),
45
+ };
46
+
44
47
  constructor(
45
48
  private peerId: PeerId,
46
49
  private config: P2PConfig,
47
50
  telemetry: TelemetryClient = getTelemetryClient(),
48
51
  private logger = createLogger('p2p:discv5_service'),
52
+ configOverrides: Partial<IDiscv5CreateOptions> = {},
49
53
  ) {
50
54
  super();
51
- const { tcpAnnounceAddress, udpAnnounceAddress, udpListenAddress, bootstrapNodes } = config;
55
+ const { p2pIp, p2pPort, bootstrapNodes } = config;
52
56
  this.bootstrapNodes = bootstrapNodes ?? [];
53
57
  this.bootstrapNodeEnrs = this.bootstrapNodes.map(x => ENR.decodeTxt(x));
54
58
  // create ENR from PeerId
@@ -56,31 +60,31 @@ export class DiscV5Service extends EventEmitter implements PeerDiscoveryService
56
60
  // Add aztec identification to ENR
57
61
  this.versions = setAztecEnrKey(this.enr, config);
58
62
 
59
- if (!tcpAnnounceAddress) {
60
- throw new Error('You need to provide at least a TCP announce address.');
61
- }
62
-
63
- const multiAddrTcp = multiaddr(`${convertToMultiaddr(tcpAnnounceAddress, 'tcp')}/p2p/${peerId.toString()}`);
64
- // if no udp announce address is provided, use the tcp announce address
65
- const multiAddrUdp = multiaddr(
66
- `${convertToMultiaddr(udpAnnounceAddress || tcpAnnounceAddress, 'udp')}/p2p/${peerId.toString()}`,
67
- );
63
+ const bindAddrs: any = {
64
+ ip4: multiaddr(convertToMultiaddr(config.listenAddress, p2pPort, 'udp')),
65
+ };
68
66
 
69
- this.listenMultiAddrUdp = multiaddr(convertToMultiaddr(udpListenAddress, 'udp'));
67
+ if (p2pIp) {
68
+ const multiAddrTcp = multiaddr(`${convertToMultiaddr(p2pIp!, p2pPort, 'tcp')}/p2p/${peerId.toString()}`);
69
+ // if no udp announce address is provided, use the tcp announce address
70
+ const multiAddrUdp = multiaddr(`${convertToMultiaddr(p2pIp!, p2pPort, 'udp')}/p2p/${peerId.toString()}`);
70
71
 
71
- // set location multiaddr in ENR record
72
- this.enr.setLocationMultiaddr(multiAddrUdp);
73
- this.enr.setLocationMultiaddr(multiAddrTcp);
72
+ // set location multiaddr in ENR record
73
+ this.enr.setLocationMultiaddr(multiAddrUdp);
74
+ this.enr.setLocationMultiaddr(multiAddrTcp);
75
+ }
74
76
 
75
77
  const metricsRegistry = new OtelMetricsAdapter(telemetry);
76
78
  this.discv5 = Discv5.create({
77
79
  enr: this.enr,
78
80
  peerId,
79
- bindAddrs: { ip4: this.listenMultiAddrUdp },
81
+ bindAddrs,
80
82
  config: {
81
83
  lookupTimeout: 2000,
82
84
  requestTimeout: 2000,
83
85
  allowUnverifiedSessions: true,
86
+ enrUpdate: !p2pIp ? true : false, // If no p2p IP is set, enrUpdate can automatically resolve it
87
+ ...configOverrides.config,
84
88
  },
85
89
  metricsRegistry,
86
90
  });
@@ -104,8 +108,16 @@ export class DiscV5Service extends EventEmitter implements PeerDiscoveryService
104
108
  }
105
109
  };
106
110
 
107
- this.discv5.on(Discv5Event.DISCOVERED, this.onDiscovered.bind(this));
108
- this.discv5.on(Discv5Event.ENR_ADDED, this.onEnrAdded.bind(this));
111
+ this.discv5.on(Discv5Event.DISCOVERED, this.handlers.onDiscovered);
112
+ this.discv5.on(Discv5Event.ENR_ADDED, this.handlers.onEnrAdded);
113
+ this.discv5.on(Discv5Event.MULTIADDR_UPDATED, this.handlers.onMultiaddrUpdated);
114
+ }
115
+
116
+ private onMultiaddrUpdated(m: Multiaddr) {
117
+ // We want to update our tcp port to match the udp port
118
+ const multiAddrTcp = multiaddr(convertToMultiaddr(m.nodeAddress().address, this.config.p2pPort, 'tcp'));
119
+ this.enr.setLocationMultiaddr(multiAddrTcp);
120
+ this.logger.info('Multiaddr updated', { multiaddr: multiaddr.toString() });
109
121
  }
110
122
 
111
123
  public async start(): Promise<void> {
@@ -187,8 +199,9 @@ export class DiscV5Service extends EventEmitter implements PeerDiscoveryService
187
199
  }
188
200
 
189
201
  public async stop(): Promise<void> {
190
- await this.discv5.off(Discv5Event.DISCOVERED, this.onDiscovered);
191
- await this.discv5.off(Discv5Event.ENR_ADDED, this.onEnrAdded);
202
+ await this.discv5.off(Discv5Event.DISCOVERED, this.handlers.onDiscovered);
203
+ await this.discv5.off(Discv5Event.ENR_ADDED, this.handlers.onEnrAdded);
204
+ await this.discv5.off(Discv5Event.MULTIADDR_UPDATED, this.handlers.onMultiaddrUpdated);
192
205
 
193
206
  await this.discv5.stop();
194
207
 
@@ -168,10 +168,8 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
168
168
  telemetry: TelemetryClient,
169
169
  logger = createLogger('p2p:libp2p_service'),
170
170
  ) {
171
- const { tcpListenAddress, tcpAnnounceAddress, maxPeerCount } = config;
172
- const bindAddrTcp = convertToMultiaddr(tcpListenAddress, 'tcp');
173
- // We know tcpAnnounceAddress cannot be null here because we set it or throw when setting up the service.
174
- const announceAddrTcp = convertToMultiaddr(tcpAnnounceAddress!, 'tcp');
171
+ const { p2pPort, maxPeerCount, listenAddress } = config;
172
+ const bindAddrTcp = convertToMultiaddr(listenAddress, p2pPort, 'tcp');
175
173
 
176
174
  const datastore = new AztecDatastore(store);
177
175
 
@@ -193,7 +191,7 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
193
191
  peerId,
194
192
  addresses: {
195
193
  listen: [bindAddrTcp],
196
- announce: [announceAddrTcp],
194
+ announce: [], // announce is handled by the peer discovery service
197
195
  },
198
196
  transports: [
199
197
  tcp({
@@ -299,11 +297,11 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
299
297
  }
300
298
 
301
299
  // Get listen & announce addresses for logging
302
- const { tcpListenAddress, tcpAnnounceAddress } = this.config;
303
- if (!tcpAnnounceAddress) {
300
+ const { p2pIp, p2pPort } = this.config;
301
+ if (!p2pIp) {
304
302
  throw new Error('Announce address not provided.');
305
303
  }
306
- const announceTcpMultiaddr = convertToMultiaddr(tcpAnnounceAddress, 'tcp');
304
+ const announceTcpMultiaddr = convertToMultiaddr(p2pIp, p2pPort, 'tcp');
307
305
 
308
306
  // Start job queue, peer discovery service and libp2p node
309
307
  this.jobQueue.start();
@@ -349,7 +347,8 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
349
347
  };
350
348
  await this.reqresp.start(requestResponseHandlers, reqrespSubProtocolValidators);
351
349
  this.logger.info(`Started P2P service`, {
352
- listen: tcpListenAddress,
350
+ listen: this.config.listenAddress,
351
+ port: this.config.p2pPort,
353
352
  announce: announceTcpMultiaddr,
354
353
  peerId: this.node.peerId.toString(),
355
354
  });
@@ -30,10 +30,9 @@ export async function makeEnr(p2pPrivateKey: string, port: number, config: Chain
30
30
  const peerId = await createLibP2PPeerIdFromPrivateKey(p2pPrivateKey);
31
31
  const enr = SignableENR.createFromPeerId(peerId);
32
32
 
33
- const udpAnnounceAddress = `127.0.0.1:${port}`;
34
- const tcpAnnounceAddress = `127.0.0.1:${port}`;
35
- const udpPublicAddr = multiaddr(convertToMultiaddr(udpAnnounceAddress, 'udp'));
36
- const tcpPublicAddr = multiaddr(convertToMultiaddr(tcpAnnounceAddress, 'tcp'));
33
+ const p2pIp = `127.0.0.1`;
34
+ const udpPublicAddr = multiaddr(convertToMultiaddr(p2pIp, port, 'udp'));
35
+ const tcpPublicAddr = multiaddr(convertToMultiaddr(p2pIp, port, 'tcp'));
37
36
 
38
37
  // ENRS must include the network and a discoverable address (udp for discv5)
39
38
  setAztecEnrKey(enr, config);
@@ -50,19 +50,14 @@ export async function makeTestP2PClient(
50
50
  logger = createLogger('p2p-test-client'),
51
51
  }: MakeTestP2PClientOptions,
52
52
  ) {
53
- const addr = `127.0.0.1:${port}`;
54
- const listenAddr = `0.0.0.0:${port}`;
55
-
56
53
  // Filter nodes so that we only dial active peers
57
54
 
58
55
  const config: P2PConfig & DataStoreConfig = {
59
56
  ...p2pBaseConfig,
60
57
  p2pEnabled: true,
61
58
  peerIdPrivateKey,
62
- tcpListenAddress: listenAddr, // run on port 0
63
- udpListenAddress: listenAddr,
64
- tcpAnnounceAddress: addr,
65
- udpAnnounceAddress: addr,
59
+ p2pIp: `127.0.0.1`,
60
+ p2pPort: port,
66
61
  bootstrapNodes: peers,
67
62
  peerCheckIntervalMS: 1000,
68
63
  maxPeerCount: 10,
@@ -109,10 +109,8 @@ export async function createTestLibP2PService<T extends P2PClientType>(
109
109
  ) {
110
110
  peerId = peerId ?? (await createSecp256k1PeerId());
111
111
  const config = {
112
- tcpAnnounceAddress: `127.0.0.1:${port}`,
113
- udpAnnounceAddress: `127.0.0.1:${port}`,
114
- tcpListenAddress: `0.0.0.0:${port}`,
115
- udpListenAddress: `0.0.0.0:${port}`,
112
+ p2pIp: `127.0.0.1`,
113
+ p2pPort: port,
116
114
  bootstrapNodes: boostrapAddrs,
117
115
  peerCheckIntervalMS: 1000,
118
116
  maxPeerCount: 5,
@@ -235,12 +233,13 @@ export class AlwaysFalseCircuitVerifier implements ClientProtocolCircuitVerifier
235
233
  export function createBootstrapNodeConfig(privateKey: string, port: number, chainConfig: ChainConfig): BootnodeConfig {
236
234
  return {
237
235
  l1ChainId: chainConfig.l1ChainId,
238
- udpListenAddress: `0.0.0.0:${port}`,
239
- udpAnnounceAddress: `127.0.0.1:${port}`,
236
+ p2pIp: '127.0.0.1',
237
+ p2pPort: port,
240
238
  peerIdPrivateKey: privateKey,
241
239
  dataDirectory: undefined,
242
240
  dataStoreMapSizeKB: 0,
243
241
  bootstrapNodes: [],
242
+ listenAddress: '0.0.0.0',
244
243
  };
245
244
  }
246
245
 
@@ -263,7 +262,7 @@ export function createBootstrapNodeFromPrivateKey(
263
262
  export async function getBootstrapNodeEnr(privateKey: string, port: number) {
264
263
  const peerId = await createLibP2PPeerIdFromPrivateKey(privateKey);
265
264
  const enr = SignableENR.createFromPeerId(peerId);
266
- const listenAddrUdp = multiaddr(convertToMultiaddr(`127.0.0.1:${port}`, 'udp'));
265
+ const listenAddrUdp = multiaddr(convertToMultiaddr('127.0.0.1', port, 'udp'));
267
266
  enr.setLocationMultiaddr(listenAddrUdp);
268
267
 
269
268
  return enr;
@@ -44,30 +44,21 @@ class WorkerClientManager {
44
44
  });
45
45
  }
46
46
 
47
- /**
48
- * Creates address strings from a port
49
- */
50
- private getAddresses(port: number) {
51
- return {
52
- addr: `127.0.0.1:${port}`,
53
- listenAddr: `0.0.0.0:${port}`,
54
- };
55
- }
56
-
57
47
  /**
58
48
  * Creates a client configuration object
59
49
  */
60
- private createClientConfig(clientIndex: number, port: number, otherNodes: string[]) {
61
- const { addr, listenAddr } = this.getAddresses(port);
62
-
50
+ private createClientConfig(
51
+ clientIndex: number,
52
+ port: number,
53
+ otherNodes: string[],
54
+ ): P2PConfig & Partial<ChainConfig> {
63
55
  return {
64
56
  ...getP2PDefaultConfig(),
65
57
  p2pEnabled: true,
66
58
  peerIdPrivateKey: this.peerIdPrivateKeys[clientIndex],
67
- tcpListenAddress: listenAddr,
68
- udpListenAddress: listenAddr,
69
- tcpAnnounceAddress: addr,
70
- udpAnnounceAddress: addr,
59
+ listenAddress: '127.0.0.1',
60
+ p2pIp: '127.0.0.1',
61
+ p2pPort: port,
71
62
  bootstrapNodes: [...otherNodes],
72
63
  ...this.p2pConfig,
73
64
  };
@@ -17,6 +17,7 @@ export enum PeerEvent {
17
17
  export enum Discv5Event {
18
18
  DISCOVERED = 'discovered',
19
19
  ENR_ADDED = 'enrAdded',
20
+ MULTIADDR_UPDATED = 'multiaddrUpdated',
20
21
  }
21
22
 
22
23
  /**
package/src/util.ts CHANGED
@@ -28,41 +28,13 @@ export interface PubSubLibp2p extends Libp2p {
28
28
  * @param address - The address string to convert. Has to be in the format <addr>:<port>.
29
29
  * @param protocol - The protocol to use in the multiaddr string.
30
30
  * @returns A multiaddr compliant string. */
31
- export function convertToMultiaddr(address: string, protocol: 'tcp' | 'udp'): string {
32
- const [addr, port] = splitAddressPort(address, false);
33
-
34
- const multiaddrPrefix = addressToMultiAddressType(addr);
31
+ export function convertToMultiaddr(address: string, port: number, protocol: 'tcp' | 'udp'): string {
32
+ const multiaddrPrefix = addressToMultiAddressType(address);
35
33
  if (multiaddrPrefix === 'dns') {
36
34
  throw new Error('Invalid address format. Expected an IPv4 or IPv6 address.');
37
35
  }
38
36
 
39
- return `/${multiaddrPrefix}/${addr}/${protocol}/${port}`;
40
- }
41
-
42
- /**
43
- * Splits an <address>:<port> string into its components.
44
- * @returns The ip6 or ip4 address & port separately
45
- */
46
- export function splitAddressPort(address: string, allowEmptyAddress: boolean): [string, string] {
47
- let addr: string;
48
- let port: string;
49
-
50
- if (address.startsWith('[')) {
51
- // IPv6 address enclosed in square brackets
52
- const match = address.match(/^\[([^\]]+)\]:(\d+)$/);
53
- if (!match) {
54
- throw new Error(`Invalid IPv6 address format:${address}. Expected format: [<addr>]:<port>`);
55
- }
56
- [, addr, port] = match;
57
- } else {
58
- // IPv4 address
59
- [addr, port] = address.split(':');
60
- if ((!addr && !allowEmptyAddress) || !port) {
61
- throw new Error(`Invalid address format: ${address}. Expected format: <addr>:<port>`);
62
- }
63
- }
64
-
65
- return [addr, port];
37
+ return `/${multiaddrPrefix}/${address}/${protocol}/${port}`;
66
38
  }
67
39
 
68
40
  /**
@@ -74,13 +46,12 @@ export async function getPublicIp(): Promise<string> {
74
46
  return text.trim();
75
47
  }
76
48
 
77
- export async function resolveAddressIfNecessary(address: string): Promise<string> {
78
- const [addr, port] = splitAddressPort(address, false);
79
- const multiaddrPrefix = addressToMultiAddressType(addr);
49
+ export async function resolveAddressIfNecessary(address: string, port: string): Promise<string> {
50
+ const multiaddrPrefix = addressToMultiAddressType(address);
80
51
  if (multiaddrPrefix === 'dns') {
81
- const resolvedAddresses = await resolve(addr);
52
+ const resolvedAddresses = await resolve(address);
82
53
  if (resolvedAddresses.length === 0) {
83
- throw new Error(`Could not resolve address: ${addr}`);
54
+ throw new Error(`Could not resolve address: ${address}`);
84
55
  }
85
56
  return `${resolvedAddresses[0]}:${port}`;
86
57
  } else {
@@ -104,47 +75,16 @@ export async function configureP2PClientAddresses(
104
75
  _config: P2PConfig & DataStoreConfig,
105
76
  ): Promise<P2PConfig & DataStoreConfig> {
106
77
  const config = { ..._config };
107
- const {
108
- tcpAnnounceAddress: configTcpAnnounceAddress,
109
- udpAnnounceAddress: configUdpAnnounceAddress,
110
- queryForIp,
111
- } = config;
112
-
113
- config.tcpAnnounceAddress = configTcpAnnounceAddress
114
- ? await resolveAddressIfNecessary(configTcpAnnounceAddress)
115
- : undefined;
116
- config.udpAnnounceAddress = configUdpAnnounceAddress
117
- ? await resolveAddressIfNecessary(configUdpAnnounceAddress)
118
- : undefined;
119
-
120
- // create variable for re-use if needed
121
- let publicIp;
78
+ const { p2pIp, queryForIp } = config;
122
79
 
123
80
  // check if no announce IP was provided
124
- const splitTcpAnnounceAddress = splitAddressPort(configTcpAnnounceAddress || '', true);
125
- if (splitTcpAnnounceAddress.length == 2 && splitTcpAnnounceAddress[0] === '') {
81
+ if (!p2pIp) {
126
82
  if (queryForIp) {
127
- publicIp = await getPublicIp();
128
- const tcpAnnounceAddress = `${publicIp}:${splitTcpAnnounceAddress[1]}`;
129
- config.tcpAnnounceAddress = tcpAnnounceAddress;
130
- } else {
131
- throw new Error(
132
- `Invalid announceTcpAddress provided: ${configTcpAnnounceAddress}. Expected format: <addr>:<port>`,
133
- );
134
- }
135
- }
136
-
137
- const splitUdpAnnounceAddress = splitAddressPort(configUdpAnnounceAddress || '', true);
138
- if (splitUdpAnnounceAddress.length == 2 && splitUdpAnnounceAddress[0] === '') {
139
- // If announceUdpAddress is not provided, use announceTcpAddress
140
- if (!queryForIp && config.tcpAnnounceAddress) {
141
- config.udpAnnounceAddress = config.tcpAnnounceAddress;
142
- } else if (queryForIp) {
143
- const udpPublicIp = publicIp || (await getPublicIp());
144
- const udpAnnounceAddress = `${udpPublicIp}:${splitUdpAnnounceAddress[1]}`;
145
- config.udpAnnounceAddress = udpAnnounceAddress;
83
+ const publicIp = await getPublicIp();
84
+ config.p2pIp = publicIp;
146
85
  }
147
86
  }
87
+ // TODO(md): guard against setting a local ip address as the announce ip
148
88
 
149
89
  return config;
150
90
  }