summaryrefslogtreecommitdiff
path: root/src/nse/gnunet-service-nse.c
blob: fa9a2e9502b4ebaf776c2262721d8bc7114eec0c (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
/*
   This file is part of GNUnet.
   Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016 GNUnet e.V.

   GNUnet is free software: you can redistribute it and/or modify it
   under the terms of the GNU Affero General Public License as published
   by the Free Software Foundation, either version 3 of the License,
   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
   Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

     SPDX-License-Identifier: AGPL3.0-or-later
 */

/**
 * @file nse/gnunet-service-nse.c
 * @brief network size estimation service
 * @author Nathan Evans
 * @author Christian Grothoff
 *
 * The purpose of this service is to estimate the size of the network.
 * Given a specified interval, each peer hashes the most recent
 * timestamp which is evenly divisible by that interval.  This hash is
 * compared in distance to the peer identity to choose an offset.  The
 * closer the peer identity to the hashed timestamp, the earlier the
 * peer sends out a "nearest peer" message.  The closest peer's
 * message should thus be received before any others, which stops
 * those peer from sending their messages at a later duration.  So
 * every peer should receive the same nearest peer message, and from
 * this can calculate the expected number of peers in the network.
 */
#include "platform.h"
#include <math.h>
#include "gnunet_util_lib.h"
#include "gnunet_constants.h"
#include "gnunet_protocols.h"
#include "gnunet_signatures.h"
#include "gnunet_statistics_service.h"
#include "gnunet_core_service.h"
#include "gnunet_nse_service.h"
#if ENABLE_NSE_HISTOGRAM
#include "gnunet_testbed_logger_service.h"
#endif
#include "nse.h"
#include <gcrypt.h>


/**
 * Should messages be delayed randomly?  This option should be set to
 * #GNUNET_NO only for experiments, not in production.
 */
#define USE_RANDOM_DELAYS GNUNET_YES

/**
 * Generate extensive debug-level log messages?
 */
#define DEBUG_NSE GNUNET_NO

/**
 * Over how many values do we calculate the weighted average?
 */
#define HISTORY_SIZE 64

/**
 * Message priority to use.  No real rush, reliability not
 * required. Corking OK.
 */
#define NSE_PRIORITY                                       \
  (GNUNET_MQ_PRIO_BACKGROUND | GNUNET_MQ_PREF_UNRELIABLE   \
   | GNUNET_MQ_PREF_CORK_ALLOWED)

#if BSD
#define log2(a) (log (a) / log (2))
#endif

/**
 * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
 */
static unsigned long long nse_work_required;

/**
 * Interval for sending network size estimation flood requests.
 */
static struct GNUNET_TIME_Relative gnunet_nse_interval;

/**
 * Interval between proof find runs.
 */
static struct GNUNET_TIME_Relative proof_find_delay;

#if ENABLE_NSE_HISTOGRAM

/**
 * Handle to test if testbed logger service is running or not
 */
struct GNUNET_CLIENT_TestHandle *logger_test;

/**
 * Handle for writing when we received messages to disk.
 */
static struct GNUNET_TESTBED_LOGGER_Handle *lh;

/**
 * Handle for writing message received timestamp information to disk.
 */
static struct GNUNET_BIO_WriteHandle *histogram;

#endif


/**
 * Per-peer information.
 */
struct NSEPeerEntry
{
  /**
   * Core handle for sending messages to this peer.
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * What is the identity of the peer?
   */
  const struct GNUNET_PeerIdentity *id;

  /**
   * Task scheduled to send message to this peer.
   */
  struct GNUNET_SCHEDULER_Task *transmit_task;

  /**
   * Did we receive or send a message about the previous round
   * to this peer yet?   #GNUNET_YES if the previous round has
   * been taken care of.
   */
  int previous_round;

#if ENABLE_NSE_HISTOGRAM
  /**
   * Amount of messages received from this peer on this round.
   */
  unsigned int received_messages;

  /**
   * Amount of messages transmitted to this peer on this round.
   */
  unsigned int transmitted_messages;

  /**
   * Which size did we tell the peer the network is?
   */
  unsigned int last_transmitted_size;
#endif
};


GNUNET_NETWORK_STRUCT_BEGIN

/**
 * Network size estimate reply; sent when "this"
 * peer's timer has run out before receiving a
 * valid reply from another peer.
 */
struct GNUNET_NSE_FloodMessage
{
  /**
   * Type: #GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
   */
  struct GNUNET_MessageHeader header;

  /**
   * Number of hops this message has taken so far.
   */
  uint32_t hop_count GNUNET_PACKED;

  /**
   * Purpose.
   */
  struct GNUNET_CRYPTO_EccSignaturePurpose purpose;

  /**
   * The current timestamp value (which all
   * peers should agree on).
   */
  struct GNUNET_TIME_AbsoluteNBO timestamp;

  /**
   * Number of matching bits between the hash
   * of timestamp and the initiator's public
   * key.
   */
  uint32_t matching_bits GNUNET_PACKED;

  /**
   * Public key of the originator.
   */
  struct GNUNET_PeerIdentity origin;

  /**
   * Proof of work, causing leading zeros when hashed with pkey.
   */
  uint64_t proof_of_work GNUNET_PACKED;

  /**
   * Signature (over range specified in purpose).
   */
  struct GNUNET_CRYPTO_EddsaSignature signature;
};
GNUNET_NETWORK_STRUCT_END

/**
 * Handle to our current configuration.
 */
static const struct GNUNET_CONFIGURATION_Handle *cfg;

/**
 * Handle to the statistics service.
 */
static struct GNUNET_STATISTICS_Handle *stats;

/**
 * Handle to the core service.
 */
static struct GNUNET_CORE_Handle *core_api;

/**
 * Map of all connected peers.
 */
static struct GNUNET_CONTAINER_MultiPeerMap *peers;

/**
 * The current network size estimate.  Number of bits matching on
 * average thus far.
 */
static double current_size_estimate;

/**
 * The standard deviation of the last #HISTORY_SIZE network
 * size estimates.
 */
static double current_std_dev = NAN;

/**
 * Current hop counter estimate (estimate for network diameter).
 */
static uint32_t hop_count_max;

/**
 * Message for the next round, if we got any.
 */
static struct GNUNET_NSE_FloodMessage next_message;

/**
 * Array of recent size estimate messages.
 */
static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];

