aboutsummaryrefslogtreecommitdiff
path: root/src/fs/fs_pseudonym.c
blob: 5e9c9816e6b89828453542d201e8bd24f26f4657 (plain) (blame)
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
/*
     This file is part of GNUnet
     (C) 2003, 2004, 2005, 2006, 2007, 2008, 2013 Christian Grothoff (and other contributing authors)

     GNUnet 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 2, or (at your
     option) any later version.

     GNUnet 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 GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
*/
/**
 * @file fs/fs_pseudonym.c
 * @brief pseudonym functions
 * @author Christian Grothoff
 *
 * TODO:
 * - all cryptographic operations are currently NOT implemented and
 *   provided by stubs that merely pretend to work!
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_fs_service.h"
#include <gcrypt.h>


#define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)

#define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)

#define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)

/**
 * Log an error message at log-level 'level' that indicates
 * a failure of the command 'cmd' with the message given
 * by gcry_strerror(rc).
 */
#define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0);

/**
 * Name of the directory which stores meta data for pseudonym
 */
#define PS_METADATA_DIR DIR_SEPARATOR_STR "data" DIR_SEPARATOR_STR "pseudonym" DIR_SEPARATOR_STR "metadata" DIR_SEPARATOR_STR

/**
 * Name of the directory which stores names for pseudonyms
 */
#define PS_NAMES_DIR    DIR_SEPARATOR_STR "data" DIR_SEPARATOR_STR "pseudonym" DIR_SEPARATOR_STR "names"    DIR_SEPARATOR_STR


/**
 * Configuration section we use.
 */
#define GNUNET_CLIENT_SERVICE_NAME "fs"


/* ************************* Disk operations (pseudonym data mgmt) **************** */

/**
 * Registered callbacks for discovery of pseudonyms.
 */
struct GNUNET_PSEUDONYM_DiscoveryHandle
{
  /**
   * This is a doubly linked list.
   */
  struct GNUNET_PSEUDONYM_DiscoveryHandle *next;

  /**
   * This is a doubly linked list.
   */
  struct GNUNET_PSEUDONYM_DiscoveryHandle *prev;

  /**
   * Function to call each time a pseudonym is discovered.
   */
  GNUNET_PSEUDONYM_Iterator callback;

  /**
   * Closure for callback.
   */
  void *callback_cls;
};


/**
 * Head of the linked list of functions to call when
 * new pseudonyms are added.
 */
static struct GNUNET_PSEUDONYM_DiscoveryHandle *disco_head;

/**
 * Tail of the linked list of functions to call when
 * new pseudonyms are added.
 */
static struct GNUNET_PSEUDONYM_DiscoveryHandle *disco_tail;


/**
 * Internal notification about new tracked URI.
 *
 * @param pseudonym public key of the pseudonym
 * @param md meta data to be written
 * @param rating rating of pseudonym
 */
static void
internal_notify (const struct GNUNET_PseudonymIdentifier *pseudonym,
                 const struct GNUNET_CONTAINER_MetaData *md, int rating)
{
  struct GNUNET_PSEUDONYM_DiscoveryHandle *pos;

  for (pos = disco_head; NULL != pos; pos = pos->next)
    pos->callback (pos->callback_cls, pseudonym, NULL, NULL, md, rating);
}


/**
 * Register callback to be invoked whenever we discover
 * a new pseudonym.
 * Will immediately call provided iterator callback for all
 * already discovered pseudonyms.
 *
 * @param cfg configuration to use
 * @param iterator iterator over pseudonym
 * @param iterator_cls point to a closure
 * @return registration handle
 */
struct GNUNET_PSEUDONYM_DiscoveryHandle *
GNUNET_PSEUDONYM_discovery_callback_register (const struct
					      GNUNET_CONFIGURATION_Handle *cfg,
                                              GNUNET_PSEUDONYM_Iterator iterator, 
					      void *iterator_cls)
{
  struct GNUNET_PSEUDONYM_DiscoveryHandle *dh;

  dh = GNUNET_malloc (sizeof (struct GNUNET_PSEUDONYM_DiscoveryHandle));
  dh->callback = iterator;
  dh->callback_cls = iterator_cls;
  GNUNET_CONTAINER_DLL_insert (disco_head, disco_tail, dh);
  GNUNET_PSEUDONYM_list_all (cfg, iterator, iterator_cls);
  return dh;
}


/**
 * Unregister pseudonym discovery callback.
 *
 * @param dh registration to unregister
 */
void
GNUNET_PSEUDONYM_discovery_callback_unregister (struct GNUNET_PSEUDONYM_DiscoveryHandle *dh)
{
  GNUNET_CONTAINER_DLL_remove (disco_head, disco_tail, dh);
  GNUNET_free (dh);
}


/**
 * Get the filename (or directory name) for the given
 * pseudonym identifier and directory prefix.
 *
 * @param cfg configuration to use
 * @param prefix path components to append to the private directory name
 * @param pseudonym the pseudonym, can be NULL
 * @return filename of the pseudonym (if pseudonym != NULL) or directory with the data (if pseudonym == NULL)
 */
static char *
get_data_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
                   const char *prefix, 
		   const struct GNUNET_PseudonymIdentifier *pseudonym)
{
  struct GNUNET_CRYPTO_HashAsciiEncoded enc;
  struct GNUNET_HashCode psid;

  if (NULL != pseudonym)
  {
    GNUNET_CRYPTO_hash (pseudonym,
			sizeof (struct GNUNET_PseudonymIdentifier),
			&psid);
    GNUNET_CRYPTO_hash_to_enc (&psid, &enc);
  }
  return GNUNET_DISK_get_home_filename (cfg, 
					GNUNET_CLIENT_SERVICE_NAME, prefix,
                                        (NULL == pseudonym) 
					? NULL 
					: (const char *) &enc,
                                        NULL);
}


/**
 * Get the filename (or directory name) for the given
 * hash code and directory prefix.
 *
 * @param cfg configuration to use
 * @param prefix path components to append to the private directory name
 * @param hc some hash code
 * @return filename of the pseudonym (if hc != NULL) or directory with the data (if hc == NULL)
 */
static char *
get_data_filename_hash (const struct GNUNET_CONFIGURATION_Handle *cfg,
			const char *prefix, 
			const struct GNUNET_HashCode *hc)
{
  struct GNUNET_CRYPTO_HashAsciiEncoded enc;

  if (NULL != hc)
    GNUNET_CRYPTO_hash_to_enc (hc, &enc);
  return GNUNET_DISK_get_home_filename (cfg, 
					GNUNET_CLIENT_SERVICE_NAME, prefix,
                                        (NULL == hc) 
					? NULL 
					: (const char *) &enc,
                                        NULL);
}


