IPFS & Decentralized Storage

Decentralized StorageFree Lesson

Advertisement

IPFS & Decentralized Storage

InterPlanetary File System, content addressing, pinning, and storage solutions.

Overview

IPFS provides decentralized, content-addressed storage.

Key Concepts

ConceptDescription
CIDContent Identifier
PinningKeep data available
GatewayHTTP access to IPFS
SwarmDistributed storage

IPFS Operations

// Pin a file
const fs = require('fs');
const { create } = require('ipfs-http-client');

const ipfs = create('http://localhost:5001');

async function pinFile(filePath) {
    const file = fs.readFileSync(filePath);
    const result = await ipfs.add(file);
    console.log('CID:', result.path);
    return result.path;
}

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

Pinning Services

ServiceFeatures
PinataManaged pinning
InfuraIPFS gateway
FilecoinIncentivized storage
ArweavePermanent storage

Smart Contract Integration

contract IPFSStore {
    mapping(uint256 => string) public documents;
    
    function storeDocument(uint256 id, string calldata cid) public {
        documents[id] = cid;
    }
    
    function getDocumentURL(uint256 id) public view returns (string memory) {
        return string(abi.encodePacked("https://ipfs.io/ipfs/", documents[id]));
    }
}

Best Practices

  1. Pin important data — Ensure availability
  2. Use gateways — HTTP fallback
  3. Encrypt sensitive data — Privacy protection
  4. Backup references — Multiple sources

Practice

Build a decentralized file storage dApp with IPFS.

Advertisement

Need Expert Blockchain Help?

Get personalized Web3 training or smart contract consulting.

Advertisement