IPFS & Decentralized Storage
InterPlanetary File System, content addressing, pinning, and storage solutions.
Overview
IPFS provides decentralized, content-addressed storage.
Key Concepts
| Concept | Description |
|---|---|
| CID | Content Identifier |
| Pinning | Keep data available |
| Gateway | HTTP access to IPFS |
| Swarm | Distributed 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
| Service | Features |
|---|---|
| Pinata | Managed pinning |
| Infura | IPFS gateway |
| Filecoin | Incentivized storage |
| Arweave | Permanent 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
- Pin important data — Ensure availability
- Use gateways — HTTP fallback
- Encrypt sensitive data — Privacy protection
- Backup references — Multiple sources
Practice
Build a decentralized file storage dApp with IPFS.