aboutsummaryrefslogtreecommitdiff
path: root/shard/lib/identity.ex
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2018-09-01 16:06:23 +0200
committerAlex Auvolat <alex@adnab.me>2018-09-01 16:06:23 +0200
commitc6ec33d6e612168e14d77007915a4ea423c55a2e (patch)
tree8b5645651a0cc991b8ac9c68c388d84c8dbe73d2 /shard/lib/identity.ex
parent1a0ef154a421af60f6d57dfe861dacb844a7d142 (diff)
downloadshard-c6ec33d6e612168e14d77007915a4ea423c55a2e.tar.gz
shard-c6ec33d6e612168e14d77007915a4ea423c55a2e.zip
Move everything to subdirectory
Diffstat (limited to 'shard/lib/identity.ex')
-rw-r--r--shard/lib/identity.ex46
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