What is Blockchain: Explanation and Solidity Example
blockchain is a secure, decentralized digital ledger that records transactions in linked blocks. Each block contains data and a reference to the previous block, making the chain tamper-resistant and transparent.How It Works
Imagine a blockchain as a chain of blocks, where each block is like a page in a ledger book. When you write a transaction on a page, it is linked to the previous page by a special code called a hash. This linking makes it very hard to change any page without changing all the following pages, which everyone can see.
Because many people keep copies of this ledger, no single person can change the records secretly. This makes blockchain very secure and trustworthy, like a shared notebook that everyone agrees on and checks together.
Example
This Solidity example shows a simple contract that stores a list of transactions, each linked by a hash to the previous one, mimicking a blockchain structure.
pragma solidity ^0.8.19; contract SimpleBlockchain { struct Block { uint id; string data; bytes32 prevHash; bytes32 blockHash; } Block[] public blocks; constructor() { // Create the first block with no previous hash _addBlock("Genesis Block", bytes32(0)); } function _addBlock(string memory data, bytes32 prevHash) private { uint id = blocks.length; bytes32 blockHash = keccak256(abi.encodePacked(id, data, prevHash)); blocks.push(Block(id, data, prevHash, blockHash)); } function addBlock(string memory data) public { bytes32 prevHash = blocks[blocks.length - 1].blockHash; _addBlock(data, prevHash); } function getBlock(uint index) public view returns (uint, string memory, bytes32, bytes32) { require(index < blocks.length, "Block does not exist"); Block memory blk = blocks[index]; return (blk.id, blk.data, blk.prevHash, blk.blockHash); } }
When to Use
Use blockchain when you need a secure, transparent, and tamper-proof record of transactions without relying on a single trusted party. It is ideal for financial services, supply chain tracking, voting systems, and digital identity management.
For example, blockchain can track the origin of goods in a supply chain, ensuring authenticity, or enable secure peer-to-peer payments without banks.
Key Points
- Blockchain is a linked chain of blocks storing data securely.
- Each block references the previous one using a hash, making tampering difficult.
- It is decentralized, with many participants verifying the data.
- Solidity can be used to create smart contracts that interact with blockchain data.