// // 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 } }