A lightweight blockchain implementation written in Swift using the Vapor framework. This project demonstrates the core concepts of blockchain technology including mining, transactions, and consensus mechanisms.
This repository implements a blockchain with the following features:
- Proof of Work algorithm
- Transaction validation
- Consensus mechanism for distributed nodes
- RESTful API for interaction
This implementation is inspired by the concepts outlined in the article Learn Blockchains by Building One by Daniel van Flymen, adapted to Swift and the Vapor framework.
- Swift 5.8+
- macOS or Linux
swift buildswift runThe blockchain server will start on port 8080 by default.
You can interact with the blockchain API using cURL, Postman, or any HTTP client.
curl http://localhost:8080/chaincurl http://localhost:8080/minecurl -X POST -H "Content-Type: application/json" -d '{
"sender": "sender-address",
"recipient": "recipient-address",
"amount": 5
}' http://localhost:8080/transactions/newcurl -X POST -H "Content-Type: application/json" -d '{
"nodes": ["http://localhost:8081"]
}' http://localhost:8080/nodes/registercurl http://localhost:8080/nodes/resolveTo test the consensus mechanism, you need to run multiple nodes on different ports:
Modify the port configuration in configure.swift for the second node:
// In the second node's configure.swift
app.http.server.configuration.port = 8081Run the second node:
swift run --working-directory /path/to/second/nodeRegister the second node with the first node:
curl -X POST -H "Content-Type: application/json" -d '{
"nodes": ["http://localhost:8081"]
}' http://localhost:8080/nodes/registerRegister the first node with the second node:
curl -X POST -H "Content-Type: application/json" -d '{
"nodes": ["http://localhost:8080"]
}' http://localhost:8081/nodes/registerMine a few blocks on the first node:
curl http://localhost:8080/mine
curl http://localhost:8080/mineThen invoke the consensus mechanism on the second node:
curl http://localhost:8081/nodes/resolveThis will synchronize node 2 with node 1, accepting the longer chain from node 1.
Author: Bo-Hsun Hsu
Email: bohsunhsu@gmail.com
This project is available under the MIT License.