diff options
Diffstat (limited to 'shard/lib/identity.ex')
-rw-r--r-- | shard/lib/identity.ex | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/shard/lib/identity.ex b/shard/lib/identity.ex new file mode 100644 index 0000000..f1899df --- /dev/null +++ b/shard/lib/identity.ex @@ -0,0 +1,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 |