IPFS and Decentralized Storage
InterPlanetary File System (IPFS) provides decentralized storage using content addressing, enabling permanent and censorship-resistant data storage.
IPFS Architecture
Content Addressing
IPFS uses content-based addressing instead of location-based addressing.
CID (Content Identifier)
CID Structure
// 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
| Algorithm | Output Size | Use Case | Security |
|---|---|---|---|
| SHA-256 | 32 bytes | General purpose | High |
| SHA-512 | 64 bytes | High security | Very High |
| BLAKE2b | 32 bytes | Fast hashing | High |
| BLAKE3 | 32 bytes | Fastest | High |
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
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
| Service | Cost | Replicas | Guarantees | API |
|---|---|---|---|---|
| Pinata | $0.10/GB | 3+ | SLA | REST |
| Infura | $0.10/GB | 3+ | SLA | REST |
| Filecoin | Variable | 10+ | Economic | GraphQL |
| Crust | Variable | 6+ | Economic | REST |
| Self-hosted | Free | Variable | None | IPFS |
Filecoin Integration
Filecoin Deal Flow
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
| Feature | Arweave | IPFS |
|---|---|---|
| Storage Model | Permanent | Pinning required |
| Cost | One-time fee | Recurring |
| Consensus | Proof of Access | None |
| Data Availability | Permanent | Depends on pinning |
| Use Case | Archives | Dynamic content |
Decentralized Frontends
IPFS + ENS Deployment
// 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
// 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
| Feature | IPFS | Arweave | Filecoin | Sia |
|---|---|---|---|---|
| Storage Model | Pinning | Permanent | Contract | Contract |
| Cost | Low | Medium | Variable | Variable |
| Durability | Medium | High | High | High |
| Speed | Fast | Medium | Variable | Medium |
| Complexity | Low | Medium | High | Medium |
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
-
Explain the difference between content-based addressing (IPFS) and location-based addressing (HTTP). What are the advantages of each?
-
How does Filecoin's Proof of Replication and Proof of Spacetime ensure data availability and integrity?
-
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
-
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
-
Which service provides permanent storage on Arweave?
- A) Pinning service
- B) Storage endowment
- C) Filecoin deal
- D) IPFS cluster
-
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