Skip to content
frederikgramkortegaardPublic

About

Bitcoin-style blockchain with custom smart contract language, and 256-bit VM with gas metering

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

August: Bitcoin-Style Blockchain with Smart Contracts

Go · Distributed Systems · Blockchain · Virtual Machines · Compiler Design

A blockchain platform built from scratch in Go, featuring proof-of-work consensus, a custom virtual machine, and a high-level smart contract programming language. Implements Bitcoin-inspired consensus with Ethereum-style smart contracts and gas-metered execution.

Project Overview

August is a blockchain platform implementing the technology stack from consensus protocols to high-level programming languages. The system combines Bitcoin's proof-of-work consensus model with Ethereum-style smart contracts, featuring a custom virtual machine (AVM) and the Marigold programming language.

The blockchain uses SHA-256 proof-of-work with dynamic difficulty adjustment and longest-chain fork resolution. Smart contracts execute on AVM, a stack-based bytecode runtime with 256-bit arithmetic and gas-metered execution. Marigold provides a high-level syntax that compiles to AVM bytecode through a complete compiler pipeline with lexer, parser, type checker, and code generator.

The P2P network uses libp2p for peer discovery via DHT and headers-first synchronization. The toolchain includes wallet, miner, compiler, and HTTP API for development and interaction.

Architecture

┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
│   Marigold      │->│       AVM       │->│   Blockchain    │
│   Language      │  │  Virtual Machine│  │     Core        │
└─────────────────┘  └─────────────────┘  └─────────────────┘
         |                       |                   |
         v                       v                   v
┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
│   Compiler      │  │  Gas Metering   │  │  P2P Network    │
│   Toolchain     │  │  & Storage      │  │   Protocol      │
└─────────────────┘  └─────────────────┘  └─────────────────┘

Features

Blockchain

  • Proof-of-work consensus with SHA-256 and dynamic difficulty adjustment
  • Account-based state model with Ed25519 signatures
  • Longest-chain fork resolution with automatic reorganization
  • Mempool with fee-based transaction ordering

AVM (August Virtual Machine)

  • Stack-based bytecode runtime with 256-bit arithmetic
  • Opcodes for arithmetic, memory, storage, control flow, strings, blockchain context
  • Gas metering to prevent infinite loops
  • Persistent storage with PSTORE/PLOAD for contract state
  • String table optimization for efficient string literal handling

Marigold Language

  • Static type system: int, float, string, bool (arrays and maps WIP)
  • String operations: slicing, concatenation, length, conversions
  • Control flow: if/else, while, break/continue, functions
  • Blockchain context via @ variables: @caller, @balance, @timestamp, etc.
  • Full compiler: lexer -> parser -> typechecker -> codegen

Networking

  • libp2p for P2P networking with DHT peer discovery
  • Protobuf message serialization
  • Headers-first chain synchronization

Quick Start

Network Setup

# Start seed node with HTTP API
go run cmd/seed/main.go --port 9372 --minerport 8080

# Generate cryptographic keys
go run cmd/keygen/main.go

# Start mining node
go run cmd/miner/main.go --privkey <private_key> --node localhost:8080

Basic Wallet Operations

# Check account balance
go run cmd/wallet/main.go --privkey <private_key> --node localhost:8080 balance

# Send AUG to another address
go run cmd/wallet/main.go --privkey <sender_key> --node localhost:8080 send \
  --amount 1000 --to <recipient_public_key>

# Check transaction status via HTTP API
curl http://localhost:8080/transaction/<transaction_hash>

# View current chain information
curl http://localhost:8080/chain-info

# Check account balance via HTTP API
curl http://localhost:8080/balance/<public_key_address>

Smart Contract Development

# Compile to AVM bytecode
go run cmd/marigold/main.go token.mg

# Deploy to blockchain
go run cmd/wallet/main.go --privkey <key> --node localhost:8080 deploy \
  --bytecode token.avmbc --amount 1000000 --gas-limit 100000

# Call contract with transaction data
go run cmd/wallet/main.go --privkey <key> --node localhost:8080 call \
  --contract <address> --amount 500 --data "627579" --gas-limit 50000

# Transfer tokens between addresses
go run cmd/wallet/main.go --privkey <key> --node localhost:8080 call \
  --contract <address> --amount 0 --data "7472616e73666572<recipient_address>200" --gas-limit 50000

Language Features

Marigold Smart Contract Language

Here's a complete fungible token contract demonstrating the language features:

define init() : int {
  // Contract deployer receives initial token supply
  persistent[@caller] = string(@callvalue)
  return 0
}

define call() : int {
  // Buy tokens with AUG
  if len(@tsxdata) == 3 && @tsxdata[:3] == "buy" {
    balanceStr: string = persistent[@caller]
    currentBalance: int = 0
    if len(balanceStr) > 0 {
      currentBalance = int(balanceStr)
    }
    newBalance: int = currentBalance + @callvalue
    persistent[@caller] = string(newBalance)
    return 0
  }

  // Transfer tokens between addresses
  if len(@tsxdata) >= 73 && @tsxdata[:8] == "transfer" {
      // Extract recipient address (64 hex chars)
      recipient: string = @tsxdata[8:72]
      if len(recipient) != 64 {
        return 1 // Invalid address length
      }

      // Extract transfer amount
      amountStr: string = @tsxdata[72:]
      if len(amountStr) == 0 {
        return 1 // No amount specified
      }
      amount: int = int(amountStr)
      if amount <= 0 {
        return 1 // Invalid amount
      }

      // Check sender balance
      senderBalanceStr: string = persistent[@caller]
      senderBalance: int = 0
      if len(senderBalanceStr) > 0 {
        senderBalance = int(senderBalanceStr)
      }
      if senderBalance < amount {
        return 1 // Insufficient balance
      }

      // Execute transfer
      newSenderBalance: int = senderBalance - amount
      persistent[@caller] = string(newSenderBalance)

      recipientBalanceStr: string = persistent[recipient]
      recipientBalance: int = 0
      if len(recipientBalanceStr) > 0 {
        recipientBalance = int(recipientBalanceStr)
      }
      newRecipientBalance: int = recipientBalance + amount
      persistent[recipient] = string(newRecipientBalance)

      return 0
    }
  }

  // Query balance (default behavior)
  return 0
}

Key Language Features:

  • String operations: Slicing @tsxdata[:8], concatenation, length checking
  • Type conversions: int(string) and string(int) for storage
  • Persistent storage: Key-value storage that persists between calls
  • Blockchain context: @caller, @callvalue, @tsxdata for transaction data
  • Control flow: If statements, comparisons, early returns

Blockchain Context Variables

The language provides blockchain context variables for contract interaction:

  • @caller - Message sender address
  • @address - Current contract address
  • @balance - Contract's AUG balance
  • @timestamp - Block timestamp
  • @height - Current block number
  • @gasprice - Gas price for transaction
  • @callvalue - AUG sent with call
  • @origin - Transaction originator
  • @difficulty - Current mining difficulty
  • @coinbase - Block miner address
  • @gaslimit - Block gas limit
  • @tsxdata - Transaction data

AVM Instruction Set

Core Operations

Stack:      PUSH <hex>, POP, DUP, SWAP
Arithmetic: ADD, SUB, MUL, DIV, AND, OR
Comparison: EQ, LT, GT, ISZERO (EQ supports string content comparison)
Memory:     MSTORE, MLOAD (temporary)
Storage:    PSTORE, PLOAD (persistent)
Control:    JUMP, JUMPC, STOP
Strings:    STRCONCAT, STRLEN, STRINDEX, STRSLICE, STRTOINT, INTTOSTR, EMITSTR

Blockchain Context Instructions

CALLER      - Push message sender address (2 gas)
ADDRESS     - Push contract address (2 gas)
BALANCE     - Push account balance (400 gas)
TIMESTAMP   - Push block timestamp (2 gas)
HEIGHT      - Push block number (2 gas)
GASPRICE    - Push gas price (2 gas)
CALLVALUE   - Push call value (2 gas)
TSXDATA     - Push transaction data as string (20 gas)

HTTP API

Blockchain Queries

# Account information with balance and nonce
curl http://localhost:8080/balance/993fe6a36d19ed527890a7698e940c3c1c629ca06443837871cb0ed19435229b

# Transaction lookup with block information
curl http://localhost:8080/transaction/d1cef77df9dff5b5abcd1234567890abcdef1234567890abcdef1234567890ab

# Block details by hash
curl http://localhost:8080/block/000046f22dc6219e1234567890abcdef1234567890abcdef1234567890abcdef

# Current chain head and height
curl http://localhost:8080/chain-info

# Full chain state including account balances and contract storage
curl http://localhost:8080/chain-state

# Pending transactions ordered by fee
curl http://localhost:8080/mempool?limit=10

