Case study
Problem statement 2:
C program solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BLOCKS 100
struct Block {
int index;
char previousHash[64];
char currentHash[64];
char transactionData[256];
};
void generateHash(const char* input, char* output) {
unsigned long hash = 5381;
int c;
while ((c = *input++)) {
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
sprintf(output, "%lx", hash);
}
void createBlock(struct Block *blockchain, int index, const char*
previousHash, const char* transactionData) {
struct Block newBlock;
newBlock.index = index;
strcpy(newBlock.previousHash, previousHash);
strcpy(newBlock.transactionData, transactionData);
char combinedData[512];
sprintf(combinedData, "%s%s", previousHash,
transactionData);
generateHash(combinedData, newBlock.currentHash);
blockchain[index] = newBlock;
}
void displayBlockchain(struct Block *blockchain, int blockCount)
{
printf("\nBlockchain:\n");
for (int i = 0; i < blockCount; i++) {
printf("Block %d:\n", blockchain[i].index);
printf("Previous Hash: %s\n", blockchain[i].previousHash);
printf("Current Hash: %s\n", blockchain[i].currentHash);
printf("Transaction Data: %s\n\n",
blockchain[i].transactionData);
}
}
int main() {
struct Block blockchain[MAX_BLOCKS];
int blockCount = 0;
char previousHash[64] = "0";
char transactionData[256];
strcpy(transactionData, "User A transfers $100 to User B");
createBlock(blockchain, blockCount++, previousHash,
transactionData);
strcpy(previousHash, blockchain[blockCount -
1].currentHash);
strcpy(transactionData, "User C transfers $200 to User D");
createBlock(blockchain, blockCount++, previousHash,
transactionData);
strcpy(previousHash, blockchain[blockCount -
1].currentHash);
displayBlockchain(blockchain, blockCount);
return 0;
}
Explanation of the Program:
1. Blockchain Implementation:
o The program uses a basic block structure where each
block contains:
Index: Position in the blockchain.
Previous Hash: Hash of the previous block to ensure
immutability.
Current Hash: Generated based on the previous hash
and transaction data.
Transaction Data: A string representing banking
transactions.
2. Block Creation:
o The createBlock function generates a new block by
calculating a simple hash of the previous block’s hash and
transaction data. This ensures that every block is linked to
the previous one, simulating a blockchain’s immutable
ledger.
3. Transaction Simulation:
o The program simulates a few transactions between users
and stores them in the blockchain. Each transaction creates
a new block.
4. Security and Data Integrity:
o Immutability: Each block's hash is dependent on the
previous block, ensuring that any attempt to alter a block
invalidates the entire chain, thereby protecting data integrity.