🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

IPFS and Decentralized Storage

Blockchain InfrastructuređŸŸĸ Free Lesson

IPFS and Decentralized Storage

InterPlanetary File System (IPFS) provides decentralized storage using content addressing, enabling permanent and censorship-resistant data storage.

IPFS Architecture

IPFS ArchitectureClientipfs addipfs catipfs getIPFS NodeDHTBitswapMerkle DAGNetworkPeer 1Peer 2Peer 3

Content Addressing

IPFS uses content-based addressing instead of location-based addressing.

CID (Content Identifier)

CID Structure

javascript
// CID v1 Structure
{
    version: 1,
    codec: 'dag-pb',  // or 'dag-cbor', 'raw', etc.
    multihash: {
        function: 'sha2-256',
        digest: '0x1220...',  // 32 bytes
        length: 32
    }
}

// Example CID
"bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi"

Hashing Algorithms

AlgorithmOutput SizeUse CaseSecurity
SHA-25632 bytesGeneral purposeHigh
SHA-51264 bytesHigh securityVery High
BLAKE2b32 bytesFast hashingHigh
BLAKE332 bytesFastestHigh

IPFS Operations

Adding Files

# Add a file
ipfs add file.txt

# Add a directory
ipfs add -r ./my-directory

# Add with pinning
ipfs add --pin file.txt

# Add with wrap directory
ipfs add --wrap-directory file.txt

JavaScript Client

javascript
import { create } from 'ipfs-http-client';

const client = create({ url: 'http://localhost:5001' });

// Add a file
async function addFile(file) {
    const result = await client.add(file);
    console.log('Added:', result.path);
    console.log('CID:', result.cid.toString());
    return result;
}

// Retrieve a file
async function getFile(cid) {
    const chunks = [];
    for await (const chunk of client.cat(cid)) {
        chunks.push(chunk);
    }
    return Buffer.concat(chunks);
}

// Pin a file
async function pinFile(cid) {
    await client.pin.add(cid);
    console.log('Pinned:', cid);
}

Pinning Services

Pinning Strategies

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract IPFSPinning {
    struct PinRequest {
        bytes32 cid;
        address requester;
        uint256 timestamp;
        bool pinned;
        uint256 replicas;
    }
    
    mapping(bytes32 => PinRequest) public pinRequests;
    mapping(bytes32 => uint256) public pinCount;
    
    uint256 public constant MIN_REPLICAS = 3;
    uint256 public constant PIN_FEE = 0.01 ether;
    
    function requestPin(
        bytes32 cid,
        uint256 replicas
    ) external payable {
        require(msg.value >= PIN_FEE * replicas, "Insufficient fee");
        require(replicas >= MIN_REPLICAS, "Insufficient replicas");
        
        pinRequests[cid] = PinRequest({
            cid: cid,
            requester: msg.sender,
            timestamp: block.timestamp,
            pinned: false,
            replicas: replicas
        });
        
        emit PinRequested(cid, msg.sender, replicas);
    }
    
    function confirmPin(bytes32 cid) external onlyPinProvider {
        require(pinRequests[cid].requester != address(0), "No pin request");
        require(!pinRequests[cid].pinned, "Already pinned");
        
        pinRequests[cid].pinned = true;
        pinCount[cid]++;
        
        if (pinCount[cid] >= pinRequests[cid].replicas) {
            emit PinComplete(cid);
        }
    }
}

Pinning Service Comparison

ServiceCostReplicasGuaranteesAPI
Pinata$0.10/GB3+SLAREST
Infura$0.10/GB3+SLAREST
FilecoinVariable10+EconomicGraphQL
CrustVariable6+EconomicREST
Self-hostedFreeVariableNoneIPFS

Filecoin Integration

Filecoin Deal Flow

Filecoin Deal FlowClientProposes DealMinerAccepts DealStorageProves StorageDeal StatesProposed → Staged → Sealing → Active → ExpiredStorage Proof: PoRep (Proof of Replication) + PoSt (Proof of Spacetime)

Filecoin Smart Contract Integration

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@zondax/filecoin-solidity/contracts/v0.8/MarketAPI.sol";

contract FilecoinStorage {
    struct DealProposal {
        bytes32 cid;
        uint256 size;
        address miner;
        uint256 price;
        uint256 duration;
    }
    
    mapping(bytes32 => DealProposal) public deals;
    
    function proposeDeal(
        bytes32 cid,
        uint256 size,
        address miner,
        uint256 price,
        uint256 duration
    ) external payable {
        require(msg.value >= price, "Insufficient payment");
        
        // Create deal proposal on Filecoin
        MarketAPI.FilMarketClientDealProposal memory proposal = _createProposal(
            cid, size, miner, price, duration
        );
        
        deals[cid] = DealProposal({
            cid: cid,
            size: size,
            miner: miner,
            price: price,
            duration: duration
        });
        
        emit DealProposed(cid, miner, price);
    }
    
    function verifyDeal(bytes32 cid) external view returns (bool) {
        DealProposal memory deal = deals[cid];
        require(deal.miner != address(0), "No deal");
        
        // Verify storage proof
        return _verifyStorageProof(cid, deal.miner);
    }
}

Arweave Integration