# Example responses:
# Balance: {"address": "993fe6a3...", "exists": true, "balance": 1000000, "nonce": 5}
# Chain Info: {"height": 42, "head_hash": "000046f2...", "difficulty": 12345}

Testing Framework

Primary Integration Test

Run the complete end-to-end test to see the full blockchain stack in action:

go test ./tests/integration/ -v

This demonstrates:

  • Complete blockchain node startup with HTTP API
  • Marigold smart contract compilation to AVM bytecode
  • Contract deployment with persistent storage initialization
  • Contract execution with state transitions (42 -> 43 -> 44)
  • Detailed chain state logging at each step

Additional Test Suites

# Smart contract and blockchain tests
go test ./tests/contracts/...   # Contract deployment and execution tests
go test ./tests/node/...        # Node networking and consensus tests
go test ./tests/peerservice/... # P2P communication tests

# Specific contract functionality
go test ./tests/contracts/ -run TestFungibleTokenContract    # Token contract test
go test ./tests/contracts/ -run TestContractDeployment       # Contract deployment
go test ./tests/contracts/ -run TestStringOperations         # String manipulation

Multi-Node Network Simulation

# Terminal 1: Primary node
go run cmd/seed/main.go --port 9372 --minerport 8080

# Terminal 2: Secondary node
go run cmd/seed/main.go --port 9373 --minerport 8081 --peer localhost:9372

# Terminal 3-4: Distributed mining
go run cmd/miner/main.go --privkey <key1> --node localhost:8080
go run cmd/miner/main.go --privkey <key2> --node localhost:8081

Project Structure

august/
├── avm/                    # Virtual machine implementation
│   ├── bytecode.go         # Instruction definitions
│   ├── runtime.go          # Stack-based execution engine
│   ├── gas.go              # Gas metering and pricing
│   └── parser.go           # Bytecode parsing and validation
├── blockchain/             # Core blockchain logic
│   ├── chain.go            # Block and transaction structures
│   ├── mining.go           # Proof-of-work implementation
│   ├── validation.go       # Consensus validation rules
│   └── crypto.go           # Ed25519 signatures and hashing
├── marigold/               # High-level programming language
│   ├── lexer.go            # Tokenization and lexical analysis
│   ├── parser.go           # AST construction and syntax parsing
│   ├── typechecker.go      # Static type analysis
│   ├── chainidents.go      # Blockchain context integration
│   ├── codegen.go          # AVM bytecode generation
│   └── tests/              # Language test suite
├── libnet/                 # libp2p networking layer
│   ├── peerservice.go      # P2P service management
│   ├── rpc/                # RPC protocol handlers
│   └── protobuf/           # Protocol buffer definitions
├── node/                   # Full node implementation
│   ├── node.go             # Node lifecycle and coordination
│   ├── api.go              # HTTP API server
│   ├── header_processing.go # Block header validation
│   └── mempool.go          # Transaction pool management
├── types/                  # Shared type definitions
├── execution/              # Transaction execution engine
├── config/                 # Network configuration
├── utils/                  # Utility functions
├── cmd/                    # Command-line tools
│   ├── marigold/           # Language compiler
│   ├── wallet/             # Transaction and contract tools
│   ├── miner/              # Mining implementation
│   ├── seed/               # Full node with HTTP API
│   └── avm/                # Bytecode execution environment
└── tests/                  # Integration and unit tests
    ├── integration/        # End-to-end tests
    ├── contracts/          # Smart contract tests
    └── node/               # Node and consensus tests

Performance Characteristics

  • Block Time: Configurable difficulty targeting (default 10 minutes)
  • TPS: Limited by block size and gas limits (similar to Ethereum)
  • Storage: In-memory state with persistent contract storage
  • Memory: Bounded VM execution with configurable limits
  • Network: libp2p-based with DHT peer discovery and connection management

Technical Implementation Notes

  • Atomic Updates: Copy-validate-replace pattern for thread-safe chain operations
  • Gas Metering: Prevents infinite loops and resource exhaustion in smart contracts
  • Type Safety: Static analysis prevents runtime type errors in Marigold contracts
  • Fork Handling: Automatic chain reorganization with total work comparison
  • State Management: Efficient key-value storage with account and contract separation

August demonstrates a blockchain implementation from consensus protocols to high-level programming languages, showcasing distributed systems design, virtual machine architecture, and compiler construction in a unified platform.

About

Bitcoin-style blockchain with custom smart contract language, and 256-bit VM with gas metering

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages