# System Architecture Overview

LocalGreenChain is a distributed agricultural tracking platform built on blockchain technology with a focus on demand-driven, seasonal production and reduced environmental impact.

## High-Level Architecture

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         LOCALGREENCHAIN PLATFORM                            │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │                        PRESENTATION LAYER                            │  │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌────────────┐ │  │
│  │  │   Web App   │  │ Mobile PWA  │  │   IoT Hub   │  │  QR Scanner│ │  │
│  │  │  (Next.js)  │  │   (React)   │  │  Dashboard  │  │    App     │ │  │
│  │  └─────────────┘  └─────────────┘  └─────────────┘  └────────────┘ │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                                    │                                        │
│                                    ▼                                        │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │                          API LAYER                                   │  │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌────────────┐ │  │
│  │  │   Plants    │  │  Transport  │  │   Demand    │  │  Vertical  │ │  │
│  │  │     API     │  │     API     │  │     API     │  │  Farm API  │ │  │
│  │  └─────────────┘  └─────────────┘  └─────────────┘  └────────────┘ │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                                    │                                        │
│                                    ▼                                        │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │                       SERVICE LAYER                                  │  │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌────────────┐ │  │
│  │  │ Blockchain  │  │   Climate   │  │   Demand    │  │   Carbon   │ │  │
│  │  │   Service   │  │   Service   │  │  Forecasting│  │  Calculator│ │  │
│  │  └─────────────┘  └─────────────┘  └─────────────┘  └────────────┘ │  │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌────────────┐ │  │
│  │  │ Geolocation │  │   Privacy   │  │    Seed     │  │  Analytics │ │  │
│  │  │   Service   │  │   (Tor)     │  │   Service   │  │   Engine   │ │  │
│  │  └─────────────┘  └─────────────┘  └─────────────┘  └────────────┘ │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                                    │                                        │
│                                    ▼                                        │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │                         DATA LAYER                                   │  │
│  │  ┌─────────────────────────────────────────────────────────────┐   │  │
│  │  │                    USER BLOCKCHAINS                          │   │  │
│  │  │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐        │   │  │
│  │  │  │ User A  │  │ User B  │  │ User C  │  │  ...    │        │   │  │
│  │  │  │  Chain  │  │  Chain  │  │  Chain  │  │         │        │   │  │
│  │  │  └─────────┘  └─────────┘  └─────────┘  └─────────┘        │   │  │
│  │  └─────────────────────────────────────────────────────────────┘   │  │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐                │  │
│  │  │   Master    │  │   Demand    │  │   Climate   │                │  │
│  │  │   Ledger    │  │    Store    │  │    Store    │                │  │
│  │  └─────────────┘  └─────────────┘  └─────────────┘                │  │
│  └─────────────────────────────────────────────────────────────────────┘  │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

## Core Components

### 1. User Blockchain System

Each user operates their own blockchain that records:
- Plant registrations
- Growth updates
- Transport events
- Harvest records
- Seed saving activities

```typescript
// User blockchain structure
interface UserBlockchain {
  userId: string;
  publicKey: string;
  chain: PlantBlock[];
  transportChain: TransportBlock[];
  demandPreferences: DemandPreference[];
}
```

### 2. Master Ledger

A global ledger that:
- Indexes all user blockchains
- Maintains cross-references for plant lineage
- Validates chain integrity
- Calculates network-wide statistics

### 3. Demand Forecasting Engine

Predicts demand based on:
- Historical consumption patterns
- Seasonal trends
- Weather forecasts
- Consumer preferences
- Regional availability

### 4. Carbon Calculator

Tracks environmental impact:
- Transport emissions
- Growing resource usage
- Packaging lifecycle
- Waste generation

## Data Flow

### Plant Registration Flow

```
User Input → Validation → Block Creation → Mining → Chain Addition → Index Update
                                                                          ↓
                                                              Master Ledger Sync
```

### Transport Event Flow

