Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: refactor PeerInfo typings #568

Merged
merged 2 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/beacon-core/src/transports/Transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,11 @@ export abstract class Transport<
*/
public async send(message: string, peer?: PeerInfo): Promise<void> {
if (peer) {
return this.client.sendMessage(message, peer as any)
return this.client.sendMessage(message, peer)
} else {
const knownPeers = await this.getPeers()
// A broadcast request has to be sent everywhere.
const promises = knownPeers.map((peerEl) => this.client.sendMessage(message, peerEl as any))
const promises = knownPeers.map((peerEl) => this.client.sendMessage(message, peerEl))

return (await Promise.all(promises))[0]
}
Expand Down
17 changes: 2 additions & 15 deletions packages/beacon-core/src/transports/clients/CommunicationClient.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import {
P2PPairingRequest,
ExtendedP2PPairingResponse,
PostMessagePairingRequest,
ExtendedPostMessagePairingResponse,
WalletConnectPairingRequest,
ExtendedWalletConnectPairingResponse
} from '@airgap/beacon-types'
import { PeerInfoType } from '@airgap/beacon-types'
import { toHex, getHexHash, sealCryptobox } from '@airgap/beacon-utils'
import { convertPublicKeyToX25519, convertSecretKeyToX25519, KeyPair } from '@stablelib/ed25519'
import { clientSessionKeys, serverSessionKeys, SessionKeys } from '@stablelib/x25519-session'
Expand Down Expand Up @@ -90,12 +83,6 @@ export abstract class CommunicationClient {
// abstract send(message: string, recipient?: string): Promise<void>
public abstract sendMessage(
message: string,
peer?:
| P2PPairingRequest
| ExtendedP2PPairingResponse
| PostMessagePairingRequest
| ExtendedPostMessagePairingResponse
| WalletConnectPairingRequest
| ExtendedWalletConnectPairingResponse
peer?: PeerInfoType
): Promise<void>
}
21 changes: 7 additions & 14 deletions packages/beacon-core/src/transports/clients/MessageBasedClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,12 @@ export abstract class MessageBasedClient extends CommunicationClient {
* Get the pairing request information. This will be shared with the peer during the connection setup
*/
public async getPairingRequestInfo(): Promise<PostMessagePairingRequest> {
return {
id: await generateGUID(),
type: 'postmessage-pairing-request',
name: this.name,
version: BEACON_VERSION,
publicKey: await this.getPublicKey()
}
return new PostMessagePairingRequest(
await generateGUID(),
this.name,
await this.getPublicKey(),
BEACON_VERSION
)
}

/**
Expand All @@ -52,13 +51,7 @@ export abstract class MessageBasedClient extends CommunicationClient {
public async getPairingResponseInfo(
request: PostMessagePairingRequest
): Promise<PostMessagePairingResponse> {
return {
id: request.id,
type: 'postmessage-pairing-response',
name: this.name,
version: request.version,
publicKey: await this.getPublicKey()
}
return new PostMessagePairingResponse(request.id, this.name, await this.getPublicKey(), request.version)
}

/**
Expand Down
54 changes: 19 additions & 35 deletions packages/beacon-dapp/src/dapp-client/DAppClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ import {
AppMetadata,
ExtendedP2PPairingResponse,
ExtendedPostMessagePairingResponse,
PostMessagePairingResponse,
SigningType,
ExtendedPeerInfo,
Optional,
Expand All @@ -60,7 +59,8 @@ import {
ExtensionApp,
WebApp,
ExtendedWalletConnectPairingResponse,
ChangeAccountRequest
ChangeAccountRequest,
PeerInfoType
// PermissionRequestV3
// RequestEncryptPayloadInput,
// EncryptPayloadResponseOutput,
Expand Down Expand Up @@ -167,12 +167,7 @@ export class DAppClient extends Client {
/**
* The currently active peer. This is used to address a peer in case the active account is not set. (Eg. for permission requests)
*/
private _activePeer: ExposedPromise<
| ExtendedPostMessagePairingResponse
| ExtendedP2PPairingResponse
| ExtendedWalletConnectPairingResponse
| undefined
> = new ExposedPromise()
private _activePeer: ExposedPromise<PeerInfoType | undefined> = new ExposedPromise()

private _initPromise: Promise<TransportType> | undefined

Expand Down Expand Up @@ -283,7 +278,7 @@ export class DAppClient extends Client {
(peerEl) => peerEl.senderId === message.senderId
)
if (peer) {
await relevantTransport.removePeer(peer as any)
await relevantTransport.removePeer(peer)
}
await this.removeAccountsForPeerIds([message.senderId])
await this.events.emit(BeaconEvent.CHANNEL_CLOSED)
Expand Down Expand Up @@ -349,7 +344,7 @@ export class DAppClient extends Client {
(peerEl) => peerEl.senderId === message.senderId
)
if (peer) {
await relevantTransport.removePeer(peer as any)
await relevantTransport.removePeer(peer)
}
await this.removeAccountsForPeerIds([message.senderId])
await this.events.emit(BeaconEvent.CHANNEL_CLOSED)
Expand Down Expand Up @@ -603,7 +598,7 @@ export class DAppClient extends Client {
await this.setTransport(this.walletConnectTransport)
}
const peer = await this.getPeer(account)
await this.setActivePeer(peer as any)
await this.setActivePeer(peer)
} else {
await this.setActivePeer(undefined)
await this.setTransport(undefined)
Expand Down Expand Up @@ -1234,34 +1229,25 @@ export class DAppClient extends Client {
return message
}

protected async setActivePeer(
peer?:
| ExtendedPostMessagePairingResponse
| ExtendedP2PPairingResponse
| ExtendedWalletConnectPairingResponse
): Promise<void> {
protected async setActivePeer(peer?: PeerInfoType): Promise<void> {
if (this._activePeer.isSettled()) {
// If the promise has already been resolved we need to create a new one.
this._activePeer = ExposedPromise.resolve<
| ExtendedPostMessagePairingResponse
| ExtendedP2PPairingResponse
| ExtendedWalletConnectPairingResponse
| undefined
>(peer)
this._activePeer = ExposedPromise.resolve(peer)
} else {
this._activePeer.resolve(peer)
}

if (peer) {
await this.initInternalTransports()
if (peer.type === 'postmessage-pairing-response') {
await this.setTransport(this.postMessageTransport)
} else if (peer.type === 'p2p-pairing-response') {
await this.setTransport(this.p2pTransport)
}
if (!peer) {
return
}

return
await this.initInternalTransports()

if (peer.type === 'postmessage-pairing-response') {
await this.setTransport(this.postMessageTransport)
} else if (peer.type === 'p2p-pairing-response') {
await this.setTransport(this.p2pTransport)
}
}

/**
Expand Down Expand Up @@ -1445,12 +1431,10 @@ export class DAppClient extends Client {
walletInfo = await this.appMetadataManager.getAppMetadata(selectedAccount.senderId)
}

const typedPeer: PostMessagePairingResponse = selectedPeer as any

if (!walletInfo) {
walletInfo = {
name: typedPeer?.name,
icon: typedPeer?.icon
name: selectedPeer?.name ?? '',
icon: selectedPeer?.icon
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,13 @@ export class P2PCommunicationClient extends CommunicationClient {
}

public async getPairingRequestInfo(): Promise<P2PPairingRequest> {
const info: P2PPairingRequest = {
id: await generateGUID(),
type: 'p2p-pairing-request',
name: this.name,
version: BEACON_VERSION,
publicKey: await this.getPublicKey(),
relayServer: (await this.getRelayServer()).server
}
const info: P2PPairingRequest = new P2PPairingRequest(
await generateGUID(),
this.name,
await this.getPublicKey(),
BEACON_VERSION,
(await this.getRelayServer()).server
)

if (this.iconUrl) {
info.icon = this.iconUrl
Expand All @@ -126,14 +125,13 @@ export class P2PCommunicationClient extends CommunicationClient {
}

public async getPairingResponseInfo(request: P2PPairingRequest): Promise<P2PPairingResponse> {
const info: P2PPairingResponse = {
id: request.id,
type: 'p2p-pairing-response',
name: this.name,
version: request.version,
publicKey: await this.getPublicKey(),
relayServer: (await this.getRelayServer()).server
}
const info: P2PPairingResponse = new P2PPairingResponse(
request.id,
this.name,
await this.getPublicKey(),
request.version,
(await this.getRelayServer()).server
)

if (this.iconUrl) {
info.icon = this.iconUrl
Expand Down Expand Up @@ -713,13 +711,13 @@ export class P2PCommunicationClient extends CommunicationClient {
? new PeerManager(this.storage, StorageKey.TRANSPORT_P2P_PEERS_DAPP)
: new PeerManager(this.storage, StorageKey.TRANSPORT_P2P_PEERS_WALLET)
const peers = await manager.getPeers()
const promiseArray = (peers as any).map(
async (peer: P2PPairingRequest | ExtendedP2PPairingResponse) => {
const promiseArray = peers.map(
async (peer) => {
const hash = `@${await getHexHash(Buffer.from(peer.publicKey, 'hex'))}`
if (hash === senderHash) {
if (peer.relayServer !== relayServer) {
peer.relayServer = relayServer
await manager.addPeer(peer as any)
await manager.addPeer(peer as ExtendedP2PPairingResponse)
}
}
}
Expand Down
15 changes: 10 additions & 5 deletions packages/beacon-transport-postmessage/src/PostMessageClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,16 @@ export class PostMessageClient extends MessageBasedClient {
await openCryptobox(payload, this.keyPair!.publicKey, this.keyPair!.secretKey)
)

messageCallback({
...pairingResponse,
senderId: await getSenderId(pairingResponse.publicKey),
extensionId: event?.data?.sender.id
})
messageCallback(
new ExtendedPostMessagePairingResponse(
pairingResponse.id,
pairingResponse.name,
pairingResponse.publicKey,
pairingResponse.version,
await getSenderId(pairingResponse.publicKey),
event?.data?.sender.id
)
)
} catch (decryptionError) {
/* NO-OP. We try to decode every message, but some might not be addressed to us. */
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,15 +378,15 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
// to get data required in the pairing response
try {
const session = await this.openSession(topic)
const pairingResponse = {
id: topic,
type: 'walletconnect-pairing-response',
name: session.peer.metadata.name,
publicKey: session.peer.publicKey,
senderId: topic,
extensionId: session.peer.metadata.name,
version: '3'
} as ExtendedWalletConnectPairingResponse
const pairingResponse: ExtendedWalletConnectPairingResponse =
new ExtendedWalletConnectPairingResponse(
topic,
session.peer.metadata.name,
session.peer.publicKey,
'3',
topic,
session.peer.metadata.name
)

this.channelOpeningListeners.forEach((listener) => {
listener(pairingResponse)
Expand Down Expand Up @@ -558,15 +558,15 @@ export class WalletConnectCommunicationClient extends CommunicationClient {

public async getPairingRequestInfo(): Promise<ExtendedWalletConnectPairingRequest> {
const { uri, topic } = (await this.init(true)) ?? {}
return {
id: topic!,
type: 'walletconnect-pairing-request',
name: 'WalletConnect',
version: BEACON_VERSION,
uri: uri!,
senderId: await generateGUID(),
publicKey: await generateGUID()
}

return new ExtendedWalletConnectPairingRequest(
topic!,
'WalletConnect',
await generateGUID(),
BEACON_VERSION,
await generateGUID(),
uri!
)
}

private async closePairings() {
Expand Down
3 changes: 2 additions & 1 deletion packages/beacon-types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ import {
PartialTezosOriginationOperation,
PartialTezosRevealOperation
} from './types/tezos/PartialTezosOperation'
import { ExtendedPeerInfo, PeerInfo } from './types/PeerInfo'
import { ExtendedPeerInfo, PeerInfo, PeerInfoType } from './types/PeerInfo'
import { AcknowledgeResponse } from './types/beacon/messages/AcknowledgeResponse'
import { DisconnectMessage } from './types/beacon/messages/DisconnectMessage'
import { SigningType } from './types/beacon/SigningType'
Expand Down Expand Up @@ -253,6 +253,7 @@ export { Storage, StorageKey, StorageKeyReturnDefaults, StorageKeyReturnType }
export {
PeerInfo,
ExtendedPeerInfo,
PeerInfoType,
PostMessagePairingRequest,
PostMessagePairingResponse,
ExtendedPostMessagePairingRequest,
Expand Down
Loading
Loading