@@ -141,29 +141,42 @@ class ElectrumWorker extends BaseWorker<ElectrumClient> {
141
141
this . txListener = L . txListener ( this ) ;
142
142
}
143
143
144
- private chooseServer ( server : string [ ] ) : string {
145
- if ( ! server || ! Array . isArray ( server ) || server . length < 1 ) {
146
- throw new CustomError ( 'connect' , 'Endpoint not set' ) ;
147
- }
148
- return server [ 0 ] ;
149
- }
150
-
151
144
async connect ( ) : Promise < ElectrumClient > {
152
145
if ( ! this . api ?. connected ( ) ) {
153
- const { server = [ ] , debug, timeout, keepAlive, name } = this . settings ;
154
- const url = this . chooseServer ( server ) ;
155
- const socket = createSocket ( url , { timeout, keepAlive, proxyAgent : this . proxyAgent } ) ;
156
- const api = new CachingElectrumClient ( ) ;
157
- await api . connect ( socket , {
158
- url,
159
- coin : name ?? 'BTC' ,
160
- debug,
161
- client : {
162
- name : 'blockchain-link' ,
163
- protocolVersion : '1.4' ,
164
- } ,
165
- } ) ;
166
- this . api = api ;
146
+ const { debug, timeout, keepAlive, name } = this . settings ;
147
+
148
+ this . validateEndpoints ( ) ;
149
+ const url = this . endpoints [ 0 ] ;
150
+ this . debug ( 'Connecting to' , url ) ;
151
+
152
+ try {
153
+ const socket = createSocket ( url , {
154
+ timeout,
155
+ keepAlive,
156
+ proxyAgent : this . proxyAgent ,
157
+ } ) ;
158
+ const api = new CachingElectrumClient ( ) ;
159
+ await api . connect ( socket , {
160
+ url,
161
+ coin : name ?? 'BTC' ,
162
+ debug,
163
+ client : {
164
+ name : 'blockchain-link' ,
165
+ protocolVersion : '1.4' ,
166
+ } ,
167
+ } ) ;
168
+ this . api = api ;
169
+ } catch ( error ) {
170
+ this . debug ( 'Connection failed' , error ) ;
171
+ this . api = undefined ;
172
+ // connection error, remove endpoint
173
+ this . endpoints . splice ( 0 , 1 ) ;
174
+ // and try another one or throw error
175
+ if ( this . endpoints . length < 1 ) {
176
+ throw new CustomError ( 'connect' , 'All backends are down' ) ;
177
+ }
178
+ return this . connect ( ) ;
179
+ }
167
180
168
181
this . post ( {
169
182
id : - 1 ,
0 commit comments