/**
 * Set the pseudonym metadata, rank and name.
 * Writes the pseudonym infomation into a file
 *
 * @param cfg overall configuration
 * @param pseudonym id of the pseudonym
 * @param name name to set. Must be the non-unique version of it.
 *        May be NULL, in which case it erases pseudonym's name!
 * @param md metadata to set
 *        May be NULL, in which case it erases pseudonym's metadata!
 * @param rank rank to assign
 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
 */
int
GNUNET_PSEUDONYM_set_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
			   const struct GNUNET_PseudonymIdentifier *pseudonym,
			   const char *name,
			   const struct GNUNET_CONTAINER_MetaData *md, 
			   int32_t rank)
{
  char *fn;
  struct GNUNET_BIO_WriteHandle *fileW;

  fn = get_data_filename (cfg, PS_METADATA_DIR, pseudonym);
  if (NULL == (fileW = GNUNET_BIO_write_open (fn)))
  {
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  }
  if ((GNUNET_OK != GNUNET_BIO_write (fileW, pseudonym, 
				      sizeof (struct GNUNET_PseudonymIdentifier))) ||
      (GNUNET_OK != GNUNET_BIO_write_int32 (fileW, rank)) ||
      (GNUNET_OK != GNUNET_BIO_write_string (fileW, name)) ||
      (GNUNET_OK != GNUNET_BIO_write_meta_data (fileW, md)))
  {
    (void) GNUNET_BIO_write_close (fileW);
    GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK != GNUNET_BIO_write_close (fileW))
  {
    GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  } 
  GNUNET_free (fn);
  /* create entry for pseudonym name in names */
  if (NULL != name)
    GNUNET_free_non_null (GNUNET_PSEUDONYM_name_uniquify (cfg, pseudonym, 
							  name, NULL));
  return GNUNET_OK;
}


/**
 * Read pseudonym infomation from a file
 *
 * @param cfg configuration to use
 * @param pseudonym hash code of a pseudonym
 * @param meta meta data to be read from a file
 * @param rank rank of a pseudonym
 * @param ns_name name of a pseudonym
 * @return GNUNET_OK on success, GNUNET_SYSERR on error
 */
static int
read_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
           const struct GNUNET_PseudonymIdentifier *pseudonym,
           struct GNUNET_CONTAINER_MetaData **meta,
	   int32_t *rank,
           char **ns_name)
{
  struct GNUNET_PseudonymIdentifier pd;
  char *fn;
  char *emsg;
  struct GNUNET_BIO_ReadHandle *fileR;

  fn = get_data_filename (cfg, PS_METADATA_DIR, pseudonym);
  if (GNUNET_YES !=
      GNUNET_DISK_file_test (fn))
  {
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  }
  if (NULL == (fileR = GNUNET_BIO_read_open (fn)))
  {
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  }
  emsg = NULL;
  *ns_name = NULL;
  if ( (GNUNET_OK != GNUNET_BIO_read (fileR, "pseudonym", &pd, sizeof (pd))) ||
       (0 != memcmp (&pd, pseudonym, sizeof (pd))) ||
       (GNUNET_OK != GNUNET_BIO_read_int32 (fileR, rank)) ||
       (GNUNET_OK !=
	GNUNET_BIO_read_string (fileR, "Read string error!", ns_name, 200)) ||
       (GNUNET_OK !=
       GNUNET_BIO_read_meta_data (fileR, "Read meta data error!", meta)) )
  {
    (void) GNUNET_BIO_read_close (fileR, &emsg);
    GNUNET_free_non_null (emsg);
    GNUNET_free_non_null (*ns_name);
    *ns_name = NULL;
    GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK != GNUNET_BIO_read_close (fileR, &emsg))
  {
    LOG (GNUNET_ERROR_TYPE_WARNING,
         _("Failed to parse metadata about pseudonym from file `%s': %s\n"), fn,
         emsg);
    GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
    GNUNET_CONTAINER_meta_data_destroy (*meta);
    *meta = NULL;
    GNUNET_free_non_null (*ns_name);
    *ns_name = NULL;
    GNUNET_free_non_null (emsg);
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  }
  GNUNET_free (fn);
  return GNUNET_OK;
}


/**
 * Return unique variant of the namespace name.  Use it after
 * GNUNET_PSEUDONYM_get_info() to make sure that name is unique.
 *
 * @param cfg configuration
 * @param pseudonym public key of the pseudonym
 * @param name name to uniquify
 * @param suffix if not NULL, filled with the suffix value
 * @return NULL on failure (should never happen), name on success.
 *         Free the name with GNUNET_free().
 */
char *
GNUNET_PSEUDONYM_name_uniquify (const struct GNUNET_CONFIGURATION_Handle *cfg,
				const struct GNUNET_PseudonymIdentifier *pseudonym,
				const char *name,
				unsigned int *suffix)
{
  struct GNUNET_HashCode nh;
  struct GNUNET_PseudonymIdentifier pi;
  uint64_t len;
  char *fn;
  struct GNUNET_DISK_FileHandle *fh;
  unsigned int i;
  unsigned int idx;
  char *ret;
  struct stat sbuf;

  GNUNET_CRYPTO_hash (name, strlen (name), &nh);
  fn = get_data_filename_hash (cfg, PS_NAMES_DIR, &nh);
  len = 0;
  if (0 == STAT (fn, &sbuf))
    GNUNET_break (GNUNET_OK == GNUNET_DISK_file_size (fn, &len, GNUNET_YES, GNUNET_YES));
  fh = GNUNET_DISK_file_open (fn,
                              GNUNET_DISK_OPEN_CREATE |
                              GNUNET_DISK_OPEN_READWRITE,
                              GNUNET_DISK_PERM_USER_READ |
                              GNUNET_DISK_PERM_USER_WRITE);
  i = 0;
  idx = -1;
  while ((len >= sizeof (struct GNUNET_PseudonymIdentifier)) &&
         (sizeof (struct GNUNET_PseudonymIdentifier) ==
          GNUNET_DISK_file_read (fh, &pi, sizeof (struct GNUNET_PseudonymIdentifier))))
  {
    if (0 == memcmp (&pi, pseudonym, sizeof (struct GNUNET_PseudonymIdentifier)))
    {
      idx = i;
      break;
    }
    i++;
    len -= sizeof (struct GNUNET_HashCode);
  }
  if (-1 == idx)
  {
    idx = i;
    if (sizeof (struct GNUNET_PseudonymIdentifier) !=
        GNUNET_DISK_file_write (fh, pseudonym, sizeof (struct GNUNET_PseudonymIdentifier)))
      LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "write", fn);
  }
  GNUNET_DISK_file_close (fh);
  ret = GNUNET_malloc (strlen (name) + 32);
  GNUNET_snprintf (ret, strlen (name) + 32, "%s-%u", name, idx);
  if (suffix != NULL)
    *suffix = idx;
  GNUNET_free (fn);
  return ret;
}


