localgreenchain/docs/architecture/user-blockchain.md
Claude ac93368e9a
Add seed-to-seed transport tracking, demand forecasting, and vertical farming systems
This comprehensive update implements:

Transport Tracking System:
- Complete seed-to-seed lifecycle tracking with 9 event types
- TransportChain blockchain for immutable transport records
- Carbon footprint calculation per transport method
- Food miles tracking with Haversine distance calculation
- QR code generation for full traceability

Demand Forecasting System:
- Consumer preference registration and aggregation
- Regional demand signal generation
- Supply gap identification and market matching
- Grower planting recommendations with risk assessment
- Seasonal planning integration

Vertical Farming Module:
- Multi-zone facility management
- Environmental control systems (HVAC, CO2, humidity, lighting)
- Growing recipes with stage-based environment targets
- Crop batch tracking with health scoring
- Farm analytics generation

Documentation:
- Complete docs/ folder structure for Turborepo
- Seed-to-seed transport concept documentation
- Demand forecasting and seasonal planning guides
- System architecture and user blockchain design
- Transport API reference
- Vertical farming integration guide

Agent Report:
- AGENT_REPORT.md with 5 parallel agent tasks for continued development
- API routes implementation task
- UI components task
- Vertical farming pages task
- Testing suite task
- Documentation completion task
2025-11-22 18:23:08 +00:00

12 KiB

User Blockchain Architecture

Every user in LocalGreenChain operates their own blockchain, creating a decentralized network of plant lineage and transport records that collectively form a global agricultural tracking system.

Why Per-User Blockchains?

Traditional Centralized Approach

All Data → Central Database → Single Point of Failure
                ↓
        Trust the operator
        Data can be modified
        Privacy concerns

LocalGreenChain Distributed Approach

User A Chain ←→ User B Chain ←→ User C Chain
      ↓              ↓              ↓
   Own data      Own data       Own data
   Own history   Own history    Own history
      ↓              ↓              ↓
         Cross-referenced via Master Ledger

Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                     USER BLOCKCHAIN NETWORK                         │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌─────────────────────────────────────────────────────────────┐  │
│  │                      MASTER LEDGER                           │  │
│  │  ┌─────────────────────────────────────────────────────┐   │  │
│  │  │ Plant Index: plantId → [userA:block5, userB:block12] │   │  │
│  │  │ Lineage Index: parentId → [childId1, childId2...]    │   │  │
│  │  │ Transport Index: batchId → [events...]               │   │  │
│  │  │ User Directory: userId → publicKey, chainHash        │   │  │
│  │  └─────────────────────────────────────────────────────┘   │  │
│  └─────────────────────────────────────────────────────────────┘  │
│                              ↑                                      │
│              ┌───────────────┼───────────────┐                     │
│              ▼               ▼               ▼                     │
│  ┌───────────────┐  ┌───────────────┐  ┌───────────────┐         │
│  │  USER A CHAIN │  │  USER B CHAIN │  │  USER C CHAIN │         │
│  ├───────────────┤  ├───────────────┤  ├───────────────┤         │
│  │ Block 0: Gen  │  │ Block 0: Gen  │  │ Block 0: Gen  │         │
│  │ Block 1: Reg  │  │ Block 1: Acq  │  │ Block 1: Reg  │         │
│  │ Block 2: Grow │  │ Block 2: Plant│  │ Block 2: Clone│         │
│  │ Block 3: Harv │  │ Block 3: Grow │  │ Block 3: Trans│         │
│  │ Block 4: Send │  │ Block 4: Recv │  │ Block 4: ...  │         │
│  │ ...           │  │ ...           │  │ ...           │         │
│  └───────────────┘  └───────────────┘  └───────────────┘         │
│        ↓                   ↓                   ↓                   │
│        └───────────────────┼───────────────────┘                   │
│                            ▼                                        │
│                  ┌───────────────────┐                             │
│                  │ CROSS-CHAIN REFS  │                             │
│                  │ Plant P in A:3    │                             │
│                  │ received by B:4   │                             │
│                  │ cloned to C:2     │                             │
│                  └───────────────────┘                             │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Block Types

Plant Registration Block

interface PlantBlock {
  index: number;
  timestamp: string;
  blockType: 'plant_registration';

  plant: {
    id: string;
    commonName: string;
    scientificName: string;
    propagationType: 'original' | 'seed' | 'clone' | 'cutting';
    generation: number;
    parentPlantId?: string;  // Cross-chain reference
    location: PlantLocation;
    owner: PlantOwner;
    childPlants: string[];
  };

  previousHash: string;
  hash: string;
  nonce: number;
}

Transport Event Block

interface TransportBlock {
  index: number;
  timestamp: string;
  blockType: 'transport_event';

  transportEvent: {
    eventType: TransportEventType;
    fromLocation: TransportLocation;
    toLocation: TransportLocation;
    plantIds?: string[];
    batchIds?: string[];
    carbonFootprintKg: number;
    senderId: string;  // Cross-chain reference
    receiverId: string;  // Cross-chain reference
  };

  previousHash: string;
  hash: string;
  nonce: number;
}

Environment Update Block

interface EnvironmentBlock {
  index: number;
  timestamp: string;
  blockType: 'environment_update';

