-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathpseudo_node.c
3425 lines (3171 loc) · 99.6 KB
/
pseudo_node.c
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
/*
* PseudoNode
* Copyright (c) 2015 the copyright holders
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
#include <getopt.h>
#include "sha256.c"
#define MAX_MESSAGE_LEN (1 << 25) // 32MB
#define MSG_TX 1
#define MSG_BLOCK 2
#define MSG_FILTERED_BLOCK 3
#define TX 1
#define BLOCK 2
#define ADDRESS 3
#define HEADERS 4
#define MAX_REQUESTS 32 // Max requests
#define MAX_INVS 8192 // Max invs
#ifdef MACOSX
#define LINUX
#endif
#ifdef LINUX
#include "linux.c"
#endif
#ifdef WINDOWS
#include "windows.c"
#endif
#include "pseudo_node.h"
#define atomic_add(addr, val) __sync_fetch_and_add((addr), (val))
#define atomic_sub(addr, val) __sync_fetch_and_sub((addr), (val))
/*****************************************************************************/
// 256-bit number.
union uint256_s
{
uint8_t i8[32];
uint16_t i16[16];
uint32_t i32[8];
uint64_t i64[4];
};
typedef union uint256_s uint256_t;
#define HASH_FORMAT "%.16llx%.16llx%.16llx%.16llx"
#define HASH_FORMAT_SHORT "%.16llx%.16llx..."
#define HASH(hsh) \
(hsh).i64[3], (hsh).i64[2], (hsh).i64[1], (hsh).i64[0]
#define HASH_SHORT(hsh) \
(hsh).i64[3], (hsh).i64[2]
// Protocol message header.
struct header
{
uint32_t magic; // Magic number.
char command[12]; // Message command (e.g. "version").
uint32_t length; // Message length.
uint32_t checksum; // Message checksum.
} __attribute__((__packed__));
// Block header.
struct block
{
uint32_t version; // Block version.
uint256_t prev_block; // Previous block hash.
uint256_t merkle_root; // Block Merkle root.
uint32_t timestamp; // Block timestamp.
uint32_t bits; // Block difficulty.
uint32_t nonce; // Block nonce.
} __attribute__((__packed__));
// Data buffer.
struct buf
{
char *data; // Buffer data.
uint32_t ptr; // Buffer current position.
uint32_t len; // Buffer length of data.
int32_t ref_count; // Buffer reference count.
jmp_buf *env; // jmp_buf for pop() errors.
};
// Fetch data info.
struct fetch
{
uint256_t hash; // Data hash.
uint64_t nonce; // Peer nonce.
uint32_t type; // Data type.
bool sync; // Requires synced node.
int8_t ttl; // TTL.
time_t time; // Time of last request.
struct fetch *next; // Next.
};
// Peer message queue.
struct msg
{
struct buf *buf; // Queued message.
struct msg *next; // Next message.
};
// Peer information.
struct peer
{
sock sock; // Peer socket.
mutex lock; // Peer lock (for messages).
event event; // Peer event (for messages).
time_t timeout; // Peer timeout.
uint64_t nonce; // Peer nonce.
int32_t ref_count; // Peer reference count.
struct msg *msg_head; // Message queue head.
struct msg *msg_tail; // Message queue tail.
size_t msg_len; // Total message queue length.
time_t alive; // Peer last message time (alive or not?)
struct in6_addr to_addr; // Peer remote address.
in_port_t to_port; // Peer remote port.
struct in6_addr from_addr; // Peer local address.
in_port_t from_port; // Peer local port.
char *name; // Peer name (string version of to_addr).
uint32_t index; // Peer index.
int16_t score; // Peer DoS score.
int16_t inv_score; // Peer inv limit.
bool ready; // Peer is ready? (have seen version message?)
bool sync; // Peer is synced? (up-to-date height?)
bool local_sync; // This peer is synced?
bool outbound; // Peer is an outbound connection?
bool error; // Has an error occurred?
};
// Delayed message.
struct delay
{
size_t index; // Peer index waiting for response.
uint64_t nonce; // Peer nonce.
struct delay *next; // Next delayed message.
};
// Table entry.
struct entry
{
uint256_t hash; // Entry hash.
uint64_t vote; // Entry vote mask (which peers have object?)
time_t time; // Entry time.
uint8_t type; // Entry type.
uint8_t state; // Entry state (observed, fetching, available).
uint16_t ref_count; // Entry reference count.
uint32_t len; // Entry data length.
void *data; // Entry data.
struct delay *delays; // Entry delayed messages (waiting for data).
struct entry *next; // Next entry.
};
// The big data table.
struct table
{
size_t len; // Table size.
size_t count; // Table entry count.
mutex lock; // Table lock.
struct entry **entries; // Table entries.
};
// Peer initialization info.
struct info
{
struct state *state; // The state.
size_t peer_idx; // The peer's index.
int sock; // The peer's socket.
struct in6_addr addr; // The peer's remote address.
bool outbound; // Is the peer outbound?
};
// Send worker initialization.
struct send_info
{
struct state *state; // The state.
struct peer *peer; // The peer.
};
// Inv vector element.
struct inv
{
uint32_t type; // The type.
uint256_t hash; // The hash.
};
// Entry states:
#define MISSING 0
#define OBSERVED 1
#define FETCHING 2
#define AVAILABLE 3
static void deref_peer(struct peer *peer);
/****************************************************************************/
// GLOBAL STATE:
#define PEER_RESERVE ((struct peer *)1)
#define MAX_SEEDS 8
struct state
{
// Global table:
struct table *table;
// Height logic:
mutex height_lock;
uint32_t init_height;
uint32_t height;
uint32_t height_0;
uint32_t height_1;
uint32_t height_inc;
// Our address:
mutex addr_lock;
struct in6_addr myaddr;
struct in6_addr myaddr_0;
struct in6_addr myaddr_1;
// Hash salts:
uint64_t addr_salt;
uint64_t headers_salt;
// Random numbers:
mutex rand_lock;
uint64_t state[2];
uint256_t rnum;
size_t rnum_idx;
// Stats:
size_t recv_bytes;
size_t send_bytes;
size_t num_ins;
size_t num_outs;
// Peer storage:
mutex peer_lock;
size_t peers_len;
struct peer **peers;
size_t last_idx;
// Address queue:
mutex queue_lock;
ssize_t queue_head;
ssize_t queue_tail;
size_t queue_len;
struct in6_addr *queue;
// Fetch queue:
mutex pending_lock;
struct fetch *pending;
// Coin config:
uint32_t protocol_version;
uint32_t magic;
uint16_t port;
bool use_relay;
const char *seeds[MAX_SEEDS + 1];
// Callbacks:
PN_callback cb_block;
PN_callback cb_tx;
PN_callback cb_inv;
PN_callback cb_version;
PN_callback cb_raw;
PN_callback cb_warning;
PN_callback cb_log;
// Node config:
const char *user_agent;
uint64_t services;
unsigned threshold;
bool prefetch;
unsigned num_peers;
};
// Create a new state
static struct state *alloc_state(void)
{
struct state *S = (struct state *)malloc(sizeof(struct state));
assert(S != NULL);
memset(S, 0, sizeof(struct state));
mutex_init(&S->queue_lock);
mutex_init(&S->height_lock);
mutex_init(&S->addr_lock);
mutex_init(&S->peer_lock);
mutex_init(&S->rand_lock);
mutex_init(&S->pending_lock);
return S;
}
/****************************************************************************/
// HEIGHT
// Set the current height.
static void set_height(struct state *S, uint32_t h)
{
mutex_lock(&S->height_lock);
if (h > S->height)
{
S->height_1 = S->height_0;
S->height_0 = h;
static const uint32_t MAX_DIFF = 6;
uint32_t diff = (S->height_0 < S->height_1?
S->height_1 - S->height_0:
S->height_0 - S->height_1);
if (diff <= MAX_DIFF)
{
S->height = (S->height_0 < S->height_1?
S->height_0:
S->height_1);
S->height_inc = S->height;
}
else if (h <= S->height_inc && S->height_inc - h < MAX_DIFF)
{
S->height = h;
S->height_inc = S->height;
}
}
mutex_unlock(&S->height_lock);
}
// Set the current height.
static bool clobber_height(struct state *S, uint32_t h)
{
bool is_new = false;
mutex_lock(&S->height_lock);
if (h > S->height)
{
is_new = true;
S->height_1 = S->height_0 = S->height_inc = h;
}
mutex_unlock(&S->height_lock);
return is_new;
}
// Increment the height for a new block. This is tricky because of orphan
// blocks, so care must be taken not to overtake the real height.
static void height_inc(struct state *S)
{
mutex_lock(&S->height_lock);
if (S->height > S->init_height)
{
S->height_inc++;
static const uint32_t MAX_DIFF = 6;
if (S->height + MAX_DIFF < S->height_inc)
S->height = S->height_inc - MAX_DIFF;
}
mutex_unlock(&S->height_lock);
}
// Get the current height.
static uint32_t get_height(struct state *S)
{
mutex_lock(&S->height_lock);
uint32_t h = S->height;
mutex_unlock(&S->height_lock);
return h;
}
/****************************************************************************/
// ADDRESS
//
// PseudoNode thinks its address is A if 2 or more outbound peers agree.
// Set address.
static bool set_my_addr(struct state *S, struct in6_addr addr)
{
mutex_lock(&S->addr_lock);
S->myaddr_1 = S->myaddr_0;
S->myaddr_0 = addr;
bool new = false;
if (memcmp(&S->myaddr_0, &S->myaddr_1, sizeof(S->myaddr_0)) == 0)
{
new = (memcmp(&S->myaddr, &S->myaddr_1, sizeof(S->myaddr)) != 0);
S->myaddr = S->myaddr_1;
}
mutex_unlock(&S->addr_lock);
return new;
}
// Get address.
static struct in6_addr get_my_addr(struct state *S)
{
mutex_lock(&S->addr_lock);
struct in6_addr addr = S->myaddr;
mutex_unlock(&S->addr_lock);
return addr;
}
/****************************************************************************/
// LOGGING
#define MAX_LOG 4096
#define ACTION 0
#define LOG 1
#define WARNING 2
#define FATAL 3
// Print fancy log message.
static void print_log(struct state *S, unsigned type, PN_callback cb,
struct in6_addr addr, const char *format, ...)
{
if (cb == NULL)
return;
va_list ap;
va_start(ap, format);
char buf[MAX_LOG];
int res = vsnprintf(buf, sizeof(buf)-1, format, ap);
if (res <= 0 || res > sizeof(buf)-1)
{
va_end(ap);
return;
}
char *message = strdup(buf);
if (message == NULL)
{
va_end(ap);
return;
}
unsigned len = res + 1;
message = (char *)cb((struct PN *)S, type, addr, (unsigned char *)message,
&len);
free(message);
va_end(ap);
}
#define action(S, addr, format, ...) \
print_log(S, PN_CALLBACK_LOG, S->cb_log, addr, format, ##__VA_ARGS__)
#define log(S, format, ...) \
print_log(S, PN_CALLBACK_LOG, S->cb_log, addr, format, ##__VA_ARGS__)
#define warning(S, addr, format, ...) \
print_log(S, PN_CALLBACK_WARNING, S->cb_warning, addr, format, \
##__VA_ARGS__)
#define fatal(format, ...) \
do { \
fprintf(stderr, "fatal: " format "\n", ##__VA_ARGS__); \
abort(); \
} while (false)
/****************************************************************************/
// MEMORY ALLOCATION
static inline void *mem_alloc(size_t size)
{
void *mem = malloc(size);
assert(mem != NULL);
return mem;
}
#define mem_free free
/****************************************************************************/
// HASH FUNCTIONS
static uint256_t sha256(const void *data, size_t len)
{
uint256_t res;
sha256_hash(data, len, (char *)&res);
return res;
}
static uint256_t hash(const void *data, size_t len)
{
uint256_t res = sha256(data, len);
res = sha256(&res, sizeof(res));
return res;
}
static uint256_t addr_hash(struct state *S, struct in6_addr addr)
{
addr.s6_addr16[0] ^= (uint16_t)S->addr_salt;
addr.s6_addr16[1] ^= (uint16_t)(S->addr_salt >> 16);
addr.s6_addr16[2] ^= (uint16_t)(S->addr_salt >> 32);
addr.s6_addr16[3] ^= (uint16_t)(S->addr_salt >> 48);
return sha256(&addr, sizeof(addr));
}
static uint256_t headers_hash(struct state *S, uint256_t hsh)
{
hsh.i64[0] ^= S->headers_salt;
return sha256(&hsh, sizeof(hsh));
}
/****************************************************************************/
// RANDOM NUMBERS
// Initialize random numbers.
static void rand64_init(struct state *S)
{
S->rnum_idx = SIZE_MAX;
if (!rand_init(S->state))
fatal("failed to initialize random numbers");
}
// Return a 64-bit random number.
static uint64_t rand64(struct state *S)
{
mutex_lock(&S->rand_lock);
if (S->rnum_idx >= sizeof(uint256_t) / sizeof(uint64_t))
{
S->state[0]++;
if (S->state[0] == 0)
S->state[1]++;
S->rnum = sha256(S->state, sizeof(S->state));
S->rnum_idx = 0;
}
uint64_t r = S->rnum.i64[S->rnum_idx++];
mutex_unlock(&S->rand_lock);
return r;
}
/****************************************************************************/
// SIMPLE DATA BUFFERS
//
// Data buffer are mainly used to store/construct/deconstruct messages. They
// are analogous to C++'s vector<> type.
#define BUFFER_SIZE 256
// Allocate a new buffer. Note env must be non-NULL if we intend to read from
// the buffer (e.g. use pop()).
static struct buf *alloc_buf(jmp_buf *env)
{
struct buf *buf = (struct buf *)mem_alloc(sizeof(struct buf));
char *data = (char *)mem_alloc(BUFFER_SIZE);
buf->env = env;
buf->data = data;
buf->len = BUFFER_SIZE;
buf->ptr = 0;
buf->ref_count = 1;
return buf;
}
// Reset an existing buffer.
static void reset_buf(struct buf *buf)
{
if (buf->len > BUFFER_SIZE)
{
mem_free(buf->data);
buf->data = (char *)mem_alloc(BUFFER_SIZE);
}
buf->len = BUFFER_SIZE;
buf->ptr = 0;
}
static void ref_buf(struct buf *buf)
{
if (buf == NULL)
return;
atomic_add(&buf->ref_count, 1);
}
static void deref_buf(struct buf *buf)
{
if (buf == NULL)
return;
ssize_t ref_count = atomic_sub(&buf->ref_count, 1);
if (ref_count > 1)
return;
mem_free(buf->data);
mem_free(buf);
}
// Grow (i.e. reserve space) a buffer by length `len'.
static void grow_buf(struct buf *buf, size_t len)
{
if (buf->len - buf->ptr >= len)
return;
size_t old_len = buf->len;
while (buf->len - buf->ptr < len)
buf->len = 2 * buf->len;
char *old_data = buf->data;
buf->data = (char *)mem_alloc(buf->len);
memcpy(buf->data, old_data, old_len);
mem_free(old_data);
}
// Push data onto a buffer.
#define push(buf, v) \
do { \
grow_buf((buf), sizeof(v)); \
memcpy((buf)->data + (buf)->ptr, &(v), sizeof(v)); \
(buf)->ptr += sizeof(v); \
} while (false)
// Push a varint.
static void push_varint(struct buf *buf, uint64_t v)
{
uint8_t v8; uint16_t v16; uint32_t v32;
if (v < 0xFD)
{
v8 = (int8_t)v;
push(buf, v8);
}
else if (v <= 0xFFFF)
{
v8 = 0xFD; push(buf, v8);
v16 = (uint16_t)v; push(buf, v16);
}
else if (v <= 0xFFFFFFFF)
{
v8 = 0xFE; push(buf, v8);
v32 = (uint32_t)v; push(buf, v32);
}
else
{
v8 = 0xFF; push(buf, v8);
push(buf, v);
}
}
// Push a varstr.
static void push_varstr(struct buf *buf, const char *str)
{
size_t len = strlen(str);
push_varint(buf, len);
grow_buf(buf, len);
memcpy(buf->data + buf->ptr, str, len);
buf->ptr += len;
}
// Push the contents of another buffer.
static void push_buf(struct buf *buf, const struct buf *data)
{
grow_buf(buf, data->ptr);
memcpy(buf->data + buf->ptr, data->data, data->ptr);
buf->ptr += data->ptr;
}
// Push arbitrary data.
static void push_data(struct buf *buf, size_t len, const void *data)
{
grow_buf(buf, len);
memcpy(buf->data + buf->ptr, data, len);
buf->ptr += len;
}
// pop_error() will be called if a message is truncated.
static int pop_error(jmp_buf *env, size_t len)
{
assert(env != NULL);
longjmp(*env, 1);
}
// Pop data of `type' from the buffer.
#define pop(buf, type) \
(((buf)->ptr + sizeof(type) <= (buf)->len? 0: \
pop_error((buf)->env, sizeof(type))), \
(buf)->ptr += sizeof(type), \
*(type *)((buf->data + (buf)->ptr - sizeof(type))))
// Pop a varint from the buffer.
static uint64_t pop_varint(struct buf *buf)
{
uint8_t v8 = pop(buf, uint8_t);
if (v8 < 0xFD)
return (uint64_t)v8;
else if (v8 == 0xFD)
return (uint64_t)pop(buf, uint16_t);
else if (v8 == 0xFE)
return (uint64_t)pop(buf, uint32_t);
else
return pop(buf, uint64_t);
}
// Pop arbitrary "data" of length `len' from the buffer.
static char *pop_data(struct buf *buf, size_t len)
{
if ((buf)->ptr + (len) > (buf)->len)
pop_error(buf->env, len);
char *data = mem_alloc(len);
memcpy(data, buf->data + buf->ptr, len);
buf->ptr += len;
return data;
}
// Pop a varstr from the buffer.
static char *pop_varstr(struct buf *buf)
{
size_t len = pop_varint(buf);
if (buf->ptr + len > buf->len)
pop_error(buf->env, len);
char *s = (char *)mem_alloc(len+1);
memcpy(s, buf->data + buf->ptr, len);
s[len] = '\0';
buf->ptr += len;
return s;
}
// Returns `true' if the buffer has no more data.
static bool is_empty(struct buf *buf)
{
return (buf->ptr == buf->len);
}
// Invoke a callback on a struct buf.
static bool callback_buf(struct state *S, unsigned type, struct in6_addr addr,
struct buf *in, PN_callback f)
{
unsigned len = in->ptr;
unsigned char *new_data = f((struct PN *)S, type, addr,
(unsigned char *)in->data, &len);
if (new_data == NULL)
{
in->len = in->ptr = 0;
in->data = NULL;
return false;
}
in->len = in->ptr = len;
in->data = (char *)new_data;
return true;
}
/****************************************************************************/
// DATA TABLE
//
// The monolithic data "table". Stores blocks, tx, peers, addrs, etc., etc.
// Acts are PseudoNode's mempool, blockchain, address list, etc., etc.
// Create a new table. Only ever called once.
static struct table *alloc_table(void)
{
struct table *table = (struct table *)mem_alloc(sizeof(struct table));
size_t len = 4096;
struct entry **entries = (struct entry **)mem_alloc(
len * sizeof(struct entry *));
memset(entries, 0, len * sizeof(struct entry *));
table->len = len;
table->count = 0;
table->entries = entries;
mutex_init(&table->lock);
return table;
}
// Population count (for tallying votes):
static size_t tally(uint64_t x)
{
size_t count;
for (count = 0; x; count++)
x &= x - 1;
return count;
}
// Get the table index from a hash.
#define get_index(table, hsh) ((size_t)(hsh).i32[4] % (table)->len)
// Possibly grow the table if we are running out of space. Assumes a locked
// table.
static void grow_table(struct table *table)
{
const size_t FACTOR = 8;
if (table->count < FACTOR * table->len)
return;
size_t len = table->len;
table->len *= 2;
struct entry **entries = table->entries;
table->entries = (struct entry **)mem_alloc(
table->len * sizeof(struct entry *));
memset(table->entries, 0, table->len * sizeof(struct entry *));
for (size_t i = 0; i < len; i++)
{
struct entry *entry = entries[i];
while (entry != NULL)
{
struct entry *e = entry;
entry = entry->next;
size_t idx = get_index(table, e->hash);
e->next = table->entries[idx];
table->entries[idx] = e;
}
}
mem_free(entries);
}
// Find the entry associated with `hsh'. Assumes a locked table.
static struct entry *get_entry(struct table *table, uint256_t hsh)
{
size_t idx = get_index(table, hsh);
struct entry *entry = table->entries[idx];
while (entry != NULL)
{
if (memcmp(&hsh, &entry->hash, sizeof(hsh)) == 0)
return entry;
entry = entry->next;
}
return NULL;
}
// Vote some (potential) data into existence. In effect, this creates and
// initializes a new entry (if one does not already exist), or records the
// vote for `vote_idx' of an existing entry. Each index can only vote once.
// Inbound peers are not allowed to vote to prevent ballot stuffing.
static uint64_t vote(struct table *table, uint256_t hsh, unsigned type,
size_t vote_idx, struct state *S)
{
if (vote_idx >= S->num_peers)
return 0; // Inbound peers cannot vote.
size_t vote = (1 << (vote_idx % 64));
time_t curr_time = time(NULL);
mutex_lock(&table->lock);
struct entry *entry = get_entry(table, hsh);
if (entry != NULL)
{
entry->vote |= vote;
size_t new_vote = entry->vote;
mutex_unlock(&table->lock);
return new_vote;
}
else
{
grow_table(table);
size_t idx = get_index(table, hsh);
entry = (struct entry *)mem_alloc(sizeof(struct entry));
entry->hash = hsh;
entry->type = type;
entry->vote = vote;
entry->time = curr_time;
entry->state = OBSERVED;
entry->ref_count = 1;
entry->len = 0;
entry->data = NULL;
entry->delays = NULL;
entry->next = table->entries[idx];
table->entries[idx] = entry;
table->count++;
mutex_unlock(&table->lock);
return vote;
}
}
// Insert is similar to voting, except for data where the vote count is
// irrelevant.
#define insert(table, hsh, type, S) vote((table), (hsh), (type), 0, (S))
// Free an entry. Assumes a locked table.
static void free_entry(struct entry *entry)
{
struct delay *delays = entry->delays;
while (delays != NULL)
{
struct delay *d = delays;
delays = delays->next;
mem_free(d);
}
mem_free(entry->data);
mem_free(entry);
}
// Associate data with `hsh'. Returns false if data already exists.
static bool set_data(struct table *table, uint256_t hsh, void *data,
size_t len)
{
assert(len <= UINT32_MAX);
bool ok = true;
mutex_lock(&table->lock);
struct entry *entry = get_entry(table, hsh);
if (entry != NULL)
{
if (entry->data == NULL)
{
entry->len = len;
entry->data = data;
entry->state = AVAILABLE;
}
else
ok = false;
}
else
ok = false;
mutex_unlock(&table->lock);
return ok;
}
// Get the data associated with `hsh', otherwise return NULL. If non-NULL
// data is returned, then the entry reference count is increased.
static void *get_data(struct table *table, uint256_t hsh, size_t *lenptr)
{
void *data = NULL;
if (lenptr != NULL)
*lenptr = 0;
mutex_lock(&table->lock);
struct entry *entry = get_entry(table, hsh);
if (entry != NULL)
{
data = entry->data;
if (lenptr != NULL)
*lenptr = (size_t)entry->len;
if (data != NULL)
entry->ref_count++;
}
mutex_unlock(&table->lock);
return data;
}
// Deref the data associated with `hsh'. Free the entry if the ref count is 0.
static bool deref_data(struct table *table, uint256_t hsh)
{
mutex_lock(&table->lock);
size_t idx = get_index(table, hsh);
struct entry *entry = table->entries[idx], *prev = NULL;
while (entry != NULL)
{
if (memcmp(&hsh, &entry->hash, sizeof(hsh)) == 0)
{
if (entry->ref_count > 1)
{
entry->ref_count--;
mutex_unlock(&table->lock);
return false;
}
if (prev == NULL)
table->entries[idx] = entry->next;
else
prev->next = entry->next;
table->count--;
mutex_unlock(&table->lock);
free_entry(entry);
return true;
}
prev = entry;
entry = entry->next;
}
mutex_unlock(&table->lock);
return false;
}
// Set the state associated with `hsh'. Return the old state.
static unsigned set_state(struct table *table, uint256_t hsh, unsigned state)
{
time_t curr_time = time(NULL);
unsigned old_state = MISSING;
mutex_lock(&table->lock);
struct entry *entry = get_entry(table, hsh);
if (entry != NULL && entry->state < state)
{
old_state = entry->state;
entry->state = state;
entry->time = curr_time;
}
mutex_unlock(&table->lock);
return old_state;
}
// Get the state associated with `hsh'.
static unsigned get_state(struct table *table, uint256_t hsh)
{
unsigned state = MISSING;
mutex_lock(&table->lock);
struct entry *entry = get_entry(table, hsh);
if (entry != NULL)
state = entry->state;
mutex_unlock(&table->lock);
return state;
}
// Set the time associated with `hsh'.
static void set_time(struct table *table, uint256_t hsh, time_t time)
{
mutex_lock(&table->lock);
struct entry *entry = get_entry(table, hsh);
if (entry != NULL)