Skip to content

Commit

Permalink
Address CR comments
Browse files Browse the repository at this point in the history
  • Loading branch information
MegaRedHand committed Dec 12, 2023
1 parent 98226e7 commit b8bac2b
Showing 1 changed file with 30 additions and 17 deletions.
47 changes: 30 additions & 17 deletions lib/lambda_ethereum_consensus/state_transition/misc.ex
Original file line number Diff line number Diff line change
Expand Up @@ -174,37 +174,50 @@ defmodule LambdaEthereumConsensus.StateTransition.Misc do
<<value::unsigned-integer-little-size(64)>>
end

@doc """
Computes the validator indices of the ``committee_index``-th committee at some epoch
with ``committee_count`` committees, and for some given ``indices`` and ``seed``.
"""
@spec compute_committee(
list(SszTypes.validator_index()),
SszTypes.bytes32(),
SszTypes.uint64(),
SszTypes.uint64()
) ::
{:ok, list(SszTypes.validator_index())} | {:error, binary()}
def compute_committee(indices, seed, index, count) do
def compute_committee(indices, seed, committee_index, committee_count) do
index_count = length(indices)
a = div(index_count * index, count)
b = div(index_count * (index + 1), count) - 1
committee_start = div(index_count * committee_index, committee_count)
committee_end = div(index_count * (committee_index + 1), committee_count) - 1

to_swap_indices =
a..b//1
result =
committee_start..committee_end//1
|> Stream.map(&compute_shuffled_index(&1, index_count, seed))
|> Stream.map(fn {:ok, i} -> i end)
|> Stream.with_index()
|> Enum.sort(fn {a, _}, {b, _} -> a <= b end)
|> Enum.reduce_while([], fn
{{:ok, shuffled_index}, i}, {:ok, acc} ->
{:cont, {:ok, [{shuffled_index, i} | acc]}}

{swapped_indices, []} =
indices
|> Stream.with_index()
|> Enum.flat_map_reduce(to_swap_indices, fn
{v, i}, [{i, j} | tail] -> {[{v, j}], tail}
_, acc -> {[], acc}
{{:error, _} = err, _}, _ ->
{:halt, err}
end)

swapped_indices
|> Enum.sort(fn {_, a}, {_, b} -> a <= b end)
|> Enum.map(fn {v, _} -> v end)
|> then(&{:ok, &1})
with {:ok, to_swap_indices} <- result do
to_swap_indices = Enum.sort(to_swap_indices, fn {a, _}, {b, _} -> a <= b end)

{swapped_indices, []} =
indices
|> Stream.with_index()
|> Enum.flat_map_reduce(to_swap_indices, fn
{v, i}, [{i, j} | tail] -> {[{v, j}], tail}
_, acc -> {[], acc}
end)

swapped_indices
|> Enum.sort(fn {_, a}, {_, b} -> a <= b end)
|> Enum.map(fn {v, _} -> v end)
|> then(&{:ok, &1})
end
end

@doc """
Expand Down

0 comments on commit b8bac2b

Please sign in to comment.