# 🌱 LocalGreenChain

**A blockchain for plants that preserves lineage across clones and seeds, connecting growers worldwide.**

LocalGreenChain is a revolutionary plant tracking system that uses blockchain technology to create an immutable record of plant lineage. Track every clone, cutting, seed, and offspring throughout multiple generations while connecting with nearby growers who share your passion for plants.

## ✨ Features

### 🌳 **Lineage Tracking**
- Track every plant from its origin through unlimited generations
- Record propagation methods (clone, seed, cutting, division, grafting)
- Build comprehensive family trees showing ancestors, descendants, and siblings
- Immutable blockchain ensures lineage data can never be lost or altered

### 📍 **Geographic Connections**
- Find plants and growers near your location
- Discover plant clusters and hotspots in your area
- Connect with people who have plants from the same lineage
- Build local plant-sharing communities

### 🔗 **Blockchain Security**
- Proof-of-work consensus ensures data integrity
- Each plant registration is a permanent block in the chain
- Cryptographic hashing prevents tampering
- Distributed architecture for reliability

### 🌍 **Global Network**
- Integration with plants.net API for plant identification
- Track how your plants spread across the world
- See global distribution statistics by species and location
- Join a worldwide community of plant enthusiasts

### 🎨 **User-Friendly Interface**
- Beautiful, intuitive web interface
- Easy plant registration with geolocation support
- Visual lineage explorer
- Network statistics dashboard
- Mobile-responsive design

### 🔒 **Privacy & Anonymity (Tor Integration)**
- Anonymous plant registration with zero personal information
- Location obfuscation (fuzzy, city, country, or hidden)
- Tor hidden service support for .onion access
- SOCKS proxy integration for outbound Tor connections
- Privacy-preserving geolocation (share area, not exact location)
- Pseudonymous identities and wallet addresses
- End-to-end encrypted communications

### 🌍 **Environmental Tracking**
- Comprehensive soil composition tracking (type, pH, drainage, amendments)
- Complete nutrient monitoring (NPK, micronutrients, EC/TDS)
- Climate conditions (temperature, humidity, airflow, CO2)
- Lighting analysis (natural/artificial, hours, spectrum, PPFD/DLI)
- Watering schedules and water quality monitoring
- Container and growing location details
- Pest, disease, and companion plant tracking
- Growth metrics and health scoring
- Environmental comparison between plants
- Personalized growing recommendations
- Success correlation analysis across network

**📘 Full Guide**: See [ENVIRONMENTAL_TRACKING.md](./ENVIRONMENTAL_TRACKING.md)

## 🚀 Quick Start

### Prerequisites
- **Bun 1.0+** (https://bun.sh) - A fast JavaScript runtime and package manager
- Basic knowledge of plant propagation (optional but helpful!)

### Why Bun?
LocalGreenChain uses Bun for faster installation, builds, and runtime performance:
- **3x faster** package installation compared to npm
- **Native TypeScript support** without configuration
- **Built-in bundler** for optimal production builds
- **Compatible** with npm packages

### Installing Bun
If you don't have Bun installed:

```bash
# macOS/Linux/WSL
curl -fsSL https://bun.sh/install | bash

# Or using npm
npm install -g bun
```

### Installation

1. **Clone the repository**
```bash
git clone https://github.com/yourusername/localgreenchain.git
cd localgreenchain
```

2. **Install dependencies**
```bash
bun install
```

3. **Set up environment variables** (optional)
```bash
cp .env.example .env
```

Edit `.env` and add your plants.net API key if you have one:
```
PLANTS_NET_API_KEY=your_api_key_here
```

4. **Run the development server**
```bash
bun run dev
```

5. **Open your browser**
Navigate to [http://localhost:3001](http://localhost:3001)

### 🧅 Tor Setup (Optional - For Privacy)

For anonymous plant sharing and privacy protection:

```bash
# Quick start with Docker Compose
docker-compose -f docker-compose.tor.yml up -d

# Or manual setup
# 1. Install Tor
sudo apt install tor

# 2. Configure Tor (copy example config)
sudo cp tor/torrc.example /etc/tor/torrc

# 3. Start Tor
sudo systemctl start tor

# 4. Enable Tor in LocalGreenChain
# Edit .env and set: TOR_ENABLED=true

# 5. Start LocalGreenChain
bun run start

# 6. Get your .onion address
sudo cat /var/lib/tor/localgreenchain/hostname
```

**📘 Full Guide**: See [TOR_SETUP.md](./TOR_SETUP.md) for complete instructions

## 📖 How It Works

### The Blockchain

LocalGreenChain uses a custom blockchain implementation where:

- **Each block** represents a plant registration or update
- **Proof-of-work** mining ensures data integrity
- **Cryptographic hashing** links blocks together
- **Genesis block** initializes the chain

### Plant Lineage System

```
Original Plant (Generation 0)
    ├── Clone 1 (Generation 1)
    │   ├── Seed 1-1 (Generation 2)
    │   └── Cutting 1-2 (Generation 2)
    ├── Clone 2 (Generation 1)
    └── Seed 3 (Generation 1)
        └── Clone 3-1 (Generation 2)
```

Every plant maintains:
- **Parent reference**: Which plant it came from
- **Children array**: All offspring created from it
- **Generation number**: How many steps from the original
- **Propagation type**: How it was created

### Geographic Discovery

The system calculates distances between plants using the Haversine formula to:
- Find plants within a specified radius
- Cluster nearby plants to show hotspots
- Suggest connections based on proximity and species

## 🎯 Use Cases

### For Home Gardeners
- Track your plant collection and propagation success
- Share clones with friends while maintaining the lineage record
- Find local gardeners with similar plants for trading

### For Plant Nurseries
- Provide customers with verified lineage information
- Track all plants sold and their offspring
- Build trust through transparent provenance

### For Conservation Projects
- Document rare plant propagation efforts
- Track genetic diversity across populations
- Coordinate distribution of endangered species

### For Community Gardens
- Manage shared plant collections
- Track plant donations and their spread
- Build local food security networks

### For Research
- Study plant propagation success rates
- Track genetic drift across generations
- Analyze geographic distribution patterns

## 🛠️ API Reference

### Register a Plant
```http
POST /api/plants/register
Content-Type: application/json

{
  "id": "plant-unique-id",
  "commonName": "Tomato",
  "scientificName": "Solanum lycopersicum",
  "location": {
    "latitude": 40.7128,
    "longitude": -74.0060,
    "city": "New York",
    "country": "USA"
  },
  "owner": {
    "id": "user-id",
    "name": "John Doe",
    "email": "john@example.com"
  }
}
```

### Clone a Plant
```http
POST /api/plants/clone
Content-Type: application/json

{
  "parentPlantId": "parent-plant-id",
  "propagationType": "clone",
  "newPlant": {
    "location": {...},
    "owner": {...}
  }
}
```

### Find Nearby Plants
```http
GET /api/plants/nearby?lat=40.7128&lon=-74.0060&radius=50
```

### Get Plant Lineage
```http
GET /api/plants/lineage/plant-id
```

### Search Plants
```http
GET /api/plants/search?q=tomato&type=species
```

### Get Network Statistics
```http
GET /api/plants/network
```

## 🏗️ Architecture

### Tech Stack
- **Runtime**: Bun (fast JavaScript runtime and package manager)
- **Frontend**: Next.js, React, TypeScript, Tailwind CSS
- **Blockchain**: Custom implementation with proof-of-work
- **Storage**: JSON file-based (production can use database)
- **APIs**: RESTful endpoints
- **Geolocation**: Haversine distance calculation, OpenStreetMap geocoding

### Project Structure
```
localgreenchain/
├── lib/
│   ├── blockchain/
│   │   ├── types.ts          # Type definitions
│   │   ├── PlantBlock.ts     # Block implementation
│   │   ├── PlantChain.ts     # Blockchain logic
│   │   └── manager.ts        # Blockchain singleton
│   └── services/
│       ├── plantsnet.ts      # Plants.net API integration
│       └── geolocation.ts    # Location services
├── pages/
│   ├── index.tsx             # Home page
│   ├── plants/
│   │   ├── register.tsx      # Register new plant
│   │   ├── clone.tsx         # Clone existing plant
│   │   ├── explore.tsx       # Browse network
│   │   └── [id].tsx          # Plant details
│   └── api/
│       └── plants/           # API endpoints
└── data/
    └── plantchain.json       # Blockchain storage
```

## 🌐 Scaling for Mass Adoption

### Current Implementation
- **Single-server blockchain**: Good for 10,000s of plants
- **File-based storage**: Simple and portable
- **Client-side rendering**: Fast initial setup

### Scaling Recommendations

#### For 100,000+ Plants
1. **Switch to database**: PostgreSQL or MongoDB
2. **Add caching**: Redis for frequently accessed data
3. **Optimize mining**: Reduce difficulty or use alternative consensus

#### For 1,000,000+ Plants
1. **Distributed blockchain**: Multiple nodes with consensus
2. **Sharding**: Geographic or species-based partitioning
3. **CDN**: Serve static content globally
4. **API rate limiting**: Protect against abuse

#### For Global Scale
1. **Blockchain network**: Peer-to-peer node system
2. **Mobile apps**: Native iOS/Android applications
3. **Offline support**: Sync when connection available
4. **Federation**: Regional chains with cross-chain references

## 🤝 Contributing

We welcome contributions! Here's how you can help:

1. **Add features**: New propagation types, plant care tracking, etc.
2. **Improve UI**: Design enhancements, accessibility
3. **Optimize blockchain**: Better consensus algorithms
4. **Mobile app**: React Native implementation
5. **Documentation**: Tutorials, translations

### Development Process
```bash
# Create a feature branch
git checkout -b feature/amazing-feature

# Make your changes
# ...

# Run tests (when available)
bun test

# Commit with clear message
git commit -m "Add amazing feature"

# Push and create pull request
git push origin feature/amazing-feature
```

## 📜 License

MIT License - see [LICENSE](LICENSE) file for details

## 🙏 Acknowledgments

- Inspired by the global plant-sharing community
- Built with Next.js and React
- Blockchain concept adapted for plant tracking
- Geocoding powered by OpenStreetMap Nominatim

## 📞 Support

- **Issues**: [GitHub Issues](https://github.com/yourusername/localgreenchain/issues)
- **Discussions**: [GitHub Discussions](https://github.com/yourusername/localgreenchain/discussions)
- **Email**: support@localgreenchain.org

## 🗺️ Roadmap

### Phase 1: Core Features ✅
- [x] Blockchain implementation
- [x] Plant registration and cloning
- [x] Lineage tracking
- [x] Geographic search
- [x] Web interface

### Phase 2: Enhanced Features (Q2 2025)
- [ ] User authentication
- [ ] Plant care reminders
- [ ] Photo uploads
- [ ] QR code plant tags
- [ ] Mobile app (React Native)

### Phase 3: Community Features (Q3 2025)
- [ ] Trading marketplace
- [ ] Events and meetups
- [ ] Expert advice forum
- [ ] Plant care wiki
- [ ] Achievements and badges

### Phase 4: Advanced Features (Q4 2025)
- [ ] DNA/genetic tracking integration
- [ ] AI plant identification
- [ ] Environmental impact tracking
- [ ] Carbon sequestration calculations
- [ ] Partnership with botanical gardens

---

**Built with 💚 for the planet**

Start your plant lineage journey today! 🌱
