hackertron / hackertron/zkTrust

starknet plan

Open
#3 0 comments 0 reactions 1 assignee Claimed by @hackertron View on GitHub
Dominant language
TypeScript
Stars
3
Forks
0
PR merge metrics
No merged PRs in 30d

Description

# ZKTrust Starknet Integration: Technical Design Document

## 1. Introduction and Overview

This document outlines a detailed technical approach for integrating Starknet's Garaga tool with the existing ZKTrust platform to enhance purchase verification through zero-knowledge proofs. The implementation focuses on creating a targeted integration that leverages Starknet's cryptographic capabilities while minimizing changes to the existing ZKTrust architecture.

### 1.1 Project Scope

For this hackathon implementation, we will:
- Create a Cairo smart contract using Garaga for verifying email purchase proofs
- Develop the necessary frontend integration to connect ZKTrust with the Starknet verification layer
- Maintain the existing user experience and workflow, adding only the enhanced verification capability

### 1.2 Benefits of Starknet Integration

- **Enhanced Security**: Leverage Starknet's STARK proofs for verification, providing cryptographic guarantees
- **Privacy**: Ensure customer data remains private while still proving purchase authenticity
- **Scalability**: Reduce computational overhead by offloading verification to Starknet
- **Future-proofing**: Position ZKTrust within the growing Starknet ecosystem

## 2. System Architecture

### 2.1 High-Level Architecture

```
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ │ │ │ │ │
│ ZKTrust │ ──────▶ │ Starknet │ ──────▶ │ Ethereum L1 │
│ Application │ │ Verification │ │ (Optional) │
│ │ ◀────── │ Layer │ ◀────── │ │
└───────────────┘ └───────────────┘ └───────────────┘
```

### 2.2 Component Overview

1. **ZKTrust Frontend**: Existing application that handles user interactions, email parsing, and review submission
2. **ZK Email Proof Generator**: Enhanced component that generates purchase proofs
3. **Starknet Verification Contract**: New Cairo contract that verifies proofs using Garaga
4. **ZKTrust Backend**: Existing backend that stores verified reviews in the database

### 2.3 Data Flow

1. User uploads an email receipt to ZKTrust
2. ZKTrust generates a ZK proof of the purchase
3. The proof is sent to the Starknet verification contract
4. Starknet verifies the proof and returns the result
5. ZKTrust saves the verified review with a verification marker

## 3. Technical Implementation

### 3.1 Development Environment Setup

#### 3.1.1 Prerequisites

- Node.js (v18+)
- Python 3.10 (required for Garaga)
- Cairo development tools
- Starknet.js (for frontend integration)

#### 3.1.2 Installation Steps

```bash
# Install Cairo dependencies
brew install gmp

# Install Python dependencies
pip install fastecdsa
pip install garaga

# Add Starknet.js to existing project
npm install starknet@next starknet-devnet
```

### 3.2 Smart Contract Development

#### 3.2.1 Cairo Contract for Proof Verification

Create a simplified verification contract in Cairo that integrates with Garaga to verify ZK proofs from email receipts.

**File Structure**:
```
/contracts
/zktrust_verifier
- verifier.cairo # Main verification contract
- interfaces.cairo # Contract interfaces
```

**Key Components**:
- Proof verification function
- Interface for ZKTrust to call
- Event emission for successful verifications

#### 3.2.2 Contract Development Process

1. Define the verification interface
2. Implement the core verification logic using Garaga
3. Add event emission for tracking
4. Test with sample proofs
5. Deploy to Starknet testnet

### 3.3 Frontend Integration

#### 3.3.1 Adding Starknet.js to ZKTrust

Integrate Starknet.js with the existing ZKTrust frontend to enable communication with the Starknet verification contract.

```javascript
// Example Starknet.js integration
import { Provider, Contract } from 'starknet';

// Initialize provider
const provider = new Provider({
sequencer: { baseUrl: 'https://alpha4.starknet.io' }
});

// Load contract
const contract = new Contract(
VerifierABI,
VerifierAddress,
provider
);
```

#### 3.3.2 Updating Proof Generation Flow

Extend the existing proof generation process to include Starknet verification:

1. Generate the ZK proof as before
2. Format the proof for Starknet verification
3. Send the proof to the Starknet contract
4. Process the verification result

### 3.4 Backend Integration

#### 3.4.1 Updating the Review Storage Process

Enhance the review submission and storage process to include Starknet verification status:

1. Add a `starknet_verified` field to the reviews table
2. Update the submission API to include verification information
3. Add verification results to the review display

#### 3.4.2 API Modifications

```
POST /api/submit-review
{
proofObject: {...},
reviewText: "Great product!",
rating: 5,
starknetVerification: {
verified: true,
transactionHash: "0x..."
}
}
```

## 4. Testing Strategy

### 4.1 Unit Testing

- Test verification contract functions
- Test proof generation and format conversion
- Test frontend-to-Starknet communication

### 4.2 Integration Testing

- End-to-end flow from email receipt to verified review
- Error handling and recovery
- Network issues and retry logic

### 4.3 Performance Testing

- Verify proof generation speed
- Measure verification latency
- Test under concurrent user load

## 5. Implementation Plan

### 5.1 Phase 1: Setup and Smart Contract Development (Days 1-2)

- [ ] Set up development environment
- [ ] Create and test basic verification contract
- [ ] Deploy contract to Starknet testnet

### 5.2 Phase 2: Frontend Integration (Days 3-4)

