Skip to main content

Chapter 11: Blockchain Attributes and Data Integrity

Overview

Vektagraf's blockchain attributes feature provides immutability, cryptographic integrity, and verifiability constraints at the field, model, and database levels. This chapter explores how to leverage blockchain-like functionality within traditional database operations to ensure data integrity, compliance, and auditability.

Learning Objectives

By the end of this chapter, you will understand:

  • Core blockchain attribute types and their applications
  • How to configure blockchain attributes in schemas
  • Cryptographic integrity and verification mechanisms
  • Hash chain implementation for audit trails
  • Performance considerations and optimization strategies
  • Real-world use cases and implementation patterns

When to Use Blockchain Attributes

Blockchain attributes are ideal for scenarios requiring:

  • Financial Systems: Transaction immutability and audit trails
  • Compliance: Regulatory requirements for data integrity
  • Supply Chain: Traceability and authenticity verification
  • Healthcare: Patient record integrity and HIPAA compliance
  • Legal: Evidence preservation and chain of custody
  • Audit Systems: Tamper-proof logging and reporting

Core Concepts

Blockchain Attribute Types

Vektagraf provides four primary blockchain attribute types:

Read Only

Prevents write operations on fields or models based on conditions.

{
  "status": {
    "type": "string",
    "blockchain": {
      "attributes": ["readOnly"],
      "conditions": ["status == 'finalized'"]
    }
  }
}

Use Cases:

  • Finalized documents that shouldn't be modified
  • Archived records with retention policies
  • Status-dependent write protection

Immutable

Prevents modifications after initial creation.

{
  "transaction_id": {
    "type": "string",
    "blockchain": {
      "attributes": ["immutable"]
    }
  }
}

Use Cases:

  • Unique identifiers and reference numbers
  • Creation timestamps and audit metadata
  • Critical business data that must never change

Signed

Automatically generates cryptographic signatures for field values.

{
  "amount": {
    "type": "float64",
    "blockchain": {
      "attributes": ["signed"],
      "signature": {
        "algorithm": "ed25519",
        "key_source": "system"
      }
    }
  }
}

Use Cases:

  • Financial amounts and balances
  • Sensitive personal information
  • Critical business decisions and approvals

Verifiable

Enables cryptographic verification and merkle tree generation.

{
  "models": {
    "audit_record": {
      "id": "id",
      "data": "string",
      "$meta": {
        "blockchain": {
          "attributes": ["verifiable"],
          "verification": {
            "level": "full",
            "merkle_tree": true
          }
        }
      }
    }
  }
}

Use Cases:

  • Complete audit trails
  • Batch verification of large datasets
  • External verification requirements

Cryptographic Foundations

Signature Algorithms

Vektagraf supports multiple cryptographic algorithms:

AlgorithmKey SizeSecurity LevelPerformanceUse Case
ed25519256-bitHighFastGeneral purpose
rsa2048-bitHighMediumLegacy compatibility
ecdsa256-bitHighFastStandards compliance

Hash Algorithms

For hash chains and integrity verification:

AlgorithmOutput SizeSecurity LevelPerformance
sha256256-bitHighFast
sha512512-bitVery HighMedium
blake2b512-bitVery HighFast

Hash Chains

{
  "$meta": {
    "blockchain": {
      "hash_chain": {
        "enabled": true,
        "algorithm": "sha256"
      }
    }
  }
}

Each record includes:

  • Current Hash: Hash of the current record's data
  • Previous Hash: Hash of the previous record in the chain
  • Sequence Number: Position in the chain
  • Timestamp: When the record was created

Practical Examples

Example 1: Financial Transaction System

Let's build a financial transaction system with complete blockchain integrity:

Schema Definition

