Skip to content

Commit 54d47a0

Browse files
marekrjpolakvdovhanych
authored andcommitted
feat(blockchain-link): electrum backends shuffle
(cherry picked from commit cefa971)
1 parent 862fd3a commit 54d47a0

File tree

1 file changed

+34
-21
lines changed
  • packages/blockchain-link/src/workers/electrum

1 file changed

+34
-21
lines changed

packages/blockchain-link/src/workers/electrum/index.ts

+34-21
Original file line numberDiff line numberDiff line change
@@ -141,29 +141,42 @@ class ElectrumWorker extends BaseWorker<ElectrumClient> {
141141
this.txListener = L.txListener(this);
142142
}
143143

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-
151144
async connect(): Promise<ElectrumClient> {
152145
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+
}
167180

168181
this.post({
169182
id: -1,

0 commit comments

Comments
 (0)