# Blockchain Architecture

Understanding LocalGreenChain's blockchain implementation for plant lineage and transport tracking.

## Overview

LocalGreenChain uses a custom proof-of-work blockchain designed specifically for agricultural traceability. Unlike cryptocurrency blockchains, our focus is on:

- **Immutability** - Plant records cannot be altered
- **Traceability** - Complete chain of custody
- **Efficiency** - Lightweight for agricultural use
- **Privacy** - User-controlled data visibility

## Core Concepts

### Blocks

Each block contains:

```typescript
interface PlantBlock {
  index: number;           // Position in chain
  timestamp: string;       // ISO 8601 datetime
  data: PlantData;         // Plant or transport data
  previousHash: string;    // Link to previous block
  hash: string;            // This block's hash
  nonce: number;           // Proof-of-work solution
}
```

### Chain Structure

```
┌─────────────────────────────────────────────────────────────────┐
│                         BLOCKCHAIN                               │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌─────────┐    ┌─────────┐    ┌─────────┐    ┌─────────┐     │
│  │ Genesis │───→│ Block 1 │───→│ Block 2 │───→│ Block 3 │     │
│  │ Block   │    │         │    │         │    │         │     │
│  │         │    │ hash: A │    │ hash: B │    │ hash: C │     │
│  │ prev: 0 │    │ prev: G │    │ prev: A │    │ prev: B │     │
│  └─────────┘    └─────────┘    └─────────┘    └─────────┘     │
│       G              A              B              C             │
│                                                                  │
│  Each block contains:                                            │
│  - Plant registration OR transport event                         │
│  - Timestamp                                                     │
│  - Cryptographic link to previous block                          │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

## Proof of Work

### Mining Process

```typescript
function mineBlock(block: PlantBlock): void {
  const target = '0'.repeat(difficulty);

  while (block.hash.substring(0, difficulty) !== target) {
    block.nonce++;
    block.hash = calculateHash(block);
  }
}
```

### Difficulty Levels

| Difficulty | Leading Zeros | Avg. Time | Use Case |
|------------|---------------|-----------|----------|
| 1 | 0 | < 1ms | Development |
| 2 | 00 | ~10ms | Testing |
| 3 | 000 | ~100ms | Default |
| 4 | 0000 | ~1s | Production |
| 5 | 00000 | ~10s | High Security |

### Hash Calculation

```typescript
function calculateHash(block: PlantBlock): string {
  const data = `${block.index}${block.timestamp}${JSON.stringify(block.data)}${block.previousHash}${block.nonce}`;
  return crypto.createHash('sha256').update(data).digest('hex');
}
```

## Chain Integrity

### Validation

Every block must satisfy:

1. **Correct Hash** - Hash matches recalculated hash
2. **Valid Previous Hash** - Links to actual previous block
3. **Proof of Work** - Hash meets difficulty requirement
4. **Timestamp Order** - Blocks are chronological

```typescript
function isChainValid(chain: PlantBlock[]): boolean {
  for (let i = 1; i < chain.length; i++) {
    const current = chain[i];
    const previous = chain[i - 1];

    // Verify hash
    const expectedHash = calculateHash(current);
    if (current.hash !== expectedHash) return false;

    // Verify chain link
    if (current.previousHash !== previous.hash) return false;

    // Verify proof of work
    const target = '0'.repeat(difficulty);
    if (current.hash.substring(0, difficulty) !== target) return false;
  }
  return true;
}
```

## Data Types

### Plant Registration Block

```typescript
{
  index: 42,
  timestamp: "2024-06-01T10:00:00Z",
  data: {
    type: "plant_registration",
    plantId: "plant-abc123",
    commonName: "Tomato",
    scientificName: "Solanum lycopersicum",
    location: {
      latitude: 40.7128,
      longitude: -74.0060
    },
    owner: {
      id: "user-123",
      name: "John Doe"
    },
    generation: 0,
    parentPlantId: null
  },
  previousHash: "00abc...",
  hash: "00def...",
  nonce: 12345
}
```

### Transport Event Block

```typescript
{
  index: 43,
  timestamp: "2024-06-15T08:00:00Z",
  data: {
    type: "transport_event",
    eventType: "harvest",
    plantIds: ["plant-abc123"],
    fromLocation: { ... },
    toLocation: { ... },
    transportMethod: "electric_vehicle",
    carbonFootprintKg: 2.5,
    distanceKm: 25
  },
  previousHash: "00def...",
  hash: "00ghi...",
  nonce: 67890
}
```

## Lineage Tracking

### Parent-Child Relationships

```
Original Plant (Gen 0)
├── previousHash: null
├── propagationType: null
│
├─→ Clone A (Gen 1)
│   ├── previousHash: Original
│   ├── propagationType: "clone"
│   │
│   ├─→ Seed A-1 (Gen 2)
│   │   └── propagationType: "seed"
│   │
│   └─→ Clone A-2 (Gen 2)
│       └── propagationType: "clone"
│
└─→ Seed B (Gen 1)
    ├── propagationType: "seed"
    │
    └─→ Clone B-1 (Gen 2)
        └── propagationType: "clone"
```

### Lineage Query

```typescript
function getLineage(plantId: string, generations: number): LineageTree {
  const plant = findPlant(plantId);

  return {
    plant,
    ancestors: getAncestors(plant.parentPlantId, generations),
    descendants: getDescendants(plantId, generations)
  };
}
```

## Cross-Chain References

### Transport Chain ↔ Plant Chain

Transport events reference plants by ID:

```typescript
// Transport chain references plant chain
{
  eventType: "harvest",
  plantIds: ["plant-abc123", "plant-abc124"],  // References plant chain
  harvestBatchId: "batch-001"
}

// Plant chain may reference transport
{
  plantId: "plant-abc123",
  lastTransportBlock: 156,  // Reference to transport chain
  currentCustodian: "user-456"
}
```

## Performance Considerations

### Storage

```
Block Size:    ~1-2 KB typical
Growth Rate:   ~10-100 blocks/day (varies by activity)
Storage/year:  ~10-100 MB for active installation
```

### Indexing

Secondary indexes for fast lookups:

```typescript
// Plant ID → Block indices
plantIndex: Map<string, number[]>

// User ID → Block indices
userIndex: Map<string, number[]>

// Location → Block indices (geohash)
locationIndex: Map<string, number[]>
```

## Security

### Tamper Resistance

1. **Hash Chain** - Altering any block changes all subsequent hashes
2. **Proof of Work** - Expensive to recompute chain
3. **Distributed Copies** - Multiple users hold chain copies
4. **Signature Support** - Optional digital signatures

### Attack Resistance

| Attack | Defense |
|--------|---------|
| Data tampering | Hash verification fails |
| Chain rewrite | PoW cost prohibitive |
| Fake blocks | Signature verification |
| Replay | Timestamps + indices |

## Best Practices

### For Developers

1. **Validate on load** - Always verify chain integrity
2. **Backup regularly** - Export chain to JSON
3. **Monitor growth** - Archive old blocks if needed
4. **Index selectively** - Only index what you query

### For Operators

1. **Set appropriate difficulty** - Balance speed vs security
2. **Backup before updates** - Chain is your source of truth
3. **Monitor disk space** - Plan for growth
4. **Test restores** - Verify backups work

## Future Considerations

- **Distributed Consensus** - Multi-node verification
- **Sharding** - Geographic or species-based partitions
- **Merkle Trees** - Efficient verification
- **Zero-Knowledge Proofs** - Privacy-preserving verification
