aboutsummaryrefslogtreecommitdiff
path: root/shard/lib/identity.ex
blob: f1899df903288ce1082945019907a2726b0d2b42 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
defmodule Shard.Identity do
  use Agent
  require Salty.Sign.Ed25519, as: Sign
  require Logger

  def start_link(_) do
    Agent.start_link(__MODULE__, :init, [], name: __MODULE__)
  end

  def init() do
    Logger.info "Generating keypair..."
    {pk, sk} = gen_keypair(Application.get_env(:shard, :peer_id_suffix))
    nick_suffix = pk
                  |> binary_part(0, 3)
                  |> Base.encode16
                  |> String.downcase
    %{
      keypair:  {pk, sk},
      nickname: "Anon" <> nick_suffix,
    }
  end

  defp gen_keypair(suffix, n \\ 0) do
    {:ok, pk, sk} = Sign.keypair
    if rem(n, 10000) == 0 do
      Logger.info "#{n}... expected #{:math.pow(256, byte_size(suffix))}"
    end
    if :binary.longest_common_suffix([pk, suffix]) == byte_size(suffix) do
      {pk, sk}
    else
      gen_keypair(suffix, n+1)
    end
  end

  def get_keypair() do
    Agent.get(__MODULE__, &(&1.keypair))
  end

  def get_nickname() do
    Agent.get(__MODULE__, &(&1.nickname))
  end

  def set_nickname(newnick) do
    Agent.update(__MODULE__, &(%{&1 | nickname: newnick}))
  end
end