summaryrefslogtreecommitdiff
path: root/src/crypto/emscInterface.ts
blob: 2ddc15a375fd4e38aba859c97dd84e0f14bd93b7 (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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
/*
 This file is part of TALER
 (C) 2015 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/>
 */


/**
 * Medium-level interface to emscripten-compiled modules used
 * by the wallet.  Handles memory management by allocating by allocating
 * objects in arenas that then can be disposed of all at once.
 *
 * The high-level interface (using WebWorkers) is exposed in src/cryptoApi.ts.
 */

/**
 * Imports.
 */
import { AmountJson } from "../amounts";

import { EmscFunGen, EmscLib } from "./emscLoader";


// Will be set only after initialization.
let maybeEmscEnv: EmscEnvironment | undefined = undefined;

export function isInitialized() {
  return !!maybeEmscEnv;
}


export function initialize(lib: EmscLib) {
  if (!lib) {
    throw Error("library must be object");
  }
  if (maybeEmscEnv) {
    throw Error("emsc lib already initialized");
  }
  maybeEmscEnv = new EmscEnvironment(lib);
}


function emsc() {
  if (maybeEmscEnv) {
    return maybeEmscEnv;
  }
  throw Error("cannot use taler emscripten before initialization");
}


/**
 * Size of a native pointer.  Must match the size
 * use when compiling via emscripten.
 */
const PTR_SIZE = 4;

const GNUNET_OK = 1;

interface EmscFunctions {
  amount_add(a1: number, a2: number, a3: number): number;
  amount_cmp(a1: number, a2: number): number;
  amount_get_zero(a1: string, a2: number): number;
  amount_hton(a1: number, a2: number): void;
  amount_normalize(a1: number): void;
  amount_ntoh(a1: number, a2: number): void;
  amount_subtract(a1: number, a2: number, a3: number): number;
  ecdh_eddsa(a1: number, a2: number, a3: number): number;
  eddsa_sign(a1: number, a2: number, a3: number): number;
  eddsa_verify(a1: number, a2: number, a3: number, a4: number): number;
  free(ptr: number): void;
  get_currency(a: number): string;
  get_fraction(a: number): number;
  get_value(a: number): number;
  hash(a1: number, a2: number, a3: number): void;
  hash_context_abort(ctx: number): void;
  hash_context_finish(a1: number, a2: number): void;
  hash_context_read(a1: number, a2: number, a3: number): void;
  hash_create_random(a1: number, a2: number): void;
  memmove(a1: number, a2: number, a3: number): number;
  random_block(a1: number, a2: number, a3: number): void;
  rsa_blinding_key_free(a1: number): void;
  rsa_public_key_free(a1: number): void;
  rsa_private_key_free(a1: number): void;
  rsa_signature_free(a1: number): void;
  rsa_verify(msgHash: number, sig: number, pubKey: number): number;
  setup_fresh_coin(a1: number, a2: number, a3: number): void;
  string_to_data(a1: number, a2: number, a3: number, a4: number): number;
}

interface EmscAllocFunctions {
  data_to_string_alloc(a1: number, a2: number): number;
  ecdhe_key_create(): number;
  ecdhe_public_key_from_private(a1: number): number;
  ecdsa_key_create(): number;
  ecdsa_public_key_from_private(a1: number): number;
  eddsa_key_create(): number;
  eddsa_public_key_from_private(a1: number): number;
  /**
   * Note that value_1 and value_2 are the first 64-bit parameter,
   * and not two separate parameters (by the emscripten calling convention).
   */
  get_amount(value_1: number, value_2: number, fraction: number, currency: string): number;
  hash_context_start(): number;
  malloc(size: number): number;
  purpose_create(a1: number, a2: number, a3: number): number;
  rsa_blind(a1: number, a2: number, a3: number, a4: number, a5: number): number;
  rsa_blinding_key_create(a1: number): number;
  rsa_blinding_key_decode(a1: number, a2: number): number;
  rsa_blinding_key_encode(a1: number, a2: number): number;
  rsa_private_key_create(len: number): number;
  rsa_private_key_decode(a1: number, a2: number): number;
  rsa_private_key_encode(a1: number, a2: number): number;
  rsa_private_key_get_public(privKeyPtr: number): number;
  rsa_public_key_decode(a1: number, a2: number): number;
  rsa_public_key_encode(a1: number, a2: number): number;
  rsa_signature_decode(a1: number, a2: number): number;
  rsa_signature_encode(a1: number, a2: number): number;
  rsa_sign_blinded(keyPtr: number, msgPtr: number, msgLen: number): number;
  rsa_unblind(a1: number, a2: number, a3: number): number;
}

class EmscEnvironment {

  /**
   * Emscripten functions that don't do any memory allocations.
   */
  public funcs: EmscFunctions;

  /**
   * Emscripten functions that allocate memory.
   */
  public allocFuncs: EmscAllocFunctions;

  public lib: EmscLib;

  constructor(lib: EmscLib) {
    const getEmsc: EmscFunGen = (name: string, ret: any, argTypes: any[]) => {
      return (...args: any[]) => {
        return lib.ccall(name, ret, argTypes, args);
      };
    };
    this.lib = lib;
    this.allocFuncs = {
      data_to_string_alloc: getEmsc("GNUNET_STRINGS_data_to_string_alloc", "number", ["number", "number"]),
      ecdhe_key_create: getEmsc("GNUNET_CRYPTO_ecdhe_key_create", "number", []),
      ecdhe_public_key_from_private: getEmsc( "TALER_WRALL_ecdhe_public_key_from_private", "number", ["number"]),
      ecdsa_key_create: getEmsc("GNUNET_CRYPTO_ecdsa_key_create", "number", []),
      ecdsa_public_key_from_private: getEmsc( "TALER_WRALL_ecdsa_public_key_from_private", "number", ["number"]),
      eddsa_key_create: getEmsc("GNUNET_CRYPTO_eddsa_key_create", "number", []),
      eddsa_public_key_from_private: getEmsc( "TALER_WRALL_eddsa_public_key_from_private", "number", ["number"]),
      get_amount: getEmsc("TALER_WRALL_get_amount", "number", ["number", "number", "number", "string"]),
      hash_context_start: getEmsc("GNUNET_CRYPTO_hash_context_start", "number", []),
      malloc: (size: number) => lib._malloc(size),
      purpose_create: getEmsc("TALER_WRALL_purpose_create", "number", ["number", "number", "number"]),
      rsa_blind: getEmsc("GNUNET_CRYPTO_rsa_blind", "number", ["number", "number", "number", "number", "number"]),
      rsa_blinding_key_create: getEmsc("GNUNET_CRYPTO_rsa_blinding_key_create", "number", ["number"]),
      rsa_blinding_key_decode: getEmsc("GNUNET_CRYPTO_rsa_blinding_key_decode", "number", ["number", "number"]),
      rsa_blinding_key_encode: getEmsc("GNUNET_CRYPTO_rsa_blinding_key_encode", "number", ["number", "number"]),
      rsa_private_key_create: getEmsc("GNUNET_CRYPTO_rsa_private_key_create", "number", ["number"]),
      rsa_private_key_decode: getEmsc("GNUNET_CRYPTO_rsa_private_key_decode", "number", ["number", "number"]),
      rsa_private_key_encode: getEmsc("GNUNET_CRYPTO_rsa_private_key_encode", "number", ["number", "number"]),
      rsa_private_key_get_public: getEmsc("GNUNET_CRYPTO_rsa_private_key_get_public", "number", ["number"]),
      rsa_public_key_decode: getEmsc("GNUNET_CRYPTO_rsa_public_key_decode", "number", ["number", "number"]),
      rsa_public_key_encode: getEmsc("GNUNET_CRYPTO_rsa_public_key_encode", "number", ["number", "number"]),
      rsa_signature_decode: getEmsc("GNUNET_CRYPTO_rsa_signature_decode", "number", ["number", "number"]),
      rsa_signature_encode: getEmsc("GNUNET_CRYPTO_rsa_signature_encode", "number", ["number", "number"]),
      rsa_sign_blinded: getEmsc("GNUNET_CRYPTO_rsa_sign_blinded", "number", ["number", "number", "number"]),
      rsa_unblind: getEmsc("GNUNET_CRYPTO_rsa_unblind", "number", ["number", "number", "number"]),
    };
    this.funcs = {
      amount_add: getEmsc("TALER_amount_add", "number", ["number", "number", "number"]),
      amount_cmp: getEmsc("TALER_amount_cmp", "number", ["number", "number"]),
      amount_get_zero: getEmsc("TALER_amount_get_zero", "number", ["string", "number"]),
      amount_hton: getEmsc("TALER_amount_hton", "void", ["number", "number"]),
      amount_normalize: getEmsc("TALER_amount_normalize", "void", ["number"]),
      amount_ntoh: getEmsc("TALER_amount_ntoh", "void", ["number", "number"]),
      amount_subtract: getEmsc("TALER_amount_subtract", "number", ["number", "number", "number"]),
      ecdh_eddsa: getEmsc("GNUNET_CRYPTO_ecdh_eddsa", "number", ["number", "number", "number"]),
      eddsa_sign: getEmsc("GNUNET_CRYPTO_eddsa_sign", "number", ["number", "number", "number"]),
      eddsa_verify: getEmsc("GNUNET_CRYPTO_eddsa_verify", "number", ["number", "number", "number", "number"]),
      free: (ptr: number) => lib._free(ptr),
      get_currency: getEmsc("TALER_WR_get_currency", "string", ["number"]),
      get_fraction: getEmsc("TALER_WR_get_fraction", "number", ["number"]),
      get_value: getEmsc("TALER_WR_get_value", "number", ["number"]),
      hash: getEmsc("GNUNET_CRYPTO_hash", "void", ["number", "number", "number"]),
      hash_context_abort: getEmsc("GNUNET_CRYPTO_hash_context_abort", "void", ["number"]),
      hash_context_finish: getEmsc("GNUNET_CRYPTO_hash_context_finish", "void", ["number", "number"]),
      hash_context_read: getEmsc("GNUNET_CRYPTO_hash_context_read", "void", ["number", "number", "number"]),
      hash_create_random: getEmsc("GNUNET_CRYPTO_hash_create_random", "void", ["number", "number"]),
      memmove: getEmsc("memmove", "number", ["number", "number", "number"]),
      random_block: getEmsc("GNUNET_CRYPTO_random_block", "void", ["number", "number", "number"]),
      rsa_blinding_key_free: getEmsc("GNUNET_CRYPTO_rsa_blinding_key_free", "void", ["number"]),
      rsa_public_key_free: getEmsc("GNUNET_CRYPTO_rsa_public_key_free", "void", ["number"]),
      rsa_private_key_free: getEmsc("GNUNET_CRYPTO_rsa_private_key_free", "void", ["number"]),
      rsa_signature_free: getEmsc("GNUNET_CRYPTO_rsa_signature_free", "void", ["number"]),
      rsa_verify: getEmsc("GNUNET_CRYPTO_rsa_verify", "number", ["number", "number", "number"]),
      setup_fresh_coin: getEmsc("TALER_setup_fresh_coin", "void", ["number", "number", "number"]),
      string_to_data: getEmsc("GNUNET_STRINGS_string_to_data", "number", ["number", "number", "number", "number"]),
    };
  }
}


/**
 * Constants for signatures purposes, define what the signatures vouches for.
 */
export enum SignaturePurpose {
  RESERVE_WITHDRAW = 1200,
  WALLET_COIN_DEPOSIT = 1201,
  MASTER_DENOMINATION_KEY_VALIDITY = 1025,
  WALLET_COIN_MELT = 1202,
  TEST = 4242,
  MERCHANT_PAYMENT_OK = 1104,
  MASTER_WIRE_FEES = 1028,
  WALLET_COIN_PAYBACK = 1203,
  WALLET_COIN_LINK = 1204,
}


/**
 * Desired quality levels for random numbers.
 */
export enum RandomQuality {
  WEAK = 0,
  STRONG = 1,
  NONCE = 2,
}


/**
 * Object that is allocated in some arena.
 */
interface ArenaObject {
  destroy(): void;
}


/**
 * Context for cummulative hashing.
 */
export class HashContext implements ArenaObject {
  private hashContextPtr: number | undefined;

  constructor() {
    this.hashContextPtr = emsc().allocFuncs.hash_context_start();
  }

  /**
   * Add data to be hashed.
   */
  read(obj: PackedArenaObject): void {
    if (!this.hashContextPtr) {
      throw Error("assertion failed");
    }
    emsc().funcs.hash_context_read(this.hashContextPtr, obj.nativePtr, obj.size());
  }

  /**
   * Finish the hash computation.
   */
  finish(h: HashCode) {
    if (!this.hashContextPtr) {
      throw Error("assertion failed");
    }
    h.alloc();
    emsc().funcs.hash_context_finish(this.hashContextPtr, h.nativePtr);
  }

  /**
   * Abort hashing without computing the result.
   */
  destroy(): void {
    if (this.hashContextPtr) {
      emsc().funcs.hash_context_abort(this.hashContextPtr);
    }
    this.hashContextPtr = undefined;
  }
}


/**
 * Arena object that points to an allocated block of memory.
 */
abstract class MallocArenaObject implements ArenaObject {
  protected _nativePtr: number | undefined = undefined;

  /**
   * Is this a weak reference to the underlying memory?
   */
  isWeak = false;

  destroy(): void {
    if (this._nativePtr && !this.isWeak) {
      emsc().funcs.free(this.nativePtr);
      this._nativePtr = undefined;
    }
  }

  constructor(arena?: Arena) {
    if (!arena) {
      if (arenaStack.length === 0) {
        throw Error("No arena available");
      }
      arena = arenaStack[arenaStack.length - 1];
    }
    arena.put(this);
  }

  alloc(size: number) {
    if (this._nativePtr !== undefined) {
      throw Error("Double allocation");
    }
    this.nativePtr = emsc().allocFuncs.malloc(size);
  }

  set nativePtr(v: number) {
    if (v === undefined) {
      throw Error("Native pointer must be a number or null");
    }
    this._nativePtr = v;
  }

  get nativePtr() {
    // We want to allow latent allocation
    // of native wrappers, but we never want to
    // pass 'undefined' to emscripten.
    if (this._nativePtr === undefined) {
      throw Error("Native pointer not initialized");
    }
    return this._nativePtr;
  }
}


/**
 * An arena stores objects that will be deallocated
 * at the same time.
 */
interface Arena {
  put(obj: ArenaObject): void;
  destroy(): void;
}


/**
 * Arena that must be manually destroyed.
 */
class SimpleArena implements Arena {
  protected heap: ArenaObject[];

  constructor() {
    this.heap = [];
  }

  put(obj: ArenaObject) {
    this.heap.push(obj);
  }

  destroy() {
    for (const obj of this.heap) {
      obj.destroy();
    }
    this.heap = [];
  }
}


/**
 * Arena that destroys all its objects once control has returned to the message
 * loop.
 */
class SyncArena extends SimpleArena {
  private isScheduled: boolean;

  constructor() {
    super();
  }

  pub(obj: MallocArenaObject) {
    super.put(obj);
    if (!this.isScheduled) {
      this.schedule();
    }
    this.heap.push(obj);
  }

  private schedule() {
    this.isScheduled = true;
    Promise.resolve().then(() => {
      this.isScheduled = false;
      this.destroy();
    });
  }
}

export const arenaStack: Arena[] = [];
arenaStack.push(new SyncArena());


/**
 * Representation of monetary value in a given currency.
 */
export class Amount extends MallocArenaObject {
  constructor(args?: AmountJson, arena?: Arena) {
    super(arena);
    if (args) {
      this.nativePtr = emsc().allocFuncs.get_amount(args.value,
                                            0,
                                            args.fraction,
                                            args.currency);
    } else {
      this.nativePtr = emsc().allocFuncs.get_amount(0, 0, 0, "");
    }
  }

  static getZero(currency: string, a?: Arena): Amount {
    const am = new Amount(undefined, a);
    const r = emsc().funcs.amount_get_zero(currency, am.nativePtr);
    if (r !== GNUNET_OK) {
      throw Error("invalid currency");
    }
    return am;
  }


  toNbo(a?: Arena): AmountNbo {
    const x = new AmountNbo(a);
    x.alloc();
    emsc().funcs.amount_hton(x.nativePtr, this.nativePtr);
    return x;
  }

  fromNbo(nbo: AmountNbo): void {
    emsc().funcs.amount_ntoh(this.nativePtr, nbo.nativePtr);
  }

  get value() {
    return emsc().funcs.get_value(this.nativePtr);
  }

  get fraction() {
    return emsc().funcs.get_fraction(this.nativePtr);
  }

  get currency(): string {
    return emsc().funcs.get_currency(this.nativePtr);
  }

  toJson(): AmountJson {
    return {
      currency: emsc().funcs.get_currency(this.nativePtr),
      fraction: emsc().funcs.get_fraction(this.nativePtr),
      value: emsc().funcs.get_value(this.nativePtr),
    };
  }

  /**
   * Add an amount to this amount.
   */
  add(a: Amount) {
    const res = emsc().funcs.amount_add(this.nativePtr, a.nativePtr, this.nativePtr);
    if (res < 1) {
      // Overflow
      return false;
    }
    return true;
  }

  /**
   * Perform saturating subtraction on amounts.
   */
  sub(a: Amount) {
    // this = this - a
    const res = emsc().funcs.amount_subtract(this.nativePtr, this.nativePtr, a.nativePtr);
    if (res === 0) {
      // Underflow
      return false;
    }
    if (res > 0) {
      return true;
    }
    throw Error("Incompatible currencies");
  }

  cmp(a: Amount) {
    // If we don't check this, the c code aborts.
    if (this.currency !== a.currency) {
      throw Error(`incomparable currencies (${this.currency} and ${a.currency})`);
    }
    return emsc().funcs.amount_cmp(this.nativePtr, a.nativePtr);
  }

  normalize() {
    emsc().funcs.amount_normalize(this.nativePtr);
  }
}


/**
 * Count the UTF-8 characters in a JavaScript string.
 */
function countUtf8Bytes(str: string): number {
  let s = str.length;
  // JavaScript strings are UTF-16 arrays
  for (let i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) {
      // We need an extra byte in utf-8 here
      s++;
    } else if (code > 0x7ff && code <= 0xffff) {
      // We need two extra bytes in utf-8 here
      s += 2;
    }
    // Skip over the other surrogate
    if (code >= 0xDC00 && code <= 0xDFFF) {
      i--;
    }
  }
  return s;
}


