Cardano Ledger

repository·master·Indexed 43 days ago

https://github.com/intersectmbo/cardano-ledger

Formal specifications, executable models, and implementations of the Cardano Ledger across multiple eras, including Byron, Shelley, Allegra, Mary, Alonzo, Babbage, and Conway. Includes validation rules for blocks and transactions, cryptographic primitives via cardano-crypto-wrapper, and tools for managing LedgerState and UTXO sets.

Tokens
30.1K
Snippets
66
Records
133
Agent score
55%

What's inside Cardano Ledger

  1. Overview of cardano-ledger validation rules

    master

    The cardano-ledger package provides the implementation of the validation rules for the Cardano Ledger. These rules define the state transition systems used to:

    • Validate new blocks and transactions.
    • Define how the ledger is extended.

    This implementation is based on the formal specification defined in the main cardano-ledger repository.

  2. Overview of cardano-crypto-wrapper primitives

    master

    The cardano-crypto-wrapper provides the core cryptographic primitives used within the Cardano ledger. It abstracts several critical security functions:

    • Hashing: Implements cryptographic hashing using the cryptonite library.
    • Randomness: Provides secure generation of cryptographically random numbers and ByteStrings.
    • Key Derivation: Supports hierarchical derivation functionality for Hierarchical Deterministic (HD) key creation, typically used for wallet management.
    • Signing: Handles cryptographic signing and signature verification.
    • Serialization: Provides To/FromCBOR instances (compatible with the cardano-ledger-binary package) for all cryptographic data types to ensure consistent binary encoding/decoding.
  3. What is a token bundle and how is it used?

    master

    A token bundle is a heterogeneous collection of tokens and is the standard, and only, way to represent and store assets on the Cardano blockchain.

    Key characteristics:

    • Composition: It can bundle any combination of tokens and ada amounts together.
    • Fungibility: It organizes tokens so that fungibility is explicitly defined by the Asset ID (Policy ID + Asset Name).
    • Storage Locations: Token bundles are found in:
      1. The mint field of a transaction (indicating tokens being minted).
      2. An output of a transaction or an output in the UTXO set (e.g., { MyAddress, TB_Example }).

    Note: While token bundles handle multi-asset amounts, certain transaction fields like the fee field must still explicitly specify ada amounts.

    {
    	NFLPlayerCardsPolicyID {
    		(SomeNFLPlayerCard, 1),
    		(SomeOtherNFLPlayerCard, 1),
    		(YetAnotherNFLPlayerCard, 1)}
    
    	RushConcertPolicyID {
    		(Tickets, 500),
    		(VIPTickets, 50)}
    }
  4. Compare Native Tokens to ERC20 Tokens

    master

    Cardano's native tokens differ significantly from Ethereum's ERC20 standard because their tracking and accounting are built directly into the Cardano ledger.

    Key Advantages of Native Tokens:

    • No Smart Contract Requirement for Transfers: Unlike ERC20, which requires a smart contract to move value, native tokens are transferred by the ledger itself. This allows them to be transferred alongside other token types without special support.
    • Lower Complexity: Native tokens do not require special transfer fees, additional event-handling logic to track transactions, or the customization of transfer logic.
    • Unified Asset Types: Cardano's native token system supports both fungible tokens and unique (non-fungible) assets within the same framework, whereas Ethereum typically requires a separate standard (ERC721) for NFTs.
    • Control: Native tokens are controlled by a minting policy script written in any Cardano-supported scripting language.
    | Feature | ERC20 | Native tokens |
    | :--- | :--- | :--- |
    | Blockchain | Ethereum | Cardano |
    | Relationship to the blockchain | A contract standard, users copy-paste the standard code and modify it. | Not a standard. Most functionality is built into the ledger itself. |
    | Controlled by | A Solidity smart contract | A minting policy script in any scripting language supported by Cardano |
    | Requires a smart contract to mint/burn? | Y | Y |
    | Minting logic can be customized? | Y | Y |
    | Requires a smart contract to transfer? | Y | N |
    | Can be used by other smart contracts without special support? | N | Y |
    | Can be transferred alongside other tokens? | N | Y |
    | Transfer logic provided by | Copy-pasting from the ERC20 template | The Cardano ledger itself |
    | Transfer logic can be customized | Y | N |
    | Requires special fees to transfer | Y | N |
    | Requires additional event-handling logic to track transfers | Y | N |
    | Supports non-fungible tokens | N | Y |
    | Readable metadata | Provided by the operating smart contract | Provided by the off-chain metadata server |
  5. Verify Chain Quality Property

    master

    The Chain Quality property ensures the integrity and quality of the chain structure.

    Theorem 7 (Chain quality): In a $\Delta$-semisynchronous environment, the probability that an $\alpha$-dominated adversary $A$ causes the protocol $\pi_{SPoS}$ to violate the chain quality property (with parameters $k$ and $\mu = 1/k$) over $R$ slots is no more than $\exp(\ln R - \Omega(k))$.

  6. Verify Common Prefix Property

    master

    The Common Prefix property ensures that there is a low probability of different parts of the network seeing different versions of the chain history.

    Theorem 5 (Common prefix): In a $\Delta$-semisynchronous environment, the probability that an $\alpha$-dominated adversary $A$ causes the protocol $\pi_{SPoS}$ to violate the common prefix property with parameter $k$ over $R$ slots is no more than $\exp(\ln R + \Delta - \Omega(k))$.

  7. Compare Native Tokens vs ERC20 Tokens

    master

    When designing token systems on Cardano, it is important to understand how native tokens differ from ERC20 smart contract tokens in terms of security and implementation.

    Native tokens are handled directly by the Cardano ledger, which eliminates several common vulnerabilities found in ERC20 implementations:

    • Reduced Human Error: Unlike ERC20, which requires manual modification of contract standards (leading to potential bugs), native token functionality is provided by the ledger itself.
    • Elimination of Overflow/Underflow: Cardano's scripting languages do not use fixed-size integers, and the ledger tracks token movement rather than relying on user-written code for arithmetic.
    • Minimized Unprotected Functions: In the native model, user code is only invoked in specific cases to validate minting, reducing the attack surface compared to ERC20's exposed contract functions.

    Note on Denial of Service: While native tokens mitigate many smart contract-specific risks, they do not eliminate the possibility of system-wide denial of service attacks via gas price manipulation.

  8. Understand the tiered fee calculation for Reference Scripts

    master

    In the Conway era, using Reference Scripts in a transaction incurs an additional fee to prevent DDoS attacks involving large, expensive-to-deserialize scripts. Instead of a simple linear cost, the protocol uses a tiered pricing mechanism.

    To calculate the total size used for the fee:

    1. Combine all regular inputs and reference inputs from the transaction.
    2. Lookup the corresponding outputs from the UTxO map.
    3. Sum the sizes of every reference script found in those outputs.

    Key Calculation Rules:

    • Deduplication: If an input is both a regular input and a reference input, it is only counted once.
    • Duplicates: Duplicate reference scripts in different outputs are not removed; each instance contributes its size to the total.
    • Scope: All Plutus scripts and Native scripts used as reference scripts contribute to the calculation, regardless of whether they are actually executed within the transaction.
    • Tiered Pricing: The total size is split into 25KiB (25,600 bytes) chunks. Each subsequent chunk is more expensive than the previous one by a multiplier of 1.2.
    tierRefScriptFee :: Integer -> Integer
    tierRefScriptFee = go 0 minFeeRefScriptCostPerByte
      where
        go acc curTierPrice n
          | n < sizeIncrement =
              floor (acc + (n % 1) * curTierPrice)
          | otherwise =
              let acc' = acc + curTierPrice * (sizeIncrement % 1)
               in go acc' (multiplier * curTierPrice) (n - sizeIncrement)
        sizeIncrement = 25600
        multiplier = 1.2
        minFeeRefScriptCostPerByte = 15
  9. Understand the token bundle size constraint

    master

    To prevent transaction outputs from becoming so large that they cannot be spent without exceeding the maximum transaction size, the ledger enforces a constraint on the size of the token bundle in transaction outputs.

    Unlike the min-ada-value calculation which uses an estimated size, this constraint uses the actual size of the serialized representation of the token bundle.

    The constraint is governed by the protocol parameter maxValSize.

    Current Value:

    • maxValSize = 4000 bytes (equivalent to 500 words).
  10. How versioned serialization schemes work in the Cardano Ledger

    master

    To prevent network splitting during hard forks, the Cardano ledger uses versioned serialization schemes instead of static ToCBOR and FromCBOR typeclasses.

    Previously, fixing a deserialization bug required maintaining two separate serializations for the same type simultaneously, which was difficult to manage with the standard FromCBOR typeclass. The new approach introduces a typeclass that depends on both the type and the protocol version (or the ledger era).

    When implementing or using serializers, you must now provide the appropriate protocol version or ledger era to ensure the correct serialization logic is applied for the current network state.

  11. Define and use Minting Policies

    master

    A minting policy is a set of rules that regulates the creation and destruction of assets scoped under it. The ledger checks adherence to these rules whenever a transaction attempts to use the mint field.

    Key types of policies include:

    • Single-issuer policy: Only specific entities holding a designated set of keys can mint tokens. This can be implemented using multisig scripts.
    • One-time minting policy: All tokens under the policy are minted in a single specific transaction, after which no more can ever be created. This requires Plutus smart contracts and cannot be expressed via multisig.
    • Plutus-based policies: Using the Plutus smart contract language allows for complex logic beyond simple multisig requirements (e.g., conditional minting).
  12. How deposit tracking works in the Cardano Ledger

    master

    The Cardano Ledger has transitioned from tracking deposit amounts via global protocol parameters to tracking individual deposits.

    The Old Model (Parameter-based)

    Previously, deposit amounts for stake credential registrations and stake pool registrations were determined by protocol parameters. If these parameters changed:

    • Increasing deposit amounts: The difference was taken from the reserves and added to the deposit pot. Users de-registering received a larger amount than they originally paid.
    • Decreasing deposit amounts: The difference was moved from the deposit pot to the reserves. Users de-registering received a smaller amount than they originally paid.

    The New Model (Individual Tracking)

    To prevent economic exploits (like registering credentials right before a deposit increase) and to avoid 'split-brain' states during hard forks, the ledger now tracks the specific amount paid by each individual. When a user de-registers a resource, the ledger pays back exactly what they originally deposited.

    Implementation Details

    • The ledger maintains a history of deposits to ensure exact repayment.
    • This increases the size of the stake credential map, but is designed to be efficient (estimated at approximately one word/eight bytes per stake credential).