ZKFile
Loading

ZKFile Core SDK Documentation

Build privacy-first applications with zero-knowledge encryption and on-chain access control.

What is ZKFile Core SDK?

ZKFile Core SDK is a TypeScript/JavaScript library that enables developers to build applications with:

  • Client-side encryption using AES-256-GCM
  • On-chain access control via Solana blockchain
  • Decentralized storage with IPFS and Arweave
  • Zero-knowledge proofs for privacy-preserving verification
View on GitHub

Installation

Install the ZKFile Core SDK using your preferred package manager:

npm
npm install @zkfile/core-sdk
yarn
yarn add @zkfile/core-sdk
pnpm
pnpm add @zkfile/core-sdk

Note: ZKFile Core SDK requires Node.js 16+ and works in both browser and Node.js environments.

Quick Start

Get started with ZKFile in just a few lines of code:

example.ts
import { ZKFileClient } from '@zkfile/core-sdk';
import { Connection, clusterApiUrl } from '@solana/web3.js';

// Initialize client
const zkfile = new ZKFileClient({
  rpcEndpoint: clusterApiUrl('mainnet-beta'),
  storageProvider: 'ipfs'
});

// Upload encrypted file
const file = new File(['Hello ZKFile'], 'secret.txt');
const result = await zkfile.upload({
  file,
  password: 'secure-password',
  wallet: walletAdapter
});

console.log('File ID:', result.fileId);
console.log('CID:', result.cid);

// Download and decrypt file
const decrypted = await zkfile.download({
  fileId: result.fileId,
  password: 'secure-password',
  wallet: walletAdapter
});

Architecture Overview

ZKFile Core SDK follows a modular architecture with clear separation of concerns:

System Architecture
┌─────────────────────────────────────┐
│      Client Application             │
│    (React / Next.js / Vue)          │
└────────────┬────────────────────────┘
             │
             ▼
┌─────────────────────────────────────┐
│      @zkfile/core-sdk               │
│  ┌──────────────────────────────┐   │
│  │   ZKFileClient (Main API)    │   │
│  └──────────────────────────────┘   │
│         │                            │
│  ┌──────┴──────┬──────┬──────┐      │
│  ▼             ▼      ▼      ▼      │
│ Crypto    Storage  Blockchain ZKProof│
│ Module    Module   Module    Module │
└─────────────────────────────────────┘
       │          │          │
       ▼          ▼          ▼
   ┌──────┐  ┌────────┐ ┌──────┐
   │ IPFS │  │Arweave │ │Solana│
   └──────┘  └────────┘ └──────┘

Core Modules

Crypto Module

Handles all cryptographic operations including AES-256-GCM encryption, PBKDF2 key derivation, and secure random generation.

Storage Module

Manages decentralized storage operations with IPFS and Arweave, providing redundancy and permanent storage options.

Blockchain Module

Interacts with Solana blockchain for on-chain access control, metadata storage, and immutable audit trails.

ZK Proof Module

Generates and verifies zero-knowledge proofs for privacy-preserving data verification without revealing the data itself.

Encryption

ZKFile uses industry-standard AES-256-GCM encryption with PBKDF2 key derivation:

Encryption Specifications

AlgorithmAES-256-GCM
Key Size256 bits
IV Size96 bits (12 bytes)
Salt Size128 bits (16 bytes)
Auth Tag128 bits
KDFPBKDF2-SHA256
Iterations100,000
Encryption Flow
Password → PBKDF2 (100k iterations) → 256-bit Key
                                            ↓
File Data + Key + IV → AES-256-GCM → Ciphertext + Auth Tag

Storage Layer

ZKFile supports multiple decentralized storage providers:

IPFS Storage

  • Fast access with CDN support
  • Content-addressed storage
  • Distributed and redundant

Arweave Storage

  • Permanent storage (200+ years)
  • One-time payment model
  • Immutable by design

Blockchain Integration

ZKFile leverages Solana blockchain for on-chain access control and metadata storage:

On-Chain Data Structure
File Account (PDA)
├── owner: PublicKey
├── cid: string (IPFS/Arweave)
├── file_hash: string (SHA-256)
├── created_at: i64
├── metadata: Vec<u8>
└── access_list: Vec<AccessGrant>

AccessGrant
├── recipient: PublicKey
├── granted_at: i64
├── expires_at: Option<i64>
└── permissions: u8

ZKFileClient API

Constructor
new ZKFileClient(config: ZKFileConfig)

interface ZKFileConfig {
  rpcEndpoint: string;              // Solana RPC URL
  programId?: string;               // ZKFile program ID
  storageProvider: 'ipfs' | 'arweave';
  ipfsGateway?: string;             // IPFS gateway URL
  arweaveGateway?: string;          // Arweave gateway URL
}

Upload API

upload()
await zkfile.upload(options: UploadOptions): Promise<UploadResult>

