private void RemoveTransactionsFromPool(IList <Transaction> transactions) { foreach (var tx in transactions) { TransactionPool.Remove(HexadecimalEncoding.ToHexString(tx.Id)); } }
private void HandleInv(CommandMessage rxMsg) { var inventory = new Inv().DeSerialize(rxMsg.Data); logger.Debug("Inventory recieved: " + inventory.Kind); if (inventory.Kind == "block") { if (blocksInTransit.Count == 0) { blocksInTransit = ReduceBlocksInTransit(inventory.Items); //reduce blocksInTransit, don't wanna download whole chain again //blocksInTransit = (inventory.Items); //dont reduce blocksInTransit - download whole chain logger.Debug("Reduced blocks, to download : " + blocksInTransit.Count); } if (blocksInTransit.Count == 0) { return; //this means, blockInTransit was reduced totaly and nothing is needed } var latestHashToTake = blocksInTransit[0]; SendGetData(rxMsg.Client.ToString(), "block", latestHashToTake); blocksInTransit.RemoveAt(0); } else if (inventory.Kind == "tx") { var txId = inventory.Items[0]; //request it only if I dont have it yet if (!TransactionPool.ContainsKey(HexadecimalEncoding.ToHexString(txId))) { SendGetData(rxMsg.Client.ToString(), "tx", txId); } } }
public (Dictionary <string, List <int> >, int) FindSpendableOutputs(byte[] pubKeyHash, int amount) { var unspentOuts = new Dictionary <string, List <int> >(); var accumulated = 0; var cursor = Chain.TransactionDB.Cursor(); foreach (var current in cursor) { var key = current.Key; var value = current.Value; var txId = HexadecimalEncoding.ToHexString(key); var outs = TxOutputs.DeSerialize(value); if (!unspentOuts.ContainsKey(txId)) { unspentOuts.Add(txId, new List <int>()); } foreach (var(output, index) in outs.Outputs.Select((v, i) => (v, i))) { if (output.IsLockedWithKey(pubKeyHash) && accumulated < amount) { accumulated += output.Value; unspentOuts[txId].Add(index); } } } return(unspentOuts, accumulated); }
public void Sign(byte[] privateKey, Dictionary <string, Transaction> prevTxs) { if (IsCoinBase()) { return; } foreach (var inp in Inputs) { var hex = HexadecimalEncoding.ToHexString(inp.Id); if (prevTxs[hex]?.Id == null) { Console.WriteLine("prev transaction does not exist"); } } var txCopy = TransactionTrimmed(this); var index = 0; foreach (var inp in txCopy.Inputs) { var prevTx = prevTxs[HexadecimalEncoding.ToHexString(inp.Id)]; txCopy.Inputs[index].Signature = null; txCopy.Inputs[index].PubKey = prevTx.Outputs[inp.Out].PublicKeyHash; txCopy.Id = txCopy.CalculateHash(); txCopy.Inputs[index].PubKey = null; var signature = CryptoFinal.SignTransaction(txCopy.Id, privateKey); Inputs[index].Signature = signature; index++; } }
//ver1 public static Transaction NewTransaction(string from, string to, int amount, UTXOSet set) { var inputs = new List <TxInput>(); var outputs = new List <TxOutput>(); var walletBank = new WalletBank(); var wallet = walletBank.FindWallet(from); var pubKeyHash = wallet.PublicKeyHash; var spendableOutputs = set.FindSpendableOutputs(pubKeyHash, amount); var account = spendableOutputs.Item2; var validOutputs = spendableOutputs.Item1; if (account < amount) { Console.WriteLine("Insufficient funds"); return(null); } else { foreach (var output in validOutputs.Keys) { var txId = (output); if (validOutputs.ContainsKey(txId)) { foreach (var @out in validOutputs[txId]) { var input = new TxInput() { Id = HexadecimalEncoding.FromHexStringToByte(txId), Out = @out, Signature = null, PubKey = wallet.PublicKey }; inputs.Add(input); } } } outputs.Add(TxOutput.NewTxOutput(amount, to)); if (account > amount) { outputs.Add(TxOutput.NewTxOutput(account - amount, from)); } } var tx = new Transaction() { Id = null, Inputs = inputs, Outputs = outputs, TimeStamp = DateTime.Now }; tx.Id = tx.CalculateHash(); set.Chain.SignTransaction(tx, wallet.PrivateKey); return(tx); }
public HttpResponseMessage GetActiveProfessor(string guid) { var accountId = HexadecimalEncoding.FromHexString(HttpContext.Current.Server.UrlDecode(guid)); var professor = _professorsServices.ActivateUser(accountId); var response = Request.CreateResponse(HttpStatusCode.Moved); response.Headers.Location = new Uri(frontEndSite); return(response); }
public VN_EN_Word getWord(string key) { VN_EN_Word w = null; try { if (conn.State != ConnectionState.Open) { conn.Open(); } using (SqlCommand cmd = new SqlCommand(getVnWordCommand, conn)) { cmd.Parameters.Add("@VNKey", SqlDbType.NVarChar).Value = HexadecimalEncoding.ToHexString(key + " \r"); SqlDataReader sdr = cmd.ExecuteReader(); if (sdr.Read()) { w = new VN_EN_Word(); w.VNKey = HexadecimalEncoding.FromHexString(sdr["VNKey"].ToString()); w.VNSuggestion = sdr["VNSuggestion"].ToString(); w.WordType = sdr["WordType"].ToString(); w.Means = sdr["ENMeans"].ToString(); w.Example = sdr["Example"].ToString(); } else { sdr.Close(); } cmd.Parameters.Clear(); cmd.Parameters.Add("@VNKey", SqlDbType.NVarChar).Value = HexadecimalEncoding.ToHexString(key + "\r"); sdr = cmd.ExecuteReader(); if (sdr.Read()) { w = new VN_EN_Word(); w.VNKey = HexadecimalEncoding.FromHexString(sdr["VNKey"].ToString()); w.VNSuggestion = sdr["VNSuggestion"].ToString(); w.WordType = sdr["WordType"].ToString(); w.Means = sdr["ENMeans"].ToString(); w.Example = sdr["Example"].ToString(); } sdr.Close(); } } catch (Exception e) { conn.Close(); throw e; } return(w); }
public void SignTransaction(Transaction tx, byte[] privateKey) { var prevTxs = new Dictionary <string, Transaction>(); foreach (var inp in tx.Inputs) { var prevTx = FindTransaction(inp.Id); prevTxs[HexadecimalEncoding.ToHexString(prevTx.Id)] = prevTx; } tx.Sign(privateKey, prevTxs); }
public IHttpActionResult PostResetPassword(ResetPasswordModel model) { _studentsServices.ResetPasswordStudent(model); var stringparameter = HexadecimalEncoding.ToHexString(model.AccountId); _email.Send(model.Email + ",[email protected]", "Hacer click en el siguiente link para confirmar el cambio de contrasena: " + backEndSite + "/api/Students/" + HttpContext.Current.Server.UrlEncode(stringparameter) + "/Active", "Vinculación"); return(Ok()); }
/// <summary> /// 1. Clear Database, /// 2. Finds UTXO /// 3. Add to DB /// </summary> public void ReIndex() { DeleteKeys(); var UTXO = Chain.FindUtxo(); var index = 0; foreach (var outputs in UTXO) { var key = HexadecimalEncoding.FromHexStringToByte(outputs.Key); Chain.TransactionDB.Put(key, outputs.Value.Serialize()); index++; } }
public IHttpActionResult PostStudent(UserEntryModel userModel) { var newStudent = new User(); _studentsServices.Map(newStudent, userModel); _studentsServices.Add(newStudent); var stringparameter = HexadecimalEncoding.ToHexString(newStudent.AccountId); _email.Send(newStudent.Email, "Hacer click en el siguiente link para activar su cuenta: " + backEndSite + "/api/Students/" + HttpContext.Current.Server.UrlEncode(stringparameter) + "/Active", "Vinculación"); return(Ok(newStudent)); }
public bool VerifyTransaction(Transaction tx) { if (tx.IsCoinBase()) { return(true); // new byte[]{} id, which is a problem as well as I dont need to verify cb txs } var prevTxs = new Dictionary <string, Transaction>(); foreach (var inp in tx.Inputs) { var prevTx = FindTransaction(inp.Id); //TODO if not found here... prevTx is null, must return false. prevTxs[HexadecimalEncoding.ToHexString(prevTx.Id)] = prevTx; } return(tx.Verify(prevTxs)); }
private void HandleGetData(CommandMessage message) { var data = new Data().DeSerialize(message.Data); if (data.Kind == "block") { var block = chain.GetBlock(data.Id); SendBlock(message.Client.ToString(), block); } ; if (data.Kind == "tx") { var txId = HexadecimalEncoding.ToHexString(data.Id); var transaction = TransactionPool[txId]; SendTx(message.Client.ToString(), transaction); } ; }
public byte[] GetMessagePacket() { if (Data == null) { Data = new byte[] { } } ; var textResult = ""; textResult += "<message>"; textResult += "<type>" + Type + "</type>"; textResult += "<command>" + Command + "</command>"; textResult += "<data>" + HexadecimalEncoding.ToHexString(Data) + "</data>"; textResult += "<clientdetails><name>" + mClient.ClientName + "</name><ipaddress>" + mClient.ClientIPAddress + "</ipaddress><listenport>" + mClient.ClientListenPort + "</listenport></clientdetails>"; textResult += "</message>"; return(Encoding.UTF8.GetBytes(textResult)); }
public bool Verify(Dictionary <string, Transaction> prevTxs) { if (IsCoinBase()) { return(true); } foreach (var inp in Inputs) { var hex = HexadecimalEncoding.ToHexString(inp.Id); if (prevTxs[hex]?.Id == null) { Console.WriteLine("prev transaction does not exist"); } } var txCopy = TransactionTrimmed(this); var index = 0; foreach (var inp in Inputs) { var prevTx = prevTxs[HexadecimalEncoding.ToHexString(inp.Id)]; txCopy.Inputs[index].Signature = null; txCopy.Inputs[index].PubKey = prevTx.Outputs[inp.Out].PublicKeyHash; txCopy.Id = txCopy.CalculateHash(); txCopy.Inputs[index].PubKey = null; var(r, s, v) = CryptoFinal.GetRSV(inp.Signature); var recoveredKey = CryptoFinal.RecoverPublicKey(r.ToByteArray(), s.ToByteArray(), v.ToByteArray(), txCopy.Id); if (!CryptoFinal.VerifyHashed(inp.Signature, recoveredKey, txCopy.Id)) { Console.WriteLine("verify failed"); return(false); } index++; } //Console.WriteLine("verify ok"); return(true); }
private void HandleTransaction(CommandMessage message) { var tx = new Transaction().DeSerialize(message.Data); logger.Debug("New Transaction recieved : " + HexadecimalEncoding.ToHexString(tx.Id)); //add to pool TransactionPool.Add(HexadecimalEncoding.ToHexString(tx.Id), tx); TransactionPoolChanged?.Invoke(this, new TransactionPoolEventArgs(new List <string>(TransactionPool.Keys))); if (!miningInProgress) { if (TransactionPool.Count >= numberOfTransactionsToStartMining) { //Mine transaction var thread = new Thread(MineTransactions); thread.Start(); } } }
private void HandleBlock(CommandMessage message) { var block = new Block().DeSerialize(message.Data); logger.Debug("Recieved new block from: " + message.Client.ToString()); chain.AddBlock(block); logger.Debug("block added ID:" + Convert.ToBase64String(block.Hash) + "index: " + block.Index); BlockOnTheFly.Remove(HexadecimalEncoding.ToHexString(block.Hash)); //--progress bar if (highestIndex < block.Index) { highestIndex = block.Index; //check best index } NewBlockArrived?.Invoke(this, new ProgressBarEventArgs(highestIndex, blocksInTransit.Count, reducedBlockCount)); //invoke this, mainly for progress bar now. //--progress bar end if (blocksInTransit.Count > 0) { var blockHash = blocksInTransit[0]; SendGetData(message.Client.ToString(), "block", blockHash); BlockOnTheFly.Add(HexadecimalEncoding.ToHexString(blockHash)); blocksInTransit.RemoveAt(0); } else { if (BlockOnTheFly.Count != 0) { return; } reindexing = true; chain.ReindexUTXO(); // asynch WholeChainDownloaded?.Invoke(this, EventArgs.Empty); // invoke this after all is downloaded, cause downloading from lastest to oldest, could cause problems after displaying after each block isBusy = false; reindexing = false; ProcessNextMessage(); } }
public override string ToString() { return(HexadecimalEncoding.ToHexString(Data).Substring(0, 4)); }
public void Send(string from, string to, int amount) { var utxoSet = new UTXOSet(chain); var tx = Transaction.NewTransaction(from, to, amount, utxoSet); if (tx == null) { logger.Debug("Couldn't create new TX to send"); InsufficientFund?.Invoke(this, EventArgs.Empty); return; } //old ver //var block = chain.MineBlock(new List<Transaction>() { tx }); //utxoSet.Update(block); //WholeChainDownloaded?.Invoke(this, EventArgs.Empty); //chain.ReindexUTXO(); //check if not referencing same output, TODO BUG FIX //var referencingSameOutput = false; //foreach (var transaction in TransactionPool) //{ // var txOutputs = tx.Outputs; // var poolOutputs = transaction.Value.Outputs; // foreach (var outp in poolOutputs) // { // foreach (var txOutp in txOutputs) // { // if (outp.Equals(txOutp)) // { // referencingSameOutput = true; // break; // } // } // if (referencingSameOutput) break; // } // if (referencingSameOutput) break; //} //if (referencingSameOutput) //{ // logger.Debug("Referencing same output in tx. Tx not added to TPool"); // return; //} //add to pool TransactionPool.Add(HexadecimalEncoding.ToHexString(tx.Id), tx); TransactionPoolChanged?.Invoke(this, new TransactionPoolEventArgs(new List <string>(TransactionPool.Keys))); //send to all except me and the one who send the tx var addressesToExclude = new string[] { _blockchainPeer.ClientDetails().ToString() }; var msg = new CommandMessage(); msg.Command = CommandType.Transaction; msg.Client = _blockchainPeer.ClientDetails(); msg.Data = tx.Serialize(); _blockchainPeer.BroadcastMessageAsyncExceptAddress(addressesToExclude, msg); logger.Debug("Sending tx over nettwork"); if (!miningInProgress) { if (TransactionPool.Count >= numberOfTransactionsToStartMining) { var thread = new Thread(MineTransactions); thread.Start(); } } }
public bool Parse(Byte[] data) { //parse the message from "incoming data packet" var messageContent = Encoding.UTF8.GetString(data); ////////////////////////////////////////////////////////////////////////// //Data validation XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.LoadXml(messageContent); } catch (XmlException ex) { System.Diagnostics.Debug.WriteLine("There was an xml parsing error in the received message : " + ex.Message); return(false); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("There was an error in the received message : " + ex.Message); return(false); } MessageType type = MessageType.EmptyMessage; XmlElement messageElement = xmlDoc.DocumentElement; if (messageElement.Name == "message") { foreach (XmlNode node in messageElement.ChildNodes) { if (node.Name == "type") { type = (MessageType)Enum.Parse(typeof(MessageType), node.InnerText); break; } } } if (type != MessageType.CommandMessage) { Console.WriteLine("The supplied data was the wrong message type!"); return(false); } foreach (XmlNode node in messageElement.ChildNodes) { if (node.Name == "data") { this.Data = HexadecimalEncoding.FromHexStringToByte(node.InnerText); } else if (node.Name == "command") { Enum.TryParse(node.InnerText, out CommandType command); Command = command; } else if (node.Name == "clientdetails") { mClient = new ClientDetails(); foreach (XmlNode detailsNode in node.ChildNodes) { if (detailsNode.Name == "name") { mClient.ClientName = detailsNode.InnerText; } else if (detailsNode.Name == "ipaddress") { mClient.ClientIPAddress = detailsNode.InnerText; } else if (detailsNode.Name == "listenport") { mClient.ClientListenPort = int.Parse(detailsNode.InnerText); } } } } ////////////////////////////////////////////////////////////////////////// return(true); }
public IHttpActionResult EnableProfessor(EnableProfessorModel model) { /* check if the account Id exists on the system * if exists, check * if the status = inactive (0) * update account information and send email * else * cannot update information * else -> account doesnt exist * create account with the model * send email */ var professor = _professorsServices.FindNullable(model.AccountId); // Check if account exists if (professor != null) { // Check if account is inactive if (((User)professor).Status == 0) { var updatedProfessor = _professorsServices.UpdateProfessor(model.AccountId, model); // Send confirmation email var encryptedTalentoHumano = HexadecimalEncoding.ToHexString(model.AccountId); _email.Send(model.Email, "Hacer click en el siguiente link para activar su cuenta: " + backEndSite + "/api/Professors/EnableProfessors/Activate/" + HttpContext.Current.Server.UrlEncode(encryptedTalentoHumano), "Vinculación"); return(Ok()); } else { throw new Exception("account is already active"); } } else { var newProfessor = new User(); //mapeo newProfessor.AccountId = model.AccountId; newProfessor.Email = model.Email; newProfessor.Password = _encryption.Encrypt(model.Password); newProfessor.Name = model.FirstName + " " + model.LastName; newProfessor.Major = null; newProfessor.Campus = "USPS"; newProfessor.CreationDate = DateTime.Now; newProfessor.ModificationDate = DateTime.Now; newProfessor.Status = Data.Enums.Status.Inactive; newProfessor.Finiquiteado = false; _professorsServices.AddProfessor(newProfessor); // Send confirmation email var encryptedTalentoHumano = HexadecimalEncoding.ToHexString(model.AccountId); _email.Send(model.Email, "Hacer click en el siguiente link para activar su cuenta: " + backEndSite + "/api/Professors/EnableProfessors/Activate/" + HttpContext.Current.Server.UrlEncode(encryptedTalentoHumano), "Vinculación"); return(Ok()); } }
public IHttpActionResult PostChangePassword(EnableStudentModel model) { var student = _studentsServices.FindNullable(model.AccountId); if (student != null) { if (((User)student).Status == 0) { var updatedStudent = _studentsServices.UpdateStudent(model.AccountId, model); // Send confirmation email var encryptedAccountId = HexadecimalEncoding.ToHexString(model.AccountId); _email.Send(model.Email, "Hacer click en el siguiente link para activar su cuenta: " + backEndSite + "/api/Students/" + HttpContext.Current.Server.UrlEncode(encryptedAccountId) + "/Active", "Vinculación"); return(Ok()); } else { throw new Exception("account is already active"); } } else { var newStudent = new User(); //mapeo newStudent.AccountId = model.AccountId; newStudent.Email = model.Email; newStudent.Password = _encryption.Encrypt(model.Password); newStudent.Name = model.FirstName + " " + model.LastName; newStudent.Major = _majorServices.Find(model.MajorId); newStudent.Campus = "USPS"; newStudent.CreationDate = DateTime.Now; newStudent.ModificationDate = DateTime.Now; newStudent.Status = Data.Enums.Status.Inactive; newStudent.Finiquiteado = false; _studentsServices.Add(newStudent); // Send confirmation email var encryptedAccountId = HexadecimalEncoding.ToHexString(model.AccountId); _email.Send(model.Email, "Hacer click en el siguiente link para activar su cuenta: " + backEndSite + "/api/Students/" + HttpContext.Current.Server.UrlEncode(encryptedAccountId) + "/Active", "Vinculación"); return(Ok()); } //_studentsServices.ChangePassword(model); //var stringparameter = HexadecimalEncoding.ToHexString(model.AccountId); //_email.Send(model.Email, // "Hacer click en el siguiente link para activar su cuenta: " + // backEndSite + // "/api/Students/" + HttpContext.Current.Server.UrlEncode(stringparameter) + // "/Active", // "Vinculación"); //return Ok(); }
public Dictionary <string, TxOutputs> FindUtxo() { var UTXOs = new Dictionary <string, TxOutputs>(); var spentTxOs = new Dictionary <string, List <int> >(); var confirmationIndex = 0; foreach (var block in this) { confirmationIndex++; foreach (var tx in block) { if (tx.IsCoinBase() == true) { if (confirmationIndex < 3 && block.Index != 0) { continue; //last 3 blocks are to be confirmed for accepting coinbase tx } } var tXId = tx.Id; //transaction ID if (!spentTxOs.ContainsKey(HexadecimalEncoding.ToHexString(tXId))) { spentTxOs.Add(HexadecimalEncoding.ToHexString(tXId), new List <int>()); } var index = 0; foreach (var output in tx.Outputs) { if (spentTxOs.ContainsKey(HexadecimalEncoding.ToHexString(tXId))) { foreach (var spentOut in spentTxOs[HexadecimalEncoding.ToHexString(tXId)]) { if (spentOut.Equals(index)) { goto endOfTheLoop; } } } if (!UTXOs.ContainsKey(HexadecimalEncoding.ToHexString(tXId))) { UTXOs.Add(HexadecimalEncoding.ToHexString(tXId), new TxOutputs()); } var outs = UTXOs[HexadecimalEncoding.ToHexString(tXId)]; outs.Outputs.Add(output); UTXOs[HexadecimalEncoding.ToHexString(tXId)] = outs; endOfTheLoop: { } index++; } if (tx.IsCoinBase() == false) { foreach (var input in tx.Inputs) { if (!spentTxOs.ContainsKey(HexadecimalEncoding.ToHexString(input.Id))) { spentTxOs.Add(HexadecimalEncoding.ToHexString(input.Id), new List <int>()); } spentTxOs[HexadecimalEncoding.ToHexString(input.Id)].Add(input.Out); } } } } return(UTXOs); }