forked from capythulhu/coxinhacoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.h
86 lines (70 loc) · 2.01 KB
/
block.h
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
// Header guards
#ifndef BLOCK_H
#define BLOCK_H
#ifndef TIME_H
#define TIME_H
#include <time.h>
#endif
#include "bytes.h"
#include "list.h"
#include "transaction.h"
// Estrutura do bloco
typedef struct _block {
buffer id;
buffer previousHash;
list *transactions;
buffer gold;
long timestamp;
} block;
buffer get_block_hash(const block *b);
block *new_block(buffer previousHash);
void mine_block(block *b);
bool put_transaction_on_block(block *b, transaction *t, hashmap *outputs);
// Calcular a hash de um bloco
buffer get_block_hash(const block *b) {
buffer input = new_buffer(sizeof(long));
int i;
for(i = 0; i < sizeof(long); i++) {
input.bytes[i] = b->timestamp & (0xff << (i * 8));
}
listnode *temp = b->transactions->first;
while(temp) {
concat_buffer(&input, ((transaction*)temp->val)->id);
temp = temp->next;
}
concat_buffer(&input, b->previousHash);
return hash(input);
}
// Gerar novo bloco
block *new_block(buffer previousHash) {
block *output = malloc(sizeof(block));
output->previousHash = previousHash;
output->timestamp = time(NULL);
output->transactions = new_list();
output->id = new_buffer(1);
return output;
}
// Minera um bloco
void mine_block(block *b) {
printf("Mining block...\n");
if(b->id.length > 0) free_buffer(b->id);
b->id = get_block_hash(b);
b->gold = new_buffer(HASH_LENGTH);
while(!mine(b->id, b->gold, true)) increment_buffer(b->gold);
printf("Block mined.\n");
}
// Adiciona transação
bool put_transaction_on_block(block *b, transaction *t, hashmap *outputs) {
if(!b || !t) return false;
if(b->previousHash.length > 0
&& !compare_buffer_with_int(b->previousHash, 0)
&& b->previousHash.bytes) {
if(!process_transaction(t, outputs)) {
printf("Transaction failed to process.\n");
}
}
printf("Transaction processed successfully.\n");
put_val_on_list(b->transactions, t);
return true;
}
#endif