This commit is contained in:
2024-09-26 21:54:04 +09:00
commit 6a8748b05e
13 changed files with 6285 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
%%% @doc
%%% Clutch
%%% @end
-module(clutch).
-vsn("0.1.0").
-behavior(application).
-author("Craig Everett <craigeverett@qpq.swiss>").
-copyright("Craig Everett <craigeverett@qpq.swiss>").
-license("GPL-3.0-or-later").
-export([ts/0]).
-export([start/2, stop/1]).
-export_type([id/0, key/0, ak/0, tx/0, ts/0]).
-include("$zx_include/zx_logger.hrl").
-include("gmc.hrl").
-type id() :: binary().
-type key() :: #key{}.
-type ak() :: #ak{}.
-type tx() :: #tx{}.
-type ts() :: integer().
ts() ->
erlang:system_time(nanosecond).
-spec start(normal, Args :: term()) -> {ok, pid()}.
%% @private
%% Called by OTP to kick things off. This is for the use of the "application" part of
%% OTP, not to be called by user code.
%%
%% NOTE:
%% The commented out second argument would come from ebin/clutch.app's 'mod'
%% section, which is difficult to define dynamically so is not used by default
%% here (if you need this, you already know how to change it).
%%
%% Optional runtime arguments passed in at start time can be obtained by calling
%% zx_daemon:argv/0 anywhere in the body of the program.
%%
%% See: http://erlang.org/doc/apps/kernel/application.html
start(normal, _Args) ->
ok =
case net_kernel:stop() of
ok ->
log(info, "SAFE: This node is running standalone.");
{error, not_found} ->
log(warning, "SAFETY: Distribution has been disabled on this node.");
{error, not_allowed} ->
ok = tell(error, "DANGER! This node is in distributed mode!"),
init:stop(1)
end,
ok = application:ensure_started(zxwidgets),
gmc_sup:start_link().
-spec stop(term()) -> ok.
%% @private
%% Similar to start/2 above, this is to be called by the "application" part of OTP,
%% not client code. Causes a (hopefully graceful) shutdown of the application.
stop(_State) ->
ok.
+470
View File
@@ -0,0 +1,470 @@
%%% @doc
%%% Clutch Controller
%%%
%%% This process is a in charge of maintaining the program's state.
%%% @end
-module(gmc_con).
-vsn("0.1.0").
-author("Craig Everett <craigeverett@qpq.swiss>").
-copyright("Craig Everett <craigeverett@qpq.swiss>").
-license("GPL-3.0-or-later").
-behavior(gen_server).
-export([make_key/6, recover_key/1, mnemonic/1, rename_key/2, drop_key/1,
login/1, password/2]). % add_key/1, drop_key/1]).
-export([encrypt/2, decrypt/2]).
-export([start_link/0, stop/0, save/1]).
-export([init/1, terminate/2, code_change/3,
handle_call/3, handle_cast/2, handle_info/2]).
-include("$zx_include/zx_logger.hrl").
-include("gmc.hrl").
%%% Type and Record Definitions
-record(s,
{window = none :: none | wx:wx_object(),
accounts = [] :: [clutch:ak()],
pass = none :: none | binary(),
keys = [] :: [clutch:key()],
chains = [] :: [chain()],
prefs = #{} :: #{atom() := term()}}).
-record(chain,
{id = "" :: string(),
nodes = [] :: [address()],
mdws = [] :: [address()]}).
-type state() :: #s{}.
-type chain() :: tuple().
-type address() :: {inet:ip_address(), inet:port_number()}.
%% Interface
-spec make_key(Type, Size, Name, Seed, Encoding, Transform) -> ok
when Type :: {eddsa, ed25519},
Size :: 256,
Name :: string(),
Seed :: string(),
Encoding :: utf8 | base64 | base58,
Transform :: raw | {Algo, Yugeness},
Algo :: sha3 | sha2 | x_or | pbkdf2,
Yugeness :: rand | non_neg_integer().
%% @doc
%% Generate a new key.
%% The magic first two args are here because `ak_*' basically has no option other than
%% to mean a 256 bit key based on Curve 25519. When more key varieties are added to the
%% system this will change quite a lot.
make_key({eddsa, ed25519}, 256, Name, Seed, Encoding, Transform) ->
gen_server:cast(?MODULE, {make_key, Name, Seed, Encoding, Transform}).
-spec recover_key(Mnemonic) -> ok
when Mnemonic :: string().
recover_key(Mnemonic) ->
gen_server:cast(?MODULE, {recover_key, Mnemonic}).
-spec mnemonic(ID) -> {ok, Mnemonic} | error
when ID :: clutch:id(),
Mnemonic :: string().
mnemonic(ID) ->
gen_server:call(?MODULE, {mnemonic, ID}).
-spec rename_key(ID, NewName) -> ok
when ID :: clutch:id(),
NewName :: string().
rename_key(ID, NewName) ->
gen_server:cast(?MODULE, {rename_key, ID, NewName}).
-spec drop_key(ID) -> ok
when ID :: clutch:id().
drop_key(ID) ->
gen_server:cast(?MODULE, {drop_key, ID}).
-spec stop() -> ok.
stop() ->
gen_server:cast(?MODULE, stop).
-spec login(Phrase) -> ok
when Phrase :: string().
login(Phrase) ->
gen_server:cast(?MODULE, {login, Phrase}).
-spec password(Old, New) -> ok
when Old :: none | string(),
New :: none | string().
password(Old, New) ->
gen_server:cast(?MODULE, {password, Old, New}).
-spec save(Prefs) -> ok | {error, Reason}
when Prefs :: #{atom() := term()},
Reason :: file:posix().
save(Prefs) ->
gen_server:call(?MODULE, {save, Prefs}).
%%% Startup Functions
-spec start_link() -> Result
when Result :: {ok, pid()}
| {error, Reason},
Reason :: {already_started, pid()}
| {shutdown, term()}
| term().
%% @private
%% Called by gmc_sup.
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, none, []).
-spec init(none) -> {ok, state()}.
init(none) ->
ok = log(info, "Starting"),
Prefs = read_prefs(),
Window = gmc_gui:start_link(Prefs),
ok = log(info, "Window: ~p", [Window]),
ok = gmc_gui:ask_password(),
State = #s{window = Window},
ArgV = zx_daemon:argv(),
ok = gmc_gui:show(ArgV),
{ok, State}.
read_prefs() ->
case file:consult(prefs_path()) of
{ok, Prefs} ->
proplists:to_map(Prefs);
_ ->
#{selected => 0,
lang => en_us,
geometry => none}
end.
%%% gen_server Message Handling Callbacks
-spec handle_call(Message, From, State) -> Result
when Message :: term(),
From :: {pid(), reference()},
State :: state(),
Result :: {reply, Response, NewState}
| {noreply, State},
Response :: ok
| {error, {listening, inet:port_number()}},
NewState :: state().
%% @private
%% The gen_server:handle_call/3 callback.
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_call-3
handle_call({save, Prefs}, _, State) ->
Response = do_save(State#s{prefs = Prefs}),
{reply, Response, State};
handle_call({mnemonic, ID}, _, State) ->
Response = do_mnemonic(ID, State),
{reply, Response, State};
handle_call(Unexpected, From, State) ->
ok = log(warning, "Unexpected call from ~tp: ~tp~n", [From, Unexpected]),
{noreply, State}.
-spec handle_cast(Message, State) -> {noreply, NewState}
when Message :: term(),
State :: state(),
NewState :: state().
%% @private
%% The gen_server:handle_cast/2 callback.
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_cast-2
handle_cast({make_key, Name, Seed, Encoding, Transform}, State) ->
NewState = do_make_key(Name, Seed, Encoding, Transform, State),
{noreply, NewState};
handle_cast({recover_key, Mnemonic}, State) ->
NewState = do_recover_key(Mnemonic, State),
{noreply, NewState};
handle_cast({rename_key, ID, NewName}, State) ->
NewState = do_rename_key(ID, NewName, State),
{noreply, NewState};
handle_cast({drop_key, ID}, State) ->
NewState = do_drop_key(ID, State),
{noreply, NewState};
handle_cast({login, Phrase}, State) ->
NewState = do_login(Phrase, State),
{noreply, NewState};
handle_cast({password, Old, New}, State) ->
NewState = do_password(Old, New, State),
{noreply, NewState};
handle_cast(stop, State) ->
ok = log(info, "Received a 'stop' message."),
{stop, normal, State};
handle_cast(Unexpected, State) ->
ok = tell(warning, "Unexpected cast: ~tp~n", [Unexpected]),
{noreply, State}.
-spec handle_info(Message, State) -> {noreply, NewState}
when Message :: term(),
State :: state(),
NewState :: state().
%% @private
%% The gen_server:handle_info/2 callback.
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_info-2
handle_info(Unexpected, State) ->
ok = log(warning, "Unexpected info: ~tp~n", [Unexpected]),
{noreply, State}.
%% @private
%% gen_server callback to handle state transformations necessary for hot
%% code updates. This template performs no transformation.
code_change(_, State, _) ->
{ok, State}.
terminate(Reason, State) ->
ok = log(info, "Reason: ~tp, State: ~tp", [Reason, State]),
zx:stop().
%%%
do_make_key(Name, <<>>, _, Transform, State) ->
Bin = crypto:strong_rand_bytes(32),
do_make_key2(Name, Bin, Transform, State);
do_make_key(Name, Seed, utf8, Transform, State) ->
Bin = unicode:characters_to_binary(Seed),
do_make_key2(Name, Bin, Transform, State);
do_make_key(Name, Seed, base64, Transform, State) ->
case base64_decode(Seed) of
{ok, Bin} ->
do_make_key2(Name, Bin, Transform, State);
{error, Reason} ->
ok = gmc_gui:notify({error, {base64, Reason}}),
State
end;
do_make_key(Name, Seed, base58, Transform, State) ->
case base58:check_base58(Seed) of
true ->
Bin = base58:base58_to_binary(Seed),
do_make_key2(Name, Bin, Transform, State);
false ->
ok = gmc_gui:notify({error, {base58, badarg}}),
State
end.
do_make_key2(Name, Bin, Transform, State = #s{accounts = Accounts, keys = Keys}) ->
T = transform(Transform),
Seed = T(Bin),
Key = #key{name = KeyName, id = ID} = gmc_key_master:make_key(Name, Seed),
Account = #ak{name = KeyName, id = ID},
NewKeys = [Key | Keys],
NewAccounts = [Account | Accounts],
ok = gmc_gui:show(NewAccounts),
State#s{accounts = NewAccounts, keys = NewKeys}.
base64_decode(String) ->
try
{ok, base64:decode(String)}
catch
E:R -> {E, R}
end.
transform({sha3, 256}) ->
fun(D) -> crypto:hash(sha3_256, D) end;
transform({sha2, 256}) ->
fun(D) -> crypto:hash(sha256, D) end;
transform({x_or, 256}) ->
fun t_xor/1;
transform(raw) ->
fun(D) -> D end.
t_xor(Bin) -> t_xor(Bin, <<0:256>>).
t_xor(<<H:32/binary, T/binary>>, A) ->
t_xor(T, crypto:exor(H, A));
t_xor(<<>>, A) ->
A;
t_xor(B, A) ->
H = <<0:(256 - bit_size(B)), B/binary>>,
crypto:exor(H, A).
do_recover_key(Mnemonic, State = #s{keys = Keys, accounts = Accounts}) ->
case gmc_key_master:decode(Mnemonic) of
{ok, Seed} ->
do_recover_key2(Seed, State);
Error ->
ok = gmc_gui:notify(Error),
State
end.
do_recover_key2(Seed, State = #s{keys = Keys, accounts = Accounts}) ->
Recovered = #key{id = ID, name = Name} = gmc_key_master:make_key("", Seed),
case lists:keymember(ID, #key.id, Keys) of
false ->
NewKeys = [Recovered | Keys],
Account = #ak{name = Name, id = ID},
NewAccounts = [Account | Accounts],
ok = gmc_gui:show(NewAccounts),
State#s{accounts = NewAccounts, keys = NewKeys};
true ->
State
end.
do_mnemonic(ID, #s{keys = Keys}) ->
case lists:keyfind(ID, #key.id, Keys) of
#key{pair = #{secret := <<K:32/binary, _/binary>>}} ->
Mnemonic = gmc_key_master:encode(K),
{ok, Mnemonic};
false ->
{error, bad_key}
end.
do_rename_key(ID, NewName, State = #s{accounts = Accounts, keys = Keys}) ->
A = lists:keyfind(ID, #ak.id, Accounts),
K = lists:keyfind(ID, #key.id, Keys),
NewAccounts = lists:keystore(ID, #ak.id, Accounts, A#ak{name = NewName}),
NewKeys = lists:keystore(ID, #key.id, Keys, K#key{name = NewName}),
ok = gmc_gui:show(NewAccounts),
State#s{accounts = NewAccounts, keys = NewKeys}.
do_drop_key(ID, State = #s{accounts = Accounts, keys = Keys}) ->
NewAccounts = lists:keydelete(ID, #ak.id, Accounts),
NewKeys = lists:keydelete(ID, #key.id, Keys),
ok = gmc_gui:show(NewAccounts),
State#s{accounts = NewAccounts, keys = NewKeys}.
encrypt(Pass, Binary) ->
Flags = [{encrypt, true}, {padding, pkcs_padding}],
crypto:crypto_one_time(aes_256_ecb, Pass, Binary, Flags).
decrypt(Pass, Binary) ->
Flags = [{encrypt, false}, {padding, pkcs_padding}],
crypto:crypto_one_time(aes_256_ecb, Pass, Binary, Flags).
pass(Phrase) ->
crypto:hash(sha3_256, Phrase).
do_login(none, State) ->
case read(none) of
{ok, Recovered = #s{accounts = Accounts}} ->
ok = gmc_gui:show(Accounts),
Recovered;
error ->
State
end;
do_login(Phrase, State = #s{pass = none}) ->
Pass = pass(Phrase),
try
case read(Pass) of
{ok, Recovered = #s{accounts = Accounts}} ->
ok = gmc_gui:show(Accounts),
Recovered;
error ->
State#s{pass = Pass}
end
catch
E:R ->
ok = tell("Problem with loading state: {~p, ~p}", [E, R]),
ok = gmc_gui:ask_password(),
State
end.
do_password(none, none, State) ->
State;
do_password(none, New, State = #s{pass = none}) ->
Pass = pass(New),
State#s{pass = Pass};
do_password(Old, none, State = #s{pass = Pass}) ->
case pass(Old) =:= Pass of
true -> State#s{pass = none};
false -> State
end;
do_password(Old, New, State = #s{pass = Pass}) ->
case pass(Old) =:= Pass of
true -> State#s{pass = pass(New)};
false -> State
end.
do_save(State = #s{prefs = Prefs}) ->
ok = persist(Prefs),
do_save2(State).
do_save2(State = #s{pass = none}) ->
Path = save_path(),
ok = filelib:ensure_dir(Path),
file:write_file(Path, term_to_binary(State));
do_save2(State = #s{pass = Pass}) ->
Path = save_path(),
ok = filelib:ensure_dir(Path),
Cipher = encrypt(Pass, term_to_binary(State)),
file:write_file(Path, Cipher).
read(none) ->
case file:read_file(save_path()) of
{ok, Bin} -> {ok, binary_to_term(Bin)};
{error, enoent} -> error
end;
read(Pass) ->
case file:read_file(save_path()) of
{ok, Cipher} -> {ok, binary_to_term(decrypt(Pass, Cipher))};
{error, enoent} -> error
end.
save_path() ->
filename:join(zx_lib:path(var, "otpr", "clutch"), "opaque.data").
persist(Prefs) ->
Path = prefs_path(),
ok = filelib:ensure_dir(Path),
zx_lib:write_terms(Path, proplists:from_map(Prefs)).
prefs_path() ->
filename:join(zx_lib:path(etc, "otpr", "clutch"), "prefs.eterms").
+623
View File
@@ -0,0 +1,623 @@
%%% @doc
%%% Clutch GUI
%%%
%%% This process is responsible for creating the main GUI frame displayed to the user.
%%%
%%% Reference: http://erlang.org/doc/man/wx_object.html
%%% @end
-module(gmc_gui).
-vsn("0.1.0").
-author("Craig Everett <craigeverett@qpq.swiss>").
-copyright("Craig Everett <craigeverett@qpq.swiss>").
-license("GPL-3.0-or-later").
-behavior(wx_object).
-include_lib("wx/include/wx.hrl").
-export([show/1, notify/1, ask_password/0]).
-export([start_link/1]).
-export([init/1, terminate/2, code_change/3,
handle_call/3, handle_cast/2, handle_info/2, handle_event/2]).
-include("$zx_include/zx_logger.hrl").
-include("gmc.hrl").
-record(w,
{name = none :: atom(),
id = 0 :: integer(),
wx = none :: wx:wx_object()}).
-record(s,
{wx = none :: none | wx:wx_object(),
frame = none :: none | wx:wx_object(),
lang = en :: en | jp,
j = none :: none | fun(),
prefs = #{} :: #{atom() := term()},
accounts = [] :: [clutch:ak()],
picker = none :: none | wx:wx_object(),
id = {#w{}, #w{}} :: labeled(),
balance = {#w{}, #w{}} :: labeled(),
buttons = [] :: [widget()]}).
-type state() :: term().
-type widget() :: #w{}.
-type labeled() :: {Label :: #w{}, Control :: #w{}}.
%%% Interface functions
show(Accounts) ->
wx_object:cast(?MODULE, {show, Accounts}).
notify(Message) ->
wx_object:cast(?MODULE, {notify, Message}).
ask_password() ->
wx_object:cast(?MODULE, password).
%%% Startup Functions
start_link(Accounts) ->
wx_object:start_link({local, ?MODULE}, ?MODULE, Accounts, []).
init(Prefs) ->
ok = log(info, "GUI starting..."),
Lang = maps:get(lang, Prefs, en_us),
Trans = gmc_jt:read_translations(?MODULE),
J = gmc_jt:j(Lang, Trans),
Wx = wx:new(),
Frame = wxFrame:new(Wx, ?wxID_ANY, J("Gajumaru Clutch")),
MainSz = wxBoxSizer:new(?wxVERTICAL),
Picker = wxListBox:new(Frame, ?wxID_ANY, [{style, ?wxLC_SINGLE_SEL}]),
ID_L = wxStaticText:new(Frame, ?wxID_ANY, J("Account ID: ")),
ID_T = wxStaticText:new(Frame, ?wxID_ANY, ""),
ID_W =
{#w{id = wxStaticText:getId(ID_L), wx = ID_L},
#w{id = wxStaticText:getId(ID_T), wx = ID_T}},
ID_Sz = wxBoxSizer:new(?wxHORIZONTAL),
_ = wxSizer:add(ID_Sz, ID_L, zxw:flags(base)),
_ = wxSizer:add(ID_Sz, ID_T, zxw:flags(wide)),
BalanceL = wxStaticText:new(Frame, ?wxID_ANY, ""),
BalanceT = wxStaticText:new(Frame, ?wxID_ANY, price_to_string(0)),
Balance =
{#w{id = wxStaticText:getId(BalanceL), wx = BalanceL},
#w{id = wxStaticText:getId(BalanceT), wx = BalanceT}},
BalanceSz = wxBoxSizer:new(?wxHORIZONTAL),
_ = wxSizer:add(BalanceSz, BalanceL, zxw:flags(base)),
_ = wxSizer:add(BalanceSz, BalanceT, zxw:flags(wide)),
ButtonTemplates =
[{make_key, J("Create")},
{recover, J("Recover")},
{mnemonic, J("Mnemonic")},
{rename, J("Rename")},
{drop_key, J("Delete")},
{send, J("Send Money")},
{recv, J("Receive Money")},
{grids, J("GRIDS URL")},
{refresh, J("Refresh")}],
MakeButton =
fun({Name, Label}) ->
B = wxButton:new(Frame, ?wxID_ANY, [{label, Label}]),
#w{name = Name, id = wxButton:getId(B), wx = B}
end,
Buttons = lists:map(MakeButton, ButtonTemplates),
AccountSz = wxBoxSizer:new(?wxHORIZONTAL),
ActionsSz = wxBoxSizer:new(?wxHORIZONTAL),
HistorySz = wxBoxSizer:new(?wxVERTICAL),
#w{wx = MakeBn} = lists:keyfind(make_key, #w.name, Buttons),
#w{wx = RecoBn} = lists:keyfind(recover, #w.name, Buttons),
#w{wx = MnemBn} = lists:keyfind(mnemonic, #w.name, Buttons),
#w{wx = Rename} = lists:keyfind(rename, #w.name, Buttons),
#w{wx = DropBn} = lists:keyfind(drop_key, #w.name, Buttons),
_ = wxSizer:add(AccountSz, MakeBn, zxw:flags(wide)),
_ = wxSizer:add(AccountSz, RecoBn, zxw:flags(wide)),
_ = wxSizer:add(AccountSz, MnemBn, zxw:flags(wide)),
_ = wxSizer:add(AccountSz, Rename, zxw:flags(wide)),
_ = wxSizer:add(AccountSz, DropBn, zxw:flags(wide)),
#w{wx = SendBn} = lists:keyfind(send, #w.name, Buttons),
#w{wx = RecvBn} = lists:keyfind(recv, #w.name, Buttons),
#w{wx = GridsBn} = lists:keyfind(grids, #w.name, Buttons),
_ = wxSizer:add(ActionsSz, SendBn, zxw:flags(wide)),
_ = wxSizer:add(ActionsSz, RecvBn, zxw:flags(wide)),
_ = wxSizer:add(ActionsSz, GridsBn, zxw:flags(wide)),
#w{wx = Refresh} = lists:keyfind(refresh, #w.name, Buttons),
_ = wxSizer:add(HistorySz, Refresh, zxw:flags(base)),
_ = wxSizer:add(MainSz, AccountSz, zxw:flags(base)),
_ = wxSizer:add(MainSz, Picker, zxw:flags(wide)),
_ = wxSizer:add(MainSz, ID_Sz, zxw:flags(base)),
_ = wxSizer:add(MainSz, BalanceSz, zxw:flags(base)),
_ = wxSizer:add(MainSz, ActionsSz, zxw:flags(base)),
_ = wxSizer:add(MainSz, HistorySz, [{proportion, 3}, {flag, ?wxEXPAND}]),
ok = wxFrame:setSizer(Frame, MainSz),
ok = wxSizer:layout(MainSz),
ok =
case safe_size(Prefs) of
{pref, max} ->
wxTopLevelWindow:maximize(Frame);
{pref, WSize} ->
wxFrame:setSize(Frame, WSize);
{center, WSize} ->
ok = wxFrame:setSize(Frame, WSize),
wxFrame:center(Frame)
end,
ok = wxFrame:connect(Frame, command_button_clicked),
ok = wxFrame:connect(Frame, close_window),
true = wxFrame:show(Frame),
ok = wxListBox:connect(Picker, command_listbox_selected),
State = #s{wx = Wx, frame = Frame, lang = Lang, j = J, prefs = Prefs,
accounts = [],
picker = Picker,
id = ID_W,
balance = Balance,
buttons = Buttons},
{Frame, State}.
safe_size(Prefs) ->
Display = wxDisplay:new(),
GSize = wxDisplay:getGeometry(Display),
CSize = wxDisplay:getClientArea(Display),
PPI =
try
wxDisplay:getPPI(Display)
catch
Class:Exception -> {Class, Exception}
end,
ok = log(info, "Geometry: ~p", [GSize]),
ok = log(info, "ClientArea: ~p", [CSize]),
ok = log(info, "PPI: ~p", [PPI]),
Geometry =
case maps:find(geometry, Prefs) of
{ok, none} ->
{X, Y, _, _} = GSize,
{center, {X, Y, 420, 520}};
{ok, G} ->
{pref, G};
error ->
{X, Y, _, _} = GSize,
{center, {X, Y, 420, 520}}
end,
ok = wxDisplay:destroy(Display),
Geometry.
-spec handle_call(Message, From, State) -> Result
when Message :: term(),
From :: {pid(), reference()},
State :: state(),
Result :: {reply, Response, NewState}
| {noreply, State},
Response :: ok
| {error, {listening, inet:port_number()}},
NewState :: state().
handle_call(Unexpected, From, State) ->
ok = log(warning, "Unexpected call from ~tp: ~tp~n", [From, Unexpected]),
{noreply, State}.
-spec handle_cast(Message, State) -> {noreply, NewState}
when Message :: term(),
State :: state(),
NewState :: state().
%% @private
%% The gen_server:handle_cast/2 callback.
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_cast-2
handle_cast({show, Accounts}, State) ->
NewState = do_show(Accounts, State),
{noreply, NewState};
handle_cast(password, State) ->
ok = do_ask_password(State),
{noreply, State};
handle_cast(Unexpected, State) ->
ok = log(warning, "Unexpected cast: ~tp~n", [Unexpected]),
{noreply, State}.
-spec handle_info(Message, State) -> {noreply, NewState}
when Message :: term(),
State :: state(),
NewState :: state().
%% @private
%% The gen_server:handle_info/2 callback.
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_info-2
handle_info(Unexpected, State) ->
ok = log(warning, "Unexpected info: ~tp~n", [Unexpected]),
{noreply, State}.
-spec handle_event(Event, State) -> {noreply, NewState}
when Event :: term(),
State :: state(),
NewState :: state().
%% @private
%% The wx_object:handle_event/2 callback.
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_info-2
handle_event(#wx{event = #wxCommand{type = command_button_clicked},
id = ID},
State = #s{buttons = Buttons}) ->
NewState =
case lists:keyfind(ID, #w.id, Buttons) of
#w{name = make_key} -> make_key(State);
#w{name = recover} -> recover_key(State);
#w{name = mnemonic} -> show_mnemonic(State);
#w{name = rename} -> rename_key(State);
#w{name = drop_key} -> drop_key(State);
#w{name = grids} -> grids_dialogue(State);
#w{name = Name} -> handle_button(Name, State);
false -> State
end,
{noreply, NewState};
handle_event(#wx{event = #wxCommand{type = command_listbox_selected,
commandInt = Selected}},
State) ->
NewState = do_selection(Selected, State),
{noreply, NewState};
handle_event(#wx{event = #wxClose{}}, State = #s{frame = Frame, prefs = Prefs}) ->
Geometry =
case wxTopLevelWindow:isMaximized(Frame) of
true ->
max;
false ->
{X, Y} = wxWindow:getPosition(Frame),
{W, H} = wxWindow:getSize(Frame),
{X, Y, W, H}
end,
NewPrefs = maps:put(geometry, Geometry, Prefs),
ok = gmc_con:save(NewPrefs),
ok = gmc_con:stop(),
ok = wxWindow:destroy(Frame),
{noreply, State};
handle_event(Event, State) ->
ok = tell(info, "Unexpected event ~tp State: ~tp~n", [Event, State]),
{noreply, State}.
code_change(_, State, _) ->
{ok, State}.
terminate(Reason, State) ->
ok = log(info, "Reason: ~tp, State: ~tp", [Reason, State]),
wx:destroy().
%%% Doers
make_key(State = #s{frame = Frame, j = J}) ->
Dialog = wxDialog:new(Frame, ?wxID_ANY, J("New Key")),
Sizer = wxBoxSizer:new(?wxVERTICAL),
NameSz = wxStaticBoxSizer:new(?wxVERTICAL, Dialog, [{label, J("Name (Optional)")}]),
NameTx = wxTextCtrl:new(Dialog, ?wxID_ANY),
SeedSz = wxStaticBoxSizer:new(?wxVERTICAL, Dialog, [{label, J("Seed (Optional)")}]),
SeedTx = wxTextCtrl:new(Dialog, ?wxID_ANY, [{style, ?wxDEFAULT bor ?wxTE_MULTILINE}]),
ok = wxTextCtrl:setValue(SeedTx, base64:encode(crypto:strong_rand_bytes(64))),
OptionsSz = wxStaticBoxSizer:new(?wxHORIZONTAL, Dialog, [{label, J("Options")}]),
Encodings =
["Base64",
"UTF-8",
"Base58"],
EncodingOptions = wxChoice:new(Dialog, ?wxID_ANY, [{choices, Encodings}]),
ok = wxChoice:setSelection(EncodingOptions, 0),
Transforms =
["SHA-3 (256)",
"SHA-2 (256)",
"XOR",
"Direct Input (no transform)"],
TransformOptions = wxChoice:new(Dialog, ?wxID_ANY, [{choices, Transforms}]),
ok = wxChoice:setSelection(TransformOptions, 0),
ButtSz = wxBoxSizer:new(?wxHORIZONTAL),
Affirm = wxButton:new(Dialog, ?wxID_OK),
Cancel = wxButton:new(Dialog, ?wxID_CANCEL),
_ = wxBoxSizer:add(ButtSz, Affirm, zxw:flags(wide)),
_ = wxBoxSizer:add(ButtSz, Cancel, zxw:flags(wide)),
_ = wxStaticBoxSizer:add(NameSz, NameTx, zxw:flags(base)),
_ = wxStaticBoxSizer:add(SeedSz, SeedTx, zxw:flags(wide)),
_ = wxStaticBoxSizer:add(OptionsSz, EncodingOptions, zxw:flags(wide)),
_ = wxStaticBoxSizer:add(OptionsSz, TransformOptions, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, NameSz, zxw:flags(base)),
_ = wxBoxSizer:add(Sizer, SeedSz, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, OptionsSz, zxw:flags(base)),
_ = wxBoxSizer:add(Sizer, ButtSz, zxw:flags(base)),
ok = wxDialog:setSizer(Dialog, Sizer),
ok = wxBoxSizer:layout(Sizer),
ok = wxFrame:setSize(Dialog, {400, 300}),
ok = wxFrame:center(Dialog),
ok = wxStyledTextCtrl:setFocus(NameTx),
ok =
case wxDialog:showModal(Dialog) of
?wxID_OK ->
Type = {eddsa, ed25519},
Size = 256,
Name = wxTextCtrl:getValue(NameTx),
Seed = wxTextCtrl:getValue(SeedTx),
Encoding =
case wxChoice:getSelection(EncodingOptions) of
0 -> base64;
1 -> utf8;
2 -> base58
end,
Transform =
case wxChoice:getSelection(TransformOptions) of
0 -> {sha3, 256};
1 -> {sha2, 256};
2 -> {x_or, 256};
3 -> raw
end,
gmc_con:make_key(Type, Size, Name, Seed, Encoding, Transform);
?wxID_CANCEL ->
ok
end,
ok = wxDialog:destroy(Dialog),
State.
recover_key(State = #s{frame = Frame, j = J}) ->
Dialog = wxDialog:new(Frame, ?wxID_ANY, J("Mnemonic")),
Sizer = wxBoxSizer:new(?wxVERTICAL),
MnemSz = wxStaticBoxSizer:new(?wxVERTICAL, Dialog, [{label, J("Recovery Phrase")}]),
MnemTx = wxTextCtrl:new(Dialog, ?wxID_ANY, [{style, ?wxTE_MULTILINE}]),
_ = wxStaticBoxSizer:add(MnemSz, MnemTx, zxw:flags(wide)),
ButtSz = wxBoxSizer:new(?wxHORIZONTAL),
Affirm = wxButton:new(Dialog, ?wxID_OK),
Cancel = wxButton:new(Dialog, ?wxID_CANCEL),
_ = wxBoxSizer:add(ButtSz, Affirm, zxw:flags(wide)),
_ = wxBoxSizer:add(ButtSz, Cancel, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, MnemSz, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, ButtSz, zxw:flags(base)),
ok = wxDialog:setSizer(Dialog, Sizer),
ok = wxBoxSizer:layout(Sizer),
ok = wxFrame:center(Dialog),
ok = wxStyledTextCtrl:setFocus(MnemTx),
ok =
case wxDialog:showModal(Dialog) of
?wxID_OK ->
Mnemonic = wxTextCtrl:getValue(MnemTx),
gmc_con:recover_key(Mnemonic);
?wxID_CANCEL ->
ok
end,
ok = wxDialog:destroy(Dialog),
State.
show_mnemonic(State = #s{accounts = []}) ->
State;
show_mnemonic(State = #s{picker = Picker}) ->
case wxListBox:getSelection(Picker) of
-1 -> State;
Selected -> show_mnemonic(Selected + 1, State)
end.
show_mnemonic(Selected, State = #s{frame = Frame, j = J, accounts = Accounts}) ->
#ak{id = ID} = lists:nth(Selected, Accounts),
{ok, Mnemonic} = gmc_con:mnemonic(ID),
Dialog = wxDialog:new(Frame, ?wxID_ANY, J("Mnemonic")),
Sizer = wxBoxSizer:new(?wxVERTICAL),
MnemSz = wxStaticBoxSizer:new(?wxVERTICAL, Dialog, [{label, J("Recovery Phrase")}]),
Options = [{value, Mnemonic}, {style, ?wxTE_MULTILINE bor ?wxTE_READONLY}],
MnemTx = wxTextCtrl:new(Dialog, ?wxID_ANY, Options),
_ = wxStaticBoxSizer:add(MnemSz, MnemTx, zxw:flags(wide)),
ButtSz = wxBoxSizer:new(?wxHORIZONTAL),
Affirm = wxButton:new(Dialog, ?wxID_OK),
_ = wxBoxSizer:add(ButtSz, Affirm, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, MnemSz, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, ButtSz, zxw:flags(base)),
ok = wxDialog:setSizer(Dialog, Sizer),
ok = wxBoxSizer:layout(Sizer),
ok = wxFrame:center(Dialog),
ok = wxStyledTextCtrl:setFocus(MnemTx),
?wxID_OK = wxDialog:showModal(Dialog),
ok = wxDialog:destroy(Dialog),
State.
rename_key(State = #s{accounts = []}) ->
State;
rename_key(State = #s{picker = Picker}) ->
case wxListBox:getSelection(Picker) of
-1 -> State;
Selected -> rename_key(Selected + 1, State)
end.
rename_key(Selected, State = #s{frame = Frame, j = J, accounts = Accounts}) ->
#ak{id = ID, name = Name} = lists:nth(Selected, Accounts),
Dialog = wxDialog:new(Frame, ?wxID_ANY, J("New Key")),
Sizer = wxBoxSizer:new(?wxVERTICAL),
NameSz = wxStaticBoxSizer:new(?wxVERTICAL, Dialog, [{label, J("Name (Optional)")}]),
NameTx = wxTextCtrl:new(Dialog, ?wxID_ANY),
ok = wxTextCtrl:setValue(NameTx, Name),
_ = wxStaticBoxSizer:add(NameSz, NameTx, zxw:flags(base)),
ButtSz = wxBoxSizer:new(?wxHORIZONTAL),
Affirm = wxButton:new(Dialog, ?wxID_OK),
Cancel = wxButton:new(Dialog, ?wxID_CANCEL),
_ = wxBoxSizer:add(ButtSz, Affirm, zxw:flags(wide)),
_ = wxBoxSizer:add(ButtSz, Cancel, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, NameSz, zxw:flags(base)),
_ = wxBoxSizer:add(Sizer, ButtSz, zxw:flags(base)),
ok = wxDialog:setSizer(Dialog, Sizer),
ok = wxBoxSizer:layout(Sizer),
ok = wxFrame:center(Dialog),
ok = wxStyledTextCtrl:setFocus(NameTx),
ok =
case wxDialog:showModal(Dialog) of
?wxID_OK ->
NewName = wxTextCtrl:getValue(NameTx),
gmc_con:rename_key(ID, NewName);
?wxID_CANCEL ->
ok
end,
ok = wxDialog:destroy(Dialog),
State.
drop_key(State = #s{accounts = []}) ->
State;
drop_key(State = #s{picker = Picker}) ->
case wxListBox:getSelection(Picker) of
-1 -> State;
Selected -> drop_key(Selected + 1, State)
end.
drop_key(Selected, State = #s{frame = Frame, j = J, accounts = Accounts}) ->
#ak{id = ID, name = Name} = lists:nth(Selected, Accounts),
Dialog = wxDialog:new(Frame, ?wxID_ANY, J("New Key")),
Sizer = wxBoxSizer:new(?wxVERTICAL),
Message = ["REALLY delete key: ", Name, " ?"],
MessageT = wxStaticText:new(Dialog, ?wxID_ANY, Message),
ButtSz = wxBoxSizer:new(?wxHORIZONTAL),
Affirm = wxButton:new(Dialog, ?wxID_OK),
Cancel = wxButton:new(Dialog, ?wxID_CANCEL),
_ = wxBoxSizer:add(ButtSz, Affirm, zxw:flags(wide)),
_ = wxBoxSizer:add(ButtSz, Cancel, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, MessageT, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, ButtSz, zxw:flags(base)),
ok = wxDialog:setSizer(Dialog, Sizer),
ok = wxBoxSizer:layout(Sizer),
ok = wxFrame:center(Dialog),
ok =
case wxDialog:showModal(Dialog) of
?wxID_OK -> gmc_con:drop_key(ID);
?wxID_CANCEL -> ok
end,
ok = wxDialog:destroy(Dialog),
State.
grids_dialogue(State = #s{frame = Frame, j = J}) ->
tell("Handle GRIDS URL"),
% ok =
% case zxw:modal_text_input(Frame, J("GRIDS"), J("ZA GRIDS"), [J("URL")]) of
% {ok, [URL]} -> tell("Received URL: ~p", [URL]);
% cancel -> tell("User cancelled GRIDS action.")
% end,
State.
handle_button(Name, State) ->
ok = tell("Button Click: ~p", [Name]),
State.
do_selection(Selected,
State = #s{prefs = Prefs, accounts = Accounts,
balance = {_, #w{wx = B}}, id = {_, #w{wx = I}}}) ->
#ak{id = ID, balance = Pucks} = lists:nth(Selected + 1, Accounts),
ok = wxStaticText:setLabel(I, ID),
ok = wxStaticText:setLabel(B, price_to_string(Pucks)),
NewPrefs = maps:put(selected, Selected, Prefs),
State#s{prefs = NewPrefs}.
do_show(Accounts, State = #s{prefs = Prefs, picker = Picker}) ->
AKs = [Name || #ak{name = Name} <- Accounts],
ok = wxListBox:set(Picker, AKs),
case Accounts of
[] ->
State;
[_] ->
Selected = 0,
ok = wxListBox:setSelection(Picker, Selected),
do_selection(Selected, State#s{accounts = Accounts});
_ ->
Selected = maps:get(selected, Prefs),
ok = wxListBox:setSelection(Picker, Selected),
do_selection(Selected, State#s{accounts = Accounts})
end.
do_ask_password(#s{frame = Frame, j = J}) ->
Dialog = wxDialog:new(Frame, ?wxID_ANY, J("Password")),
Sizer = wxBoxSizer:new(?wxVERTICAL),
Label = "Password (leave blank for no password)",
PassSz = wxStaticBoxSizer:new(?wxVERTICAL, Dialog, [{label, J(Label)}]),
PassTx = wxTextCtrl:new(Dialog, ?wxID_ANY),
_ = wxStaticBoxSizer:add(PassSz, PassTx, zxw:flags(wide)),
ButtSz = wxBoxSizer:new(?wxHORIZONTAL),
Affirm = wxButton:new(Dialog, ?wxID_OK),
_ = wxBoxSizer:add(ButtSz, Affirm, zxw:flags(wide)),
_ = wxBoxSizer:add(Sizer, PassSz, zxw:flags(base)),
_ = wxBoxSizer:add(Sizer, ButtSz, zxw:flags(base)),
ok = wxDialog:setSizer(Dialog, Sizer),
ok = wxBoxSizer:layout(Sizer),
ok = wxFrame:center(Dialog),
ok = wxStyledTextCtrl:setFocus(PassTx),
ok =
case wxDialog:showModal(Dialog) of
?wxID_OK ->
Phrase =
case wxTextCtrl:getValue(PassTx) of
"" -> none;
P -> P
end,
gmc_con:login(Phrase);
?wxID_CANCEL ->
gmc_con:login(none)
end,
wxDialog:destroy(Dialog).
%%% Helpers
price_to_string(Pucks) ->
Gaju = 1000000000000000000,
H = integer_to_list(Pucks div Gaju),
R = Pucks rem Gaju,
case string:strip(lists:flatten(io_lib:format("~18..0w", [R])), right, $0) of
[] -> H;
T -> string:join([H, T], ".")
end.
string_to_price(String) ->
case string:split(String, ".") of
[H] -> join_price(H, "0");
[H, T] -> join_price(H, T);
_ -> {error, bad_price}
end.
join_price(H, T) ->
try
Parts = [H, string:pad(T, 18, trailing, $0)],
Price = list_to_integer(unicode:characters_to_list(Parts)),
case Price < 0 of
false -> {ok, Price};
true -> {error, negative_price}
end
catch
error:R -> {error, R}
end.
+39
View File
@@ -0,0 +1,39 @@
%%% A rework of the JumpText idea. To be adapted into actual JumpText for v2.0.
%%% To add translations to a module you add a file named ?MODULE.trans to priv/i18n/.
%%% The file contains an Erlang terms file of the form:
%%% `{LangCode :: atom(), Translations :: #{Phrase :: string() := Translation :: string()}}'
%%% The entire file's contents are returned by `read_translations/1'.
%%% The function `j/2' extracts the dictionary requested and returns a translation
%%% function that closes over the desired phrase dictionary.
%%% The customary way to insert translations into a program is to assign the translation
%%% closure the name `J' and keep it in the local process state. When the user selects
%%% another language, create a new `J' with the desired language.
%%%
%%% `oneshot_j/2' is a convenience function for those who don't intend to keep the
%%% library of translations in memory (calling `oneshot_j/2' will always perform a disk
%%% read, where `j/2' could be called any number of times without a disk read if the
%%% translation library is retained).
-module(gmc_jt).
-export([read_translations/1, j/2, oneshot_j/2]).
read_translations(Module) ->
File = atom_to_list(Module) ++ ".trans",
Path = filename:join([zx:get_home(), "priv", "i18n", File]),
case file:consult(Path) of
{ok, Translations} -> Translations;
{error, enoent} -> []
end.
j(Lang, Translations) ->
case proplists:get_value(Lang, Translations, none) of
none -> fun(Phrase) -> Phrase end;
Dict -> fun(Phrase) -> maps:get(Phrase, Dict, Phrase) end
end.
oneshot_j(Module, Lang) ->
Translations = read_translations(Module),
j(Lang, Translations).
+204
View File
@@ -0,0 +1,204 @@
%%% @doc
%%% Key functions go here.
%%%
%%% The main reason this is a module of its own is that in the original architecture
%%% it was a process rather than just a library of functions. Now that it exists, though,
%%% there is little motivation to cram everything here into the controller process's
%%% code.
%%% @end
-module(gmc_key_master).
-export([make_key/2, encode/1, decode/1]).
-export([lcg/1]).
%-export([start_link/1]).
%-export([init/1, terminate/2, code_change/3,
% handle_call/3, handle_cast/2, handle_info/2, handle_event/2]).
%-include("$zx_include/zx_logger.hrl").
-include("gmc.hrl").
%-record(s,
% {wx = none :: none | wx:wx_object(),
% frame = none :: none | wx:wx_object(),
% lang = en :: en | jp,
% j = none :: none | fun(),
% prefs = #{} :: #{atom() := term()},
% accounts = [] :: [clutch:ak()],
% picker = none :: none | wx:wx_object(),
% balance = {#w{}, #w{}} :: labeled(),
% buttons = [] :: [widget()]}).
%%% Startup Functions
%start_link(Accounts) ->
% wx_object:start_link({local, ?MODULE}, ?MODULE, Accounts, []).
%init({Accounts, Prefs}) ->
% ok = log(info, "GUI starting..."),
% Lang = maps:get(lang, Prefs, en_us),
% Trans = gmc_jt:read_translations(?MODULE),
% J = gmc_jt:j(Lang, Trans),
%
% Selected = maps:get(selected, Prefs, 1),
% AKs = [ID || #ak{id = ID} <- Accounts],
%
% Wx = wx:new(),
% Frame = wxFrame:new(Wx, ?wxID_ANY, J("Gajumaru Clutch")),
% MainSz = wxBoxSizer:new(?wxVERTICAL),
%%%
make_key("", <<>>) ->
Pair = #{public := Public} = ecu_eddsa:sign_keypair(),
ID = aeser_api_encoder:encode(account_pubkey, Public),
Name = binary_to_list(ID),
#key{name = Name, id = ID, pair = Pair};
make_key("", Seed) ->
Pair = #{public := Public} = ecu_eddsa:sign_seed_keypair(Seed),
ID = aeser_api_encoder:encode(account_pubkey, Public),
Name = binary_to_list(ID),
#key{name = Name, id = ID, pair = Pair};
make_key(Name, <<>>) ->
Pair = #{public := Public} = ecu_eddsa:sign_keypair(),
ID = aeser_api_encoder:encode(account_pubkey, Public),
#key{name = Name, id = ID, pair = Pair};
make_key(Name, Seed) ->
Pair = #{public := Public} = ecu_eddsa:sign_seed_keypair(Seed),
ID = aeser_api_encoder:encode(account_pubkey, Public),
#key{name = Name, id = ID, pair = Pair}.
-spec encode(Secret) -> Phrase
when Secret :: binary(),
Phrase :: string().
%% @doc
%% The encoding and decoding procesures are written to be able to handle any
%% width of bitstring or binary and a variable size dictionary. The magic numbers
%% 32, 4096 and 12 have been dropped in because currently these are known, but that
%% will change in the future if the key size or type changes.
encode(Bin) ->
<<Number:(32 * 8)>> = Bin,
DictSize = 4096,
Words = read_words(),
% Width = chunksize(DictSize - 1, 2),
Width = 12,
Chunks = chunksize(Number, DictSize),
Binary = <<Number:(Chunks * Width)>>,
encode(Width, Binary, Words).
encode(Width, Bits, Words) ->
CheckSum = checksum(Width, Bits),
encode(Width, <<CheckSum:Width, Bits/bitstring>>, Words, []).
encode(_, <<>>, _, Acc) ->
unicode:characters_to_list(lists:join(" ", lists:reverse(Acc)));
encode(Width, Bits, Words, Acc) ->
<<I:Width, Rest/bitstring>> = Bits,
Word = lists:nth(I + 1, Words),
encode(Width, Rest, Words, [Word | Acc]).
-spec decode(Phrase) -> {ok, Secret} | {error, Reason}
when Phrase :: string(),
Secret :: binary(),
Reason :: bad_phrase | bad_word.
%% @doc
%% Reverses the encoded secret string back into its binary representation.
decode(Encoded) ->
DictSize = 4096,
Words = read_words(),
Width = chunksize(DictSize - 1, 2),
decode(Width, Words, Encoded).
decode(Width, Words, Encoded) when is_list(Encoded) ->
decode(Width, Words, list_to_binary(Encoded));
decode(Width, Words, Encoded) ->
Split = string:lexemes(Encoded, " "),
decode(Width, Words, Split, <<>>).
decode(Width, Words, [Word | Rest], Acc) ->
case find(Word, Words) of
{ok, N} -> decode(Width, Words, Rest, <<Acc/bitstring, N:Width>>);
Error -> Error
end;
decode(Width, _, [], Acc) ->
sumcheck(Width, Acc).
chunksize(N, C) ->
chunksize(N, C, 0).
chunksize(0, _, A) -> A;
chunksize(N, C, A) -> chunksize(N div C, C, A + 1).
read_words() ->
Path = filename:join([zx:get_home(), "priv", "words4096.txt"]),
{ok, Bin} = file:read_file(Path),
string:lexemes(Bin, "\n").
find(Word, Words) ->
find(Word, Words, 0).
find(Word, [Word | _], N) -> {ok, N};
find(Word, [_ | Rest], N) -> find(Word, Rest, N + 1);
find(Word, [], _) -> {error, {bad_word, Word}}.
checksum(Width, Bits) ->
checksum(Width, Bits, 0).
checksum(_, <<>>, Sum) ->
Sum;
checksum(Width, Bits, Sum) ->
<<N:Width, Rest/bitstring>> = Bits,
checksum(Width, Rest, N bxor Sum).
sumcheck(Width, Bits) ->
<<CheckSum:Width, Binary/bitstring>> = Bits,
case checksum(Width, Binary) =:= CheckSum of
true ->
<<N:(bit_size(Binary))>> = Binary,
{ok, <<N:(32 * 8)>>};
false ->
{error, bad_phrase}
end.
-spec lcg(integer()) -> integer().
%% A simple PRNG that fits into 32 bits and is easy to implement anywhere (Kotlin).
%% Specifically, it is a "linear congruential generator" of the Lehmer variety.
%% The constants used are based on recommendations from Park, Miller and Stockmeyer:
%% https://www.firstpr.com.au/dsp/rand31/p105-crawford.pdf#page=4
%%
%% The input value should be between 1 and 2^31-1.
%%
%% The purpose of this PRNG is for password-based dictionary shuffling.
lcg(N) ->
M = 16#7FFFFFFF,
A = 48271,
Q = 44488, % M div A
R = 3399, % M rem A
Div = N div Q,
Rem = N rem Q,
S = Rem * A,
T = Div * R,
Result = S - T,
case Result < 0 of
false -> Result;
true -> Result + M
end.
+46
View File
@@ -0,0 +1,46 @@
%%% @doc
%%% Clutch Top-level Supervisor
%%%
%%% The very top level supervisor in the system. It only has one service branch: the
%%% "con" (program controller). The con is the
%%% only be one part of a larger system. Were this a game system, for example, the
%%% item data management service would be a peer, as would a login credential provision
%%% service, game world event handling, and so on.
%%%
%%% See: http://erlang.org/doc/design_principles/applications.html
%%% See: http://zxq9.com/archives/1311
%%% @end
-module(gmc_sup).
-vsn("0.1.0").
-behaviour(supervisor).
-author("Craig Everett <craigeverett@qpq.swiss>").
-copyright("Craig Everett <craigeverett@qpq.swiss>").
-license("GPL-3.0-or-later").
-export([start_link/0]).
-export([init/1]).
-spec start_link() -> {ok, pid()}.
%% @private
%% This supervisor's own start function.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
-spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}.
%% @private
%% The OTP init/1 function.
init([]) ->
RestartStrategy = {one_for_one, 0, 60},
Clients = {gmc_con,
{gmc_con, start_link, []},
permanent,
5000,
worker,
[gmc_con]},
Children = [Clients],
{ok, {RestartStrategy, Children}}.