/**
 * Managed reference to a contiguous block of memory in the Emscripten heap.
 * Can be converted from / to a serialized representation.
 * Should contain only data, not pointers.
 */
abstract class PackedArenaObject extends MallocArenaObject {
  abstract size(): number;

  constructor(a?: Arena) {
    super(a);
  }

  randomize(qual: RandomQuality = RandomQuality.STRONG): void {
    emsc().funcs.random_block(qual, this.nativePtr, this.size());
  }

  toCrock(): string {
    const d = emsc().allocFuncs.data_to_string_alloc(this.nativePtr, this.size());
    const s = emsc().lib.Pointer_stringify(d);
    emsc().funcs.free(d);
    return s;
  }

  toJson(): any {
    // Per default, the json encoding of
    // packed arena objects is just the crockford encoding.
    // Subclasses typically want to override this.
    return this.toCrock();
  }

  loadCrock(s: string) {
    this.alloc();
    // We need to get the javascript string
    // to the emscripten heap first.
    const buf = ByteArray.fromStringWithNull(s);
    const res = emsc().funcs.string_to_data(buf.nativePtr,
                                  s.length,
                                  this.nativePtr,
                                  this.size());
    buf.destroy();
    if (res < 1) {
      throw {error: "wrong encoding"};
    }
  }

