forked from rustyrussell/bitcoin-iterate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockfiles.c
72 lines (65 loc) · 1.84 KB
/
blockfiles.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
#include <ccan/err/err.h>
#include <ccan/tal/path/path.h>
#include <ccan/tal/str/str.h>
#include <ccan/short_types/short_types.h>
#include <unistd.h>
#include <stdio.h>
#include <pwd.h>
#include <dirent.h>
#include "blockfiles.h"
static void add_name(char ***names_p, unsigned int num, char *name)
{
size_t count = tal_count(*names_p);
if (num >= count) {
tal_resize(names_p, num + 1);
memset(*names_p + count, 0, sizeof(char *) * (num + 1 - count));
}
if ((*names_p)[num])
errx(1, "Duplicate block file for %u? '%s' and '%s'",
num, name, (*names_p)[num]);
(*names_p)[num] = name;
}
char **block_filenames(tal_t *ctx, const char *path, enum networks network){
char **names = tal_arr(ctx, char *, 0);
char *tmp_ctx = tal_arr(ctx, char, 0);
DIR *dir;
struct dirent *ent;
if (!path) {
char *base = getenv("HOME");
if (!base) {
struct passwd *passwd = getpwuid(getuid());
if (!passwd)
err(1, "Could not get home dir");
base = passwd->pw_dir;
}
base = path_join(tmp_ctx, base, ".bitcoin");
if (network == TESTNET3)
base = path_join(tmp_ctx, base, "testnet3");
if (network == REGTEST)
base = path_join(tmp_ctx, base, "regtest");
if (network == SIGNET)
base = path_join(tmp_ctx, base, "signet");
/* First try new-style: $HOME/.bitcoin/blocks/blk[0-9]*.dat. */
path = path_join(tmp_ctx, base, "blocks");
dir = opendir(path);
if (!dir) {
/* Old-style: $HOME/.bitcoin/blk[0-9]*.dat. */
path = base;
dir = opendir(path);
}
} else
dir = opendir(path);
if (!dir)
err(1, "Could not open bitcoin dir '%s'", path);
while ((ent = readdir(dir)) != NULL) {
char *numstr;
int num;
if (!tal_strreg(tmp_ctx, ent->d_name,
"^blk([0-9]+)\\.dat$", &numstr))
continue;
num = strtol(numstr, NULL, 10);
add_name(&names, num, path_join(names, path, ent->d_name));
}
tal_free(tmp_ctx);
return names;
}