private static void GenerateIdentity(int keySize = 256) { ECKeyPairGenerator gen = new ECKeyPairGenerator(); SecureRandom secureRandom = new SecureRandom(); KeyGenerationParameters keyGenParam = new KeyGenerationParameters(secureRandom, keySize); gen.Init(keyGenParam); var keyPair = gen.GenerateKeyPair(); BigInteger privateKey = ((ECPrivateKeyParameters)keyPair.Private).D; Console.WriteLine("Private key (hex): " + privateKey.ToString(16)); Console.WriteLine("Private key: " + privateKey.ToString(10)); Console.WriteLine("Password for private key encryption:"); var password = Console.ReadLine(); var encryptedPrivateKey = CryptographyUtilities.Encrypt(privateKey.ToByteArray(), password); StorageFileProvider <string> .SetModel(Constants.WalletEncryptedPrivateKeyFilePath, encryptedPrivateKey); ECPoint pubKey = ((ECPublicKeyParameters)keyPair.Public).Q; string pubKeyCompressed = CryptographyUtilities.EncodeECPointHexCompressed(pubKey); Console.WriteLine("Public key (compressed): " + pubKeyCompressed); string addr = CryptographyUtilities.CalcRipeMD160(pubKeyCompressed); Console.WriteLine("Blockchain address: " + addr); }
/// <summary> /// Uses Azure Storage Blob Container for serving `Static File`. /// </summary> /// <typeparam name="TOptions">The type of the configuration object to be used to register the Azure Storage Blob container.</typeparam> /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param> /// <returns></returns> public static IApplicationBuilder UseAzureStorageForStaticFiles <TOptions>( this IApplicationBuilder app) where TOptions : StorageFileProviderOptions { var storageOptions = app.ApplicationServices.GetRequiredService <IOptionsMonitor <StorageAccountOptions> >(); var options = app.ApplicationServices.GetRequiredService <IOptionsMonitor <TOptions> >().CurrentValue; var azureFileProvider = new StorageFileProvider( storageOptions.Get(options.AzureStorageConfiguration), options.ContainerName); app.UseStaticFiles(new StaticFileOptions() { FileProvider = azureFileProvider, RequestPath = options.RequestPath }); if (options.EnableDirectoryBrowsing) { app.UseDirectoryBrowser(new DirectoryBrowserOptions() { FileProvider = azureFileProvider, RequestPath = options.RequestPath }); } return(app); }
public static void UnlockWallet() { if (privateKey == null) { var encryptedPrivateKey = StorageFileProvider <string> .GetModel(Constants.WalletEncryptedPrivateKeyFilePath); if (encryptedPrivateKey != null && encryptedPrivateKey != string.Empty) { Console.WriteLine("Type your password:"******"Unlock wallet..."); var bytes = CryptographyUtilities.Decrypt(encryptedPrivateKey, password); if (bytes != null && bytes.Length > 0) { privateKey = new BigInteger(bytes); } break; } catch { Console.WriteLine("Incorrect password..."); Console.WriteLine("Type your password again:"); password = Console.ReadLine(); } } } } }
public void Load() { int index = 0; string path = $"{Constants.BlocksFilePath}/block_{index}.json"; bool isFileExist = File.Exists(path); while (isFileExist) { var block = StorageFileProvider <Block> .GetModel(path); this.blocks.Add(block); index++; path = $"{Constants.BlocksFilePath}/block_{index}.json"; isFileExist = File.Exists(path); } Console.WriteLine("Load blocks..."); if (StorageFileProvider <Node[]> .HasContent(Constants.PeersFilePath)) { this.peers = StorageFileProvider <Node[]> .GetModel(Constants.PeersFilePath).ToList(); } Console.WriteLine("Load peers..."); if (StorageFileProvider <Transaction[]> .HasContent(Constants.PendingTransactionsFilePath)) { this.pendingTransactions = StorageFileProvider <Transaction[]> .GetModel(Constants.PendingTransactionsFilePath).ToList(); } Console.WriteLine("Load pending transactions..."); }
public Block AddBlock(Block block) { Console.WriteLine("Try add block..."); if (block.Index == 0) { Console.WriteLine(); Console.WriteLine(block.Index); Console.WriteLine(); } if (ValidateBlock(block)) { this.blocks.Add(block); StorageFileProvider <Block> .SetModel($"{Constants.BlocksFilePath}/block_{block.Index}.json", block); //Shoud think :-) this.pendingTransactions = new List <Transaction>(); StorageFileProvider <Transaction[]> .SetModel(Constants.PendingTransactionsFilePath, this.pendingTransactions.ToArray()); Console.WriteLine("Done..."); return(block); } return(null); }
public StorageFileSystem(Options.IConfiguration configuration) { _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _file = new StorageFileProvider(this); _directory = new StorageDirectoryProvider(this); _pool = new ConcurrentDictionary <string, StorageClient>(); }
public Transaction AddTransaction(Transaction transaction) { Console.WriteLine("Try add pending transaction..."); if (ValidateTransaction(transaction)) { Console.WriteLine("Done..."); this.pendingTransactions.Add(transaction); StorageFileProvider <Transaction[]> .SetModel(Constants.PendingTransactionsFilePath, this.pendingTransactions.ToArray()); return(transaction); } return(null); }
public Block AddBlock(int nonce, WalletProvider walletProvider) { string lastBlockHash = this.LastBlock.BlockHash; string winnerHash = CryptographyUtilities.BytesToHex(CryptographyUtilities.CalcSHA256($"{lastBlockHash}{nonce}")); if (!winnerHash.ToCharArray().Take(this.Difficulty).All(s => s == '0')) { Console.WriteLine("Incorrect winner hash..."); return(null); } var transactions = this.pendingTransactions; foreach (var transaction in transactions) { transaction.DateReceived = DateTime.Now; transaction.MinedInBlockIndex = this.LastBlock.Index + 1; } var block = new Block() { Index = this.LastBlock.Index + 1, DateCreated = DateTime.Now, Difficulty = this.Difficulty, MinedBy = walletProvider.Address, Nonce = nonce, PreviousBlockHash = this.LastBlock.BlockHash, Transactions = transactions.ToList() }; string blockJson = JsonConvert.SerializeObject(block); var blockHash = CryptographyUtilities.BytesToHex(CryptographyUtilities.CalcSHA256(blockJson)); block.BlockHash = blockHash; this.blocks.Add(block); StorageFileProvider <Block> .SetModel($"{Constants.BlocksFilePath}/block_{block.Index}.json", block); //Shoud think :-) this.pendingTransactions = new List <Transaction>(); StorageFileProvider <Transaction[]> .SetModel(Constants.PendingTransactionsFilePath, this.pendingTransactions.ToArray()); return(block); }
public bool RegisterNode(string ip, int port) { IPAddress address; if (IPAddress.TryParse(ip, out address)) { this.peers.Add(new Node() { Address = ip, Port = port }); StorageFileProvider <Node[]> .SetModel(Constants.PeersFilePath, this.peers.ToArray()); return(true); } return(false); }
public static void UnlockWallet() { if (privateKey == null) { var encryptedPrivateKey = StorageFileProvider <string> .GetModel(Constants.WalletEncryptedPrivateKeyFilePath); if (encryptedPrivateKey != null && encryptedPrivateKey != string.Empty) { var password = "******"; var bytes = CryptographyUtilities.Decrypt(encryptedPrivateKey, password); if (bytes != null && bytes.Length > 0) { privateKey = new BigInteger(bytes); } } } }
public List <Block> LoadBlocks(string folderPath) { int index = 0; string path = $"{folderPath}/block_{index}.json"; bool isFileExist = File.Exists(path); List <Block> blocks = new List <Block>(); while (isFileExist) { var block = StorageFileProvider <Block> .GetModel(path); blocks.Add(block); index++; path = $"{folderPath}/block_{index}.json"; isFileExist = File.Exists(path); } return(blocks); }
public void CreateGenesis() { var genesisBlock = new Block(); genesisBlock.Index = 0; genesisBlock.DateCreated = DateTime.Now; genesisBlock.Difficulty = 0; genesisBlock.MinedBy = "GENESIS"; genesisBlock.Nonce = 0; genesisBlock.PreviousBlockHash = "GENESIS"; var transaction = new Transaction() { From = "GENESIS", To = "e39f2a9daf79084f96b28d0b92439b0b6112981c", Value = 1000000000000000, SenderPublicKey = null, SenderSignature = null }; string transactionJson = JsonConvert.SerializeObject(transaction); var transactionHash = CryptographyUtilities.BytesToHex(CryptographyUtilities.CalcSHA256(transactionJson)); transaction.TransactionHash = transactionHash; transaction.DateReceived = DateTime.Now; genesisBlock.Transactions = new List <Transaction>(); genesisBlock.Transactions.Add(transaction); string blockJson = JsonConvert.SerializeObject(genesisBlock); var blockHash = CryptographyUtilities.BytesToHex(CryptographyUtilities.CalcSHA256(blockJson)); genesisBlock.BlockHash = blockHash; string path = $"{Constants.BlocksFilePath}/block_0.json"; StorageFileProvider <Block> .SetModel(path, genesisBlock); this.blocks.Add(genesisBlock); }
public Transaction AddTransaction(string from, string to, decimal amount, IWalletProvider walletProvider) { this.CalculateBalances(0); if (balances.ContainsKey(from) && balances[from] < amount) { Console.WriteLine("Not enought coins..."); return(null); } var publicKeyHex = CryptographyUtilities.BytesToHex(walletProvider.PublicKey.GetEncoded()); var transaction = new Transaction() { From = from, To = to, Value = amount, SenderPublicKey = publicKeyHex }; string transactionJson = JsonConvert.SerializeObject(transaction, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var transactionHash = CryptographyUtilities.BytesToHex(CryptographyUtilities.CalcSHA256(transactionJson)); var signiture = walletProvider.SignTransaction(Encoding.UTF8.GetBytes(transactionHash)); transaction.TransactionHash = transactionHash; transaction.SenderSignature = signiture; this.pendingTransactions.Add(transaction); StorageFileProvider <Transaction[]> .SetModel(Constants.PendingTransactionsFilePath, this.pendingTransactions.ToArray()); Console.WriteLine("Transaction is pending..."); return(transaction); }
public StorageFileSystem() { _file = new StorageFileProvider(this); _directory = new StorageDirectoryProvider(this); _pool = new ConcurrentDictionary <string, StorageClient>(); }
public List <Transaction> LoadPendingTransactions(string path) { List <Transaction> pendingTransactions = StorageFileProvider <Transaction[]> .GetModel(path).ToList(); return(pendingTransactions); }
public void MineAsync() { int nonce = 0; string hash = string.Empty; try { string lastBlockPath = Directory.GetFiles($"{Constants.BlocksFilePath}/", "*.json") .OrderBy(n => int.Parse(n.Split('_')[1].Replace(".json", ""))).ToList().Last(); string lastBlockHash = StorageFileProvider <Block> .GetModel(lastBlockPath).BlockHash; int counter = 0; while (true) { counter++; if (StopThread) { break; } if (counter > 100000) { lastBlockPath = Directory.GetFiles($"{Constants.BlocksFilePath}/", "*.json") .OrderBy(n => int.Parse(n.Split('_')[1].Replace(".json", ""))).ToList().Last(); lastBlockHash = StorageFileProvider <Block> .GetModel(lastBlockPath).BlockHash; counter = 0; } hash = CryptographyUtilities.BytesToHex(CryptographyUtilities.CalcSHA256($"{lastBlockHash}{nonce}")); if (hash.ToCharArray().Take(this.blockchain.Difficulty).All(s => s == '0')) { string currentLastBlockPath = Directory.GetFiles($"{Constants.BlocksFilePath}/", "*.json") .OrderBy(n => int.Parse(n.Split('_')[1].Replace(".json", ""))).ToList().Last(); string newLastBlockHash = StorageFileProvider <Block> .GetModel(currentLastBlockPath).BlockHash; counter = 0; if (newLastBlockHash != lastBlockHash) { nonce = 0; continue; } break; } nonce++; } } catch { } if (!StopThread) { NextBlockMined(hash, nonce); Thread thread = new Thread(MineAsync); thread.Start(); var miningThread = CommandFabric.ThreadsInfo.First(t => t.Key == "Mining"); CommandFabric.ThreadsInfo.Remove(miningThread); CommandFabric.ThreadsInfo.Add("Mining", thread.ManagedThreadId); } }