  alloc() {
    // FIXME: should the client be allowed to call alloc multiple times?
    if (!this._nativePtr) {
      this.nativePtr = emsc().allocFuncs.malloc(this.size());
    }
  }

  hash(): HashCode {
    const x = new HashCode();
    x.alloc();
    emsc().funcs.hash(this.nativePtr, this.size(), x.nativePtr);
    return x;
  }

  hexdump() {
    const bytes: string[] = [];
    for (let i = 0; i < this.size(); i++) {
      let b = emsc().lib.getValue(this.nativePtr + i, "i8");
      b = (b + 256) % 256;
      bytes.push("0".concat(b.toString(16)).slice(-2));
    }
    const lines: string[] = [];
    for (let i = 0; i < bytes.length; i += 8) {
      lines.push(bytes.slice(i, i + 8).join(","));
    }
    return lines.join("\n");
  }
}


/**
 * Amount, encoded for network transmission.
 */
export class AmountNbo extends PackedArenaObject {
  size() {
    return 24;
  }

  toJson(): any {
    const a = new SimpleArena();
    const am = new Amount(undefined, a);
    am.fromNbo(this);
    const json = am.toJson();
    a.destroy();
    return json;
  }
}


/**
 * Create a packed arena object from the base32 crockford encoding.
 */
