aboutsummaryrefslogtreecommitdiff
path: root/packages/taler-wallet-core/src/remote.ts
blob: 164f7cfe97323a07d5622f5f84ad0d59a188764b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/*
 This file is part of GNU Taler
 (C) 2023 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

import {
  CoreApiRequestEnvelope,
  CoreApiResponse,
  j2s,
  Logger,
  TalerError,
  WalletNotification,
} from "@gnu-taler/taler-util";
import { connectRpc, JsonMessage } from "@gnu-taler/taler-util/twrpc";
import { OpenedPromise, openPromise } from "./index.js";
import { WalletCoreApiClient } from "./wallet-api-types.js";

const logger = new Logger("remote.ts");

export interface RemoteWallet {
  /**
   * Low-level interface for making API requests to wallet-core.
   */
  makeCoreApiRequest(
    operation: string,
    payload: unknown,
  ): Promise<CoreApiResponse>;

  /**
   * Close the connection to the remote wallet.
   */
  close(): void;
}

export interface RemoteWalletConnectArgs {
  socketFilename: string;
  notificationHandler?: (n: WalletNotification) => void;
}

export async function createRemoteWallet(
  args: RemoteWalletConnectArgs,
): Promise<RemoteWallet> {
  let nextRequestId = 1;
  let requestMap: Map<
    string,
    {
      promiseCapability: OpenedPromise<CoreApiResponse>;
    }
  > = new Map();

  const ctx = await connectRpc<RemoteWallet>({
    socketFilename: args.socketFilename,
    onEstablished(connection) {
      const ctx: RemoteWallet = {
        makeCoreApiRequest(operation, payload) {
          const id = `req-${nextRequestId}`;
          nextRequestId += 1;
          const req: CoreApiRequestEnvelope = {
            operation,
            id,
            args: payload,
          };
          const promiseCap = openPromise<CoreApiResponse>();
          requestMap.set(id, {
            promiseCapability: promiseCap,
          });
          connection.sendMessage(req as unknown as JsonMessage);
          return promiseCap.promise;
        },
        close() {
          connection.close();
        },
      };
      return {
        result: ctx,
        onDisconnect() {
          logger.info("remote wallet disconnected");
        },
        onMessage(m) {
          // FIXME: use a codec for parsing the response envelope!

          logger.info(`got message from remote wallet: ${j2s(m)}`);
          if (typeof m !== "object" || m == null) {
            logger.warn("message from wallet not understood (wrong type)");
            return;
          }
          const type = (m as any).type;
          if (type === "response" || type === "error") {
            const id = (m as any).id;
            if (typeof id !== "string") {
              logger.warn(
                "message from wallet not understood (no id in response)",
              );
              return;
            }
            const h = requestMap.get(id);
            if (!h) {
              logger.warn(`no handler registered for response id ${id}`);
              return;
            }
            h.promiseCapability.resolve(m as any);
          } else if (type === "notification") {
            if (args.notificationHandler) {
              args.notificationHandler((m as any).payload);
            }
          } else {
            logger.warn("message from wallet not understood");
          }
        },
      };
    },
  });
  return ctx;
}

/**
 * Get a high-level API client from a remove wallet.
 */
export function getClientFromRemoteWallet(
  w: RemoteWallet,
): WalletCoreApiClient {
  const client: WalletCoreApiClient = {
    async call(op, payload): Promise<any> {
      const res = await w.makeCoreApiRequest(op, payload);
      switch (res.type) {
        case "error":
          throw TalerError.fromUncheckedDetail(res.error);
        case "response":
          return res.result;
      }
    },
  };
  return client;
}

export interface WalletNotificationWaiter {
  notify(wn: WalletNotification): void;
  waitForNotificationCond<T>(
    cond: (n: WalletNotification) => T | false | undefined,
  ): Promise<T>;
}

interface NotificationCondEntry<T> {
  condition: (n: WalletNotification) => T | false | undefined;
  promiseCapability: OpenedPromise<T>;
}

/**
 * Helper that allows creating a promise that resolves when the
 * wallet
 */
export function makeNotificationWaiter(): WalletNotificationWaiter {
  // Bookkeeping for waiting on notification conditions
  let nextCondIndex = 1;
  const condMap: Map<number, NotificationCondEntry<any>> = new Map();
  function onNotification(n: WalletNotification) {
    condMap.forEach((cond, condKey) => {
      const res = cond.condition(n);
      if (res) {
        cond.promiseCapability.resolve(res);
      }
    });
  }
  function waitForNotificationCond<T>(
    cond: (n: WalletNotification) => T | false | undefined,
  ) {
    const promCap = openPromise<T>();
    condMap.set(nextCondIndex++, {
      condition: cond,
      promiseCapability: promCap,
    });
    return promCap.promise;
  }
  return {
    waitForNotificationCond,
    notify: onNotification,
  };
}