diff options
author | Alex Auvolat <alex@adnab.me> | 2018-09-11 15:39:09 +0200 |
---|---|---|
committer | Alex Auvolat <alex@adnab.me> | 2018-09-11 15:39:09 +0200 |
commit | a033c82a3c656a8f53feb60b5b149680771ac247 (patch) | |
tree | bc3cb9a6954aebcfd1a0c5f61d367e1083802c3e /shard/lib/identity.ex | |
parent | e92969db3f0a2093da16eb7db18c9db49225a719 (diff) | |
download | shard-a033c82a3c656a8f53feb60b5b149680771ac247.tar.gz shard-a033c82a3c656a8f53feb60b5b149680771ac247.zip |
Use DETS to store shard & peer list to disk
Diffstat (limited to 'shard/lib/identity.ex')
-rw-r--r-- | shard/lib/identity.ex | 41 |
1 files changed, 30 insertions, 11 deletions
diff --git a/shard/lib/identity.ex b/shard/lib/identity.ex index f1899df..01b3c9e 100644 --- a/shard/lib/identity.ex +++ b/shard/lib/identity.ex @@ -3,21 +3,36 @@ defmodule Shard.Identity do require Salty.Sign.Ed25519, as: Sign require Logger + @identity_db [Application.get_env(:shard, :data_path), "identity_db"] |> Path.join |> String.to_atom + 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, - } + :dets.start + {:ok, @identity_db} = :dets.open_file @identity_db, type: :set + + case :dets.match @identity_db, :"$1" 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 + nick = "Anon" <> nick_suffix + :dets.insert @identity_db, {pk, sk, nick} + %{ + keypair: {pk, sk}, + nickname: nick + } + [[{pk, sk, nick}] | _] -> + %{ + keypair: {pk, sk}, + nickname: nick + } + end end defp gen_keypair(suffix, n \\ 0) do @@ -41,6 +56,10 @@ defmodule Shard.Identity do end def set_nickname(newnick) do - Agent.update(__MODULE__, &(%{&1 | nickname: newnick})) + Agent.update(__MODULE__, fn state -> + {pk, sk} = state.keypair + :dets.insert @identity_db, {pk, sk, newnick} + %{state | nickname: newnick} + end) end end |