🐛 Fix blockchain sync

This commit is contained in:
Victor Bodinaud
2024-11-30 11:57:05 +01:00
parent 6d0777930d
commit 22d8b22ea1
2 changed files with 23 additions and 16 deletions

View File

@@ -16,6 +16,17 @@ class Blockchain {
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 // 1er Décembre 2023 00:00:00 GMT
block.difficulty = 4
block.nonce = 12345 // Nonce précalculé qui donne un hash valide
block.hash = "000088c1731bed4996680d2c50ea3d9b573c1507d2d61866c0deff33a7f8cf5e"
return block
}()
init() {
self.accountManager = AccountManager()
self.memPool = MemPool(accountManager: accountManager)
@@ -28,13 +39,8 @@ class Blockchain {
- data: The datas of the block
*/
func createGenesisBlock() {
let genesisBlock = Block()
genesisBlock.previousHash = "0000"
genesisBlock.index = 0
genesisBlock.timestamp = Int(Date().timeIntervalSince1970)
let _ = genesisBlock.mineBlock()
chain.append(genesisBlock)
print("Genesis block created -- hash: \(genesisBlock.hash)")
chain.append(Blockchain.genesisBlock)
print("Genesis block initialized -- hash: \(Blockchain.genesisBlock.hash)")
}
/**
@@ -118,24 +124,23 @@ class Blockchain {
}
func validateChain(_ newChain: [Block]) -> Bool {
// Vérifier que la chaîne commence par notre genesis block
guard newChain.first?.hash == chain.first?.hash else {
// Vérifier que la chaîne commence par notre bloc genesis codé en dur
guard let firstBlock = newChain.first,
firstBlock.hash == Blockchain.genesisBlock.hash else {
print("Genesis block mismatch")
return false
}
// Vérifier chaque bloc
// Vérifier les blocs suivants
for i in 1..<newChain.count {
let block = newChain[i]
let previousBlock = newChain[i-1]
// Vérifier le chaînage
if block.previousHash != previousBlock.hash {
print("Invalid chain at block \(i): incorrect previous hash")
return false
}
// Vérifier la validité du bloc
if !block.isValid() {
print("Invalid chain at block \(i): invalid block hash")
return false

View File

@@ -72,10 +72,12 @@ class Node {
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 to: \(host)")
print("Connection cancelled: \(host)")
default:
break
}
@@ -180,14 +182,14 @@ class Node {
}
}
// Quand un pair se connecte, demander sa blockchain
private func handleNewConnection(_ connection: NWConnection) {
connection.start(queue: queue)
peers.append(connection)
startReceiving(connection)
print("New connection established with: \(connection.endpoint)")
// Demander la blockchain
requestBlockchain(from: connection)
// Envoyer notre blockchain au nouveau pair
sendBlockchain(to: connection)
}
private func requestBlockchain(from peer: NWConnection) {