Arweave Permanent Storage

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract ArweaveStorage {
    struct Transaction {
        bytes32 id;
        uint256 timestamp;
        uint256 size;
        address uploader;
    }
    
    mapping(bytes32 => Transaction) public transactions;
    
    function uploadData(
        bytes calldata data,
        uint256 arweaveFee
    ) external payable {
        require(msg.value >= arweaveFee, "Insufficient fee");
        
        bytes32 txId = _submitToArweave(data, arweaveFee);
        
        transactions[txId] = Transaction({
            id: txId,
            timestamp: block.timestamp,
            size: data.length,
            uploader: msg.sender
        });
        
        emit DataUploaded(txId, msg.sender, data.length);
    }
    
    function verifyData(bytes32 txId) external view returns (bool) {
        Transaction memory tx = transactions[txId];
        require(tx.uploader != address(0), "No transaction");
        
        return _verifyOnArweave(txId, tx.size);
    }
}

Arweave vs IPFS Comparison

FeatureArweaveIPFS
Storage ModelPermanentPinning required
CostOne-time feeRecurring
ConsensusProof of AccessNone
Data AvailabilityPermanentDepends on pinning
Use CaseArchivesDynamic content

Decentralized Frontends

IPFS + ENS Deployment

javascript
// Deploy frontend to IPFS and link to ENS
import { create } from 'ipfs-http-client';
import { ethers } from 'ethers';

async function deployFrontend() {
    const client = create({ url: 'http://localhost:5001' });
    
    // Build frontend files
    const files = [
        { path: 'index.html', content: fs.readFileSync('./dist/index.html') },
        { path: 'app.js', content: fs.readFileSync('./dist/app.js') },
        { path: 'style.css', content: fs.readFileSync('./dist/style.css') }
    ];
    
    // Add to IPFS
    let lastCid;
    for (const file of files) {
        const result = await client.add(file.content, { path: file.path });
        lastCid = result.cid;
        console.log(`Added ${file.path}: ${result.cid.toString()}`);
    }
    
    // Update ENS domain
    const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
    const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
    
    const ensContract = new ethers.Contract(
        '0x283Af0B28c62C092C9727F1EeD90A32357C1f35', // ENS Resolver
        ['function setContenthash(bytes32 node, bytes calldata hash) external'],
        signer
    );
    
    // Set contenthash for ENS domain
    const node = ethers.namehash('myapp.eth');
    const contentHash = ethers.solidityPacked(['bytes'], [lastCid.toBytes()]);
    
    const tx = await ensContract.setContenthash(node, contentHash);
    await tx.wait();
    
    console.log('Frontend deployed to IPFS and linked to ENS');
}

IPFS Gateway Configuration

javascript
// Multiple gateway providers
const gateways = [
    'https://ipfs.io/ipfs/',
    'https://gateway.pinata.cloud/ipfs/',
    'https://cloudflare-ipfs.com/ipfs/',
    'https://dweb.link/ipfs/'
];

async function loadFromGateway(cid) {
    for (const gateway of gateways) {
        try {
            const response = await fetch(`${gateway}${cid}`);
            if (response.ok) {
                return await response.text();
            }
        } catch (error) {
            console.log(`Gateway ${gateway} failed:`, error.message);
        }
    }
    throw new Error('All gateways failed');
}

Trade-offs

FeatureIPFSArweaveFilecoinSia
Storage ModelPinningPermanentContractContract
CostLowMediumVariableVariable
DurabilityMediumHighHighHigh
SpeedFastMediumVariableMedium
ComplexityLowMediumHighMedium

Real-World Example: NFT Metadata Storage

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract NFTWithIPFS is ERC721, Ownable {
    struct TokenMetadata {
        string name;
        string description;
        string imageUri;  // IPFS CID
        string animationUri;  // IPFS CID
        string attributes;  // JSON string
    }
    
    mapping(uint256 => TokenMetadata) public tokenMetadata;
    
    constructor() ERC721("IPFS NFT", "INFT") {}
    
    function mint(
        address to,
        uint256 tokenId,
        string calldata name,
        string calldata description,
        string calldata imageUri,
        string calldata animationUri,
        string calldata attributes
    ) external onlyOwner {
        _safeMint(to, tokenId);
        
        tokenMetadata[tokenId] = TokenMetadata({
            name: name,
            description: description,
            imageUri: imageUri,
            animationUri: animationUri,
            attributes: attributes
        });
        
        emit MetadataUpdated(tokenId, imageUri);
    }
    
    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        TokenMetadata memory metadata = tokenMetadata[tokenId];
        
        return string(
            abi.encodePacked(
                'data:application/json;base64,',
                _encodeMetadata(metadata)
            )
        );
    }
    
    function _encodeMetadata(TokenMetadata memory metadata) internal pure returns (bytes memory) {
        return abi.encodePacked(
            '{"name":"', metadata.name,
            '","description":"', metadata.description,
            '","image":"ipfs://', metadata.imageUri,
            '","animation_url":"ipfs://', metadata.animationUri,
            '","attributes":', metadata.attributes, '}'
        );
    }
}

Interview Questions

  1. Explain the difference between content-based addressing (IPFS) and location-based addressing (HTTP). What are the advantages of each?

  2. How does Filecoin's Proof of Replication and Proof of Spacetime ensure data availability and integrity?

  3. Design a decentralized storage solution for a social media platform that needs to store user profiles, posts, and media files with high availability.

Quiz Questions

  1. What is a CID (Content Identifier) in IPFS?

    • A) A file path
    • B) A cryptographic hash of content
    • C) An IP address
    • D) A public key
  2. Which service provides permanent storage on Arweave?

    • A) Pinning service
    • B) Storage endowment
    • C) Filecoin deal
    • D) IPFS cluster
  3. What is the main difference between IPFS and Arweave?

    • A) IPFS is faster
    • B) Arweave provides permanent storage
    • C) IPFS is more decentralized
    • D) Arweave is cheaper
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement