decrypt101
SocialOpen ProjectsSupport me My Resumes
  • Preface
    • Motivation
    • Roadmap’s
  • Introduction to Blockchain
    • A Brief History
    • Growth of Blockchain
    • Structure of Blockchain
    • Types of Blockchain
    • Key Technologies of Blockchain
    • Features of Blockchain
    • How Blockchain Works ?
    • Implementation of Blockchain
    • Summary
  • Components of Blockchain Architecture
    • Distributed Ledger
    • Blocks
    • Transaction
    • Chain
    • Peer-to-Peer Network
    • Blockchain Layers
    • Off-Chain & On-Chain
    • Wallet
    • Mining
    • Tokens
    • Assets
    • State Channels
    • Sidechains
    • Oracles on Blockchain
    • Atomic Swaps
    • Decentralized Identity (DID)
    • Blockchain Data Storage
    • Interoperability
    • Data structures for Scaling Blockchain
    • Maximal Extractable Value (MEV)
  • Consensus Mechanisms
    • Proof of Work (PoW)
      • Implemation Using Rust
    • Proof of Stake (PoS)
    • Proof of Burn (PoB)
    • Proof of Capacity (PoC)
    • Proof of Activity (PoAc)
    • Proof of Weight (PoWe)
    • Proof of Luck (PoL)
    • Proof of Ownership (PoO)
    • Proof of Existence (PoE)
    • Proof of Believability (PoBe)
    • Proof of History (PoH)
    • Proof of Authority (PoA)
    • Proof of Elapsed Time (PoET)
  • Cryptographics
    • Encryption & Decryption
      • Symmetric Encryption
      • Asymmetric Encryption
      • Key Management and Exchange
      • Implementation
    • Cryptographic Hashing
      • Secure Hash Algorithms (SHA)
      • Message Digest Algorithms
      • Ethash
      • Blake2
      • SCrypt
      • RIPEMD-160
    • Digital Signature
      • Digital Signature Algorithms
      • Digital Signature in Blockchain
    • Zero-Knowledge Proofs (ZKPs)
      • Types of Zero-Knowledge Proof and Protocols
      • A Case Study of Polygon Platform
    • Multi-Party Computation (MPC)
    • Cryptanalysis
    • Practical Implementation
  • Decentralized Application (DApp)
    • Design and UX in Web3
  • Smart Contract
    • Development Tools
    • Solidity
    • Testing Smart Contract
    • Developing Smart Contract
    • Interacting & Deploying with Smart Contract
    • Verifying Smart Contracts
    • Upgrading Smart Contracts
    • Securing Smart Contract
    • Smart Contract Composability
    • Testnet and Mainnet
    • Blockchain Platform Using Smart Contract
    • Application of Smart Contract
    • Practical Implementation
  • Blockchain Platforms
    • Ethereum
      • Ethereum Virtual Machine (EVM)
      • ETHER and GAS
      • Ethereum transaction
      • Ethereum Accounts
      • Ethereum Stacking
      • Ethereum Network
      • Ethereum Scaling Solutions
      • Ethereum Use-Cases
      • Getting Started with Ethereum
      • Ethereum Ecosystem and Support
    • Solana
      • Solana Architecture
        • Solana Account Model
        • Solana Wallet
        • Transactions and Instructions
        • Solana Programs
        • Program Derived Address (PDA)
        • Cross Program Invocation (CPI)
        • Tokens on Solana
        • Clusters and Public RPC Endpoints
        • Transaction Confirmation & Expiration
        • Retrying Transactions
        • Versioned Transactions
        • Address Lookup Tables
        • State Compression
        • Actions and Blinks
      • Solana Developments
      • Solana Client
      • Advanced Solana
      • Solana Scaling and Performance Architecture
      • Solana Solutions and cases
      • Practical Implemenation
    • Binance Smart Chain (BSC)
      • Create a BEP20 Token
    • Hyperledger Fabric
    • Cosmos
    • Polkadot
    • Quorum
    • Polygon
    • Algorand
    • Corda
    • Avalanche
    • TRON
    • Summary
  • Decentralized Finance (DeFi)
    • DeFi Components
    • DeFi Protocols
    • DeFi Platforms
    • DeFi Risk Classification
      • Infrastructure-layer Attacks
      • Smart Contract Layer-attacks
      • Application Layer-attacks
      • DeFi Risks
    • DeFi and Blockchain
    • DeFi Impact
  • Decentralized Ecosystem and Digital Innovation
    • Layer 2 Scaling Fundamental
    • Tokenomics
    • Cryptocurrency
    • Quantative Trading
    • NFTs
    • GameFi
    • Metaverse
  • Blockchain as a Service (BaaS)
    • Building Fullstack Blockchain Platform
    • Decentralized Digital Identity
    • Build a Cryptocurrencies Exchange
    • Play-to-Earn Gaming
    • Solana Token Airdrop Manager
    • Smart Contract Development on Solana with Rust
    • Quantitative Trading Platform
    • Insurances protocols
    • Flash Loans
    • Asset Management
    • Tokenized Derivatives
    • Automated Market Makers (AMMs)
    • Staking
    • Lending and Borrowing Platforms
    • Yield Farming
    • Stablecoin System
    • Security Token Offerings (STOs)
    • Initial Coin Offerings (ICOs)
    • On-Chain Voting Systems
    • Decentralized Autonomous Organizations (DAOs)
    • NFT Marketplaces
    • Provenance Verification
    • Supply Chain Tracking
    • Commodities Tokenization
    • Real Estate Tokenization
    • Digital Certificates
    • KYC (Know Your Customer)
  • Blockchain Development Across Languages
    • Blockchain using Go(Golang)
    • Blockchain using Rust
    • Blockchain using Python
    • Blockchain using Cairo
  • Distributed Systems & Infrastructure Technology
    • Classification of Distributed Systems
    • Networked systems versus Distributed systems
    • Parallel systems vs Distributed systems
    • Distributed versus Decentralized systems
    • Processes of Distributed Systems
    • Architecture of Distributed systems
    • Infrastructure Technologies
  • Distributed System Patterns
    • Distributed Agreements Algorithms
      • HoneyBadgerBFT
    • Data Replications
    • Data Partition
    • Consistency
    • Distributed Time
    • Cluster Management
    • Communication between Nodes
    • Fault Tolerance and Resilience
      • How to design better fault tolerance systems
      • Resilience Patterns
    • Coordination systems
      • Clock synchronization
    • Security
      • Trust in distributed systems
      • Design of Principal Security
      • Security threats, policies, and mechanisms
      • Authentication and Authorizations
      • Cryptography
      • Monitoring in Security
  • Distributed System Design
    • Page 1
    • Distributed Shared Memory
    • Distributed Data Management
    • Distributed Knowledge Management
    • Distributed Ledger
  • FAQs
  • Support and Community
Powered by GitBook
On this page
  • A Quick Maintain Of Proof od Work using Rust
  • Output
  1. Consensus Mechanisms
  2. Proof of Work (PoW)

Implemation Using Rust

A Quick Maintain Of Proof od Work using Rust

// So
extern crate sha2;
use sha2::{Digest, Sha256};
use std::time::Instant;

// The block structure
struct Block {
    index: u64,
    timestamp: u128,
    data: String,
    prev_hash: String,
    hash: String,
    nonce: u64,
}

// The Proof of Work struct
struct ProofOfWork {
    target: Vec<u8>,
}

impl ProofOfWork {
    // Creates a new Proof of Work with a difficulty level
    fn new(difficulty: u32) -> Self {
        let mut target = vec![255; 32]; // Initialize target with max values (255)
        let shift = difficulty / 8;
        target[shift as usize] = 255 >> (difficulty % 8); // Adjust the target based on the difficulty level
        ProofOfWork { target }
    }

    // This method calculates the hash of the block with a specific nonce
    fn calculate_hash(block: &Block, nonce: u64) -> Vec<u8> {
        let data = format!(
            "{}{}{}{}{}",
            block.index, block.timestamp, block.data, block.prev_hash, nonce
        );
        let mut hasher = Sha256::new();
        hasher.update(data);
        hasher.finalize().to_vec()
    }

    // Perform the proof of work, return the valid hash and nonce
    fn mine(&self, block: &Block) -> (Vec<u8>, u64) {
        let mut nonce = 0;
        let start = Instant::now();

        loop {
            let hash = ProofOfWork::calculate_hash(block, nonce);
            if hash <= self.target {
                println!("Block mined! Nonce: {}, Hash: {:x?}", nonce, hash);
                println!("Mining took: {:?}", start.elapsed());
                return (hash, nonce);
            }
            nonce += 1;
        }
    }
}

impl Block {
    // Creates a new block
    fn new(index: u64, timestamp: u128, data: String, prev_hash: String) -> Self {
        Block {
            index,
            timestamp,
            data,
            prev_hash,
            hash: String::new(),
            nonce: 0,
        }
    }

    // Starts mining and returns the mined block
    fn mine_block(&mut self, difficulty: u32) {
        let pow = ProofOfWork::new(difficulty);
        let (hash, nonce) = pow.mine(self);
        self.hash = format!("{:x?}", hash);
        self.nonce = nonce;
    }
}

fn main() {
    let mut block = Block::new(1, 1234567890, "Test Block".to_string(), "0".to_string());

    // Set the difficulty level (e.g., 16)
    let difficulty = 16;
    
    println!("Mining block...");
    block.mine_block(difficulty);

    // Display the block information
    println!("Block mined:");
    println!("Index: {}", block.index);
    println!("Timestamp: {}", block.timestamp);
    println!("Data: {}", block.data);
    println!("Prev Hash: {}", block.prev_hash);
    println!("Hash: {}", block.hash);
    println!("Nonce: {}", block.nonce);
}

Output

Mining block...
Block mined! Nonce: 0, Hash: [78, 7c, ee, 8c, 46, b3, bd, 48, aa, 2b, 85, 25, d6, 30, a9, 96, cc, b0, b9, 81, cf, c2, 6, ca, 71, 53, 33, d3, 32, 2c, 84, 52]
Mining took: 20.417µs
Block mined:
Index: 1
Timestamp: 1234567890
Data: Test Block
Prev Hash: 0
Hash: [78, 7c, ee, 8c, 46, b3, bd, 48, aa, 2b, 85, 25, d6, 30, a9, 96, cc, b0, b9, 81, cf, c2, 6, ca, 71, 53, 33, d3, 32, 2c, 84, 52]
Nonce: 0
PreviousProof of Work (PoW)NextProof of Stake (PoS)

Last updated 8 months ago