11import axios from 'axios' ;
22import debug from 'debug' ;
3+ import { shuffle } from 'libp2p-gossipsub/src/utils' ;
34
45const dbg = debug ( 'waku:discovery' ) ;
56
7+ const DefaultWantedNumber = 1 ;
8+
69/**
710 * GET list of nodes from remote HTTP host.
811 *
@@ -14,15 +17,21 @@ const dbg = debug('waku:discovery');
1417 * request returns `{ foo: { bar: [address1, address2] } }` then `path` should be
1518 * `[ "foo", "bar" ]`.
1619 * @param url Remote host containing bootstrap peers in JSON format.
20+ * @param wantedNumber The number of connections desired. Defaults to [DefaultWantedNumber].
1721 *
1822 * @returns An array of multiaddresses.
1923 * @throws If the remote host is unreachable or the response cannot be parsed
2024 * according to the passed _path_.
2125 */
2226export async function getBootstrapNodes (
2327 path : string [ ] = [ 'fleets' , 'wakuv2.prod' , 'waku-websocket' ] ,
24- url = 'https://fleets.status.im/'
28+ url = 'https://fleets.status.im/' ,
29+ wantedNumber : number = DefaultWantedNumber
2530) : Promise < string [ ] > {
31+ if ( wantedNumber <= 0 ) {
32+ return [ ] ;
33+ }
34+
2635 const res = await axios . get ( url , {
2736 headers : { 'Content-Type' : 'application/json' } ,
2837 } ) ;
@@ -43,18 +52,30 @@ export async function getBootstrapNodes(
4352 }
4453
4554 if ( Array . isArray ( nodes ) ) {
46- return nodes ;
55+ return getPseudoRandomSubset ( nodes , wantedNumber ) ;
4756 }
4857
4958 if ( typeof nodes === 'string' ) {
5059 return [ nodes ] ;
5160 }
5261
5362 if ( typeof nodes === 'object' ) {
54- return Object . values ( nodes ) ;
63+ nodes = Object . values ( nodes ) ;
64+ getPseudoRandomSubset ( nodes , wantedNumber ) ;
5565 }
5666
5767 throw `Failed to retrieve bootstrap nodes: response format is not supported: ${ JSON . stringify (
5868 nodes
5969 ) } `;
6070}
71+
72+ export function getPseudoRandomSubset (
73+ values : string [ ] ,
74+ wantedNumber : number
75+ ) : string [ ] {
76+ if ( values . length <= wantedNumber ) {
77+ return values ;
78+ }
79+
80+ return shuffle ( values ) . slice ( 0 , wantedNumber ) ;
81+ }
0 commit comments