#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ------------------------------
Simple Hash Function (Pedagogical)
NOT cryptographically secure
-------------------------------- */
unsigned int simple_hash(const char *data)
{
unsigned int hash = 0;
while (*data)
{
hash = hash * 31 + *data;
data++;
}
return hash;
}
/* ------------------------------
Block Structure with Hash Pointer
-------------------------------- */
typedef struct Block
{
char data[100];
unsigned int previous_hash; // hash pointer part
struct Block *previous; // normal pointer part
} Block;
/* ------------------------------
Create New Block
-------------------------------- */
Block *create_block(const char *data, Block *previous_block)
{
Block
*new_block
= (Block
*)malloc(sizeof(Block
)); strcpy(new_block
->data
, data
); new_block->previous = previous_block;
if (previous_block == NULL)
new_block->previous_hash = 0; // Genesis block
else
new_block->previous_hash = simple_hash(previous_block->data);
return new_block;
}
/* ------------------------------
Verify Integrity of Chain
-------------------------------- */
int verify_chain(Block *current)
{
while (current->previous != NULL)
{
unsigned int recalculated_hash =
simple_hash(current->previous->data);
if (recalculated_hash != current->previous_hash)
return 0; // Tampering detected
current = current->previous;
}
return 1; // Chain is valid
}
/* ------------------------------
Print Blockchain
-------------------------------- */
void print_chain(Block *current)
{
while (current != NULL)
{
printf("Block Data: %s\n", current
->data
); printf("Previous Hash: %u\n", current
->previous_hash
); printf("-------------------------\n");
current = current->previous;
}
}
/* ------------------------------
Main Demonstration
-------------------------------- */
int main()
{
Block *genesis = create_block("Genesis Block", NULL);
Block *block2 = create_block("Second Block", genesis);
Block *block3 = create_block("Third Block", block2);
printf("=== Original Chain ===\n"); print_chain(block3);
if (verify_chain(block3))
else
printf("\n--- Tampering with Block 2 ---\n"); strcpy(block2
->data
, "Hacked Data");
if (verify_chain(block3))
else
printf("Chain is INVALID (Tampering Detected)\n");
return 0;
}