]> git.ozlabs.org Git - ccan/blob - ccan/crypto/shachain/tools/shachain48.c
5cc910909ba1d33a9f151701a76134d9d328a0a2
[ccan] / ccan / crypto / shachain / tools / shachain48.c
1 #include <ccan/crypto/shachain/shachain.h>
2 #include <ccan/str/hex/hex.h>
3 #include <ccan/str/str.h>
4 #include <ccan/err/err.h>
5 #include <ccan/rbuf/rbuf.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9
10 int main(int argc, char *argv[])
11 {
12         if (argc == 2 && streq(argv[1], "--store")) {
13                 struct shachain s;
14                 struct rbuf rbuf;
15                 size_t size = rbuf_good_size(STDIN_FILENO);
16                 char *p;
17
18                 shachain_init(&s);
19                 rbuf_init(&rbuf, STDIN_FILENO, malloc(size), size);
20
21                 while ((p = rbuf_read_str(&rbuf, '\n', realloc)) != NULL) {
22                         struct sha256 hash;
23                         unsigned long long idx;
24
25                         if (strstarts(p, "0x"))
26                                 p += 2;
27                         if (!hex_decode(p, 64, &hash, sizeof(hash)))
28                                 errx(2, "%.*s is not 64 chars of hex", 64, p);
29                         p += 64;
30                         p += strspn(p, " \t");
31                         idx = strtoull(p, NULL, 0);
32                         if (shachain_add_hash(&s, idx, &hash))
33                                 printf("OK\n");
34                         else
35                                 printf("ERROR\n");
36                 }
37         } else if (argc == 3) {
38                 struct sha256 seed, hash;
39                 const char *p;
40                 unsigned long long idx;
41                 char hex[65];
42
43                 if (strstarts(argv[1], "0x"))
44                         p = argv[1] + 2;
45                 else
46                         p = argv[1];
47                 idx = strtoull(argv[2], NULL, 0);
48
49                 if (!hex_decode(p, 64, &seed, sizeof(seed)))
50                         errx(2, "%s is not 64 chars of hex", p);
51
52                 shachain_from_seed(&seed, idx, &hash);
53                 hex_encode(&hash, sizeof(hash), hex, sizeof(hex));
54                 printf("0x%s\n", hex);
55         } else
56                 errx(1, "Usage: shachain --store OR shachain <seed> <index>");
57         return 0;
58 }