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
  • Project Structure
  • The codes
  • The Output
  1. Introduction to Blockchain

Implementation of Blockchain

A quick 'n dirty implementation of a basic blockchain data structure to learn about Blockchain and understand some of the fundamentals using Golang

Project Structure

mkdir blockchain
cd Blockchain 
code .

Or you can clone the repository and start use it directly

git clone https://github.com/EncrypteDL/Simple-Block.git
cd Simple-Block
code . #if you are using vscode
Simple-Block
├── internal
│   └── block.go
│   └── chain.go
│   └── util.go
├── go mod
└── main.go

The codes

block.go

package internal

import (
	"bytes"
	"crypto/sha256"
	"time"
)

// We need to define the Block| A Blocck represent a single block in a chain of blocks(Blockchain)
type Block struct {
	Index       int
	TimesTamp   time.Time
	Data        []byte
	PreviosHash []byte
	Hash        []byte
}

// we need to define a newBlock and returns a new empty `Block`
func newBlock() Block {
	n := Block{}
	n.TimesTamp = time.Now()
	n.Hash = hashBlock(n)

	return n
}

func hashBlock(b Block) []byte {
	h := sha256.New()

	h.Write(Int64Bytes(int64(b.Index)))
	h.Write(Int64Bytes(b.TimesTamp.Unix()))
	h.Write(b.Data)
	h.Write(b.PreviosHash)

	return h.Sum(nil)
}

//isValidate validites the current block ('b') with previos block in a chain
func (b Block) Validate(o Block) bool {
	if (bytes.Compare(b.Hash, hashBlock(b)) != 0) ||
		(b.Index != (o.Index + 1)) ||
		(bytes.Compare(b.PreviosHash, o.Hash) != 0) {
		return false
	}
	return true
}

// Generate creates a new block from the current block which is assumed to be the
// last block in the chain.

func (b Block) Generate(data []byte) Block{
	n := Block{
		Index: b.Index+1,
		TimesTamp: time.Now(),
		Data: make([]byte, data[0]),
		PreviosHash: b.Hash,
	}

	return n
}

chain.go

package internal

import "errors"

var (
	// ErrInvalidBlock is an error returned if an invalid block is added to
	// a block chain where the new block's has and index are invalid
	ErrInvalidBlock = errors.New("error: invalid block")
)

// Chain is a slice of blocks to form the "block chain". Each block is
// connected to the previous block cryptographically by each block's hash
// being in corporated into the next block in the chain. The larger the chain
// grows the higher the integrity of the chain and the more difficult it is to
// temper with or modify previous blocks in the chain.
type Chain []Block

// NewChain creates a new "block chain" `Chain` with an initial block already
// created called the "genesis block"
func NewChain() *Chain {
	return &Chain{newBlock()}
}

// Add adds a new block (`block`) to the chain verifying its validty
// If the block is invalid an error is returned otherwise the block is appended
// to the block chain.
func (c *Chain) Add(block Block) error {
	prevBlock := (*c)[len(*c)-1]
	if !block.Validate(prevBlock) {
		return ErrInvalidBlock
	}
	*c = append(*c, block)
	return nil
}

// Write creates a new block with the given data (`data`) and appends it to the
// block chain. This implements the `io.Writer` interface so you can treat the
// block chain as a valid Writer.
func (c *Chain) Write(data []byte) (int, error) {
	prevBlock := (*c)[len(*c)-1]
	block := prevBlock.Generate(data)
	if err := c.Add(block); err != nil {
		return 0, ErrInvalidBlock
	}
	return len(data), nil
}

// Verify verifies the cryptographic hashes of every block inthe chain
// ensuring all blocks are valid and their integrity in tact
func (c *Chain) Verify() bool {
	prevBlock := (*c)[0]
	for _, block := range (*c)[1:] {
		if !block.Validate(prevBlock) {
			return false
		}
		prevBlock = block
	}
	return true
}

util.go

package internal

import "encoding/binary"

// Int64Bytes converts the integer `i` an `int64` into a byte array
// using Big Endian encoding
func Int64Bytes(i int64) []byte{
	b := make([]byte, 8)
	binary.BigEndian.PutUint64(b, uint64(i))
	return b
}

main.go

package main

import (
	"SimpleBlock/internal"
	"encoding/json"
	"fmt"
)

func main() {
	c := internal.NewChain()
	c.Write([]byte("foo"))
	c.Write([]byte("bar"))
	if !c.Verify() {
		panic("Blockchain verification failure")
	}

	data, _ := json.Marshal(c)
	fmt.Print(string(data))
}

The Output

{
  "Index": 0,
  "Timestamp": "2024-09-07T17:46:28.008676+01:00",
  "Data": null,
  "PreviousHash": null,
  "Hash": "r5jygeLj/oGREtEsIGFopz/r4gkd8VWVoiB/6nvys5g="
}
PreviousHow Blockchain Works ?NextSummary

Last updated 8 months ago