function fromCrock<T extends PackedArenaObject>(s: string, ctor: Ctor<T>): T {
  const x: T = new ctor();
  x.alloc();
  x.loadCrock(s);
  return x;
}


/**
 * Create a packed arena object from the base32 crockford encoding for objects
 * that have a special decoding function.
 */
function fromCrockDecoded<T extends MallocArenaObject>(s: string,
                                                       ctor: Ctor<T>,
                                                       decodeFn: (p: number, s: number) => number): T {
  const obj = new ctor();
  const buf = ByteArray.fromCrock(s);
  obj.nativePtr = decodeFn(buf.nativePtr, buf.size());
  buf.destroy();
  return obj;
}


/**
 * Encode an object using a special encoding function.
 */
function encode<T extends MallocArenaObject>(obj: T, encodeFn: any, arena?: Arena): ByteArray {
  const ptr = emsc().allocFuncs.malloc(PTR_SIZE);
  const len = encodeFn(obj.nativePtr, ptr);
  const res = new ByteArray(len, undefined, arena);
  res.nativePtr = emsc().lib.getValue(ptr, "*");
  emsc().funcs.free(ptr);
  return res;
}


/**
 * Private EdDSA key.
 */
export class EddsaPrivateKey extends PackedArenaObject {
  static create(a?: Arena): EddsaPrivateKey {
    const obj = new EddsaPrivateKey(a);
    obj.nativePtr = emsc().allocFuncs.eddsa_key_create();
    return obj;
  }

  size() {
    return 32;
  }

  getPublicKey(a?: Arena): EddsaPublicKey {
    const obj = new EddsaPublicKey(a);
    obj.nativePtr = emsc().allocFuncs.eddsa_public_key_from_private(this.nativePtr);
    return obj;
  }

  static fromCrock(s: string): EddsaPrivateKey {
    return fromCrock(s, this);
  }
}


/**
 * Low-level handle to an EdDSA private key.
 */
export class EcdsaPrivateKey extends PackedArenaObject {
  static create(a?: Arena): EcdsaPrivateKey {
    const obj = new EcdsaPrivateKey(a);
    obj.nativePtr = emsc().allocFuncs.ecdsa_key_create();
    return obj;
  }

  size() {
    return 32;
  }

  getPublicKey(a?: Arena): EcdsaPublicKey {
    const obj = new EcdsaPublicKey(a);
    obj.nativePtr = emsc().allocFuncs.ecdsa_public_key_from_private(this.nativePtr);
    return obj;
  }

  static fromCrock(s: string): EcdsaPrivateKey {
    return fromCrock(s, this);
  }
}


