public ResultHelper AddBlock(BlockDto blockDto) { try { if (IsThere(blockDto)) { return(new ResultHelper(false, 0, ResultHelper.IsThereItem)); } block item = new block(); item.BlockID = blockDto.BlockID; item.BuildID = blockDto.BuildID; item.Name = blockDto.Name; item.Gps = blockDto.Gps; using (UnitOfWork unitOfWork = new UnitOfWork()) { unitOfWork.GetRepository <block>().Insert(item); unitOfWork.saveChanges(); return(new ResultHelper(true, item.BlockID, ResultHelper.SuccessMessage)); } } catch (Exception ex) { return(new ResultHelper(false, 0, ResultHelper.UnSuccessMessage)); } }
private void CompareAddresses(BlockDto blockDto, List <AddressDto> addressesBefore, List <AddressDto> addressesAfter) { foreach (var before in addressesBefore) { var after = addressesAfter.FirstOrDefault(x => x.AddressId == before.AddressId); Assert.True(after != null); var balanceDelta = blockDto.Transactions .Select(x => x.Inputs.Concat(x.Outputs) .Where(y => y.AddressId == before.AddressId) .Sum(y => y.TransactionInputOutputType == TransactionInputOutputType.Input ? -y.Amount : y.Amount)) .Sum(); var diff = Math.Abs(before.Balance - after.Balance); _output.WriteLine($"\r\nAddress ID {before.AddressId}:"); _output.WriteLine($"prev: {before.Balance}"); _output.WriteLine($"txs: {balanceDelta}"); _output.WriteLine($"new: {after.Balance}"); _output.WriteLine($"diff: {diff}"); _output.WriteLine($"\r\n"); Assert.True(Math.Abs(diff - Math.Abs(balanceDelta)) < 0.000000001); } }
public async Task <Block> InsertBlockAsync(BlockDto blockDto, bool consoleOutput = false) { return((await InsertBlocksAsync(new List <BlockDto>() { blockDto })).FirstOrDefault()); }
public List <BlockDto> GetAllBlockWithByBuildID(int buildID) { try { List <BlockDto> list = new List <BlockDto>(); using (UnitOfWork unitofWork = new UnitOfWork()) { List <block> collection = unitofWork.GetRepository <block>().Select(null, x => x.BuildID == buildID).ToList(); foreach (var item in collection) { BlockDto blockDto = new BlockDto(); blockDto.Name = item.Name; blockDto.BlockID = item.BlockID; blockDto.BuildID = item.BuildID.Value; blockDto.Gps = item.Gps; list.Add(blockDto); } return(list); } } catch (Exception ex) { return(new List <BlockDto>()); } }
private IEnumerable <TransactionDto> BlockToTansactionDtos(BlockDto block) { return(block.data .Split(new[] { lineEndin }, StringSplitOptions.None) .Select(line => TryParseLine(line, block)) .Where(transaction => transaction != null)); }
public ActionResult <BlockDto> GetBlockById([FromHeader] string key, Guid ID) { if (!authHelper1.AuthUser(key)) { logger.LogWarning("Autorizacija korisnika neuspesna"); return(Unauthorized()); } try { BlockDto one = blockingService1.GetBlockById(ID); if (one == null) { logger.LogWarning("Ne postoji nijedno blokiranje korisnika"); return(NotFound()); } logger.LogInformation("Uspesno vracen blokiranje sa prosledjenim ID-em"); return(Ok(one)); } catch (Exception e) { logger.LogError(e.Message); return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } }
public void GetLastBlock() { var block1 = new BlockDto() { index = 1 }; var block2 = new BlockDto() { index = 2 }; var block3 = new BlockDto() { index = 3 }; repository.Save(block3); repository.Save(block1); repository.Save(block2); var lastBlock = repository.TryGetLastBlock(); Assert.Equal(3, lastBlock.index); }
public void AddBlock(string pageGuid, string blockTypeGuid, BlockDto block) { var sb = new StringBuilder(); sb.Append(@" DECLARE @PageId int "); if (string.IsNullOrWhiteSpace(pageGuid)) { sb.Append(@" SET @PageId = NULL "); } else { sb.AppendFormat(@" SET @PageId = (SELECT [Id] FROM [Page] WHERE [Guid] = '{0}') ", pageGuid); } sb.AppendFormat(@" DECLARE @BlockTypeId int DECLARE @EntityTypeId int SET @BlockTypeId = (SELECT [Id] FROM [BlockType] WHERE [Guid] = '{0}') SET @EntityTypeId = (SELECT [Id] FROM [EntityType] WHERE [Guid] = 'B2DE7D41-EA40-42A9-B212-9DD2ADE2DDAE') DECLARE @BlockId int INSERT INTO [Block] ( [IsSystem],[PageId],[Layout],[BlockTypeId],[Zone], [Order],[Name],[OutputCacheDuration], [Guid]) VALUES( {1},@PageId,{2},@BlockTypeId,'{3}', {4},'{5}',{6}, '{7}') SET @BlockId = SCOPE_IDENTITY() ", blockTypeGuid, block.IsSystem.Bit(), block.Layout == null ? "NULL" : "'" + block.Layout + "'", block.Zone, block.Order, block.Name, block.OutputCacheDuration, block.Guid); // If adding a layout block, give edit/configuration authorization to admin role if (string.IsNullOrWhiteSpace(pageGuid)) { sb.Append(@" INSERT INTO [Auth] ([EntityTypeId],[EntityId],[Order],[Action],[AllowOrDeny],[SpecialRole],[PersonId],[GroupId],[Guid]) VALUES(@EntityTypeId,@BlockId,0,'Edit','A',0,NULL,2,NEWID()) INSERT INTO [Auth] ([EntityTypeId],[EntityId],[Order],[Action],[AllowOrDeny],[SpecialRole],[PersonId],[GroupId],[Guid]) VALUES(@EntityTypeId,@BlockId,0,'Configure','A',0,NULL,2,NEWID()) "); } Sql(sb.ToString()); }
public ActionResult Edit(BlockDto model) { ResultHelper result = JsonConvert.DeserializeObject <ResultHelper>(blockService.SetBlock(model)); ViewBag.Message = Helper.GetResultMessage(result.Result, result.ResultDescription); GetBuilds(); return(View()); }
/// <summary> /// Get information about a given block by block hash. Otionally with the list of its transactions. /// </summary> /// <param name="blockHash">block hash</param> /// <param name="includeTransactions">include transactions or not</param> /// <returns></returns> public async Task <BlockDto> GetBlockAsync(string blockHash, bool includeTransactions = false) { Hash realBlockHash; try { realBlockHash = HashHelper.HexStringToHash(blockHash); } catch { throw new UserFriendlyException(Error.Message[Error.InvalidBlockHash], Error.InvalidBlockHash.ToString()); } var block = await GetBlockAsync(realBlockHash); if (block == null) { throw new UserFriendlyException(Error.Message[Error.NotFound], Error.NotFound.ToString()); } var blockDto = new BlockDto { BlockHash = block.GetHash().ToHex(), Header = new BlockHeaderDto { PreviousBlockHash = block.Header.PreviousBlockHash.ToHex(), MerkleTreeRootOfTransactions = block.Header.MerkleTreeRootOfTransactions.ToHex(), MerkleTreeRootOfWorldState = block.Header.MerkleTreeRootOfWorldState.ToHex(), Extra = block.Header.ExtraData.ToString(), Height = block.Header.Height, Time = block.Header.Time.ToDateTime(), ChainId = ChainHelper.ConvertChainIdToBase58(block.Header.ChainId), Bloom = block.Header.Bloom.ToByteArray().ToHex(), SignerPubkey = block.Header.SignerPubkey.ToByteArray().ToHex() }, Body = new BlockBodyDto() { TransactionsCount = block.Body.TransactionsCount, Transactions = new List <string>() } }; if (includeTransactions) { var transactions = block.Body.TransactionIds; var txs = new List <string>(); foreach (var transactionId in transactions) { txs.Add(transactionId.ToHex()); } blockDto.Body.Transactions = txs; } return(blockDto); }
public async Task <BlockDto> GetBlockByIdAsync(Guid id) { BlockDto block = BlockConverter.Convert(await _blockRepo.GetByIdAsync(id)); block.BlockTypeName = _blockTypeRepo.GetByIdAsync(block.BlockTypeId).Result.Name; block.PageName = _pageRepo.GetByIdAsync(block.PageId).Result.Name; block.Questions = QuestionConverter.Convert(await _questionRepo.GetByBlockIdAsync(id)); return(block); }
public void RemoveAllCoins() { var block = new BlockDto(); repository.Save(block); repository.DeleteAll(); Assert.Equal(0, repository.GetAll().Count); }
private async Task AggregateAddresses(Block block, BlockDto blockDto) { var addressesBefore = await GetAddressesAsync(block); await _fixture.AddressAggregator.AggregateAddressesAsync(blockDto); var addressesAfter = await GetAddressesAsync(block); CompareAddresses(blockDto, addressesBefore, addressesAfter); }
public BlockDto DefaultSystemBlock(string name, Guid guid) { var block = new BlockDto(); block.IsSystem = true; block.Zone = "Content"; block.Name = name; block.Guid = guid; return(block); }
public void Save(BlockDto block) { var collection = _collection; if (block.createdTimeStampUtc == null) { block.createdTimeStampUtc = DateTime.UtcNow; } collection.InsertOne(block); }
public async Task <BlockDto> GetBlockByNumber(string number) { string url = $"/v1/block/height/{number}"; using HttpResponseMessage response = await _client.GetAsync(url).ConfigureAwait(false); response.EnsureSuccessStatusCode(); BlockDto result = await response.Content.ReadAsAsync <BlockDto>().ConfigureAwait(false); return(result); }
public static Block Convert(BlockDto item) { return(new Block { BlockTypeId = item.BlockTypeId, Id = item.Id, Img = item.Img, LoadImg = item.LoadImg, Name = item.Name, PageId = item.PageId, Text = item.Text }); }
public bool AddBlockIntoBlockChain(BlockDto newBlockDto) { newBlockDto.PreviousHash = GetLatestBlock().Hash; newBlockDto.mineBlock(difficulty); blockChainDto.BlockChain.Add(newBlockDto); //if the new block does not validate the chain remove from the chain if (isChainValid() != true) { blockChainDto.BlockChain.Remove(newBlockDto); return(false); } return(true); }
public async Task AddAsync(BlockDto block) { if (block == null) { return; } await _redisCommand.SetAsync(Settings.Redis.BuildBlockCacheKey(block.Height), block); await _redisCommand.SetAsync(Settings.Redis.ChainHeight, block.Height); await _redisCommand.DeleteAsync(Settings.Redis.BuildBlockCacheKey(block.Height - Settings.App.BlockCacheSize)); }
private async Task AggregateAddressesAsync(BlockDto blockDto) { var stopwatch = new Stopwatch(); Logger.LogInformation($"Syncing address from block {blockDto.Height}..."); stopwatch.Start(); await _addressAggregator.AggregateAddressesAsync(blockDto); stopwatch.Stop(); Logger.LogInformation($"Address synced in {stopwatch.Elapsed:g}"); }
public void Move(int id, BlockDto block) { var user = CurrentUser(); if (user != null) { var service = new BlockService(); Block model; if (!service.TryGet(id, out model)) { throw new HttpResponseException(HttpStatusCode.NotFound); } if (!model.IsAuthorized("Edit", user.Person)) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } if (model.IsValid) { if (model.Layout != null && model.Layout != block.Layout) { Rock.Web.Cache.PageCache.FlushLayoutBlocks(model.Layout); } if (block.Layout != null) { Rock.Web.Cache.PageCache.FlushLayoutBlocks(block.Layout); } else { var page = Rock.Web.Cache.PageCache.Read(block.PageId.Value); page.FlushBlocks(); } block.CopyToModel(model); service.Move(model); service.Save(model, user.PersonId); } else { throw new HttpResponseException(HttpStatusCode.BadRequest); } } else { throw new HttpResponseException(HttpStatusCode.Unauthorized); } }
public void SaveCoin() { var block = new BlockDto() { index = 10 }; repository.Save(block); var allBlocks = repository.GetAll(); Assert.Equal(1, allBlocks.Count); Assert.Equal(10, allBlocks[0].index); }
public Result <Block> ImportBlock(BlockDto blockDto) { using (var uow = NewUnitOfWork(UnitOfWorkMode.Writable)) { var blockRepo = NewRepository <Block>(uow); if (blockRepo.Exists(b => b.BlockNumber == blockDto.Number)) { return(Result.Failure <Block>("Block {0} already exists.".F(blockDto.Number))); } var block = new Block { BlockNumber = blockDto.Number, Hash = blockDto.Hash, PreviousBlockHash = blockDto.PreviousBlockHash, ConfigurationBlockNumber = blockDto.ConfigurationBlockNumber, Timestamp = blockDto.Timestamp, TxSetRoot = blockDto.TxSetRoot, TxResultSetRoot = blockDto.TxResultSetRoot, EquivocationProofsRoot = blockDto.EquivocationProofsRoot, EquivocationProofResultsRoot = blockDto.EquivocationProofResultsRoot, StateRoot = blockDto.StateRoot, StakingRewardsRoot = blockDto.StakingRewardsRoot, ConfigurationRoot = blockDto.ConfigurationRoot, Configuration = JsonConvert.SerializeObject(blockDto.Configuration), ConsensusRound = blockDto.ConsensusRound, Signatures = string.Join(';', blockDto.Signatures) }; var previousBlockId = blockRepo .GetAs(b => b.Hash == blockDto.PreviousBlockHash, b => b.BlockId) .SingleOrDefault(); if (previousBlockId != default(long)) { block.PreviousBlockId = previousBlockId; } block.ValidatorId = NewRepository <Validator>(uow) .GetAs(v => v.BlockchainAddress == blockDto.ProposerAddress, v => v.ValidatorId) .SingleOrDefault(); blockRepo.Insert(block); uow.Commit(); return(Result.Success(block)); } }
public bool IsThere(BlockDto blockDto) { using (UnitOfWork unitofWork = new UnitOfWork()) { var item = unitofWork.GetRepository <block>().GetById(x => x.BuildID == blockDto.BuildID && x.Name == blockDto.Name); if (item != null) { return(true); } else { return(false); } } }
private bool isChainValid() { //the first block will be a gensis block that's why start from 1 instead of 0 for (int i = 1; i < this.blockChainDto.BlockChain.Count(); i++) { BlockDto currentBlock = this.blockChainDto.BlockChain[i]; BlockDto previousBlock = this.blockChainDto.BlockChain[i - 1]; if (currentBlock.PreviousHash != previousBlock.Hash) { return(false); } } return(true); }
public async Task <ActionResult <BlockDto> > Post([FromBody] BlockDto item) { try { if (item == null) { return(BadRequest()); } return(Ok(await _supervisor.CreateBlockAsync(item))); } catch (Exception ex) { return(StatusCode(500, ex)); } }
/// <summary> /// Get information about a given block by block height. Otionally with the list of its transactions. /// </summary> /// <param name="blockHeight">block height</param> /// <param name="includeTransactions">include transactions or not</param> /// <returns></returns> public async Task <BlockDto> GetBlockByHeight(long blockHeight, bool includeTransactions = false) { if (blockHeight == 0) { throw new UserFriendlyException(Error.Message[Error.NotFound], Error.NotFound.ToString()); } var blockInfo = await GetBlockAtHeight(blockHeight); if (blockInfo == null) { throw new UserFriendlyException(Error.Message[Error.NotFound], Error.NotFound.ToString()); } var blockDto = new BlockDto { BlockHash = blockInfo.GetHash().ToHex(), Header = new BlockHeaderDto { PreviousBlockHash = blockInfo.Header.PreviousBlockHash.ToHex(), MerkleTreeRootOfTransactions = blockInfo.Header.MerkleTreeRootOfTransactions.ToHex(), MerkleTreeRootOfWorldState = blockInfo.Header.MerkleTreeRootOfWorldState.ToHex(), Extra = blockInfo.Header.BlockExtraDatas.ToString(), Height = blockInfo.Header.Height, Time = blockInfo.Header.Time.ToDateTime(), ChainId = ChainHelpers.ConvertChainIdToBase58(blockInfo.Header.ChainId), Bloom = blockInfo.Header.Bloom.ToByteArray().ToHex() }, Body = new BlockBodyDto() { TransactionsCount = blockInfo.Body.TransactionsCount, Transactions = new List <string>() } }; if (includeTransactions) { var transactions = blockInfo.Body.Transactions; var txs = new List <string>(); foreach (var txHash in transactions) { txs.Add(txHash.ToHex()); } blockDto.Body.Transactions = txs; } return(blockDto); }
private async Task AddBlockAsync(BlockDto blockDto) { var stopwatch = new Stopwatch(); stopwatch.Start(); var block = await _blockInsert.InsertBlockAsync(blockDto); if (block == null) { throw new NullReferenceException("Something failed inserting the new block"); } stopwatch.Stop(); Logger.LogInformation($"Block {block.Height} synced in {stopwatch.Elapsed:g}"); }
public async Task <ActionResult <List <AdministrationDto> > > GetByBlock(Guid id) { try { BlockDto block = await _supervisor.GetBlockByIdAsync(id); if (block == null) { return(NotFound()); } return(Ok(await _supervisor.GetQuestionByBlockIdAsync(id))); } catch (Exception ex) { return(StatusCode(500, ex)); } }
private BlockDto CreateBlockDto(Block block, bool includeTransactions) { if (block == null) { throw new UserFriendlyException(Error.Message[Error.NotFound], Error.NotFound.ToString()); } var bloom = block.Header.Bloom; var blockDto = new BlockDto { BlockHash = block.GetHash().ToHex(), Header = new BlockHeaderDto { PreviousBlockHash = block.Header.PreviousBlockHash.ToHex(), MerkleTreeRootOfTransactions = block.Header.MerkleTreeRootOfTransactions.ToHex(), MerkleTreeRootOfWorldState = block.Header.MerkleTreeRootOfWorldState.ToHex(), MerkleTreeRootOfTransactionState = block.Header.MerkleTreeRootOfTransactionStatus.ToHex(), Extra = block.Header.ExtraData.ToString(), Height = block.Header.Height, Time = block.Header.Time.ToDateTime(), ChainId = ChainHelper.ConvertChainIdToBase58(block.Header.ChainId), Bloom = bloom.Length == 0 ? ByteString.CopyFrom(new byte[256]).ToBase64(): bloom.ToBase64(), SignerPubkey = block.Header.SignerPubkey.ToByteArray().ToHex() }, Body = new BlockBodyDto() { TransactionsCount = block.Body.TransactionsCount, Transactions = new List <string>() } }; if (!includeTransactions) { return(blockDto); } var transactions = block.Body.TransactionIds; var txs = new List <string>(); foreach (var transactionId in transactions) { txs.Add(transactionId.ToHex()); } blockDto.Body.Transactions = txs; return(blockDto); }