✨ Enhance blockchain
This commit is contained in:
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user