General Logic
The idea
Here is the complete implementation of the General Logic. You can copy and paste the code into your main.ts
file.
Blockchain Architecture
Our blockchain implementation consists of three main components that work together:
- Block Class - Represents individual blocks in the chain
- Wallet Class - Handles user accounts and transactions
- Blockchain Class - Manages the entire blockchain network
Block Class Logic
The Block class is the fundamental building block of our blockchain:
- Properties: Each block contains an index, timestamp, transactions array, previous hash, its own hash, and a nonce value
- Hash Calculation: The block's hash is calculated using all its properties, creating a unique fingerprint
- Mining: The mineBlock method finds a hash that starts with a specific number of zeros (difficulty), requiring computational work
- Transaction Limit: Each block can hold a maximum of 10 transactions to maintain efficiency
Wallet Class Logic
The Wallet class manages user accounts and transactions:
- Transaction Creation: Allows users to send coins to other addresses
- Balance Calculation: Tracks the user's balance by analyzing the blockchain
- Transaction Verification: Validates transactions to prevent double-spending
Blockchain Class Logic
The Blockchain class orchestrates the entire network:
- Chain Management: Maintains the array of blocks that form the blockchain
- Genesis Block: Creates the first block with special properties
- Block Addition: Adds new blocks to the chain, linking them with previous hashes
- Transaction Pool: Manages pending transactions before they're added to blocks
- Validation: Verifies the integrity of the entire blockchain
Transaction Flow
The complete flow of a transaction in our blockchain:
- User creates a transaction using their wallet
- Transaction is added to the pending transactions pool
- Miners collect transactions from the pool (up to 10 per block)
- Miners perform proof-of-work to find a valid hash
- New block is added to the blockchain
- Transaction is now confirmed and permanent
- Recipient's wallet balance is updated
Security Mechanisms
The blockchain implements several security features:
- Cryptographic Hashing: Ensures data integrity and immutability
- Proof-of-Work: Makes it computationally expensive to alter the blockchain
- Chain Validation: Detects any tampering with the blockchain
- Transaction Verification: Prevents double-spending and invalid transactions
Implementation Details
Key technical details of our implementation:
- Hash Algorithm: SHA-256 for cryptographic hashing
- Mining Difficulty: Configurable number of leading zeros in block hashes
- Transaction Structure: Includes sender, recipient, amount, and signature
- Block Structure: Contains metadata and transaction data