使用C++写一段区块链的代码
时间: 2023-05-23 17:02:33 浏览: 266
我很乐意回答您的问题,以下是一段使用 C 语言实现的简单区块链代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define BLOCK_SIZE 512 // 区块大小
#define HASH_SIZE 64 // hash 值大小
typedef struct Block {
int index; // 区块链索引
time_t timestamp; // 时间戳
char data[BLOCK_SIZE]; // 数据
char prev_hash[HASH_SIZE]; // 上一个区块的 hash 值
char hash[HASH_SIZE]; // 当前区块的 hash 值
struct Block* next; // 下一个区块的指针
} Block;
// 生成 hash 值的函数
char* generate_hash(char* data) {
char* hash = (char*)malloc(sizeof(char) * HASH_SIZE);
// 实现 hash 算法
// ...
return hash;
}
int main() {
Block* head = (Block*)malloc(sizeof(Block));
head->index = 0;
head->timestamp = time(0);
strcpy(head->data, "This is the first block.");
memset(head->prev_hash, 0, HASH_SIZE);
strcpy(head->hash, generate_hash(head->data));
head->next = NULL;
Block* curr = head;
// 添加新的区块
Block* new_block = (Block*)malloc(sizeof(Block));
new_block->index = curr->index + 1;
new_block->timestamp = time(0);
strcpy(new_block->data, "This is the second block.");
strcpy(new_block->prev_hash, curr->hash);
strcpy(new_block->hash, generate_hash(new_block->data));
curr->next = new_block;
curr = new_block;
// 输出区块链的内容
curr = head;
while (curr != NULL) {
printf("Index: %d\n", curr->index);
printf("Timestamp: %ld\n", curr->timestamp);
printf("Data: %s\n", curr->data);
printf("Prev Hash: %s\n", curr->prev_hash);
printf("Hash: %s\n", curr->hash);
curr = curr->next;
}
// 释放内存
curr = head;
while (curr != NULL) {
Block* temp = curr;
curr = curr->next;
free(temp);
}
return 0;
}
```
以上代码实现了一个基本的区块链,包含了区块链的索引、时间戳、数据、上一个区块的 hash 值和当前区块的 hash 值,通过链接不同的区块形成区块链。
阅读全文