/**
 * Low-level handle to an ECDHE private key.
 */
export class EcdhePrivateKey extends PackedArenaObject {
  static create(a?: Arena): EcdhePrivateKey {
    const obj = new EcdhePrivateKey(a);
    obj.nativePtr = emsc().allocFuncs.ecdhe_key_create();
    return obj;
  }

  size() {
    return 32;
  }

  getPublicKey(a?: Arena): EcdhePublicKey {
    const obj = new EcdhePublicKey(a);
    obj.nativePtr = emsc().allocFuncs.ecdhe_public_key_from_private(this.nativePtr);
    return obj;
  }

  static fromCrock(s: string): EcdhePrivateKey {
    return fromCrock(s, this);
  }
}


/**
 * Constructor for a given type.
 */
interface Ctor<T> {
  new(): T;
}


/**
 * Low-level handle to an EdDSA public key.
 */
export class EddsaPublicKey extends PackedArenaObject {
  size() {
    return 32;
  }

  static fromCrock(s: string): EddsaPublicKey {
    return fromCrock(s, this);
  }
}

/**
 * Low-level handle to an ECDSA public key.
 */
export class EcdsaPublicKey extends PackedArenaObject {
  size() {
    return 32;
  }

  static fromCrock(s: string): EcdsaPublicKey {
    return fromCrock(s, this);
  }
}


/**
 * Low-level handle to an ECDHE public key.
 */
export class EcdhePublicKey extends PackedArenaObject {
  size() {
    return 32;
  }

  static fromCrock(s: string): EcdhePublicKey {
    return fromCrock(s, this);
  }
}


/**
 * Low-level handle to a blinding key secret.
 */
export class RsaBlindingKeySecret extends PackedArenaObject {
  size() {
    return 32;
  }

  /**
   * Create a random blinding key secret.
   */
  static create(a?: Arena): RsaBlindingKeySecret {
    const o = new RsaBlindingKeySecret(a);
    o.alloc();
    o.randomize();
    return o;
  }

  static fromCrock(s: string): RsaBlindingKeySecret {
    return fromCrock(s, this);
  }
}


/**
 * Low-level handle to a hash code.
 */
export class HashCode extends PackedArenaObject {
  size() {
    return 64;
  }

  static fromCrock(s: string): HashCode {
    return fromCrock(s, this);
  }

  random(qual: RandomQuality = RandomQuality.STRONG) {
    this.alloc();
    emsc().funcs.hash_create_random(qual, this.nativePtr);
  }
}


/**
 * Low-level handle to a byte array.
 */
export class ByteArray extends PackedArenaObject {
  private allocatedSize: number;

  size() {
    return this.allocatedSize;
  }

  constructor(desiredSize: number, init?: number, a?: Arena) {
    super(a);
    if (init === undefined) {
      this.nativePtr = emsc().allocFuncs.malloc(desiredSize);
    } else {
      this.nativePtr = init;
    }
    this.allocatedSize = desiredSize;
  }

  static fromStringWithoutNull(s: string, a?: Arena): ByteArray {
    // UTF-8 bytes, including 0-terminator
    const terminatedByteLength = countUtf8Bytes(s) + 1;
    const hstr = emsc().allocFuncs.malloc(terminatedByteLength);
    emsc().lib.stringToUTF8(s, hstr, terminatedByteLength);
    return new ByteArray(terminatedByteLength - 1, hstr, a);
  }

  static fromStringWithNull(s: string, a?: Arena): ByteArray {
    // UTF-8 bytes, including 0-terminator
    const terminatedByteLength = countUtf8Bytes(s) + 1;
    const hstr = emsc().allocFuncs.malloc(terminatedByteLength);
    emsc().lib.stringToUTF8(s, hstr, terminatedByteLength);
    return new ByteArray(terminatedByteLength, hstr, a);
  }

  static fromCrock(s: string, a?: Arena): ByteArray {
    // this one is a bit more complicated than the other fromCrock functions,
    // since we don't have a fixed size
    const byteLength = countUtf8Bytes(s);
    const hstr = emsc().allocFuncs.malloc(byteLength + 1);
    emsc().lib.stringToUTF8(s, hstr, byteLength + 1);
    const decodedLen = Math.floor((byteLength * 5) / 8);
    const ba = new ByteArray(decodedLen, undefined, a);
    const res = emsc().funcs.string_to_data(hstr, byteLength, ba.nativePtr, decodedLen);
    emsc().funcs.free(hstr);
    if (res !== GNUNET_OK) {
      throw Error("decoding failed");
    }
    return ba;
  }
}


/**
 * Data to sign, together with a header that includes a purpose id
 * and size.
 */
export class EccSignaturePurpose extends PackedArenaObject {
  size() {
    return this.payloadSize + 8;
  }

  private payloadSize: number;

  constructor(purpose: SignaturePurpose,
              payload: PackedArenaObject,
              a?: Arena) {
    super(a);
    this.nativePtr = emsc().allocFuncs.purpose_create(purpose,
                                                      payload.nativePtr,
                                                      payload.size());
    this.payloadSize = payload.size();
  }
}


abstract class SignatureStruct {
  abstract fieldTypes(): any[];

  abstract purpose(): SignaturePurpose;

  private members: any = {};

  constructor(x: { [name: string]: any }) {
    for (const k in x) {
      this.set(k, x[k]);
    }
  }

  toPurpose(a?: Arena): EccSignaturePurpose {
    let totalSize = 0;
    for (const f of this.fieldTypes()) {
      const name = f[0];
      const member = this.members[name];
      if (!member) {
        throw Error(`Member ${name} not set`);
      }
      totalSize += member.size();
    }

    const buf = emsc().allocFuncs.malloc(totalSize);
    let ptr = buf;
    for (const f of this.fieldTypes()) {
      const name = f[0];
      const member = this.members[name];
      const size = member.size();
      emsc().funcs.memmove(ptr, member.nativePtr, size);
      ptr += size;
    }
    const ba = new ByteArray(totalSize, buf, a);
    return new EccSignaturePurpose(this.purpose(), ba);
  }


