Skip to content

feat: Add Proof of Work implementation for v2#4

Merged
Perafan18 merged 3 commits intomasterfrom
feature/v2-proof-of-work
Nov 9, 2025
Merged

feat: Add Proof of Work implementation for v2#4
Perafan18 merged 3 commits intomasterfrom
feature/v2-proof-of-work

Conversation

@Perafan18
Copy link
Owner

@Perafan18 Perafan18 commented Nov 9, 2025

Summary

  • Implements Proof of Work (PoW) mining algorithm for blocks
  • Adds nonce and difficulty fields to Block model
  • Implements mine_block method that finds valid hash with required leading zeros
  • Updates block creation to mine blocks before saving
  • Adds validation to check PoW difficulty requirement
  • Adds GET endpoint to retrieve block details including mining information

Technical Details

  • Mining Algorithm: Increments nonce until hash starts with required number of zeros
  • Default Difficulty: 2 (requires 2 leading zeros in hash)
  • Configurable: Difficulty can be specified when creating blocks
  • Validation: valid_hash? method checks if hash meets difficulty requirement
  • Blockchain Integrity: Updated to validate PoW for all blocks

API Changes

  • POST /chain/:id/block: Now accepts optional difficulty parameter and returns nonce and difficulty in response
  • GET /chain/:id/block/:block_id: New endpoint to retrieve complete block details including mining information

Test plan

  • Test block mining with default difficulty (2)
  • Test block mining with custom difficulty
  • Verify mined blocks have required leading zeros in hash
  • Test blockchain integrity validation with PoW
  • Test GET endpoint for block details
  • Verify nonce increments until valid hash is found

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Nuevas funcionalidades

    • Minado Proof-of-Work integrado con dificultad configurable y campos públicos nonce y dificultad.
    • Nueva API para recuperar bloques individuales por identificador; respuestas incluyen datos completos del bloque (hash, nonce, dificultad, timestamp, etc.).
  • Mejoras

    • Validación de integridad reforzada y respuesta de creación de bloque ampliada con nonce y dificultad.

- Add nonce and difficulty fields to Block model
- Implement mine_block method with PoW algorithm
- Update calculate_hash to include nonce
- Add valid_hash? method to verify difficulty requirement
- Update Blockchain.add_block to mine blocks
- Update integrity_valid? to check PoW validity
- Add GET endpoint for block details with mining info
- Add optional difficulty parameter to block creation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai
Copy link

coderabbitai bot commented Nov 9, 2025

Walkthrough

Se introduce Proof-of-Work: Block ahora tiene campos nonce y difficulty, incluye minería (mine_block) y validación de hash (valid_hash?). Blockchain#add_block acepta difficulty: y mina antes de guardar. API: POST /chain/:id/block devuelve nonce y difficulty; añadido GET /chain/:id/block/:block_id.

Cambios

Cohort / File(s) Resumen
API / Aplicación
main.rb
Añadido endpoint GET '/chain/:id/block/:block_id' para recuperar un bloque completo. POST '/chain/:id/block' ahora valida difficulty, invoca blockchain.add_block(..., difficulty: difficulty) y devuelve block_hash, nonce y difficulty. Añadido helper validate_difficulty.
Modelo: Block
src/block.rb
Añadidos campos públicos nonce (Integer, default 0) y difficulty (Integer, default 2). calculate_hash incorpora nonce. Nuevo método mine_block que itera nonce hasta cumplir la dificultad; nuevo método valid_hash? para verificar el hash contra la dificultad. Validaciones actualizadas.
Modelo: Blockchain
src/blockchain.rb
Firma de add_block cambiada a add_block(data, difficulty: 2). Construye bloque con difficulty, llama mine_block, guarda (save!) y retorna. integrity_valid? ahora incluye comprobación current_block.valid_hash?.

Diagramas de Secuencia

sequenceDiagram
    participant Cliente
    participant App as main.rb
    participant Blockchain
    participant Block

    Cliente->>App: POST /chain/:id/block (data, difficulty)
    App->>App: validate_difficulty(difficulty)
    App->>Blockchain: add_block(data, difficulty)
    Blockchain->>Block: build new block(data, difficulty)
    Block-->Block: nonce = 0
    Blockchain->>Block: mine_block()
    loop Minado (PoW)
        Block->>Block: incrementar nonce
        Block->>Block: calcular hash
        alt hash cumple dificultad
            Block-->>Blockchain: hash minado
        end
    end
    Blockchain->>Blockchain: save! block
    Blockchain-->>App: bloque creado
    App-->>Cliente: { block_hash, nonce, difficulty }

    Cliente->>App: GET /chain/:id/block/:block_id
    App->>Blockchain: find_block(block_id)
    Blockchain-->>App: bloque
    App->>Block: valid_hash?
    Block-->>App: true/false
    App-->>Cliente: { id, index, data, hash, previous_hash, nonce, difficulty, timestamp, valid_hash }
Loading

Esfuerzo estimado de revisión de código

🎯 4 (Complejo) | ⏱️ ~45 minutos

  • Revisar comportamiento de mine_block por riesgo de bucles largos/infinitos si difficulty es alto.
  • Comprobar que calculate_hash y valid_hash? usan exactamente los mismos campos (consistencia).
  • Verificar migración de add_block en llamadas existentes y manejo de errores en validate_difficulty.
  • Asegurar que respuestas JSON y tests (si existen) se actualizan para los nuevos campos nonce y difficulty.

Poema

🐰 Con patas blandas y ojos curiosos,
cuento nonces que saltan y giran en paz,
la cadena late en ritmos laboriosos,
ceros al frente: el misterio verás.
¡Minería y canto, un bloque más!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed El título describe con precisión la característica principal del cambio: la implementación de Proof of Work (PoW) para la versión 2, que es el objetivo central del PR.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/v2-proof-of-work

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1e49e45 and 0335861.

📒 Files selected for processing (1)
  • main.rb (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • main.rb

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Resolved conflict in main.rb by keeping PoW implementation with difficulty parameter
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59c87f0 and 1e49e45.

📒 Files selected for processing (3)
  • main.rb (2 hunks)
  • src/block.rb (2 hunks)
  • src/blockchain.rb (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/blockchain.rb (1)
src/block.rb (3)
  • mine_block (60-69)
  • calculate_hash (43-46)
  • valid_hash? (74-77)
main.rb (2)
src/blockchain.rb (1)
  • add_block (22-34)
src/block.rb (1)
  • valid_hash? (74-77)

- Add validate_difficulty helper method
- Convert difficulty to integer and default to 2 if nil
- Reject negative values with 422 status
- Reject values > 10 to prevent excessive mining time
- Prevents TypeError from string/float inputs

Addresses CodeRabbit security review comment
@Perafan18 Perafan18 merged commit e137378 into master Nov 9, 2025
2 checks passed
@Perafan18 Perafan18 deleted the feature/v2-proof-of-work branch November 9, 2025 21:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant