Skip to content

Commit

Permalink
Fix cycle levels math
Browse files Browse the repository at this point in the history
  • Loading branch information
Groxan committed Jun 20, 2024
1 parent 76df188 commit 344f760
Show file tree
Hide file tree
Showing 15 changed files with 32 additions and 43 deletions.
8 changes: 3 additions & 5 deletions Tzkt.Api/Services/Home/HomeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -322,13 +322,11 @@ async Task<DailyData> GetDailyData(IDbConnection db)
CycleData GetCycleData()
{
var state = State.Current;
var proto = Protocols.Current;

var cycle = state.Cycle;
var level = state.Level;
var cycleSize = proto.BlocksPerCycle;
var firstLevel = proto.GetCycleStart(cycle);
var lastLevel = proto.GetCycleEnd(cycle);
var cycleSize = Protocols.FindByCycle(cycle).BlocksPerCycle;
var firstLevel = Protocols.FindByCycle(cycle).GetCycleStart(cycle);
var lastLevel = Protocols.FindByCycle(cycle).GetCycleEnd(cycle);

return new CycleData
{
Expand Down
2 changes: 1 addition & 1 deletion Tzkt.Sync/Protocols/Handlers/Genesis/GenesisHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ await Db.Database.ExecuteSqlRawAsync(@"
DELETE FROM ""Blocks"";");

await Cache.Statistics.ResetAsync();
Cache.Protocols.Reset();
await Cache.Protocols.ResetAsync();
Cache.Blocks.Reset();

#region update state
Expand Down
2 changes: 1 addition & 1 deletion Tzkt.Sync/Protocols/Handlers/Initiator/InitiatorHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ await Db.Database.ExecuteSqlRawAsync($@"
DELETE FROM ""Blocks"" WHERE ""Level"" = {curr.Level};");

await Cache.Statistics.ResetAsync();
Cache.Protocols.Reset();
await Cache.Protocols.ResetAsync();
Cache.Blocks.Reset();

#region update state
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ partial class ProtoActivator : ProtocolCommit
public async Task ClearProtocol()
{
await Db.Database.ExecuteSqlRawAsync(@"DELETE FROM ""Protocols"" WHERE ""Code"" = 1");
Cache.Protocols.Reset();
await Cache.Protocols.ResetAsync();
}

protected virtual void SetParameters(Protocol protocol, JToken parameters)
Expand Down Expand Up @@ -142,7 +142,7 @@ public async Task DowngradeProtocol(AppState state)
Db.TryAttach(prev);
prev.LastLevel = -1;

Cache.Protocols.Reset();
await Cache.Protocols.ResetAsync();
}

protected virtual void UpgradeParameters(Protocol protocol, Protocol prev) { }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public virtual async Task Apply(JsonElement rawBlock)
if (metadata.RequiredArray("deactivated").Count() > 0)
events |= BlockEvents.Deactivations;

if ((level - protocol.GetCycleStart(protocol.GetCycle(level)) + 1) % protocol.BlocksPerSnapshot == 0)
if ((level - Cache.Protocols.GetCycleStart(protocol.GetCycle(level)) + 1) % protocol.BlocksPerSnapshot == 0)
events |= BlockEvents.BalanceSnapshot;

var payloadRound = header.RequiredInt32("payload_round");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public void Revert(DoubleBakingOperation operation)

protected virtual int GetSlashingLevel(Block block, Protocol protocol, int accusedLevel)
{
return protocol.GetCycleEnd(block.Cycle);
return Cache.Protocols.GetCycleEnd(block.Cycle);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public void Revert(DoubleEndorsingOperation operation)

protected virtual int GetSlashingLevel(Block block, Protocol protocol, int accusedLevel)
{
return protocol.GetCycleEnd(block.Cycle);
return Cache.Protocols.GetCycleEnd(block.Cycle);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public void Revert(DoublePreendorsingOperation operation)

protected virtual int GetSlashingLevel(Block block, Protocol protocol, int accusedLevel)
{
return protocol.GetCycleEnd(block.Cycle);
return Cache.Protocols.GetCycleEnd(block.Cycle);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public DoubleBakingCommit(ProtocolHandler protocol) : base(protocol) { }

protected override int GetSlashingLevel(Block block, Protocol protocol, int accusedLevel)
{
return protocol.GetCycleEnd(protocol.GetCycle(accusedLevel) + protocol.MaxSlashingPeriod - 1);
return Cache.Protocols.GetCycleEnd(protocol.GetCycle(accusedLevel) + protocol.MaxSlashingPeriod - 1);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public DoubleEndorsingCommit(ProtocolHandler protocol) : base(protocol) { }

protected override int GetSlashingLevel(Block block, Protocol protocol, int accusedLevel)
{
return protocol.GetCycleEnd(protocol.GetCycle(accusedLevel) + protocol.MaxSlashingPeriod - 1);
return Cache.Protocols.GetCycleEnd(protocol.GetCycle(accusedLevel) + protocol.MaxSlashingPeriod - 1);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public DoublePreendorsingCommit(ProtocolHandler protocol) : base(protocol) { }

protected override int GetSlashingLevel(Block block, Protocol protocol, int accusedLevel)
{
return protocol.GetCycleEnd(protocol.GetCycle(accusedLevel) + protocol.MaxSlashingPeriod - 1);
return Cache.Protocols.GetCycleEnd(protocol.GetCycle(accusedLevel) + protocol.MaxSlashingPeriod - 1);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ protected virtual async Task ValidateSeedNonceRevelation(JsonElement content)
var level = content.RequiredInt32("level");
var proto = await Cache.Protocols.FindByLevelAsync(level);

if ((level - proto.GetCycleStart(proto.GetCycle(level)) + 1) % proto.BlocksPerCommitment != 0)
if ((level - Cache.Protocols.GetCycleStart(proto.GetCycle(level)) + 1) % proto.BlocksPerCommitment != 0)
throw new ValidationException("invalid seed nonce revelation level");

var balanceUpdates = content.Required("metadata").RequiredArray("balance_updates").EnumerateArray();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ protected virtual async Task ValidateSeedNonceRevelation(JsonElement content)
var level = content.RequiredInt32("level");
var proto = await Cache.Protocols.FindByLevelAsync(level);

if ((level - proto.GetCycleStart(proto.GetCycle(level)) + 1) % proto.BlocksPerCommitment != 0)
if ((level - Cache.Protocols.GetCycleStart(proto.GetCycle(level)) + 1) % proto.BlocksPerCommitment != 0)
throw new ValidationException("invalid seed nonce revelation level");

var balanceUpdates = content.Required("metadata").RequiredArray("balance_updates").EnumerateArray();
Expand Down
2 changes: 1 addition & 1 deletion Tzkt.Sync/Services/Cache/CacheService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ public async Task ResetAsync()
BakerCycles.Reset();
BakingRights.Reset();
Blocks.Reset();
Protocols.Reset();
Proposals.Reset();
Periods.Reset();
Software.Reset();
Expand All @@ -76,6 +75,7 @@ public async Task ResetAsync()
RefutationGames.Reset();
UnstakeRequests.Reset();

await Protocols.ResetAsync();
await AppState.ResetAsync();
await Accounts.ResetAsync();
await Statistics.ResetAsync();
Expand Down
39 changes: 15 additions & 24 deletions Tzkt.Sync/Services/Cache/ProtocolsCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ namespace Tzkt.Sync.Services.Cache
{
public class ProtocolsCache
{
public const int MaxProtocols = 16; //TODO: set limits in app settings

static readonly Dictionary<int, Protocol> CachedByCode = new(17);
static readonly Dictionary<string, Protocol> CachedByHash = new(17);
static readonly Dictionary<int, Protocol> CachedByCode = new(37);
static readonly Dictionary<string, Protocol> CachedByHash = new(37);

readonly TzktContext Db;

Expand All @@ -18,15 +16,17 @@ public ProtocolsCache(TzktContext db)
Db = db;
}

public void Reset()
public async Task ResetAsync()
{
CachedByCode.Clear();
CachedByHash.Clear();

foreach (var protocol in await Db.Protocols.ToListAsync())
Add(protocol);
}

public void Add(Protocol protocol)
{
CheckSpace();
CachedByCode[protocol.Code] = protocol;
CachedByHash[protocol.Hash] = protocol;
}
Expand Down Expand Up @@ -95,31 +95,22 @@ public async Task<Protocol> FindByLevelAsync(int level)
return protocol;
}

public async Task<int> GetCycle(int level)
public Protocol FindByCycle(int cycle)
{
var protocol = await FindByLevelAsync(level);
return protocol.GetCycle(level);
return CachedByCode.Values
.OrderByDescending(x => x.Code)
.FirstOrDefault(x => x.FirstCycle <= cycle)
?? throw new Exception($"Protocol for cycle {cycle} doesn't exist");
}

public void Remove(Protocol protocol)
public int GetCycleStart(int cycle)
{
CachedByCode.Remove(protocol.Code);
CachedByHash.Remove(protocol.Hash);
return FindByCycle(cycle).GetCycleStart(cycle);
}

void CheckSpace()
public int GetCycleEnd(int cycle)
{
if (CachedByCode.Count >= MaxProtocols)
{
var oldest = CachedByCode.Values
.Take(MaxProtocols / 4);

foreach (var code in oldest.Select(x => x.Code).ToList())
CachedByCode.Remove(code);

foreach (var hash in oldest.Select(x => x.Hash).ToList())
CachedByHash.Remove(hash);
}
return FindByCycle(cycle).GetCycleEnd(cycle);
}
}
}

0 comments on commit 344f760

Please sign in to comment.