```
Transport Scan → GPS Capture → Condition Check → Block Creation → Chain Update
       ↓               ↓              ↓
  QR Decode    Location Record   Temp/Humidity
       ↓               ↓              ↓
  Plant Lookup  Distance Calc   Alert if OOB
                      ↓
              Carbon Calculation
```

### Demand Signal Flow

```
Consumer Preference → Aggregation → Forecasting → Grower Signals
         ↓                              ↓
    Market Data                   Planting Recommendations
         ↓                              ↓
    Weather API                   Seasonal Optimization
```

## Module Structure

```
localgreenchain/
├── lib/
│   ├── blockchain/           # Core blockchain implementation
│   │   ├── PlantBlock.ts     # Block structure
│   │   ├── PlantChain.ts     # Chain operations
│   │   ├── UserChain.ts      # Per-user blockchain
│   │   ├── types.ts          # Type definitions
│   │   └── manager.ts        # Singleton manager
│   │
│   ├── transport/            # Transport tracking
│   │   ├── events.ts         # Event types
│   │   ├── tracker.ts        # Transport logic
│   │   ├── carbon.ts         # Emissions calculator
│   │   └── qr.ts             # QR code generation
│   │
│   ├── demand/               # Demand forecasting
│   │   ├── forecaster.ts     # ML forecasting
│   │   ├── seasonal.ts       # Seasonal planning
│   │   ├── aggregator.ts     # Demand aggregation
│   │   └── signals.ts        # Grower notifications
│   │
│   ├── vertical-farming/     # Vertical farm integration
│   │   ├── controller.ts     # Environment control
│   │   ├── sensors.ts        # IoT integration
│   │   ├── automation.ts     # Automated systems
│   │   └── recipes.ts        # Growing recipes
│   │
│   ├── environment/          # Environmental tracking
│   │   ├── types.ts          # Environment types
│   │   └── analysis.ts       # Data analysis
│   │
│   ├── privacy/              # Privacy features
│   │   └── anonymity.ts      # Tor integration
│   │
│   └── services/             # External services
│       ├── geolocation.ts    # Location services
│       ├── plantsnet.ts      # Plants.net API
│       └── tor.ts            # Tor connectivity
│
├── pages/
│   ├── api/                  # API routes
│   │   ├── plants/           # Plant endpoints
│   │   ├── transport/        # Transport endpoints
│   │   ├── demand/           # Demand endpoints
│   │   └── vertical-farm/    # VF endpoints
│   │
│   └── [pages]               # UI pages
│
├── components/               # React components
├── docs/                     # Documentation
└── types/                    # Global types
```

## Security Model

### Blockchain Security

- **Proof-of-Work**: Mining difficulty prevents rapid chain modification
- **Hash Linking**: Each block references previous hash
- **Validation**: Full chain validation before accepting data

### User Security

- **Wallet Addresses**: Pseudonymous identification
- **Tor Integration**: Optional anonymous operation
- **Location Privacy**: Configurable precision levels

### Data Integrity

- **Immutable Records**: Historical data cannot be altered
- **Cross-Verification**: Multiple parties can verify events
- **Audit Trail**: Complete history of all operations

## Scalability Strategy

### Current Implementation (10K plants)
- File-based blockchain storage
- Single-server architecture
- Client-side rendering

### Medium Scale (100K plants)
- PostgreSQL/MongoDB backend
- Redis caching layer
- Load-balanced API servers

### Large Scale (1M+ plants)
- Distributed node network
- Geographic sharding
- P2P blockchain sync
- Mobile-first architecture

## Integration Points

### External APIs
- **Plants.net**: Plant identification
- **OpenStreetMap**: Geocoding
- **Weather APIs**: Climate data
- **Carbon APIs**: Emission factors

### IoT Devices
- **Temperature sensors**: Cold chain monitoring
- **GPS trackers**: Transport tracking
- **Humidity sensors**: Environment monitoring
- **Vertical farm controllers**: Automated growing
