✨ Enhance blockchain
This commit is contained in:
18
SwiftChainCore/Models/Account.swift
Normal file
18
SwiftChainCore/Models/Account.swift
Normal file
@@ -0,0 +1,18 @@
|
||||
//
|
||||
// File.swift
|
||||
//
|
||||
//
|
||||
// Created by Victor BODINAUD on 31/03/2021.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public class Account {
|
||||
var id: String
|
||||
var balance: Int
|
||||
|
||||
init(id: String, balance: Int) {
|
||||
self.id = id
|
||||
self.balance = balance
|
||||
}
|
||||
}
|
||||
66
SwiftChainCore/Models/AccountManager.swift
Normal file
66
SwiftChainCore/Models/AccountManager.swift
Normal file
@@ -0,0 +1,66 @@
|
||||
//
|
||||
// AccountManager.swift
|
||||
// SwiftChain
|
||||
//
|
||||
// Created by Victor on 27/11/2024.
|
||||
//
|
||||
|
||||
public class AccountManager {
|
||||
private var accounts: [String: Account] = [:]
|
||||
private let miningReward = 50
|
||||
|
||||
func getAccount(_ address: String) -> Account {
|
||||
if let account = accounts[address] {
|
||||
return account
|
||||
}
|
||||
let newAccount = Account(id: address, balance: 0)
|
||||
accounts[address] = newAccount
|
||||
return newAccount
|
||||
}
|
||||
|
||||
func canProcessTransaction(_ transaction: Transaction) -> Bool {
|
||||
if transaction.type == "MINING_REWARD" {
|
||||
return true
|
||||
}
|
||||
|
||||
let senderAccount = getAccount(transaction.sender)
|
||||
return senderAccount.balance >= transaction.amount
|
||||
}
|
||||
|
||||
func processTransaction(_ transaction: Transaction) -> Bool {
|
||||
if !canProcessTransaction(transaction) {
|
||||
return false
|
||||
}
|
||||
|
||||
if transaction.type == "MINING_REWARD" {
|
||||
let minerAccount = getAccount(transaction.receiver)
|
||||
minerAccount.balance += miningReward
|
||||
return true
|
||||
}
|
||||
|
||||
let senderAccount = getAccount(transaction.sender)
|
||||
let receiverAccount = getAccount(transaction.receiver)
|
||||
|
||||
senderAccount.balance -= transaction.amount
|
||||
receiverAccount.balance += transaction.amount
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func getBalance(_ address: String) -> Int {
|
||||
return getAccount(address).balance
|
||||
}
|
||||
|
||||
func processBlock(_ block: Block) -> Bool {
|
||||
let tempAccounts = accounts
|
||||
|
||||
for transaction in block.transactions {
|
||||
if !processTransaction(transaction) {
|
||||
accounts = tempAccounts
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
116
SwiftChainCore/Models/Block.swift
Normal file
116
SwiftChainCore/Models/Block.swift
Normal file
@@ -0,0 +1,116 @@
|
||||
//
|
||||
// Block.swift
|
||||
// Blockchain
|
||||
//
|
||||
// Created by Victor BODINAUD on 27/02/2020.
|
||||
// Copyright © 2020 Victor BODINAUD. All rights reserved.
|
||||
//
|
||||
|
||||
internal import CryptoSwift
|
||||
import Foundation
|
||||
|
||||
public class Block: Codable {
|
||||
var hash: String
|
||||
var transactions: [Transaction]
|
||||
var previousHash: String
|
||||
var index: Int
|
||||
var nonce: Int
|
||||
var timestamp: Int
|
||||
var difficulty: Int
|
||||
var miner: String?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case hash, transactions, previousHash, index, nonce, timestamp, difficulty, miner
|
||||
}
|
||||
|
||||
init(hash: String = "", transactions: [Transaction] = [], previousHash: String = "",
|
||||
index: Int = 0, nonce: Int = 0, timestamp: Int = 0, difficulty: Int = 4)
|
||||
{
|
||||
self.hash = hash
|
||||
self.transactions = transactions
|
||||
self.previousHash = previousHash
|
||||
self.index = index
|
||||
self.nonce = nonce
|
||||
self.timestamp = timestamp
|
||||
self.difficulty = difficulty
|
||||
}
|
||||
|
||||
func mineBlock() -> Double {
|
||||
let startTime = Date()
|
||||
let target = String(repeating: "0", count: difficulty)
|
||||
|
||||
print("Mining block \(index) with difficulty \(difficulty)...")
|
||||
|
||||
repeat {
|
||||
nonce += 1
|
||||
hash = generateHash()
|
||||
} while !hash.hasPrefix(target)
|
||||
|
||||
let timeElapsed = Date().timeIntervalSince(startTime)
|
||||
print("Block mined! Nonce: \(nonce), Hash: \(hash)")
|
||||
|
||||
return timeElapsed
|
||||
}
|
||||
|
||||
func isValid() -> Bool {
|
||||
// Vérification de base du hash
|
||||
let target = String(repeating: "0", count: difficulty)
|
||||
if hash != generateHash() || !hash.hasPrefix(target) {
|
||||
print("Block \(index): Invalid hash")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier l'index
|
||||
if index < 0 {
|
||||
print("Block: Invalid index")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier le timestamp
|
||||
let currentTime = Int(Date().timeIntervalSince1970)
|
||||
if timestamp > currentTime + 7200 || timestamp < 1701388800 { // 2h dans le futur max
|
||||
print("Block: Invalid timestamp")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier les transactions
|
||||
for transaction in transactions {
|
||||
if !transaction.isValid() {
|
||||
print("Block: Invalid transaction found")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier qu'il n'y a qu'une seule récompense de minage
|
||||
if transaction.type == "MINING_REWARD" {
|
||||
if transactions.filter({ $0.type == "MINING_REWARD" }).count > 1 {
|
||||
print("Block: Multiple mining rewards found")
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func generateHash() -> String {
|
||||
let txData = transactions.map {
|
||||
"\($0.sender)\($0.receiver)\($0.amount)\($0.type)"
|
||||
}.joined()
|
||||
|
||||
return "\(previousHash)\(txData)\(String(timestamp))\(String(index))\(String(nonce))".sha256()
|
||||
}
|
||||
}
|
||||
|
||||
// Structure pour suivre la progression du mining
|
||||
struct MiningProgress {
|
||||
let hashesChecked: Int
|
||||
let hashRate: Double
|
||||
let elapsedTime: TimeInterval
|
||||
let estimatedTimeRemaining: TimeInterval?
|
||||
}
|
||||
|
||||
// Erreurs possibles pendant le mining
|
||||
enum MiningError: Error {
|
||||
case cancelled
|
||||
case failed(String)
|
||||
}
|
||||
127
SwiftChainCore/Models/Blockchain.swift
Normal file
127
SwiftChainCore/Models/Blockchain.swift
Normal file
@@ -0,0 +1,127 @@
|
||||
//
|
||||
// Blockchain.swift
|
||||
// Blockchain
|
||||
//
|
||||
// Created by Victor BODINAUD on 27/02/2020.
|
||||
// Copyright © 2020 Victor BODINAUD. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public class Blockchain {
|
||||
var chain = [Block]()
|
||||
let minDifficulty = 2
|
||||
let maxDifficulty = 6
|
||||
let targetBlockTime = 10.0 // en secondes
|
||||
|
||||
static let genesisBlock: Block = {
|
||||
let block = Block()
|
||||
block.previousHash = "0000genesis0000"
|
||||
block.index = 0
|
||||
block.timestamp = 1701388800
|
||||
block.difficulty = 4
|
||||
block.nonce = 12345
|
||||
block.hash = "000088c1731bed4996680d2c50ea3d9b573c1507d2d61866c0deff33a7f8cf5e"
|
||||
return block
|
||||
}()
|
||||
|
||||
init() {
|
||||
chain.append(Blockchain.genesisBlock)
|
||||
print("Genesis block initialized -- hash: \(Blockchain.genesisBlock.hash)")
|
||||
}
|
||||
|
||||
func calculateNewDifficulty() -> Int {
|
||||
guard chain.count >= 2 else { return minDifficulty }
|
||||
|
||||
let lastBlock = chain.last!
|
||||
let previousBlock = chain[chain.count - 2]
|
||||
let timeSpent = Double(lastBlock.timestamp - previousBlock.timestamp)
|
||||
|
||||
if timeSpent < targetBlockTime / 2 {
|
||||
return min(lastBlock.difficulty + 1, maxDifficulty)
|
||||
} else if timeSpent > targetBlockTime * 2 {
|
||||
return max(lastBlock.difficulty - 1, minDifficulty)
|
||||
}
|
||||
|
||||
return lastBlock.difficulty
|
||||
}
|
||||
|
||||
func validateChain(_ chain: [Block]) -> Bool {
|
||||
guard let firstBlock = chain.first,
|
||||
firstBlock.hash == Blockchain.genesisBlock.hash
|
||||
else {
|
||||
print("Genesis block mismatch")
|
||||
return false
|
||||
}
|
||||
|
||||
for i in 1..<chain.count {
|
||||
let block = chain[i]
|
||||
let previousBlock = chain[i - 1]
|
||||
|
||||
if block.previousHash != previousBlock.hash {
|
||||
print("Invalid chain at block \(i): incorrect previous hash")
|
||||
return false
|
||||
}
|
||||
|
||||
if !block.isValid() {
|
||||
print("Invalid chain at block \(i): invalid block hash")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func validateChainTotally(_ chain: [Block]) -> Bool {
|
||||
// Vérifier le genesis block
|
||||
guard let firstBlock = chain.first,
|
||||
firstBlock.hash == Blockchain.genesisBlock.hash
|
||||
else {
|
||||
print("Chain: Invalid genesis block")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier la séquence des blocs
|
||||
for i in 1..<chain.count {
|
||||
let block = chain[i]
|
||||
let previousBlock = chain[i - 1]
|
||||
|
||||
// Vérifier le chaînage
|
||||
if block.previousHash != previousBlock.hash {
|
||||
print("Chain: Invalid block sequence at height \(i)")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier l'index
|
||||
if block.index != i {
|
||||
print("Chain: Invalid block index at height \(i)")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier la chronologie
|
||||
if block.timestamp <= previousBlock.timestamp {
|
||||
print("Chain: Invalid timestamp at height \(i)")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier la difficulté
|
||||
let expectedDifficulty = calculateExpectedDifficulty(at: i, chain: chain)
|
||||
if block.difficulty != expectedDifficulty {
|
||||
print("Chain: Invalid difficulty at height \(i)")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier le bloc lui-même
|
||||
if !block.isValid() {
|
||||
print("Chain: Invalid block at height \(i)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
private func calculateExpectedDifficulty(at index: Int, chain: [Block]) -> Int {
|
||||
return chain[index].difficulty
|
||||
}
|
||||
}
|
||||
130
SwiftChainCore/Models/MemPool.swift
Normal file
130
SwiftChainCore/Models/MemPool.swift
Normal file
@@ -0,0 +1,130 @@
|
||||
//
|
||||
// MemPool.swift
|
||||
// SwiftChain
|
||||
//
|
||||
// Created by Victor on 27/11/2024.
|
||||
//
|
||||
|
||||
public class MemPool {
|
||||
private var pendingTransactions: [Transaction] = []
|
||||
private let maxTransactionsPerBlock: Int = 10
|
||||
private let accountManager: AccountManager
|
||||
|
||||
init(accountManager: AccountManager) {
|
||||
self.accountManager = accountManager
|
||||
}
|
||||
|
||||
/**
|
||||
Ajoute une transaction au mempool après validation
|
||||
*/
|
||||
func addTransaction(_ transaction: Transaction) -> Bool {
|
||||
if validateTransaction(transaction) {
|
||||
pendingTransactions.append(transaction)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
Valide une transaction avant de l'ajouter au pool
|
||||
*/
|
||||
private func validateTransaction(_ transaction: Transaction) -> Bool {
|
||||
// Vérifications basiques
|
||||
if transaction.amount <= 0 {
|
||||
print("MemPool: Transaction refusée - montant invalide")
|
||||
return false
|
||||
}
|
||||
|
||||
// Pas besoin de vérifier la signature pour les récompenses de minage
|
||||
if transaction.type == "MINING_REWARD" {
|
||||
return true
|
||||
}
|
||||
|
||||
// Vérifier la signature
|
||||
if !transaction.isSignatureValid() {
|
||||
print("MemPool: Transaction refusée - signature invalide")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifier le solde
|
||||
if !accountManager.canProcessTransaction(transaction) {
|
||||
print("MemPool: Transaction refusée - solde insuffisant")
|
||||
return false
|
||||
}
|
||||
|
||||
print("MemPool: Transaction validée avec succès")
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
Récupère un lot de transactions prêtes pour le prochain bloc
|
||||
*/
|
||||
func getTransactionsForBlock() -> [Transaction] {
|
||||
var validTransactions: [Transaction] = []
|
||||
var remainingTransactions: [Transaction] = []
|
||||
|
||||
for transaction in pendingTransactions {
|
||||
if validTransactions.count >= maxTransactionsPerBlock {
|
||||
break
|
||||
}
|
||||
|
||||
if validateTransaction(transaction) {
|
||||
validTransactions.append(transaction)
|
||||
} else {
|
||||
remainingTransactions.append(transaction)
|
||||
}
|
||||
}
|
||||
|
||||
// Update pending transactions, removing the selected ones
|
||||
pendingTransactions = remainingTransactions + pendingTransactions.dropFirst(validTransactions.count)
|
||||
|
||||
return validTransactions
|
||||
}
|
||||
|
||||
/**
|
||||
Vérifie si il y a des transactions en attente
|
||||
*/
|
||||
var hasPendingTransactions: Bool {
|
||||
return !pendingTransactions.isEmpty
|
||||
}
|
||||
|
||||
/**
|
||||
Retourne toutes les transactions en attente sans les retirer
|
||||
*/
|
||||
func getAllPendingTransactions() -> [Transaction] {
|
||||
return pendingTransactions
|
||||
}
|
||||
|
||||
/**
|
||||
* Nettoie le mempool en retirant les transactions qui sont dans la chaîne
|
||||
*/
|
||||
func cleanupMempool(chain: [Block]) {
|
||||
var remainingTransactions: [Transaction] = []
|
||||
|
||||
for pendingTx in pendingTransactions {
|
||||
// On vérifie si la transaction est dans un des blocs
|
||||
var isInChain = false
|
||||
|
||||
for block in chain {
|
||||
if block.transactions.contains(where: { chainTx in
|
||||
chainTx.sender == pendingTx.sender &&
|
||||
chainTx.receiver == pendingTx.receiver &&
|
||||
chainTx.amount == pendingTx.amount &&
|
||||
chainTx.type == pendingTx.type
|
||||
}) {
|
||||
isInChain = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Si la transaction n'est pas dans la chaîne, on la garde
|
||||
if !isInChain {
|
||||
remainingTransactions.append(pendingTx)
|
||||
}
|
||||
}
|
||||
|
||||
// Mettre à jour les transactions en attente
|
||||
print("Mempool cleanup: removed \(pendingTransactions.count - remainingTransactions.count) transactions")
|
||||
pendingTransactions = remainingTransactions
|
||||
}
|
||||
}
|
||||
500
SwiftChainCore/Models/Node.swift
Normal file
500
SwiftChainCore/Models/Node.swift
Normal file
@@ -0,0 +1,500 @@
|
||||
//
|
||||
// Node.swift
|
||||
// SwiftChain
|
||||
//
|
||||
// Created by Victor on 27/11/2024.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Network
|
||||
|
||||
public class Node {
|
||||
// Network properties
|
||||
private var peers: [NWConnection] = []
|
||||
private let port: NWEndpoint.Port = 8333
|
||||
private var listener: NWListener?
|
||||
private let queue = DispatchQueue(label: "com.blockchain.node")
|
||||
|
||||
// Blockchain components
|
||||
private let blockchain: Blockchain
|
||||
private let accountManager: AccountManager
|
||||
private var pendingTransactions: [Transaction] = []
|
||||
private let maxTransactionsPerBlock: Int = 10
|
||||
|
||||
public init() {
|
||||
self.accountManager = AccountManager()
|
||||
self.blockchain = Blockchain()
|
||||
setupListener()
|
||||
}
|
||||
|
||||
enum MessageType: String, Codable {
|
||||
case transaction = "TX"
|
||||
case blockchainRequest = "BC_REQ"
|
||||
case blockchainResponse = "BC_RES"
|
||||
case newBlock = "NEW_BLOCK"
|
||||
}
|
||||
|
||||
struct NetworkMessage: Codable {
|
||||
let type: MessageType
|
||||
let data: Data
|
||||
}
|
||||
|
||||
// Configuration du listener
|
||||
private func setupListener() {
|
||||
let parameters = NWParameters.tcp
|
||||
do {
|
||||
listener = try NWListener(using: parameters, on: port)
|
||||
listener?.stateUpdateHandler = { [weak self] state in
|
||||
switch state {
|
||||
case .ready:
|
||||
print("Node is listening on port \(self?.port.rawValue ?? 0)")
|
||||
case .failed(let error):
|
||||
print("Listener failed with error: \(error)")
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
listener?.newConnectionHandler = { [weak self] connection in
|
||||
self?.handleNewConnection(connection)
|
||||
print("New incoming connection from: \(connection.endpoint)")
|
||||
}
|
||||
|
||||
listener?.start(queue: queue)
|
||||
} catch {
|
||||
print("Failed to create listener: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
public func mineBlock(minerAddress: String) -> Block? {
|
||||
guard let lastBlock = blockchain.chain.last else {
|
||||
print("No existing blockchain")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Utiliser la méthode locale au lieu de memPool
|
||||
var transactions = getTransactionsForBlock()
|
||||
let miningReward = Transaction(
|
||||
sender: "SYSTEM",
|
||||
receiver: minerAddress,
|
||||
amount: 50,
|
||||
type: "MINING_REWARD"
|
||||
)
|
||||
transactions.append(miningReward)
|
||||
|
||||
let newBlock = Block(
|
||||
transactions: transactions,
|
||||
previousHash: lastBlock.hash,
|
||||
index: blockchain.chain.count,
|
||||
difficulty: blockchain.calculateNewDifficulty()
|
||||
)
|
||||
|
||||
newBlock.miner = minerAddress
|
||||
newBlock.timestamp = Int(Date().timeIntervalSince1970)
|
||||
let miningTime = newBlock.mineBlock()
|
||||
|
||||
if accountManager.processBlock(newBlock) {
|
||||
blockchain.chain.append(newBlock)
|
||||
broadcastBlock(newBlock)
|
||||
|
||||
// Nettoyer le mempool après avoir ajouté le bloc
|
||||
cleanupMempool(chain: blockchain.chain)
|
||||
|
||||
print("""
|
||||
Block \(newBlock.index) created:
|
||||
Hash: \(newBlock.hash)
|
||||
Previous hash: \(newBlock.previousHash)
|
||||
Transactions: \(newBlock.transactions.count)
|
||||
Mining time: \(String(format: "%.2f", miningTime)) seconds
|
||||
""")
|
||||
return newBlock
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Public interface
|
||||
public func submitTransaction(_ transaction: Transaction) -> Bool {
|
||||
if addTransaction(transaction) {
|
||||
broadcastTransaction(transaction)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
public func getBalance(_ address: String) -> Int {
|
||||
return accountManager.getBalance(address)
|
||||
}
|
||||
|
||||
public func getPendingTransactions() -> [Transaction] {
|
||||
return pendingTransactions
|
||||
}
|
||||
|
||||
public func isChainValid() -> Bool {
|
||||
return blockchain.validateChain(blockchain.chain)
|
||||
}
|
||||
|
||||
// Connexion à un pair
|
||||
public func connectToPeer(host: String) {
|
||||
let endpoint = NWEndpoint.hostPort(host: NWEndpoint.Host(host), port: port)
|
||||
let connection = NWConnection(to: endpoint, using: .tcp)
|
||||
|
||||
connection.stateUpdateHandler = { [weak self] state in
|
||||
switch state {
|
||||
case .ready:
|
||||
print("Connected to peer: \(host)")
|
||||
self?.peers.append(connection)
|
||||
self?.startReceiving(connection)
|
||||
// Demander la blockchain au pair
|
||||
self?.requestBlockchain(from: connection)
|
||||
case .failed(let error):
|
||||
print("Connection failed: \(error)")
|
||||
case .cancelled:
|
||||
print("Connection cancelled: \(host)")
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
connection.start(queue: queue)
|
||||
}
|
||||
|
||||
// Méthode pour lister les pairs connectés
|
||||
public func listPeers() {
|
||||
if peers.isEmpty {
|
||||
print("Aucun pair connecté")
|
||||
return
|
||||
}
|
||||
|
||||
print("\nPairs connectés (\(peers.count)):")
|
||||
for (index, peer) in peers.enumerated() {
|
||||
print("\(index + 1). \(peer.endpoint)")
|
||||
}
|
||||
}
|
||||
|
||||
// Propagation d'une transaction
|
||||
func broadcastTransaction(_ transaction: Transaction) {
|
||||
do {
|
||||
let transactionData = try JSONEncoder().encode(transaction)
|
||||
let message = NetworkMessage(type: .transaction, data: transactionData)
|
||||
let messageData = try JSONEncoder().encode(message)
|
||||
|
||||
print("Broadcasting transaction to \(peers.count) peers")
|
||||
|
||||
for peer in peers {
|
||||
peer.send(content: messageData, completion: .contentProcessed { error in
|
||||
if let error = error {
|
||||
print("Failed to send transaction: \(error)")
|
||||
} else {
|
||||
print("Transaction sent successfully to: \(peer.endpoint)")
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
print("Failed to encode transaction: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// Réception des messages
|
||||
private func startReceiving(_ connection: NWConnection) {
|
||||
connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] content, _, isComplete, error in
|
||||
if let data = content {
|
||||
self?.handleReceivedData(data, from: connection)
|
||||
}
|
||||
|
||||
if let error = error {
|
||||
print("Receive error: \(error)")
|
||||
}
|
||||
|
||||
if !isComplete, error == nil {
|
||||
self?.startReceiving(connection)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handleReceivedData(_ data: Data, from connection: NWConnection) {
|
||||
do {
|
||||
print("Received data of size: \(data.count) bytes")
|
||||
let message = try JSONDecoder().decode(NetworkMessage.self, from: data)
|
||||
print("Message decoded successfully, type: \(message.type)")
|
||||
|
||||
switch message.type {
|
||||
case .transaction:
|
||||
let transaction = try JSONDecoder().decode(Transaction.self, from: message.data)
|
||||
print("Transaction decoded: \(transaction.sender) -> \(transaction.receiver): \(transaction.amount)")
|
||||
if addTransaction(transaction) { // Utiliser la méthode locale
|
||||
print("Transaction added to mempool successfully")
|
||||
} else {
|
||||
print("Failed to add transaction to mempool")
|
||||
}
|
||||
|
||||
case .blockchainRequest:
|
||||
// Envoyer notre blockchain au pair
|
||||
sendBlockchain(to: connection)
|
||||
|
||||
case .blockchainResponse:
|
||||
// Recevoir et traiter la blockchain
|
||||
let receivedChain = try JSONDecoder().decode([Block].self, from: message.data)
|
||||
handleReceivedBlockchain(receivedChain)
|
||||
|
||||
case .newBlock:
|
||||
// Recevoir et traiter un nouveau bloc
|
||||
let block = try JSONDecoder().decode(Block.self, from: message.data)
|
||||
handleReceivedBlock(block)
|
||||
}
|
||||
} catch {
|
||||
print("Failed to decode received data: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
private func handleNewConnection(_ connection: NWConnection) {
|
||||
connection.start(queue: queue)
|
||||
peers.append(connection)
|
||||
startReceiving(connection)
|
||||
print("New connection established with: \(connection.endpoint)")
|
||||
|
||||
// Envoyer notre blockchain au nouveau pair
|
||||
sendBlockchain(to: connection)
|
||||
}
|
||||
|
||||
private func requestBlockchain(from peer: NWConnection) {
|
||||
do {
|
||||
let message = NetworkMessage(type: .blockchainRequest, data: Data())
|
||||
let messageData = try JSONEncoder().encode(message)
|
||||
|
||||
peer.send(content: messageData, completion: .contentProcessed { error in
|
||||
if let error = error {
|
||||
print("Failed to request blockchain: \(error)")
|
||||
} else {
|
||||
print("Blockchain request sent to: \(peer.endpoint)")
|
||||
}
|
||||
})
|
||||
} catch {
|
||||
print("Failed to encode blockchain request: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
private func sendBlockchain(to peer: NWConnection) {
|
||||
do {
|
||||
let chainData = try JSONEncoder().encode(blockchain.chain)
|
||||
let message = NetworkMessage(type: .blockchainResponse, data: chainData)
|
||||
let messageData = try JSONEncoder().encode(message)
|
||||
|
||||
peer.send(content: messageData, completion: .contentProcessed { error in
|
||||
if let error = error {
|
||||
print("Failed to send blockchain: \(error)")
|
||||
} else {
|
||||
print("Blockchain sent to: \(peer.endpoint)")
|
||||
}
|
||||
})
|
||||
} catch {
|
||||
print("Failed to encode blockchain: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
private func handleReceivedBlockchain(_ receivedChain: [Block]) {
|
||||
print("Received blockchain with \(receivedChain.count) blocks")
|
||||
|
||||
if receivedChain.count > blockchain.chain.count {
|
||||
print("Received chain is longer, validating...")
|
||||
if blockchain.validateChain(receivedChain) {
|
||||
// Sauvegarder l'état actuel
|
||||
let oldChain = blockchain.chain
|
||||
|
||||
// Essayer d'appliquer la nouvelle chaîne
|
||||
blockchain.chain = receivedChain
|
||||
|
||||
// Vérifier que toutes les transactions sont valides
|
||||
var isValid = true
|
||||
for block in receivedChain where !accountManager.processBlock(block) {
|
||||
isValid = false
|
||||
break
|
||||
}
|
||||
|
||||
if isValid {
|
||||
print("Blockchain updated successfully")
|
||||
cleanupMempool(chain: receivedChain)
|
||||
} else {
|
||||
blockchain.chain = oldChain
|
||||
print("Failed to process transactions in received chain")
|
||||
}
|
||||
} else {
|
||||
print("Received chain is invalid")
|
||||
}
|
||||
} else {
|
||||
print("Current chain is longer or equal, keeping it")
|
||||
}
|
||||
}
|
||||
|
||||
private func handleReceivedBlock(_ block: Block) {
|
||||
print("Received new block: \(block.hash)")
|
||||
|
||||
// Vérifier que le bloc suit bien notre dernier bloc
|
||||
guard let lastBlock = blockchain.chain.last else {
|
||||
print("No existing chain")
|
||||
return
|
||||
}
|
||||
|
||||
if block.previousHash != lastBlock.hash {
|
||||
print("Block does not connect to our chain")
|
||||
return
|
||||
}
|
||||
|
||||
if !block.isValid() {
|
||||
print("Block is not valid")
|
||||
return
|
||||
}
|
||||
|
||||
// Traiter les transactions du bloc
|
||||
if !accountManager.processBlock(block) {
|
||||
print("Failed to process block transactions")
|
||||
return
|
||||
}
|
||||
|
||||
// Nettoyer le mempool des transactions incluses dans le bloc
|
||||
cleanupMempool(chain: [block])
|
||||
|
||||
// Ajouter le bloc à la chaîne
|
||||
blockchain.chain.append(block)
|
||||
print("New block added to chain")
|
||||
|
||||
// Propager le bloc aux autres pairs (sauf celui qui nous l'a envoyé)
|
||||
broadcastBlock(block)
|
||||
}
|
||||
|
||||
private func broadcastBlock(_ block: Block) {
|
||||
do {
|
||||
let blockData = try JSONEncoder().encode(block)
|
||||
let message = NetworkMessage(type: .newBlock, data: blockData)
|
||||
let messageData = try JSONEncoder().encode(message)
|
||||
|
||||
print("Broadcasting block to peers")
|
||||
|
||||
for peer in peers {
|
||||
peer.send(content: messageData, completion: .contentProcessed { error in
|
||||
if let error = error {
|
||||
print("Failed to send block: \(error)")
|
||||
} else {
|
||||
print("Block sent successfully to: \(peer.endpoint)")
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
print("Failed to encode block: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Mempool methods
|
||||
|
||||
extension Node {
|
||||
// MemPool functionality
|
||||
private func addTransaction(_ transaction: Transaction) -> Bool {
|
||||
if validateTransaction(transaction) {
|
||||
pendingTransactions.append(transaction)
|
||||
print("Transaction added to mempool successfully")
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private func getTransactionsForBlock() -> [Transaction] {
|
||||
var validTransactions: [Transaction] = []
|
||||
var remainingTransactions: [Transaction] = []
|
||||
|
||||
for transaction in pendingTransactions {
|
||||
if validTransactions.count >= maxTransactionsPerBlock {
|
||||
break
|
||||
}
|
||||
|
||||
if validateTransaction(transaction) {
|
||||
validTransactions.append(transaction)
|
||||
} else {
|
||||
remainingTransactions.append(transaction)
|
||||
}
|
||||
}
|
||||
|
||||
// Update pending transactions
|
||||
pendingTransactions = remainingTransactions + pendingTransactions.dropFirst(validTransactions.count)
|
||||
|
||||
return validTransactions
|
||||
}
|
||||
|
||||
private func cleanupMempool(chain: [Block]) {
|
||||
var remainingTransactions: [Transaction] = []
|
||||
|
||||
for pendingTx in pendingTransactions {
|
||||
// On vérifie si la transaction est dans un des blocs
|
||||
var isInChain = false
|
||||
|
||||
for block in chain {
|
||||
if block.transactions.contains(where: { chainTx in
|
||||
chainTx.sender == pendingTx.sender &&
|
||||
chainTx.receiver == pendingTx.receiver &&
|
||||
chainTx.amount == pendingTx.amount &&
|
||||
chainTx.type == pendingTx.type
|
||||
}) {
|
||||
isInChain = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !isInChain {
|
||||
remainingTransactions.append(pendingTx)
|
||||
}
|
||||
}
|
||||
|
||||
print("Mempool cleanup: removed \(pendingTransactions.count - remainingTransactions.count) transactions")
|
||||
pendingTransactions = remainingTransactions
|
||||
}
|
||||
|
||||
var hasPendingTransactions: Bool {
|
||||
return !pendingTransactions.isEmpty
|
||||
}
|
||||
|
||||
public func printMemPoolStatus() {
|
||||
print("""
|
||||
MemPool Status:
|
||||
- Pending transactions: \(pendingTransactions.count)
|
||||
- Maximum transactions per block: \(maxTransactionsPerBlock)
|
||||
""")
|
||||
}
|
||||
|
||||
private func checkDoubleSpending(_ transaction: Transaction) -> Bool {
|
||||
let address = transaction.sender
|
||||
let pendingAmount = pendingTransactions
|
||||
.filter { $0.sender == address }
|
||||
.reduce(0) { $0 + $1.amount }
|
||||
|
||||
let currentBalance = accountManager.getBalance(address)
|
||||
|
||||
if currentBalance < (pendingAmount + transaction.amount) {
|
||||
print("MemPool: Transaction refusée - tentative de double dépense détectée")
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
private func validateTransaction(_ transaction: Transaction) -> Bool {
|
||||
if !transaction.isValid() {
|
||||
return false
|
||||
}
|
||||
|
||||
if transaction.type == "MINING_REWARD" {
|
||||
return true
|
||||
}
|
||||
|
||||
if !checkDoubleSpending(transaction) {
|
||||
return false
|
||||
}
|
||||
|
||||
if !accountManager.canProcessTransaction(transaction) {
|
||||
print("MemPool: Transaction refusée - solde insuffisant")
|
||||
return false
|
||||
}
|
||||
|
||||
print("MemPool: Transaction validée avec succès")
|
||||
return true
|
||||
}
|
||||
}
|
||||
96
SwiftChainCore/Models/Transaction.swift
Normal file
96
SwiftChainCore/Models/Transaction.swift
Normal file
@@ -0,0 +1,96 @@
|
||||
//
|
||||
// File.swift
|
||||
//
|
||||
//
|
||||
// Created by Victor BODINAUD on 31/03/2021.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public class Transaction: Codable {
|
||||
public let sender: String
|
||||
public let receiver: String
|
||||
public let amount: Int
|
||||
public let type: String
|
||||
public var signature: Data?
|
||||
public var senderPublicKey: Data?
|
||||
|
||||
public init(sender: String, receiver: String, amount: Int, type: String) {
|
||||
self.sender = sender
|
||||
self.receiver = receiver
|
||||
self.amount = amount
|
||||
self.type = type
|
||||
}
|
||||
|
||||
// Pour encoder/décoder les Data optionnels
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case sender, receiver, amount, type, signature, senderPublicKey
|
||||
}
|
||||
|
||||
func messageToSign() -> Data {
|
||||
return "\(sender)\(receiver)\(amount)\(type)".data(using: .utf8)!
|
||||
}
|
||||
|
||||
func isSignatureValid() -> Bool {
|
||||
guard let signature = signature,
|
||||
let publicKeyData = senderPublicKey
|
||||
else {
|
||||
return false
|
||||
}
|
||||
|
||||
if type == "MINING_REWARD" {
|
||||
return true
|
||||
}
|
||||
|
||||
return Wallet.verifySignature(
|
||||
for: self,
|
||||
signature: signature,
|
||||
publicKeyData: publicKeyData
|
||||
)
|
||||
}
|
||||
|
||||
func isValid() -> Bool {
|
||||
// Vérifications de base
|
||||
if amount <= 0 {
|
||||
print("Transaction: Amount must be positive")
|
||||
return false
|
||||
}
|
||||
|
||||
if sender.isEmpty || receiver.isEmpty {
|
||||
print("Transaction: Invalid addresses")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérification du type
|
||||
if !["TRANSFER", "MINING_REWARD"].contains(type) {
|
||||
print("Transaction: Invalid type")
|
||||
return false
|
||||
}
|
||||
|
||||
// Vérifications spécifiques selon le type
|
||||
if type == "MINING_REWARD" {
|
||||
if sender != "SYSTEM" {
|
||||
print("Transaction: Mining reward must come from SYSTEM")
|
||||
return false
|
||||
}
|
||||
if amount != 50 { // La récompense doit être exactement 50
|
||||
print("Transaction: Invalid mining reward amount")
|
||||
return false
|
||||
}
|
||||
return true // Pas besoin de vérifier la signature pour les récompenses
|
||||
}
|
||||
|
||||
// Pour les transactions normales
|
||||
if !isSignatureValid() {
|
||||
print("Transaction: Invalid signature")
|
||||
return false
|
||||
}
|
||||
|
||||
if sender == receiver {
|
||||
print("Transaction: Sender cannot be receiver")
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
47
SwiftChainCore/Models/Wallet.swift
Normal file
47
SwiftChainCore/Models/Wallet.swift
Normal file
@@ -0,0 +1,47 @@
|
||||
//
|
||||
// Wallet.swift
|
||||
// SwiftChain
|
||||
//
|
||||
// Created by Victor on 27/11/2024.
|
||||
//
|
||||
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
public class Wallet {
|
||||
private let privateKey: Curve25519.Signing.PrivateKey
|
||||
let publicKey: Curve25519.Signing.PublicKey
|
||||
public let address: String
|
||||
|
||||
public init() {
|
||||
// Générer une nouvelle paire de clés
|
||||
privateKey = Curve25519.Signing.PrivateKey()
|
||||
publicKey = privateKey.publicKey
|
||||
|
||||
// Créer une adresse au format swift_(hash)
|
||||
let pubKeyData = publicKey.rawRepresentation
|
||||
let hash = SHA256.hash(data: pubKeyData)
|
||||
let hashString = hash.compactMap { String(format: "%02x", $0) }.joined()
|
||||
address = "swift_" + hashString.prefix(40)
|
||||
}
|
||||
|
||||
// Signer une transaction
|
||||
public func signTransaction(_ transaction: Transaction) -> Data? {
|
||||
let messageData = transaction.messageToSign()
|
||||
return try? privateKey.signature(for: messageData)
|
||||
}
|
||||
|
||||
// Vérifier une signature
|
||||
static func verifySignature(for transaction: Transaction, signature: Data, publicKeyData: Data) -> Bool {
|
||||
guard let publicKey = try? Curve25519.Signing.PublicKey(rawRepresentation: publicKeyData) else {
|
||||
return false
|
||||
}
|
||||
|
||||
return publicKey.isValidSignature(signature, for: transaction.messageToSign())
|
||||
}
|
||||
|
||||
// Obtenir la clé publique en format Data
|
||||
public func getPublicKeyData() -> Data {
|
||||
return publicKey.rawRepresentation
|
||||
}
|
||||
}
|
||||
13
SwiftChainCore/SwiftChainCore.docc/SwiftChainCore.md
Normal file
13
SwiftChainCore/SwiftChainCore.docc/SwiftChainCore.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# ``SwiftChainCore``
|
||||
|
||||
<!--@START_MENU_TOKEN@-->Summary<!--@END_MENU_TOKEN@-->
|
||||
|
||||
## Overview
|
||||
|
||||
<!--@START_MENU_TOKEN@-->Text<!--@END_MENU_TOKEN@-->
|
||||
|
||||
## Topics
|
||||
|
||||
### <!--@START_MENU_TOKEN@-->Group<!--@END_MENU_TOKEN@-->
|
||||
|
||||
- <!--@START_MENU_TOKEN@-->``Symbol``<!--@END_MENU_TOKEN@-->
|
||||
18
SwiftChainCore/SwiftChainCore.h
Normal file
18
SwiftChainCore/SwiftChainCore.h
Normal file
@@ -0,0 +1,18 @@
|
||||
//
|
||||
// SwiftChainCore.h
|
||||
// SwiftChainCore
|
||||
//
|
||||
// Created by Victor on 02/12/2024.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
//! Project version number for SwiftChainCore.
|
||||
FOUNDATION_EXPORT double SwiftChainCoreVersionNumber;
|
||||
|
||||
//! Project version string for SwiftChainCore.
|
||||
FOUNDATION_EXPORT const unsigned char SwiftChainCoreVersionString[];
|
||||
|
||||
// In this header, you should import all the public headers of your framework using statements like #import <SwiftChainCore/PublicHeader.h>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user