{
  "$meta": {
    "description": "Financial system with blockchain integrity",
    "blockchain": {
      "global_attributes": ["verifiable"],
      "cryptographic_provider": "default"
    }
  },
  "models": {
    "account": {
      "id": "id",
      "account_number": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable", "signed"]
        }
      },
      "balance": {
        "type": "float64",
        "blockchain": {
          "attributes": ["signed"],
          "conditions": ["balance >= 0"]
        }
      },
      "status": {
        "type": "string",
        "blockchain": {
          "attributes": ["readOnly"],
          "conditions": ["status == 'frozen'"]
        }
      }
    },
    "transaction": {
      "id": "id",
      "amount": {
        "type": "float64",
        "blockchain": {
          "attributes": ["immutable", "signed"]
        }
      },
      "from_account": {
        "type": "@account",
        "blockchain": {
          "attributes": ["immutable"]
        }
      },
      "to_account": {
        "type": "@account",
        "blockchain": {
          "attributes": ["immutable"]
        }
      },
      "$meta": {
        "blockchain": {
          "attributes": ["verifiable"],
          "hash_chain": {
            "enabled": true,
            "algorithm": "sha256"
          }
        }
      }
    }
  }
}

Implementation

class FinancialSystem {
  final VektagrafDatabase database;
  
  FinancialSystem(this.database);
  
  /// Create a transaction with blockchain integrity
  Future<String> createTransaction({
    required String fromAccountId,
    required String toAccountId,
    required double amount,
  }) async {
    // Validate accounts and balances
    final fromAccount = await database.get('account', fromAccountId);
    final toAccount = await database.get('account', toAccountId);
    
    if (fromAccount['balance'] < amount) {
      throw InsufficientFundsException();
    }
    
    // Create transaction (automatically signed and chained)
    final transaction = await database.create('transaction', {
      'amount': amount,
      'from_account': fromAccountId,
      'to_account': toAccountId,
      'timestamp': DateTime.now(),
    });
    
    // Update balances (signatures automatically generated)
    await database.update('account', fromAccountId, {
      'balance': fromAccount['balance'] - amount,
    });
    
    await database.update('account', toAccountId, {
      'balance': toAccount['balance'] + amount,
    });
    
    return transaction.id;
  }
  
  /// Verify transaction integrity
  Future<bool> verifyTransaction(String transactionId) async {
    // Verify signatures
    final signatureResult = await database.verifySignatures(
      collection: 'transaction',
      recordId: transactionId,
      fields: ['amount'],
    );
    
    // Verify hash chain
    final chainResult = await database.verifyHashChain(
      collection: 'transaction',
      recordId: transactionId,
    );
    
    return signatureResult.isValid && chainResult.isValid;
  }
}

Example 2: Supply Chain Tracking

Schema Definition

{
  "models": {
    "shipment": {
      "id": "id",
      "tracking_number": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable", "signed"]
        }
      },
      "product_id": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable"]
        }
      },
      "origin": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable"]
        }
      },
      "destination": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable"]
        }
      },
      "$meta": {
        "blockchain": {
          "attributes": ["verifiable"],
          "hash_chain": {
            "enabled": true
          }
        }
      }
    },
    "tracking_event": {
      "id": "id",
      "shipment": {
        "type": "@shipment",
        "blockchain": {
          "attributes": ["immutable"]
        }
      },
      "location": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable", "signed"]
        }
      },
      "timestamp": {
        "type": "datetime",
        "blockchain": {
          "attributes": ["immutable", "signed"]
        }
      },
      "$meta": {
        "blockchain": {
          "attributes": ["verifiable"],
          "hash_chain": {
            "enabled": true
          }
        }
      }
    }
  }
}

Implementation

class SupplyChainTracker {
  final VektagrafDatabase database;
  
  SupplyChainTracker(this.database);
  
  /// Add tracking event
  Future<void> addTrackingEvent({
    required String shipmentId,
    required String location,
  }) async {
    // Create immutable tracking event
    await database.create('tracking_event', {
      'shipment': shipmentId,
      'location': location,
      'timestamp': DateTime.now(),
    });
  }
  
  /// Get complete tracking history with verification
  Future<TrackingHistory> getTrackingHistory(String shipmentId) async {
    final events = await database.query('tracking_event')
      .where('shipment == ?', [shipmentId])
      .orderBy('timestamp')
      .includeVerificationStatus()
      .execute();
    
    // Verify chain integrity
    final chainIntegrity = await database.verifyHashChain(
      collection: 'tracking_event',
      filter: {'shipment': shipmentId},
    );
    
    return TrackingHistory(
      events: events,
      chainIntegrity: chainIntegrity,
    );
  }
  