/**
 * Index of most recent estimate.
 */
static unsigned int estimate_index;

/**
 * Number of valid entries in the history.
 */
static unsigned int estimate_count;

/**
 * Task scheduled to update our flood message for the next round.
 */
static struct GNUNET_SCHEDULER_Task *flood_task;

/**
 * Task scheduled to compute our proof.
 */
static struct GNUNET_SCHEDULER_Task *proof_task;

/**
 * Notification context, simplifies client broadcasts.
 */
static struct GNUNET_NotificationContext *nc;

/**
 * The next major time.
 */
static struct GNUNET_TIME_Absolute next_timestamp;

/**
 * The current major time.
 */
static struct GNUNET_TIME_Absolute current_timestamp;

/**
 * The private key of this peer.
 */
static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;

/**
 * The peer identity of this peer.
 */
static struct GNUNET_PeerIdentity my_identity;

/**
 * Proof of work for this peer.
 */
static uint64_t my_proof;


/**
 * Initialize a message to clients with the current network
 * size estimate.
 *
 * @param em message to fill in
 */
static void
setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
{
  double mean;
  double sum;
  double std_dev;
  double variance;
  double val;
  double nsize;

#define WEST 1
  /* Weighted incremental algorithm for stddev according to West (1979) */
#if WEST
  double sumweight;
  double weight;
  double q;
  double r;
  double temp;

  mean = 0.0;
  sum = 0.0;
  sumweight = 0.0;
  variance = 0.0;
  for (unsigned int i = 0; i < estimate_count; i++)
  {
    unsigned int j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;

    val = htonl (size_estimate_messages[j].matching_bits);
    weight = estimate_count + 1 - i;

    temp = weight + sumweight;
    q = val - mean;
    r = q * weight / temp;
    mean += r;
    sum += sumweight * q * r;
    sumweight = temp;
  }
  if (estimate_count > 0)
    variance = (sum / sumweight) * estimate_count / (estimate_count - 1.0);
#else
  /* trivial version for debugging */
  double vsq;

  /* non-weighted trivial version */
  sum = 0.0;
  vsq = 0.0;
  variance = 0.0;
  mean = 0.0;

  for (unsigned int i = 0; i < estimate_count; i++)
  {
    unsigned int j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;

    val = htonl (size_estimate_messages[j].matching_bits);
    sum += val;
    vsq += val * val;
  }
  if (0 != estimate_count)
  {
    mean = sum / estimate_count;
    variance = (vsq - mean * sum)
               / (estimate_count - 1.0); // terrible for numerical stability...
  }
#endif
  if (variance >= 0)
    std_dev = sqrt (variance);
  else
    std_dev = variance; /* must be infinity due to estimate_count == 0 */
  current_std_dev = std_dev;
  current_size_estimate = mean;

  em->header.size = htons (sizeof(struct GNUNET_NSE_ClientMessage));
  em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
  em->reserved = htonl (0);
  em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
  {
    double se = mean - 0.332747;
    unsigned int j = GNUNET_CONTAINER_multipeermap_size (peers);
    if (0 == j)
      j = 1; /* Avoid log2(0); can only happen if CORE didn't report
                connection to self yet */
    nsize = log2 (j);
    em->size_estimate = GNUNET_hton_double (GNUNET_MAX (se, nsize));
    em->std_deviation = GNUNET_hton_double (std_dev);
    GNUNET_STATISTICS_set (stats,
                           "# nodes in the network (estimate)",
                           (uint64_t) pow (2, GNUNET_MAX (se, nsize)),
                           GNUNET_NO);
  }
}


/**
 * Handler for START message from client, triggers an
 * immediate current network estimate notification.
 * Also, we remember the client for updates upon future
 * estimate measurements.
 *
 * @param cls client who sent the message
 * @param message the message received
 */
static void
handle_start (void *cls, const struct GNUNET_MessageHeader *message)
{
  struct GNUNET_SERVICE_Client *client = cls;
  struct GNUNET_MQ_Handle *mq;
  struct GNUNET_NSE_ClientMessage em;
  struct GNUNET_MQ_Envelope *env;

  (void) message;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n");
  mq = GNUNET_SERVICE_client_get_mq (client);
  GNUNET_notification_context_add (nc, mq);
  setup_estimate_message (&em);
  env = GNUNET_MQ_msg_copy (&em.header);
  GNUNET_MQ_send (mq, env);
  GNUNET_SERVICE_client_continue (client);
}


/**
 * How long should we delay a message to go the given number of
 * matching bits?
 *
 * @param matching_bits number of matching bits to consider
 */
