libp2p 0.35.7 → 0.35.8-bf1fc32

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 (89) hide show
  1. package/dist/index.min.js +55 -0
  2. package/dist/src/circuit/auto-relay.d.ts +8 -10
  3. package/dist/src/circuit/auto-relay.d.ts.map +1 -1
  4. package/dist/src/connection-manager/auto-dialler.d.ts +1 -1
  5. package/dist/src/connection-manager/auto-dialler.d.ts.map +1 -1
  6. package/dist/src/connection-manager/index.d.ts +1 -2
  7. package/dist/src/connection-manager/index.d.ts.map +1 -1
  8. package/dist/src/content-routing/utils.d.ts +3 -3
  9. package/dist/src/content-routing/utils.d.ts.map +1 -1
  10. package/dist/src/dht/dht-peer-routing.d.ts.map +1 -1
  11. package/dist/src/dialer/dial-request.d.ts.map +1 -1
  12. package/dist/src/dialer/index.d.ts +5 -5
  13. package/dist/src/dialer/index.d.ts.map +1 -1
  14. package/dist/src/identify/index.d.ts +4 -4
  15. package/dist/src/identify/index.d.ts.map +1 -1
  16. package/dist/src/index.d.ts +6 -6
  17. package/dist/src/index.d.ts.map +1 -1
  18. package/dist/src/metrics/index.d.ts +9 -4
  19. package/dist/src/metrics/index.d.ts.map +1 -1
  20. package/dist/src/metrics/tracked-map.d.ts +6 -1
  21. package/dist/src/metrics/tracked-map.d.ts.map +1 -1
  22. package/dist/src/peer-routing.d.ts +1 -1
  23. package/dist/src/peer-routing.d.ts.map +1 -1
  24. package/dist/src/peer-store/address-book.d.ts +28 -84
  25. package/dist/src/peer-store/address-book.d.ts.map +1 -1
  26. package/dist/src/peer-store/index.d.ts +25 -94
  27. package/dist/src/peer-store/index.d.ts.map +1 -1
  28. package/dist/src/peer-store/key-book.d.ts +31 -15
  29. package/dist/src/peer-store/key-book.d.ts.map +1 -1
  30. package/dist/src/peer-store/metadata-book.d.ts +33 -29
  31. package/dist/src/peer-store/metadata-book.d.ts.map +1 -1
  32. package/dist/src/peer-store/pb/peer.d.ts +222 -0
  33. package/dist/src/peer-store/proto-book.d.ts +27 -28
  34. package/dist/src/peer-store/proto-book.d.ts.map +1 -1
  35. package/dist/src/peer-store/store.d.ts +73 -0
  36. package/dist/src/peer-store/store.d.ts.map +1 -0
  37. package/dist/src/peer-store/types.d.ts +202 -0
  38. package/dist/src/peer-store/types.d.ts.map +1 -0
  39. package/dist/src/ping/index.d.ts.map +1 -1
  40. package/dist/src/record/peer-record/index.d.ts +2 -2
  41. package/dist/src/record/peer-record/index.d.ts.map +1 -1
  42. package/dist/src/registrar.d.ts +5 -5
  43. package/dist/src/registrar.d.ts.map +1 -1
  44. package/dist/src/upgrader.d.ts.map +1 -1
  45. package/package.json +18 -25
  46. package/src/circuit/auto-relay.js +19 -19
  47. package/src/connection-manager/auto-dialler.js +9 -4
  48. package/src/connection-manager/index.js +39 -22
  49. package/src/content-routing/utils.js +4 -4
  50. package/src/dht/dht-peer-routing.js +2 -6
  51. package/src/dialer/dial-request.js +4 -1
  52. package/src/dialer/index.js +22 -10
  53. package/src/identify/index.js +28 -23
  54. package/src/index.js +33 -27
  55. package/src/metrics/index.js +15 -8
  56. package/src/metrics/tracked-map.js +45 -13
  57. package/src/peer-routing.js +4 -1
  58. package/src/peer-store/address-book.js +242 -227
  59. package/src/peer-store/index.js +77 -110
  60. package/src/peer-store/key-book.js +99 -54
  61. package/src/peer-store/metadata-book.js +171 -101
  62. package/src/peer-store/pb/peer.d.ts +222 -0
  63. package/src/peer-store/pb/peer.js +643 -0
  64. package/src/peer-store/pb/peer.proto +31 -0
  65. package/src/peer-store/proto-book.js +171 -105
  66. package/src/peer-store/store.js +250 -0
  67. package/src/peer-store/types.ts +245 -0
  68. package/src/ping/index.js +6 -0
  69. package/src/record/peer-record/index.js +1 -1
  70. package/src/record/utils.js +1 -1
  71. package/src/registrar.js +4 -4
  72. package/src/upgrader.js +3 -1
  73. package/dist/src/peer-store/book.d.ts +0 -81
  74. package/dist/src/peer-store/book.d.ts.map +0 -1
  75. package/dist/src/peer-store/persistent/consts.d.ts +0 -6
  76. package/dist/src/peer-store/persistent/consts.d.ts.map +0 -1
  77. package/dist/src/peer-store/persistent/index.d.ts +0 -129
  78. package/dist/src/peer-store/persistent/index.d.ts.map +0 -1
  79. package/dist/src/peer-store/persistent/pb/address-book.d.ts +0 -198
  80. package/dist/src/peer-store/persistent/pb/proto-book.d.ts +0 -59
  81. package/src/peer-store/book.js +0 -124
  82. package/src/peer-store/persistent/consts.js +0 -15
  83. package/src/peer-store/persistent/index.js +0 -408
  84. package/src/peer-store/persistent/pb/address-book.d.ts +0 -198
  85. package/src/peer-store/persistent/pb/address-book.js +0 -522
  86. package/src/peer-store/persistent/pb/address-book.proto +0 -27
  87. package/src/peer-store/persistent/pb/proto-book.d.ts +0 -59
  88. package/src/peer-store/persistent/pb/proto-book.js +0 -157
  89. package/src/peer-store/persistent/pb/proto-book.proto +0 -5