- [ ] Add Starknet.js to ZKTrust
- [ ] Implement proof submission flow
- [ ] Update user interface for verification feedback

### 5.3 Phase 3: Backend Integration and Testing (Day 5)

- [ ] Update review storage and API
- [ ] Perform integration testing
- [ ] Fix bugs and optimize performance

## 6. Hackathon Demo

For the hackathon demo, we'll focus on the following key points:

1. **Proof of Concept**: Show a complete flow from email receipt to verified review
2. **Technical Innovation**: Highlight the use of Garaga for verification
3. **User Experience**: Demonstrate how the verification enhances trust in reviews
4. **Future Potential**: Discuss scaling and additional features

## 7. Code Examples

### 7.1 Cairo Verification Contract

```cairo
#[starknet::contract]
mod ZKTrustVerifier {
use garaga::groth16::verifier::{self, VerificationKey, Proof};
use starknet::event::EventEmitter;

#[storage]
struct Storage {
verified_proofs: LegacyMap::,
}

#[event]
#[derive(Drop, starknet::Event)]
enum Event {
ProofVerified: ProofVerified,
}

#[derive(Drop, starknet::Event)]
struct ProofVerified {
proof_hash: felt252,
product_name: felt252,
}

#[external]
fn verify_purchase_proof(
ref self: ContractState,
proof: Proof,
public_inputs: Array,
product_name: felt252,
) -> bool {
let verification_key = get_verification_key();
let is_valid = verifier::verify(verification_key, proof, public_inputs);

if is_valid {
let proof_hash = compute_proof_hash(proof, public_inputs);
self.verified_proofs.write(proof_hash, true);

self.emit(ProofVerified {
proof_hash,
product_name
});
}

is_valid
}

#[view]
fn is_proof_verified(
self: @ContractState,
proof_hash: felt252
) -> bool {
self.verified_proofs.read(proof_hash)
}

fn compute_proof_hash(
proof: Proof,
public_inputs: Array
) -> felt252 {
// Compute a hash of the proof and public inputs
// Implementation details omitted for brevity
return hash;
}

fn get_verification_key() -> VerificationKey {
// Return the verification key for email purchase proofs
// Implementation details omitted for brevity
return verification_key;
}
}
```

### 7.2 Frontend Integration with Starknet.js

```typescript
import { Provider, Contract, stark, uint256 } from 'starknet';
import VerifierABI from './abis/verifier_abi.json';

export class StarknetVerifier {
private provider: Provider;
private contract: Contract;

constructor(contractAddress: string) {
this.provider = new Provider({
sequencer: { baseUrl: 'https://alpha4.starknet.io' }
});

this.contract = new Contract(
VerifierABI,
contractAddress,
this.provider
);
}

async verifyProof(proofObject: any, publicInputs: string[], productName: string): Promise {
try {
// Format proof for Starknet
const starknetProof = this.formatProofForStarknet(proofObject);

// Call the verification contract
const result = await this.contract.verify_purchase_proof(
starknetProof,
publicInputs,
stark.shortStringToBigInt(productName)
);

return result.verified;
} catch (error) {
console.error("Verification error:", error);
return false;
}
}

private formatProofForStarknet(proofObject: any) {
// Convert proof object to Starknet-compatible format
// Implementation details depend on proof structure
return formattedProof;
}
}
```

### 7.3 Integration with Existing ZKTrust Components

```typescript
// In ProofGenerator.tsx
import { StarknetVerifier } from './StarknetVerifier';

// Initialize verifier with contract address
const verifier = new StarknetVerifier('0x123...abc');

// Inside handleSubmitReview function
const handleSubmitReview = async () => {
// Validate inputs as before
if (!proofResult || !reviewText || rating === 0) {
// Handle validation errors
return;
}

// Set submission status
setSubmissionStatus('submitting');

try {
// Verify proof using Starknet
const isVerified = await verifier.verifyProof(
proofResult,
proofResult.props.publicOutputs,
verifiedProductName
);

if (!isVerified) {
setSubmissionError('Starknet verification failed');
setSubmissionStatus('failed');
return;
}

// Submit review with verification result
const response = await fetch(`${API_URL}/submit-review`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
proofObject: proofResult,
reviewText: reviewText.trim(),
rating: rating,
starknetVerification: {
verified: isVerified,
transactionHash: proofResult.transactionHash
}
})
});

// Process response as before
} catch (error) {
// Handle errors
}
};
```

## 8. Limitations and Future Work

### 8.1 Limitations

- Initial implementation focuses only on purchase verification, not full Starknet integration
- The verification process adds latency to the review submission flow
- Limited to proof types supported by Garaga

### 8.2 Future Work

- Move more of the verification logic on-chain
- Add support for other types of proof (service usage, membership, etc.)
- Implement token-based incentives for verified reviews
- Create a more robust proof generation process
- Explore full migration to Starknet for enhanced scalability

## 9. Resources and References

- [Garaga GitHub Repository](https://github.com/keep-starknet-strange/garaga)
- [Starknet Documentation](https://docs.starknet.io/)
- [Cairo Programming Language](https://book.cairo-lang.org/)
- [Starknet.js Documentation](https://www.starknetjs.com/)

---

## Conclusion

This technical design document provides a roadmap for integrating Starknet's Garaga tool with the ZKTrust platform for enhanced purchase verification. By focusing on a targeted integration that leverages Starknet's cryptographic capabilities while minimizing changes to the existing architecture, we can deliver a compelling proof of concept for the hackathon that demonstrates the potential of zero-knowledge proofs for verified reviews.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.