/**
 * Get namespace name, metadata and rank
 * This is a wrapper around internal read_info() call, and ensures that
 * returned data is not invalid (not NULL).
 *
 * @param cfg configuration
 * @param pseudonym public key of the pseudonym
 * @param ret_meta a location to store metadata pointer. NULL, if metadata
 *        is not needed. Destroy with GNUNET_CONTAINER_meta_data_destroy().
 * @param ret_rank a location to store rank. NULL, if rank not needed.
 * @param ret_name a location to store human-readable name. Name is not unique.
 *        NULL, if name is not needed. Free with GNUNET_free().
 * @param name_is_a_dup is set to GNUNET_YES, if ret_name was filled with
 *        a duplicate of a "no-name" placeholder
 * @return GNUNET_OK on success. GNUENT_SYSERR if the data was
 *         unobtainable (in that case ret_* are filled with placeholders - 
 *         empty metadata container, rank -1 and a "no-name" name).
 */
int
GNUNET_PSEUDONYM_get_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
			   const struct GNUNET_PseudonymIdentifier *pseudonym, 
			   struct GNUNET_CONTAINER_MetaData **ret_meta,
			   int32_t *ret_rank, 
			   char **ret_name, 
			   int *name_is_a_dup)
{
  struct GNUNET_CONTAINER_MetaData *meta;
  char *name;
  int32_t rank = -1;

  meta = NULL;
  name = NULL;
  if (GNUNET_OK == read_info (cfg, pseudonym, &meta, &rank, &name))
  {
    if ((meta != NULL) && (name == NULL))
      name =
          GNUNET_CONTAINER_meta_data_get_first_by_types (meta,
                                                         EXTRACTOR_METATYPE_TITLE,
                                                         EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
                                                         EXTRACTOR_METATYPE_FILENAME,
                                                         EXTRACTOR_METATYPE_DESCRIPTION,
                                                         EXTRACTOR_METATYPE_SUBJECT,
                                                         EXTRACTOR_METATYPE_PUBLISHER,
                                                         EXTRACTOR_METATYPE_AUTHOR_NAME,
                                                         EXTRACTOR_METATYPE_COMMENT,
                                                         EXTRACTOR_METATYPE_SUMMARY,
                                                         -1);
    if (ret_name != NULL)
    {
      if (name == NULL)
      {
        name = GNUNET_strdup (_("no-name"));
        if (name_is_a_dup != NULL)
          *name_is_a_dup = GNUNET_YES;
      }
      else if (name_is_a_dup != NULL)
        *name_is_a_dup = GNUNET_NO;
      *ret_name = name;
    }
    else if (name != NULL)
      GNUNET_free (name);

    if (ret_meta != NULL)
    {
      if (meta == NULL)
        meta = GNUNET_CONTAINER_meta_data_create ();
      *ret_meta = meta;
    }
    else if (meta != NULL)
      GNUNET_CONTAINER_meta_data_destroy (meta);

    if (ret_rank != NULL)
      *ret_rank = rank;

    return GNUNET_OK;
  }
  if (ret_name != NULL)
    *ret_name = GNUNET_strdup (_("no-name"));
  if (ret_meta != NULL)
    *ret_meta = GNUNET_CONTAINER_meta_data_create ();
  if (ret_rank != NULL)
    *ret_rank = -1;
  if (name_is_a_dup != NULL)
    *name_is_a_dup = GNUNET_YES;
  return GNUNET_SYSERR;
}


/**
 * Get the namespace ID belonging to the given namespace name.
 *
 * @param cfg configuration to use
 * @param ns_uname unique (!) human-readable name for the namespace
 * @param pseudonym set to public key of pseudonym based on 'ns_uname'
 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
 */
int
GNUNET_PSEUDONYM_name_to_id (const struct GNUNET_CONFIGURATION_Handle *cfg,
			     const char *ns_uname, 
			     struct GNUNET_PseudonymIdentifier *pseudonym)
{
  size_t slen;
  uint64_t len;
  unsigned int idx;
  char *name;
  struct GNUNET_HashCode nh;
  char *fn;
  struct GNUNET_DISK_FileHandle *fh;

  idx = -1;
  slen = strlen (ns_uname);
  while ((slen > 0) && (1 != SSCANF (&ns_uname[slen - 1], "-%u", &idx)))
    slen--;
  if (0 == slen)
    return GNUNET_SYSERR;
  name = GNUNET_strdup (ns_uname);
  name[slen - 1] = '\0';

  GNUNET_CRYPTO_hash (name, strlen (name), &nh);
  GNUNET_free (name);
  fn = get_data_filename_hash (cfg, PS_NAMES_DIR, &nh);

  if ((GNUNET_OK != GNUNET_DISK_file_test (fn) ||
       (GNUNET_OK != GNUNET_DISK_file_size (fn, &len, GNUNET_YES, GNUNET_YES))) ||
      ((idx + 1) * sizeof (struct GNUNET_PseudonymIdentifier) > len))
  {
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  }
  fh = GNUNET_DISK_file_open (fn,
                              GNUNET_DISK_OPEN_CREATE |
                              GNUNET_DISK_OPEN_READWRITE,
                              GNUNET_DISK_PERM_USER_READ |
                              GNUNET_DISK_PERM_USER_WRITE);
  GNUNET_free (fn);
  if (GNUNET_SYSERR ==
      GNUNET_DISK_file_seek (fh, idx * sizeof (struct GNUNET_PseudonymIdentifier),
			     GNUNET_DISK_SEEK_SET))
  {
    GNUNET_DISK_file_close (fh);
    return GNUNET_SYSERR;
  }
  if (sizeof (struct GNUNET_PseudonymIdentifier) !=
      GNUNET_DISK_file_read (fh, pseudonym, sizeof (struct GNUNET_PseudonymIdentifier)))
  {
    GNUNET_DISK_file_close (fh);
    return GNUNET_SYSERR;
  }
  GNUNET_DISK_file_close (fh);
  return GNUNET_OK;
}



/**
 * struct used to list the pseudonym
 */
struct ListPseudonymClosure
{

  /**
   * iterator over pseudonym
   */
  GNUNET_PSEUDONYM_Iterator iterator;

  /**
   * Closure for iterator.
   */
  void *iterator_cls;

  /**
   * Configuration to use.
   */
  const struct GNUNET_CONFIGURATION_Handle *cfg;
};



