//Check whether output has been spent or contained in another transaction, true = spent, false = unspent private bool checkOutputSpent(string currentTxHash, string outputTxHash, int outputIndex) { var outputDac = new OutputDac(); var inputDac = new InputDac(); var txDac = new TransactionDac(); var blockDac = new BlockDac(); var outputEntity = outputDac.SelectByHashAndIndex(outputTxHash, outputIndex); var inputEntity = inputDac.SelectByOutputHash(outputTxHash, outputIndex); if (inputEntity != null && inputEntity.TransactionHash != currentTxHash) { var tx = txDac.SelectByHash(inputEntity.TransactionHash); if (tx != null) { var blockEntity = blockDac.SelectByHash(tx.BlockHash); if (blockEntity != null && blockEntity.IsVerified) { return(true); } } } return(false); }
public List <BlockHeaderMsg> GetBlockHeaderMsgByHeights(List <long> heights) { var blockDac = new BlockDac(); var txDac = new TransactionDac(); var headers = new List <BlockHeaderMsg>(); foreach (var height in heights) { var items = blockDac.SelectByHeight(height); foreach (var entity in items) { var header = new BlockHeaderMsg(); header.Version = entity.Version; header.Hash = entity.Hash; header.Height = entity.Height; header.PreviousBlockHash = entity.PreviousBlockHash; header.Bits = entity.Bits; header.Nonce = entity.Nonce; header.Timestamp = entity.Timestamp; var transactions = txDac.SelectByBlockHash(entity.Hash); header.TotalTransaction = entity.Transactions == null ? 0 : entity.Transactions.Count; headers.Add(header); } } return(headers); }
/// <summary> /// 获取区块总的奖励 /// </summary> /// <param name="blockHash"></param> /// <returns></returns> public long GetBlockReward(string blockHash) { //总的奖励分为两部分,一部分挖矿所得,一部分区块中交易手续费 BlockDac dac = new BlockDac(); Block block = dac.SelectByHash(blockHash); long miningAward = block.TotalAmount; long totalfee = block.TotalFee; return(miningAward + totalfee); }
private bool exists(string blockHash) { var blockDac = new BlockDac(); if (blockDac.SelectByHash(blockHash) != null) { return(true); } return(false); }
public long GetLatestConfirmedHeight() { var dac = new BlockDac(); var block = dac.SelectLastConfirmed(); if (block != null) { return(block.Height); } else { return(-1); } }
public BlockMsg GetBlockMsgByHeight(long height) { var blockDac = new BlockDac(); var txDac = new TransactionDac(); BlockMsg block = null; var items = blockDac.SelectByHeight(height); if (items.Count > 0) { block = this.convertEntityToBlockMsg(items[0]); } return(block); }
public BlockMsg GetBlockMsgByHash(string hash) { var blockDac = new BlockDac(); var txDac = new TransactionDac(); BlockMsg block = null; var entity = blockDac.SelectByHash(hash); if (entity != null) { block = this.convertEntityToBlockMsg(entity); } return(block); }
public List <BlockMsg> GetBlockMsgByHeights(List <long> heights) { var blockDac = new BlockDac(); var txDac = new TransactionDac(); var inputDac = new InputDac(); var outputDac = new OutputDac(); var blocks = new List <BlockMsg>(); foreach (var height in heights) { var items = blockDac.SelectByHeight(height); foreach (var entity in items) { blocks.Add(this.convertEntityToBlockMsg(entity)); } } return(blocks); }
//check whether output is existed. get amount and lockscript from output. private bool getOutput(string transactionHash, int outputIndex, out long outputAmount, out string lockScript, out long blockHeight) { var outputDac = new OutputDac(); var outputEntity = outputDac.SelectByHashAndIndex(transactionHash, outputIndex); if (outputEntity == null) { long height = -1; var outputMsg = TransactionPool.Instance.GetOutputMsg(transactionHash, outputIndex); if (outputMsg != null) { outputAmount = outputMsg.Amount; lockScript = outputMsg.LockScript; blockHeight = height; return(true); } } else { outputAmount = outputEntity.Amount; lockScript = outputEntity.LockScript; var tx = new TransactionDac().SelectByHash(outputEntity.TransactionHash); if (tx != null) { var blockEntity = new BlockDac().SelectByHash(tx.BlockHash); blockHeight = blockEntity.Height; return(true); } } outputAmount = 0; lockScript = null; blockHeight = -1; return(false); }
public List <BlockHeaderMsg> GetBlockHeaderMsgByHeights(List <long> heights) { var blockDac = new BlockDac(); var txDac = new TransactionDac(); var headers = new List <BlockHeaderMsg>(); foreach (var height in heights) { var items = blockDac.SelectByHeight(height); foreach (var entity in items) { var header = new BlockHeaderMsg(); header.Version = entity.Version; header.Hash = entity.Hash; header.Height = entity.Height; header.PreviousBlockHash = entity.PreviousBlockHash; header.Bits = entity.Bits; header.Nonce = entity.Nonce; header.Timestamp = entity.Timestamp; header.GeneratorId = entity.GeneratorId; //header.GenerationSignature = entity.GenerationSignature; //header.BlockSignature = entity.BlockSignature; //header.CumulativeDifficulty = entity.CumulativeDifficulty; header.PayloadHash = entity.PayloadHash; header.BlockSignature = entity.BlockSignature; header.BlockSigSize = entity.BlockSignature.Length; var transactions = txDac.SelectByBlockHash(entity.Hash); header.TotalTransaction = entity.Transactions == null ? 0 : entity.Transactions.Count; headers.Add(header); } } return(headers); }
public Dictionary <Block, long> GetChainTips() { var dac = new BlockDac(); var blocks = dac.SelectTipBlocks(); var dict = new Dictionary <Block, long>(); if (blocks.Count == 1) { dict.Add(blocks[0], 0); } else { var maxLength = 0; Block maxBlock = null; foreach (var block in blocks) { var len = dac.CountBranchLength(block.Hash); if (len > maxLength) { len = maxLength; maxBlock = block; } dict.Add(block, len); } if (maxBlock != null && dict.ContainsKey(maxBlock)) { dict[maxBlock] = 0; } } return(dict); }
//public List<UtxoMsg> GetAllConfirmedOutputs() //{ // return UtxoSet.Instance.GetAllUnspentOutputs(); //} public List <UtxoMsg> GetAllConfirmedOutputs() { List <UtxoMsg> utxoMsgs = new List <UtxoMsg>(); var outputDac = new OutputDac(); var txDac = new TransactionDac(); var blockDac = new BlockDac(); var accountDac = new AccountDac(); var lastHeight = -1L; var lastBlock = blockDac.SelectLast(); if (lastBlock != null) { lastHeight = lastBlock.Height; } var outputs = outputDac.SelectAllUnspentOutputs(); foreach (var output in outputs) { var msg = new UtxoMsg(); msg.AccountId = output.ReceiverId; msg.TransactionHash = output.TransactionHash; msg.OutputIndex = output.Index; msg.Amount = output.Amount; msg.IsConfirmed = true; var account = accountDac.SelectById(msg.AccountId); msg.IsWatchedOnly = account.WatchedOnly; var txEntity = txDac.SelectByHash(output.TransactionHash); msg.BlockHash = txEntity != null ? txEntity.BlockHash : null; utxoMsgs.Add(msg); } return(utxoMsgs); }
public BlockMsg CreateNewBlock(string minerName, string accountId = null) { var accountDac = new AccountDac(); var blockDac = new BlockDac(); var outputDac = new OutputDac(); var txDac = new TransactionDac(); var txPool = TransactionPool.Instance; var transactionMsgs = new List <TransactionMsg>(); long lastBlockHeight = -1; string lastBlockHash = Base16.Encode(HashHelper.EmptyHash()); long lastBlockBits = -1; var blockEntity = blockDac.SelectLast(); if (blockEntity != null) { lastBlockHeight = blockEntity.Height; lastBlockHash = blockEntity.Hash; lastBlockBits = blockEntity.Bits; } long totalSize = 0; long maxSize = BlockSetting.MAX_BLOCK_SIZE - (500 * 1024); var poolItemList = txPool.MainPool.OrderByDescending(t => t.FeeRate).ToList(); var index = 0; while (totalSize < maxSize && index < poolItemList.Count) { var tx = poolItemList[index].Transaction; if (tx != null && transactionMsgs.Where(t => t.Hash == tx.Hash).Count() == 0) { if (txDac.SelectByHash(tx.Hash) == null) { transactionMsgs.Add(tx); totalSize += tx.Size; } else { txPool.RemoveTransaction(tx.Hash); } } else { break; } index++; } var minerAccount = accountDac.SelectDefaultAccount(); if (accountId != null) { var account = accountDac.SelectById(accountId); if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey)) { minerAccount = account; } } BlockMsg newBlockMsg = new BlockMsg(); BlockHeaderMsg headerMsg = new BlockHeaderMsg(); newBlockMsg.Header = headerMsg; headerMsg.Height = lastBlockHeight + 1; headerMsg.PreviousBlockHash = lastBlockHash; long totalAmount = 0; long totalFee = 0; foreach (var tx in transactionMsgs) { long totalInputsAmount = 0L; long totalOutputAmount = 0L; foreach (var input in tx.Inputs) { var utxo = outputDac.SelectByHashAndIndex(input.OutputTransactionHash, input.OutputIndex); if (utxo != null) { totalInputsAmount += utxo.Amount; } } foreach (var output in tx.Outputs) { totalOutputAmount += output.Amount; } totalAmount += totalOutputAmount; totalFee += (totalInputsAmount - totalOutputAmount); } var work = new POW(headerMsg.Height); BlockMsg previous4032Block = null; if (headerMsg.Height > POW.DiffiucltyAdjustStep) { previous4032Block = this.GetBlockMsgByHeight(headerMsg.Height - POW.DiffiucltyAdjustStep); } var newBlockReward = work.GetNewBlockReward(); headerMsg.Bits = work.CalculateNextWorkTarget(lastBlockHeight, lastBlockBits, previous4032Block); headerMsg.TotalTransaction = transactionMsgs.Count + 1; var coinbaseTxMsg = new TransactionMsg(); coinbaseTxMsg.Timestamp = Time.EpochTime; coinbaseTxMsg.Locktime = 0; var coinbaseInputMsg = new InputMsg(); coinbaseTxMsg.Inputs.Add(coinbaseInputMsg); coinbaseInputMsg.OutputIndex = 0; coinbaseInputMsg.OutputTransactionHash = Base16.Encode(HashHelper.EmptyHash()); coinbaseInputMsg.UnlockScript = Script.BuildMinerScript(minerName); coinbaseInputMsg.Size = coinbaseInputMsg.UnlockScript.Length; var coinbaseOutputMsg = new OutputMsg(); coinbaseTxMsg.Outputs.Add(coinbaseOutputMsg); coinbaseOutputMsg.Amount = newBlockReward + totalFee; coinbaseOutputMsg.LockScript = Script.BuildLockScipt(minerAccount.Id); coinbaseOutputMsg.Size = coinbaseOutputMsg.LockScript.Length; coinbaseOutputMsg.Index = 0; coinbaseTxMsg.Hash = coinbaseTxMsg.GetHash(); newBlockMsg.Transactions.Insert(0, coinbaseTxMsg); foreach (var tx in transactionMsgs) { newBlockMsg.Transactions.Add(tx); } return(newBlockMsg); }
public ListSinceBlock ListSinceBlock(string blockHash, long heightLength, long confirmations) { BlockDac dac = new BlockDac(); return(dac.GetSinceBlock(blockHash, heightLength, confirmations)); }
public List <Block> GetVerifiedHashes(List <string> hashes) { BlockDac dac = new BlockDac(); return(dac.DistinguishBlockVerifiedByHashes(hashes)); }
public void ProcessUncsonfirmedBlocks() { var blockDac = new BlockDac(); var txDac = new TransactionDac(); var txComponent = new TransactionComponent(); var utxoComponent = new UtxoComponent(); long lastHeight = this.GetLatestHeight(); long confirmedHeight = -1; var confirmedBlock = blockDac.SelectLastConfirmed(); var confirmedHash = Base16.Encode(HashHelper.EmptyHash()); if (confirmedBlock != null) { confirmedHeight = confirmedBlock.Height; confirmedHash = confirmedBlock.Hash; } if (lastHeight - confirmedHeight >= 6) { var blocks = blockDac.SelectByPreviousHash(confirmedHash); if (blocks.Count == 1) { blockDac.UpdateBlockStatusToConfirmed(blocks[0].Hash); this.ProcessUncsonfirmedBlocks(); } else if (blocks.Count > 1) { var countOfDescendants = new Dictionary <string, long>(); foreach (var block in blocks) { var count = blockDac.CountOfDescendants(block.Hash); if (!countOfDescendants.ContainsKey(block.Hash)) { countOfDescendants.Add(block.Hash, count); } } var dicSort = countOfDescendants.OrderBy(d => d.Value).ToList(); var lastItem = blocks.Where(b => b.Hash == dicSort[dicSort.Count - 1].Key).First(); var index = 0; while (index < dicSort.Count - 1) { var currentItem = blocks.Where(b => b.Hash == dicSort[index].Key).First(); if (lastHeight - currentItem.Height >= 6) { var txList = txDac.SelectByBlockHash(currentItem.Hash); //Skip coinbase tx for (int i = 1; i < txList.Count; i++) { var tx = txList[i]; var txMsg = txComponent.ConvertTxEntityToMsg(tx); txComponent.AddTransactionToPool(txMsg); } //remove coinbase from utxo UtxoSet.Instance.RemoveUtxoRecord(txList[0].Hash, 0); blockDac.UpdateBlockStatusToDiscarded(currentItem.Hash); index++; } else { break; } } if (dicSort.Count - index <= 1) { blockDac.UpdateBlockStatusToConfirmed(lastItem.Hash); this.ProcessUncsonfirmedBlocks(); } } } }
public void GetBalanceInDB(out long confirmedBalance, out long unconfirmedBalance) { //return new OutputDac().SumSelfUnspentOutputs(); confirmedBalance = 0; unconfirmedBalance = 0; var outputDac = new OutputDac(); var txDac = new TransactionDac(); var blockDac = new BlockDac(); var lastHeight = -1L; var lastBlock = blockDac.SelectLast(); if (lastBlock != null) { lastHeight = lastBlock.Height; } var outputs = outputDac.SelectAllUnspentOutputs(); foreach (var output in outputs) { var tx = txDac.SelectByHash(output.TransactionHash); if (tx != null) { var block = blockDac.SelectByHash(tx.BlockHash); if (block != null) { if (tx.TotalInput == 0) { //coinbase if (lastHeight - block.Height >= 100) { confirmedBalance += output.Amount; } else { unconfirmedBalance += output.Amount; } } else { if (block.IsVerified) { if (Time.EpochTime >= tx.LockTime) { confirmedBalance += output.Amount; } else { unconfirmedBalance += output.Amount; } } else { unconfirmedBalance += output.Amount; } } } } } }
public void SaveBlockIntoDB(BlockMsg msg) { try { VerifyBlock(msg); Block block = this.convertBlockMsgToEntity(msg); block.IsDiscarded = false; block.IsVerified = false; var blockDac = new BlockDac(); var transactionDac = new TransactionDac(); var inputDac = new InputDac(); var outputDac = new OutputDac(); //foreach (var tx in block.Transactions) //{ // foreach (var input in tx.Inputs) // { // if (input.OutputTransactionHash != Base16.Encode(HashHelper.EmptyHash())) // { // var output = outputDac.SelectByHashAndIndex(input.OutputTransactionHash, input.OutputIndex); // if (output != null) // { // input.AccountId = output.ReceiverId; // outputDac.UpdateSpentStatus(input.OutputTransactionHash, input.OutputIndex); // } // } // } //} blockDac.Save(block); //update nextblock hash //blockDac.UpdateNextBlockHash(block.PreviousBlockHash, block.Hash); //remove transactions in tx pool foreach (var tx in block.Transactions) { TransactionPool.Instance.RemoveTransaction(tx.Hash); //save into utxo set foreach (var output in tx.Outputs) { var accountId = AccountIdHelper.CreateAccountAddressByPublicKeyHash( Base16.Decode( Script.GetPublicKeyHashFromLockScript(output.LockScript) ) ); UtxoSet.Instance.AddUtxoRecord(new UtxoMsg { AccountId = accountId, BlockHash = block.Hash, TransactionHash = tx.Hash, OutputIndex = output.Index, Amount = output.Amount, IsConfirmed = true }); } } } catch (Exception ex) { LogHelper.Error(ex.Message, ex); throw ex; } }
/// <summary> /// 创建新的区块 /// </summary> /// <param name="minerName"></param> /// <param name="generatorId"></param> /// <param name="accountId"></param> /// <returns></returns> public BlockMsg CreateNewBlock(string minerName, string generatorId, string remark = null, string accountId = null) { var accountDac = new AccountDac(); var blockDac = new BlockDac(); var outputDac = new OutputDac(); var txDac = new TransactionDac(); var txPool = TransactionPool.Instance; var transactionMsgs = new List <TransactionMsg>(); long lastBlockHeight = -1; string lastBlockHash = Base16.Encode(HashHelper.EmptyHash()); long lastBlockBits = -1; string lastBlockGenerator = null; //获取最后一个区块 var blockEntity = blockDac.SelectLast(); if (blockEntity != null) { lastBlockHeight = blockEntity.Height; lastBlockHash = blockEntity.Hash; lastBlockBits = blockEntity.Bits; lastBlockGenerator = blockEntity.GeneratorId; } long totalSize = 0; long maxSize = BlockSetting.MAX_BLOCK_SIZE - (1 * 1024); var poolItemList = txPool.MainPool.OrderByDescending(t => t.FeeRate).ToList(); var index = 0; while (totalSize < maxSize && index < poolItemList.Count) { var tx = poolItemList[index].Transaction; if (tx != null && transactionMsgs.Where(t => t.Hash == tx.Hash).Count() == 0) { if (txDac.SelectByHash(tx.Hash) == null) { transactionMsgs.Add(tx); totalSize += tx.Size; } else { txPool.RemoveTransaction(tx.Hash); } } else { break; } index++; } var minerAccount = accountDac.SelectDefaultAccount(); if (accountId != null) { var account = accountDac.SelectById(accountId); if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey)) { minerAccount = account; } } var minerAccountId = minerAccount.Id; BlockMsg newBlockMsg = new BlockMsg(); BlockHeaderMsg headerMsg = new BlockHeaderMsg(); headerMsg.Hash = Base16.Encode(HashHelper.EmptyHash()); headerMsg.GeneratorId = generatorId; newBlockMsg.Header = headerMsg; headerMsg.Height = lastBlockHeight + 1; headerMsg.PreviousBlockHash = lastBlockHash; if (headerMsg.Height == 0) { minerAccountId = BlockSetting.GenesisBlockReceiver; remark = BlockSetting.GenesisBlockRemark; } long totalAmount = 0; long totalFee = 0; foreach (var tx in transactionMsgs) { long totalInputsAmount = 0L; long totalOutputAmount = 0L; foreach (var input in tx.Inputs) { var utxo = outputDac.SelectByHashAndIndex(input.OutputTransactionHash, input.OutputIndex); if (utxo != null) { totalInputsAmount += utxo.Amount; } } foreach (var output in tx.Outputs) { totalOutputAmount += output.Amount; } totalAmount += totalOutputAmount; totalFee += (totalInputsAmount - totalOutputAmount); } //var work = new POW(headerMsg.Height); BlockMsg prevBlockMsg = null; BlockMsg prevStepBlockMsg = null; if (blockEntity != null) { prevBlockMsg = this.convertEntityToBlockMsg(blockEntity); } if (headerMsg.Height >= POC.DIFFIUCLTY_ADJUST_STEP) { prevStepBlockMsg = this.GetBlockMsgByHeight(headerMsg.Height - POC.DIFFIUCLTY_ADJUST_STEP - 1); } var newBlockReward = POC.GetNewBlockReward(headerMsg.Height); headerMsg.Bits = POC.CalculateBaseTarget(headerMsg.Height, prevBlockMsg, prevStepBlockMsg); headerMsg.TotalTransaction = transactionMsgs.Count + 1; var coinbaseTxMsg = new TransactionMsg(); coinbaseTxMsg.Timestamp = Time.EpochTime; coinbaseTxMsg.Locktime = 0; var coinbaseInputMsg = new InputMsg(); coinbaseTxMsg.Inputs.Add(coinbaseInputMsg); coinbaseInputMsg.OutputIndex = 0; coinbaseInputMsg.OutputTransactionHash = Base16.Encode(HashHelper.EmptyHash()); coinbaseInputMsg.UnlockScript = Script.BuildMinerScript(minerName, remark); coinbaseInputMsg.Size = coinbaseInputMsg.UnlockScript.Length; var coinbaseOutputMsg = new OutputMsg(); coinbaseTxMsg.Outputs.Add(coinbaseOutputMsg); coinbaseOutputMsg.Amount = newBlockReward + totalFee; coinbaseOutputMsg.LockScript = Script.BuildLockScipt(minerAccountId); coinbaseOutputMsg.Size = coinbaseOutputMsg.LockScript.Length; coinbaseOutputMsg.Index = 0; coinbaseTxMsg.Hash = coinbaseTxMsg.GetHash(); newBlockMsg.Transactions.Insert(0, coinbaseTxMsg); foreach (var tx in transactionMsgs) { newBlockMsg.Transactions.Add(tx); } headerMsg.PayloadHash = newBlockMsg.GetPayloadHash(); var dsa = ECDsa.ImportPrivateKey(Base16.Decode(minerAccount.PrivateKey)); var signResult = dsa.SingnData(Base16.Decode(headerMsg.PayloadHash)); headerMsg.BlockSignature = Base16.Encode(signResult); headerMsg.BlockSigSize = headerMsg.BlockSignature.Length; headerMsg.TotalTransaction = newBlockMsg.Transactions.Count; return(newBlockMsg); }