  toJson() {
    const res: any = {};
    for (const f of this.fieldTypes()) {
      const name = f[0];
      const member = this.members[name];
      if (!member) {
        throw Error(`Member ${name} not set`);
      }
      res[name] = member.toJson();
    }
    res.purpose = this.purpose();
    return res;
  }

  protected set(name: string, value: PackedArenaObject) {
    const typemap: any = {};
    for (const f of this.fieldTypes()) {
      typemap[f[0]] = f[1];
    }
    if (!(name in typemap)) {
      throw Error(`Key ${name} not found`);
    }
    if (!(value instanceof typemap[name])) {
      throw Error(`Wrong type for ${name}`);
    }
    this.members[name] = value;
  }
}


/**
 * Arguments to constructor of [[WithdrawRequestPS]].
 */
export interface WithdrawRequestPS_Args {
  /**
   * Reserve public key.
   */
  reserve_pub: EddsaPublicKey;
  /**
   * Amount with fee.
   */
  amount_with_fee: AmountNbo;
  /**
   * Withdraw fee.
   */
  withdraw_fee: AmountNbo;
  /**
   * Hash of denomination public key.
   */
  h_denomination_pub: HashCode;
  /**
   * Hash of coin envelope.
   */
  h_coin_envelope: HashCode;
}


/**
 * Low-level handle to a WithdrawRequest signature structure.
 */
export class WithdrawRequestPS extends SignatureStruct {
  constructor(w: WithdrawRequestPS_Args) {
    super(w);
  }

  purpose() {
    return SignaturePurpose.RESERVE_WITHDRAW;
  }

  fieldTypes() {
    return [
      ["reserve_pub", EddsaPublicKey],
      ["amount_with_fee", AmountNbo],
      ["withdraw_fee", AmountNbo],
      ["h_denomination_pub", HashCode],
      ["h_coin_envelope", HashCode],
    ];
  }
}


/**
 * Arguments for constructor or [[PaybackRequestPS]].
 */
export interface PaybackRequestPS_args {
  coin_pub: EddsaPublicKey;
  h_denom_pub: HashCode;
  coin_blind: RsaBlindingKeySecret;
}


/**
 * Low-level handle to a PaybackRequest signature structure.
 */
export class PaybackRequestPS extends SignatureStruct {
  constructor(w: PaybackRequestPS_args) {
    super(w);
  }

  purpose() {
    return SignaturePurpose.WALLET_COIN_PAYBACK;
  }

  fieldTypes() {
    return [
      ["coin_pub", EddsaPublicKey],
      ["h_denom_pub", HashCode],
      ["coin_blind", RsaBlindingKeySecret],
    ];
  }
}


/**
 * Arguments for constructor of [[RefreshMeltCoinAffirmationPS]].
 */
interface RefreshMeltCoinAffirmationPS_Args {
  session_hash: HashCode;
  amount_with_fee: AmountNbo;
  melt_fee: AmountNbo;
  coin_pub: EddsaPublicKey;
}

/**
 * Low-level handle to a RefreshMeltCoinAffirmationPS signature structure.
 */
export class RefreshMeltCoinAffirmationPS extends SignatureStruct {
  constructor(w: RefreshMeltCoinAffirmationPS_Args) {
    super(w);
  }

  purpose() {
    return SignaturePurpose.WALLET_COIN_MELT;
  }

  fieldTypes() {
    return [
      ["session_hash", HashCode],
      ["amount_with_fee", AmountNbo],
      ["melt_fee", AmountNbo],
      ["coin_pub", EddsaPublicKey],
    ];
  }
}


/**
 * Arguments for constructor of [[MasterWireFeePS]].
 */
interface MasterWireFeePS_Args {
  /**
   * Hash of wire method.
   */
  h_wire_method: HashCode;
  /**
   * Start date.
   */
  start_date: AbsoluteTimeNbo;
  /**
   * End date.
   */
  end_date: AbsoluteTimeNbo;
  /**
   * Wire fee.
   */
  wire_fee: AmountNbo;
  /**
   * Closing fee.
   */
  closing_fee: AmountNbo;
}


/**
 * Low-level handle to a structure being signed over.
 */
export class MasterWireFeePS extends SignatureStruct {
  constructor(w: MasterWireFeePS_Args) {
    super(w);
  }

  purpose() {
    return SignaturePurpose.MASTER_WIRE_FEES;
  }

  fieldTypes() {
    return [
      ["h_wire_method", HashCode],
      ["start_date", AbsoluteTimeNbo],
      ["end_date", AbsoluteTimeNbo],
      ["wire_fee", AmountNbo],
      ["closing_fee", AmountNbo],
    ];
  }
}


/**
 * Low-level handle to an absolute time in network byte order (NBO).
 */
export class AbsoluteTimeNbo extends PackedArenaObject {
  static fromTalerString(s: string): AbsoluteTimeNbo {
    const x = new AbsoluteTimeNbo();
    x.alloc();
    const r = /Date\(([0-9]+)\)/;
    const m = r.exec(s);
    if (!m || m.length !== 2) {
      throw Error();
    }
    const n = parseInt(m[1], 10) * 1000000;
    // XXX: This only works up to 54 bit numbers.
    set64(x.nativePtr, n);
    return x;
  }

  static fromStampSeconds(stamp: number): AbsoluteTimeNbo {
    const x = new AbsoluteTimeNbo();
    x.alloc();
    // XXX: This only works up to 54 bit numbers.
    set64(x.nativePtr, stamp * 1000000);
    return x;
  }


  size() {
    return 8;
  }
}


// XXX: This only works up to 54 bit numbers.
function set64(p: number, n: number) {
  for (let i = 0; i < 8; ++i) {
    emsc().lib.setValue(p + (7 - i), n & 0xFF, "i8");
    n = Math.floor(n / 256);
  }
}

// XXX: This only works up to 54 bit numbers.
function set32(p: number, n: number) {
  for (let i = 0; i < 4; ++i) {
    emsc().lib.setValue(p + (3 - i), n & 0xFF, "i8");
    n = Math.floor(n / 256);
  }
}