/**
 * Helper function to list all available pseudonyms
 *
 * @param cls point to a struct ListPseudonymClosure
 * @param fullname name of pseudonym
 */
static int
list_pseudonym_helper (void *cls, const char *fullname)
{
  struct ListPseudonymClosure *lpc = cls;
  struct GNUNET_PseudonymIdentifier pd;
  char *emsg;
  struct GNUNET_BIO_ReadHandle *fileR;
  int32_t rank;
  char *ns_name;
  struct GNUNET_CONTAINER_MetaData *meta;
  int ret; 
  char *name_unique;

  if (NULL == (fileR = GNUNET_BIO_read_open (fullname)))
    return GNUNET_SYSERR;
  emsg = NULL;
  ns_name = NULL;
  if ( (GNUNET_OK != GNUNET_BIO_read (fileR, "pseudonym", &pd, sizeof (pd))) ||
       (GNUNET_OK != GNUNET_BIO_read_int32 (fileR, &rank)) ||
       (GNUNET_OK !=
	GNUNET_BIO_read_string (fileR, "Read string error!", &ns_name, 200)) ||
       (GNUNET_OK !=
       GNUNET_BIO_read_meta_data (fileR, "Read meta data error!", &meta)) )
  {
    (void) GNUNET_BIO_read_close (fileR, &emsg);
    GNUNET_free_non_null (emsg);
    GNUNET_free_non_null (ns_name);
    GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fullname));
    return GNUNET_SYSERR;
  }
  if (NULL == ns_name)
    ns_name = GNUNET_strdup (_("no-name"));
  if (GNUNET_OK != GNUNET_BIO_read_close (fileR, &emsg))
  {
    LOG (GNUNET_ERROR_TYPE_WARNING,
         _("Failed to parse metadata about pseudonym from file `%s': %s\n"), fullname,
         emsg);
    GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fullname));
    GNUNET_CONTAINER_meta_data_destroy (meta);
    GNUNET_free (ns_name);
    GNUNET_free_non_null (emsg);
    return GNUNET_SYSERR;
  }
  ret = GNUNET_OK;
  name_unique = GNUNET_PSEUDONYM_name_uniquify (lpc->cfg, &pd, ns_name, NULL);
  if (NULL != lpc->iterator)
    ret = lpc->iterator (lpc->iterator_cls, &pd, ns_name, name_unique, meta, rank);
  GNUNET_free (ns_name);
  GNUNET_free_non_null (name_unique);
  GNUNET_CONTAINER_meta_data_destroy (meta);
  return ret;
}


/**
 * List all available pseudonyms.
 *
 * @param cfg overall configuration
 * @param iterator function to call for each pseudonym
 * @param iterator_cls closure for iterator
 * @return number of pseudonyms found
 */
int
GNUNET_PSEUDONYM_list_all (const struct GNUNET_CONFIGURATION_Handle *cfg,
                           GNUNET_PSEUDONYM_Iterator iterator, 
			   void *iterator_cls)
{
  struct ListPseudonymClosure cls;
  char *fn;
  int ret;

  cls.iterator = iterator;
  cls.iterator_cls = iterator_cls;
  cls.cfg = cfg;
  fn = get_data_filename (cfg, PS_METADATA_DIR, NULL);
  GNUNET_assert (fn != NULL);
  GNUNET_DISK_directory_create (fn);
  ret = GNUNET_DISK_directory_scan (fn, &list_pseudonym_helper, &cls);
  GNUNET_free (fn);
  return ret;
}


/**
 * Change the rank of a pseudonym.
 *
 * @param cfg overall configuration
 * @param pseudonym the pseudonym
 * @param delta by how much should the rating be changed?
 * @return new rating of the pseudonym
 */
int
GNUNET_PSEUDONYM_rank (const struct GNUNET_CONFIGURATION_Handle *cfg,
                       const struct GNUNET_PseudonymIdentifier *pseudonym, 
		       int32_t delta)
{
  struct GNUNET_CONTAINER_MetaData *meta;
  int ret;
  int32_t rank;
  char *name;

  name = NULL;
  ret = read_info (cfg, pseudonym, &meta, &rank, &name);
  if (ret == GNUNET_SYSERR)
  {
    rank = 0;
    meta = GNUNET_CONTAINER_meta_data_create ();
  }
  rank += delta;
  GNUNET_PSEUDONYM_set_info (cfg, pseudonym, name, meta, rank);
  GNUNET_CONTAINER_meta_data_destroy (meta);
  GNUNET_free_non_null (name);
  return rank;
}


/**
 * Add a pseudonym to the set of known pseudonyms.
 * For all pseudonym advertisements that we discover
 * FS should automatically call this function.
 *
 * @param cfg overall configuration
 * @param pseudonym the pseudonym to add
 * @param meta metadata for the pseudonym
 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
 */
int
GNUNET_PSEUDONYM_add (const struct GNUNET_CONFIGURATION_Handle *cfg,
                      const struct GNUNET_PseudonymIdentifier *pseudonym,
                      const struct GNUNET_CONTAINER_MetaData *meta)
{
  char *name;
  int32_t rank;
  struct GNUNET_CONTAINER_MetaData *old;
  char *fn;
  struct stat sbuf;
  int ret;

  rank = 0;
  fn = get_data_filename (cfg, PS_METADATA_DIR, pseudonym);
  GNUNET_assert (fn != NULL);

  if ((0 == STAT (fn, &sbuf)) &&
      (GNUNET_OK == read_info (cfg, pseudonym, &old, &rank, &name)))
  {
    GNUNET_CONTAINER_meta_data_merge (old, meta);
    ret = GNUNET_PSEUDONYM_set_info (cfg, pseudonym, name, old, rank);
    GNUNET_CONTAINER_meta_data_destroy (old);
    GNUNET_free_non_null (name);
  }
  else
  {
    ret = GNUNET_PSEUDONYM_set_info (cfg, pseudonym, NULL, meta, rank);
  }
  GNUNET_free (fn);
  internal_notify (pseudonym, meta, rank);
  return ret;
}


/* ***************************** cryptographic operations ************************* */

/**
 * Handle for a pseudonym (private key).
 */
struct GNUNET_PseudonymHandle
{
  /**
   * 256-bit 'd' secret value (mod 'n', where n is 256-bit for NIST P-256).
   */
  unsigned char d[256 / 8];

  /**
   * Public key corresponding to the private key.
   */
  struct GNUNET_PseudonymIdentifier public_key;
};


/**
 * If target != size, move target bytes to the end of the size-sized
 * buffer and zero out the first target-size bytes.
 *
 * @param buf original buffer
 * @param size number of bytes in the buffer
 * @param target target size of the buffer
 */
static void
adjust (unsigned char *buf, size_t size, size_t target)
{
  if (size < target)
  {
    memmove (&buf[target - size], buf, size);
    memset (buf, 0, target - size);
  }
}


/**
 * Extract values from an S-expression.
 *
 * @param array where to store the result(s)
 * @param sexp S-expression to parse
 * @param topname top-level name in the S-expression that is of interest
 * @param elems names of the elements to extract
 * @return 0 on success
 */
static int
key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
               const char *elems)
{
  gcry_sexp_t list;
  gcry_sexp_t l2;
  const char *s;
  unsigned int i;
  unsigned int idx;

  if (! (list = gcry_sexp_find_token (sexp, topname, 0)))
    return 1;  
  l2 = gcry_sexp_cadr (list);
  gcry_sexp_release (list);
  list = l2;
  if (! list)  
    return 2;
  idx = 0;
  for (s = elems; *s; s++, idx++)
  {
    if (! (l2 = gcry_sexp_find_token (list, s, 1)))
    {
      for (i = 0; i < idx; i++)
      {
        gcry_free (array[i]);
        array[i] = NULL;
      }
      gcry_sexp_release (list);
      return 3;                 /* required parameter not found */
    }
    array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
    gcry_sexp_release (l2);
    if (! array[idx])
    {
      for (i = 0; i < idx; i++)
      {
        gcry_free (array[i]);
        array[i] = NULL;
      }
      gcry_sexp_release (list);
      return 4;                 /* required parameter is invalid */
    }
  }
  gcry_sexp_release (list);
  return 0;
}


/**
 * Create a pseudonym.
 *
 * @param filename name of the file to use for storage, NULL for in-memory only
 * @return handle to the private key of the pseudonym
 */
struct GNUNET_PseudonymHandle *
GNUNET_PSEUDONYM_create (const char *filename)
{
  struct GNUNET_PseudonymHandle *ph;
  ssize_t ret;
  gcry_sexp_t r_key;
  gcry_sexp_t params;
  gcry_ctx_t ctx;
  gcry_mpi_point_t q;
  gcry_mpi_t q_x;
  gcry_mpi_t q_y;
  gcry_error_t rc;
  gcry_mpi_t d;
  size_t size;

  ph = GNUNET_malloc (sizeof (struct GNUNET_PseudonymHandle));
  if ( (NULL != filename) &&
       (GNUNET_YES == GNUNET_DISK_file_test (filename)) )
  {
    ret = GNUNET_DISK_fn_read (filename, ph, 
			       sizeof (struct GNUNET_PseudonymHandle));
    /* Note: we don't do any validation here, maybe we should? */
    if (sizeof (struct GNUNET_PseudonymHandle) == ret)
      return ph;
  }  
  if (0 != (rc = gcry_sexp_build (&params, NULL,
                                  "(genkey(ecdsa(curve \"NIST P-256\")))")))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
    return NULL;
  }
  if (0 != (rc = gcry_pk_genkey (&r_key, params)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
    gcry_sexp_release (r_key);
    return NULL;
  }
  /* extract "d" (secret key) from r_key */
  rc = key_from_sexp (&d, r_key, "private-key", "d");
  if (0 != rc)
    rc = key_from_sexp (&d, r_key, "private-key", "d");
  if (0 != rc)
    rc = key_from_sexp (&d, r_key, "ecc", "d");
  if (0 != rc)
  {
    gcry_sexp_release (r_key);
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
    return NULL;
  }
  size = sizeof (ph->d);
  GNUNET_assert (0 ==
                 gcry_mpi_print (GCRYMPI_FMT_USG, ph->d, size, &size,
                                 d));
  gcry_mpi_release (d);
  adjust (ph->d, size, sizeof (ph->d));

  /* extract 'q' (public key) from r_key */
  if (0 != (rc = gcry_mpi_ec_new (&ctx, r_key, NULL)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);  /* erroff gives more info */
    gcry_sexp_release (r_key);
    return NULL;
  }  
  gcry_sexp_release (r_key);
  q = gcry_mpi_ec_get_point ("q", ctx, 0);
  q_x = gcry_mpi_new (256);
  q_y = gcry_mpi_new (256);
  gcry_mpi_ec_get_affine (q_x, q_y, q, ctx);
  gcry_mpi_point_release (q);

  /* store q_x/q_y in public key */
  size = sizeof (ph->public_key.q_x);  
  if (0 !=
      gcry_mpi_print (GCRYMPI_FMT_USG, ph->public_key.q_x, size, &size,
		      q_x))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_print", rc);
    gcry_mpi_release (q_x);
    gcry_mpi_release (q_y);
    return NULL;

  }
  adjust (ph->public_key.q_x, size, sizeof (ph->public_key.q_x));
  gcry_mpi_release (q_x);

  size = sizeof (ph->public_key.q_y);  
  if (0 !=
      gcry_mpi_print (GCRYMPI_FMT_USG, ph->public_key.q_y, size, &size,
		      q_y))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_print", rc);
    gcry_mpi_release (q_y);
    return NULL;
  }
  adjust (ph->public_key.q_y, size, sizeof (ph->public_key.q_y));
  gcry_mpi_release (q_y);

  /* write to disk */
  if (NULL != filename)
  {
    ret = GNUNET_DISK_fn_write (filename, ph, sizeof (struct GNUNET_PseudonymHandle),
				GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
    if (sizeof (struct GNUNET_PseudonymHandle) != ret)
    {
      GNUNET_free (ph);
      return NULL;
    }
  }
  return ph;
}


/**
 * Create a pseudonym, from a file that must already exist.
 *
 * @param filename name of the file to use for storage, NULL for in-memory only
 * @return handle to the private key of the pseudonym
 */
struct GNUNET_PseudonymHandle *
GNUNET_PSEUDONYM_create_from_existing_file (const char *filename)
{
  struct GNUNET_PseudonymHandle *ph;
  ssize_t ret;

  ph = GNUNET_malloc (sizeof (struct GNUNET_PseudonymHandle));
  ret = GNUNET_DISK_fn_read (filename, ph, 
			     sizeof (struct GNUNET_PseudonymHandle));
  if (sizeof (struct GNUNET_PseudonymHandle) != ret)
  {
    GNUNET_free (ph);
    return NULL;
  }
  /* Note: we don't do any validation here; maybe we should? */
  return ph;
}


/**
 * Get the handle for the 'anonymous' pseudonym shared by all users.
 * That pseudonym uses a fixed 'secret' for the private key; this
 * construction is useful to make anonymous and pseudonymous APIs
 * (and packets) indistinguishable on the network.  See #2564.
 *
 * @return handle to the (non-secret) private key of the 'anonymous' pseudonym
 */
struct GNUNET_PseudonymHandle *
GNUNET_PSEUDONYM_get_anonymous_pseudonym_handle ()
{
  struct GNUNET_PseudonymHandle *ph;

  ph = GNUNET_malloc (sizeof (struct GNUNET_PseudonymHandle));
  /* Note if we use 'd=0' for the anonymous handle (as per#2564),
     then I believe the public key should be also zero, as Q=0P=0;
     so setting everything to all-zeros (as per GNUNET_malloc)
     should be all that is needed here).
  */
  return ph;
}


/**
 * Destroy a pseudonym handle.  Does NOT remove the private key from
 * the disk.
 *
 * @param ph pseudonym handle to destroy
 */
void
GNUNET_PSEUDONYM_destroy (struct GNUNET_PseudonymHandle *ph)
{
  GNUNET_free (ph);
}


/**
 * Convert the data specified in the given purpose argument to an
 * S-expression suitable for signature operations.
 *
 * @param purpose data to convert
 * @return converted s-expression
 */
static gcry_sexp_t
data_to_pkcs1 (const struct GNUNET_PseudonymSignaturePurpose *purpose)
{
  struct GNUNET_CRYPTO_ShortHashCode hc;
  size_t bufSize;
  gcry_sexp_t data;

  GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
#define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
  bufSize = strlen (FORMATSTRING) + 1;
  {
    char buff[bufSize];

    memcpy (buff, FORMATSTRING, bufSize);
    memcpy (&buff
	    [bufSize -
	     strlen
	     ("01234567890123456789012345678901))")
	     - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
    GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
  }
#undef FORMATSTRING
  return data;
}

gcry_ctx_t xctx;


/**
 * Cryptographically sign some data with the pseudonym.
 *
 * @param ph private key 'd' used for signing (corresponds to 'x' in #2564)
 * @param purpose data to sign
 * @param seed hash of the plaintext of the data that we are signing, 
 *             used for deterministic PRNG for anonymous signing;
 *             corresponds to 'k' in section 2.7 of #2564
 * @param signing_key modifier to apply to the private key for signing ('h');
 *                    see section 2.3 of #2564.
 * @param signature where to store the signature
 * @return GNUNET_SYSERR on failure
 */
int 
GNUNET_PSEUDONYM_sign (struct GNUNET_PseudonymHandle *ph,
		       const struct GNUNET_PseudonymSignaturePurpose *purpose,
		       const struct GNUNET_HashCode *seed,
		       const struct GNUNET_HashCode *signing_key,
		       struct GNUNET_PseudonymSignature *signature)
{
  size_t size;
  size_t erroff;
  gcry_mpi_t d;
  gcry_mpi_t k;
  gcry_mpi_t h;
  gcry_mpi_t dh;
  gcry_mpi_t n; /* n from P-256 */
  gcry_sexp_t spriv;
  gcry_sexp_t data;
  gcry_sexp_t result;
  gcry_mpi_t rs[2];
  int rc;

  /* get private key 'd' from pseudonym */
  size = sizeof (ph->d);
  if (0 != (rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
				&ph->d,
				size, &size)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    return GNUNET_SYSERR;
  }
  /* get 'x' value from signing key */
  size = sizeof (struct GNUNET_HashCode);
  if (0 != (rc = gcry_mpi_scan (&h, GCRYMPI_FMT_USG,
				signing_key,
				size, &size)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    gcry_mpi_release (d);
    return GNUNET_SYSERR;
  } 
  
  /* initialize 'n' from P-256; hex copied from libgcrypt code */
  if (0 != (rc = gcry_mpi_scan (&n, GCRYMPI_FMT_HEX, 
				"0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", 0, NULL)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    gcry_mpi_release (d);
    gcry_mpi_release (h);
    return GNUNET_SYSERR;
  }

  /* calculate dx = d + h mod n */
  dh = gcry_mpi_new (256);
  gcry_mpi_addm (dh, d, h, n);  
  // gcry_mpi_release (d);
  // gcry_mpi_release (h);
  gcry_mpi_release (n);

  if (1) {
    gcry_mpi_point_t g;
    gcry_mpi_point_t v;
    gcry_mpi_point_t hg;
    gcry_mpi_point_t q;
    gcry_mpi_t v_x;
    gcry_mpi_t v_y;

    gcry_mpi_ec_new (&xctx, NULL, "NIST P-256");
    g = gcry_mpi_ec_get_point ("g", xctx, 0);

    hg = gcry_mpi_point_new (0);
    gcry_mpi_ec_mul (hg, h, g, xctx);
    fprintf (stderr, "\nExpected verification hG value:\n");
    v_x = gcry_mpi_new (256);
    v_y = gcry_mpi_new (256);
    gcry_mpi_ec_get_affine (v_x, v_y, hg, xctx);
    gcry_mpi_dump (v_x);
    gcry_mpi_dump (v_y);

    q = gcry_mpi_point_new (0);    
    gcry_mpi_ec_mul (q, d, g, xctx);
    fprintf (stderr, "\nExpected verification q value:\n");
    gcry_mpi_ec_get_affine (v_x, v_y, q, xctx);
    gcry_mpi_dump (v_x);
    gcry_mpi_dump (v_y);

    v = gcry_mpi_point_new (0);
    gcry_mpi_ec_add (v, q, hg, xctx);
    gcry_mpi_ec_get_affine (v_x, v_y, v, xctx);
    fprintf (stderr, "\nExpected verification key public point value V := q + hG:\n");
    gcry_mpi_dump (v_x);
    gcry_mpi_dump (v_y);
    fprintf (stderr, "\n");
    
  }

  
  /* now build sexpression with the signing key */
  if (0 != (rc = gcry_sexp_build (&spriv, &erroff,
				  "(private-key(ecdsa(curve \"NIST P-256\")(d %m)))",
				  dh)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
    gcry_mpi_release (dh);
    return GNUNET_SYSERR;
  }
  gcry_mpi_release (dh);
  /* prepare data for signing */
  data = data_to_pkcs1 (purpose);
  
  /* get 'k' value from seed, if available */
  if (NULL != seed)
  {
    size = sizeof (struct GNUNET_HashCode);
    if (0 != (rc = gcry_mpi_scan (&k, GCRYMPI_FMT_USG,
				  seed,
				  size, &size)))
    {
      LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
      return GNUNET_SYSERR;
    }
  }

  /* actually create signature */
  /* FIXME: need API to pass 'k' if 'seed' was non-NULL! */
  if (0 != (rc = gcry_pk_sign (&result, data, spriv)))
  {
    LOG (GNUNET_ERROR_TYPE_WARNING,
         _("ECC signing failed at %s:%d: %s\n"), __FILE__,
         __LINE__, gcry_strerror (rc));
    gcry_sexp_release (data);
    gcry_sexp_release (spriv);
    if (NULL != seed)
      gcry_mpi_release (k);
    memset (signature, 0, sizeof (struct GNUNET_PseudonymSignature));
    return GNUNET_SYSERR;
  }
  if (NULL != seed)
    gcry_mpi_release (k);
  gcry_sexp_release (data);
  gcry_sexp_release (spriv);


  /* extract 'r' and 's' values from sexpression 'result' and store in 'signature' */
  if (0 != (rc = key_from_sexp (rs, result, "sig-val", "rs")))
  {
    GNUNET_break (0);
    gcry_sexp_release (result);
    return GNUNET_SYSERR;
  }
  gcry_sexp_release (result);
  size = sizeof (signature->sig_r);
  if (0 != (rc = gcry_mpi_print (GCRYMPI_FMT_USG, signature->sig_r, size,
                                 &size, rs[0])))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_print", rc);
    gcry_mpi_release (rs[0]);
    gcry_mpi_release (rs[1]);
    return GNUNET_SYSERR;
  }
  gcry_mpi_release (rs[0]);
  size = sizeof (signature->sig_s);
  if (0 != (rc = gcry_mpi_print (GCRYMPI_FMT_USG, signature->sig_s, size,
                                 &size, rs[1])))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_print", rc);
    gcry_mpi_release (rs[1]);
    return GNUNET_SYSERR;
  }
  gcry_mpi_release (rs[1]);
  return GNUNET_OK;
}


/**
 * Get an ECC context (with Q set to the respective public key) from
 * a pseudonym.
 *
 * @param pseudonym with information on 'q'
 * @return curve context
 */
static gcry_ctx_t 
get_context_from_pseudonym (struct GNUNET_PseudonymIdentifier *pseudonym)
{
  gcry_ctx_t ctx;
  gcry_mpi_t ONE;
  gcry_mpi_t q_x;
  gcry_mpi_t q_y;
  gcry_mpi_point_t q;
  size_t size;
  int rc;

  /* extract 'q' from pseudonym */
  size = sizeof (pseudonym->q_x);
  if (0 != (rc = gcry_mpi_scan (&q_x, GCRYMPI_FMT_USG, pseudonym->q_x, size, &size)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    return NULL;
  }
  size = sizeof (pseudonym->q_y);
  if (0 != (rc = gcry_mpi_scan (&q_y, GCRYMPI_FMT_USG, pseudonym->q_y, size, &size)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    gcry_mpi_release (q_x);
    return NULL;
  }
  q = gcry_mpi_point_new (256);
  ONE = gcry_mpi_new (1);
  gcry_mpi_set_ui (ONE, 1);
  gcry_mpi_point_set (q, q_x, q_y, ONE); /* FIXME: convenience function 'set_affine'? */
  gcry_mpi_release (ONE);
  gcry_mpi_release (q_x);
  gcry_mpi_release (q_y);

  /* create basic ECC context */
  if (0 != (rc = gcry_mpi_ec_new (&ctx, NULL, "NIST P-256")))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);  /* erroff gives more info */
    gcry_mpi_point_release (q);
    return NULL;
  }  
  /* initialize 'ctx' with 'q' */
  gcry_mpi_ec_set_point ("q", q, ctx);
  gcry_mpi_point_release (q);
  return ctx;
}


/**
 * Given a pseudonym and a signing key, derive the corresponding public
 * key that would be used to verify the resulting signature.
 *
 * @param pseudonym the public key (dQ in ECDSA)
 * @param signing_key input to derive 'h' (see section 2.4 of #2564)
 * @param verification_key resulting public key to verify the signature
 *        created from the '(d+h)' of 'pseudonym' and the 'signing_key';
 *        the value stored here can then be given to GNUNET_PSEUDONYM_verify.
 * @return GNUNET_OK on success, GNUNET_SYSERR on error
 */
int
GNUNET_PSEUDONYM_derive_verification_key (struct GNUNET_PseudonymIdentifier *pseudonym,
					  const struct GNUNET_HashCode *signing_key,
					  struct GNUNET_PseudonymIdentifier *verification_key)
{
  gcry_mpi_t h;  
  size_t size;
  int rc;
  gcry_ctx_t ctx;
  gcry_mpi_point_t g;
  gcry_mpi_point_t q;
  gcry_mpi_point_t hg;
  gcry_mpi_point_t v;
  gcry_mpi_t v_x;
  gcry_mpi_t v_y;

  /* get 'h' value from signing key */
  size = sizeof (struct GNUNET_HashCode);
  if (0 != (rc = gcry_mpi_scan (&h, GCRYMPI_FMT_USG,
				signing_key,
				size, &size)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    return GNUNET_SYSERR;
  }
  /* create ECC context based on Q from pseudonym */
  if (NULL == (ctx = get_context_from_pseudonym (pseudonym)))
  {
    gcry_mpi_release (h);
    return GNUNET_SYSERR;
  }
  /* get G */  
  g = gcry_mpi_ec_get_point ("g", ctx, 0);

  /* then call the 'multiply' function, to compute the product hG */
  hg = gcry_mpi_point_new (0);
  gcry_mpi_ec_mul (hg, h, g, ctx);

  {
    fprintf (stderr, "\nVerification hG value:\n");
    v_x = gcry_mpi_new (256);
    v_y = gcry_mpi_new (256);
    gcry_mpi_ec_get_affine (v_x, v_y, hg, ctx);
    gcry_mpi_dump (v_x);
    gcry_mpi_dump (v_y);
  }
  gcry_mpi_release (h);

  /* get Q = dG from 'pseudonym' */
  q = gcry_mpi_ec_get_point ("q", ctx, 0);
  {
    fprintf (stderr, "\nVerification q value:\n");
    v_x = gcry_mpi_new (256);
    v_y = gcry_mpi_new (256);
    gcry_mpi_ec_get_affine (v_x, v_y, q, ctx);
    gcry_mpi_dump (v_x);
    gcry_mpi_dump (v_y);
  }
  /* calculate V = Q + hG = dG + hG = (d + h)G*/
  v = gcry_mpi_point_new (0);
  gcry_mpi_ec_add (v, q, hg, xctx);
  /* FIXME: free 'hg'? */
  
  /* store 'v' point in "verification_key" */
  v_x = gcry_mpi_new (256);
  v_y = gcry_mpi_new (256);
  gcry_mpi_ec_get_affine (v_x, v_y, v, xctx);

  {
    fprintf (stderr, "\nVerification key public point value V := q + hG:\n");
    gcry_mpi_dump (v_x);
    gcry_mpi_dump (v_y);
    fprintf (stderr, " <=== WTF!?\n");
  }


  gcry_mpi_point_release (v);
  gcry_ctx_release (ctx);

  size = sizeof (verification_key->q_x);
  if (0 != (rc = gcry_mpi_print (GCRYMPI_FMT_USG, verification_key->q_x, size,
                                 &size, v_x)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_print", rc);
    gcry_mpi_release (v_x);
    gcry_mpi_release (v_y);
    return GNUNET_SYSERR;
  }
  gcry_mpi_release (v_x);
  size = sizeof (verification_key->q_y);
  if (0 != (rc = gcry_mpi_print (GCRYMPI_FMT_USG, verification_key->q_y, size,
                                 &size, v_y)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_print", rc);
    gcry_mpi_release (v_y);
    return GNUNET_SYSERR;
  }
  gcry_mpi_release (v_y);
  return GNUNET_OK;
}


/**
 * Verify a signature made with a pseudonym.
 *
 * @param purpose data that was signed
 * @param signature signature to verify
 * @param verification_key public key to use for checking the signature;
 *                    corresponds to 'g^(x+h)' in section 2.4 of #2564.
 * @return GNUNET_OK on success (signature valid, 'pseudonym' set),
 *         GNUNET_SYSERR if the signature is invalid
 */
int
GNUNET_PSEUDONYM_verify (const struct GNUNET_PseudonymSignaturePurpose *purpose,
			 const struct GNUNET_PseudonymSignature *signature,
			 const struct GNUNET_PseudonymIdentifier *verification_key)
{
  gcry_sexp_t data;
  gcry_sexp_t sig_sexpr;
  gcry_sexp_t pk_sexpr;
  size_t size;
  gcry_ctx_t ctx;
  gcry_mpi_t ONE;
  gcry_mpi_t r;
  gcry_mpi_t s;
  gcry_mpi_point_t q;
  gcry_mpi_t q_x;
  gcry_mpi_t q_y;
  size_t erroff;
  int rc;

  /* build s-expression for signature */
  size = sizeof (signature->sig_r);
  if (0 != (rc = gcry_mpi_scan (&r, GCRYMPI_FMT_USG,
                                signature->sig_r, size, &size)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    return GNUNET_SYSERR;
  }
  size = sizeof (signature->sig_s);
  if (0 != (rc = gcry_mpi_scan (&s, GCRYMPI_FMT_USG,
                                signature->sig_s, size, &size)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    gcry_mpi_release (r);
    return GNUNET_SYSERR;
  }
  if (0 != (rc = gcry_sexp_build (&sig_sexpr, &erroff, "(sig-val(ecdsa(r %m)(s %m)))",
                                  r, s)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
    gcry_mpi_release (r);
    gcry_mpi_release (s);
    return GNUNET_SYSERR;
  }
  gcry_mpi_release (r);
  gcry_mpi_release (s);

  /* build s-expression for data that was signed */
  data = data_to_pkcs1 (purpose);

  /* create context of public key and initialize Q */
  size = sizeof (verification_key->q_x);
  if (0 != (rc = gcry_mpi_scan (&q_x, GCRYMPI_FMT_USG,
                                verification_key->q_x, size, &size)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    gcry_sexp_release (data);
    gcry_sexp_release (sig_sexpr);
    return GNUNET_SYSERR;
  }
  size = sizeof (verification_key->q_y);
  if (0 != (rc = gcry_mpi_scan (&q_y, GCRYMPI_FMT_USG,
                                verification_key->q_y, size, &size)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
    gcry_sexp_release (data);
    gcry_sexp_release (sig_sexpr);
    gcry_mpi_release (q_x);
    return GNUNET_SYSERR;
  }
  q = gcry_mpi_point_new (256);
  ONE = gcry_mpi_new (1);
  gcry_mpi_set_ui (ONE, 1);
  gcry_mpi_point_set (q, q_x, q_y, ONE); /* FIXME: convenience function 'set_affine'? */
  gcry_mpi_release (ONE);
  gcry_mpi_release (q_x);
  gcry_mpi_release (q_y);

  /* create basic ECC context */
  if (0 != (rc = gcry_mpi_ec_new (&ctx, NULL, "NIST P-256")))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);  /* erroff gives more info */
    gcry_sexp_release (data);
    gcry_sexp_release (sig_sexpr);
    gcry_mpi_point_release (q);
    return GNUNET_SYSERR;
  }  
  /* initialize 'ctx' with 'q' */
  gcry_mpi_ec_set_point ("q", q, ctx);
  gcry_mpi_point_release (q);

  /* convert 'ctx' to 'sexp' */
  if (0 != (rc = gcry_pubkey_get_sexp (&pk_sexpr, GCRY_PK_GET_PUBKEY, ctx)))
  {
    LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_from_context", rc);
    gcry_ctx_release (ctx);
    gcry_sexp_release (data);
    gcry_sexp_release (sig_sexpr);
    return GNUNET_SYSERR;
  }
  gcry_ctx_release (ctx);

  /* finally, verify the signature */
  rc = gcry_pk_verify (sig_sexpr, data, pk_sexpr);
  gcry_sexp_release (sig_sexpr);
  gcry_sexp_release (data);
  gcry_sexp_release (pk_sexpr);
  if (rc)
  {
    LOG (GNUNET_ERROR_TYPE_WARNING,
         _("ECDSA signature verification failed at %s:%d: %s\n"), __FILE__,
         __LINE__, gcry_strerror (rc));
exit (1);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Get the identifier (public key) of a pseudonym.
 *
 * @param ph pseudonym handle with the private key
 * @param pseudonym pseudonym identifier (set based on 'ph')
 */
void
GNUNET_PSEUDONYM_get_identifier (struct GNUNET_PseudonymHandle *ph,
				 struct GNUNET_PseudonymIdentifier *pseudonym)
{
  memcpy (pseudonym, &ph->public_key,
	  sizeof (struct GNUNET_PseudonymIdentifier));
}


/**
 * Remove pseudonym from the set of known pseudonyms.
 *
 * @param cfg overall configuration
 * @param id the pseudonym identifier
 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
 */
int
GNUNET_PSEUDONYM_remove (const struct GNUNET_CONFIGURATION_Handle *cfg,
			 const struct GNUNET_PseudonymIdentifier *id)
{
  char *fn;
  int result;

  fn = get_data_filename (cfg, PS_METADATA_DIR, id);
  if (NULL == fn)
    return GNUNET_SYSERR;
  result = UNLINK (fn);
  GNUNET_free (fn);  
  return (0 == result) ? GNUNET_OK : GNUNET_SYSERR;
}

/* end of pseudonym.c */