static double
get_matching_bits_delay (uint32_t matching_bits)
{
  /* Calculated as: S + f/2 - (f / pi) * (atan(x - p')) */
  // S is next_timestamp (ignored in return value)
  // f is frequency (gnunet_nse_interval)
  // x is matching_bits
  // p' is current_size_estimate
  return ((double) gnunet_nse_interval.rel_value_us / (double) 2.0)
         - ((gnunet_nse_interval.rel_value_us / M_PI)
            * atan (matching_bits - current_size_estimate));
}


/**
 * What delay randomization should we apply for a given number of matching bits?
 *
 * @param matching_bits number of matching bits
 * @return random delay to apply
 */
static struct GNUNET_TIME_Relative
get_delay_randomization (uint32_t matching_bits)
{
#if USE_RANDOM_DELAYS
  struct GNUNET_TIME_Relative ret;
  uint32_t i;
  double d;

  d = get_matching_bits_delay (matching_bits);
  i = (uint32_t) (d / (double) (hop_count_max + 1));
  ret.rel_value_us = i;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Randomizing flood using latencies up to %s\n",
              GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
  ret.rel_value_us =
    GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, i + 1);
  return ret;
#else
  return GNUNET_TIME_UNIT_ZERO;
#endif
}


/**
 * Calculate the 'proof-of-work' hash (an expensive hash).
 *
 * @param buf data to hash
 * @param buf_len number of bytes in @a buf
 * @param result where to write the resulting hash
 */
static void
pow_hash (const void *buf, size_t buf_len, struct GNUNET_HashCode *result)
{
  GNUNET_break (
    0 == gcry_kdf_derive (buf,
                          buf_len,
                          GCRY_KDF_SCRYPT,
                          1 /* subalgo */,
                          "gnunet-proof-of-work",
                          strlen ("gnunet-proof-of-work"),
                          2 /* iterations; keep cost of individual op small */,
                          sizeof(struct GNUNET_HashCode),
                          result));
}


/**
 * Get the number of matching bits that the given timestamp has to the given peer ID.
 *
 * @param timestamp time to generate key
 * @param id peer identity to compare with
 * @return number of matching bits
 */
static uint32_t
get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
                   const struct GNUNET_PeerIdentity *id)
{
  struct GNUNET_HashCode timestamp_hash;
  struct GNUNET_HashCode pid_hash;

  GNUNET_CRYPTO_hash (&timestamp.abs_value_us,
                      sizeof(timestamp.abs_value_us),
                      &timestamp_hash);
  GNUNET_CRYPTO_hash (id, sizeof(struct GNUNET_PeerIdentity), &pid_hash);
  return GNUNET_CRYPTO_hash_matching_bits (&timestamp_hash, &pid_hash);
}


/**
 * Get the transmission delay that should be applied for a
 * particular round.
 *
 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
 *                      0 for the current round (based on our proximity to time key)
 * @return delay that should be applied
 */
static struct GNUNET_TIME_Relative
get_transmit_delay (int round_offset)
{
  struct GNUNET_TIME_Relative ret;
  struct GNUNET_TIME_Absolute tgt;
  double dist_delay;
  uint32_t matching_bits;

  switch (round_offset)
  {
  case -1:
    /* previous round is randomized between 0 and 50 ms */
#if USE_RANDOM_DELAYS
    ret.rel_value_us =
      GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50);
#else
    ret = GNUNET_TIME_UNIT_ZERO;
#endif
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Transmitting previous round behind schedule in %s\n",
                GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
    return ret;

  case 0:
    /* current round is based on best-known matching_bits */
    matching_bits =
      ntohl (size_estimate_messages[estimate_index].matching_bits);
    dist_delay = get_matching_bits_delay (matching_bits);
    dist_delay += get_delay_randomization (matching_bits).rel_value_us;
    ret.rel_value_us = (uint64_t) dist_delay;
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "For round %s, delay for %u matching bits is %s\n",
                GNUNET_STRINGS_absolute_time_to_string (current_timestamp),
                (unsigned int) matching_bits,
                GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
    /* now consider round start time and add delay to it */
    tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
    return GNUNET_TIME_absolute_get_remaining (tgt);
  }
  GNUNET_break (0);
  return GNUNET_TIME_UNIT_FOREVER_REL;
}


/**
 * Task that triggers a NSE P2P transmission.
 *
 * @param cls the `struct NSEPeerEntry *`
 */