/**
 * Low-level handle to an unsigned 64-bit value.
 */
export class UInt64 extends PackedArenaObject {
  static fromNumber(n: number): UInt64 {
    const x = new UInt64();
    x.alloc();
    set64(x.nativePtr, n);
    return x;
  }

  size() {
    return 8;
  }
}


/**
 * Low-level handle to an unsigned 32-bit value.
 */
export class UInt32 extends PackedArenaObject {
  static fromNumber(n: number): UInt32 {
    const x = new UInt32();
    x.alloc();
    set32(x.nativePtr, n);
    return x;
  }

  size() {
    return 4;
  }
}


/**
 * Argument to the constructor of [[DepositRequestPS]].
 */
export interface DepositRequestPS_Args {
  /**
   * Contract hash.
   */
  h_contract: HashCode;
  /**
   * Wire info hash.
   */
  h_wire: HashCode;
  /**
   * Timestamp.
   */
  timestamp: AbsoluteTimeNbo;
  /**
   * Refund deadline.
   */
  refund_deadline: AbsoluteTimeNbo;
  /**
   * Amount with fee.
   */
  amount_with_fee: AmountNbo;
  /**
   * Deposit fee.
   */
  deposit_fee: AmountNbo;
  /**
   * Merchant public key.
   */
  merchant: EddsaPublicKey;
  /**
   * Public key of the coin being deposited.
   */
  coin_pub: EddsaPublicKey;
}


/**
 * Low-level handle to a struct being signed over.
 */
export class DepositRequestPS extends SignatureStruct {
  constructor(w: DepositRequestPS_Args) {
    super(w);
  }

  purpose() {
    return SignaturePurpose.WALLET_COIN_DEPOSIT;
  }

  fieldTypes() {
    return [
      ["h_contract", HashCode],
      ["h_wire", HashCode],
      ["timestamp", AbsoluteTimeNbo],
      ["refund_deadline", AbsoluteTimeNbo],
      ["amount_with_fee", AmountNbo],
      ["deposit_fee", AmountNbo],
      ["merchant", EddsaPublicKey],
      ["coin_pub", EddsaPublicKey],
    ];
  }
}


interface CoinLinkSignaturePS_args {
  h_denom_pub: HashCode;
  old_coin_pub: EddsaPublicKey;
  transfer_pub: EcdhePublicKey;
  coin_envelope_hash: HashCode;
}


export class CoinLinkSignaturePS extends SignatureStruct {
  constructor(w: CoinLinkSignaturePS_args) {
    super(w);
  }

  purpose() {
    return SignaturePurpose.WALLET_COIN_LINK;
  }

  fieldTypes() {
    return [
      ["h_denom_pub", HashCode],
      ["old_coin_pub", EddsaPublicKey],
      ["transfer_pub", EcdhePublicKey],
      ["coin_envelope_hash", HashCode],
    ];
  }
}


/**
 * Arguments for constuctor of [[DenominationKeyValidityPS]].
 */
export interface DenominationKeyValidityPS_args {
  master: EddsaPublicKey;
  start: AbsoluteTimeNbo;
  expire_withdraw: AbsoluteTimeNbo;
  expire_spend: AbsoluteTimeNbo;
  expire_legal: AbsoluteTimeNbo;
  value: AmountNbo;
  fee_withdraw: AmountNbo;
  fee_deposit: AmountNbo;
  fee_refresh: AmountNbo;
  fee_refund: AmountNbo;
  denom_hash: HashCode;
}


/**
 * Low-level handle to a structure being signed over.
 */
export class DenominationKeyValidityPS extends SignatureStruct {
  constructor(w: DenominationKeyValidityPS_args) {
    super(w);
  }

  purpose() {
    return SignaturePurpose.MASTER_DENOMINATION_KEY_VALIDITY;
  }

  fieldTypes() {
    return [
      ["master", EddsaPublicKey],
      ["start", AbsoluteTimeNbo],
      ["expire_withdraw", AbsoluteTimeNbo],
      ["expire_spend", AbsoluteTimeNbo],
      ["expire_legal", AbsoluteTimeNbo],
      ["value", AmountNbo],
      ["fee_withdraw", AmountNbo],
      ["fee_deposit", AmountNbo],
      ["fee_refresh", AmountNbo],
      ["fee_refund", AmountNbo],
      ["denom_hash", HashCode],
    ];
  }
}

/**
 * Arguments to constructor of [[PaymentSignaturePS]].
 */
export interface PaymentSignaturePS_args {
  /**
   * Contract hash.
   */
  contract_hash: HashCode;
}


/**
 * Low-level handle to a structure being signed over.
 */
export class PaymentSignaturePS extends SignatureStruct {
  constructor(w: PaymentSignaturePS_args) {
    super(w);
  }

  purpose() {
    return SignaturePurpose.MERCHANT_PAYMENT_OK;
  }

  fieldTypes() {
    return [
      ["contract_hash", HashCode],
    ];
  }
}


/**
 * Low-level handle to an RsaPrivateKey.
 */
export class RsaPrivateKey extends MallocArenaObject {
  static fromCrock(s: string): RsaPrivateKey {
    return fromCrockDecoded(s, this, emsc().allocFuncs.rsa_private_key_decode);
  }

  static create(bitLen: number, a?: Arena): RsaPrivateKey {
    const obj = new RsaPrivateKey(a);
    obj.nativePtr = emsc().allocFuncs.rsa_private_key_create(bitLen);
    return obj;
  }

  toCrock() {
    return this.encode().toCrock();
  }


  getPublicKey(a?: Arena): RsaPublicKey {
    const obj = new RsaPublicKey(a);
    obj.nativePtr = emsc().allocFuncs.rsa_private_key_get_public(this.nativePtr);
    return obj;
  }

  destroy() {
    emsc().funcs.rsa_public_key_free(this.nativePtr);
    this.nativePtr = 0;
  }

  encode(arena?: Arena): ByteArray {
    return encode(this, emsc().allocFuncs.rsa_private_key_encode);
  }
}


