Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Rust
target/
**/*.rs.bk
*.swp
*.swo

# Cargo
Cargo.lock

# IDE
.vscode/
.idea/
*.iml

# OS
.DS_Store
Thumbs.db

# Soroban
.soroban/
52 changes: 52 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Contributing to PiRC3 (PiDCTP)

Thank you for your interest in contributing to the Pi Decentralized Commerce & Trust Protocol.

## How to Contribute

### Specification Improvements
1. Open an Issue describing the proposed change
2. Reference the specific section (e.g., "Section 3: Escrow System")
3. Provide rationale and any supporting research

### Smart Contract Changes
1. Fork the repository
2. Create a feature branch from `main`
3. Write code with proper error handling (MMMEEE format)
4. Add unit tests for all new functions
5. Ensure `cargo test` passes
6. Submit a Pull Request

### Code Standards

- **Language**: Rust (Soroban SDK)
- **Error codes**: MMMEEE format (MMM=module, EEE=error number)
- **Authorization**: Always call `require_auth()` on action initiators
- **Events**: Emit events for all state-changing operations
- **Imports**: Use shared types from `contracts/shared/`

### Testing

```bash
cargo test # All tests
cargo test -p escrow # Specific module
cargo test -p reputation
cargo test -p dispute
```

### Pull Request Process

1. PRs require at least 1 review
2. All tests must pass
3. No `unwrap()` without proper error handling
4. Documentation updates required for new features

## Reporting Issues

- **Bugs**: Open an Issue with reproduction steps
- **Security vulnerabilities**: Email security@pidctp.org (do NOT publicly disclose)
- **Feature requests**: Open an Issue with use case and rationale

## License

By contributing, you agree that your contributions will be licensed under the MIT License.
14 changes: 14 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[workspace]
members = [
"contracts/shared",
"contracts/escrow",
"contracts/reputation",
"contracts/dispute",
"contracts/merchant",
"contracts/loyalty",
"contracts/coordinator",
]
resolver = "2"

[workspace.dependencies]
soroban-sdk = "22.0.0"
44 changes: 44 additions & 0 deletions PiRC3/1-vision.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# PiRC3 Section 1: Vision & Problem Statement

## The Commerce Trust Gap

Pi Network has 60M+ Pioneers, but commerce between them remains limited by a fundamental problem: **lack of trust infrastructure**. When a Pioneer wants to buy goods or services from another Pioneer, there is no mechanism to:

- Ensure the seller delivers what was promised
- Protect the buyer's payment if the seller fails
- Verify that either party has a reliable transaction history
- Resolve disputes fairly without centralized arbitration

This is the **Commerce Trust Gap** — the missing layer between Pi's token economy (PiRC1) and its payment infrastructure (PiRC2).

## Why Existing Solutions Fall Short

| Approach | Limitation |
|----------|-----------|
| Social trust | Doesn't scale; easily manipulated |
| Centralized escrow | Single point of failure; not decentralized |
| Off-chain reputation | Not verifiable; cannot be used in smart contracts |
| Traditional courts | Too slow; too expensive for micro-transactions |

## PiDCTP Vision

**Pi Decentralized Commerce & Trust Protocol (PiDCTP)** provides a complete, on-chain trust infrastructure that enables safe commerce between any two Pioneers — even those who have never interacted before.

### Core Principles

1. **Trustless by Design**: No single entity controls funds, reputation, or dispute outcomes
2. **Progressive Trust**: Reputation builds over time through verified actions, not purchased
3. **Economic Alignment**: Incentives reward honest behavior; penalties deter fraud
4. **Modular Architecture**: Each module can be upgraded independently
5. **Pi-Native**: Built on Soroban/Stellar, integrated with PiRC1 and PiRC2

### Impact on the Pi Ecosystem

- **For Buyers**: Escrow protection ensures you never lose funds to non-delivery
- **For Sellers**: Verified reputation attracts more customers; escrow confirms buyer has funds
- **For Merchants**: KYB verification establishes legitimacy and builds customer confidence
- **For the Community**: Dispute resolution provides fair outcomes; loyalty rewards honest commerce

## Design Philosophy

PiDCTP follows the principle of **minimum viable centralization** — using on-chain logic and economic incentives wherever possible, and decentralized human judgment (jurors) only when algorithmic resolution is insufficient.
32 changes: 32 additions & 0 deletions PiRC3/10-integration-pirc2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# PiRC3 Section 10: PiRC2 Integration Guide

## Overview

PiDCTP integrates with the PiRC2 Subscription Contract API to enable recurring commerce with escrow protection.

## Integration Points

### Subscription → Escrow
When a subscription charge occurs, PiDCTP can automatically create an escrow for the payment period, protecting both the subscriber and the service provider.

### Subscription → Reputation
Subscription payment history contributes to reputation scores, providing verifiable transaction history for recurring commerce.

### Subscription → Dispute
Subscription-related disputes (unauthorized charges, service not provided) are routed through the Dispute module with the `Subscription` juror specialty.

## Data Flow

```
PiRC2 Subscription Charge
→ PiDCTP Escrow (auto-create with subscription_id)
→ PiDCTP Reputation (record completion)
→ PiDCTP Loyalty (earn points)
```

## Contract Interface

The `subscription_id` field in `EscrowAccount` links escrow transactions to their originating PiRC2 subscriptions, enabling:
- Automatic escrow creation on subscription renewal
- Bulk dispute resolution for subscription-related issues
- Subscription-specific reputation tracking
49 changes: 49 additions & 0 deletions PiRC3/11-security-model.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# PiRC3 Section 11: Security Model

## Threat Analysis

| Threat | Mitigation |
|--------|-----------|
| Fund theft | Checks-Effects-Interactions; no admin override |
| Front-running | Commit-reveal voting; hidden jurors |
| Sybil attacks | Social graph analysis; stake requirements; badge non-transferability |
| Juror collusion | Commit-reveal; weighted voting; consensus tracking |
| Reputation farming | Sybil scoring; attestation weight limits; decay mechanism |
| Governance takeover | Timelock; multi-sig; progressive decentralization |
| Flash loan attacks | No price oracles; no instant governance |
| Reentrancy | All state changes before external calls |

## Security Features

### Smart Contract Level
- **Checks-Effects-Interactions**: All state changes before external token transfers
- **No admin override**: Admins cannot move funds or change escrow outcomes
- **Emergency pause**: Available for critical vulnerabilities only
- **Timelock**: 48-hour delay on all contract upgrades

### Protocol Level
- **3-of-5 admin multi-sig**: Required for upgrades and parameter changes
- **Fee ceiling**: Maximum 10% fee enforced at protocol level
- **Score bounds**: Reputation score clamped to 50-1000 range

### v1.1: Defense-in-Depth

| Attack | Layer 1 | Layer 2 | Layer 3 |
|--------|---------|---------|---------|
| Sybil farming | Sybil scoring | Attestation limits | Badge non-transferability |
| Reputation buying | Soulbound badges | Attestation expiry | Counterparty tracking |
| Juror collusion | Commit-reveal | Weighted voting | Consensus tracking |
| Vote copying | Commit-reveal | Hidden jurors | Vetting requirements |

## Bug Bounty Program

| Severity | Reward | Criteria |
|----------|--------|----------|
| Critical | 5,000 Pi | Fund loss, governance takeover |
| High | 2,000 Pi | State corruption, bypass |
| Medium | 500 Pi | Logic errors, DoS |
| Low | 100 Pi | Minor issues, gas optimization |

## Responsible Disclosure

Report vulnerabilities to security@pidctp.org. Do not publicly disclose until patch is deployed.
71 changes: 71 additions & 0 deletions PiRC3/12-implementation-guide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# PiRC3 Section 12: Implementation Guide

## Technical Stack

- **Smart Contracts**: Rust + Soroban SDK (Stellar blockchain)
- **Token Standard**: Stellar Classic Asset (Pi)
- **Randomness**: Verifiable Random Function (VRF) for juror selection
- **Privacy (roadmap)**: Zero-Knowledge Proofs (ZK-SNARKs)

## Project Structure

```
contracts/
├── shared/ # Shared types & events
├── escrow/ # Escrow + Milestone + Group Escrow
├── reputation/ # Reputation + Badges + Attestations + Sybil + ZK
├── dispute/ # Dispute + Juror Vetting + Weighted Voting
├── merchant/ # Merchant verification
├── loyalty/ # Loyalty & rewards
└── coordinator/ # Entry point & router
```

## Build & Test

```bash
# Build all contracts
soroban contract build

# Run unit tests
cargo test

# Run integration tests
cargo test --test full_flow_test
```

## Deployment

### Testnet
```bash
./scripts/deploy_testnet.sh
```

### Mainnet
```bash
# Pre-deployment checklist
./scripts/verify_deployment.sh
./scripts/deploy_mainnet.sh
```

## Configuration

| Parameter | Testnet | Mainnet |
|-----------|---------|---------|
| Fee | 1% | 1% |
| Evidence duration | 72h | 72h |
| Voting duration | 48h | 48h |
| Reveal duration | 24h | 24h |
| Appeal window | 24h | 24h |
| Dispute fee | 1 Pi | 1 Pi |
| Appeal fee | 2 Pi | 2 Pi |
| Juror count | 3 | 5 |
| Admin threshold | 2-of-3 | 3-of-5 |

## Upgrade Process

1. Deploy new contract version
2. Submit upgrade transaction with 48h timelock
3. Multi-sig approval (3-of-5 on mainnet)
4. Wait for timelock expiry
5. Execute upgrade
6. Verify deployment with `verify_deployment.sh`
54 changes: 54 additions & 0 deletions PiRC3/13-advanced-innovations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# PiRC3 Section 13: Advanced Innovations (v1.1)

## Overview

7 advanced innovations researched from Kleros, Aragon, Status Network, and academic literature on decentralized justice and Sybil resistance.

| Innovation | Module | Attack Vector |
|-----------|--------|--------------|
| Soulbound Badges | Reputation | Reputation buying/selling |
| Milestone Escrow | Escrow | All-or-nothing risk |
| Group Escrow | Escrow | Multi-party coordination |
| Sybil Resistance | Reputation | Fake account farming |
| Juror Vetting | Dispute | Unqualified juror selection |
| Reputation Attestations | Reputation | Cold-start problem |
| ZK Verification | Reputation | Privacy leakage |

## Soulbound Reputation Badges

Non-transferable credential tokens representing what a Pioneer has DONE, not what they HOLD. 10 badge types with +2 score bonus each (max +20). Revocable only for proven fraud (-10 penalty).

## Milestone Escrow

Multi-stage fund release for large/complex orders. Each milestone has independent amount, deadline, and confirmation. Failed milestones refund remaining funds to buyer.

## Group Escrow

Multi-party escrow for group purchases. Each participant contributes independently with proportional refund shares. All must fund before escrow activates.

## Social Graph Sybil Resistance

On-chain transaction pattern analysis: tracks unique counterparties, flags accounts with <30% unique counterparty ratio. Sybil score 0-10000. High Sybil score reduces effective reputation.

## Juror Vetting & Reputation-Weighted Voting

Jurors must meet minimum Silver reputation + 10 Pi stake. Specialty matching ensures relevant expertise. Voting weighted by reputation tier (Bronze=1 to Diamond=5) with consensus bonus.

## Reputation Attestations

Third-party vouching with tier-derived weights (1-5). 180-day expiry. Minimum Silver to attest. Reaching 20 attestation score grants +5 reputation bonus.

## ZK Reputation Verification Roadmap

Phase 1 (current): Simple on-chain tier verification. Phase 2 (planned): Off-chain ZK proof generation. Phase 3 (future): Full ZK-SNARK integration with dedicated verifier contract.

## Cross-Innovation Defense-in-Depth

| Attack | Layer 1 | Layer 2 | Layer 3 |
|--------|---------|---------|---------|
| Sybil farming | Sybil scoring | Attestation limits | Badge non-transferability |
| Reputation buying | Soulbound badges | Attestation expiry | Counterparty tracking |
| Juror collusion | Commit-reveal | Weighted voting | Consensus tracking |
| Vote copying | Commit-reveal | Hidden jurors | Vetting requirements |
| Cold-start spam | Min Silver to attest | Attestation expiry | Stake requirements |
| Score privacy leak | ZK tier verification | Off-chain proof gen | Dedicated verifier |
Loading