What is Block in Blockchain: Explanation and Solidity Example
block in blockchain is a container that holds a group of transactions and related data, linked securely to previous blocks forming a chain. Each block ensures data integrity and order, making blockchain tamper-resistant.How It Works
Think of a block as a page in a ledger book where multiple transactions are recorded. Each block contains a list of transactions, a timestamp, and a reference to the previous block, creating a secure chain.
This linking is like a chain of locked boxes, where each box holds information and a key to the previous box. Changing one block would break the chain, so the blockchain stays trustworthy and secure.
Example
This Solidity example shows a simple Block struct that stores transactions and links to the previous block's hash.
pragma solidity ^0.8.0; contract SimpleBlockchain { struct Block { uint id; string data; bytes32 previousHash; bytes32 blockHash; uint timestamp; } Block[] public blocks; constructor() { // Create the first block (genesis block) _createBlock("Genesis Block", 0x0); } function _createBlock(string memory data, bytes32 prevHash) private { uint blockId = blocks.length; uint time = block.timestamp; bytes32 hash = keccak256(abi.encodePacked(blockId, data, prevHash, time)); blocks.push(Block(blockId, data, prevHash, hash, time)); } function addBlock(string memory data) public { bytes32 prevHash = blocks[blocks.length - 1].blockHash; _createBlock(data, prevHash); } function getBlock(uint index) public view returns (uint, string memory, bytes32, bytes32, uint) { require(index < blocks.length, "Block does not exist"); Block memory blk = blocks[index]; return (blk.id, blk.data, blk.previousHash, blk.blockHash, blk.timestamp); } }
When to Use
Blocks are used whenever you need a secure, ordered record of transactions or data that cannot be changed without detection. This is common in cryptocurrencies like Ethereum, supply chain tracking, voting systems, and digital identity verification.
Using blocks in a blockchain helps build trust without a central authority, making it ideal for decentralized applications and smart contracts.
Key Points
- A
blockstores a batch of transactions and links to the previous block. - Blocks form a chain that secures data integrity and order.
- Each block has a unique hash based on its content and previous block.
- Changing one block breaks the chain, preventing tampering.
- Blocks enable decentralized, trustless systems like cryptocurrencies and smart contracts.