static void
transmit_task_cb (void *cls)
{
  struct NSEPeerEntry *peer_entry = cls;
  unsigned int idx;
  struct GNUNET_MQ_Envelope *env;

  peer_entry->transmit_task = NULL;
  idx = estimate_index;
  if (GNUNET_NO == peer_entry->previous_round)
  {
    idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
    peer_entry->previous_round = GNUNET_YES;
    peer_entry->transmit_task =
      GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0),
                                    &transmit_task_cb,
                                    peer_entry);
  }
  if ((0 == ntohl (size_estimate_messages[idx].hop_count)) &&
      (NULL != proof_task))
  {
    GNUNET_STATISTICS_update (stats,
                              "# flood messages not generated (no proof yet)",
                              1,
                              GNUNET_NO);
    return;
  }
  if (0 == ntohs (size_estimate_messages[idx].header.size))
  {
    GNUNET_STATISTICS_update (stats,
                              "# flood messages not generated (lack of history)",
                              1,
                              GNUNET_NO);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "In round %s, sending to `%s' estimate with %u bits\n",
              GNUNET_STRINGS_absolute_time_to_string (
                GNUNET_TIME_absolute_ntoh (
                  size_estimate_messages[idx].timestamp)),
              GNUNET_i2s (peer_entry->id),
              (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
  if (0 == ntohl (size_estimate_messages[idx].hop_count))
    GNUNET_STATISTICS_update (stats, "# flood messages started", 1, GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
                            "# flood messages transmitted",
                            1,
                            GNUNET_NO);
#if ENABLE_NSE_HISTOGRAM
  peer_entry->transmitted_messages++;
  peer_entry->last_transmitted_size =
    ntohl (size_estimate_messages[idx].matching_bits);
#endif
  env = GNUNET_MQ_msg_copy (&size_estimate_messages[idx].header);
  GNUNET_MQ_send (peer_entry->mq, env);
}


/**
 * We've sent on our flood message or one that we received which was
 * validated and closer than ours.  Update the global list of recent
 * messages and the average.  Also re-broadcast the message to any
 * clients.
 */
static void
update_network_size_estimate ()
{
  struct GNUNET_NSE_ClientMessage em;

  setup_estimate_message (&em);
  GNUNET_notification_context_broadcast (nc, &em.header, GNUNET_YES);
}


/**
 * Setup a flood message in our history array at the given
 * slot offset for the given timestamp.
 *
 * @param slot index to use
 * @param ts timestamp to use
 */
static void
setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts)
{
  struct GNUNET_NSE_FloodMessage *fm;
  uint32_t matching_bits;

  matching_bits = get_matching_bits (ts, &my_identity);
  fm = &size_estimate_messages[slot];
  fm->header.size = htons (sizeof(struct GNUNET_NSE_FloodMessage));
  fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
  fm->hop_count = htonl (0);
  fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
  fm->purpose.size =
    htonl (sizeof(struct GNUNET_NSE_FloodMessage)
           - sizeof(struct GNUNET_MessageHeader) - sizeof(uint32_t)
           - sizeof(struct GNUNET_CRYPTO_EddsaSignature));
  fm->matching_bits = htonl (matching_bits);
  fm->timestamp = GNUNET_TIME_absolute_hton (ts);
  fm->origin = my_identity;
  fm->proof_of_work = my_proof;
  if (nse_work_required > 0)
    GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
                                                          &fm->purpose,
                                                          &fm->signature));
  else
    memset (&fm->signature, 0, sizeof(fm->signature));
}


/**
 * Schedule transmission for the given peer for the current round based
 * on what we know about the desired delay.
 *
 * @param cls unused
 * @param key hash of peer identity
 * @param value the `struct NSEPeerEntry`
 * @return #GNUNET_OK (continue to iterate)
 */
static int
schedule_current_round (void *cls,
                        const struct GNUNET_PeerIdentity *key,
                        void *value)
{
  struct NSEPeerEntry *peer_entry = value;
  struct GNUNET_TIME_Relative delay;

  (void) cls;
  (void) key;
  if (NULL != peer_entry->transmit_task)
  {
    GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
    peer_entry->previous_round = GNUNET_NO;
  }
#if ENABLE_NSE_HISTOGRAM
  if (peer_entry->received_messages > 1)
    GNUNET_STATISTICS_update (stats,
                              "# extra messages",
                              peer_entry->received_messages - 1,
                              GNUNET_NO);
  peer_entry->transmitted_messages = 0;
  peer_entry->last_transmitted_size = 0;
  peer_entry->received_messages = 0;
#endif
  delay =
    get_transmit_delay ((GNUNET_NO == peer_entry->previous_round) ? -1 : 0);
  peer_entry->transmit_task =
    GNUNET_SCHEDULER_add_delayed (delay, &transmit_task_cb, peer_entry);
  return GNUNET_OK;
}


/**
 * Update our flood message to be sent (and our timestamps).
 *
 * @param cls unused
 */
static void
update_flood_message (void *cls)
{
  struct GNUNET_TIME_Relative offset;

  (void) cls;
  flood_task = NULL;
  offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
  if (0 != offset.rel_value_us)
  {
    /* somehow run early, delay more */
    flood_task =
      GNUNET_SCHEDULER_add_delayed (offset, &update_flood_message, NULL);
    return;
  }
  estimate_index = (estimate_index + 1) % HISTORY_SIZE;
  if (estimate_count < HISTORY_SIZE)
    estimate_count++;
  current_timestamp = next_timestamp;
  next_timestamp =
    GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval);
  if ((current_timestamp.abs_value_us ==
       GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value_us) &&
      (get_matching_bits (current_timestamp, &my_identity) <
       ntohl (next_message.matching_bits)))
  {
    /* we received a message for this round way early, use it! */
    size_estimate_messages[estimate_index] = next_message;
    size_estimate_messages[estimate_index].hop_count =
      htonl (1 + ntohl (next_message.hop_count));
  }
  else
    setup_flood_message (estimate_index, current_timestamp);
  next_message.matching_bits = htonl (0);  /* reset for 'next' round */
  hop_count_max = 0;
  for (unsigned int i = 0; i < HISTORY_SIZE; i++)
    hop_count_max =
      GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count), hop_count_max);
  GNUNET_CONTAINER_multipeermap_iterate (peers, &schedule_current_round, NULL);
  flood_task =
    GNUNET_SCHEDULER_add_at (next_timestamp, &update_flood_message, NULL);
}


/**
 * Count the leading zeroes in hash.
 *
 * @param hash to count leading zeros in
 * @return the number of leading zero bits.
 */
