aboutsummaryrefslogtreecommitdiff
path: root/lib/wallet/cryptoApi.ts
blob: 62f51f450fee17b4c3cdd3bd2fbb9083f691f878 (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
190
191
192
193
194
195
/*
 This file is part of TALER
 (C) 2016 GNUnet e.V.

 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.

 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
 TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */


/**
 * API to access the Taler crypto worker thread.
 * @author Florian Dold
 */


import {PreCoin} from "./types";
import {Reserve} from "./types";
import {Denomination} from "./types";
import {Offer} from "./wallet";
import {CoinWithDenom} from "./wallet";
import {PayCoinInfo} from "./types";

interface RegistryEntry {
  resolve: any;
  reject: any;
  workerIndex: number;
}

interface WorkerState {
  /**
   * The actual worker thread.
   */
  w: Worker;
  /**
   * Are we currently running a task on this worker?
   */
  busy: boolean;
}

interface WorkItem {
  operation: string;
  args: any[];
  resolve: any;
  reject: any;
}


/**
 * Number of different priorities. Each priority p
 * must be 0 <= p < NUM_PRIO.
 */
const NUM_PRIO = 5;

export class CryptoApi {
  private nextRpcId: number = 1;
  private rpcRegistry: {[n: number]: RegistryEntry} = {};
  private workers: WorkerState[];
  private workQueues: WorkItem[][];
  /**
   * Number of busy workers.
   */
  private numBusy: number = 0;
  /**
   * Number if pending work items.
   */
  private numWaiting: number = 0;


  constructor() {
    let handler = (msg: MessageEvent) => {
      let id = msg.data.id;
      if (typeof id !== "number") {
        console.error("rpc id must be number");
        return;
      }
      if (!this.rpcRegistry[id]) {
        console.error(`RPC with id ${id} has no registry entry`);
        return;
      }
      let {resolve, workerIndex} = this.rpcRegistry[id];
      delete this.rpcRegistry[id];
      let ws = this.workers[workerIndex];
      ws.busy = false;
      this.numBusy--;
      resolve(msg.data.result);

      // try to find more work for this worker
      for (let i = 0; i < NUM_PRIO; i++) {
        let q = this.workQueues[NUM_PRIO - i - 1];
        if (q.length != 0) {
          let work: WorkItem = q.shift()!;
          let msg: any = {
            operation: work.operation,
            args: work.args,
            id: this.registerRpcId(work.resolve, work.reject, workerIndex),
          };
          ws.w.postMessage(msg);
          ws.busy = true;
          this.numBusy++;
        }
      }
    };

    this.workers = new Array<WorkerState>((navigator as any)["hardwareConcurrency"] || 2);

    for (let i = 0; i < this.workers.length; i++) {
      let w = new Worker("/lib/wallet/cryptoWorker.js");
      w.onmessage = handler;
      this.workers[i] = {
        w,
        busy: false,
      };
    }
    this.workQueues = [];
    for (let i = 0; i < NUM_PRIO; i++) {
      this.workQueues.push([]);
    }
  }


  private registerRpcId(resolve: any, reject: any,
                        workerIndex: number): number {
    let id = this.nextRpcId++;
    this.rpcRegistry[id] = {resolve, reject, workerIndex};
    return id;
  }


  private doRpc<T>(operation: string, priority: number,
                   ...args: any[]): Promise<T> {
    if (this.numBusy == this.workers.length) {
      let q = this.workQueues[priority];
      if (!q) {
        throw Error("assertion failed");
      }
      return new Promise<T>((resolve, reject) => {
        this.workQueues[priority].push({operation, args, resolve, reject});
      });
    }

    for (let i = 0; i < this.workers.length; i++) {
      let ws = this.workers[i];
      if (ws.busy) {
        continue;
      }

      return new Promise<T>((resolve, reject) => {
        let msg: any = {
          operation, args,
          id: this.registerRpcId(resolve, reject, i),
        };
        ws.w.postMessage(msg);
        ws.busy = true;
        this.numBusy++;
      });
    }

    throw Error("assertion failed");
  }


  createPreCoin(denom: Denomination, reserve: Reserve): Promise<PreCoin> {
    return this.doRpc("createPreCoin", 1, denom, reserve);
  }

  hashRsaPub(rsaPub: string): Promise<string> {
    return this.doRpc("hashRsaPub", 2, rsaPub);
  }

  isValidDenom(denom: Denomination,
               masterPub: string): Promise<boolean> {
    return this.doRpc("isValidDenom", 2, denom, masterPub);
  }

  signDeposit(offer: Offer,
              cds: CoinWithDenom[]): Promise<PayCoinInfo> {
    return this.doRpc("signDeposit", 3, offer, cds);
  }

  createEddsaKeypair(): Promise<{priv: string, pub: string}> {
    return this.doRpc("createEddsaKeypair", 1);
  }

  rsaUnblind(sig: string, bk: string, pk: string): Promise<string> {
    return this.doRpc("rsaUnblind", 4, sig, bk, pk);
  }
}