| | 1 | | namespace EF.Blockchain.Domain; |
| | 2 | |
|
| | 3 | | /// <summary> |
| | 4 | | /// Represents the core blockchain logic, managing blocks, transactions, mining, and validation. |
| | 5 | | /// </summary> |
| | 6 | | public class Blockchain |
| | 7 | | { |
| | 8 | | /// <summary> |
| | 9 | | /// All confirmed blocks in the blockchain. |
| | 10 | | /// </summary> |
| 3151 | 11 | | public List<Block> Blocks { get; private set; } |
| | 12 | |
|
| | 13 | | /// <summary> |
| | 14 | | /// Pool of pending transactions waiting to be mined. |
| | 15 | | /// </summary> |
| 1920 | 16 | | public List<Transaction> Mempool { get; private set; } |
| | 17 | |
|
| | 18 | | /// <summary> |
| | 19 | | /// Index to be used for the next block. |
| | 20 | | /// </summary> |
| 1424 | 21 | | public int NextIndex { get; private set; } = 0; |
| | 22 | |
|
| | 23 | | /// <summary> |
| | 24 | | /// Number of blocks required to increase mining difficulty. |
| | 25 | | /// </summary> |
| 8 | 26 | | public static readonly int DIFFICULTY_FACTOR = 5; |
| | 27 | |
|
| | 28 | | /// <summary> |
| | 29 | | /// Maximum number of transactions per block. |
| | 30 | | /// </summary> |
| 8 | 31 | | public static readonly int TX_PER_BLOCK = 2; |
| | 32 | |
|
| | 33 | | /// <summary> |
| | 34 | | /// Maximum mining difficulty. |
| | 35 | | /// </summary> |
| 8 | 36 | | public static readonly int MAX_DIFFICULTY = 62; |
| | 37 | |
|
| | 38 | | /// <summary> |
| | 39 | | /// Initializes a new blockchain with a genesis block mined by the given miner. |
| | 40 | | /// </summary> |
| | 41 | | /// <param name="miner">The public key (wallet address) of the genesis miner.</param> |
| 280 | 42 | | public Blockchain(string miner) |
| 280 | 43 | | { |
| 280 | 44 | | Blocks = new List<Block>(); |
| 280 | 45 | | Mempool = new List<Transaction>(); |
| | 46 | |
|
| 280 | 47 | | var genesisBlock = CreateGenesis(miner); |
| 280 | 48 | | Blocks.Add(genesisBlock); |
| 280 | 49 | | NextIndex++; |
| 280 | 50 | | } |
| | 51 | |
|
| | 52 | | private Block CreateGenesis(string miner) |
| 280 | 53 | | { |
| 280 | 54 | | var amount = GetRewardAmount(GetDifficulty()); |
| | 55 | |
|
| 280 | 56 | | var txOutput = new TransactionOutput(toAddress: miner, amount: amount); |
| | 57 | |
|
| 280 | 58 | | var feeTx = Transaction.FromReward(txOutput); |
| | 59 | |
|
| 280 | 60 | | var blockGenesis = new Block( |
| 280 | 61 | | index: NextIndex, |
| 280 | 62 | | previousHash: "", |
| 280 | 63 | | transactions: new List<Transaction> { feeTx } |
| 280 | 64 | | ); |
| | 65 | |
|
| 280 | 66 | | blockGenesis.Mine(GetDifficulty(), miner); |
| | 67 | |
|
| 280 | 68 | | return blockGenesis; |
| 280 | 69 | | } |
| | 70 | |
|
| | 71 | | /// <summary> |
| | 72 | | /// Returns the last confirmed block. |
| | 73 | | /// </summary> |
| | 74 | | public Block GetLastBlock() |
| 648 | 75 | | { |
| 648 | 76 | | return Blocks.Last(); |
| 648 | 77 | | } |
| | 78 | |
|
| | 79 | | /// <summary> |
| | 80 | | /// Calculates the current mining difficulty based on the number of blocks. |
| | 81 | | /// </summary> |
| | 82 | | public int GetDifficulty() |
| 1175 | 83 | | { |
| 1175 | 84 | | return (int)Math.Ceiling((double)Blocks.Count / DIFFICULTY_FACTOR) + 1; |
| 1175 | 85 | | } |
| | 86 | |
|
| | 87 | | /// <summary> |
| | 88 | | /// Attempts to add a transaction to the mempool after validating it. |
| | 89 | | /// </summary> |
| | 90 | | public Validation AddTransaction(Transaction transaction) |
| 56 | 91 | | { |
| 56 | 92 | | if (transaction.TxInputs != null && transaction.TxInputs.Any()) |
| 56 | 93 | | { |
| 56 | 94 | | var from = transaction.TxInputs[0].FromAddress; |
| | 95 | |
|
| 56 | 96 | | var pendingTx = Mempool |
| 8 | 97 | | .Where(tx => tx.TxInputs != null) |
| 8 | 98 | | .SelectMany(tx => tx.TxInputs!) |
| 8 | 99 | | .Where(txi => txi.FromAddress == from) |
| 56 | 100 | | .ToList(); |
| | 101 | |
|
| 56 | 102 | | if (pendingTx.Any()) |
| 8 | 103 | | return new Validation(false, "This wallet has a pending transaction"); |
| | 104 | |
|
| 48 | 105 | | var utxo = GetUtxo(from); |
| 216 | 106 | | foreach (var txi in transaction.TxInputs) |
| 48 | 107 | | { |
| 48 | 108 | | var match = utxo.FirstOrDefault(txo => |
| 80 | 109 | | txo.Tx == txi.PreviousTx && txo.Amount >= txi.Amount); |
| | 110 | |
|
| 48 | 111 | | if (match == null) |
| 24 | 112 | | return new Validation(false, "Invalid tx: the TXO is already spent or nonexistent"); |
| 24 | 113 | | } |
| 24 | 114 | | } |
| | 115 | |
|
| 24 | 116 | | var validation = transaction.IsValid(GetDifficulty(), GetFeePerTx()); |
| 24 | 117 | | if (!validation.Success) |
| 0 | 118 | | return new Validation(false, "Invalid tx: " + validation.Message); |
| | 119 | |
|
| 72 | 120 | | if (Blocks.Any(b => b.Transactions.Any(tx => tx.Hash == transaction.Hash))) |
| 0 | 121 | | return new Validation(false, "Duplicated tx in blockchain"); |
| | 122 | |
|
| 24 | 123 | | Mempool.Add(transaction); |
| | 124 | |
|
| 24 | 125 | | return new Validation(true, transaction.Hash); |
| 56 | 126 | | } |
| | 127 | |
|
| | 128 | | /// <summary> |
| | 129 | | /// Attempts to add a new mined block to the blockchain after validation. |
| | 130 | | /// </summary> |
| | 131 | | public Validation AddBlock(Block block) |
| 312 | 132 | | { |
| 312 | 133 | | var nextBlockInfo = GetNextBlock(); |
| 312 | 134 | | if (nextBlockInfo == null) |
| 8 | 135 | | return new Validation(false, "There is no next block info"); |
| | 136 | |
|
| 304 | 137 | | var validation = block.IsValid( |
| 304 | 138 | | nextBlockInfo.PreviousHash, |
| 304 | 139 | | nextBlockInfo.Index - 1, |
| 304 | 140 | | nextBlockInfo.Difficulty, |
| 304 | 141 | | nextBlockInfo.FeePerTx |
| 304 | 142 | | ); |
| | 143 | |
|
| 304 | 144 | | if (!validation.Success) |
| 280 | 145 | | return new Validation(false, $"Invalid block: {validation.Message}"); |
| | 146 | |
|
| 24 | 147 | | var txs = block.Transactions |
| 48 | 148 | | .Where(tx => tx.Type != TransactionType.FEE) |
| 24 | 149 | | .Select(tx => tx.Hash) |
| 24 | 150 | | .ToList(); |
| | 151 | |
|
| 24 | 152 | | var newMempool = Mempool |
| 64 | 153 | | .Where(tx => !txs.Contains(tx.Hash)) |
| 24 | 154 | | .ToList(); |
| | 155 | |
|
| 24 | 156 | | if (newMempool.Count + txs.Count != Mempool.Count) |
| 0 | 157 | | return new Validation(false, "Invalid tx in block: mempool"); |
| | 158 | |
|
| 24 | 159 | | Mempool = newMempool; |
| 24 | 160 | | Blocks.Add(block); |
| 24 | 161 | | NextIndex++; |
| | 162 | |
|
| 24 | 163 | | return new Validation(true, block.Hash); |
| 312 | 164 | | } |
| | 165 | |
|
| | 166 | | /// <summary> |
| | 167 | | /// Finds a block by its hash. |
| | 168 | | /// </summary> |
| | 169 | | public Block? GetBlock(string hash) |
| 8 | 170 | | { |
| 16 | 171 | | return Blocks.FirstOrDefault(b => b.Hash == hash); |
| 8 | 172 | | } |
| | 173 | |
|
| | 174 | | /// <summary> |
| | 175 | | /// Finds a transaction by hash in the mempool or blockchain. |
| | 176 | | /// </summary> |
| | 177 | | public TransactionSearch GetTransaction(string hash) |
| 32 | 178 | | { |
| 64 | 179 | | var mempoolIndex = Mempool.FindIndex(tx => tx.Hash == hash); |
| 32 | 180 | | if (mempoolIndex != -1) |
| 16 | 181 | | { |
| 16 | 182 | | return new TransactionSearch( |
| 16 | 183 | | transaction: Mempool[mempoolIndex], |
| 16 | 184 | | mempoolIndex: mempoolIndex, |
| 16 | 185 | | blockIndex: -1 |
| 16 | 186 | | ); |
| | 187 | | } |
| | 188 | |
|
| 64 | 189 | | var blockIndex = Blocks.FindIndex(b => b.Transactions.Any(tx => tx.Hash == hash)); |
| 16 | 190 | | if (blockIndex != -1) |
| 8 | 191 | | { |
| 16 | 192 | | var transaction = Blocks[blockIndex].Transactions.First(tx => tx.Hash == hash); |
| 8 | 193 | | return new TransactionSearch( |
| 8 | 194 | | transaction: transaction, |
| 8 | 195 | | mempoolIndex: -1, |
| 8 | 196 | | blockIndex: blockIndex |
| 8 | 197 | | ); |
| | 198 | | } |
| | 199 | |
|
| 8 | 200 | | return new TransactionSearch( |
| 8 | 201 | | blockIndex: -1, |
| 8 | 202 | | mempoolIndex: -1, |
| 8 | 203 | | transaction: null! |
| 8 | 204 | | ); |
| 32 | 205 | | } |
| | 206 | |
|
| | 207 | | /// <summary> |
| | 208 | | /// Validates the integrity of the entire blockchain from the latest block to the genesis. |
| | 209 | | /// </summary> |
| | 210 | | public Validation IsValid() |
| 32 | 211 | | { |
| 64 | 212 | | for (int i = Blocks.Count - 1; i > 0; i--) |
| 8 | 213 | | { |
| 8 | 214 | | var currentBlock = Blocks[i]; |
| 8 | 215 | | var previousBlock = Blocks[i - 1]; |
| 8 | 216 | | var validation = currentBlock.IsValid( |
| 8 | 217 | | previousBlock.Hash, |
| 8 | 218 | | previousBlock.Index, |
| 8 | 219 | | GetDifficulty(), |
| 8 | 220 | | GetFeePerTx() |
| 8 | 221 | | ); |
| | 222 | |
|
| 8 | 223 | | if (!validation.Success) |
| 8 | 224 | | return new Validation(false, $"Invalid block #{currentBlock.Index}: {validation.Message}"); |
| 0 | 225 | | } |
| 24 | 226 | | return new Validation(); |
| 32 | 227 | | } |
| | 228 | |
|
| | 229 | | /// <summary> |
| | 230 | | /// Returns the current fixed fee per transaction. |
| | 231 | | /// </summary> |
| | 232 | | public int GetFeePerTx() |
| 360 | 233 | | { |
| 360 | 234 | | return 1; |
| 360 | 235 | | } |
| | 236 | |
|
| | 237 | | /// <summary> |
| | 238 | | /// Builds a <see cref="BlockInfo"/> object with data needed to mine the next block. |
| | 239 | | /// </summary> |
| | 240 | | public BlockInfo? GetNextBlock() |
| 336 | 241 | | { |
| 336 | 242 | | if (Mempool == null || Mempool.Count == 0) |
| 16 | 243 | | return null; |
| | 244 | |
|
| 320 | 245 | | var transactions = Mempool.Take(Blockchain.TX_PER_BLOCK).ToList(); |
| | 246 | |
|
| 320 | 247 | | var difficulty = GetDifficulty(); |
| 320 | 248 | | var previousHash = GetLastBlock().Hash; |
| 320 | 249 | | var index = Blocks.Count; |
| 320 | 250 | | var feePerTx = GetFeePerTx(); |
| 320 | 251 | | var maxDifficulty = MAX_DIFFICULTY; |
| | 252 | |
|
| 320 | 253 | | return new BlockInfo( |
| 320 | 254 | | transactions: transactions, |
| 320 | 255 | | difficulty: difficulty, |
| 320 | 256 | | previousHash: previousHash, |
| 320 | 257 | | index: index, |
| 320 | 258 | | feePerTx: feePerTx, |
| 320 | 259 | | maxDifficulty: maxDifficulty |
| 320 | 260 | | ); |
| 336 | 261 | | } |
| | 262 | |
|
| | 263 | | /// <summary> |
| | 264 | | /// Returns all transaction inputs for a specific wallet. |
| | 265 | | /// </summary> |
| | 266 | | public List<TransactionInput> GetTxInputs(string wallet) |
| 88 | 267 | | { |
| 88 | 268 | | return Blocks |
| 104 | 269 | | .SelectMany(b => b.Transactions) |
| 104 | 270 | | .Where(tx => tx.TxInputs != null && tx.TxInputs.Any()) |
| 16 | 271 | | .SelectMany(tx => tx.TxInputs!) |
| 16 | 272 | | .Where(txi => txi.FromAddress == wallet) |
| 88 | 273 | | .ToList(); |
| 88 | 274 | | } |
| | 275 | |
|
| | 276 | | /// <summary> |
| | 277 | | /// Returns all transaction outputs for a specific wallet. |
| | 278 | | /// </summary> |
| | 279 | | public List<TransactionOutput> GetTxOutputs(string wallet) |
| 88 | 280 | | { |
| 88 | 281 | | return Blocks |
| 104 | 282 | | .SelectMany(b => b.Transactions) |
| 104 | 283 | | .Where(tx => tx.TxOutputs != null && tx.TxOutputs.Any()) |
| 96 | 284 | | .SelectMany(tx => tx.TxOutputs!) |
| 104 | 285 | | .Where(txo => txo.ToAddress == wallet) |
| 88 | 286 | | .ToList(); |
| 88 | 287 | | } |
| | 288 | |
|
| | 289 | | /// <summary> |
| | 290 | | /// Returns the list of unspent transaction outputs (UTXOs) for a wallet. |
| | 291 | | /// </summary> |
| | 292 | | public List<TransactionOutput> GetUtxo(string wallet) |
| 88 | 293 | | { |
| 88 | 294 | | var txIns = GetTxInputs(wallet); |
| 88 | 295 | | var txOuts = GetTxOutputs(wallet); |
| | 296 | |
|
| 88 | 297 | | if (txIns == null || txIns.Count == 0) |
| 72 | 298 | | return txOuts; |
| | 299 | |
|
| 80 | 300 | | foreach (var txi in txIns) |
| 16 | 301 | | { |
| 32 | 302 | | var index = txOuts.FindIndex(txo => txo.Amount == txi.Amount); |
| | 303 | |
|
| 16 | 304 | | if (index != -1) |
| 0 | 305 | | txOuts.RemoveAt(index); |
| 16 | 306 | | } |
| | 307 | |
|
| 16 | 308 | | return txOuts; |
| 88 | 309 | | } |
| | 310 | |
|
| | 311 | | /// <summary> |
| | 312 | | /// Returns the total balance of a wallet based on UTXOs. |
| | 313 | | /// </summary> |
| | 314 | | public int GetBalance(string wallet) |
| 24 | 315 | | { |
| 24 | 316 | | var utxo = GetUtxo(wallet); |
| 40 | 317 | | return utxo?.Sum(txo => txo.Amount) ?? 0; |
| 24 | 318 | | } |
| | 319 | |
|
| | 320 | | /// <summary> |
| | 321 | | /// Calculates the mining reward based on the current difficulty. |
| | 322 | | /// </summary> |
| | 323 | | public static int GetRewardAmount(int difficulty) |
| 672 | 324 | | { |
| 672 | 325 | | return (64 - difficulty) * 10; |
| 672 | 326 | | } |
| | 327 | | } |