static unsigned int
count_leading_zeroes (const struct GNUNET_HashCode *hash)
{
  unsigned int hash_count;

  hash_count = 0;
  while (0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count))
    hash_count++;
  return hash_count;
}


/**
 * Check whether the given public key and integer are a valid proof of
 * work.
 *
 * @param pkey the public key
 * @param val the integer
 * @return #GNUNET_YES if valid, #GNUNET_NO if not
 */
static int
check_proof_of_work (const struct GNUNET_CRYPTO_EddsaPublicKey *pkey,
                     uint64_t val)
{
  char buf[sizeof(struct GNUNET_CRYPTO_EddsaPublicKey)
           + sizeof(val)] GNUNET_ALIGN;
  struct GNUNET_HashCode result;

  GNUNET_memcpy (buf, &val, sizeof(val));
  GNUNET_memcpy (&buf[sizeof(val)],
                 pkey,
                 sizeof(struct GNUNET_CRYPTO_EddsaPublicKey));
  pow_hash (buf, sizeof(buf), &result);
  return (count_leading_zeroes (&result) >= nse_work_required) ? GNUNET_YES
         : GNUNET_NO;
}


/**
 * Write our current proof to disk.
 */
static void
write_proof ()
{
  char *proof;

  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
    return;
  if (sizeof(my_proof) != GNUNET_DISK_fn_write (proof,
                                                &my_proof,
                                                sizeof(my_proof),
                                                GNUNET_DISK_PERM_USER_READ
                                                | GNUNET_DISK_PERM_USER_WRITE))
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", proof);
  GNUNET_free (proof);
}


/**
 * Find our proof of work.
 *
 * @param cls closure (unused)
 */
static void
find_proof (void *cls)
{
#define ROUND_SIZE 10
  uint64_t counter;
  char buf[sizeof(struct GNUNET_CRYPTO_EddsaPublicKey)
           + sizeof(uint64_t)] GNUNET_ALIGN;
  struct GNUNET_HashCode result;
  unsigned int i;

  (void) cls;
  proof_task = NULL;
  GNUNET_memcpy (&buf[sizeof(uint64_t)],
                 &my_identity,
                 sizeof(struct GNUNET_PeerIdentity));
  i = 0;
  counter = my_proof;
  while ((counter != UINT64_MAX) && (i < ROUND_SIZE))
  {
    GNUNET_memcpy (buf, &counter, sizeof(uint64_t));
    pow_hash (buf, sizeof(buf), &result);
    if (nse_work_required <= count_leading_zeroes (&result))
    {
      my_proof = counter;
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Proof of work found: %llu!\n",
                  (unsigned long long) GNUNET_ntohll (counter));
      write_proof ();
      setup_flood_message (estimate_index, current_timestamp);
      return;
    }
    counter++;
    i++;
  }
  if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Testing proofs currently at %llu\n",
                (unsigned long long) counter);
    /* remember progress every 100 rounds */
    my_proof = counter;
    write_proof ();
  }
  else
  {
    my_proof = counter;
  }
  proof_task =
    GNUNET_SCHEDULER_add_delayed_with_priority (proof_find_delay,
                                                GNUNET_SCHEDULER_PRIORITY_IDLE,
                                                &find_proof,
                                                NULL);
}


/**
 * An incoming flood message has been received which claims
 * to have more bits matching than any we know in this time
 * period.  Verify the signature and/or proof of work.
 *
 * @param incoming_flood the message to verify
 * @return #GNUNET_YES if the message is verified
 *         #GNUNET_NO if the key/signature don't verify
 */
static int
verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood)
{
  if (GNUNET_YES != check_proof_of_work (&incoming_flood->origin.public_key,
                                         incoming_flood->proof_of_work))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Proof of work invalid: %llu!\n",
                (unsigned long long) GNUNET_ntohll (
                  incoming_flood->proof_of_work));
    GNUNET_break_op (0);
    return GNUNET_NO;
  }
  if ((nse_work_required > 0) &&
      (GNUNET_OK !=
       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
                                   &incoming_flood->purpose,
                                   &incoming_flood->signature,
                                   &incoming_flood->origin.public_key)))
  {
    GNUNET_break_op (0);
    return GNUNET_NO;
  }
  return GNUNET_YES;
}


/**
 * Update transmissions for the given peer for the current round based
 * on updated proximity information.
 *
 * @param cls peer entry to exclude from updates
 * @param key hash of peer identity
 * @param value the `struct NSEPeerEntry *` of a peer to transmit to
 * @return #GNUNET_OK (continue to iterate)
 */
static int
update_flood_times (void *cls,
                    const struct GNUNET_PeerIdentity *key,
                    void *value)
{
  struct NSEPeerEntry *exclude = cls;
  struct NSEPeerEntry *peer_entry = value;
  struct GNUNET_TIME_Relative delay;

  (void) key;
  if (peer_entry == exclude)
    return GNUNET_OK; /* trigger of the update */
  if (GNUNET_NO == peer_entry->previous_round)
  {
    /* still stuck in previous round, no point to update, check that
     * we are active here though... */
    if (NULL == peer_entry->transmit_task)
    {
      GNUNET_break (0);
    }
    return GNUNET_OK;
  }
  if (NULL != peer_entry->transmit_task)
  {
    GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
    peer_entry->transmit_task = NULL;
  }
  delay = get_transmit_delay (0);
  peer_entry->transmit_task =
    GNUNET_SCHEDULER_add_delayed (delay, &transmit_task_cb, peer_entry);
  return GNUNET_OK;
}