@@ -1,74 +1,36 @@
1
1
  'use strict'
2
2
 
3
3
  const debug = require('debug')
4
- const log = Object.assign(debug('libp2p:peer-store:address-book'), {
5
- error: debug('libp2p:peer-store:address-book:err')
6
- })
7
4
  const errcode = require('err-code')
8
-
9
5
  const { Multiaddr } = require('multiaddr')
10
6
  const PeerId = require('peer-id')
11
-
12
- const Book = require('./book')
7
+ const { codes } = require('../errors')
13
8
  const PeerRecord = require('../record/peer-record')
14
-
15
- const {
16
- codes: { ERR_INVALID_PARAMETERS }
17
- } = require('../errors')
18
9
  const Envelope = require('../record/envelope')
19
10
 
20
11
  /**
21
- * @typedef {import('./')} PeerStore
12
+ * @typedef {import('./types').PeerStore} PeerStore
13
+ * @typedef {import('./types').Address} Address
14
+ * @typedef {import('./types').AddressBook} AddressBook
22
15
  */
23
16
 
24
- /**
25
- * @typedef {Object} Address
26
- * @property {Multiaddr} multiaddr peer multiaddr.
27
- * @property {boolean} isCertified obtained from a signed peer record.
28
- *
29
- * @typedef {Object} CertifiedRecord
30
- * @property {Uint8Array} raw raw envelope.
31
- * @property {number} seqNumber seq counter.
32
- *
33
- * @typedef {Object} Entry
34
- * @property {Address[]} addresses peer Addresses.
35
- * @property {CertifiedRecord} record certified peer record.
36
- */
17
+ const log = Object.assign(debug('libp2p:peer-store:address-book'), {
18
+ error: debug('libp2p:peer-store:address-book:err')
19
+ })
20
+
21
+ const EVENT_NAME = 'change:multiaddrs'
37
22
 
