Madara Documentation

repository·main·Indexed 19 days ago

https://github.com/abdelstark/madara

A modular stack built on Substrate for creating sovereign application chains utilizing Cairo and Starknet technology. Madara provides primitives including CairoVM, Starknet RPC, DA interfaces, and Proving. The ecosystem includes the cairo-contracts package for E2E testing, a Starknet block import handler to mitigate DoS attacks, and the MadaraRunner for node initialization and testing.

Tokens
63K
Snippets
239
Records
299
Agent score
68%

What's inside Madara

  1. Overview of the Madara App Chain Stack

    main

    Madara is a modular stack designed for building application chains using Cairo and Starknet technology. Built on the Substrate framework, it provides a modular foundation that allows developers to own more of the stack and gain greater control over their chains.

    Key components provided by Madara include:

    • pallet_starknet: Integrates the CairoVM into Substrate, enabling the deployment and execution of Cairo contracts.
    • Starknet RPC: Provides Starknet RPC compatibility, allowing the use of standard tools like starknet-js and various wallets.
    • DA Interface: A generalized interface for integrating Data Availability (DA) layers such as Avail, Celestia, or Ethereum.
    • Proving: Implements the Starknet OS runtime logic in Cairo to enable proving on Layer 1 (L1).
  2. What is Madara and why use App Chains?

    main

    Madara is a high-performance Starknet sequencer designed to enable the creation of customized, high-throughput App Chains (L3s). By building an App Chain instead of deploying directly to Starknet (L2), developers can achieve:

    • Increased Throughput & Lower Costs: Dedicated resources prevent competition with other applications, potentially reducing costs by up to a million times from L1 to L3.
    • Customization: Developers can fine-tune infrastructure, such as choosing specific hash functions, consensus algorithms, or even excluding certain Cairo VM features.
    • Innovation: Enables experimental features like on-chain KYC without compromising privacy or using risky functions on a general-purpose chain.

    Madara leverages the Substrate framework to provide this modularity while integrating the Cairo VM to ensure all executions are provable and secure, inheriting the security of the underlying Starknet L2.

  3. Understand the Madara project structure

    main

    The Madara project is organized into several key directories:

    • benchmarking: Code for benchmarking custom FRAME pallets.
    • crates: The core logic of the project, subdivided into:
      • node: Blockchain node services (chain specification, RPC, etc.).
      • pallets: Custom FRAME pallets (e.g., pallet-starknet).
      • runtime: The assembly of Madara's custom logic and configured pallets.
      • primitives: Primitives used by the pallets.
    • docs: Project documentation.
    • examples: Example implementations.
  4. What is Madara and how does it enable Starknet Appchains?

    main

    Madara is a high-performance sequencer built using the Substrate framework that allows developers to launch custom Starknet Appchains (L3s). It integrates the Cairo VM to execute Cairo programs and Starknet smart contracts while leveraging Substrate's modularity to provide a customizable blockchain stack.

    Key benefits of using Madara for Appchains include:

    • Throughput & Cost: Dedicated blockchain resources prevent competition with other dApps, potentially achieving massive cost reductions (up to 1,000,000x from L1 to L3) through layered scaling.
    • Customization: Developers can fine-tune consensus algorithms, hash functions, signature schemes, and storage layouts.
    • Innovation: Enables features like on-chain privacy (e.g., encrypted mempools for KYC) and custom code hints that might be too risky for general-purpose L2s.
  5. How Madara integrates Substrate and Cairo VM

    main

    Madara's core architecture combines the modularity of Substrate (a Rust-based framework) with the provability of the Cairo VM.

    • Substrate provides the modular framework, allowing developers to integrate custom consensus protocols, hash functions, signature schemes, and storage layouts without imposed assumptions.
    • Cairo VM is used to execute Cairo programs and Starknet smart contracts. It generates validity proofs for program execution.
    • Security Integration: The App Chain uses state tracking and smart contracts on Starknet L2 to verify these proofs, ensuring the App Chain inherits the security of the Starknet ecosystem.
  6. Understand Sharingan node typologies

    main

    Sharingan is an ephemeral Starknet testnet where nodes run Madara instances. There are two distinct roles for nodes in the network:

    1. Sequencer: A Madara instance that participates in the consensus mechanism to produce, validate, and add blocks to the chain. Currently, sequencers are managed by Starkware.
    2. Fullnode: A Madara instance used for data persistence. Fullnodes do not participate in consensus but store the chain data. Anyone can join the network as a fullnode.

    Nodes expose two primary ports:

    • 30333: Peer-to-peer (P2P) communication.
    • 9944: JSON-RPC endpoint for external communication and Starknet interaction.
  7. Understand the Genesis JSON structure

    main

    The genesis of a Madara chain is defined in a JSON file. This file specifies the initial state of the chain, including deployed code, contract instances, and initial storage values. The JSON structure consists of three primary components:

    1. contract_classes: A list of tuples containing the class hash and the class definition. The class can be provided in two ways:
      • Path Reference: An object with a path (relative to the repository root) and a version (0 or 1) indicating the Cairo version. Example: { "path": "cairo-contracts/NoValidateAccount.json", "version": 0 }.
      • Serialized Class: The complete serialized class data.
    2. contracts: A list of tuples mapping a contract address to its associated class hash.
    3. storage: A list of tuples mapping a storage key to a storage value. The storage key is a tuple containing the target contract address and the Starknet storage key.
    {
      "contract_classes": [
        ["class_hash", { "path": "cairo-contracts/NoValidateAccount.json", "version": 0 }]
      ],
      "contracts": [
        ["contract_address", "class_hash"]
      ],
      "storage": [
        [["contract_address", "starknet_storage_key"], "storage_value"]
      ]
    }
  8. Apply the SRP (Single Responsibility Principle)

    main

    A module, class, or function should have one, and only one, reason to change. If a component handles both data management and data presentation/output, it violates SRP.

    Refactoring Pattern: Separate the data structure (responsible for state and formatting) from the printer/output logic (responsible for rendering to the user).

    pub struct Report {
        title: String,
        data: Vec<String>,
    }
    
    impl Report {
        pub fn new(title: String, data: Vec<String>) -> Report {
            Report { title, data }
        }
    
        pub fn format(&mut self) {
            self.data = self.data.iter().map(|line| format!("{}\n", line)).collect();
        }
    }
    
    pub struct ReportPrinter {
        report: Report,
    }
    
    impl ReportPrinter {
        pub fn new(report: Report) -> ReportPrinter {
            ReportPrinter { report }
        }
    
        pub fn print(&self) {
            println!("Title: {}", self.report.title);
            for line in &self.report.data {
                println!("{}", line);
            }
        }
    }
  9. Use the Starknet block import handler to prevent DoS attacks

    main

    The mc-starknet-block-import crate provides a specialized Starknet handler for the block import pipeline. It acts as a wrapper that executes at the beginning of the import queue to perform security checks on declare transactions.

    Purpose

    It mitigates a Denial of Service (DoS) attack vector where a malicious user submits a Cairo contract that cannot be proven. Without this handler, a node might accept a transaction without verifying the corresponding Sierra classes, leading to a failure in the sequencer's ability to prove execution or charge for work.

    How it works

    1. Detection: Upon receiving a new block, the handler scans for declare transactions.
    2. Verification: For each declare transaction, it searches for the corresponding Sierra classes in the local database.
    3. Validation: It attempts to compile the found classes to ensure they match the contract class provided in the transaction.
    4. Enforcement: If any transaction contains mismatching class hashes, the block import process fails immediately.
  10. Limitations and considerations for Starknet block import

    main

    When using the Starknet block import handler, be aware of the following operational constraints:

    Multi-node Setup

    Currently, the Sierra classes database is populated via RPC requests. This means the verification mechanism is optimized for single-node setups. In a multi-node environment, nodes cannot automatically find missing Sierra classes from peers. To support multi-node settings, you must implement a mechanism to query missing Sierra classes via P2P (referencing the Starknet P2P specs).

    Compiler Versioning

    Because the handler relies on compiling Sierra classes to verify hashes, the Cairo compiler version used by Madara is critical:

    • Lagging Versions: If Madara's compiler is significantly older than the one used to generate recent Sierra classes, compilation may fail.
    • Backward Compatibility: Old Sierra classes may fail to compile if backward compatibility is broken in newer compiler versions.
  11. Understand the Madara App Chain Stack

    main

    Madara provides a modular stack for building App Chains, allowing developers to customize different layers of the blockchain architecture:

    1. Execution Layer: Defines block execution and state diff generation. Madara allows switching between execution toolkits: StarkWare's blockifier or LambdaClass's starknet_in_rust. Both use the Cairo VM to generate validity proofs.
    2. Settlement Layer: As a Validity Rollup, the App Chain state is reconstructed via the settlement layer. Frequent settlement on Starknet L2 provides faster hard finality, while a decentralized sequencer provides strong soft finality.
    3. Ordering Layer: Responsible for transaction sequencing. Supports various schemes ranging from simple First-Come-First-Served (FCFS) or Priority Gas Auctions (PGA) to complex consensus like Narwhall and Bullshark. Supports encrypted mempools to mitigate MEV.
    4. Data Availability (DA): Ensures the full state tree is accessible so users can prove ownership even if Madara fails. Madara supports multiple DA solutions.
    5. Governance Layer: Supports various models, including on-chain governance via Snapshot X (relying on storage proofs) or native Substrate governance pallets.