/**
 * Core handler for size estimate flooding messages.
 *
 * @param cls peer this message is from
 * @param incoming_flood received message
 */
static void
handle_p2p_estimate (void *cls,
                     const struct GNUNET_NSE_FloodMessage *incoming_flood)
{
  struct NSEPeerEntry *peer_entry = cls;
  struct GNUNET_TIME_Absolute ts;
  uint32_t matching_bits;
  unsigned int idx;

#if ENABLE_NSE_HISTOGRAM
  {
    uint64_t t;

    t = GNUNET_TIME_absolute_get ().abs_value_us;
    if (NULL != lh)
      GNUNET_TESTBED_LOGGER_write (lh, &t, sizeof(uint64_t));
    if (NULL != histogram)
      GNUNET_BIO_write_int64 (histogram, t);
  }
#endif
  GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO);
  matching_bits = ntohl (incoming_flood->matching_bits);
#if DEBUG_NSE
  {
    char origin[5];
    char pred[5];
    struct GNUNET_PeerIdentity os;

    GNUNET_snprintf (origin,
                     sizeof(origin),
                     "%s",
                     GNUNET_i2s (&incoming_flood->origin));
    GNUNET_snprintf (pred, sizeof(pred), "%s", GNUNET_i2s (peer_entry->id));
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Flood at %s from `%s' via `%s' at `%s' with bits %u\n",
                GNUNET_STRINGS_absolute_time_to_string (
                  GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp)),
                origin,
                pred,
                GNUNET_i2s (&my_identity),
                (unsigned int) matching_bits);
  }
#endif

#if ENABLE_NSE_HISTOGRAM
  peer_entry->received_messages++;
  if ((peer_entry->transmitted_messages > 0) &&
      (peer_entry->last_transmitted_size >= matching_bits) )
    GNUNET_STATISTICS_update (stats, "# cross messages", 1, GNUNET_NO);
#endif

  ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
  if (ts.abs_value_us == current_timestamp.abs_value_us)
    idx = estimate_index;
  else if (ts.abs_value_us ==
           current_timestamp.abs_value_us - gnunet_nse_interval.rel_value_us)
    idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
  else if (ts.abs_value_us == next_timestamp.abs_value_us)
  {
    if (matching_bits <= ntohl (next_message.matching_bits))
      return;   /* ignore, simply too early/late */
    if (GNUNET_YES != verify_message_crypto (incoming_flood))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Peer %s is likely ill-configured!\n",
                  GNUNET_i2s (peer_entry->id));
      GNUNET_break_op (0);
      return;
    }
    next_message = *incoming_flood;
    return;
  }
  else
  {
    GNUNET_STATISTICS_update (stats,
                              "# flood messages discarded (clock skew too large)",
                              1,
                              GNUNET_NO);
    return;
  }
  if (0 == (GNUNET_memcmp (peer_entry->id, &my_identity)))
  {
    /* send to self, update our own estimate IF this also comes from us! */
    if (0 == GNUNET_memcmp (&incoming_flood->origin, &my_identity))
      update_network_size_estimate ();
    return;
  }
  if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
  {
    /* Cancel transmission in the other direction, as this peer clearly has
       up-to-date information already. Even if we didn't talk to this peer in
       the previous round, we should no longer send it stale information as it
       told us about the current round! */
    peer_entry->previous_round = GNUNET_YES;
    if (idx != estimate_index)
    {
      /* do not transmit information for the previous round to this peer
         anymore (but allow current round) */
      return;
    }
    /* got up-to-date information for current round, cancel transmission to
     * this peer altogether */
    if (NULL != peer_entry->transmit_task)
    {
      GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
      peer_entry->transmit_task = NULL;
    }
    return;
  }
  if (matching_bits < ntohl (size_estimate_messages[idx].matching_bits))
  {
    if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES))
    {
      peer_entry->previous_round = GNUNET_NO;
    }
    /* push back our result now, that peer is spreading bad information... */
    if (NULL != peer_entry->transmit_task)
      GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
    peer_entry->transmit_task =
      GNUNET_SCHEDULER_add_now (&transmit_task_cb, peer_entry);
    /* Not closer than our most recent message, no need to do work here */
    GNUNET_STATISTICS_update (stats,
                              "# flood messages ignored (had closer already)",
                              1,
                              GNUNET_NO);
    return;
  }
  if (GNUNET_YES != verify_message_crypto (incoming_flood))
  {
    GNUNET_break_op (0);
    return;
  }
  GNUNET_assert (matching_bits >
                 ntohl (size_estimate_messages[idx].matching_bits));
  /* Cancel transmission in the other direction, as this peer clearly has
   * up-to-date information already.
   */
  peer_entry->previous_round = GNUNET_YES;
  if (idx == estimate_index)
  {
    /* cancel any activity for current round */
    if (NULL != peer_entry->transmit_task)
    {
      GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
      peer_entry->transmit_task = NULL;
    }
  }
  size_estimate_messages[idx] = *incoming_flood;
  size_estimate_messages[idx].hop_count =
    htonl (ntohl (incoming_flood->hop_count) + 1);
  hop_count_max =
    GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max);
  GNUNET_STATISTICS_set (stats,
                         "# estimated network diameter",
                         hop_count_max,
                         GNUNET_NO);

  /* have a new, better size estimate, inform clients */
  update_network_size_estimate ();

  /* flood to rest */
  GNUNET_CONTAINER_multipeermap_iterate (peers,
                                         &update_flood_times,
                                         peer_entry);
}