  environment: {
    plantId: string;
    readings: GrowingEnvironment;
    healthScore: number;
    alerts: EnvironmentAlert[];
  };

  previousHash: string;
  hash: string;
  nonce: number;
}

Cross-Chain References

When plants move between users, cross-chain references maintain lineage:

User A's Chain:                    User B's Chain:
┌────────────────────┐             ┌────────────────────┐
│ Block 5            │             │ Block 12           │
│ Type: Send Plant   │────────────→│ Type: Receive Plant│
│ PlantId: tomato-1  │             │ PlantId: tomato-1  │
│ To: UserB          │             │ From: UserA        │
│ ToBlock: pending   │←────────────│ FromBlock: A:5     │
└────────────────────┘             └────────────────────┘

After confirmation:
Block 5.ToBlock = "B:12"  // Updated with cross-reference

Chain Synchronization

Local-First Operation

1. User creates block locally
2. Block is mined (proof-of-work)
3. Block added to local chain
4. Sync to master ledger index
5. Cross-references updated

Conflict Resolution

If chain fork detected:
1. Longer chain wins (most work)
2. Orphaned blocks flagged
3. Cross-references updated
4. Users notified of conflicts

Privacy Model

Default Privacy

  • Location can be fuzzy (city-level)
  • Owner name can be pseudonymous
  • Wallet addresses are pseudonymous

Enhanced Privacy (Tor)

  • Onion routing for chain sync
  • Hidden service for API access
  • No IP logging
  • Anonymous registration

Public Data

  • Plant species/variety
  • Lineage relationships
  • Transport events (anonymized)
  • Environmental data (aggregated)

Verification

Single Chain Verification

function verifyChain(chain: Block[]): boolean {
  for (let i = 1; i < chain.length; i++) {
    const current = chain[i];
    const previous = chain[i - 1];

    // Verify hash
    if (current.hash !== calculateHash(current)) {
      return false;
    }

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

    // Verify proof-of-work
    if (!current.hash.startsWith('0'.repeat(difficulty))) {
      return false;
    }
  }
  return true;
}

Cross-Chain Verification

function verifyCrossReference(
  senderChain: Block[],
  receiverChain: Block[],
  reference: CrossReference
): boolean {
  const senderBlock = senderChain[reference.senderBlockIndex];
  const receiverBlock = receiverChain[reference.receiverBlockIndex];

  // Verify matching plant/batch IDs
  if (senderBlock.plantId !== receiverBlock.plantId) {
    return false;
  }

  // Verify timestamps (receiver after sender)
  if (new Date(receiverBlock.timestamp) < new Date(senderBlock.timestamp)) {
    return false;
  }

  // Verify signatures
  if (!verifySignature(senderBlock, senderPublicKey)) {
    return false;
  }

  return true;
}

Querying the Network

Find Plant History

// Query across all user chains
const history = masterLedger.queryPlantHistory(plantId);

// Returns:
{
  plantId: 'tomato-123',
  currentOwner: 'userC',
  registeredBy: 'userA',
  generation: 2,
  history: [
    { user: 'userA', block: 1, event: 'registered', date: '2025-01-01' },
    { user: 'userA', block: 5, event: 'cloned', date: '2025-02-15' },
    { user: 'userB', block: 12, event: 'received', date: '2025-02-16' },
    { user: 'userB', block: 20, event: 'grew', date: '2025-03-01' },
    { user: 'userC', block: 8, event: 'received', date: '2025-03-15' },
  ]
}

Find Lineage

const lineage = masterLedger.queryLineage(plantId, generations: 5);

// Returns tree structure
{
  plant: 'tomato-123',
  generation: 2,
  ancestors: [
    { plant: 'tomato-orig', generation: 0, owner: 'userA' },
    { plant: 'tomato-clone1', generation: 1, owner: 'userA' }
  ],
  descendants: [
    { plant: 'tomato-123-seed1', generation: 3, owner: 'userD' },
    { plant: 'tomato-123-seed2', generation: 3, owner: 'userE' }
  ],
  siblings: [
    { plant: 'tomato-clone2', generation: 2, owner: 'userF' }
  ]
}

Data Storage

Local Storage

Each user stores their chain locally:

~/.localgreenchain/
├── chain.json           # Main blockchain
├── transport-chain.json # Transport events
├── keys/
│   ├── private.key      # User's private key
│   └── public.key       # User's public key
└── cache/
    └── master-index.json # Cached master ledger

Cloud Sync (Optional)

User Chain → Encrypted → Cloud Backup
              ↓
         Only user can decrypt
         Master ledger has index only

Performance Considerations

Block Size

  • Target: < 10KB per block
  • Compression for large data
  • Images stored as references

Mining Difficulty

  • Adjustable per chain
  • Lower for personal use (difficulty: 2)
  • Higher for shared chains (difficulty: 4)

Sync Frequency

  • Real-time for active users
  • Batch sync for inactive users
  • Prioritize cross-references

Security Measures

Against Tampering

  • Hash chains prevent modification
  • Cross-references create witnesses
  • Master ledger provides redundancy

Against Sybil Attacks

  • Proof-of-work makes spam expensive
  • Reputation system for users
  • Rate limiting on registrations

Against Privacy Leaks

  • Minimal data in master ledger
  • Tor integration optional
  • User controls visibility