interface UploadOptions {
  file: File | Blob;
  password: string;
  wallet: WalletAdapter;
  metadata?: {
    name?: string;
    description?: string;
    tags?: string[];
  };
  onProgress?: (progress: number) => void;
}

interface UploadResult {
  fileId: string;
  cid: string;
  signature: string;
  metadata: FileMetadata;
  uploadedAt: number;
}

Example

const result = await zkfile.upload({
  file: myFile,
  password: 'secure-password',
  wallet: walletAdapter,
  metadata: {
    name: 'My Document',
    tags: ['important', 'private']
  },
  onProgress: (progress) => {
    console.log(`Upload progress: ${progress}%`);
  }
});

Download API

download()
await zkfile.download(options: DownloadOptions): Promise<File>

interface DownloadOptions {
  fileId: string;
  password: string;
  wallet: WalletAdapter;
  onProgress?: (progress: number) => void;
}

Example

const file = await zkfile.download({
  fileId: 'abc123...',
  password: 'secure-password',
  wallet: walletAdapter
});

// Use the decrypted file
const url = URL.createObjectURL(file);

Share API

share()
await zkfile.share(options: ShareOptions): Promise<ShareResult>

interface ShareOptions {
  fileId: string;
  recipient: PublicKey;
  expiresAt?: number;
  wallet: WalletAdapter;
}

interface ShareResult {
  accessId: string;
  signature: string;
  recipient: PublicKey;
  expiresAt?: number;
}

Example

const result = await zkfile.share({
  fileId: 'abc123...',
  recipient: new PublicKey('recipient-address'),
  expiresAt: Date.now() + 7 * 24 * 60 * 60 * 1000, // 7 days
  wallet: walletAdapter
});

Security Model

ZKFile implements a multi-layer security architecture:

Layer 1: Client-Side

  • AES-256-GCM Encryption
  • PBKDF2 Key Derivation
  • Local Key Storage

Layer 2: Transport

  • HTTPS/TLS
  • Signature Verification
  • Wallet Authentication

Layer 3: Storage

  • Encrypted at Rest
  • Content Addressing
  • Distributed Storage

Layer 4: Access Control

  • Cryptographic Grants
  • Time-locked Access
  • Revocable Permissions

Layer 5: Blockchain

  • Immutable Metadata
  • On-chain Verification
  • Audit Trail

Best Practices

Security Best Practices

  • Never hardcode passwords - Use secure input methods
  • Implement password strength validation (min 12 characters)
  • Use secure random generation for salts and IVs
  • Enable 2FA on wallets for additional security
  • Validate file sizes before encryption

React Integration

FileUploader.tsx
import { useWallet } from '@solana/wallet-adapter-react';
import { ZKFileClient } from '@zkfile/core-sdk';
import { useState } from 'react';

function FileUploader() {
  const wallet = useWallet();
  const [uploading, setUploading] = useState(false);
  
  const zkfile = new ZKFileClient({
    rpcEndpoint: clusterApiUrl('mainnet-beta'),
    storageProvider: 'ipfs'
  });
  
  const handleUpload = async (file: File) => {
    setUploading(true);
    try {
      const result = await zkfile.upload({
        file,
        password: 'user-password',
        wallet
      });
      console.log('Uploaded:', result.fileId);
    } finally {
      setUploading(false);
    }
  };
  
  return (
    <input 
      type="file" 
      onChange={(e) => handleUpload(e.target.files![0])}
      disabled={uploading}
    />
  );
}

Next.js Integration

app/api/upload/route.ts
import { ZKFileClient } from '@zkfile/core-sdk';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  const formData = await request.formData();
  const file = formData.get('file') as File;
  
  const zkfile = new ZKFileClient({
    rpcEndpoint: process.env.SOLANA_RPC_URL!,
    storageProvider: 'ipfs'
  });
  
  const result = await zkfile.upload({
    file,
    password: formData.get('password') as string,
    wallet: // ... wallet adapter
  });
  
  return NextResponse.json({ fileId: result.fileId });
}

Configuration Options

const zkfile = new ZKFileClient({
  // Required
  rpcEndpoint: 'https://api.mainnet-beta.solana.com',
  storageProvider: 'ipfs', // or 'arweave'
  
  // Optional
  programId: 'ZKF...', // ZKFile Program ID
  ipfsGateway: 'https://ipfs.io',
  arweaveGateway: 'https://arweave.net',
  defaultEncryption: 'aes-256-gcm',
  kdfIterations: 100000
});

Advanced Usage

Custom Storage Provider

You can implement custom storage providers by extending the StorageProvider interface:

interface StorageProvider {
  upload(data: Uint8Array): Promise<string>;
  download(cid: string): Promise<Uint8Array>;
  pin(cid: string): Promise<void>;
  unpin(cid: string): Promise<void>;
}