private void CalculateBalances(int confirmations) { var balances = new Dictionary <string, decimal>(); foreach (var genesisTransactions in blocks[0].Transactions) { balances.Add(genesisTransactions.To, genesisTransactions.Value); } foreach (var block in blocks.Skip(1).Take(blocks.Count - confirmations)) { if (block.Index == 0) { continue; } foreach (var transaction in block.Transactions) { var senderPublicKey = CryptographyUtilities.DecodeECPointFromHex(transaction.SenderPublicKey); var bytes = Encoding.UTF8.GetBytes(transaction.TransactionHash); if (CryptographyUtilities.VerifySigniture(bytes, transaction.SenderSignature, senderPublicKey)) { balances[transaction.From] -= transaction.Value; if (balances.ContainsKey(transaction.To)) { balances[transaction.To] += transaction.Value; } else { balances.Add(transaction.To, transaction.Value); } } else { Console.WriteLine("Found incorrect signiture..."); return; } } } this.balances = balances; }
private bool ValidateTransaction(Transaction transaction, IDictionary <string, decimal> futureBalances = null) { IDictionary <string, decimal> balances; bool inSimulationMode = false; if (futureBalances != null) { inSimulationMode = true; balances = futureBalances; } else { balances = GetBalances(0); } var bytes = Encoding.UTF8.GetBytes(transaction.TransactionHash); ECPoint senderPublicKey = CryptographyUtilities.DecodeECPointFromHex(transaction.SenderPublicKey); if (!CryptographyUtilities.VerifySigniture(bytes, transaction.SenderSignature, senderPublicKey)) { Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^"); Console.WriteLine("Transaction validation failed..."); Console.WriteLine("INFO -> incorrect signiture..."); return(false); } if (!balances.ContainsKey(transaction.From) || balances[transaction.From] < transaction.Value) { Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^"); Console.WriteLine("Transaction validation failed..."); Console.WriteLine("INFO -> not enought money of sender..."); return(false); } if (inSimulationMode) { balances[transaction.From] -= transaction.Value; } var copyOftransaction = new Transaction() { From = transaction.From, To = transaction.To, Value = transaction.Value, SenderPublicKey = transaction.SenderPublicKey }; var transactionJson = JsonConvert.SerializeObject(copyOftransaction); var transactionHash = CryptographyUtilities.BytesToHex(CryptographyUtilities.CalcSHA256(transactionJson)); if (transactionHash != transaction.TransactionHash) { Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^"); Console.WriteLine("Transaction validation failed..."); Console.WriteLine("INFO -> incorrect transaction hash..."); return(false); } Console.WriteLine("Transaction validation success..."); return(true); }