  /// Generate supply chain certificate
  Future<Certificate> generateCertificate(String shipmentId) async {
    final history = await getTrackingHistory(shipmentId);
    
    // Generate cryptographic proof
    final proof = await database.generateIntegrityProof(
      collection: 'tracking_event',
      recordIds: history.events.map((e) => e.id).toList(),
    );
    
    return Certificate(
      shipmentId: shipmentId,
      history: history,
      cryptographicProof: proof,
    );
  }
}

Example 3: Compliance Audit System

Schema Definition

{
  "models": {
    "audit_log": {
      "id": "id",
      "user_id": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable", "signed"]
        }
      },
      "action": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable", "signed"]
        }
      },
      "resource": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable", "signed"]
        }
      },
      "data": {
        "type": "<string, dynamic>",
        "blockchain": {
          "attributes": ["immutable", "signed"]
        }
      },
      "timestamp": {
        "type": "datetime",
        "blockchain": {
          "attributes": ["immutable"]
        }
      },
      "$meta": {
        "blockchain": {
          "attributes": ["verifiable", "readOnly"],
          "hash_chain": {
            "enabled": true
          },
          "verification": {
            "level": "full",
            "merkle_tree": true
          }
        }
      }
    }
  }
}

Implementation

class ComplianceAuditSystem {
  final VektagrafDatabase database;
  
  ComplianceAuditSystem(this.database);
  
  /// Log user action (immutable)
  Future<void> logAction({
    required String userId,
    required String action,
    required String resource,
    required Map<String, dynamic> data,
  }) async {
    await database.create('audit_log', {
      'user_id': userId,
      'action': action,
      'resource': resource,
      'data': data,
      'timestamp': DateTime.now(),
    });
  }
  
  /// Verify audit integrity
  Future<AuditIntegrityResult> verifyAuditIntegrity({
    DateTime? startDate,
    DateTime? endDate,
  }) async {
    // Get audit logs in range
    var query = database.query('audit_log');
    if (startDate != null && endDate != null) {
      query = query.where('timestamp >= ? AND timestamp <= ?', 
                         [startDate, endDate]);
    }
    
    final auditLogs = await query.execute();
    
    // Verify hash chain
    final chainVerification = await database.verifyHashChain(
      collection: 'audit_log',
      startDate: startDate,
      endDate: endDate,
    );
    
    // Verify signatures
    final signatureFailures = <String>[];
    for (final log in auditLogs) {
      final verification = await database.verifySignatures(
        collection: 'audit_log',
        recordId: log.id,
        fields: ['user_id', 'action', 'resource', 'data'],
      );
      
      if (!verification.isValid) {
        signatureFailures.add(log.id);
      }
    }
    
    return AuditIntegrityResult(
      chainIntegrity: chainVerification.isValid,
      signatureFailures: signatureFailures,
      totalRecords: auditLogs.length,
    );
  }
  
  /// Generate compliance report
  Future<ComplianceReport> generateReport({
    required DateTime startDate,
    required DateTime endDate,
  }) async {
    final auditLogs = await database.query('audit_log')
      .where('timestamp >= ? AND timestamp <= ?', [startDate, endDate])
      .execute();
    
    // Generate cryptographic proof
    final proof = await database.generateIntegrityProof(
      collection: 'audit_log',
      recordIds: auditLogs.map((log) => log.id).toList(),
    );
    
    return ComplianceReport(
      auditLogs: auditLogs,
      integrityProof: proof,
      generatedAt: DateTime.now(),
    );
  }
}

Advanced Topics

Multi-Level Attribute Configuration

Blockchain attributes can be configured at multiple levels with inheritance:

Database Level

{
  "$meta": {
    "blockchain": {
      "global_attributes": ["verifiable"],
      "cryptographic_provider": "default",
      "performance": {
        "lazy_verification": true,
        "cache_verification": true
      }
    }
  }
}

Model Level

{
  "models": {
    "sensitive_model": {
      "$meta": {
        "blockchain": {
          "attributes": ["verifiable", "immutable"],
          "hash_chain": {
            "enabled": true
          }
        }
      }
    }
  }
}

