diff options
author | Alex Auvolat <alex@adnab.me> | 2018-09-01 16:01:48 +0200 |
---|---|---|
committer | Alex Auvolat <alex@adnab.me> | 2018-09-01 16:01:48 +0200 |
commit | 1a0ef154a421af60f6d57dfe861dacb844a7d142 (patch) | |
tree | ac4ce4ef99991c9826d69114489acaaeb7638e51 | |
parent | dd078cfecbe07f1e4d4e002467707ed53aeff180 (diff) | |
download | shard-1a0ef154a421af60f6d57dfe861dacb844a7d142.tar.gz shard-1a0ef154a421af60f6d57dfe861dacb844a7d142.zip |
Add peer id suffix to make sub networks
-rw-r--r-- | config/config.exs | 12 | ||||
-rw-r--r-- | lib/identity.ex | 16 | ||||
-rw-r--r-- | lib/net/tcpconn.ex | 4 |
3 files changed, 31 insertions, 1 deletions
diff --git a/config/config.exs b/config/config.exs index 3139220..f970078 100644 --- a/config/config.exs +++ b/config/config.exs @@ -21,6 +21,18 @@ use Mix.Config # config :logger, level: :info # + +# Peer id suffix +# ============== +# This Shard instance will only connect to other instances that use +# the same suffix. +# +# On first run, the instance will try to generate a peer id that +# has this suffix. This is done by brute-force testing, therefore +# it is not recommended to use long suffixes. +config :shard, peer_id_suffix: "S" + + # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. diff --git a/lib/identity.ex b/lib/identity.ex index 229d6c7..f1899df 100644 --- a/lib/identity.ex +++ b/lib/identity.ex @@ -1,13 +1,15 @@ 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 - {:ok, pk, sk} = Sign.keypair + Logger.info "Generating keypair..." + {pk, sk} = gen_keypair(Application.get_env(:shard, :peer_id_suffix)) nick_suffix = pk |> binary_part(0, 3) |> Base.encode16 @@ -18,6 +20,18 @@ defmodule Shard.Identity do } 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 diff --git a/lib/net/tcpconn.ex b/lib/net/tcpconn.ex index 6fc4b1a..44669bb 100644 --- a/lib/net/tcpconn.ex +++ b/lib/net/tcpconn.ex @@ -39,6 +39,10 @@ defmodule SNet.TCPConn do challenge_sign = decode_pkt(pkt, cli_sess_pkey, sess_skey) :ok = Sign.verify_detached(challenge_sign, challenge, cli_pkey) + expected_suffix = Application.get_env(:shard, :peer_id_suffix) + len = byte_size(expected_suffix) + ^len = :binary.longest_common_suffix([cli_pkey, expected_suffix]) + # Connected :inet.setopts(socket, [active: true]) |