83 Commits

Author SHA1 Message Date
zxq9 11a9b36681 Add shared secret functions to hz_key_master 2026-05-30 11:53:36 +09:00
zxq9 75bc52ede3 Doc formatting adjustments 2026-05-27 21:49:30 +09:00
zxq9 29619f08b7 Remove stdout line 2026-05-27 16:50:23 +09:00
zxq9 af46223163 Minor fixes 2026-05-27 16:41:45 +09:00
zxq9 9cafdd2b0f Merge pull request 'Improve specs' (#31) from improve_specs into master
Reviewed-on: #31
2026-05-26 15:38:26 +09:00
zxq9 6d429aa6a4 Merge branch 'master' into improve_specs 2026-05-26 15:38:08 +09:00
zxq9 fcf85077b2 Minor 2026-05-26 15:36:16 +09:00
zxq9 3585dbe534 Merge pull request 'Doc update for hz_sophia and hz_aaci and some minor fixes' (#30) from spivee/docs into master
Reviewed-on: #30
2026-05-26 09:44:53 +09:00
dimitar.p.ivanov 9a7a2a98c4 General polish (#28)
Co-authored-by: Craig Everett <zxq9@zxq9.com>
Co-authored-by: Dimitar Ivanov <dimitar.p.ivanov@gmail.com>
Reviewed-on: #28
2026-05-22 16:54:16 +09:00
dimitar.p.ivanov 4530fd2e93 Merge pull request 'Fix typespec' (#29) from respec into improve_specs
Reviewed-on: #29
2026-05-22 15:57:11 +09:00
zxq9 2a7079129f Fix typespec
Source needs to be defined as a binary.
2026-05-21 17:07:57 +09:00
Dimitar Ivanov 88aeb39d4a Fix a contract create bug 2026-05-20 17:02:36 +03:00
Jarvis Carroll 9fc89c0c22 Add type information for hz_sophia
This one was much simpler to do than hz_aaci, since it doesn't introduce any new types.

I could have made note of some of the conventions, where a type can be represented in multiple
ways in Sophia syntax, or where these functions are actually more lenient than the compiler, but
it isn't as easy to break those notes up from the basic function usage, like it was in hz_aaci,
where those aforementioned new types are used.
2026-05-19 12:29:30 +00:00
Jarvis Carroll 23c13f607e Document hz_aaci functions
Once the types were documented, the functions were easy to document. Just say "see erlang_expr/0 for details" over and over! ;p
2026-05-19 12:29:30 +00:00
Jarvis Carroll 8bc79d3b3f Fix dialyzer warnings for hz_aaci
A while ago I tried dialyzer and discovered that actually a lot of the AACI generation process
never fails, and whatever the one failure was that was possible, I think I decided was unnecessary,
and made that produce {ok, unknown_type} instead. I then set the types of these functions to be
{ok, Result} | {error, none()}, since there were in fact no errors, but dialyzer still spewed out
warnings for all the case blocks that redundantly check for these impossible error conditions.

Anyway now that is fixed! The behavior and external interface are all the same still, there are just fewer warnings
now.

Also added specs for a couple more internal functions, just because.
So noperhaps realized that actually none of it should fail. I never went in and
removed all the {ok, _} wrappers, but I did at least type the functions with the correct error list
2026-05-19 12:29:30 +00:00
Jarvis Carroll 3fae9a2edd Document hz_aaci types 2026-05-19 12:29:30 +00:00
zxq9 a3b19747b6 Adjust error condition 2026-05-18 12:56:31 +09:00
zxq9 f8e9333b4b Doc update 2026-05-14 11:01:37 +09:00
zxq9 eaccd50764 Fill in the holes in hz.erl docs and make hz_fetcher.erl 2026-05-13 19:48:49 +09:00
zxq9 9fd8dbd1a6 Merge branch 'master' into docs 2026-05-13 19:25:59 +09:00
Dimitar Ivanov f0f86ed36d Improve specs 2026-05-13 10:04:23 +03:00
Jarvis Carroll ed252b4c06 Also note index in record_element
I changed it from noting the index to just noting the field name, but
actually both pieces of information are important, since if there was
a type error, presumably the type information is actually wrong.

Now we put the index first, since that is the part of the FATE tuple
that failed, and then the field name that that would be if the type
information were correct, in case that is useful.
2026-05-12 06:07:58 +00:00
Jarvis Carroll 5dcc05d56a Change fate_to_erlang warning
This warning always confuses me. Usually it is a case I haven't actually implemented,
but I don't need the program to diagnose that for me, I need the program to tell me what the
type was, so that I can work out why it thinks it isn't implemented.

All three terms of the annotated type are relevant, but the annotated version can only differ from the normalized version if
it is a record or variant definition, so we special case those two just to communicate that the fact that it is *some* kind of record
did successfully pass through to the coerce logic, and otherwise we just try and print the opaque and normalized types faithfully.
2026-05-12 06:00:26 +00:00
Jarvis Carroll 2eca3a5338 Handle singleton records in erlang_to_fate
I realized this case needed special handling in hz_sophia, but didn't
get around to covering it properly in the older hz_aaci analogues.

While I was at it, I went and improved the error paths for record elements.
2026-05-12 04:23:21 +00:00
zxq9 e595991616 Correct keyblock() type 2026-05-10 21:02:23 +09:00
zxq9 da92d80334 Merge pull request 'Fix docs' (#24) from contract-spend into master
Reviewed-on: #24
2026-05-10 19:45:08 +09:00
zxq9 f821d57c1c Fix docs 2026-05-10 19:35:20 +09:00
zxq9 e87be689a8 Merge pull request 'Allow spending to contract addresses' (#23) from contract-spend into master
Reviewed-on: #23
2026-05-10 17:57:00 +09:00
zxq9 2a7de4fee1 verup 2026-05-10 17:56:34 +09:00
zxq9 82d08da8ca Allow spending to contract addresses 2026-05-10 16:14:00 +09:00
zxq9 85d0c6fd04 Doc fix 2026-05-10 15:52:39 +09:00
zxq9 d8221e0b25 Doc fix
#20
2026-05-10 15:49:11 +09:00
zxq9 b950bb8a67 Merge pull request 'Make Hakuzaru Great Again' (#22) from parser into master
Reviewed-on: #22
2026-05-10 15:26:44 +09:00
zxq9 a4914c1ad1 Making custom dir. 2026-05-10 15:22:13 +09:00
zxq9 9e6d9ec02e Merge branch 'master' into parser 2026-05-10 15:14:57 +09:00
zxq9 4b9fa65672 Merge down 2026-05-10 15:09:47 +09:00
zxq9 74aaad297a Merge branch 'master' into parser 2026-05-10 15:09:13 +09:00
zxq9 c9ead44aa2 Let non-zx projects call contract_create* 2026-05-10 15:01:50 +09:00
zxq9 c54c0db17a Fix list -> binary arg 2026-05-10 13:16:13 +09:00
zxq9 cd4f6a56a5 Differentiate between source return types 2026-05-09 20:07:52 +09:00
zxq9 fd2158a465 base64 -> bytearray encoding 2026-05-09 15:19:51 +09:00
zxq9 7fc3cd00da WIP 2026-05-08 23:04:56 +09:00
zxq9 02945dd10d derp 2026-05-08 19:47:25 +09:00
zxq9 695e7e4828 WIP 2026-05-08 15:48:05 +09:00
zxq9 9f02f73dbd verup 2026-05-08 08:43:07 +09:00
zxq9 fd8766a249 Unify call arg order between call and create 2026-05-07 19:53:36 +09:00
Jarvis Carroll 540b2c513b Fill AACI and coerce type specs
Any error reasons or paths are just term() still, and ACI doesn't have a defined spec in the compiler, so whatever, but the AACI types, the erlang representation of terms, and the four different kinds of coerce function are all spec'd now.

Also some internal type substitution functions were given types, just in the hopes of catching some errors, but dyalizer doesn't seem to complain at all no matter how badly I break my code. Strange approach to making a type system, but oh well.
2026-02-26 12:57:49 +00:00
zxq9 bda4e89e58 Merge branch 'parser' of ssh://git.qpq.swiss:21203/QPQ-AG/hakuzaru into parser 2026-02-25 16:21:23 +09:00
zxq9 f277e79096 Minor doc and style edits 2026-02-25 16:20:52 +09:00
Jarvis Carroll ddec3bfa74 add more format options to decode_bytearray
I reversed the argument order here, since the Format option is sort of kind of almost optional, but I am not sure if that was a good idea.
2026-02-24 06:12:00 +00:00
Jarvis Carroll a0fbeebcdb Pretty print Sophia expressions.
I think all of the tests roundtrip now, so if my parser was thorough, the pretty printer should be as thorough.
2026-02-17 07:26:42 +00:00
Jarvis Carroll 78c9c67f38 typecheck bits
Sophia bitstrings aren't really something you initialize manually, so we have to make up a literal format for them. Failing that, we just accept arbitrary integers and bytearrays as bitstrings.
2026-02-13 06:25:24 +00:00
Jarvis Carroll 9bc0ffafd1 bool/char literals
Character literals were the main complexity here, but I threw booleans in as well, since that covers all the major literals.
2026-02-13 06:25:24 +00:00
zxq9 a1fc5f19fa Merge branch 'parser' of ssh://git.qpq.swiss:21203/QPQ-AG/hakuzaru into parser 2026-02-13 13:50:57 +09:00
zxq9 efe0a64056 Update comments, add fate and sophia tagged args 2026-02-13 13:50:29 +09:00
Jarvis Carroll 60985130cb Refine tuple parsing errors
There are four major fixes here:
1. some eof tokens were being pattern matched with the wrong arity
2. tuples that are too long actually speculatively parse as an untyped tuple, and then complain that there were too many elements,
3. singleton tuples with a trailing comma are now handled differently to grouping parentheses, consistently between typed and untyped logic
4. the extra return values used to detect untyped singleton tuples are also used to pass the close paren position, so that too_many_elements can report the correct file position too.

Point 4. also completely removes the need for tracking open paren positions that I was doing, and that I thought I would need to do even more of in the ambiguous-open-paren-stack case.
2026-02-13 04:08:58 +00:00
zxq9 6c172c4783 Adjusting a few calls. 2026-02-12 17:44:56 +09:00
Jarvis Carroll 3838a7e3c5 Parse qualified names.
This seemed like it was going to be insanely insanely complex, but
then it turns out the compiler doesn't accept spaces in qualified
names, so I can just dump periods in the lexer and hit it with
string:split/3. Easy.
2026-02-05 07:13:25 +00:00
Jarvis Carroll d014ae0982 Handle token/parse errors more carefully 2026-02-04 07:00:39 +00:00
Jarvis Carroll bb4bcbb7de remove 'tk' atom from file positions 2026-02-03 06:08:54 +00:00
Jarvis Carroll a695c21fc9 Parse address literals.
Also signatures.
2026-02-03 06:00:40 +00:00
Jarvis Carroll 493bdb990c Fix lexer row/column calculations. 2026-02-03 01:42:17 +00:00
Jarvis Carroll 17f635af61 Parse long hex escape codes
This doesn't work super consistently in the compiler, for codepoints above 127, but it should work fine for us, so, oh well!
2026-02-03 00:41:00 +00:00
Jarvis Carroll 272ed01fdc Singleton record/tuple parsing.
Records are a simple case to detect and handle correctly.

Tuples took an entire rewrite of the little tuple parsing bit of the code.
2026-01-30 08:12:32 +00:00
Jarvis Carroll 49cd8b6687 Parse strings 2026-01-29 06:18:06 +00:00
Jarvis Carroll 966b4b2748 Calculate scalar values during lexing
This saves some effort and probably some performance for things like integers, but I'm mainly doing this in anticipation of string literals, because it would just be ridiculous to read code that lexes string literals twice.
2026-01-29 04:06:19 +00:00
Jarvis Carroll fe182a5233 Handle underscores in integers/bytes
This forces us to test for alpha/num/hex enough times that it's now worth making macros for these things.
2026-01-29 03:03:11 +00:00
Jarvis Carroll f1696e2b9e Bytes lexing
I don't handle underscores in bytes correctly... Nor in integers, for that matter.
2026-01-29 02:01:16 +00:00
Jarvis Carroll 2bf384ca82 Infer correct values for tests automatically
Now tests compare the literal parser against the output of the
compiler. The little example contracts we are compiling for the
AACI already had the FATE value in them, in the form of the
instruction
	{'RETURNR', {immediate, FateValue}}
so we just extract that and use it for the tests.
2026-01-27 06:42:55 +00:00
Jarvis Carroll 4f2a3c6c6f Variant parsing 2026-01-23 06:18:39 +00:00
Jarvis Carroll 7df04a81be Tuple parsing 2026-01-23 02:45:23 +00:00
Jarvis Carroll 6f02d4c4e6 Record parsing 2026-01-23 00:48:06 +00:00
zxq9 48bcccdf23 Merge pull request 'Fix hz_grids:req/2,3 and add req/4' (#18) from grids-fix into master
Reviewed-on: #18
2026-01-19 13:26:50 +09:00
zxq9 03b9756066 Fix hz_grids:req/2,3 and add req/4 2026-01-19 12:53:25 +09:00
Jarvis Carroll 56e63051bc Map parsing 2026-01-16 05:46:27 +00:00
Jarvis Carroll 3f1c9bd626 List parsing
Slowly chipping away at cases...
2026-01-15 09:38:04 +00:00
Jarvis Carroll 97e32574c4 set up parsing structure
We tokenize, and then do the simplest possible recursive descent.

We don't want to evaluate anything, so infix operators are out,
meaning no shunting yard or tree rearranging or LR(1) shenanigans
are necessary, just write the code.

If we want to 'peek', just take the next token, and pass it around
from that point on, until it can actually be consumed.
2026-01-15 01:52:30 +00:00
Jarvis Carroll 6f5525afcf Rename get_function_signature
hz_aaci:aaci_get_function_signature is a bit redundant.
2026-01-15 01:50:50 +00:00
Jarvis Carroll 4f1958b210 use lists:unzip/1
Just a little thing I noticed could be improved.
2026-01-13 01:19:29 +00:00
Jarvis Carroll 3da9bd570b split coerce/3 into two functions
Also renamed coerce_bindings to erlang_args_to_fate, to match.
2026-01-09 04:39:58 +00:00
zxq9 d65a048409 Updating eDoc style 2026-01-08 22:14:09 +09:00
zxq9 9280495b18 Adjusting eDoc output 2026-01-08 22:12:43 +09:00
Jarvis Carroll d2163c1ff8 split AACI out of hz.erl
So far the interface to hz.erl is mostly unchanged, apart from prepare_aaci/1

Maybe prepare_aaci should be re-exported, but using it is exactly in line with the
'inconvenient but more flexible primitives' that hz_aaci.erl is meant to represent,
so, maybe that is a fine place to have to go for it, dunno.
2026-01-07 09:40:55 +00:00
16 changed files with 3891 additions and 1239 deletions
+2 -2
View File
@@ -8,9 +8,9 @@ cancer
erl_crash.dump
ebin/*.beam
doc/*.html
doc/*.css
doc/edoc-info
doc/erlang.png
doc/stylesheet.css
doc/edoc-info
rel/example_project
.concrete/DEV_MODE
.rebar
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

+75
View File
@@ -0,0 +1,75 @@
/* standard EDoc style sheet */
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
margin-left: .25in;
margin-right: .2in;
margin-top: 0.2in;
margin-bottom: 0.2in;
color: #696969;
background-color: #ffffff;
}
a:link{
color: #000000;
}
a:visited{
color: #000000;
}
a:hover{
color: #d8613c;
}
h1,h2 {
margin-left: -0.2in;
}
div.navbar {
background-color: #000000;
padding: 0.2em;
}
h2.indextitle {
padding: 0.4em;
color: #dfdfdf;
background-color: #000000;
}
div.navbar a:link {
color: #dfdfdf;
}
div.navbar a:visited {
color: #dfdfdf;
}
div.navbar a:hover {
color: #d8613c;
}
h3.function,h3.typedecl {
background-color: #000000;
color: #dfdfdf;
padding-left: 1em;
}
div.spec {
margin-left: 2em;
background-color: #eeeeee;
}
a.module {
text-decoration:none
}
a.module:hover {
background-color: #eeeeee;
}
ul.definitions {
list-style-type: none;
}
ul.index {
list-style-type: none;
background-color: #eeeeee;
}
/*
* Minor style tweaks
*/
ul {
list-style-type: square;
}
table {
border-collapse: collapse;
}
td {
padding: 3
}
+4 -3
View File
@@ -1,5 +1,6 @@
@author Craig Everett <craigeverett@qpq.swiss> [https://git.qpq.swiss/QPQ-AG/hakuzaru]
@version 0.8.0
@author Craig Everett <craigeverett@qpq.swiss> [https://zxq9.com]
@author Jarvis Carrol <jarviscarrol@qpq.swiss> [https://jarviscarroll.net/]
@version 0.9.2
@title Hakuzaru: Gajumaru blockchain bindings for Erlang
@doc
@@ -21,7 +22,7 @@ After startup `hz_man' must be given the address and port of a list of Gajumaru
Note that the service nodes will need to have the dry-run endpoint enabled and the internal service query port made available in order to provide dry-runs and transaction submission.
When configuring chain nodes a list of nodes should be provided.
To avoid sync issues in the case of fast transaction formation/submission to the chain, only one node from the list of chain nodes is used for submitting transactions and querying `next_nonce/1`.
To avoid sync issues in the case of fast transaction formation/submission to the chain, only one node from the list of chain nodes is used for submitting transactions and querying `next_nonce/1'.
This node is called "the sticky node".
The first node in the list of chain nodes provided during configuration is designated as the sticky node.
+3 -3
View File
@@ -3,7 +3,7 @@
{included_applications,[]},
{applications,[stdlib,kernel]},
{description,"Gajumaru interoperation library"},
{vsn,"0.8.2"},
{modules,[hakuzaru,hz,hz_fetcher,hz_format,hz_grids,
hz_key_master,hz_man,hz_sup]},
{vsn,"0.9.2"},
{modules,[hakuzaru,hz,hz_aaci,hz_fetcher,hz_format,hz_grids,
hz_key_master,hz_man,hz_sophia,hz_sup]},
{mod,{hakuzaru,[]}}]}.
+1 -1
View File
@@ -6,7 +6,7 @@
%%% @end
-module(hakuzaru).
-vsn("0.8.2").
-vsn("0.9.2").
-author("Craig Everett <ceverett@tsuriai.jp>").
-copyright("Craig Everett <ceverett@tsuriai.jp>").
-license("GPL-3.0-or-later").
+293 -1184
View File
File diff suppressed because it is too large Load Diff
+1673
View File
File diff suppressed because it is too large Load Diff
+9 -1
View File
@@ -1,5 +1,13 @@
%%% @private
%%% Hakuzaru Request Fetcher
%%%
%%% This module defines the request workers.
%%% Each request to a remote chain node is handled by a worker that is spawned
%%% to handle it and terminates on completion.
%%% @end
-module(hz_fetcher).
-vsn("0.8.2").
-vsn("0.9.2").
-author("Craig Everett <ceverett@tsuriai.jp>").
-copyright("Craig Everett <ceverett@tsuriai.jp>").
-license("MIT").
+18 -1
View File
@@ -21,7 +21,7 @@
%%% @end
-module(hz_format).
-vsn("0.8.2").
-vsn("0.9.2").
-author("Craig Everett <ceverett@tsuriai.jp>").
-copyright("Craig Everett <ceverett@tsuriai.jp>").
-license("GPL-3.0-or-later").
@@ -462,9 +462,26 @@ ranks(heresy) ->
["k ", "m ", "b ", "t ", "q ", "e ", "z ", "y ", "r ", "Q "].
-spec mark(Unit) -> Mark
when Unit :: gaju | puck,
Mark :: $木 | $本.
%% @doc
%% Retrieve the unicode codepoint for the `gaju' mark (木) or the `puck' mark ().
mark(gaju) -> $木;
mark(puck) -> $本.
-spec one(Unit) -> Pucks
when Unit :: gaju | puck,
Pucks :: 1_000_000_000_000_000_000 | 1.
%% @doc
%% Quickly resolve the number of pucks in a given unit.
%%
%% The number of pucks in a gaju is so large that it can be a little bit annoying
%% to remember the exact amount. This is a helper to simplify this when writing
%% an app against the hakuzaru library when dealing in either unit.
one(gaju) -> 1_000_000_000_000_000_000;
one(puck) -> 1.
+45 -9
View File
@@ -37,8 +37,8 @@
%%% @end
-module(hz_grids).
-vsn("0.8.2").
-export([url/2, url/3, url/4, parse/1, req/2, req/3]).
-vsn("0.9.2").
-export([url/2, url/3, url/4, parse/1, req/2, req/3, req/4]).
-spec url(Instruction, HTTP) -> Result
@@ -47,7 +47,7 @@
Result :: {ok, GRIDS} | uri_string:uri_error(),
GRIDS :: uri_string:uri_string().
%% @doc
%% Takes
%% Takes an instruction and an HTTP endpoint location and forms a GRIDS URL.
url(Instruction, HTTP) ->
case uri_string:parse(HTTP) of
@@ -134,6 +134,8 @@ qwargs(Amount, Payload) ->
Amount :: non_neg_integer(),
Payload :: binary(),
URL :: string().
%% @doc
%% Translate a GRIDS URL into an Erlang terms instruction.
parse(GRIDS) ->
case uri_string:parse(GRIDS) of
@@ -190,27 +192,61 @@ l_to_i(S) ->
end.
-spec req(Type, Message) -> Format
when Type :: sign | tx | ack,
Message :: string() | binary(),
Format :: map().
%% @doc
%% @equiv req(Type, Message, false)
req(Type, Message) ->
req(Type, Message, false).
req(sign, Message, ID) ->
-spec req(Type, Message, ID) -> Format
when Type :: sign | tx | ack,
Message :: string() | binary(),
ID :: false | string() | binary(),
Format :: map().
%% @doc
%% Creates a GRIDS message format with the current `NetworkID'.
%%
%% The `ID' parameter indicates which key the requestee should sign with or
%% is `false' to indicate that which key to sign with is up to the requestee.
%% @equiv req(Type, Message, ID, CurrentNetworkID)
req(Type, Message, ID) ->
{ok, NetworkID} = hz:network_id(),
req(Type, Message, ID, NetworkID).
-spec req(Type, Message, ID, NetworkID) -> Format
when Type :: sign | tx | ack,
Message :: string() | binary(),
ID :: false | string() | binary(),
NetworkID :: string() | binary(),
Format :: map().
%% @doc
%% Creates a GRIDS message format.
req(sign, Message, ID, NetworkID) ->
#{"grids" => 1,
"chain" => "gajumaru",
"network_id" => hz:network_id(),
"network_id" => NetworkID,
"type" => "message",
"public_id" => ID,
"payload" => Message};
req(tx, Data, ID) ->
req(tx, Data, ID, NetworkID) ->
#{"grids" => 1,
"chain" => "gajumaru",
"network_id" => hz:network_id(),
"network_id" => NetworkID,
"type" => "tx",
"public_id" => ID,
"payload" => Data};
req(ack, Message, ID) ->
req(ack, Message, ID, NetworkID) ->
#{"grids" => 1,
"chain" => "gajumaru",
"network_id" => hz:network_id(),
"network_id" => NetworkID,
"type" => "ack",
"public_id" => ID,
"payload" => Message}.
+243 -30
View File
@@ -1,18 +1,43 @@
%%% @doc
%%% Key functions
%%% Hakuzaru Key Functions
%%%
%%% 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.
%%% The Gajumaru's default key type is based on Elliptical Curve Cryptography (ECC).
%%% The specific curve used is 25519, and the typical key representation is Ed25519.
%%%
%%% The "Ed" in "Ed25519" stands for Harold Edwards. This form represents
%%% a coordinate on a "Twisted Edwards Curve".
%%%
%%% The "X" in "X25519" stands for the X-coordinate, also known as the
%%% "Montgomery u-coordinate" on a "Montgomery Curve".
%%%
%%% The two are equivalent, but have meaningfully different properties.
%%% @end
-module(hz_key_master).
-vsn("0.8.2").
-vsn("0.9.2").
-export([make_key/0, make_key/1, encode/1, decode/1]).
-export([shared_secret_a/6, shared_secret_b/6,
ed25519_pk_to_x25519/1, ed25519_sk_to_x25519/1,
hkdf/4, hkdf/5]).
-export([make_key/1, encode/1, decode/1]).
-export([lcg/1]).
-spec make_key() -> {ID, KeyPair}
when ID :: string(),
KeyPair :: #{secret => binary(), public => binary()}.
%% @doc
%% @equiv make_key(<<>>)
make_key() ->
make_key(<<>>).
-spec make_key(Secret) -> {ID, KeyPair}
when Secret :: <<>> | <<_:32*8>>,
ID :: string(),
KeyPair :: #{secret => binary(), public => binary()}.
%% @doc
%% Generate a Ed25519 keypair tagged with the corresponding Gajumaru ID.
make_key(<<>>) ->
Pair = #{public := Public} = ecu_eddsa:sign_keypair(),
@@ -126,28 +151,216 @@ sumcheck(Width, Bits) ->
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
-spec shared_secret_a(A_E_E_SK, B_P_E_PK, B_E_E_PK, Protocol, Version, Salt) -> SS
when A_E_E_SK :: binary(),
B_P_E_PK :: <<_:32*8>>,
B_E_E_PK :: <<_:32*8>>,
Protocol :: binary(),
Version :: binary(),
Salt :: binary(),
SS :: <<_:32*8>>.
%% @doc
%% Alice's side of a shared key derivation based on ed25519 keys as generated by this module.
%%
%% The input value should be between 1 and 2^31-1.
%%
%% The purpose of this PRNG is for password-based dictionary shuffling.
%% Typically Alice would be providing an ephemeral key to establish
%% a shared secret while remaining (at least initially) anonymous from Bob. Bob,
%% on the other hand, is providing a permanent key and also an ephemeral key,
%% proving identity without exposing the shared secret in the future were one of
%% the secrets to be compromised.
%% <ul>
%% <li>`A_E_E_SK' Alice's Ephemeral Ed25519 Secret Key.</li>
%% <li>`B_P_E_PK' Bob's Permanent Ed25519 Public Key.</li>
%% <li>`B_E_E_PK' Bob's Ephemeral Ed25519 Public Key.</li>
%% <li>`Protocol' is an arbitrary binary string, typically a protocol name in UTF-8.</li>
%% <li>`Version' is another arbitrary binary string, typically a protocol version in UTF-8.</li>
%% <li>`Salt' is a binary salt, which if empty will be replaced by a binary string of zeroes.</li>
%% <li>`SS' is the resulting 32-byte shared secret.</li>
%% </ul>
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
shared_secret_a(A_E_E_SK, B_P_E_PK, B_E_E_PK, Protocol, Version, Salt) ->
A_E_X_SK = ed25519_sk_to_x25519(A_E_E_SK),
B_P_X_PK = ed25519_pk_to_x25519(B_P_E_PK),
B_E_X_PK = ed25519_pk_to_x25519(B_E_E_PK),
DH_Permanent = crypto:compute_key(ecdh, B_P_X_PK, A_E_X_SK, x25519),
DH_Ephemeral = crypto:compute_key(ecdh, B_E_X_PK, A_E_X_SK, x25519),
finalize_hkdf(DH_Permanent, DH_Ephemeral, Protocol, Version, Salt).
-spec shared_secret_b(B_P_E_SK, B_E_E_SK, A_E_E_PK, Protocol, Version, Salt) -> SS
when B_P_E_SK :: binary(),
B_E_E_SK :: binary(),
A_E_E_PK :: <<_:32*8>>,
Protocol :: binary(),
Version :: binary(),
Salt :: binary(),
SS :: <<_:32*8>>.
%% @doc
%% Bobs's side of a shared key derivation based on ed25519 keys as generated by this module.
%%
%% Typically Alice would be providing an ephemeral key to establish
%% a shared secret while remaining (at least initially) anonymous from Bob. Bob,
%% on the other hand, is providing a permanent key and also an ephemeral key,
%% proving identity without exposing the shared secret in the future were one of
%% the secrets to be compromised.
%% <ul>
%% <li>`B_P_E_SK' Bob's Permanent Ed25519 Secret Key.</li>
%% <li>`B_E_E_SK' Bob's Ephemeral Ed25519 Secret Key.</li>
%% <li>`A_E_E_PK' Alice's Ephemeral Ed25519 Public Key.</li>
%% <li>`Protocol' is an arbitrary binary string, typically a protocol name in UTF-8.</li>
%% <li>`Version' is another arbitrary binary string, typically a protocol version in UTF-8.</li>
%% <li>`Salt' is a binary salt, which if empty will be replaced by a binary string of zeroes.</li>
%% <li>`SS' is the resulting 32-byte shared secret.</li>
%% </ul>
shared_secret_b(B_P_E_SK, B_E_E_SK, A_E_E_PK, Protocol, Version, Salt) ->
B_P_X_SK = ed25519_sk_to_x25519(B_P_E_SK),
B_E_X_SK = ed25519_sk_to_x25519(B_E_E_SK),
A_E_X_PK = ed25519_pk_to_x25519(A_E_E_PK),
DH_Permanent = crypto:compute_key(ecdh, A_E_X_PK, B_P_X_SK, x25519),
DH_Ephemeral = crypto:compute_key(ecdh, A_E_X_PK, B_E_X_SK, x25519),
finalize_hkdf(DH_Permanent, DH_Ephemeral, Protocol, Version, Salt).
finalize_hkdf(DH_Permanent, DH_Ephemeral, Protocol, Version, Salt) ->
MixedInput = <<DH_Permanent/binary, DH_Ephemeral/binary>>,
Info = <<Protocol/binary, ":", Version/binary, ":">>,
hkdf(sha256, MixedInput, Salt, Info).
%% Curve25519 Prime Field Constant: 2^255 - 19
%% Yes, in hex it reads kind of like "lucky fed"
p() -> 16#7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED.
-spec ed25519_pk_to_x25519(ED25519_PubKey) -> X25519_PubKey
when ED25519_PubKey :: <<_:32*8>>,
X25519_PubKey :: <<_:32*8>>.
%% @doc
%% Convert a curve 25519 public key from Edwards representation to X-coordinate
%% representation.
ed25519_pk_to_x25519(<<ED25519_PK:32/binary>>) ->
<<CompressedInt:256/little-integer>> = ED25519_PK,
% Clear the sign bit (MSB) to get the raw y-coordinate
Y = CompressedInt band ((1 bsl 255) - 1),
% Compute u = (1 + y) / (1 - y) mod P
Num = (1 + Y) rem p(),
Den = (1 - Y + p()) rem p(),
case Den =:= 0 of
true ->
% If y == 1, the point maps to the point at infinity.
% On X25519, this translates to u = 0.
<<0:256/little-integer>>;
false ->
U = (Num * mod_inv(Den, p())) rem p(),
<<U:256/little-integer>>
end.
-spec ed25519_sk_to_x25519(ED25519_SecKey) -> X25519_SecKey
when ED25519_SecKey :: binary(),
X25519_SecKey :: <<_:32*8>>.
%% @doc
%% Convert a curve 25519 secret key from Edwards representation to X-coordinate
%% representation.
ed25519_sk_to_x25519(<<ED25519_SK_Secret:32/binary, _/binary>>) ->
<<X25519_SK:32/binary, _/binary>> = crypto:hash(sha512, ED25519_SK_Secret),
X25519_SK.
mod_inv(A, M) ->
{1, X, _} = ext_gcd(A, M),
(X + M) rem M.
ext_gcd(A, 0) ->
{A, 1, 0};
ext_gcd(A, B) ->
{G, X1, Y1} = ext_gcd(B, A rem B),
{G, Y1, X1 - (A div B) * Y1}.
-spec hkdf(Hash, IKM, Salt, Info) -> DerivedKey
when Hash :: md5 | sha | sha224 | sha256 | sha384 | sha512,
IKM :: binary(),
Salt :: binary(),
Info :: binary(),
DerivedKey :: <<_:32*8>>.
%% @doc
%% 32-byte HMAC-Based Extract-and-Expand Key Derivation
%% @equiv hkdf(Hash, IKM, Salt, Info, 32)
hkdf(Hash, IKM, Salt, Info) ->
hkdf(Hash, IKM, Salt, Info, 32).
-spec hkdf(Hash, IKM, Salt, Info, Length) -> DerivedKey
when Hash :: md5 | sha | sha224 | sha256 | sha384 | sha512,
IKM :: binary(),
Salt :: binary(),
Info :: binary(),
Length :: 16 | 20 | 28 | 32 | 48 | 64,
DerivedKey :: binary().
%% @doc
%% RFC-5869 compliant HMAC-Based Extract-and-Expand Key Derivation
%%
%% RFC-5869:
%% <a href="https://datatracker.ietf.org/doc/html/rfc5869">https://datatracker.ietf.org/doc/html/rfc5869</a>
%%
%% The purpose of HKDF is to take an initial, raw secret input that might
%% be mathematically strong but structurally "clumpy" and transform it into one
%% or more uniform, high-entropy keys suitable for use in cryptography.
%%
%% The problem is that when Alice and Bob compute a Diffie-Hellman shared secret
%% over X25519, the resulting bytes are mathematically secure, but they are not
%% evenly distributed as random noise. Cryptographic ciphers expect keys where
%% every single bit has an exactly 50% chance of being a 0 or a 1. Passing raw
%% DH outputs straight into a cipher can introduce subtle, exploitable patterns.
%%
%% HKDF "smooths out" the entropy.
%%
%% HMAC stands for "Keyed-Hash Message Authentication Code", but without the
%% leading "K" just to keep us on our toes. The problem it solves is that simply
%% concatenating a secret and some target data and hashing them together to produce
%% a message authentication hash leaves the resulting hash vulnerable to a "length
%% extension attack". An attacker can append additional data to the end of the
%% message and arrive at a valid new hash without ever knowing the secret.
%%
%% RFC-2104 provides good background information on the technique:
%% <a href="https://datatracker.ietf.org/doc/html/rfc2104">https://datatracker.ietf.org/doc/html/rfc2104</a>
hkdf(Hash, IKM, Salt, Info, Length) ->
PRK = extract(Hash, Salt, IKM),
expand(Hash, PRK, Info, Length).
extract(Hash, <<>>, IKM) ->
%% If salt is empty RFC 5869 requires a string of zeros equal to hash size
Salt = binary:copy(<<0>>, hash_size(Hash)),
extract(Hash, Salt, IKM);
extract(Hash, Salt, IKM) ->
crypto:mac(hmac, Hash, Salt, IKM).
expand(Hash, PRK, Info, OutLen) ->
HashLen = hash_size(Hash),
BlockCount = (OutLen + HashLen - 1) div HashLen,
case BlockCount > 255 of
true ->
error(hkdf_length_too_long);
false ->
FullBlocks = expand_loop(Hash, PRK, Info, BlockCount, 1, <<>>, <<>>),
<<Output:OutLen/binary, _/binary>> = FullBlocks,
Output
end.
expand_loop(Hash, PRK, Info, N, Counter, PrevT, Acc) when Counter =< N ->
Payload = <<PrevT/binary, Info/binary, Counter:8>>,
T = crypto:mac(hmac, Hash, PRK, Payload),
expand_loop(Hash, PRK, Info, N, Counter + 1, T, <<Acc/binary, T/binary>>);
expand_loop(_, _, _, _, _, _, Acc) ->
Acc.
hash_size(md5) -> 16;
hash_size(sha) -> 20;
hash_size(sha224) -> 28;
hash_size(sha256) -> 32;
hash_size(sha384) -> 48;
hash_size(sha512) -> 64.
+1 -2
View File
@@ -9,7 +9,7 @@
%%% @end
-module(hz_man).
-vsn("0.8.2").
-vsn("0.9.2").
-behavior(gen_server).
-author("Craig Everett <ceverett@tsuriai.jp>").
-copyright("Craig Everett <ceverett@tsuriai.jp>").
@@ -172,7 +172,6 @@ start_link() ->
%% preparatory work necessary for proper function.
init(none) ->
ok = io:format("hz_man starting.~n"),
State = #s{},
{ok, State}.
+1521
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -9,7 +9,7 @@
%%% @end
-module(hz_sup).
-vsn("0.8.2").
-vsn("0.9.2").
-behaviour(supervisor).
-author("Craig Everett <zxq9@zxq9.com>").
-copyright("Craig Everett <zxq9@zxq9.com>").
+2 -2
View File
@@ -2,9 +2,9 @@
{type,app}.
{modules,[]}.
{prefix,"hz"}.
{desc,"Gajumaru interoperation library"}.
{author,"Craig Everett"}.
{package_id,{"otpr","hakuzaru",{0,8,2}}}.
{desc,"Gajumaru interoperation library"}.
{package_id,{"otpr","hakuzaru",{0,9,2}}}.
{deps,[{"otpr","sophia",{9,0,0}},
{"otpr","gmserialization",{0,1,3}},
{"otpr","gmbytecode",{3,4,1}},