Field Level

{
  "critical_field": {
    "type": "string",
    "blockchain": {
      "attributes": ["immutable", "signed"],
      "signature": {
        "algorithm": "ed25519"
      }
    }
  }
}

Conditional Blockchain Attributes

Attributes can be applied conditionally based on field values or external conditions:

{
  "status": {
    "type": "string",
    "blockchain": {
      "attributes": ["readOnly"],
      "conditions": [
        "status == 'finalized'",
        "created_at < now() - interval '30 days'"
      ]
    }
  }
}

Custom Cryptographic Providers

Implement custom cryptographic providers for specific requirements:

class CustomCryptographicProvider implements CryptographicProvider {
  @override
  Future<String> generateSignature(Uint8List data, String keyId) async {
    // Custom signature implementation
    // Could integrate with HSMs, external key services, etc.
  }
  
  @override
  Future<bool> verifySignature(
    Uint8List data, 
    String signature, 
    String keyId
  ) async {
    // Custom verification implementation
  }
  
  // ... other methods
}

// Register custom provider
await database.registerCryptographicProvider(
  'custom',
  CustomCryptographicProvider(),
);

Batch Operations and Performance

For large datasets, use batch operations:

// Batch signature generation
final signatures = await database.batchGenerateSignatures(
  dataList: [data1, data2, data3],
  keyId: 'system_key',
);

// Batch verification
final results = await database.batchVerifyIntegrity(
  recordIds: ['id1', 'id2', 'id3'],
  verificationLevel: VerificationLevel.basic,
);

External Verification

Export cryptographic proofs for external verification:

// Generate standalone proof
final proof = await database.generateIntegrityProof(
  collection: 'audit_log',
  recordIds: recordIds,
  format: ProofFormat.json,
);

// Export for external verification
await exportProof(proof, 'audit_proof.json');

// External verification (without database access)
final isValid = await verifyProofStandalone(
  proofFile: 'audit_proof.json',
  publicKey: 'verification_key.pem',
);

Best Practices

Security Best Practices

  1. Use Strong Algorithms

    • Prefer Ed25519 for signatures
    • Use SHA-256 or higher for hashing
    • Regularly rotate cryptographic keys
  2. Key Management

    • Implement proper key rotation policies
    • Use hardware security modules (HSMs) for critical keys
    • Maintain secure key backup and recovery procedures
  3. Access Control

    • Combine blockchain attributes with proper authentication
    • Implement role-based access to verification functions
    • Audit all cryptographic operations

Performance Best Practices

  1. Lazy Verification

    {
      "$meta": {
        "blockchain": {
          "performance": {
            "lazy_verification": true,
            "verification_cache_ttl": 3600
          }
        }
      }
    }
    
  2. Batch Operations

    • Use batch verification for large datasets
    • Group cryptographic operations when possible
    • Implement asynchronous processing for non-critical operations
  3. Caching

    • Cache verification results for frequently accessed data
    • Use merkle trees for efficient batch verification
    • Implement intelligent cache invalidation

Compliance Best Practices

  1. Documentation

    • Document all blockchain configurations
    • Maintain audit trails of configuration changes
    • Keep records of key rotation and management
  2. Testing

    • Regular integrity verification audits
    • Test disaster recovery procedures
    • Validate external verification processes
  3. Monitoring

    • Set up alerts for integrity violations
    • Monitor performance impact of blockchain operations
    • Track verification success rates

Error Handling

Common Exceptions

ImmutabilityViolationException

try {
  await database.update('model', 'id', {'immutable_field': 'new_value'});
} catch (ImmutabilityViolationException e) {
  print('Cannot modify immutable field: ${e.fieldName}');
  // Handle immutability violation
}

SignatureVerificationException

try {
  final record = await database.get('signed_model', 'id');
} catch (SignatureVerificationException e) {
  print('Signature verification failed: ${e.message}');
  // Handle signature failure - possible tampering
}

HashChainIntegrityException

try {
  await database.verifyHashChain('blockchain_model');
} catch (HashChainIntegrityException e) {
  print('Hash chain broken at sequence ${e.sequenceNumber}');
  // Handle chain integrity failure
}

