From 4deaca5495db16d4db7e365b20a4e433bf4b55ec Mon Sep 17 00:00:00 2001 From: Lucas Leblow Date: Fri, 12 Apr 2024 10:40:31 -0700 Subject: [PATCH] fix: Re-dial peers when resuming from background on iOS --- .../connections-manager.service.ts | 1 + .../backend/src/nest/libp2p/libp2p.service.ts | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/packages/backend/src/nest/connections-manager/connections-manager.service.ts b/packages/backend/src/nest/connections-manager/connections-manager.service.ts index f52de0f6bb..ef3bf853de 100644 --- a/packages/backend/src/nest/connections-manager/connections-manager.service.ts +++ b/packages/backend/src/nest/connections-manager/connections-manager.service.ts @@ -249,6 +249,7 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI // This method is only used on iOS through rn-bridge for reacting on lifecycle changes public async openSocket() { await this.socketService.init() + await this.libp2pService.redialPeers() } public async leaveCommunity() { diff --git a/packages/backend/src/nest/libp2p/libp2p.service.ts b/packages/backend/src/nest/libp2p/libp2p.service.ts index c4129e9888..d62bb306b4 100644 --- a/packages/backend/src/nest/libp2p/libp2p.service.ts +++ b/packages/backend/src/nest/libp2p/libp2p.service.ts @@ -48,6 +48,28 @@ export class Libp2pService extends EventEmitter { await this.libp2pInstance?.dial(multiaddr(peerAddress)) } + private hangUpPeer = async (peerAddress: string) => { + await this.libp2pInstance?.hangUp(multiaddr(peerAddress)) + this.dialedPeers.delete(peerAddress) + } + + /** + * Hang up existing peer connections and re-dial them. Specifically useful on + * iOS where Tor receives a new port when the app resumes from background and + * we want to close/re-open connections. + */ + public redialPeers = async () => { + this.logger('Re-dialing peers') + + const dialedPeers = this.dialedPeers + + for (const peerAddress of dialedPeers) { + await this.hangUpPeer(peerAddress) + } + + this.processInChunksService.updateData(Array.from(dialedPeers)) + } + public readonly createLibp2pAddress = (address: string, peerId: string): string => { return createLibp2pAddress(address, peerId) }