/**
 * Low-level handle to an RsaPublicKey.
 */
export class RsaPublicKey extends MallocArenaObject {
  static fromCrock(s: string): RsaPublicKey {
    return fromCrockDecoded(s, this, emsc().allocFuncs.rsa_public_key_decode);
  }

  toCrock() {
    return this.encode().toCrock();
  }

  destroy() {
    emsc().funcs.rsa_public_key_free(this.nativePtr);
    this.nativePtr = 0;
  }

  encode(arena?: Arena): ByteArray {
    return encode(this, emsc().allocFuncs.rsa_public_key_encode);
  }
}


/**
 * Low-level handle to an EddsaSignature.
 */
export class EddsaSignature extends PackedArenaObject {
  size() {
    return 64;
  }
  static fromCrock(s: string): EddsaSignature {
    return fromCrock(s, this);
  }
}


/**
 * Low-level handle to an RsaSignature.
 */
export class RsaSignature extends MallocArenaObject {
  static fromCrock(s: string, a?: Arena) {
    return fromCrockDecoded(s, this, emsc().allocFuncs.rsa_signature_decode);
  }

  encode(arena?: Arena): ByteArray {
    return encode(this, emsc().allocFuncs.rsa_signature_encode);
  }

  destroy() {
    emsc().funcs.rsa_signature_free(this.nativePtr);
    this.nativePtr = 0;
  }
}


/**
 * Blind a value so it can be blindly signed.
 */
export function rsaBlind(hashCode: HashCode,
                         blindingKey: RsaBlindingKeySecret,
                         pkey: RsaPublicKey,
                         arena?: Arena): ByteArray|null {
  const buf_ptr_out = emsc().allocFuncs.malloc(PTR_SIZE);
  const buf_size_out = emsc().allocFuncs.malloc(PTR_SIZE);
  const res = emsc().allocFuncs.rsa_blind(hashCode.nativePtr,
                                          blindingKey.nativePtr,
                                          pkey.nativePtr,
                                          buf_ptr_out,
                                          buf_size_out);
  const buf_ptr = emsc().lib.getValue(buf_ptr_out, "*");
  const buf_size = emsc().lib.getValue(buf_size_out, "*");
  emsc().funcs.free(buf_ptr_out);
  emsc().funcs.free(buf_size_out);
  if (res !== GNUNET_OK) {
    // malicious key
    return null;
  }
  return new ByteArray(buf_size, buf_ptr, arena);
}


/**
 * Sign data using EdDSA.
 */
export function eddsaSign(purpose: EccSignaturePurpose,
                          priv: EddsaPrivateKey,
                          a?: Arena): EddsaSignature {
  const sig = new EddsaSignature(a);
  sig.alloc();
  const res = emsc().funcs.eddsa_sign(priv.nativePtr, purpose.nativePtr, sig.nativePtr);
  if (res < 1) {
    throw Error("EdDSA signing failed");
  }
  return sig;
}


/**
 * Verify EdDSA-signed data.
 */
export function eddsaVerify(purposeNum: number,
                            verify: EccSignaturePurpose,
                            sig: EddsaSignature,
                            pub: EddsaPublicKey,
                            a?: Arena): boolean {
  const r = emsc().funcs.eddsa_verify(purposeNum,
                                      verify.nativePtr,
                                      sig.nativePtr,
                                      pub.nativePtr);
  return r === GNUNET_OK;
}


export function rsaVerify(h: HashCode,
                          sig: RsaSignature,
                          pub: RsaPublicKey) {
  const r = emsc().funcs.rsa_verify(h.nativePtr,
                                    sig.nativePtr,
                                    pub.nativePtr);
  return r === GNUNET_OK;
}


/**
 * Unblind a blindly signed value.
 */
export function rsaUnblind(sig: RsaSignature,
                           bk: RsaBlindingKeySecret,
                           pk: RsaPublicKey,
                           a?: Arena): RsaSignature {
  const x = new RsaSignature(a);
  x.nativePtr = emsc().allocFuncs.rsa_unblind(sig.nativePtr,
                                              bk.nativePtr,
                                              pk.nativePtr);
  return x;
}


type TransferSecretP = HashCode;

/**
 * A fresh coin generated from a sed.
 */
export interface FreshCoin {
  /**
   * The coin's private key.
   */
  priv: EddsaPrivateKey;
  /**
   * The blinding key to use for withdrawal.
   */
  blindingKey: RsaBlindingKeySecret;
}

/**
 * Diffie-Hellman operation between an ECDHE private key
 * and an EdDSA public key.
 */
export function ecdhEddsa(priv: EcdhePrivateKey,
                          pub: EddsaPublicKey): HashCode {
  const h = new HashCode();
  h.alloc();
  const res = emsc().funcs.ecdh_eddsa(priv.nativePtr, pub.nativePtr, h.nativePtr);
  if (res !== GNUNET_OK) {
    throw Error("ecdh_eddsa failed");
  }
  return h;
}

export function rsaSignBlinded(priv: RsaPrivateKey,
                               msg: ByteArray): RsaSignature {
  const sig = new RsaSignature();
  sig.nativePtr = emsc().allocFuncs.rsa_sign_blinded (priv.nativePtr,
                                                      msg.nativePtr,
                                                      msg.size());
  return sig;
}



/**
 * Derive a fresh coin from the given seed.  Used during refreshing.
 */
export function setupFreshCoin(secretSeed: TransferSecretP,
                               coinIndex: number): FreshCoin {
  const priv = new EddsaPrivateKey();
  priv.isWeak = true;
  const blindingKey = new RsaBlindingKeySecret();
  blindingKey.isWeak = true;
  const buf = new ByteArray(priv.size() + blindingKey.size());

  emsc().funcs.setup_fresh_coin(secretSeed.nativePtr, coinIndex, buf.nativePtr);

  priv.nativePtr = buf.nativePtr;
  blindingKey.nativePtr = buf.nativePtr + priv.size();

  return { priv, blindingKey };
}