Error Recovery

// Graceful degradation configuration
final config = BlockchainConfig(
  gracefulDegradation: true,
  fallbackVerification: VerificationLevel.basic,
  alertOnFailure: true,
);

// Automatic recovery for corrupted chains
await database.repairHashChain(
  collection: 'audit_record',
  fromSequence: 100,
  recoveryMode: RecoveryMode.automatic,
);

Migration and Deployment

Adding Blockchain Attributes to Existing Schemas

  1. Backup Data

    vektagraf backup --database production --output backup.vkg
    
  2. Update Schema

    {
      "existing_field": {
        "type": "string",
        "blockchain": {
          "attributes": ["immutable"]
        }
      }
    }
    
  3. Migrate Data

    await database.migrateToBlockchain(
      collection: 'existing_model',
      attributes: {BlockchainAttributeType.immutable},
      backfillSignatures: true,
    );
    
  4. Verify Migration

    final result = await database.verifyMigration('existing_model');
    if (!result.success) {
      throw Exception('Migration failed: ${result.errors}');
    }
    

Performance Impact Assessment

Monitor performance impact during deployment:

// Before enabling blockchain attributes
final beforeMetrics = await database.getPerformanceMetrics();

// Enable blockchain attributes
await database.enableBlockchainAttributes(config);

// After enabling - compare performance
final afterMetrics = await database.getPerformanceMetrics();
final impact = calculatePerformanceImpact(beforeMetrics, afterMetrics);

Integration Patterns

With Existing Security Systems

// Integration with external authentication
class IntegratedBlockchainSystem {
  final AuthenticationService auth;
  final VektagrafDatabase database;
  
  Future<void> createSignedRecord(
    String userId,
    Map<String, dynamic> data,
  ) async {
    // Verify user permissions
    await auth.verifyPermissions(userId, 'create_signed_record');
    
    // Create record with user-specific signing
    await database.create('signed_model', {
      ...data,
      'created_by': userId,
      'signature_key_id': await auth.getUserSigningKey(userId),
    });
  }
}

With External Blockchain Networks

// Bridge to external blockchain
class BlockchainBridge {
  final EthereumClient ethereum;
  final VektagrafDatabase database;
  
  Future<void> anchorToBlockchain(String recordId) async {
    // Get record hash from Vektagraf
    final recordHash = await database.getRecordHash(recordId);
    
    // Submit to external blockchain
    final txHash = await ethereum.submitHash(recordHash);
    
    // Store blockchain reference
    await database.update('record', recordId, {
      'blockchain_anchor': {
        'network': 'ethereum',
        'transaction_hash': txHash,
        'block_number': await ethereum.getBlockNumber(),
      }
    });
  }
}

Use Case Patterns

Financial Services Pattern

class FinancialServicesPattern {
  // Immutable transaction records
  // Signed amounts and account numbers
  // Hash-chained audit trail
  // Regulatory compliance reporting
  // External audit verification
}

Healthcare Pattern

class HealthcarePattern {
  // Immutable patient identifiers
  // Signed medical records
  // HIPAA-compliant audit logs
  // Chain of custody tracking
  // Legal evidence preservation
}

Supply Chain Pattern

class SupplyChainPattern {
  // Immutable product identifiers
  // Signed location and timestamp data
  // End-to-end traceability
  // Authenticity certificates
  // Regulatory compliance tracking
}

Summary

Blockchain attributes in Vektagraf provide powerful data integrity and auditability features:

Key Takeaways

  1. Four Attribute Types: READ_ONLY, IMMUTABLE, SIGNED, and VERIFIABLE provide different levels of protection
  2. Cryptographic Security: Strong algorithms ensure data integrity and authenticity
  3. Hash Chains: Provide chronological integrity and tamper detection
  4. Performance Optimization: Lazy verification and caching minimize performance impact
  5. Compliance Ready: Built-in features support regulatory requirements
  6. External Verification: Cryptographic proofs enable independent verification

Next Steps

Additional Resources


This chapter provides comprehensive coverage of Vektagraf's blockchain attributes. For specific implementation guidance, refer to the practical examples and API documentation.