This repository has been archived by the owner on Jan 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmerkle.c
102 lines (87 loc) · 1.69 KB
/
merkle.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
#include <stdio.h>
#include <stdlib.h>
#include "sha256.h"
#define SEGSIZE 64
typedef struct stack stack;
typedef struct elem elem;
void push(stack*, elem*);
elem* pop(stack*);
void collapse(stack*);
uint8* root(stack*);
void readFrom(stack*, FILE*);
void printHash(uint8*);
struct stack {
elem* head;
};
struct elem {
int height;
uint8 sum[32];
elem* next;
};
sha256_context ctx;
void push(stack* s, elem* e) {
e->next = s->head;
s->head = e;
while (s->head->next != NULL && s->head->height == s->head->next->height) {
collapse(s);
}
}
elem* pop(stack* s) {
elem* e = s->head;
s->head = s->head->next;
return e;
}
void collapse(stack* s) {
elem* oldhead = pop(s);
sha256_starts(&ctx);
sha256_update(&ctx, s->head->sum, 32);
sha256_update(&ctx, oldhead->sum, 32);
sha256_finish(&ctx, s->head->sum);
s->head->height++;
free(oldhead);
}
uint8* root(stack* s) {
if (s->head == NULL) {
return NULL;
}
while (s->head->next != NULL) {
collapse(s);
}
return s->head->sum;
}
void readFrom(stack* s, FILE* f) {
uint8* leaf = malloc(SEGSIZE);
while (!ferror(f) && !feof(f)) {
size_t n = fread(leaf, 1, SEGSIZE, f);
elem* e = calloc(1, sizeof(elem));
sha256_starts(&ctx);
sha256_update(&ctx, leaf, n);
sha256_finish(&ctx, e->sum);
push(s, e);
}
}
void printHash(uint8* hash) {
int i;
for (i = 0; i < 32; i++) {
printf("%.2x", hash[i]);
}
printf("\n");
}
int main() {
FILE* f = fopen("test.dat", "r");
if (f == NULL) {
printf("couldn't open file");
return 1;
}
stack s;
s.head = NULL;
readFrom(&s, f);
fclose(f);
uint8* merkleRoot = root(&s);
if (merkleRoot == NULL) {
printf("couldn't calculate Merkle root");
return 1;
}
printHash(merkleRoot);
return 0;
}