/**
 * Method called whenever a peer connects. Sets up the PeerEntry and
 * schedules the initial size info transmission to this peer.
 *
 * @param cls closure
 * @param peer peer identity this notification is about
 */
static void *
handle_core_connect (void *cls,
                     const struct GNUNET_PeerIdentity *peer,
                     struct GNUNET_MQ_Handle *mq)
{
  struct NSEPeerEntry *peer_entry;

  (void) cls;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Peer `%s' connected to us\n",
              GNUNET_i2s (peer));
  /* set our default transmission options */
  GNUNET_MQ_set_options (mq, NSE_PRIORITY);
  /* create our peer entry for this peer */
  peer_entry = GNUNET_new (struct NSEPeerEntry);
  peer_entry->id = peer;
  peer_entry->mq = mq;
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multipeermap_put (
                   peers,
                   peer_entry->id,
                   peer_entry,
                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  peer_entry->transmit_task =
    GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1),
                                  &transmit_task_cb,
                                  peer_entry);
  GNUNET_STATISTICS_update (stats, "# peers connected", 1, GNUNET_NO);
  return peer_entry;
}


/**
 * Method called whenever a peer disconnects. Deletes the PeerEntry and cancels
 * any pending transmission requests to that peer.
 *
 * @param cls closure
 * @param peer peer identity this notification is about
 * @parma internal_cls the `struct NSEPeerEntry` for the @a peer
 */
static void
handle_core_disconnect (void *cls,
                        const struct GNUNET_PeerIdentity *peer,
                        void *internal_cls)
{
  struct NSEPeerEntry *pos = internal_cls;

  (void) cls;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Peer `%s' disconnected from us\n",
              GNUNET_i2s (peer));
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multipeermap_remove (peers, peer, pos));
  if (NULL != pos->transmit_task)
  {
    GNUNET_SCHEDULER_cancel (pos->transmit_task);
    pos->transmit_task = NULL;
  }
  GNUNET_free (pos);
  GNUNET_STATISTICS_update (stats, "# peers connected", -1, GNUNET_NO);
}


#if ENABLE_NSE_HISTOGRAM
/**
 * Functions of this type are called to notify a successful transmission of the
 * message to the logger service
 *
 * @param cls NULL
 * @param size the amount of data sent (ignored)
 */
static void
flush_comp_cb (void *cls, size_t size)
{
  (void) cls;
  (void) size;
  GNUNET_TESTBED_LOGGER_disconnect (lh);
  lh = NULL;
}


#endif


/**
 * Task run during shutdown.
 *
 * @param cls unused
 */
static void
shutdown_task (void *cls)
{
  (void) cls;
  if (NULL != flood_task)
  {
    GNUNET_SCHEDULER_cancel (flood_task);
    flood_task = NULL;
  }
  if (NULL != proof_task)
  {
    GNUNET_SCHEDULER_cancel (proof_task);
    proof_task = NULL;
    write_proof ();  /* remember progress */
  }
  if (NULL != nc)
  {
    GNUNET_notification_context_destroy (nc);
    nc = NULL;
  }
  if (NULL != core_api)
  {
    GNUNET_CORE_disconnect (core_api);
    core_api = NULL;
  }
  if (NULL != stats)
  {
    GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
    stats = NULL;
  }
  if (NULL != peers)
  {
    GNUNET_CONTAINER_multipeermap_destroy (peers);
    peers = NULL;
  }
  if (NULL != my_private_key)
  {
    GNUNET_free (my_private_key);
    my_private_key = NULL;
  }
#if ENABLE_NSE_HISTOGRAM
  if (NULL != logger_test)
  {
    GNUNET_CLIENT_service_test_cancel (logger_test);
    logger_test = NULL;
  }
  if (NULL != lh)
  {
    GNUNET_TESTBED_LOGGER_flush (lh, &flush_comp_cb, NULL);
  }
  if (NULL != histogram)
  {
    GNUNET_BIO_write_close (histogram);
    histogram = NULL;
  }
#endif
}


/**
 * Called on core init/fail.
 *
 * @param cls service closure
 * @param identity the public identity of this peer
 */
static void
core_init (void *cls, const struct GNUNET_PeerIdentity *identity)
{
  struct GNUNET_TIME_Absolute now;
  struct GNUNET_TIME_Absolute prev_time;

  (void) cls;
  if (NULL == identity)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to core FAILED!\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  GNUNET_assert (0 == GNUNET_memcmp (&my_identity, identity));
  now = GNUNET_TIME_absolute_get ();
  current_timestamp.abs_value_us =
    (now.abs_value_us / gnunet_nse_interval.rel_value_us)
    * gnunet_nse_interval.rel_value_us;
  next_timestamp =
    GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval);
  estimate_index = HISTORY_SIZE - 1;
  estimate_count = 0;
  if (GNUNET_YES == check_proof_of_work (&my_identity.public_key, my_proof))
  {
    int idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
    prev_time.abs_value_us =
      current_timestamp.abs_value_us - gnunet_nse_interval.rel_value_us;
    setup_flood_message (idx, prev_time);
    setup_flood_message (estimate_index, current_timestamp);
    estimate_count++;
  }
  flood_task =
    GNUNET_SCHEDULER_add_at (next_timestamp, &update_flood_message, NULL);
}


#if ENABLE_NSE_HISTOGRAM
/**
 * Function called with the status of the testbed logger service
 *
 * @param cls NULL
 * @param status #GNUNET_YES if the service is running,
 *               #GNUNET_NO if the service is not running
 *               #GNUNET_SYSERR if the configuration is invalid
 */