38
23
  /**
39
- * @extends {Book}
24
+ * @implements {AddressBook}
40
25
  */
41
- class AddressBook extends Book {
26
+ class PeerStoreAddressBook {
42
27
  /**
43
- * The AddressBook is responsible for keeping the known multiaddrs of a peer.
44
- *
45
- * @class
46
- * @param {PeerStore} peerStore
28
+ * @param {PeerStore["emit"]} emit
29
+ * @param {import('./types').Store} store
47
30
  */
48
- constructor (peerStore) {
49
- /**
50
- * PeerStore Event emitter, used by the AddressBook to emit:
51
- * "peer" - emitted when a peer is discovered by the node.
52
- * "change:multiaddrs" - emitted when the known multiaddrs of a peer change.
53
- */
54
- super({
55
- peerStore,
56
- eventName: 'change:multiaddrs',
57
- eventProperty: 'multiaddrs',
58
- eventTransformer: (data) => {
59
- if (!data.addresses) {
60
- return []
61
- }
62
- return data.addresses.map((/** @type {Address} */ address) => address.multiaddr)
63
- }
64
- })
65
-
66
- /**
67
- * Map known peers to their known Address Entries.
68
- *
69
- * @type {Map<string, Entry>}
70
- */
71
- this.data = new Map()
31
+ constructor (emit, store) {
32
+ this._emit = emit
33
+ this._store = store
72
34
  }
73
35
 
74
36
  /**
@@ -77,69 +39,90 @@ class AddressBook extends Book {
77
39
  * into the AddressBook.
78
40
  *
79
41
  * @param {Envelope} envelope
80
- * @returns {boolean}
81
42
  */
82
- consumePeerRecord (envelope) {
83
- let peerRecord
43
+ async consumePeerRecord (envelope) {
44
+ log('consumePeerRecord await write lock')
45
+ const release = await this._store.lock.writeLock()
46
+ log('consumePeerRecord got write lock')
47
+
48
+ let peerId
49
+ let updatedPeer
50
+
84
51
  try {
85
- peerRecord = PeerRecord.createFromProtobuf(envelope.payload)
86
- } catch (/** @type {any} */ err) {
87
- log.error('invalid peer record received')
88
- return false
89
- }
52
+ let peerRecord
53
+ try {
54
+ peerRecord = PeerRecord.createFromProtobuf(envelope.payload)
55
+ } catch (/** @type {any} */ err) {
56
+ log.error('invalid peer record received')
57
+ return false
58
+ }
90
59
 
91
- // Verify peerId
92
- if (!peerRecord.peerId.equals(envelope.peerId)) {
93
- log('signing key does not match PeerId in the PeerRecord')
94
- return false
95
- }
60
+ peerId = peerRecord.peerId
61
+ const multiaddrs = peerRecord.multiaddrs
96
62
 
97
- // ensure the record has multiaddrs
98
- if (!peerRecord.multiaddrs || !peerRecord.multiaddrs.length) {
99
- return false
100
- }
63
+ // Verify peerId
64
+ if (!peerId.equals(envelope.peerId)) {
65
+ log('signing key does not match PeerId in the PeerRecord')
66
+ return false
67
+ }
101
68
 
102
- const peerId = peerRecord.peerId
103
- const id = peerId.toB58String()
104
- const entry = this.data.get(id) || { record: undefined }
105
- const storedRecord = entry.record
69
+ // ensure the record has multiaddrs
70
+ if (!multiaddrs || !multiaddrs.length) {
71
+ return false
72
+ }
106
73
 
107
- // ensure seq is greater than, or equal to, the last received
108
- if (storedRecord && storedRecord.seqNumber >= peerRecord.seqNumber) {
109
- return false
110
- }
74
+ if (await this._store.has(peerId)) {
75
+ const peer = await this._store.load(peerId)
111
76
 
112
- const addresses = this._toAddresses(peerRecord.multiaddrs, true)
77
+ if (peer.peerRecordEnvelope) {
78
+ const storedEnvelope = await Envelope.createFromProtobuf(peer.peerRecordEnvelope)
79
+ const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload)
113
80
 
114
- // Replace unsigned addresses by the new ones from the record
115
- // TODO: Once we have ttls for the addresses, we should merge these in.
116
- this._setData(peerId, {
117
- addresses,
118
- record: {
119
- raw: envelope.marshal(),
120
- seqNumber: peerRecord.seqNumber
81
+ // ensure seq is greater than, or equal to, the last received
82
+ if (storedRecord.seqNumber >= peerRecord.seqNumber) {
83
+ return false
84
+ }
85
+ }
121
86
  }
122
- })
123
- log(`stored provided peer record for ${id}`)
87
+
88
+ // Replace unsigned addresses by the new ones from the record
89
+ // TODO: Once we have ttls for the addresses, we should merge these in
90
+ updatedPeer = await this._store.patchOrCreate(peerId, {
91
+ addresses: convertMultiaddrsToAddresses(multiaddrs, true),
92
+ peerRecordEnvelope: envelope.marshal()
93
+ })
94
+
95
+ log(`stored provided peer record for ${peerRecord.peerId.toB58String()}`)
96
+ } finally {
97
+ log('consumePeerRecord release write lock')
98
+ release()
99
+ }
100
+
101
+ this._emit(EVENT_NAME, { peerId, multiaddrs: updatedPeer.addresses.map(({ multiaddr }) => multiaddr) })
124
102
 
125
103
  return true
126
104
  }
127
105
 
128
106
  /**
129
- * Get the raw Envelope for a peer. Returns
130
- * undefined if no Envelope is found.
131
- *
132
107
  * @param {PeerId} peerId
133
- * @returns {Uint8Array|undefined}
134
108
  */
135
- getRawEnvelope (peerId) {
136
- const entry = this.data.get(peerId.toB58String())
109
+ async getRawEnvelope (peerId) {
110
+ log('getRawEnvelope await read lock')
111
+ const release = await this._store.lock.readLock()
112
+ log('getRawEnvelope got read lock')
137
113
 
138
- if (!entry || !entry.record || !entry.record.raw) {
139
- return undefined
140
- }
114
+ try {
115
+ const peer = await this._store.load(peerId)
141
116
 
142
- return entry.record.raw
117
+ return peer.peerRecordEnvelope
118
+ } catch (/** @type {any} */ err) {
119
+ if (err.code !== codes.ERR_NOT_FOUND) {
120
+ throw err
121
+ }
122
+ } finally {
123
+ log('getRawEnvelope release read lock')
124
+ release()
125
+ }
143
126
  }
144
127
 
145
128
  /**
@@ -147,10 +130,9 @@ class AddressBook extends Book {
147
130
  * Returns undefined if no record exists.
148
131
  *
149
132
  * @param {PeerId} peerId
150
- * @returns {Promise<Envelope|void>|undefined}
151
133
  */
152
- getPeerRecord (peerId) {
153
- const raw = this.getRawEnvelope(peerId)
134
+ async getPeerRecord (peerId) {
135
+ const raw = await this.getRawEnvelope(peerId)
154
136
 
155
137
  if (!raw) {
156
138
  return undefined
@@ -160,186 +142,189 @@ class AddressBook extends Book {
160
142
  }
161
143
 
162
144
  /**
163
- * Set known multiaddrs of a provided peer.
164
- * This will replace previously stored multiaddrs, if available.
165
- * Replacing stored multiaddrs might result in losing obtained certified addresses.
166
- * If you are not sure, it's recommended to use `add` instead.
167
- *
168
- * @override
169
145
  * @param {PeerId} peerId
170
- * @param {Multiaddr[]} multiaddrs
171
- * @returns {AddressBook}
172
146
  */
173
- set (peerId, multiaddrs) {
147
+ async get (peerId) {
174
148
  if (!PeerId.isPeerId(peerId)) {
175
149
  log.error('peerId must be an instance of peer-id to store data')
176
- throw errcode(new Error('peerId must be an instance of peer-id'), ERR_INVALID_PARAMETERS)
177
- }
178
-
179
- const addresses = this._toAddresses(multiaddrs)
180
-
181
- // Not replace multiaddrs
182
- if (!addresses.length) {
183
- return this
150
+ throw errcode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)
184
151
  }
185
152
 
186
- const id = peerId.toB58String()
187
- const entry = this.data.get(id)
153
+ log('get wait for read lock')
154
+ const release = await this._store.lock.readLock()
155
+ log('get got read lock')
188
156
 
189
- // Already knows the peer
190
- if (entry && entry.addresses && entry.addresses.length === addresses.length) {
191
- const intersection = entry.addresses.filter((addr) => addresses.some((newAddr) => addr.multiaddr.equals(newAddr.multiaddr)))
157
+ try {
158
+ const peer = await this._store.load(peerId)
192
159
 
193
- // Are new addresses equal to the old ones?
194
- // If yes, no changes needed!
195
- if (intersection.length === entry.addresses.length) {
196
- log(`the addresses provided to store are equal to the already stored for ${id}`)
197
- return this
160
+ return peer.addresses
161
+ } catch (/** @type {any} */ err) {
162
+ if (err.code !== codes.ERR_NOT_FOUND) {
163
+ throw err
198
164
  }
165
+ } finally {
166
+ log('get release read lock')
167
+ release()
199
168
  }
200
169
 
201
- this._setData(peerId, {
202
- addresses,
203
- record: entry && entry.record
204
- })
205
- log(`stored provided multiaddrs for ${id}`)
206
-
207
- // Notify the existance of a new peer
208
- if (!entry) {
209
- this._ps.emit('peer', peerId)
210
- }
211
-
212
- return this
170
+ return []
213
171
  }
214
172
 
215
173
  /**
216
- * Add known addresses of a provided peer.
217
- * If the peer is not known, it is set with the given addresses.
218
- *
219
174
  * @param {PeerId} peerId
220
175
  * @param {Multiaddr[]} multiaddrs
221
- * @returns {AddressBook}
222
176
  */
223
- add (peerId, multiaddrs) {
177
+ async set (peerId, multiaddrs) {
224
178
  if (!PeerId.isPeerId(peerId)) {
225
179
  log.error('peerId must be an instance of peer-id to store data')
226
- throw errcode(new Error('peerId must be an instance of peer-id'), ERR_INVALID_PARAMETERS)
180
+ throw errcode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)
227
181
  }
228
182
 
229
- const addresses = this._toAddresses(multiaddrs)
230
- const id = peerId.toB58String()
183
+ log('set await write lock')
184
+ const release = await this._store.lock.writeLock()
185
+ log('set got write lock')
231
186
 
232
- // No addresses to be added
233
- if (!addresses.length) {
234
- return this
235
- }
236
-
237
- const entry = this.data.get(id)
187
+ let hasPeer = false
188
+ let updatedPeer
238
189
 
239
- if (entry && entry.addresses) {
240
- // Add recorded uniquely to the new array (Union)
241
- entry.addresses.forEach((addr) => {
242
- if (!addresses.find(r => r.multiaddr.equals(addr.multiaddr))) {
243
- addresses.push(addr)
244
- }
245
- })
190
+ try {
191
+ const addresses = convertMultiaddrsToAddresses(multiaddrs)
246
192
 
247
- // If the recorded length is equal to the new after the unique union
248
- // The content is the same, no need to update.
249
- if (entry.addresses.length === addresses.length) {
250
- log(`the addresses provided to store are already stored for ${id}`)
251
- return this
193
+ // No valid addresses found
194
+ if (!addresses.length) {
195
+ return
252
196
  }
253
- }
254
197
 
255
- this._setData(peerId, {
256
- addresses,
257
- record: entry && entry.record
258
- })
198
+ try {
199
+ const peer = await this._store.load(peerId)
200
+ hasPeer = true
201
+
202
+ if (new Set([
203
+ ...addresses.map(({ multiaddr }) => multiaddr.toString()),
204
+ ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())
205
+ ]).size === peer.addresses.length && addresses.length === peer.addresses.length) {
206
+ // not changing anything, no need to update
207
+ return
208
+ }
209
+ } catch (/** @type {any} */ err) {
210
+ if (err.code !== codes.ERR_NOT_FOUND) {
211
+ throw err
212
+ }
213
+ }
259
214
 
260
- log(`added provided multiaddrs for ${id}`)
215
+ updatedPeer = await this._store.patchOrCreate(peerId, { addresses })
261
216
 
262
- // Notify the existance of a new peer
263
- if (!(entry && entry.addresses)) {
264
- this._ps.emit('peer', peerId)
217
+ log(`set multiaddrs for ${peerId.toB58String()}`)
218
+ } finally {
219
+ log('set release write lock')
220
+ release()
265
221
  }
266
222
 
267
- return this
223
+ this._emit(EVENT_NAME, { peerId, multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr) })
224
+
225
+ // Notify the existence of a new peer
226
+ if (!hasPeer) {
227
+ this._emit('peer', peerId)
228
+ }
268
229
  }
269
230
 
270
231
  /**
271
- * Get the known data of a provided peer.
272
- *
273
- * @override
274
232
  * @param {PeerId} peerId
275
- * @returns {Address[]|undefined}
233
+ * @param {Multiaddr[]} multiaddrs
276
234
  */
277
- get (peerId) {
235
+ async add (peerId, multiaddrs) {
278
236
  if (!PeerId.isPeerId(peerId)) {
279
- throw errcode(new Error('peerId must be an instance of peer-id'), ERR_INVALID_PARAMETERS)
237
+ log.error('peerId must be an instance of peer-id to store data')
238
+ throw errcode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)
280
239
  }
281
240
 
282
- const entry = this.data.get(peerId.toB58String())
241
+ log('add await write lock')
242
+ const release = await this._store.lock.writeLock()
243
+ log('add got write lock')
283
244
 
284
- return entry && entry.addresses ? [...entry.addresses] : undefined
285
- }
245
+ let hasPeer
246
+ let updatedPeer
286
247
 
287
- /**
288
- * Transforms received multiaddrs into Address.
289
- *
290
- * @private
291
- * @param {Multiaddr[]} multiaddrs
292
- * @param {boolean} [isCertified]
293
- * @returns {Address[]}
294
- */
295
- _toAddresses (multiaddrs, isCertified = false) {
296
- if (!multiaddrs) {
297
- log.error('multiaddrs must be provided to store data')
298
- throw errcode(new Error('multiaddrs must be provided'), ERR_INVALID_PARAMETERS)
299
- }
248
+ try {
249
+ const addresses = convertMultiaddrsToAddresses(multiaddrs)
300
250
 
301
- // create Address for each address
302
- /** @type {Address[]} */
303
- const addresses = []
304
- multiaddrs.forEach((addr) => {
305
- if (!Multiaddr.isMultiaddr(addr)) {
306
- log.error(`multiaddr ${addr} must be an instance of multiaddr`)
307
- throw errcode(new Error(`multiaddr ${addr} must be an instance of multiaddr`), ERR_INVALID_PARAMETERS)
251
+ // No valid addresses found
252
+ if (!addresses.length) {
253
+ return
308
254
  }
309
255
 
310
- // Guarantee no replicates
311
- if (!addresses.find((a) => a.multiaddr.equals(addr))) {
312
- addresses.push({
313
- multiaddr: addr,
314
- isCertified
315
- })
256
+ try {
257
+ const peer = await this._store.load(peerId)
258
+ hasPeer = true
259
+
260
+ if (new Set([
261
+ ...addresses.map(({ multiaddr }) => multiaddr.toString()),
262
+ ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())
263
+ ]).size === peer.addresses.length) {
264
+ return
265
+ }
266
+ } catch (/** @type {any} */ err) {
267
+ if (err.code !== codes.ERR_NOT_FOUND) {
268
+ throw err
269
+ }
316
270
  }
317
- })
318
271
 
319
- return addresses
272
+ updatedPeer = await this._store.mergeOrCreate(peerId, { addresses })
273
+
274
+ log(`added multiaddrs for ${peerId}`)
275
+ } finally {
276
+ log('set release write lock')
277
+ release()
278
+ }
279
+
280
+ this._emit(EVENT_NAME, { peerId, multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr) })
281
+
282
+ // Notify the existence of a new peer
283
+ if (!hasPeer) {
284
+ this._emit('peer', peerId)
285
+ }
320
286
  }
321
287
 
322
288
  /**
323
- * Get the known multiaddrs for a given peer. All returned multiaddrs
324
- * will include the encapsulated `PeerId` of the peer.
325
- * Returns `undefined` if there are no known multiaddrs for the given peer.
326
- *
327
289
  * @param {PeerId} peerId
328
- * @param {(addresses: Address[]) => Address[]} [addressSorter]
329
- * @returns {Multiaddr[]|undefined}
330
290
  */
331
- getMultiaddrsForPeer (peerId, addressSorter = (ms) => ms) {
291
+ async delete (peerId) {
332
292
  if (!PeerId.isPeerId(peerId)) {
333
- throw errcode(new Error('peerId must be an instance of peer-id'), ERR_INVALID_PARAMETERS)
293
+ log.error('peerId must be an instance of peer-id to store data')
294
+ throw errcode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)
334
295
  }
335
296
 
336
- const entry = this.data.get(peerId.toB58String())
337
- if (!entry || !entry.addresses) {
338
- return undefined
297
+ log('delete await write lock')
298
+ const release = await this._store.lock.writeLock()
299
+ log('delete got write lock')
300
+
301
+ let has
302
+
303
+ try {
304
+ has = await this._store.has(peerId)
305
+
306
+ await this._store.patchOrCreate(peerId, {
307
+ addresses: []
308
+ })
309
+ } finally {
310
+ log('delete release write lock')
311
+ release()
339
312
  }
340
313
 
314
+ if (has) {
315
+ this._emit(EVENT_NAME, { peerId, multiaddrs: [] })
316
+ }
317
+ }
318
+
319
+ /**
320
+ * @param {PeerId} peerId
321
+ * @param {(addresses: Address[]) => Address[]} [addressSorter]
322
+ */
323
+ async getMultiaddrsForPeer (peerId, addressSorter = (ms) => ms) {
324
+ const addresses = await this.get(peerId)
325
+
341
326
  return addressSorter(
342
- entry.addresses || []
327
+ addresses
343
328
  ).map((address) => {
344
329
  const multiaddr = address.multiaddr
345
330
 
@@ -351,4 +336,34 @@ class AddressBook extends Book {
351
336
  }
352
337
  }
353
338
 
354
- module.exports = AddressBook
339
+ /**
340
+ * Transforms received multiaddrs into Address.
341
+ *
342
+ * @private
343
+ * @param {Multiaddr[]} multiaddrs
344
+ * @param {boolean} [isCertified]
345
+ * @returns {Address[]}
346
+ */
347
+ function convertMultiaddrsToAddresses (multiaddrs, isCertified = false) {
348
+ if (!multiaddrs) {
349
+ log.error('multiaddrs must be provided to store data')
350
+ throw errcode(new Error('multiaddrs must be provided'), codes.ERR_INVALID_PARAMETERS)
351
+ }
352
+
353
+ // create Address for each address with no duplicates
354
+ return Array.from(
355
+ new Set(multiaddrs.map(ma => ma.toString()))
356
+ )
357
+ .map(addr => {
358
+ try {
359
+ return {
360
+ multiaddr: new Multiaddr(addr),
361
+ isCertified
362
+ }
363
+ } catch (err) {
364
+ throw errcode(err, codes.ERR_INVALID_PARAMETERS)
365
+ }
366
+ })
367
+ }
368
+
369
+ module.exports = PeerStoreAddressBook