Skip to content

Commit

Permalink
Merge pull request #118 from pingpongsneak/master
Browse files Browse the repository at this point in the history
RC 1 fixes
  • Loading branch information
pingpongsneak committed Oct 11, 2022
2 parents 9da0b5f + f46e02a commit 84a1bfb
Show file tree
Hide file tree
Showing 25 changed files with 407 additions and 347 deletions.
4 changes: 1 addition & 3 deletions core/Controllers/BlockController.cs
Expand Up @@ -156,9 +156,7 @@ public async Task<IActionResult> GetBlockHeightAsync()
{
try
{
var blockCountResponse =
await _cypherNetworkCore.Graph().GetBlockCountAsync();
return new ObjectResult(new { height = blockCountResponse?.Count });
return new ObjectResult(new { height = _cypherNetworkCore.UnitOfWork().HashChainRepository.Count });
}
catch (Exception ex)
{
Expand Down
4 changes: 2 additions & 2 deletions core/Extensions/AppExtensions.cs
Expand Up @@ -79,7 +79,7 @@ public static ContainerBuilder AddCypherSystemCore(this ContainerBuilder builder
Thumbprint = configuration["Node:Network:X509Certificate:Thumbprint"],
CertPath = configuration["Node:Network:X509Certificate:CertPath"]
},
TransactionRateConfig = new TransactionLeakRateConfigurationOption
MemoryPoolTransactionRateLimit = new TransactionLeakRateConfigurationOption
{
LeakRate =
Convert.ToInt32(
Expand Down Expand Up @@ -107,7 +107,7 @@ public static ContainerBuilder AddCypherSystemCore(this ContainerBuilder builder
var endpoint = Util.GetIpEndPoint(selection.item.Value);
var endpointFromHost = Util.GetIpEndpointFromHostPort(endpoint.Address.ToString(), endpoint.Port);
var publicKey = remotePublicKeys[selection.index].Value;
node.Network.SeedList.Add($"{endpointFromHost.Address}:{endpointFromHost.Port}");
node.Network.SeedList.Add($"{endpointFromHost.Address.ToString()}:{endpointFromHost.Port}");
node.Network.SeedListPublicKeys.Add(publicKey);
}
Expand Down
2 changes: 1 addition & 1 deletion core/Helper/Util.cs
Expand Up @@ -360,7 +360,7 @@ public static void ThrowPortNotFree(int port)
try
{
Task.Delay(100);
var localEp = new IPEndPoint(IPAddress.Any, port);
var localEp = new IPEndPoint(GetIpAddress(), port);
socket.Bind(localEp);
}
catch (SocketException ex)
Expand Down
83 changes: 12 additions & 71 deletions core/Ledger/Graph.cs
Expand Up @@ -40,8 +40,6 @@ public interface IGraph
Task<TransactionResponse> GetTransactionAsync(TransactionRequest transactionRequest);
Task<Block> GetPreviousBlockAsync();
Task<SafeguardBlocksResponse> GetSafeguardBlocksAsync(SafeguardBlocksRequest safeguardBlocksRequest);
Task<BlockHeightResponse> GetBlockHeightAsync();
Task<BlockCountResponse> GetBlockCountAsync();
Task<SaveBlockResponse> SaveBlockAsync(SaveBlockRequest saveBlockRequest);
Task<BlocksResponse> GetBlocksAsync(BlocksRequest blocksRequest);
Task PostAsync(BlockGraph blockGraph);
Expand Down Expand Up @@ -114,7 +112,7 @@ protected override async Task OnReceiveAsync(BlockGraph blockGraph)
{
Guard.Argument(blockGraph, nameof(blockGraph)).NotNull();
if (_cypherSystemCore.Sync().Running) return;
if (blockGraph.Block.Round != await NextRoundAsync()) return;
if (blockGraph.Block.Round != NextRound()) return;
if (await BlockHeightExistsAsync(new BlockHeightExistsRequest(blockGraph.Block.Round)) != VerifyResult.Succeed) return;
if (!_syncCacheSeenBlockGraph.Contains(blockGraph.ToIdentifier()))
{
Expand Down Expand Up @@ -221,10 +219,10 @@ public async Task<TransactionResponse> GetTransactionAsync(TransactionRequest tr
/// <returns></returns>
public async Task<Block> GetPreviousBlockAsync()
{
var unitOfWork = _cypherSystemCore.UnitOfWork();
var height = await unitOfWork.HashChainRepository.GetBlockHeightAsync();
var hashChainRepository = _cypherSystemCore.UnitOfWork().HashChainRepository;
var prevBlock =
await unitOfWork.HashChainRepository.GetAsync(x => new ValueTask<bool>(x.Height == (ulong)height));
await hashChainRepository.GetAsync(x =>
new ValueTask<bool>(x.Height == hashChainRepository.Height));
return prevBlock;
}

Expand All @@ -237,10 +235,9 @@ public async Task<SafeguardBlocksResponse> GetSafeguardBlocksAsync(SafeguardBloc
Guard.Argument(safeguardBlocksRequest, nameof(safeguardBlocksRequest)).NotNull();
try
{
var unitOfWork = _cypherSystemCore.UnitOfWork();
var height = (await GetBlockHeightAsync()).Count - safeguardBlocksRequest.NumberOfBlocks;
height = height < 0x0 ? 0x0 : height;
var blocks = await unitOfWork.HashChainRepository.OrderByRangeAsync(x => x.Height, (int)height,
var hashChainRepository = _cypherSystemCore.UnitOfWork().HashChainRepository;
var height = hashChainRepository.Height - (ulong)safeguardBlocksRequest.NumberOfBlocks;
var blocks = await hashChainRepository.OrderByRangeAsync(x => x.Height, (int)height,
safeguardBlocksRequest.NumberOfBlocks);
if (blocks.Any()) return new SafeguardBlocksResponse(blocks, string.Empty);
}
Expand Down Expand Up @@ -292,25 +289,6 @@ public async Task<BlockResponse> GetBlockByHeightAsync(BlockByHeightRequest bloc
return new BlockResponse(null);
}

/// <summary>
///
/// </summary>
/// <returns></returns>
public async Task<BlockCountResponse> GetBlockCountAsync()
{
try
{
var height = await _cypherSystemCore.UnitOfWork().HashChainRepository.CountAsync();
return new BlockCountResponse(height);
}
catch (Exception ex)
{
_logger.Here().Error("{@Message}", ex.Message);
}

return new BlockCountResponse(0);
}

/// <summary>
/// </summary>
/// <param name="blocksRequest"></param>
Expand All @@ -332,24 +310,6 @@ public async Task<BlocksResponse> GetBlocksAsync(BlocksRequest blocksRequest)
return new BlocksResponse(null);
}

/// <summary>
/// </summary>
public async Task<BlockHeightResponse> GetBlockHeightAsync()
{
try
{
var count = (await GetBlockCountAsync()).Count;
if (count > 0) count--;
return new BlockHeightResponse(count);
}
catch (Exception ex)
{
_logger.Here().Error("{@Message}", ex.Message);
}

return new BlockHeightResponse(0);
}

/// <summary>
/// </summary>
/// <param name="saveBlockRequest"></param>
Expand Down Expand Up @@ -650,7 +610,7 @@ private async Task OnDeliveredReadyAsync(Interpreted deliver)
foreach (var deliveredBlock in blocks)
try
{
if (deliveredBlock.Round != await NextRoundAsync()) continue;
if (deliveredBlock.Round != NextRound()) continue;
await using var stream = Util.Manager.GetStream(deliveredBlock.Data.AsSpan()) as RecyclableMemoryStream;
var block = await MessagePackSerializer.DeserializeAsync<Block>(stream);
_syncCacheDelivered.AddOrUpdate(block.Hash, block);
Expand Down Expand Up @@ -690,7 +650,7 @@ private async Task DecideWinnerAsync()
};
if (block is { })
{
if (block.Height != await NextRoundAsync()) return;
if (block.Height != NextRound()) return;
if (await BlockHeightExistsAsync(new BlockHeightExistsRequest(block.Height)) == VerifyResult.AlreadyExists)
{
_logger.Error("Block winner already exists");
Expand Down Expand Up @@ -744,17 +704,7 @@ private async Task DecideWinnerAsync()
/// <returns></returns>
private ulong GetRound()
{
return AsyncHelper.RunSync(GetRoundAsync);
}

/// <summary>
///
/// </summary>
/// <returns></returns>
private async Task<ulong> GetRoundAsync()
{
var blockHeightResponse = await GetBlockHeightAsync();
return (ulong)blockHeightResponse.Count;
return _cypherSystemCore.UnitOfWork().HashChainRepository.Height;
}

/// <summary>
Expand All @@ -763,16 +713,7 @@ private async Task<ulong> GetRoundAsync()
/// <returns></returns>
private ulong NextRound()
{
return AsyncHelper.RunSync(NextRoundAsync);
}

/// <summary>
///
/// </summary>
/// <returns></returns>
private async Task<ulong> NextRoundAsync()
{
return await GetRoundAsync() + 1;
return _cypherSystemCore.UnitOfWork().HashChainRepository.Count;
}

/// <summary>
Expand All @@ -784,7 +725,7 @@ private async Task BroadcastAsync(BlockGraph blockGraph)
Guard.Argument(blockGraph, nameof(blockGraph)).NotNull();
try
{
if (blockGraph.Block.Round == await NextRoundAsync())
if (blockGraph.Block.Round == NextRound())
await _cypherSystemCore.Broadcast().PostAsync((TopicType.AddBlockGraph,
MessagePackSerializer.Serialize(blockGraph)));
}
Expand Down
10 changes: 4 additions & 6 deletions core/Ledger/PPoS.cs
Expand Up @@ -234,9 +234,8 @@ private async Task<bool> BlockHeightSynchronizedAsync()
{
var peers = await _cypherSystemCore.PeerDiscovery().GetDiscoveryAsync();
if (!peers.Any()) return true;
var blockCountResponse = await _cypherSystemCore.Graph().GetBlockCountAsync();
var maxBlockHeight = peers.Max(x => x.BlockCount);
return blockCountResponse?.Count >= (long)maxBlockHeight;
return _cypherSystemCore.UnitOfWork().HashChainRepository.Count >= maxBlockHeight;
}

/// <summary>
Expand Down Expand Up @@ -324,8 +323,7 @@ private async Task<CoinStake> CreateCoinstakeAsync(Kernel kernel)
var validator = _cypherSystemCore.Validator();
var solution = await validator.SolutionAsync(kernel.CalculatedVrfSignature, kernel.Hash).ConfigureAwait(false);
if (solution == 0) return null;
var height = await _cypherSystemCore.UnitOfWork().HashChainRepository.CountAsync() + 1;
var networkShare = validator.NetworkShare(solution, (ulong)height);
var networkShare = validator.NetworkShare(solution, _cypherSystemCore.UnitOfWork().HashChainRepository.Count + 1);
var bits = validator.Bits(solution, networkShare);
_logger.Information("Begin... [COINSTAKE]");
var walletTransaction = await _cypherSystemCore.Wallet()
Expand Down Expand Up @@ -412,11 +410,11 @@ private BlockGraph NewBlockGraph(in Block block, in Block prevBlock)
var block = new Block
{
Hash = new byte[32],
Height = 1 + previousBlock.Height,
Height = previousBlock.Height + 1,
BlockHeader = new BlockHeader
{
Version = 2,
Height = previousBlock.BlockHeader.Height,
Height = previousBlock.Height + 1,
Locktime = lockTime,
LocktimeScript =
new Script(Op.GetPushOp(lockTime), OpcodeType.OP_CHECKLOCKTIMEVERIFY).ToString().ToBytes(),
Expand Down

0 comments on commit 84a1bfb

Please sign in to comment.