private Dictionary <string, string> blockToJsonDictionary(Block block) { Dictionary <string, string> blockData = new Dictionary <string, string>(); blockData.Add("Block Number", block.blockNum.ToString()); blockData.Add("Version", block.version.ToString()); blockData.Add("Block Checksum", Crypto.hashToString(block.blockChecksum)); blockData.Add("Last Block Checksum", Crypto.hashToString(block.lastBlockChecksum)); blockData.Add("Wallet State Checksum", Crypto.hashToString(block.walletStateChecksum)); blockData.Add("Sig freeze Checksum", Crypto.hashToString(block.signatureFreezeChecksum)); blockData.Add("PoW field", Crypto.hashToString(block.powField)); blockData.Add("Timestamp", block.timestamp.ToString()); blockData.Add("Difficulty", block.difficulty.ToString()); blockData.Add("Hashrate", (Miner.getTargetHashcountPerBlock(block.difficulty) / 60).ToString()); blockData.Add("Compacted Sigs", block.compactedSigs.ToString()); blockData.Add("Signature count", block.signatures.Count.ToString()); blockData.Add("Transaction count", block.transactions.Count.ToString()); blockData.Add("Transaction amount", TransactionPool.getTotalTransactionsValueInBlock(block).ToString()); blockData.Add("Signatures", JsonConvert.SerializeObject(block.signatures)); blockData.Add("TX IDs", JsonConvert.SerializeObject(block.transactions)); blockData.Add("Last Superblock", block.lastSuperBlockNum.ToString()); blockData.Add("Last Superblock checksum", Crypto.hashToString(block.lastSuperBlockChecksum)); return(blockData); }
/// <summary> /// Creates <paramref name="parallelCount"/> write sessions simultaneously over /// <paramref name="iterations"/> number of iterations. /// </summary> private async Task CreateReleaseWriteSessions( SessionPool pool, SpannerClient client, int iterations, int parallelCount) { // We yield to increase contention among parallel tasks that are kicked off. // This increases the amount of work they are doing on another thread. await Task.Yield(); for (var i = 0; i < iterations; i++) { var readWriteOptions = new TransactionOptions { ReadWrite = new TransactionOptions.Types.ReadWrite() }; var writeSessions = await Task.WhenAll( DuplicateTaskAsync(() => CreateSessionAsync(pool, client, readWriteOptions), parallelCount)); await Task.Delay(TimeSpan.FromMilliseconds(10)); foreach (var session in writeSessions) { var transaction = await TransactionPool.BeginPooledTransactionAsync(client, session, readWriteOptions); await TransactionPool.CommitAsync(transaction, session, new Mutation[0], SpannerOptions.Instance.Timeout, CancellationToken.None); pool.ReleaseToPool(client, session); } } }
public void GetWithHigestFee() { var pool = new TransactionPool(); var tx1 = new Transaction() { fee = 1 }; var tx2 = new Transaction() { fee = 2 }; var tx3 = new Transaction() { fee = 3 }; var tx4 = new Transaction() { fee = 4 }; pool.AddTransaction(tx1); pool.AddTransaction(tx2); pool.AddTransaction(tx3); pool.AddTransaction(tx4); var txs = pool.GetTransactionsWithHighestFee(3); Assert.AreEqual(3, txs.Length); Assert.AreEqual(4, txs[0].fee); Assert.AreEqual(3, txs[1].fee); Assert.AreEqual(2, txs[2].fee); }
public async Task FindNonce() { await Task.Run(() => { lock (lockObject_) { ulong nonce = 0; do { NewBlock.Nonce = nonce; var hash = GetHash(NewBlock); if (hash < Target) { BlockChain.Add(NewBlock); NewBlock = null; LastHash = SerializeHash(hash); OnBlockChainChanged(); TransactionPool.Clear(); OnTransactionPoolChanged(); return; } ++nonce; } while (nonce != ulong.MaxValue); throw new Exception("nonce not found."); } }); }
public int Add(TransactionPool item) { return(db.Query("pool").InsertGetId <int>(new { item.Timestamp })); }
// Broadcasts the solution to the network public void sendSolution(byte[] nonce) { byte[] pubkey = Node.walletStorage.getPrimaryPublicKey(); // Check if this wallet's public key is already in the WalletState Wallet mywallet = Node.walletState.getWallet(Node.walletStorage.getPrimaryAddress()); if (mywallet.publicKey != null && mywallet.publicKey.SequenceEqual(pubkey)) { // Walletstate public key matches, we don't need to send the public key in the transaction pubkey = null; } byte[] data = null; using (MemoryStream mw = new MemoryStream()) { using (BinaryWriter writerw = new BinaryWriter(mw)) { writerw.Write(activeBlock.blockNum); writerw.Write(Crypto.hashToString(nonce)); data = mw.ToArray(); } } Transaction tx = new Transaction((int)Transaction.Type.PoWSolution, new IxiNumber(0), new IxiNumber(0), ConsensusConfig.ixianInfiniMineAddress, Node.walletStorage.getPrimaryAddress(), data, pubkey, Node.blockChain.getLastBlockNum()); if (TransactionPool.addTransaction(tx)) { PendingTransactions.addPendingLocalTransaction(tx); } else { Logging.error("An unknown error occured while sending PoW solution."); } }
public int redactChain() { lock (blocks) { // redaction int begin_size = blocks.Count(); while ((ulong)blocks.Count() > CoreConfig.redactedWindowSize) { Block block = getBlock(blocks[0].blockNum); TransactionPool.redactTransactionsForBlock(block); // Remove from Transaction Pool // Check if this is a full history node if (Config.storeFullHistory == false) { Storage.removeBlock(block); // Remove from storage } lock (blocksDictionary) { blocksDictionary.Remove(block.blockNum); } blocks.RemoveAt(0); // Remove from memory } if (begin_size > blocks.Count()) { Logging.info(String.Format("REDACTED {0} blocks to keep the chain length appropriate.", begin_size - blocks.Count())); } return(begin_size - blocks.Count()); } }
public JsonResponse onGetTransaction(Dictionary <string, object> parameters) { if (!parameters.ContainsKey("id")) { JsonError error = new JsonError { code = (int)RPCErrorCode.RPC_INVALID_PARAMETER, message = "Parameter 'id' is missing" }; return(new JsonResponse { result = null, error = error }); } string txid_string = (string)parameters["id"]; Transaction t = TransactionPool.getTransaction(txid_string, 0, Config.storeFullHistory); if (t == null) { return(new JsonResponse { result = null, error = new JsonError { code = (int)RPCErrorCode.RPC_INVALID_PARAMETER, message = "Transaction not found." } }); } return(new JsonResponse { result = t.toDictionary(), error = null }); }
public TransactionController(TransactionPool transactionPool, BalanceLedger balanceLedger, HttpProvider httpProvider, ContactLedger contactLedger) { _transactionPool = transactionPool; _balanceLedger = balanceLedger; _httpProvider = httpProvider; _contactLedger = contactLedger; }
/// <summary> /// Aborts a transaction and releases it. /// </summary> /// <param name="trans">Transaction to be aborted.</param> public void AbortTransaction(IDbTransaction trans) { if (trans == null) { return; } bool isRequestTransaction; TransactionInfo transInfo = GetTransactionInfo(trans, out isRequestTransaction); if (transInfo != null) { #if DEBUG_DBCONNECTIONPOOLING OSTrace.Info("DBConnectionPooling[TID=" + transInfo.Transaction.GetHashCode() + "] - returned to pool"); OSTrace.Error(new StackTrace().ToString()); #endif transInfo.Release(); if (isRequestTransaction) { RequestTransactionInfo = null; } else { TransactionPool.Remove(transInfo.Transaction); } transInfo.ReturnConnectionToPool(); } }
public static void handleTransactionData(byte[] data, RemoteEndpoint endpoint) { /*if(TransactionPool.checkSocketTransactionLimits(socket) == true) * { * // Throttled, ignore this transaction * return; * }*/ Transaction transaction = new Transaction(data); if (transaction == null) { return; } bool no_broadcast = false; if (!Node.blockSync.synchronizing) { if (transaction.type == (int)Transaction.Type.StakingReward) { // Skip received staking transactions if we're not synchronizing return; } } else { no_broadcast = true; } // Add the transaction to the pool TransactionPool.addTransaction(transaction, no_broadcast, endpoint); }
protected TransactionInfo AddToPoolAndReserve() { lock (this) { TransactionInfo transInfo = null; while (transInfo == null) { transInfo = BuildTransactionInfo(); transInfo.Reserve(); //drivers doesn't ensure connection is good so make sure if (transInfo.Transaction.Connection == null || transInfo.Transaction.Connection.State == ConnectionState.Closed) { if (transInfo.Transaction.Connection != null) { transInfo.ReturnConnectionToPool(); } LogException(new InvalidTransactionException("Connection in transaction is null."), new StackTrace(), "Releasing connection pools and retrying"); transInfo = null; // retry; TransactionService.ReleasePooledConnections("Connection in transaction is null."); Thread.Sleep(TransactionServiceConstants.RETRY_CONNECTION_TIME); } } #if DEBUG_DBCONNECTIONPOOLING OSTrace.Info("DBConnectionPooling[TID=" + transInfo.Transaction.GetHashCode() + "] - reserved from pool"); OSTrace.Error(new StackTrace().ToString()); #endif TransactionPool.Add(transInfo.Transaction, transInfo); return(transInfo); } }
private static void broadcastBlockHeaderTransactions(Block b, RemoteEndpoint endpoint) { if (!endpoint.isConnected()) { return; } foreach (var txid in b.transactions) { Transaction t = TransactionPool.getAppliedTransaction(txid, b.blockNum, true); if (endpoint.isSubscribedToAddress(NetworkEvents.Type.transactionFrom, new Address(t.pubKey).address)) { endpoint.sendData(ProtocolMessageCode.transactionData, t.getBytes(true), null); } else { foreach (var entry in t.toList) { if (endpoint.isSubscribedToAddress(NetworkEvents.Type.transactionTo, entry.Key)) { endpoint.sendData(ProtocolMessageCode.transactionData, t.getBytes(true), null); } } } } }
public JsonResponse onTxa(Dictionary <string, object> parameters) { JsonError error = null; string fromIndex = "0"; if (parameters.ContainsKey("fromIndex")) { fromIndex = (string)parameters["fromIndex"]; } string count = "50"; if (parameters.ContainsKey("count")) { count = (string)parameters["count"]; } Transaction[] transactions = TransactionPool.getAppliedTransactions().Skip(Int32.Parse(fromIndex)).Take(Int32.Parse(count)).ToArray(); Dictionary <string, Dictionary <string, object> > tx_list = new Dictionary <string, Dictionary <string, object> >(); foreach (Transaction t in transactions) { tx_list.Add(t.id, t.toDictionary()); } return(new JsonResponse { result = tx_list, error = error }); }
// returns statistics about the unspent transactions private JsonResponse onGetTxOutsetInfo() { Block block = IxianHandler.getLastBlock(); Transaction[] unapplied_txs = TransactionPool.getUnappliedTransactions(); long txouts = 0; IxiNumber total_amount = new IxiNumber(0); foreach (Transaction tx in unapplied_txs) { txouts += tx.toList.Count(); total_amount += tx.amount + tx.fee; } Dictionary <string, Object> result_array = new Dictionary <string, Object> { { "height", block.blockNum }, // Block height { "bestblock", Crypto.hashToString(block.blockChecksum) }, // Block checksum { "transactions", unapplied_txs.LongCount() }, // Number of transactions { "txouts", txouts }, // Number of transaction outputs { "total_amount", total_amount.ToString() } // Total amount }; return(new JsonResponse { result = result_array, error = null }); }
public static void startTxSpamTest() { Logging.info("Starting tx spam test"); int nonce = 0; for (int i = 0; i < txspamNum; i++) { IxiNumber amount = new IxiNumber("0.01"); IxiNumber fee = ConsensusConfig.transactionPrice; byte[] to = ConsensusConfig.foundationAddress; byte[] from = Node.walletStorage.getPrimaryAddress(); byte[] pubKey = Node.walletStorage.getPrimaryPublicKey(); // Check if this wallet's public key is already in the WalletState Wallet mywallet = Node.walletState.getWallet(from, true); if (mywallet.publicKey != null && mywallet.publicKey.SequenceEqual(pubKey)) { // Walletstate public key matches, we don't need to send the public key in the transaction pubKey = null; } Transaction transaction = new Transaction((int)Transaction.Type.Normal, amount, fee, to, from, null, pubKey, Node.blockChain.getLastBlockNum()); // Console.WriteLine("> sending {0}", transaction.id); TransactionPool.addTransaction(transaction); nonce++; } Logging.info("Ending tx spam test"); }
public async Task <Exception> AddSelfEvent() { if (TransactionPool.Count == 0) { logger.Debug("Empty TxPool"); return(null); } //create new event with self head and empty other parent //empty transaction pool in its payload var newHead = new Event(TransactionPool.ToArray(), BlockSignaturePool.ToArray(), new[] { Head, "" }, PubKey(), Seq + 1); var err = await SignAndInsertSelfEvent(newHead); if (err != null) { return(new CoreError($"Error inserting new head: {err.Message}", err)); } logger.Debug("Created Self-Event Transactions={TransactionCount}; BlockSignatures={BlockSignatureCount}", TransactionPool.Count, BlockSignaturePool.Count); TransactionPool.Clear(); BlockSignaturePool.Clear(); return(null); }
// Perform periodic cleanup tasks private static void performMaintenance() { while (running) { TLC.Report(); // Sleep a while to prevent cpu usage Thread.Sleep(10000); try { TransactionPool.processPendingTransactions(); // Cleanup the presence list PresenceList.performCleanup(); if (update() == false) { IxianHandler.forceShutdown = true; } } catch (Exception e) { Logging.error("Exception occurent in Node.performMaintenance: " + e); } } }
private void DumpPoolSummaries(MethodInfo method, string description) { FileLogger.Log($"Pool summaries {description} {method.DeclaringType.Name}.{method.Name}"); FileLogger.Log($"Session pool: {SessionPool.Default.ToDiagnosticSummary()}"); FileLogger.Log($"Client pool: {ClientPool.Default.ToDiagnosticSummary()}"); FileLogger.Log($"Transaction pool: {TransactionPool.ToDiagnosticSummary()}"); FileLogger.Log(""); }
public void AddToPool <TEntity>(TransactionServiceInfo info) { if (TransactionPool == null) { TransactionPool = new TransactionPool(_directory); } TransactionPool.Put <TEntity>(info); }
public void RepositoriesFullInsert() { DigitalSignatureUtils.AssignKeyPair("addr3"); TransactionPoolRepository tpr = new TransactionPoolRepository(); TransactionPool tp = new TransactionPool { Timestamp = DateTime.Now }; int poolId = tpr.Add(tp); Assert.AreEqual(poolId, tpr.Get(poolId).Id); TransactionRepository tr = new TransactionRepository(); Transaction t = new Transaction { PoolId = poolId, SenderId = 6, RecipientId = 1, Amount = 10, Status = TransactionStatus.confirmed.ToString(), Timestamp = DateTime.Now }; int transactionId = tr.Add(t); Assert.AreEqual(transactionId, tr.Get(transactionId).Id); BlockRepository br = new BlockRepository(); Block b = new Block { PoolId = poolId, PreviousHash = br.Get().Last().Hash, Timestamp = DateTime.Now }; b.AssignPool(); b.ComputeHash(); b.Signature = Convert.ToBase64String( DigitalSignatureUtils.SignData( Convert.FromBase64String( b.Hash ) ) ); int blockId = br.Add(b); Assert.AreEqual(blockId, br.Get(blockId).Id); }
public static void startTxFileSpamTest() { Logging.info("Starting tx file spam test"); if (File.Exists(txfilename) == false) { Logging.error("Cannot start tx file spam test. Missing tx spam file!"); return; } BinaryReader reader; try { reader = new BinaryReader(new FileStream(txfilename, FileMode.Open)); } catch (IOException e) { Logging.error("Cannot open txspam file. {0}", e.Message); return; } try { int spam_num = reader.ReadInt32(); Logging.info("Reading {0} spam transactions from file.", spam_num); long start_time = Clock.getTimestampMillis(); int spam_counter = 0; for (int i = 0; i < spam_num; i++) { int length = reader.ReadInt32(); byte[] bytes = reader.ReadBytes(length); Transaction transaction = new Transaction(bytes); TransactionPool.addTransaction(transaction); spam_counter++; if (spam_counter >= targetTps) { long elapsed = Clock.getTimestampMillis() - start_time; if (elapsed < 1000) { Thread.Sleep(1000 - (int)elapsed); } spam_counter = 0; start_time = Clock.getTimestampMillis(); } } } catch (IOException e) { Logging.error("Cannot read from txspam file. {0}", e.Message); return; } reader.Close(); Logging.info("Ending tx file spam test"); }
// Reverts redaction for a single block private bool unredactChain() { lock (blocks) { int redacted_window_size = (int)ConsensusConfig.getRedactedWindowSize(getLastBlockVersion()); if (blocks.Count() == redacted_window_size) { Logging.warn("Won't unredact chain, block count is already correct."); return(false); } while (blocks.Count() < redacted_window_size) { if (lastBlockNum < (ulong)redacted_window_size) { return(false); } ulong block_num_to_unredact = lastBlockNum - (ulong)blocks.Count(); Block b = getBlock(block_num_to_unredact, true, true); lock (blocksDictionary) { if (blocksDictionary.ContainsKey(block_num_to_unredact)) { Logging.warn("Won't unredact chain, block #{0} is already in memory.", block_num_to_unredact); return(false); } } if (!TransactionPool.unredactTransactionsForBlock(b)) { TransactionPool.redactTransactionsForBlock(b); return(false); } blocks.Insert(0, b); lock (blocksDictionary) { blocksDictionary.Add(block_num_to_unredact, b); } if (b.powField != null) { increaseSolvedBlocksCount(); } Logging.info("UNREDACTED block #{0} to keep the chain length appropriate.", block_num_to_unredact); } } return(true); }
public EmbedServer(TransactionPool transactionPool, IBlockMiner blockMiner, ILoggerFactory loggerFactory, IConfigurationRoot config) { string port = config.GetSection("RpcPort").Get <string>(); url = $"http://localhost:{port}/"; server = CreateWebServer(url); this.transactionPool = transactionPool; this.blockMiner = blockMiner; this.logger = loggerFactory.CreateLogger <EmbedServer>(); }
public async Task Merge(Pool pool) { await DepositPool.Add(await pool.DepositPool.GetPool()); await OfferPool.Add(await pool.OfferPool.GetPool()); await OfferCancelPool.Add(await pool.OfferCancelPool.GetPool()); await TransactionPool.Add(await pool.TransactionPool.GetPool()); await WithdrawalPool.Add(await pool.WithdrawalPool.GetPool()); }
public void CreateBlock() { lock (lockObject_) { NewBlock = new Block { Index = BlockChain.Last().Index + 1, PreviousHash = SerializeHash(GetHash(BlockChain.Last())), TimeStamp = DateTime.UtcNow, Transactions = TransactionPool.ToList(), }; TransactionPool.Clear(); } }
public Pool Fork() { var fork = new Pool(); fork.DepositPool = DepositPool.Fork(); fork.OfferPool = OfferPool.Fork(); fork.OfferCancelPool = OfferCancelPool.Fork(); fork.TransactionPool = TransactionPool.Fork(); fork.WithdrawalPool = WithdrawalPool.Fork(); return(fork); }
private static void Demo() { // Initialize blockchain var transactionPool = new TransactionPool(); var blockChain = new BlockChain(transactionPool); // Create new transactions. var transaction1 = new Transaction(sender: "Bob", recipient: "Billy", amount: 10, fee: 0.01); var transaction2 = new Transaction(sender: "John", recipient: "Ivanka", amount: 20, fee: 0.01); var transaction3 = new Transaction(sender: "Robert", recipient: "Antonio", amount: 30, fee: 0.01); // Add transactions to transactions pool blockChain.TransactionsPool.AddTransaction(transaction1); blockChain.TransactionsPool.AddTransaction(transaction2); blockChain.TransactionsPool.AddTransaction(transaction3); // Forging a block - BlockChain will add a new block to the chain and add transactions to it blockChain.AddBlock(); // Create another transactions. transaction1 = new Transaction(sender: "Asen", recipient: "Ivan", amount: 110, fee: 0.01); transaction2 = new Transaction(sender: "Gosho", recipient: "Boqn", amount: 220, fee: 0.01); transaction3 = new Transaction(sender: "Pesho", recipient: "Martin", amount: 330, fee: 0.01); // Add transactions to transactions pool blockChain.TransactionsPool.AddTransaction(transaction1); blockChain.TransactionsPool.AddTransaction(transaction2); blockChain.TransactionsPool.AddTransaction(transaction3); // Forging another block blockChain.AddBlock(); // We have 2 blocks and 6 transactions // Chain explorer will output data from block on console var chainExplorer = new ConsoleChainExplorer(blockChain); chainExplorer.PrintGenesisBlock(); chainExplorer.PrintLastBlock(); chainExplorer.PrintBalance("Robert"); chainExplorer.PrintBalance("Antonio"); chainExplorer.PrintBalance("Martin"); chainExplorer.PrintTransactionHistory("Robert"); chainExplorer.PrintTransactionHistory("Gosho"); chainExplorer.PrintTransactionHistory("Boqn"); Console.WriteLine(); chainExplorer.PrintBlocks(); Console.WriteLine("Press enter to close application"); Console.ReadLine(); }
/// <summary> /// Releases a transaction to the pool. /// If the transaction is poolable, it is released and put back into the pool, otherwise it is removed. /// Throws an <see cref="InvalidTransactionReleaseException"/> if the transaction is not releasable. /// </summary> /// <exception cref="InvalidTransactionReleaseException">Occurs if the transaction is not releasable.</exception> /// <param name="trans">Transaction to be released.</param> public virtual void ReleaseTransaction(IDbTransaction trans) { if (trans == null) { return; } TransactionInfo transInfo = (TransactionInfo)TransactionPool[trans]; if (transInfo != null) { if (!transInfo.IsReleasable) { throw (new InvalidTransactionReleaseException("Cannot release a transaction that was created with \"GetCommitableTransaction\". Use commit or rollback")); } #if DEBUG_DBCONNECTIONPOOLING OSTrace.Info("DBConnectionPooling[TID=" + transInfo.Transaction.GetHashCode() + "] - returned to pool"); OSTrace.Error(new StackTrace().ToString()); #endif if (transInfo.IsPoolable) { transInfo.Release(); } else { TransactionPool.Remove(trans); } } else { try { if (RequestTransactionInfo != null && trans == RequestTransactionInfo.Transaction) { //when releasing the request transaction make sure the connection is ok if (trans.Connection != null && trans.Connection.State != ConnectionState.Open) { LogException(new InvalidTransactionException("Request transaction not open on release."), new StackTrace(), "Request Transaction discarded due to connection not being in a correct state."); //clear and try to dispose connection lock (this) { RequestTransactionInfo = null; } trans.Connection.Dispose(); } else { RequestTransactionInfo.MarkChange(); } } } catch { //this is a best effort } } }
public void CannotAddDuplicatedTransaction() { var pool = new TransactionPool(); var tx = new Transaction() { }; pool.AddTransaction(tx); pool.AddTransaction(tx); pool.AddTransaction(tx); Assert.AreEqual(pool.count, 1); }