#define BLOCK_SIZE 16384
struct block {
- size_t index;
+ int index;
unsigned char hash[crypto_hash_sha256_BYTES];
struct block *next;
};
-int block_duplicate(struct block**,struct block*);
void block_free(struct block*);
int block_init(struct block**);
size_t block_length(struct block*);
char *name;
char *path;
+ struct block *blocks;
struct block *root;
struct block *piece_layers;
- struct block *blocks;
uint64_t size;
};
#include<block.h>
-int block_duplicate(struct block **root, struct block *to_dup) {
- struct block *prev, *p;
- if(NULL==root) { return -1; }
- if(NULL==to_dup) { return -1; }
-
- prev = NULL;
- while(to_dup!=NULL) {
- if(block_init(&p)<0) { return -1; }
-
- memcpy(p->hash,to_dup->hash,crypto_hash_sha256_BYTES);
-
- if(NULL==prev) {
- *root = p;
- } else {
- prev->next = p;
- }
-
- prev = p;
- to_dup = to_dup->next;
- }
-
- return 1;
-}
-
void block_free(struct block *p) {
struct block *next;
return -1;
}
- (*p)->index = 0;
+ (*p)->index = -1;
memset((*p)->hash,0,crypto_hash_sha256_BYTES);
(*p)->next = NULL;
}
int block_merkle_root(struct block *root) {
+ struct block *end;
if(NULL==root) { return -1; }
+ end = NULL;
while(root->next!=NULL) {
- if(block_merkle_layer(root)<0) { return -1; }
+ end = block_merkle_layer(root,end);
+ if(NULL==end) { return -1; }
}
return 1;
}
while((i==1)||(i&&(i&(i-1)))) {
+ // block_init sets index to -1 and hash to all 0's
if(block_init(&(p->next))<0) { return -1; }
- memset(p->next->hash,0,crypto_hash_sha256_BYTES);
p = p->next;
i++;
}
uint8_t data[BLOCK_SIZE];
struct block *p, *next;
FILE *fp;
+ int i;
if(NULL==file_p) { return -1; }
}
p = NULL;
+ i = 0;
while(1) {
size_t len = fread(data,sizeof(uint8_t),BLOCK_SIZE,fp);
if((len<=BLOCK_SIZE)&&(ferror(fp)!=0)) {
file_p->size += len;
if(block_init(&next)<0) { goto clean; }
+
+ next->index = i;
+ i++;
+
if(hash(data,len,next->hash,crypto_hash_sha256_BYTES)<0) { goto clean; }
if(NULL==p) {
fclose(fp);
- // generate merkle root
- if(block_duplicate(&p,file_p->piece_layers)<0) { return -1; }
if(block_length(p)>1) {
if(block_pad(p)<0) { goto clean; }
}
- if(block_merkle_root(p)<0) { goto clean; }
- memcpy(file_p->root,p->hash,crypto_hash_sha256_BYTES);
- block_free(p);
+ if(block_merkle_root(p)<0) { goto clean; }
if(file_piece_layers(file_p,piece_length)<0) { return -1; }
return 1;