static void
status_cb (void *cls, int status)
{
  (void) cls;
  logger_test = NULL;
  if (GNUNET_YES != status)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Testbed logger not running\n");
    return;
  }
  if (NULL == (lh = GNUNET_TESTBED_LOGGER_connect (cfg)))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Cannot connect to the testbed logger.  Exiting.\n");
    GNUNET_SCHEDULER_shutdown ();
  }
}


#endif


/**
 * Handle network size estimate clients.
 *
 * @param cls closure
 * @param c configuration to use
 * @param service the initialized service
 */
static void
run (void *cls,
     const struct GNUNET_CONFIGURATION_Handle *c,
     struct GNUNET_SERVICE_Handle *service)
{
  struct GNUNET_MQ_MessageHandler core_handlers[] =
  { GNUNET_MQ_hd_fixed_size (p2p_estimate,
                             GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD,
                             struct GNUNET_NSE_FloodMessage,
                             NULL),
    GNUNET_MQ_handler_end () };
  char *proof;
  struct GNUNET_CRYPTO_EddsaPrivateKey *pk;

  (void) cls;
  (void) service;
  cfg = c;
  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg,
                                                        "NSE",
                                                        "INTERVAL",
                                                        &gnunet_nse_interval))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "INTERVAL");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg,
                                                        "NSE",
                                                        "WORKDELAY",
                                                        &proof_find_delay))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "WORKDELAY");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg,
                                                          "NSE",
                                                          "WORKBITS",
                                                          &nse_work_required))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "WORKBITS");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  if (nse_work_required >= sizeof(struct GNUNET_HashCode) * 8)
  {
    GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
                               "NSE",
                               "WORKBITS",
                               _ ("Value is too large.\n"));
    GNUNET_SCHEDULER_shutdown ();
    return;
  }

#if ENABLE_NSE_HISTOGRAM
  {
    char *histogram_dir;
    char *histogram_fn;

    if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_filename (cfg,
                                                              "NSE",
                                                              "HISTOGRAM_DIR",
                                                              &histogram_dir))
    {
      GNUNET_assert (
        0 < GNUNET_asprintf (&histogram_fn, "%s/timestamps", histogram_dir));
      GNUNET_free (histogram_dir);
      histogram = GNUNET_BIO_write_open (histogram_fn);
      if (NULL == histogram)
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Unable to open histogram file `%s'\n",
                    histogram_fn);
      GNUNET_free (histogram_fn);
    }
    logger_test = GNUNET_CLIENT_service_test ("testbed-logger",
                                              cfg,
                                              GNUNET_TIME_UNIT_SECONDS,
                                              &status_cb,
                                              NULL);
  }
#endif

  GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
  pk = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
  GNUNET_assert (NULL != pk);
  my_private_key = pk;
  GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, &my_identity.public_key);
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "PROOFFILE");
    GNUNET_free (my_private_key);
    my_private_key = NULL;
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  if ((GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
      (sizeof(my_proof) !=
       GNUNET_DISK_fn_read (proof, &my_proof, sizeof(my_proof))))
    my_proof = 0;
  GNUNET_free (proof);
  proof_task =
    GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
                                        &find_proof,
                                        NULL);

  peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
  nc = GNUNET_notification_context_create (1);
  /* Connect to core service and register core handlers */
  core_api =
    GNUNET_CORE_connect (cfg,  /* Main configuration */
                         NULL, /* Closure passed to functions */
                         &core_init, /* Call core_init once connected */
                         &handle_core_connect, /* Handle connects */
                         &handle_core_disconnect, /* Handle disconnects */
                         core_handlers); /* Register these handlers */
  if (NULL == core_api)
  {
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  stats = GNUNET_STATISTICS_create ("nse", cfg);
}


/**
 * Callback called when a client connects to the service.
 *
 * @param cls closure for the service
 * @param c the new client that connected to the service
 * @param mq the message queue used to send messages to the client
 * @return @a c
 */
static void *
client_connect_cb (void *cls,
                   struct GNUNET_SERVICE_Client *c,
                   struct GNUNET_MQ_Handle *mq)
{
  (void) cls;
  (void) mq;
  return c;
}


/**
 * Callback called when a client disconnected from the service
 *
 * @param cls closure for the service
 * @param c the client that disconnected
 * @param internal_cls should be equal to @a c
 */
static void
client_disconnect_cb (void *cls,
                      struct GNUNET_SERVICE_Client *c,
                      void *internal_cls)
{
  (void) cls;
  GNUNET_assert (c == internal_cls);
}


/**
 * Define "main" method using service macro.
 */
GNUNET_SERVICE_MAIN ("nse",
                     GNUNET_SERVICE_OPTION_NONE,
                     &run,
                     &client_connect_cb,
                     &client_disconnect_cb,
                     NULL,
                     GNUNET_MQ_hd_fixed_size (start,
                                              GNUNET_MESSAGE_TYPE_NSE_START,
                                              struct GNUNET_MessageHeader,
                                              NULL),
                     GNUNET_MQ_handler_end ());


#if defined(__linux__) && defined(__GLIBC__)
#include <malloc.h>

/**
 * MINIMIZE heap size (way below 128k) since this process doesn't need much.
 */
void __attribute__ ((constructor))
GNUNET_ARM_memory_init ()
{
  mallopt (M_TRIM_THRESHOLD, 4 * 1024);
  mallopt (M_TOP_PAD, 1 * 1024);
  malloc_trim (0);
}


#endif


/* end of gnunet-service-nse.c */