├── .gitignore
├── LICENSES
├── COPYING
└── MIT.txt
├── Makefile
├── README.md
├── apps
└── ssb
│ ├── include
│ └── ssb.hrl
│ └── src
│ ├── boxstream.erl
│ ├── config.erl
│ ├── converter.erl
│ ├── ebt.erl
│ ├── ebt_vc.erl
│ ├── foldl_hacks.erl
│ ├── friends.erl
│ ├── heartbeat.erl
│ ├── keys.erl
│ ├── mess_auth.erl
│ ├── message.erl
│ ├── rpc_parse.erl
│ ├── rpc_processor.erl
│ ├── shs.erl
│ ├── smoke.erl
│ ├── ssb.app.src
│ ├── ssb_app.erl
│ ├── ssb_feed.erl
│ ├── ssb_peer.erl
│ ├── ssb_sup.erl
│ ├── tangle.erl
│ └── utils.erl
├── archive
└── erlbutt-01-09-2025.tar
├── config
├── default.vars
├── ssb.cfg
├── sys.config.src
└── vm.args.src
├── doc
├── dev-diary
│ ├── 02-21-2025.md
│ └── 06-26-2024.md
├── project.md
└── research
│ ├── ByzantineEventualConsistency.pdf
│ ├── acmdl19-295.pdf
│ ├── dicg20-paper90.pdf
│ ├── ebt.pdf
│ ├── itc2008.pdf
│ ├── shs.pdf
│ ├── trustnet-cblgh.pdf
│ └── urls.md
├── jq
├── rebar.config
├── rebar.lock
├── rebar3
├── sbot.escript
├── test
├── erlbutt_basic_SUITE.erl
└── ssb.cfg
├── testdata.zip
└── testdata.zip.license
/.gitignore:
--------------------------------------------------------------------------------
1 | .eunit
2 | *.o
3 | *.beam
4 | *.plt
5 | erl_crash.dump
6 | *~
7 | ebin
8 | .rebar
9 | log
10 | Mnesia*
11 | _build
12 | *#*#
13 | .DS_Store
14 | foo
15 | foobar
16 | *.offset
17 | *.info
18 | testdata
19 | __MACOSX
20 | feeds
21 | *.swp
22 | TAGS
--------------------------------------------------------------------------------
/LICENSES/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
--------------------------------------------------------------------------------
/LICENSES/MIT.txt:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2021 The Go-SSB Authros
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: compile rel test
2 | REBAR=./rebar3
3 |
4 | compile:
5 | $(REBAR) compile
6 |
7 | clean:
8 | $(REBAR) clean
9 |
10 | test: compile
11 | unzip -n -o testdata.zip
12 | $(REBAR) eunit
13 | rm -Rf testdata
14 |
15 | ct: compile
16 | $(REBAR) ct
17 |
18 | rel: compile
19 | $(REBAR) release
20 |
21 | prod: compile
22 | $(REBAR) as prod release
23 |
24 | all: clean compile test prod
25 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | erlbutt
2 | ======
3 |
4 | An implementation of the [`SSB`][1] protocol.
5 |
6 | ## [Project notes][2]
7 |
8 | ## Building
9 |
10 | ```
11 | make test
12 |
13 | make ct
14 |
15 | make rel
16 |
17 | ```
18 | To run:
19 | ```
20 | ./_build/default/rel/ssb/bin/ssb-0.0.1 console
21 |
22 | ```
23 | An environment variable can be used to control logging, .eg.:
24 |
25 | ```
26 | SSB_LOG_LEVEL=debug _build/default/rel/ssb/bin/ssb-0.0.1 console
27 | ```
28 |
29 | There is also a [dev-diary][3] that are posts made on `SSB`, so many of the linked items in those entries are not visible in github.
30 |
31 | ----
32 | [1]: https://ssbc.github.io/scuttlebutt-protocol-guide/
33 | [2]: https://github.com/cmoid/erlbutt/blob/main/doc/project.md
34 | [3]: https://github.com/cmoid/erlbutt/tree/main/doc/dev-diary
35 |
--------------------------------------------------------------------------------
/apps/ssb/include/ssb.hrl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 |
5 | -include_lib("kernel/include/logger.hrl").
6 |
7 | -define(l2b(List), list_to_binary(List)).
8 | -define(b2l(List), binary_to_list(List)).
9 | -define(pgv(K,V), proplists:get_value(K, V)).
10 |
11 | -define(KEEP_ALIVE_GRACE, 1500).
12 |
13 | %% This network id is almost the same
14 | -define(DEFAULT_NETWORK_ID, base64:decode("1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYnaR/s=")).
15 | %%
16 | %% as this one that is for the current main SSB network
17 | %% 1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s=
18 | %% diff is in the last three digits
19 | %%
20 | %% Eventually this network id will be configurable
21 |
22 | %% Helper macro for declaring children of supervisor
23 | -define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
24 |
25 | -define(SHS_NONCE, <<0:24/integer-unit:8>>).
26 | -define(BOX_END, <<0:18/integer-unit:8>>).
27 | -define(RPC_END, <<0:9/integer-unit:8>>).
28 |
29 |
30 | -define(createhistorystream, <<"createHistoryStream">>).
31 | -define(whoami, <<"whoami">>).
32 | -define(ping, <<"ping">>).
33 | -define(gossip, <<"gossip">>).
34 | -define(blobs, <<"blobs">>).
35 | -define(ebt, <<"ebt">>).
36 | -define(tunnel, <<"tunnel">>).
37 |
38 | -record(ssb_conn,
39 | { socket,
40 | nonce,
41 | secret_box
42 | }).
43 |
44 | -record(ssb_rpc,
45 | { name,
46 | args,
47 | type
48 | }).
49 |
50 | -record(message,
51 | { id,
52 | previous,
53 | author,
54 | sequence,
55 | timestamp,
56 | hash,
57 | content,
58 | signature,
59 | received,
60 | validated,
61 | %% the field order counts when signing messages. In some legacy messages,
62 | %% sequence occurs before author. The swapped boolean tracks this, for
63 | %% validation purposes.
64 | swapped
65 | }).
66 |
67 | -record(sbox_state, {ref,
68 | socket,
69 | transport,
70 | dec_sbox_key,
71 | enc_sbox_key,
72 | dec_nonce,
73 | enc_nonce,
74 | shook_hands = 0,
75 | box_rem_bytes = <<>>,
76 | rpc_rem_bytes = <<>>,
77 | response}).
78 |
--------------------------------------------------------------------------------
/apps/ssb/src/boxstream.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(boxstream).
5 |
6 | -include("ssb.hrl").
7 |
8 | -import(utils, [combine/2,
9 | incr/1]).
10 |
11 | -export([box/3,
12 | unbox/3]).
13 |
14 | box(?BOX_END, Nonce, SecretBoxKey) ->
15 | EndMsgBox = enacl:secretbox(?BOX_END,
16 | Nonce,
17 | SecretBoxKey),
18 | {EndMsgBox, incr(Nonce)};
19 |
20 | box(Data, Nonce, SecretBoxKey) ->
21 |
22 | DataSizBin = size(Data),
23 |
24 | EndMsgBox = enacl:secretbox(Data,
25 | incr(Nonce),
26 | SecretBoxKey),
27 |
28 | <> = EndMsgBox,
29 |
30 | Header = <>,
32 |
33 | EncHeader =
34 | enacl:secretbox(Header,Nonce,SecretBoxKey),
35 |
36 | {combine(EncHeader, Body),
37 | incr(incr(Nonce))}.
38 |
39 | %% return complete or partial, no need for returning done. Complete
40 | %% with ?BOX_END indicates done
41 | unbox(_SecretBoxKey, Nonce, DataProc) when size(DataProc) < 34 ->
42 | {partial, <<>>, Nonce, DataProc};
43 |
44 | unbox(SecretBoxKey, Nonce, DataProc) ->
45 |
46 | <> = DataProc,
47 |
48 | Msg = shs:open_box(Header,
49 | Nonce,
50 | SecretBoxKey),
51 |
52 | EndBox = Msg == ?BOX_END,
53 |
54 | case EndBox of
55 | true ->
56 | {complete, ?BOX_END, Nonce, <<>>};
57 | _Else ->
58 | <> = Msg,
59 |
60 | LenInt = binary:decode_unsigned(Len),
61 |
62 | AlreadyHaveBytes = LenInt > 0 andalso
63 | LenInt =< size(RestData),
64 |
65 | if AlreadyHaveBytes ->
66 |
67 | <<_DontCare:LenInt/binary,RemBytes/binary>> = RestData,
68 | FullPacket = <>,
69 | {complete,
70 | shs:open_box(FullPacket,
71 | incr(Nonce),
72 | SecretBoxKey),
73 | incr(incr(Nonce)),
74 | RemBytes};
75 | true ->
76 | {partial,
77 | <<>>,
78 | Nonce,
79 | DataProc}
80 | end
81 | end.
82 |
--------------------------------------------------------------------------------
/apps/ssb/src/config.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(config).
5 | -include("ssb.hrl").
6 | -behaviour(gen_server).
7 |
8 | %% API
9 | -export([start_link/0,
10 | start_link/1,
11 | feed_store_loc/0,
12 | network_id/0]).
13 |
14 | %% gen_server callbacks
15 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2,
16 | terminate/2, code_change/3]).
17 |
18 | -define(SERVER, ?MODULE).
19 |
20 | -record(state, {store_loc,
21 | net_id}).
22 |
23 | %%%===================================================================
24 | %%% API
25 | %%%===================================================================
26 |
27 | feed_store_loc() ->
28 | gen_server:call(?MODULE, location, infinity).
29 |
30 | network_id() ->
31 | gen_server:call(?MODULE, netid, infinity).
32 |
33 | start_link() ->
34 | gen_server:start_link({local, ?SERVER}, ?MODULE, ["ssb.cfg"], []).
35 |
36 | start_link(Config) ->
37 | gen_server:start_link({local, ?SERVER}, ?MODULE, [Config], []).
38 |
39 | %%%===================================================================
40 | %%% gen_server callbacks
41 | %%%===================================================================
42 |
43 | init([Config]) ->
44 | process_flag(trap_exit, true),
45 | case filelib:is_file(Config) of
46 | true ->
47 | {ok, load_and_parse(Config, #state{})};
48 | false ->
49 | %%?LOG_DEBUG("try to load the config from ~p ~n", []),
50 | {ok, #state{store_loc = default_feed_store(),
51 | net_id = default_net_id()}}
52 | end.
53 |
54 | handle_call(location, _From, #state{store_loc = DbLoc}=State) ->
55 | {reply, DbLoc, State};
56 |
57 | handle_call(netid, _From, #state{net_id = NetId}=State) ->
58 | {reply, NetId, State}.
59 |
60 | %% casts
61 |
62 | handle_cast(_Msg, State) ->
63 | {noreply, State}.
64 |
65 | %% info
66 |
67 | handle_info(_Info, State) ->
68 | {noreply, State}.
69 |
70 |
71 | terminate(_Reason, _State) ->
72 | ok.
73 |
74 | code_change(_OldVsn, State, _Extra) ->
75 | {ok, State}.
76 |
77 | %%%===================================================================
78 | %%% Internal functions
79 | %%%===================================================================
80 | load_and_parse(CfgFile, #state{} = State) ->
81 | {ok, CfgTerms} = file:consult(CfgFile),
82 | lists:foldl(fun(CfgTerm, StateIn) ->
83 | parse(CfgTerm, StateIn)
84 | end, State, CfgTerms).
85 |
86 | parse({feed_store_location, Loc}, State) ->
87 | Store = ?l2b(Loc),
88 | filelib:ensure_dir(Store),
89 | State#state{store_loc = Store};
90 |
91 | parse({network_id, NetId}, State) ->
92 | State#state{net_id = base64:decode(NetId)};
93 |
94 | parse(_Any, State) ->
95 | %% ignore for now, this is an error technically
96 | State.
97 |
98 | default_feed_store() ->
99 | DataStore = ?l2b("./feeds/"),
100 | filelib:ensure_dir(DataStore),
101 | DataStore.
102 |
103 | default_net_id() ->
104 | ?DEFAULT_NETWORK_ID.
105 |
--------------------------------------------------------------------------------
/apps/ssb/src/converter.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 |
5 | -module(converter).
6 |
7 | %% converter is a utility that takes an existing log.offset file from the
8 | %% javascript reference implementation of scuttlebutt and produces separate
9 | %% feeds for each author in the log. Each feed is stored as a log file with the
10 | %% same format, but in it's own directory along with a profile file and a references file.
11 |
12 | -include("ssb.hrl").
13 |
14 | -export([convert/3,
15 | build_refs/1]).
16 |
17 | -import(utils, [load_term/1,
18 | update_refs/1]).
19 |
20 | convert(OffsetLog, Sleep, Feeds)->
21 |
22 | %% create initial store if needed, this info will come from config or
23 | %% environment at build time
24 | {ok, [[Home]]} = init:get_argument(home),
25 | File = Home ++ "/code/erlbutt/" ++ OffsetLog,
26 |
27 | case file:open(File, [read, binary]) of
28 | {ok, IoDev} ->
29 | convert_terms(IoDev, 0, Sleep, Feeds),
30 | file:close(IoDev),
31 | {BiggestId, NumMsgs} =
32 | lists:foldl(fun(Elem, Acc) ->
33 | case count(Elem) > count(Acc) of
34 | true -> Elem;
35 | _Else -> Acc
36 | end
37 | end,{<<"FFF">>, {0, 0}},get()),
38 | mess_auth:close(),
39 | ?LOG_INFO("number of unique feeds: ~p ~n",[length(get())]),
40 | ?LOG_INFO("largest feed belongs to: ~p ~n",
41 | [{BiggestId, NumMsgs}]);
42 | {error, enoent} ->
43 | ?LOG_INFO("Probably bad input ~n",[]),
44 | done
45 | end.
46 |
47 | convert_terms(IoDev, Found, Sleep, Feeds) ->
48 | case load_term(IoDev) of
49 | {ok, Data} ->
50 | store(Data, Sleep, Feeds),
51 | SleepCnt = Found rem 5000 == 0,
52 | if SleepCnt ->
53 | timer:sleep(Sleep),
54 | io:format(".", []);
55 | true ->
56 | true
57 | end,
58 | %% read spacer in file, at end this will cause eof but that will be picked
59 | %% up in the next iteration
60 | {ok, <<_PosInt:32/integer>>} = file:read(IoDev, 4),
61 | convert_terms(IoDev, Found + 1, Sleep, Feeds);
62 | {error, eof} ->
63 | ?LOG_INFO("Found ~p messages ~n",[Found]),
64 | done;
65 | {error, Error} ->
66 | ?LOG_INFO("Error loading the ~p term: ~p ~n",[Found, Error])
67 | end.
68 |
69 | count({_key, {_Pid, Count}}) ->
70 | Count;
71 | count(_) ->
72 | 0.
73 |
74 |
75 | get_feed(Author, Sleep) ->
76 | Val = get(Author),
77 | case Val of
78 | undefined ->
79 | {ok, Pid} = ssb_feed:start_link(Author),
80 | put(Author, {Pid, 1}),
81 | Pid;
82 | {Pid, Count} ->
83 | put(Author, {Pid, Count + 1}),
84 | PrintCount = Count rem 10000 == 0,
85 | if PrintCount ->
86 | timer:sleep(Sleep),
87 | io:format("~n",[]),
88 | ?LOG_INFO("This author ~p has ~p records ~n", [Author, Count]);
89 | true ->
90 | true
91 | end,
92 | Pid;
93 | _Else ->
94 | bad
95 | end.
96 |
97 | store(Msg, Sleep, Feeds) ->
98 |
99 | DecMsg = message:decode(Msg, true),
100 |
101 | #message{id = MsgId,
102 | author = AuthId,
103 | validated = Valid} = DecMsg,
104 |
105 | Belongs = lists:member(AuthId, Feeds) orelse
106 | (hd(Feeds) == all),
107 |
108 | if Belongs ->
109 | FeedPid = get_feed(AuthId, Sleep),
110 | ssb_feed:store_msg(FeedPid, DecMsg),
111 | %% Not needed, ssb_feed_store_msg already handles it
112 | %%gmess_auth:put(MsgId, AuthId),
113 | if Valid ->
114 | nop;
115 | true ->
116 | io:format("~n",[]),
117 | ?LOG_INFO("Stored message that does not validate ~p ~n",[{MsgId, AuthId}])
118 | end;
119 | %% need to do this in two passes now, in order to look up message/auth pairs
120 | %% in the cache.
121 | %%check_for_refs(DecMsg, Sleep);
122 | true ->
123 | nop
124 | end.
125 |
126 | build_refs(FeedId) ->
127 | {ok, Feed} = ssb_feed:start_link(FeedId),
128 | Fun = fun(Term, Acc) ->
129 | %% possibly no need to validate this here
130 | Msg = message:decode(Term, false),
131 | [update_refs(Msg) | Acc]
132 | end,
133 | ssb_feed:foldl(Feed, Fun, []).
134 |
--------------------------------------------------------------------------------
/apps/ssb/src/ebt.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2025 Charles Moid
4 | -module(ebt).
5 |
6 | -behaviour(gen_server).
7 |
8 | %% API
9 | -export([start_link/0]).
10 |
11 | %% gen_server callbacks
12 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2,
13 | terminate/2, code_change/3, format_status/1]).
14 |
15 | -define(SERVER, ?MODULE).
16 |
17 | -record(state, {}).
18 |
19 | %%%===================================================================
20 | %%% API
21 | %%%===================================================================
22 |
23 | %%--------------------------------------------------------------------
24 | %% @doc
25 | %% Starts the server
26 | %% @end
27 | %%--------------------------------------------------------------------
28 | -spec start_link() -> {ok, Pid :: pid()} |
29 | {error, Error :: {already_started, pid()}} |
30 | {error, Error :: term()} |
31 | ignore.
32 | start_link() ->
33 | gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
34 |
35 | %%%===================================================================
36 | %%% gen_server callbacks
37 | %%%===================================================================
38 |
39 | %%--------------------------------------------------------------------
40 | %% @private
41 | %% @doc
42 | %% Initializes the server
43 | %% @end
44 | %%--------------------------------------------------------------------
45 | -spec init(Args :: term()) -> {ok, State :: term()} |
46 | {ok, State :: term(), Timeout :: timeout()} |
47 | {ok, State :: term(), hibernate} |
48 | {stop, Reason :: term()} |
49 | ignore.
50 | init([]) ->
51 | process_flag(trap_exit, true),
52 | {ok, #state{}}.
53 |
54 | %%--------------------------------------------------------------------
55 | %% @private
56 | %% @doc
57 | %% Handling call messages
58 | %% @end
59 | %%--------------------------------------------------------------------
60 | -spec handle_call(Request :: term(), From :: {pid(), term()}, State :: term()) ->
61 | {reply, Reply :: term(), NewState :: term()} |
62 | {reply, Reply :: term(), NewState :: term(), Timeout :: timeout()} |
63 | {reply, Reply :: term(), NewState :: term(), hibernate} |
64 | {noreply, NewState :: term()} |
65 | {noreply, NewState :: term(), Timeout :: timeout()} |
66 | {noreply, NewState :: term(), hibernate} |
67 | {stop, Reason :: term(), Reply :: term(), NewState :: term()} |
68 | {stop, Reason :: term(), NewState :: term()}.
69 | handle_call(_Request, _From, State) ->
70 | Reply = ok,
71 | {reply, Reply, State}.
72 |
73 | %%--------------------------------------------------------------------
74 | %% @private
75 | %% @doc
76 | %% Handling cast messages
77 | %% @end
78 | %%--------------------------------------------------------------------
79 | -spec handle_cast(Request :: term(), State :: term()) ->
80 | {noreply, NewState :: term()} |
81 | {noreply, NewState :: term(), Timeout :: timeout()} |
82 | {noreply, NewState :: term(), hibernate} |
83 | {stop, Reason :: term(), NewState :: term()}.
84 | handle_cast(_Request, State) ->
85 | {noreply, State}.
86 |
87 | %%--------------------------------------------------------------------
88 | %% @private
89 | %% @doc
90 | %% Handling all non call/cast messages
91 | %% @end
92 | %%--------------------------------------------------------------------
93 | -spec handle_info(Info :: timeout() | term(), State :: term()) ->
94 | {noreply, NewState :: term()} |
95 | {noreply, NewState :: term(), Timeout :: timeout()} |
96 | {noreply, NewState :: term(), hibernate} |
97 | {stop, Reason :: normal | term(), NewState :: term()}.
98 | handle_info(_Info, State) ->
99 | {noreply, State}.
100 |
101 | %%--------------------------------------------------------------------
102 | %% @private
103 | %% @doc
104 | %% This function is called by a gen_server when it is about to
105 | %% terminate. It should be the opposite of Module:init/1 and do any
106 | %% necessary cleaning up. When it returns, the gen_server terminates
107 | %% with Reason. The return value is ignored.
108 | %% @end
109 | %%--------------------------------------------------------------------
110 | -spec terminate(Reason :: normal | shutdown | {shutdown, term()} | term(),
111 | State :: term()) -> any().
112 | terminate(_Reason, _State) ->
113 | ok.
114 |
115 | %%--------------------------------------------------------------------
116 | %% @private
117 | %% @doc
118 | %% Convert process state when code is changed
119 | %% @end
120 | %%--------------------------------------------------------------------
121 | -spec code_change(OldVsn :: term() | {down, term()},
122 | State :: term(),
123 | Extra :: term()) -> {ok, NewState :: term()} |
124 | {error, Reason :: term()}.
125 | code_change(_OldVsn, State, _Extra) ->
126 | {ok, State}.
127 |
128 | %%--------------------------------------------------------------------
129 | %% @private
130 | %% @doc
131 | %% This function is called for changing the form and appearance
132 | %% of gen_server status when it is returned from sys:get_status/1,2
133 | %% or when it appears in termination error logs.
134 | %% @end
135 | %%--------------------------------------------------------------------
136 | -spec format_status(Status :: list()) -> Status :: term().
137 | format_status(Status) ->
138 | Status.
139 |
140 | %%%===================================================================
141 | %%% Internal functions
142 | %%%===================================================================
143 |
--------------------------------------------------------------------------------
/apps/ssb/src/ebt_vc.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2025 Charles Moid
4 | -module(ebt_vc).
5 |
6 | -ifdef(TEST).
7 | -include_lib("eunit/include/eunit.hrl").
8 | -endif.
9 |
10 | -export([decode_clock_int/1,
11 | decode_clock/1]).
12 |
13 | decode_clock_int(Int) ->
14 | if Int < 0 ->
15 | {false, false, 0};
16 | true ->
17 | {true, (Int band 1) == 0, Int bsr 1}
18 | end.
19 |
20 | decode_clock(ClockList) ->
21 | lists:map(fun({Feed, Num}) ->
22 | {Feed, decode_clock_int(Num)}
23 | end, ClockList).
24 |
25 | -ifdef(TEST).
26 |
27 | %% test table in protocol guide
28 |
29 | row1_test() ->
30 | {false,false,0} == ebt_vc:decode_clock_int(-1).
31 |
32 | row2_test() ->
33 | {true,true,0} == ebt_vc:decode_clock_int(0).
34 |
35 | row3_test() ->
36 | {true,false,0} == ebt_vc:decode_clock_int(1).
37 |
38 | row4_test() ->
39 | {true,true,1} == ebt_vc:decode_clock_int(2).
40 |
41 | row5_test() ->
42 | {true,false,1} == ebt_vc:decode_clock_int(3).
43 |
44 | row6_test() ->
45 | {true,true,6} == ebt_vc:decode_clock_int(12).
46 |
47 | row7_test() ->
48 | {true,true,225} == ebt_vc:decode_clock_int(450).
49 |
50 | simple_vec_clock1_test() ->
51 | {ok, Cwd} = file:get_cwd(),
52 | F = Cwd ++ "/testdata/" ++ "vec_clock1",
53 | {ok, Vec_Clock} = file:read_file(F),
54 | {VClock} = utils:nat_decode(Vec_Clock),
55 | ?assert(is_list(VClock)).
56 |
57 | simple_vec_clock2_test() ->
58 | {ok, Cwd} = file:get_cwd(),
59 | F = Cwd ++ "/testdata/" ++ "vec_clock1",
60 | {ok, Vec_Clock} = file:read_file(F),
61 | {VClock} = utils:nat_decode(Vec_Clock),
62 | ?assert(is_list(VClock)),
63 | {Feed, Num} = hd(VClock),
64 | ?assert(Feed == <<"@qK93G/R9R5J2fiqK+kxV72HqqPUcss+rth8rACcYr4s=.ed25519">>),
65 | ?assert({true,true,225} == ebt_vc:decode_clock_int(Num)).
66 |
67 | simple_vec_clock3_test() ->
68 | {ok, Cwd} = file:get_cwd(),
69 | F = Cwd ++ "/testdata/" ++ "vec_clock1",
70 | {ok, Vec_Clock} = file:read_file(F),
71 | {VClock} = utils:nat_decode(Vec_Clock),
72 | ?assert(is_list(VClock)),
73 | {Feed, Num} = hd(VClock),
74 | ?assert(Feed == <<"@qK93G/R9R5J2fiqK+kxV72HqqPUcss+rth8rACcYr4s=.ed25519">>),
75 | ?assert({true,true,225} == ebt_vc:decode_clock_int(Num)),
76 |
77 | Dec_VClock = ebt_vc:decode_clock(VClock),
78 | {Feed1, Num1} = hd(Dec_VClock),
79 | ?assert(Feed1 == <<"@qK93G/R9R5J2fiqK+kxV72HqqPUcss+rth8rACcYr4s=.ed25519">>),
80 | ?assert({true,true,225} == Num1).
81 |
82 |
83 |
84 |
85 |
86 | -endif.
87 |
--------------------------------------------------------------------------------
/apps/ssb/src/foldl_hacks.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(foldl_hacks).
5 | -include("ssb.hrl").
6 | -export([branch_root/1,
7 | reply_root/1]).
8 |
9 | branch_root(FeedId) ->
10 | {ok, Pid} = ssb_feed:start_link(FeedId),
11 |
12 | Fun = fun(Msg, {N, B, R, RY, NT}) ->
13 | RootReply = check_branch_root(Msg),
14 | case RootReply of
15 | nope -> {N + 1, B, R, RY, NT};
16 | both -> {N, B+1, R, RY, NT};
17 | root_only -> {N, B, R + 1, RY, NT};
18 | branch_only -> {N, B, R, RY = 1, NT};
19 | neither -> {N, B, R, RY, NT + 1}
20 | end
21 | end,
22 |
23 | ssb_feed:foldl(Pid, Fun, {0, 0, 0, 0, 0}).
24 |
25 | reply_root(FeedId) ->
26 | {ok, Pid} = ssb_feed:start_link(FeedId),
27 |
28 | Fun = fun(Msg, {N, B, R, RY, NT}) ->
29 | RootReply = check_reply_root(Msg),
30 | case RootReply of
31 | nope -> {N + 1, B, R, RY, NT};
32 | both -> {N, B+1, R, RY, NT};
33 | root_only -> {N, B, R + 1, RY, NT};
34 | reply_only -> {N, B, R, RY = 1, NT};
35 | neither -> {N, B, R, RY, NT + 1}
36 | end
37 | end,
38 | ssb_feed:foldl(Pid, Fun, {0, 0, 0, 0, 0}).
39 |
40 | check_branch_root(Msg) ->
41 | {DecProps} = utils:nat_decode(Msg),
42 | {Value} = ?pgv(<<"value">>, DecProps),
43 | Val = ?pgv(<<"content">>, Value),
44 | if is_binary(Val) ->
45 | nope;
46 | true ->
47 | {Content} = Val,
48 | Type = ?pgv(<<"type">>, Content),
49 | case Type of
50 | <<"post">> ->
51 | Root = ?pgv(<<"root">>, Content),
52 | RootExists = Root /= undefined,
53 | Branch = ?pgv(<<"branch">>, Content),
54 | BranchExists = Branch /= undefined,
55 | BothExist = (RootExists
56 | andalso
57 | BranchExists),
58 | case BothExist of
59 | true ->
60 | both;
61 | false ->
62 | if RootExists ->
63 | root_only;
64 | true ->
65 | if BranchExists ->
66 | branch_only;
67 | true ->
68 | neither
69 | end
70 | end
71 | end;
72 | _Else ->
73 | nope
74 | end
75 | end.
76 |
77 | check_reply_root(Msg) ->
78 | {DecProps} = utils:nat_decode(Msg),
79 | {Value} = ?pgv(<<"value">>, DecProps),
80 | Val = ?pgv(<<"content">>, Value),
81 | if is_binary(Val) ->
82 | nope;
83 | true ->
84 | {Content} = Val,
85 | Type = ?pgv(<<"type">>, Content),
86 | case Type of
87 | <<"post">> ->
88 | Root = ?pgv(<<"root">>, Content),
89 | RootExists = Root /= undefined,
90 | Reply = ?pgv(<<"reply">>, Content),
91 | ReplyExists = Reply /= undefined,
92 | BothExist = (RootExists
93 | andalso
94 | ReplyExists),
95 | case BothExist of
96 | true ->
97 | both;
98 | false ->
99 | if RootExists ->
100 | root_only;
101 | true ->
102 | if ReplyExists ->
103 | reply_only;
104 | true ->
105 | neither
106 | end
107 | end
108 | end;
109 | _Else ->
110 | nope
111 | end
112 | end.
113 |
--------------------------------------------------------------------------------
/apps/ssb/src/friends.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(friends).
5 |
6 | -ifdef(TEST).
7 | -include_lib("eunit/include/eunit.hrl").
8 | -endif.
9 |
10 | -include("ssb.hrl").
11 |
12 | -export([direct_follows/1,
13 | follows/2]).
14 |
15 | direct_follows(FeedPid) ->
16 | Fun = fun(Data, Acc) ->
17 | Msg = message:decode(Data, false),
18 | Follow = message:is_follow(Msg),
19 | case Follow of
20 | nope -> Acc;
21 | %% this next clause handles legacy garbage from planetary feeds
22 | {true, true} -> Acc;
23 | {Id, true} -> [Id | Acc];
24 | {Id, false} -> lists:delete(Id, Acc)
25 | end
26 | end,
27 | ssb_feed:foldl(FeedPid, Fun, []).
28 |
29 | follows(FeedPid, HopCount) ->
30 | put(visited, [ssb_feed:whoami(FeedPid)]),
31 | FinalFeeds = follows2(FeedPid, HopCount),
32 | put(visited, []),
33 | lists:foldl(fun(E, Acc) ->
34 | Cf = lists:member(E, Acc),
35 | if Cf ->
36 | Acc;
37 | true ->
38 | [E | Acc]
39 | end
40 | end, [], FinalFeeds).
41 |
42 | follows2(_FeedPid, 0) ->
43 | [];
44 |
45 | follows2(FeedPid, HopCount) ->
46 | DirectFollow = direct_follows(FeedPid),
47 | NewDirectFollow = lists:filter(fun(E) ->
48 | not lists:member(E, get(visited))
49 | end, DirectFollow),
50 |
51 | lists:append(lists:foldl(recurse_follow(HopCount),
52 | [], NewDirectFollow),
53 | NewDirectFollow).
54 |
55 | recurse_follow(HopCount) ->
56 | fun(Id, Acc) ->
57 | AlreadySeen = lists:member(Id, get(visited)),
58 | if AlreadySeen ->
59 | Acc;
60 | true ->
61 | Pid = utils:find_or_create_feed_pid(Id),
62 | case Pid of
63 | bad -> Acc;
64 | OkPid ->
65 | Visited = get(visited),
66 | put(visited, [Id | Visited]),
67 | DF = follows2(OkPid, HopCount - 1),
68 | lists:flatten(lists:append(lists:filter(
69 | fun(Nid) ->
70 | not lists:member(Nid, Acc)
71 | end, DF),
72 | Acc))
73 | end
74 | end
75 | end.
76 |
--------------------------------------------------------------------------------
/apps/ssb/src/heartbeat.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(heartbeat).
5 |
6 | -include("ssb.hrl").
7 |
8 | -behaviour(gen_server).
9 |
10 | %% API
11 | -export([start_link/0]).
12 |
13 | -export([whoami/0,
14 | peers/0]).
15 |
16 | %% gen_server callbacks
17 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2,
18 | terminate/2, code_change/3]).
19 |
20 | -define(SERVER, ?MODULE).
21 |
22 | -record(state, {socket,
23 | peers = ets:new(ssb_peers, [set, named_table]),
24 | timer}).
25 |
26 | %%%===================================================================
27 | %%% API
28 | %%%===================================================================
29 |
30 | start_link() ->
31 | gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
32 |
33 | %% identifying string sent out on UDP broadcast
34 | whoami()->
35 | ?l2b("net:" ++
36 | inet:ntoa(local_ip_v4()) ++
37 | ":8008~shs:" ++
38 | keys:pub_key()).
39 |
40 | peers() ->
41 | gen_server:call(?SERVER, peers).
42 |
43 | %%%===================================================================
44 | %%% gen_server callbacks
45 | %%%===================================================================
46 |
47 | init([]) ->
48 | process_flag(trap_exit, true),
49 | Resp = gen_udp:open(8008,
50 | [binary,
51 | {broadcast, true},
52 | {active,true}]),
53 | case Resp of
54 | {ok, Socket} ->
55 | {ok, TRef} = timer:send_after(5000, beat),
56 | {ok, #state{socket = Socket,
57 | timer = TRef}};
58 | {error, Reason} ->
59 | ?LOG_ERROR("Why can't I broadcast a heartbeat? ~p ~n",
60 | [Reason]),
61 | {ok, #state{}}
62 | end.
63 |
64 | handle_call(peers, _From, #state{peers=Peers} = State) ->
65 | {reply, ets:tab2list(Peers), State};
66 |
67 | handle_call(_Request, _From, State) ->
68 | Reply = ok,
69 | {reply, Reply, State}.
70 |
71 | %% casts
72 |
73 | handle_cast(_Msg, State) ->
74 | {noreply, State}.
75 |
76 | %% info
77 |
78 | handle_info({udp, _PeerSocket, Ip, _Port, Data},
79 | #state{socket =_Socket}=State) ->
80 | %% don't talk to yourself, unless you want complete agreement
81 | IsSelf = local_ip_v4() == Ip,
82 | record_peer(Ip, Data, IsSelf),
83 | {noreply, State};
84 |
85 | handle_info(beat, #state{socket=Socket}=State) ->
86 | gen_udp:send(Socket,
87 | {255,255,255,255},
88 | 8008,
89 | whoami()),
90 | {noreply, State#state{timer=timer:send_after(5000, beat)}};
91 |
92 | handle_info(_Info, State) ->
93 | {noreply, State}.
94 |
95 | terminate(_Reason, _State) ->
96 | ok.
97 |
98 | code_change(_OldVsn, State, _Extra) ->
99 | {ok, State}.
100 |
101 | %%%===================================================================
102 | %%% Internal functions
103 | %%%===================================================================
104 |
105 |
106 | local_ip_v4() ->
107 | {ok, Addrs} = inet:getifaddrs(),
108 | %% Deal with taking hd of empty list
109 | Ips = [
110 | Addr || {_, Opts} <- Addrs, {addr, Addr} <- Opts,
111 | size(Addr) == 4, Addr =/= {127,0,0,1}
112 | ],
113 | case Ips of
114 | [] ->
115 | {127,0,0,1};
116 | _else ->
117 | hd(Ips)
118 | end.
119 |
120 | record_peer(_Ip, _Data, true) ->
121 | %%?LOG_DEBUG("No talking to self ~n",[]),
122 | ok;
123 |
124 | record_peer(Ip, Data, _) ->
125 | PeerExists = ets:member(ssb_peers, Ip),
126 | case PeerExists of
127 | false ->
128 | PubKey = extract_key(Data),
129 | ?LOG_INFO("Heartbeat received from ~p ~n",[{Ip, utils:display_pub(PubKey)}]),
130 | ets:insert(ssb_peers, {Ip, PubKey});
131 | _ ->
132 | nop
133 | end.
134 |
135 | extract_key(Data) ->
136 | %% may be more that one connection string here, look for semicolon
137 | %% and truncate
138 | CheckMatch = binary:match(Data, <<":8008~shs:">>),
139 | if CheckMatch == nomatch ->
140 | nokey;
141 | true ->
142 | {Pos, Len} = CheckMatch,
143 | CheckSemicolon = binary:match(Data, <<";">>),
144 | End = case CheckSemicolon of
145 | nomatch ->
146 | size(Data);
147 | {Pos1, _} ->
148 | Pos1
149 | end,
150 | %%base64:decode(binary_to_list(
151 | binary:part(Data,
152 | (Pos + Len),
153 | End - (Pos + Len))
154 | end.
155 |
--------------------------------------------------------------------------------
/apps/ssb/src/keys.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(keys).
5 | -include("ssb.hrl").
6 | -behaviour(gen_server).
7 |
8 | -import(utils, [base_64/1,
9 | display_pub/1]).
10 |
11 | %% API
12 | -export([start_link/0,
13 | pub_key/0,
14 | pub_key_disp/0,
15 | priv_key/0,
16 | moid/0]).
17 |
18 | %% gen_server callbacks
19 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2,
20 | terminate/2, code_change/3]).
21 |
22 | -define(SERVER, ?MODULE).
23 |
24 | -record(state, {pub_key,
25 | priv_key}).
26 |
27 | %%%===================================================================
28 | %%% API
29 | %%%===================================================================
30 |
31 | pub_key() ->
32 | gen_server:call(?MODULE, pub_key, infinity).
33 |
34 | pub_key_disp() ->
35 | gen_server:call(?MODULE, pub_key_disp, infinity).
36 |
37 | priv_key() ->
38 | gen_server:call(?MODULE, priv_key, infinity).
39 |
40 | start_link() ->
41 | gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
42 |
43 | %%%===================================================================
44 | %%% gen_server callbacks
45 | %%%===================================================================
46 |
47 | init([]) ->
48 | process_flag(trap_exit, true),
49 | {PubKey, PrivKey} =
50 | case fetch_key() of
51 | {Pub, Priv} -> {Pub, Priv};
52 | first_time ->
53 | init_secret();
54 | _Any ->
55 | ?LOG_ERROR("Should not get this ~p ~n",[_Any]),
56 | {<<"whatkey">>,<<"whatkey">>}
57 | end,
58 | {ok, #state{pub_key = PubKey,
59 | priv_key = PrivKey}}.
60 |
61 | handle_call(pub_key, _From, #state{pub_key = PubKey}=State) ->
62 | {reply, PubKey, State};
63 |
64 | handle_call(pub_key_disp, _From, #state{pub_key = PubKey}=State) ->
65 | {reply, display_pub(PubKey), State};
66 |
67 | handle_call(priv_key, _From, #state{priv_key = PrivKey}=State) ->
68 | {reply, PrivKey, State}.
69 |
70 | %% casts
71 |
72 | handle_cast(_Msg, State) ->
73 | {noreply, State}.
74 |
75 | %% info
76 |
77 | handle_info(_Info, State) ->
78 | {noreply, State}.
79 |
80 |
81 | terminate(_Reason, _State) ->
82 | ok.
83 |
84 | code_change(_OldVsn, State, _Extra) ->
85 | {ok, State}.
86 |
87 | %%%===================================================================
88 | %%% Internal functions
89 | %%%===================================================================
90 | fetch_key() ->
91 | {ok, [[Home]]} = init:get_argument(home),
92 | SecretFileName = Home ++ "/.ssberl/secret",
93 | case file:open(SecretFileName, [read]) of
94 | {error, enoent} ->
95 | ?LOG_INFO("first time empty dir ~n"),
96 | first_time;
97 | {ok, IoDevice} ->
98 | extract_key(IoDevice)
99 | end.
100 |
101 | extract_key(IoDevice) ->
102 | case file:read_line(IoDevice) of
103 | {ok, Data} ->
104 | FirstChar = string:sub_string(Data,1,1),
105 | IsCommentOrNewLine = FirstChar == "%" orelse
106 | FirstChar == "\n",
107 | if IsCommentOrNewLine ->
108 | extract_key(IoDevice);
109 | true ->
110 | KeyMap = json:decode(iolist_to_binary(Data)),
111 | {PubKey, PrKey} = {maps:get(<<"public">>, KeyMap),
112 | maps:get(<<"private">>, KeyMap)},
113 | {key_only(PubKey), key_only(PrKey)}
114 | end;
115 | eof ->
116 | {<<"nokey">>,<<"nokey">>}
117 | end.
118 |
119 | init_secret() ->
120 | {Pub, Priv} = shs:create_long_pair(),
121 | SecretFileName = check_secret_file(),
122 | file:write_file(SecretFileName, prelude(), [append]),
123 | JsonDoc = make_json({Pub, Priv}),
124 | file:write_file(SecretFileName, JsonDoc, [append]),
125 | file:write_file(SecretFileName, suffix(Pub), [append]),
126 | {?l2b(base_64(Pub)), ?l2b(base_64(Priv))}.
127 |
128 | make_json({Pub, Priv}) ->
129 | Doc = {[{<<"curve">>, <<"ed25519">>},
130 | {<<"public">>, ?l2b(base_64(Pub) ++ ".ed25519")},
131 | {<<"private">>, ?l2b(base_64(Priv) ++ ".ed25519")},
132 | {<<"id">>, ?l2b("@" ++ base_64(Pub) ++ ".ed25519")}
133 | ]},
134 | iolist_to_binary(message:ssb_encoder(Doc, fun message:ssb_encoder/3, [])).
135 |
136 | check_secret_file() ->
137 | {ok, [[Home]]} = init:get_argument(home),
138 | SSBDir = Home ++ "/.ssberl",
139 | case file:list_dir(SSBDir) of
140 | {error, enoent} ->
141 | file:make_dir(SSBDir);
142 | _ -> ok
143 | end,
144 | SSBDir ++ "/secret".
145 |
146 | key_only(Key) ->
147 | hd(string:replace(Key,".ed25519","")).
148 |
149 |
150 | prelude() ->
151 | <<"%% this is your SECRET name.\n%% this name gives you magical powers.\n%% with it you can mark your messages so that your friends can verify\n%% that they really did come from you.%%\n%% if any one learns this name, they can use it to destroy your identity\n%% NEVER show this to anyone!!!\n\n">>.
152 |
153 | suffix(Pub) ->
154 | ?l2b("\n\n%%WARNING! It's vital that you DO NOT edit OR share your secret name\n%%instead, share your public name\n%%your public name: " ++ ?b2l(utils:display_pub(Pub))).
155 |
156 | moid() ->
157 | <<"@Sur8RwcDh6kBjub8pLZpHNWDfuuRpYVyCHrVo+TdA/4=.ed25519">>.
158 |
--------------------------------------------------------------------------------
/apps/ssb/src/mess_auth.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(mess_auth).
5 |
6 | %% A thin shell around bitcask store used as a simple message-author cache
7 |
8 | -ifdef(TEST).
9 | -include_lib("eunit/include/eunit.hrl").
10 | -endif.
11 |
12 | -include("ssb.hrl").
13 |
14 | -behaviour(gen_server).
15 |
16 | %% API
17 | -export([start_link/0,
18 | put/2,
19 | get/1,
20 | close/0,
21 | sync/0,
22 | all_auths/0]).
23 |
24 | %% gen_server callbacks
25 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2,
26 | terminate/2, code_change/3]).
27 |
28 | -define(SERVER, ?MODULE).
29 |
30 | -record(state, {m_a}).
31 |
32 | %%% API
33 |
34 | start_link() ->
35 | gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
36 |
37 | put(Key, Val) ->
38 | gen_server:call(?MODULE, {put, Key, Val}, infinity).
39 |
40 | get(Key) ->
41 | gen_server:call(?MODULE, {get, Key}).
42 |
43 | close() ->
44 | gen_server:call(?MODULE, {close}).
45 |
46 | sync() ->
47 | gen_server:call(?MODULE, {sync}).
48 |
49 | all_auths() ->
50 | gen_server:call(?MODULE, {auths}, infinity).
51 |
52 |
53 | %%%===================================================================
54 | %%% gen_server callbacks
55 | %%%===================================================================
56 |
57 | init([]) ->
58 | process_flag(trap_exit, true),
59 | TabName = ?b2l(config:feed_store_loc()) ++ "mess_auth",
60 | {ok, DetsTab} = dets:open_file(mess, [{file, TabName}]),
61 | {ok, #state{m_a = DetsTab}}.
62 |
63 | handle_call({put, Key, Val}, _From, #state{m_a = BitHand} = State) ->
64 | Ok = dets:insert(BitHand, {Key, Val}),
65 | {reply, Ok, State};
66 |
67 | handle_call({get, Key}, _From, #state{m_a = BitHand} = State) ->
68 | Res = dets:lookup(BitHand, Key),
69 | case Res of
70 | [{Key, Val}] ->
71 | {reply, Val, State};
72 | [] ->
73 | {reply, not_found, State};
74 | {error, Reason} ->
75 | {reply, Reason, State}
76 | end;
77 |
78 | handle_call({sync}, _From, #state{m_a = BitHand} = State) ->
79 | ok = dets:sync(BitHand),
80 | {reply, ok, State};
81 |
82 | handle_call({close}, _From, #state{m_a = BitHand} = State) ->
83 | ok = dets:close(BitHand),
84 | {reply, ok, State};
85 |
86 | handle_call({auths}, _From, #state{m_a = BitHand} = State) ->
87 | Fun = fun({_Mess, Auth}) ->
88 | {continue, Auth}
89 | end,
90 | Auths = dets:traverse(BitHand, Fun),
91 | {reply, Auths, State}.
92 |
93 | handle_cast(_Request, State) ->
94 | {noreply, State}.
95 |
96 | handle_info(_Info, State) ->
97 | {noreply, State}.
98 |
99 | terminate(Reason, #state{m_a = BitHand}) ->
100 | ?LOG_INFO("Terminate called for reason: ~p ~n",[Reason]),
101 | dets:close(BitHand).
102 |
103 | code_change(_OldVsn, State, _Extra) ->
104 | {ok, State}.
105 |
106 | %%%===================================================================
107 | %%% Internal functions
108 | %%%===================================================================
109 |
110 | -ifdef(TEST).
111 |
112 | -endif.
113 |
--------------------------------------------------------------------------------
/apps/ssb/src/message.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(message).
5 | -include("ssb.hrl").
6 |
7 | -ifdef(TEST).
8 | -include_lib("eunit/include/eunit.hrl").
9 | -endif.
10 |
11 | %% API
12 | -export([decode/2,
13 | encode/1,
14 | ssb_encoder/3,
15 | is_follow/1,
16 | is_about/1,
17 | is_reply/1,
18 | is_branch/1,
19 | new_msg/4]).
20 |
21 | is_follow(#message{content = Val}) when is_binary(Val) ->
22 | nope;
23 |
24 | is_follow(#message{content = {ContentProps}}) ->
25 | Type = ?pgv(<<"type">>, ContentProps),
26 | case Type of
27 | <<"contact">> ->
28 | check_contact(?pgv(<<"contact">>,ContentProps),
29 | ?pgv(<<"following">>, ContentProps));
30 | _Else ->
31 | nope
32 | end.
33 |
34 | is_about(#message{content = Content}) when is_binary(Content) ->
35 | false;
36 |
37 | is_about(#message{content = {ContentProps}}) ->
38 | Type = ?pgv(<<"type">>, ContentProps),
39 | case Type of
40 | undefined ->
41 | false;
42 | Type ->
43 | Type == <<"about">>
44 | end.
45 |
46 | is_branch(#message{content = Content}) when is_binary(Content) ->
47 | false;
48 |
49 | is_branch(#message{content = {Content}}) ->
50 | Root = ?pgv(<<"root">>, Content),
51 | Branch = ?pgv(<<"branch">>, Content),
52 | build_branch(Root, Branch).
53 |
54 | build_branch(undefined, _Branch) ->
55 | false;
56 | build_branch(_Root, undefined) ->
57 | false;
58 | build_branch(false, _Branch) ->
59 | false;
60 | build_branch(_Root, false) ->
61 | false;
62 | build_branch(Root, Branch) when is_list(Branch) ->
63 | {Root, Branch};
64 | build_branch(Root, Branch) ->
65 | {Root, [Branch]}.
66 |
67 | is_reply(#message{content = Content}) when is_binary(Content) ->
68 | false;
69 |
70 | is_reply(#message{content = {Content}}) ->
71 | build_reply(?pgv(<<"reply">>, Content)).
72 |
73 | build_reply(undefined) ->
74 | false;
75 |
76 | build_reply(Reply) ->
77 | Reply.
78 |
79 | check_contact(undefined, _Following) ->
80 | nope;
81 | check_contact(<<>>, _Following) ->
82 | nope;
83 | check_contact(Contact, true) ->
84 | {Contact, true};
85 | check_contact(Contact, false) ->
86 | {Contact, false};
87 | check_contact(_Contact, _Following) ->
88 | nope.
89 |
90 | new_msg(Previous, Sequence, Content, {PubKey, PrivKey}) ->
91 | Timestamp = integer_to_binary(current_time()),
92 | Hash = <<"sha256">>,
93 | NewMsg = #message{previous = Previous,
94 | author = PubKey,
95 | sequence = Sequence,
96 | timestamp = Timestamp,
97 | hash = Hash,
98 | content = Content,
99 | received = Timestamp},
100 | EncNewMsg = ssb_encoder({msg_to_proplist(NewMsg)},
101 | fun ssb_encoder/3,
102 | [pretty, use_nil]),
103 | Sig = enacl:sign_detached(EncNewMsg,
104 | base64:decode(PrivKey)),
105 | EncSig = ?l2b(utils:base_64(Sig) ++ ".sig.ed25519"),
106 | %% Now add the sig to original msg
107 | add_sig(NewMsg, EncSig).
108 |
109 | encode(#message{id = Key, received = Received, swapped = Swapped} = Msg) ->
110 | MsgProps = msg_to_proplist(Msg),
111 | EncMsg = build_props(MsgProps, Swapped),
112 |
113 | iolist_to_binary(ssb_encoder({[{<<"key">>, Key},
114 | {<<"value">>, {EncMsg}},
115 | {<<"timestamp">>, Received}]}, fun ssb_encoder/3, [use_nil])).
116 |
117 | decode(Msg, CheckValid) ->
118 | {DecDataProps} = utils:nat_decode(Msg),
119 | Key = ?pgv(<<"key">>, DecDataProps),
120 | {Value} = ?pgv(<<"value">>, DecDataProps),
121 | IsSwapped = is_swapped(Value),
122 | IsValid = validate(CheckValid, Value),
123 | #message{id = Key,
124 | previous = ?pgv(<<"previous">>, Value),
125 | author = ?pgv(<<"author">>, Value),
126 | sequence = ?pgv(<<"sequence">>, Value),
127 | timestamp = ?pgv(<<"timestamp">>, Value),
128 | hash = ?pgv(<<"hash">>, Value),
129 | content = ?pgv(<<"content">>, Value),
130 | signature = ?pgv(<<"signature">>, Value),
131 | received = ?pgv(<<"timestamp">>, DecDataProps),
132 | validated = IsValid,
133 | swapped = IsSwapped}.
134 |
135 | is_swapped(PropList) ->
136 | element(1, lists:nth(2, PropList)) == <<"sequence">>.
137 |
138 | build_props(Props, Swapped) ->
139 | [{<<"previous">>, ?pgv(<<"previous">>, Props)}] ++
140 | check_swapped(Props, Swapped) ++
141 | [{<<"timestamp">>, ?pgv(<<"timestamp">>, Props)},
142 | {<<"hash">>, ?pgv(<<"hash">>, Props)},
143 | {<<"content">>, ?pgv(<<"content">>, Props)},
144 | {<<"signature">>, ?pgv(<<"signature">>, Props)}].
145 |
146 | check_swapped(Props, Swapped) ->
147 | Seq = {<<"sequence">>, ?pgv(<<"sequence">>, Props)},
148 | Auth = {<<"author">>, ?pgv(<<"author">>, Props)},
149 | if Swapped ->
150 | [Seq, Auth];
151 | true ->
152 | [Auth, Seq]
153 | end.
154 |
155 | validate(false, _MsgProps) ->
156 | false;
157 | validate(true, MsgProps) ->
158 | try
159 | Author = ?pgv(<<"author">>, MsgProps),
160 |
161 | %% remove signature from message and encode as json
162 | DelSigProps = proplists:delete(<<"signature">>, MsgProps),
163 | EncMsg = ssb_encoder({DelSigProps}, fun ssb_encoder/3, [pretty, use_nil]),
164 |
165 | %% extract and decode the keys for the signature and the author
166 | Sig = ?pgv(<<"signature">>, MsgProps),
167 | <<"@",KeySuf/binary>> = Author,
168 | AuthorPk = base64:decode(hd(string:replace(KeySuf,".ed25519",""))),
169 | SigDec = base64:decode(hd(string:replace(Sig,".sig.ed25519",""))),
170 |
171 | %% verify
172 | enacl:sign_verify_detached(SigDec, EncMsg, AuthorPk)
173 | catch
174 | error:Reason ->
175 | ?LOG_INFO("Unable to validate due to: ~p ~n",
176 | [Reason]),
177 | false
178 | end.
179 |
180 | add_sig(NewMsg, EncSig) ->
181 | NewMsgList = msg_to_proplist(NewMsg) ++
182 | [{<<"signature">>, EncSig}],
183 | %% added sig to msg before computing id
184 | MsgId = compute_id(ssb_encoder({NewMsgList}, fun ssb_encoder/3,
185 | [pretty,
186 | use_nil])),
187 | NewMsg#message{id = MsgId,
188 | signature = EncSig}.
189 |
190 | msg_to_proplist(Msg) ->
191 | lists:zip(lists:map(fun(A) ->
192 | atom_to_binary(A, utf8) end,
193 | record_info(fields, message)),
194 | tl(tuple_to_list(Msg))).
195 |
196 | compute_id(Msg) ->
197 | ?l2b("%" ++
198 | utils:base_64(crypto:hash(sha256, Msg))
199 | ++
200 | ".sha256").
201 |
202 | current_time() ->
203 | erlang:system_time(millisecond).
204 |
205 | ssb_encoder(Val, Encoder, Options) ->
206 | ssb_encoder1(Val, Encoder, Options, 0).
207 |
208 | ssb_encoder1([], _Encoder, _Options, _Ind) ->
209 | [<<"[]">>];
210 |
211 | ssb_encoder1([_|_] = V, Encoder, Options, Ind) when is_list(V) ->
212 | Pretty = lists:member(pretty, Options),
213 | Array = lists:map(fun(Elem) ->
214 | if Pretty ->
215 | [<<"\n">>, string:copies(" ", Ind + 1),
216 | ssb_encoder1(Elem, Encoder, Options, Ind + 1),
217 | <<",">>];
218 | true ->
219 | [ssb_encoder1(Elem, Encoder, Options, Ind + 1),
220 | <<",">>]
221 | end
222 | end, V),
223 | LastElem = lists:last(Array),
224 | ArrayNoLast = lists:reverse(tl(lists:reverse(Array))),
225 | FixElem = lists:reverse(tl(lists:reverse(LastElem))),
226 | if Pretty ->
227 | [<<"[">>, ArrayNoLast ++ [FixElem], <<"\n">>, string:copies(" ", Ind), <<"]">>];
228 | true ->
229 | [<<"[">>, ArrayNoLast ++ [FixElem], <<"]">>]
230 | end;
231 |
232 | ssb_encoder1({[]}, _Encoder, _Options, _Ind) ->
233 | [<<"{}">>];
234 |
235 | ssb_encoder1({KeyValList}, Encoder, Options, Ind) ->
236 | Pretty = lists:member(pretty, Options),
237 | Obj = lists:map(fun({_, _} = Val) -> ssb_encoder1(Val, Encoder, Options, Ind + 1) end,
238 | KeyValList),
239 | LastElem = lists:last(Obj),
240 | ObjNoLast = lists:reverse(tl(lists:reverse(Obj))),
241 | FixElem = lists:reverse(tl(lists:reverse(LastElem))),
242 | if Pretty ->
243 | [<<"{">>, ObjNoLast ++ [FixElem], <<"\n">>, string:copies(" ", Ind), <<"}">>];
244 | true ->
245 | [<<"{">>, ObjNoLast ++ [FixElem], <<"}">>]
246 | end;
247 |
248 | ssb_encoder1({Key, Val}, Encoder, Options, Ind) ->
249 | Pretty = lists:member(pretty, Options),
250 | if Pretty ->
251 | [<<"\n">>, string:copies(" ", Ind), ssb_encoder1(Key, Encoder, Options, Ind), <<": ">>, ssb_encoder1(Val, Encoder, Options, Ind), <<",">>];
252 | true ->
253 | [ssb_encoder1(Key, Encoder, Options, Ind), <<":">>, ssb_encoder1(Val, Encoder, Options, Ind), <<",">>]
254 | end;
255 |
256 | ssb_encoder1(Other, Encoder, Options, _Ind) ->
257 | GoodAtom = is_atom(Other) andalso ((Other == null)
258 | orelse
259 | (Other == true)
260 | orelse
261 | (Other == false)),
262 | UseNil = lists:member(use_nil, Options) andalso (Other == nil),
263 | if UseNil ->
264 | json:encode_value(null, Encoder);
265 | true ->
266 | if is_atom(Other) andalso (not GoodAtom) ->
267 | json:encode_value(atom_to_binary(Other), Encoder);
268 | true ->
269 | json:encode_value(Other, Encoder)
270 | end
271 | end.
272 |
273 |
274 | -ifdef(TEST).
275 |
276 | roundtrip_test() ->
277 | {ok, Cwd} = file:get_cwd(),
278 | Ints = lists:seq(1,235),
279 | Fun = fun(N) ->
280 | F = Cwd ++ "/testdata/" ++ io_lib:format("~5..0w",[N]) ++ ".full",
281 | {ok, FilBin} = file:read_file(F),
282 | encode(decode(FilBin, true)) == FilBin
283 | end,
284 |
285 | Results = lists:map(Fun, Ints),
286 | ?assert(lists:all(fun(B) ->
287 | B end, Results)).
288 |
289 | ssb_test() ->
290 | O1 = {[{<<"key1">>,<<"val1">>},{<<"key2">>, [{[{<<"skey1">>, <<"sval1">>}]},{[{<<"skey12">>, <<"sval2">>}]}]}]},
291 | BO1 = iolist_to_binary(ssb_encoder(O1, fun ssb_encoder/3, [use_nil])),
292 | ?assert(O1 == utils:nat_decode(BO1)).
293 |
294 | bad_msg_test() ->
295 | {ok, Cwd} = file:get_cwd(),
296 | F = Cwd ++ "/testdata/" ++ "bad.full",
297 | {ok, FilBin} = file:read_file(F),
298 | ?assert(FilBin == encode(decode(FilBin, true))).
299 |
300 | is_about_test() ->
301 | {ok, Cwd} = file:get_cwd(),
302 | F = Cwd ++ "/testdata/" ++ "about.full",
303 | {ok, FilBin} = file:read_file(F),
304 |
305 | ?assert(message:is_about(decode(FilBin, true))).
306 |
307 | is_reply_test() ->
308 | {ok, Cwd} = file:get_cwd(),
309 | F = Cwd ++ "/testdata/" ++ "reply.full",
310 | {ok, FilBin} = file:read_file(F),
311 |
312 | ?assert(message:is_reply(decode(FilBin, true)) /= false).
313 |
314 | is_multi_reply_test() ->
315 | {ok, Cwd} = file:get_cwd(),
316 | F = Cwd ++ "/testdata/" ++ "mult-reply.full",
317 | {ok, FilBin} = file:read_file(F),
318 | Msg = decode(FilBin, true),
319 | {ListPairs} = message:is_reply(Msg),
320 | ?assert(length(ListPairs) == 2).
321 |
322 | is_not_reply_test() ->
323 | {ok, Cwd} = file:get_cwd(),
324 | F = Cwd ++ "/testdata/" ++ "not_reply.full",
325 | {ok, FilBin} = file:read_file(F),
326 |
327 | ?assert(not message:is_reply(decode(FilBin, true))).
328 |
329 | is_single_branch_test() ->
330 | {ok, Cwd} = file:get_cwd(),
331 | F = Cwd ++ "/testdata/" ++ "single-branch.full",
332 | {ok, FilBin} = file:read_file(F),
333 | {_Root, Branches} = message:is_branch(decode(FilBin, true)),
334 | ?assert(is_list(Branches) andalso length(Branches) == 1).
335 |
336 | is_multi_branch_test() ->
337 | {ok, Cwd} = file:get_cwd(),
338 | F = Cwd ++ "/testdata/" ++ "multi-branch.full",
339 | {ok, FilBin} = file:read_file(F),
340 | {_Root, Branches} = message:is_branch(decode(FilBin, true)),
341 | ?assert(is_list(Branches) andalso length(Branches) == 2).
342 |
343 | follow_true_test() ->
344 | {ok, Cwd} = file:get_cwd(),
345 | F = Cwd ++ "/testdata/" ++ "follow_true.full",
346 | {ok, FilBin} = file:read_file(F),
347 | {_FeedId, Bool} = message:is_follow(decode(FilBin, true)),
348 |
349 | ?assert(Bool).
350 |
351 | follow_false_test() ->
352 | {ok, Cwd} = file:get_cwd(),
353 | F = Cwd ++ "/testdata/" ++ "follow_false.full",
354 | {ok, FilBin} = file:read_file(F),
355 | {_FeedId, Bool} = message:is_follow(decode(FilBin, true)),
356 |
357 | ?assert(not Bool).
358 |
359 | -endif.
360 |
--------------------------------------------------------------------------------
/apps/ssb/src/rpc_parse.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(rpc_parse).
5 |
6 | -ifdef(TEST).
7 | -include_lib("eunit/include/eunit.hrl").
8 | -import(rpc_processor, [create_flags/3,
9 | create_header/3]).
10 |
11 | -endif.
12 |
13 | -include("ssb.hrl").
14 |
15 | %% API
16 | -export([parse/1]).
17 |
18 | %%%===================================================================
19 | %%% API
20 | %%%===================================================================
21 | parse(Msg) when size(Msg) < 9 ->
22 | {partial, nil, Msg};
23 |
24 | parse(Msg) ->
25 | <> = Msg,
27 | IsEnd = Header == ?RPC_END,
28 | case IsEnd of
29 | true ->
30 | {complete, ?RPC_END, Rest};
31 | false ->
32 | parseRest(Header, Rest, Msg)
33 | end.
34 |
35 | %% private funs
36 |
37 | parseRest(Header, Rest, OrigData) ->
38 | BodySize = body_size(Header),
39 | extract_body(BodySize, Header, Rest, OrigData).
40 |
41 | extract_body(BodySize, Header, Rest, _OrigData) when BodySize =< size(Rest) ->
42 | <> = Rest,
44 | {complete, {Header, Body}, RestRest};
45 |
46 | extract_body(_BodySize, _Header, _Rest, OrigData) ->
47 | {partial, nil, OrigData}.
48 |
49 | body_size(Header) ->
50 | <<_Flags:1/binary,
51 | BodySize:4/big-unsigned-integer-unit:8,
52 | _ReqNo:4/big-signed-integer-unit:8>> = Header,
53 | BodySize.
54 |
55 | -ifdef(TEST).
56 | simple_test() ->
57 | Flags = create_flags(1,0,2),
58 | Header = create_header(Flags, 0, 1),
59 | ?assert(parse(utils:combine(Header, <<>>)) ==
60 | {complete,{<<10,0,0,0,0,0,0,0,1>>,<<>>},<<>>}).
61 |
62 | no_body_test() ->
63 | Flags = create_flags(1,0,2),
64 | Header = create_header(Flags, 6, 1),
65 | ?assert(parse(utils:combine(Header, <<"true">>)) ==
66 | {partial,nil,utils:combine(Header, <<"true">>)}).
67 |
68 | no_header_test() ->
69 | Header = <<10,0,0,0,0,0,0,0>>,
70 | ?assert(parse(Header) ==
71 | {partial,nil,Header}).
72 |
73 | full_test() ->
74 | Flags = create_flags(1,0,2),
75 | Header = create_header(Flags, 4, 1),
76 | ?assert(parse(utils:combine(Header, <<"true">>)) ==
77 | {complete,{<<10,0,0,0,4,0,0,0,1>>,<<"true">>},<<>>}).
78 |
79 | not_enough_test() ->
80 | Flags = create_flags(1,0,2),
81 | Header = create_header(Flags, 12, 1),
82 | ?assert(parse(utils:combine(Header, <<"trueorfalse">>)) ==
83 | {partial,nil,utils:combine(Header, <<"trueorfalse">>)}).
84 |
85 | over_test() ->
86 | Flags = create_flags(1,0,2),
87 | Header = create_header(Flags, 4, 1),
88 | ?assert(parse(utils:combine(Header, <<"trueorfalse">>)) ==
89 | {complete,{<<10,0,0,0,4,0,0,0,1>>,<<"true">>},<<"orfalse">>}).
90 |
91 | -endif.
92 |
--------------------------------------------------------------------------------
/apps/ssb/src/rpc_processor.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(rpc_processor).
5 |
6 | -ifdef(TEST).
7 | -include_lib("eunit/include/eunit.hrl").
8 | -endif.
9 |
10 | -include("ssb.hrl").
11 |
12 | %% API
13 | -export([process/2,
14 | create_flags/3,
15 | create_header/3,
16 | parse_flags/1]).
17 |
18 | -import(message, [ssb_encoder/3]).
19 | process({Header, Body}, #ssb_conn{
20 | socket = Socket,
21 | nonce = Nonce,
22 | secret_box = SecretBoxKey}) ->
23 | ReqNo = req_no(Header),
24 |
25 | ?LOG_DEBUG("Please process ~p ~p ~n from pid: ~p ~n",[Header, {ReqNo, Body}, self()]),
26 |
27 | case ReqNo < 0 of
28 | %% negative request numbers indicate responses
29 | true ->
30 | Resp = proc_response(ReqNo, Body),
31 | {Nonce, Resp};
32 | _Else ->
33 | ReqBod = create_req(Body),
34 | NewNonce = proc_request(ReqNo, ReqBod, Socket, Nonce, SecretBoxKey),
35 | {NewNonce, none}
36 | end.
37 |
38 | parse_flags(Header) ->
39 | <> = Header,
40 | <<_Unused:4, Stream:1, EndOrError:1, Type:2>> = Flags,
41 | {Stream, EndOrError, Type}.
42 |
43 | create_flags(Stream, EndOrError, Type) ->
44 | <<0:4, Stream:1, EndOrError:1, Type:2>>.
45 |
46 | create_header(Flags, BodySize, ReqNo) ->
47 | <>.
50 |
51 |
52 | %%%===================================================================
53 | %%% Internal functions
54 | %%%===================================================================
55 |
56 | req_no(Header) ->
57 | <<_Flags:1/binary,
58 | _BodySize:4/binary,
59 | Req:4/big-signed-integer-unit:8>> = Header,
60 | Req.
61 |
62 | create_req(Body) ->
63 | DecBody = utils:nat_decode(Body),
64 | ?LOG_DEBUG("Body decoded is ~p ~n",[DecBody]),
65 | IsTuple = is_tuple(DecBody),
66 | case IsTuple of
67 | true ->
68 | {Props} = DecBody,
69 | #ssb_rpc{
70 | name = proplists:get_value(<<"name">>, Props),
71 | args = proplists:get_value(<<"args">>, Props),
72 | type = proplists:get_value(<<"type">>, Props)};
73 | _Else ->
74 | DecBody
75 | end.
76 |
77 | proc_response(ReqNo, RespBody) ->
78 | ?LOG_DEBUG("The response from ~p was ~p ~n",[ReqNo, RespBody]),
79 | RespBody.
80 |
81 | proc_request(ReqNo, #ssb_rpc{name = [?createhistorystream],
82 | args = [{_Args}]}
83 | = _ReqBody, Socket, Nonce, SecretBoxKey) ->
84 | % to start return true and close stream
85 | Flags = create_flags(1,1,2),
86 | Header = create_header(Flags,size(<<"true">>), -ReqNo),
87 | utils:send_data(utils:combine(Header,message:ssb_encoder(true, fun message:ssb_encoder/3, [pretty])),
88 | Socket, Nonce, SecretBoxKey);
89 |
90 | proc_request(ReqNo, #ssb_rpc{name = [?gossip, ?ping],
91 | args = [{_Args}]}
92 | = _ReqBody, Socket, Nonce, SecretBoxKey) ->
93 | % to start return true and close stream
94 | Flags = create_flags(1,0,10),
95 | TimeStamp = iolist_to_binary(message:ssb_encoder(integer_to_binary(current_time()),
96 | fun message:ssb_encoder/3, [pretty])),
97 | Header = create_header(Flags,size(TimeStamp), -ReqNo),
98 | ?LOG_DEBUG("Answering ping with ~p ~n",[{Header, TimeStamp}]),
99 | NewNonce = utils:send_data(utils:combine(Header, TimeStamp), Socket, Nonce, SecretBoxKey),
100 | NewNonce;
101 | %%utils:send_data(?BOX_END, Socket, NewNonce, SecretBoxKey);
102 |
103 | proc_request(ReqNo, #ssb_rpc{name = [?whoami],
104 | args = []}
105 | = _ReqBody, Socket, Nonce, SecretBoxKey) ->
106 | % to start return true and close stream
107 | Flags = create_flags(1,0,10),
108 | Body = whoami(),
109 | Header = create_header(Flags, size(Body), -ReqNo),
110 | Data = utils:combine(Header, Body),
111 | NewNonce = utils:send_data(Data, Socket, Nonce, SecretBoxKey),
112 | NewNonce1 = utils:send_data(?RPC_END, Socket, NewNonce, SecretBoxKey),
113 | utils:send_data(?BOX_END, Socket, NewNonce1, SecretBoxKey);
114 |
115 | proc_request(ReqNo, #ssb_rpc{name = [?blobs, <<"createWants">>],
116 | args = []}
117 | = _ReqBody, Socket, Nonce, SecretBoxKey) ->
118 | % to start return true and close stream
119 | Flags = create_flags(1,1,2),
120 | TrueEnd = message:ssb_encoder(true, fun message:ssb_encoder/3, [pretty]),
121 | Header = create_header(Flags,size(TrueEnd), -ReqNo),
122 | utils:send_data(utils:combine(utils:combine(Header,TrueEnd), ?RPC_END),
123 | Socket, Nonce, SecretBoxKey);
124 |
125 | proc_request(ReqNo, #ssb_rpc{name = [?tunnel, <<"isRoom">>],
126 | args = []}
127 | = _ReqBody, Socket, Nonce, SecretBoxKey) ->
128 | % to start return true and close stream
129 | Flags = create_flags(0,0,2),
130 | TrueEnd = message:ssb_encoder(false, fun message:ssb_encoder/3, [pretty]),
131 | Header = create_header(Flags,size(TrueEnd), -ReqNo),
132 | utils:send_data(utils:combine(utils:combine(Header,TrueEnd), ?RPC_END),
133 | Socket, Nonce, SecretBoxKey);
134 |
135 | proc_request(ReqNo, #ssb_rpc{name = [?ebt, <<"replicate">>] = Name,
136 | args = _Args}
137 | = _ReqBody, Socket, Nonce, SecretBoxKey) ->
138 | % to start return true and close stream
139 | Flags = create_flags(0,1,2),
140 | ErrorMsg = utils:error_msg(Name, <<"Not yet implemented">>),
141 | %%TrueEnd = message:ssb_encoder(true, fun message:ssb_encoder/3, [pretty]),
142 | Header = create_header(Flags,size(ErrorMsg), -ReqNo),
143 | ?LOG_DEBUG("Answering ebt_rep with ~p ~n",[{Header, ErrorMsg}]),
144 | utils:send_data(utils:combine(utils:combine(Header,ErrorMsg), ?RPC_END),
145 | Socket, Nonce, SecretBoxKey);
146 |
147 | proc_request(ReqNo, ReqBody, Socket, Nonce, SecretBoxKey) ->
148 | ?LOG_DEBUG("Fall thru with ~p ~n",[ReqBody]),
149 | Flags = create_flags(0,1,2),
150 | TrueEnd = message:ssb_encoder(true, fun message:ssb_encoder/3, [pretty]),
151 | Header = create_header(Flags,size(TrueEnd), -ReqNo),
152 | NewNonce = utils:send_data(utils:combine(Header, TrueEnd),
153 | Socket, Nonce, SecretBoxKey),
154 | utils:send_data(?RPC_END, Socket, NewNonce, SecretBoxKey).
155 |
156 | current_time() ->
157 | erlang:system_time(millisecond).
158 |
159 | whoami() ->
160 | iolist_to_binary(message:ssb_encoder({[{<<"id">>, keys:pub_key_disp()}]},
161 | fun message:ssb_encoder/3, [])).
162 |
163 | -ifdef(TEST).
164 |
165 | body1_test() ->
166 | Rpc = create_req(iolist_to_binary(ssb_encoder({[{<<"name">>,[<<"gossip">>,<<"ping">>]},
167 | {<<"args">>,[{[{<<"timeout">>,300000}]}]},
168 | {<<"type">>,<<"duplex">>}]}, fun message:ssb_encoder/3, []))),
169 | ?assert(Rpc#ssb_rpc.name == [<<"gossip">>,<<"ping">>]),
170 | ?assert(Rpc#ssb_rpc.type == <<"duplex">>).
171 |
172 | body2_test() ->
173 | Rpc = create_req(iolist_to_binary(ssb_encoder(22222, fun message:ssb_encoder/3, []))),
174 | ?assert(Rpc == 22222).
175 |
176 | flags_test() ->
177 | ?assert(<<10>> == create_flags(1,0,2)),
178 | ?assert({1,0,2} == parse_flags(<<10>>)),
179 | ?assert({1,1,2} == parse_flags(<<14>>)).
180 |
181 | -endif.
182 |
--------------------------------------------------------------------------------
/apps/ssb/src/shs.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(shs).
5 |
6 | -include("ssb.hrl").
7 |
8 | -ifdef(TEST).
9 | -include_lib("eunit/include/eunit.hrl").
10 | -endif.
11 |
12 | -import(utils, [concat/1,
13 | combine/2]).
14 | -export([open_box/3,
15 | create_long_pair/0,
16 | client_shake_hands/2,
17 | server_shake_hands/3]).
18 |
19 | check_hello(BinData) ->
20 | case size(BinData) of
21 | 64 ->
22 | <> = BinData,
23 | Valid = enacl:auth_verify(Hmac, Eph_pk, config:network_id()),
24 | <> = Hmac,
25 | {Valid, Eph_pk, Nonce};
26 | _ ->
27 | {false, nobody, none}
28 | end.
29 |
30 | gen_hello() ->
31 |
32 | #{public := Eph_pk,
33 | secret := Eph_sk} = enacl:box_keypair(),
34 | SizEph_pk = size(Eph_pk),
35 |
36 | NaclAuth = enacl:auth(Eph_pk, config:network_id()),
37 | SizNaclAuth = size(NaclAuth),
38 |
39 | <> = NaclAuth,
40 |
41 | {Eph_sk, <>, Nonce}.
43 |
44 | mult(Key1, Key2) ->
45 | enacl:curve25519_scalarmult(Key1, Key2).
46 |
47 | sk_to_curve25519(Key) ->
48 | enacl:crypto_sign_ed25519_secret_to_curve25519(Key).
49 |
50 | pk_to_curve25519(Key) ->
51 | enacl:crypto_sign_ed25519_public_to_curve25519(Key).
52 |
53 | open_box(Data, Nonce, Key) ->
54 | Resp = enacl:secretbox_open(Data,Nonce,Key),
55 | case Resp of
56 | {error, failed_verification} ->
57 | %% need to handle this above somewhere, for now let it crash!
58 | <<"bad">>;
59 | {ok, Msg} ->
60 | Msg
61 | end.
62 |
63 | create_box(Data, Key) ->
64 | enacl:secretbox(Data,?SHS_NONCE,crypto:hash(sha256, Key)).
65 |
66 | create_long_pair() ->
67 | KeyPair = enacl:crypto_sign_ed25519_keypair(),
68 | {maps:get(public, KeyPair),
69 | maps:get(secret, KeyPair)}.
70 |
71 | client_shake_hands(Socket, RemotePubKey) ->
72 |
73 | {Pub_pk, Priv_sk} = create_long_pair(),
74 | {Eph_sk, Hmac, DecNonce} = gen_hello(),
75 |
76 | % say hello to server
77 | gen_tcp:send(Socket, Hmac),
78 |
79 | % receive response from server
80 | {ok, ServerHmac} = gen_tcp:recv(Socket, 64, 5000),
81 |
82 | {true, ServEph_pk, EncNonce} = check_hello(ServerHmac),
83 |
84 | Shared_ab = mult(Eph_sk, ServEph_pk),
85 | Shared_aB = mult(Eph_sk,
86 | pk_to_curve25519(RemotePubKey)),
87 |
88 | ShaSab = crypto:hash(sha256,Shared_ab),
89 |
90 | DetSigA = enacl:sign_detached(concat([config:network_id(),
91 | RemotePubKey,
92 | ShaSab]),
93 | Priv_sk),
94 |
95 | Msg = concat([DetSigA, Pub_pk]),
96 |
97 | Box = create_box(Msg,
98 | concat([config:network_id(),
99 | Shared_ab,
100 | Shared_aB])),
101 |
102 | % client authenticates
103 | gen_tcp:send(Socket, Box),
104 |
105 | Shared_Ab = mult(sk_to_curve25519(Priv_sk),
106 | ServEph_pk),
107 | {ok, ServData} = gen_tcp:recv(Socket, 80, 5000),
108 |
109 | DetSigB =
110 | open_box(ServData,
111 | ?SHS_NONCE,
112 | crypto:hash(sha256,
113 | concat([config:network_id(),
114 | Shared_ab,
115 | Shared_aB,
116 | Shared_Ab]))),
117 |
118 | M = concat([config:network_id(),
119 | DetSigA,
120 | Pub_pk,
121 | ShaSab]),
122 |
123 | true = enacl:sign_verify_detached(DetSigB,
124 | M,
125 | RemotePubKey),
126 |
127 | SharedKey = crypto:hash(sha256,
128 | crypto:hash(sha256,
129 | concat([config:network_id(),
130 | Shared_ab,
131 | Shared_aB,
132 | Shared_Ab]))),
133 | DecBoxKey = crypto:hash(sha256,
134 | concat([SharedKey, Pub_pk])),
135 | EncBoxKey = crypto:hash(sha256,
136 | concat([SharedKey, RemotePubKey])),
137 |
138 | {ok, {Socket, DecBoxKey, DecNonce, EncBoxKey, EncNonce}}.
139 |
140 | server_shake_hands(Data, Socket, Transport) ->
141 |
142 | % check hellow from client
143 | {true, ClEph_pk, EncNonce} = check_hello(Data),
144 |
145 | {Eph_sk, ServerHmac, DecNonce} = gen_hello(),
146 | % server says hello
147 | Transport:send(Socket,ServerHmac),
148 |
149 | Shared_ab = mult(Eph_sk, ClEph_pk),
150 | Shared_aB = mult(sk_to_curve25519(long_sk()),
151 | ClEph_pk),
152 |
153 | % receive client autheticate
154 | {ok, ServData} = Transport:recv(Socket, 112, 5000),
155 |
156 | ShaSab = crypto:hash(sha256,Shared_ab),
157 | MsgPlain =
158 | open_box(ServData, ?SHS_NONCE,
159 | crypto:hash(sha256,
160 | concat([config:network_id(),
161 | Shared_ab,
162 | Shared_aB]))),
163 | <> = MsgPlain,
164 | true =
165 | enacl:sign_verify_detached(DetSigA,
166 | concat([config:network_id(),
167 | long_pk(),
168 | ShaSab]),
169 | ClLong_pk),
170 | Shared_Ab =
171 | mult(Eph_sk,pk_to_curve25519(ClLong_pk)),
172 | DetSigB =
173 | enacl:sign_detached(concat([config:network_id(),
174 | DetSigA,
175 | ClLong_pk,
176 | ShaSab]),
177 | long_sk()),
178 | Box =
179 | create_box(DetSigB,
180 | concat([config:network_id(),
181 | Shared_ab,
182 | Shared_aB,
183 | Shared_Ab])),
184 |
185 | % server accepts
186 | Transport:send(Socket,Box),
187 |
188 | SharedKey = crypto:hash(sha256,
189 | crypto:hash(sha256, concat([config:network_id(),
190 | Shared_ab,
191 | Shared_aB,
192 | Shared_Ab]))),
193 | DecBoxKey = crypto:hash(sha256, combine(SharedKey,
194 | long_pk())),
195 | EncBoxKey = crypto:hash(sha256, combine(SharedKey,
196 | ClLong_pk)),
197 |
198 | {ok, {DecBoxKey, DecNonce, EncBoxKey, EncNonce}}.
199 |
200 | long_sk() ->
201 | base64:decode(keys:priv_key()).
202 |
203 | long_pk() ->
204 | base64:decode(keys:pub_key()).
205 |
206 |
207 |
208 | -ifdef(TEST).
209 |
210 | simple_test() ->
211 | {ok, Pid} = config:start_link("test/ssb.cfg"),
212 | {Eph_sk, Hmac, _Nonce} = gen_hello(),
213 | ?assert(size(Eph_sk) == 32),
214 | ?assert(size(Hmac) == 64),
215 | gen_server:stop(Pid).
216 |
217 | round_trip_test() ->
218 | {ok, Pid} = config:start_link("test/ssb.cfg"),
219 | {_Eph_sk, Hmac, _} = gen_hello(),
220 | {true, _Eph_pk, _} = check_hello(Hmac),
221 | gen_server:stop(Pid).
222 |
223 | -endif.
224 |
--------------------------------------------------------------------------------
/apps/ssb/src/smoke.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(smoke).
5 | -include_lib("ssb/include/ssb.hrl").
6 |
7 | -export([secret_handshake/1,
8 | remote_long_pk/0,
9 | smoke/0,
10 | largest_feed/0,
11 | whoami/1]).
12 |
13 | -import(proplists, [get_value/2,
14 | get_value/3]).
15 |
16 | -import(utils, [concat3/3,
17 | concat4/4,
18 | incr/1]).
19 |
20 | secret_handshake(Host) ->
21 | {ok, NewSbotClient} = ssb_peer:start_link(Host, remote_long_pk()),
22 | NewSbotClient.
23 |
24 | remote_long_pk() ->
25 | base64:decode(keys:pub_key()).
26 |
27 |
28 | smoke() ->
29 | NewClient = secret_handshake("localhost"),
30 | ssb_peer:send(NewClient, utils:ping_req()).
31 |
32 | whoami(Peer) ->
33 | NewClient = secret_handshake(Peer),
34 | ssb_peer:send(NewClient, utils:whoami_req()).
35 |
36 | %% This function is kind of a joke performance-wise :)
37 | largest_feed() ->
38 | %%this is silly. all_auths returns duplicates in a list
39 | Auths = sets:to_list(sets:from_list(mess_auth:all_auths())),
40 | NoAuths = length(Auths),
41 | check_feeds(Auths, 1, NoAuths, {<<"feeds">>,0}).
42 |
43 | check_feeds(_Auths, N, NoAuths, Max) when N == NoAuths ->
44 | Max;
45 | check_feeds(Auths, N, NoAuths, Max) ->
46 | {_Feed, Seq} = Max,
47 | Id = lists:nth(N, Auths),
48 | Pid = utils:find_or_create_feed_pid(Id),
49 | Mess = ssb_feed:fetch_last_msg(Pid),
50 | case Mess of
51 | done ->
52 | check_feeds(Auths, N + 1, NoAuths, Max);
53 | _Else ->
54 | #message{sequence = NewSeq} = Mess,
55 | NewMax = case Seq > NewSeq of
56 | true ->
57 | Max;
58 | false ->
59 | {Id, NewSeq}
60 | end,
61 | check_feeds(Auths, N + 1, NoAuths, NewMax)
62 | end.
63 |
--------------------------------------------------------------------------------
/apps/ssb/src/ssb.app.src:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | {application, ssb,
5 | [{description, "ssb"},
6 | {vsn, {cmd, "echo 0.1-`git describe --always --tags`"}},
7 | {registered, []},
8 | {applications, [kernel,
9 | sasl,
10 | stdlib,
11 | crypto,
12 | observer,
13 | wx,
14 | ranch,
15 | enacl,
16 | compiler,
17 | debugger,
18 | syntax_tools,
19 | tools]},
20 | {env, []},
21 | {mod, {ssb_app, [{ssb_log_level, notice}]}}]}.
22 |
--------------------------------------------------------------------------------
/apps/ssb/src/ssb_app.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(ssb_app).
5 | -behaviour(application).
6 |
7 | %% Application callbacks
8 | -export([start/2, stop/1]).
9 |
10 | -include("ssb.hrl").
11 |
12 | -ifdef(TEST).
13 | -include_lib("eunit/include/eunit.hrl").
14 | -endif.
15 | %% ===================================================================
16 | %% Application callbacks
17 | %% ===================================================================
18 | start(_StartType, _StartArgs) ->
19 | LogLevel = application:get_env(ssb, ssb_log_level, notice),
20 | logger:set_primary_config(level, LogLevel),
21 | logger:set_module_level(supervisor, error),
22 | ?LOG(LogLevel, "Log level ~p set from env ~n", [LogLevel]),
23 |
24 | {ok, _} = ranch:start_listener(erlbutt_listener, 5,
25 | ranch_tcp, [{port, 8008},
26 | {max_connections, 10}],
27 | ssb_peer, []),
28 |
29 | ssb_sup:start_link().
30 |
31 | stop(_State) ->
32 | ok.
33 |
34 |
35 | -ifdef(TEST).
36 |
37 | simple_test() ->
38 | application:ensure_all_started(ssb),
39 | ?assertNot(undefined == whereis(ssb_sup)),
40 | application:stop(ssb).
41 |
42 | -endif.
43 |
--------------------------------------------------------------------------------
/apps/ssb/src/ssb_feed.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(ssb_feed).
5 |
6 | -ifdef(TEST).
7 | -include_lib("eunit/include/eunit.hrl").
8 | -endif.
9 |
10 | -include("ssb.hrl").
11 |
12 | -behaviour(gen_server).
13 |
14 | %% API
15 | -export([start_link/1]).
16 |
17 | -export([whoami/1,
18 | post_content/2,
19 | store_msg/2,
20 | fetch_msg/2,
21 | fetch_last_msg/1,
22 | store_ref/2,
23 | references/3,
24 | foldl/3]).
25 |
26 | %% gen_server callbacks
27 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2,
28 | terminate/2, code_change/3]).
29 |
30 | -import(utils, [load_term/1]).
31 |
32 | -define(SERVER, ?MODULE).
33 |
34 | -record(state, {id,
35 | last_msg = null,
36 | last_seq = 0,
37 | feed,
38 | profile,
39 | refs,
40 | msg_cache}).
41 | %%%===================================================================
42 | %%% API
43 | %%%===================================================================
44 |
45 | start_link(FeedId) ->
46 | gen_server:start_link(?MODULE, [FeedId], []).
47 |
48 | whoami(FeedPid) ->
49 | gen_server:call(FeedPid, whoami).
50 |
51 | post_content(FeedPid, Content) ->
52 | gen_server:call(FeedPid, {post, Content}, infinity).
53 |
54 | store_msg(FeedPid, Msg) ->
55 | gen_server:call(FeedPid, {store, Msg}, infinity).
56 |
57 | fetch_msg(FeedPid, Key) ->
58 | gen_server:call(FeedPid, {fetch, Key}).
59 |
60 | fetch_last_msg(FeedPid) ->
61 | gen_server:call(FeedPid, {fetch_last_msg}).
62 |
63 | store_ref(FeedPid, Arrow) ->
64 | gen_server:call(FeedPid, {store_ref, Arrow}, infinity).
65 |
66 | references(FeedPid, MsgId, RootId) ->
67 | gen_server:call(FeedPid, {refs, MsgId, RootId}, infinity).
68 |
69 | foldl(FeedPid, Fun, Acc) ->
70 | gen_server:call(FeedPid, {foldl, Fun, Acc}, infinity).
71 |
72 |
73 | %%%===================================================================
74 | %%% gen_server callbacks
75 | %%%===================================================================
76 | init([FeedId]) ->
77 | process_flag(trap_exit, true),
78 | DecodeId = utils:decode_id(FeedId),
79 | {Feed, Profile, Refs} = init_directories(DecodeId),
80 | State = #state{id = FeedId,
81 | feed = Feed,
82 | profile = Profile,
83 | refs = Refs,
84 | msg_cache = ets:new(messages, [])},
85 | {ok, check_owner_feed(State)}.
86 |
87 | handle_call(whoami, _From, #state{id = Id} = State) ->
88 | {reply, Id, State};
89 |
90 | handle_call({post, Content}, _From, #state{id = Id} = State) ->
91 | %% A given peer can only post to the feed it owns
92 | CanPost = Id == keys:pub_key_disp(),
93 | if CanPost ->
94 | NewState = post(Content, State),
95 | {reply, ok, NewState};
96 | true ->
97 | {reply, no_post, State}
98 | end;
99 |
100 | handle_call({store, Msg}, _From, State) ->
101 | NewState = store(Msg, State),
102 | {reply, ok, NewState};
103 |
104 | handle_call({store_ref, Arrow}, _From, #state{refs = Refs} = State) ->
105 | write_msg(Arrow, Refs),
106 | {reply, ok, State};
107 |
108 | handle_call({fetch, Key}, _From, #state{feed = Feed,
109 | msg_cache = Messages} = State) ->
110 | Val = ets:lookup(Messages, Key),
111 | {Pos, Msg} = feed_get(Feed, Val, Key),
112 | case Val of
113 | [] ->
114 | ets:insert(Messages, {Key, Pos});
115 | _Else ->
116 | nop
117 | end,
118 | {reply, message:decode(Msg, false), State};
119 |
120 | handle_call({fetch_last_msg}, _From, #state{feed = Feed,
121 | msg_cache = Messages} = State) ->
122 | Resp = feed_get_last(Feed),
123 | case Resp of
124 | {Pos, Msg, Key} ->
125 | ets:insert(Messages, {Key, Pos}),
126 | {reply, message:decode(Msg, false), State};
127 | Else ->
128 | {reply, Else, State}
129 | end;
130 |
131 | handle_call({refs, MsgId, TangleId}, _From, #state{refs = Refs} = State) ->
132 | Fun =
133 | fun(Data, Acc) ->
134 | IsArc = has_target(Data, MsgId, TangleId),
135 | case IsArc of
136 | false ->
137 | Acc;
138 | Targets ->
139 | [Targets | Acc]
140 | end end,
141 |
142 | Result =
143 | case file:open(Refs, [read, binary]) of
144 | {ok, IoDev} ->
145 | int_foldr(Fun, [], IoDev);
146 | {error, enoent} ->
147 | ?LOG_INFO("Ill formed tangle arcs file ~n",[]),
148 | done
149 | end,
150 | {reply, Result, State};
151 |
152 | handle_call({foldl, Fun, Acc}, _From, #state{feed = Feed} = State) ->
153 | Result =
154 | case file:open(Feed, [read, binary]) of
155 | {ok, IoDev} ->
156 | int_foldr(Fun, Acc, IoDev);
157 | {error, enoent} ->
158 | ?LOG_INFO("Ill formed feed ~p ~n",[Feed]),
159 | Acc
160 | end,
161 |
162 | {reply, Result, State}.
163 |
164 | handle_cast(_Request, State) ->
165 | {noreply, State}.
166 |
167 | %% info
168 |
169 | handle_info(Info, State) ->
170 | ?LOG_INFO("WTF: ~p ~n",[Info]),
171 | {noreply, State}.
172 |
173 | %%
174 |
175 | terminate(Reason, _State) ->
176 | ?LOG_INFO("Closed gen_server: ~p ~n",[Reason]),
177 | ok.
178 |
179 | code_change(_OldVsn, State, _Extra) ->
180 | {ok, State}.
181 |
182 | %%%===================================================================
183 | %%% Internal functions
184 | %%%===================================================================
185 |
186 | post(Content, #state{id = FeedId, last_msg = Prev,
187 | last_seq = Seq} = State) ->
188 | #message{id = Id} = Msg =
189 | message:new_msg(Prev, Seq + 1, Content,
190 | {FeedId, keys:priv_key()}),
191 | NewState = store(Msg, State),
192 | NewState#state{last_msg = Id, last_seq = Seq + 1}.
193 |
194 | store(#message{id = Id, author = Auth} = Msg,
195 | #state{feed = Feed,
196 | profile = Profile} = State) ->
197 | mess_auth:put(Id, Auth),
198 | write_msg(Msg, Feed),
199 | utils:update_refs(Msg),
200 | IsAbout = message:is_about(Msg),
201 | case IsAbout of
202 | true ->
203 | write_msg(Msg, Profile),
204 | State;
205 | _Else ->
206 | State
207 | end.
208 |
209 | write_msg(#message{} = DecMsg, Store) ->
210 | Msg = message:encode(DecMsg),
211 | write_msg(Msg, Store);
212 |
213 | write_msg(Msg, Store) ->
214 | DataSiz = size(Msg),
215 | O = open_file(Store),
216 | ok = file:write(O,
217 | <>),
218 | FileSize = filelib:file_size(Store) + 4,
219 | ok = file:write(O, <>),
220 | close_file(O).
221 |
222 | init_directories(AuthDir) ->
223 | Location = config:feed_store_loc(),
224 | %% Author is already decoded as hex, use first two chars for directory
225 | <> = AuthDir,
226 | FeedDir = <>/binary,RestAuth/binary>>,
227 | Feed = <>/binary,<<"log.offset">>/binary>>,
228 | Profile = <>/binary,<<"profile">>/binary>>,
229 | Refs = <>/binary,<<"references">>/binary>>,
230 | filelib:ensure_dir(Feed),
231 | filelib:ensure_dir(Profile),
232 | filelib:ensure_dir(Refs),
233 | {Feed, Profile, Refs}.
234 |
235 | %% Only feed corresponding to the owner of the peer can post.
236 | %% All the other feeds are only meant to be read
237 | check_owner_feed(#state{id = FeedId, feed = Feed,
238 | msg_cache = Messages} = State) ->
239 | IsOwner = FeedId == keys:pub_key_disp(),
240 | if IsOwner ->
241 | Resp = feed_get_last(Feed),
242 | case Resp of
243 | no_file ->
244 | State;
245 | done ->
246 | State;
247 | {Pos, Msg, Key} ->
248 | ets:insert(Messages, {Key, Pos}),
249 | #message{sequence = Seq} = message:decode(Msg, true),
250 | State#state{last_msg = Key,
251 | last_seq = Seq}
252 | end;
253 | true ->
254 | State
255 | end.
256 |
257 | feed_get(Feed, [], Key) ->
258 | feed_get(Feed, [{Key, 0}], Key);
259 |
260 | feed_get(Feed, [{Key, Pos}], Key) ->
261 | case file:open(Feed, [read, binary]) of
262 | {ok, IoDev} ->
263 | file:position(IoDev, Pos),
264 | scan(IoDev, Pos, Key);
265 | {error, enoent} ->
266 | ?LOG_INFO("Probably bad input ~n",[]),
267 | done
268 | end.
269 |
270 | feed_get_last(Feed) ->
271 | case filelib:is_file(Feed) of
272 | true ->
273 | case file:open(Feed, [read, binary]) of
274 | {ok, IoDev} ->
275 | Beg = filelib:file_size(Feed) - 8,
276 | file:position(IoDev, Beg),
277 | case file:read(IoDev, 4) of
278 | {ok, <>} ->
279 | file:position(IoDev, Beg - (TermLenInt + 4)),
280 | {ok, Data} = load_term(IoDev),
281 | file:close(IoDev),
282 | Key = extract_key(Data),
283 | {Beg - (TermLenInt + 4), Data, Key};
284 | _Else ->
285 | file:close(IoDev),
286 | done
287 | end;
288 | {error, Error} ->
289 | ?LOG_INFO("Probably bad input ~p ~n",[{Error, Feed}]),
290 | done
291 | end;
292 | false ->
293 | no_file
294 | end.
295 |
296 | extract_key(Data) ->
297 | {DataProps} = utils:nat_decode(Data),
298 | ?pgv(<<"key">>, DataProps).
299 |
300 | scan(IoDev, Pos, Key) ->
301 | case load_term(IoDev) of
302 | {ok, Data} ->
303 | KeyVal = extract_key(Data),
304 | if KeyVal == Key ->
305 | {Pos, Data};
306 | true ->
307 | {ok, <>} = file:read(IoDev, 4),
308 | scan(IoDev, NextPos, Key)
309 | end;
310 | {error, eof} ->
311 | ?LOG_INFO("Key not found: ~p ~n",[Key]),
312 | not_found;
313 | {error, Error} ->
314 | ?LOG_INFO("Error ~p scanning for key: ~p ~n",[Error, Key])
315 | end.
316 |
317 | int_foldr(Fun, Acc, IoDev) ->
318 | case load_term(IoDev) of
319 | {ok, Data} ->
320 | file:read(IoDev, 4),
321 | int_foldr(Fun, Fun(Data, Acc), IoDev);
322 | {error, _Error} ->
323 | file:close(IoDev),
324 | Acc
325 | end.
326 |
327 | has_target(Msg, Id, RootId) ->
328 | {DecProps} = utils:nat_decode(Msg),
329 | Root = ?pgv(<<"root">>, DecProps),
330 | IsRootId = RootId == Root,
331 | [Src, _AuthId] = ?pgv(<<"src">>, DecProps),
332 | case IsRootId of
333 | true ->
334 | if Src == Id ->
335 | ?pgv(<<"tar">>, DecProps);
336 | true ->
337 | false
338 | end;
339 | false ->
340 | false
341 | end.
342 |
343 | open_file(File) ->
344 | Open = file:open(File, [append, sync]),
345 | case Open of
346 | {ok, F} ->
347 | F;
348 | Else ->
349 | ?LOG_INFO("Tried to open failed: ~p ~n",[Else]),
350 | nil
351 | end.
352 |
353 | close_file(File) ->
354 | ok = file:close(File).
355 |
356 | -ifdef(TEST).
357 | instance_feed_test() ->
358 | keys:start_link(),
359 | config:start_link("test/ssb.cfg"),
360 | mess_auth:start_link(),
361 | {ok, F1} = ssb_feed:start_link(keys:pub_key_disp()),
362 | ok = ssb_feed:post_content(F1, <<"foo">>).
363 | -endif.
364 |
--------------------------------------------------------------------------------
/apps/ssb/src/ssb_peer.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(ssb_peer).
5 |
6 | -behaviour(gen_server).
7 | -behaviour(ranch_protocol).
8 |
9 | -include("ssb.hrl").
10 |
11 | -export([start_link/2,
12 | start_link/4,
13 | send/2]).
14 |
15 | %% gen_server exports
16 | -export([init/1, handle_call/3, handle_cast/2,
17 | handle_info/2, terminate/2,
18 | code_change/3]).
19 |
20 | -import(utils, [concat/1,
21 | combine/2,
22 | send_data/4]).
23 |
24 | %% connect to another peer, acting as a client.
25 | start_link(Ip, PubKey) ->
26 | gen_server:start_link(?MODULE, [Ip, PubKey], []).
27 |
28 | send(Pid, Data) ->
29 | gen_server:cast(Pid, {send, Data}).
30 |
31 | %% accept a connection from another peer, acting as a server.
32 | start_link(Ref, Socket, Transport, Opts) ->
33 | gen_server:start_link(?MODULE, [Ref, Socket, Transport, Opts], []).
34 |
35 | init([Ip, PubKey]) ->
36 | process_flag(trap_exit, true),
37 | try
38 | {ok, {Socket, DecBoxKey, DecNonce, EncBoxKey, EncNonce}} =
39 | shs:client_shake_hands(connect(Ip, 8008), PubKey),
40 | ranch_tcp:setopts(Socket, [{active, false}]),
41 | {ok, #sbox_state{socket = Socket,
42 | transport = ranch_tcp,
43 | dec_sbox_key = DecBoxKey,
44 | enc_sbox_key = EncBoxKey,
45 | dec_nonce = DecNonce,
46 | enc_nonce = EncNonce,
47 | shook_hands = 1}}
48 | catch
49 | error:Reason ->
50 | {stop, Reason}
51 | end;
52 |
53 | init([Ref, Socket, Transport, _Opts = []]) ->
54 | %% note the return of a 0 timeout, this is required to notify
55 | %% ranch that it owns the socket, and start_link doesn't return
56 | %% until init does.
57 | {ok, #sbox_state{ref = Ref,
58 | socket = Socket,
59 | transport = Transport}, 0}.
60 |
61 | handle_info({tcp, Socket, Data},
62 | #sbox_state{socket=Socket,
63 | transport=Transport,
64 | shook_hands = 0} = State) ->
65 | try
66 | {ok, {DecBoxKey, DecNonce, EncBoxKey, EncNonce}}
67 | = shs:server_shake_hands(Data, Socket, Transport),
68 | Transport:setopts(Socket, [{active, once}]),
69 | {noreply, State#sbox_state{ dec_sbox_key = DecBoxKey,
70 | enc_sbox_key = EncBoxKey,
71 | dec_nonce = DecNonce,
72 | enc_nonce = EncNonce,
73 | shook_hands = 1}}
74 | catch
75 | error:Reason ->
76 | ?LOG_ERROR("Unable to shake hands with stranger ~p ~n",
77 | [Reason]),
78 | {stop, Reason}
79 | end;
80 |
81 | %% This function is called after the handshake is complete
82 | %% and we can begin to process secret box messages
83 | handle_info({tcp, Socket, Data},
84 | #sbox_state{socket=Socket,
85 | transport=Transport,
86 | box_rem_bytes = BoxLeftOver} = State) ->
87 |
88 | % combine new data with left overs from previous packets
89 | BoxData = combine(BoxLeftOver, Data),
90 |
91 | {Done, NewState} = unbox_and_parse(BoxData, State),
92 |
93 |
94 | case Done of
95 | done ->
96 | stop(done, NewState);
97 | _Else ->
98 | ?LOG_DEBUG("Are we complete and need to wait? ~p ~n",[Done]),
99 | Transport:setopts(Socket, [{active, once}]),
100 | {noreply, NewState}
101 | end;
102 |
103 | handle_info({tcp_closed, _Socket}, State) ->
104 | network_error(normal, State);
105 |
106 | handle_info({tcp_error, _, Reason}, State) ->
107 | network_error(Reason, State);
108 |
109 | handle_info(timeout, #sbox_state{ref = Ref,
110 | socket = Socket,
111 | transport = Transport} = State) ->
112 | %% notify ranch that it owns the socket
113 | ok = ranch:accept_ack(Ref),
114 | ok = Transport:setopts(Socket, [{active, once}]),
115 | {noreply, State};
116 |
117 | handle_info(Info, State) ->
118 | ?LOG_INFO("Stopped presumably for normal reason: ~p ~n",[Info]),
119 | {stop, normal, State}.
120 |
121 | handle_call(_Request, _From, State) ->
122 | {reply, ok, State}.
123 |
124 |
125 | handle_cast({send, Data}, #sbox_state{socket = Socket,
126 | transport = Transport,
127 | enc_sbox_key = EncBoxKey,
128 | dec_nonce = _ServerNonce,
129 | enc_nonce = EncNonce} = State) ->
130 | NewEncNonce = send_data(Data, Socket, EncNonce, EncBoxKey),
131 | Transport:setopts(Socket, [{active, once}]),
132 | {noreply, State#sbox_state{enc_nonce = NewEncNonce}};
133 |
134 | handle_cast(_Msg, State) ->
135 | {noreply, State}.
136 |
137 | terminate(_Reason, _State) ->
138 | ok.
139 |
140 | code_change(_OldVsn, State, _Extra) ->
141 | {ok, State}.
142 |
143 | %%%===================================================================
144 | %%% Internal functions
145 | %%%===================================================================
146 |
147 | unbox_and_parse(BoxData, #sbox_state{dec_sbox_key = DecBoxKey,
148 | dec_nonce = DecNonce,
149 | rpc_rem_bytes = RpcLeftOver} = State) ->
150 | {Status, Msg, NewDecNonce, NewBoxLeftOver} =
151 | boxstream:unbox(DecBoxKey, DecNonce,
152 | BoxData),
153 |
154 | NewState = State#sbox_state{dec_nonce = NewDecNonce,
155 | box_rem_bytes = NewBoxLeftOver},
156 |
157 | case Status of
158 | partial ->
159 | {partial, NewState};
160 | complete ->
161 | Done = Msg == ?BOX_END,
162 | case Done of
163 | true ->
164 | ?LOG_DEBUG("Box end received ~p ~n",[Msg]),
165 | {done, NewState};
166 | false ->
167 | %% now parse rpc
168 | NewState2 = rpc_parse(combine(RpcLeftOver, Msg), NewState),
169 | if (size(NewBoxLeftOver) > 34) ->
170 | unbox_and_parse(NewBoxLeftOver, NewState2);
171 | true ->
172 | {complete, NewState2}
173 | end
174 | end
175 | end.
176 |
177 | rpc_parse(Data, #sbox_state{socket = Socket,
178 | enc_nonce = EncNonce,
179 | enc_sbox_key = EncBoxKey,
180 | response = Response} = State) ->
181 |
182 | %% Should append Msg to rpc_rem_bytes from previous call?
183 | Parsed = rpc_parse:parse(Data),
184 | {Status, NewRpcLeftOver, NewEncNonce, NewResponse} =
185 | case Parsed of
186 | {partial, nil, Rest} ->
187 | % if partial parse then Rest is the original input
188 | {partial, Rest, EncNonce, Response};
189 | {complete, ?RPC_END, <<>>} ->
190 | {complete, <<>>, EncNonce, Response};
191 | {complete, {Header, Body}, Rest} ->
192 | %% Need to track request here somehow
193 | {ProcEncNonce, Resp} =
194 | rpc_processor:process({Header, Body},
195 | #ssb_conn{
196 | socket = Socket,
197 | nonce = EncNonce,
198 | secret_box = EncBoxKey}),
199 | ?LOG_DEBUG("The rpc call returned ~p ~n",[Resp]),
200 | {complete, Rest, ProcEncNonce, Resp}
201 | end,
202 |
203 | NewState = State#sbox_state{enc_nonce = NewEncNonce,
204 | rpc_rem_bytes = NewRpcLeftOver,
205 | response = NewResponse},
206 | if (size(NewRpcLeftOver) >= 9 andalso (Status == complete)) ->
207 | %% parse some more
208 | rpc_parse(NewRpcLeftOver, NewState#sbox_state{
209 | rpc_rem_bytes = <<>>});
210 | true ->
211 | NewState
212 | end.
213 |
214 | network_error(Reason, State) ->
215 | ?LOG_ERROR("Network error ~p ~n",[Reason]),
216 | stop({shutdown, conn_closed}, State).
217 |
218 | stop(Reason, State) ->
219 | {stop, Reason, State}.
220 |
221 | connect(Host, Port) ->
222 | {ok, Socket} =
223 | gen_tcp:connect(Host, Port,
224 | [binary,
225 | {reuseaddr, true},
226 | {active, false},
227 | {packet, raw}
228 | ],
229 | 5000),
230 | Socket.
231 |
--------------------------------------------------------------------------------
/apps/ssb/src/ssb_sup.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(ssb_sup).
5 |
6 | -behaviour(supervisor).
7 |
8 | -include("ssb.hrl").
9 |
10 | %% API
11 | -export([start_link/0]).
12 |
13 | %% Supervisor callbacks
14 | -export([init/1]).
15 |
16 | %% ===================================================================
17 | %% API functions
18 | %% ===================================================================
19 | start_link() ->
20 | supervisor:start_link({local, ?MODULE}, ?MODULE, []).
21 |
22 | %% ===================================================================
23 | %% Supervisor callbacks
24 | %% ===================================================================
25 | init([]) ->
26 | {ok, { {one_for_one, 5, 10},
27 | [?CHILD(heartbeat, worker),
28 | ?CHILD(config, worker),
29 | ?CHILD(keys, worker),
30 | ?CHILD(mess_auth, worker)]}}.
31 |
--------------------------------------------------------------------------------
/apps/ssb/src/tangle.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(tangle).
5 |
6 | -ifdef(TEST).
7 | -include_lib("eunit/include/eunit.hrl").
8 | -endif.
9 |
10 | -include("ssb.hrl").
11 |
12 | -export([get_tangle/1,
13 | parents/2,
14 | ancestors/2,
15 | children/2,
16 | descendants/2,
17 | get_msgs/1
18 | ]).
19 |
20 | get_tangle(TangleId) ->
21 | %% retrieve tangle root author
22 | Auth = mess_auth:get(TangleId),
23 | FeedPid = utils:find_or_create_feed_pid(Auth),
24 | Targets = ssb_feed:references(FeedPid, TangleId, TangleId),
25 | Fun = fun([M, A]) ->
26 | find_paths(M, A, TangleId)
27 | end,
28 | {TangleId, Auth, lists:map(Fun, Targets)}.
29 |
30 | get_msgs({TangleId, Auth, Nodes}) ->
31 | [get_msg(TangleId, Auth) | get_msgs1(Nodes, [])].
32 |
33 | get_msgs1(Nodes, Msgs) ->
34 | Fun = fun({Id, Auth, Rest}) ->
35 | get_msgs1(Rest, [get_msg(Id, Auth) | Msgs]);
36 | ({Id, Auth}) ->
37 | lists:reverse([get_msg(Id, Auth) | Msgs])
38 | end,
39 | TmpRes = lists:flatten(lists:map(Fun, Nodes)),
40 | lists:reverse(lists:foldl(fun(E, Acc) ->
41 | case lists:member(E, Acc) of
42 | true ->
43 | Acc;
44 | _Else ->
45 | [E | Acc]
46 | end end, [], TmpRes)).
47 |
48 | get_msg(Id, Auth) ->
49 | Feed = utils:find_or_create_feed_pid(Auth),
50 | Msg = ssb_feed:fetch_msg(Feed, Id),
51 | {Content} = Msg#message.content,
52 | ?pgv(<<"text">>, Content).
53 |
54 | children(MsgId, TangleId) ->
55 | %% retrieve tangle root author
56 | Auth = mess_auth:get(MsgId),
57 | FeedPid = utils:find_or_create_feed_pid(Auth),
58 | {MsgId, ssb_feed:references(FeedPid, MsgId, TangleId)}.
59 |
60 | descendants(MsgId, TangleId) ->
61 | %% retrieve tangle root author
62 | Auth = mess_auth:get(MsgId),
63 | FeedPid = utils:find_or_create_feed_pid(Auth),
64 | Targets = ssb_feed:references(FeedPid, MsgId, TangleId),
65 | Fun = fun([M, A]) ->
66 | find_paths(M, A, TangleId)
67 | end,
68 | {MsgId, lists:map(Fun, Targets)}.
69 |
70 | parents(MsgId, TangleId) ->
71 | %% retrieve message author
72 | Auth = mess_auth:get(MsgId),
73 | FeedPid = utils:find_or_create_feed_pid(Auth),
74 | Msg = ssb_feed:fetch_msg(FeedPid, MsgId),
75 | Branches = message:is_branch(Msg),
76 | case Branches of
77 | false ->
78 | none;
79 | {TangleId, BranchList} ->
80 | {MsgId, lists:map(fun(P) -> [P, mess_auth:get(P)] end,
81 | BranchList)};
82 | _Else ->
83 | none
84 | end.
85 |
86 | ancestors(MsgId, TangleId) ->
87 | %% retrieve message author
88 | Auth = mess_auth:get(MsgId),
89 | FeedPid = utils:find_or_create_feed_pid(Auth),
90 | Msg = ssb_feed:fetch_msg(FeedPid, MsgId),
91 | Branches = message:is_branch(Msg),
92 | case Branches of
93 | false ->
94 | none;
95 | {TangleId, BranchList} ->
96 | {MsgId, lists:map(fun(P) -> find_par_paths(P, mess_auth:get(P), TangleId) end,
97 | BranchList)};
98 | _Else ->
99 | none
100 | end.
101 |
102 | %%%===================================================================
103 | %%% Internal functions
104 | %%%===================================================================
105 |
106 | find_paths(MsgId, AuthId, RootId) ->
107 | Pid = utils:find_or_create_feed_pid(AuthId),
108 | Targets = ssb_feed:references(Pid, MsgId, RootId),
109 | Fun = fun([M, A]) ->
110 | find_paths(M, A, RootId)
111 | end,
112 | case Targets of
113 | [] ->
114 | {MsgId, AuthId};
115 | done ->
116 | {MsgId, AuthId};
117 | _Else ->
118 | {MsgId, AuthId, lists:map(Fun, Targets)}
119 | end.
120 |
121 | find_par_paths(MsgId, AuthId, RootId) ->
122 | Pid = utils:find_or_create_feed_pid(AuthId),
123 | Msg = ssb_feed:fetch_msg(Pid, MsgId),
124 | Branches = message:is_branch(Msg),
125 | case Branches of
126 | false ->
127 | {MsgId, AuthId};
128 | {RootId, BranchList} ->
129 | {MsgId, AuthId,
130 | lists:map(fun(P) ->
131 | find_par_paths(P, mess_auth:get(P),
132 | RootId) end,
133 | BranchList)};
134 | _Else ->
135 | {MsgId, AuthId}
136 | end.
137 |
138 | -ifdef(TEST).
139 |
140 | basic_test() ->
141 | {Auth, Priv, Feed} = init(),
142 | #message{id = Id} = make_msg_one(Auth, Priv, Feed),
143 | #message{content = {Content}} = ssb_feed:fetch_msg(Feed, Id),
144 | ?assert(<<"bar">> == ?pgv(<<"foo">>, Content)).
145 |
146 | tangle1_test() ->
147 | {Auth, Priv, Feed} = init(),
148 | #message{id = Id} = make_msg_one(Auth, Priv, Feed),
149 | #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed),
150 |
151 |
152 | ?assert({Id, Auth, [{Id2, Auth}]} == tangle:get_tangle(Id)).
153 |
154 | tangle2_test() ->
155 | {Auth, Priv, Feed} = init(),
156 | #message{id = Id} = make_msg_one(Auth, Priv, Feed),
157 | #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed),
158 | #message{id = Id3} = make_msg(3, Id2, Id, Id2, Auth, Priv, Feed),
159 |
160 | ?assert({Id, Auth, [{Id2, Auth,
161 | [{Id3, Auth}]}]} == tangle:get_tangle(Id)).
162 |
163 | tangle3_test() ->
164 | {Auth, Priv, Feed} = init(),
165 | #message{id = Id} = make_msg_one(Auth, Priv, Feed),
166 | #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed),
167 | #message{id = Id3} = make_msg(3, Id2, Id, Id2, Auth, Priv, Feed),
168 |
169 | ?assert({Id, Auth, [{Id2, Auth,
170 | [{Id3, Auth}]}]} == tangle:get_tangle(Id)),
171 |
172 | %% Now create another feed
173 | {Auth2, Priv2, Feed2} = create_id(),
174 | #message{id = Id4} = make_msg(4, Id2, Id, Id2, Auth2, Priv2, Feed2),
175 |
176 |
177 | ?assert({Id, Auth, [{Id2, Auth,
178 | [{Id4, Auth2},
179 | {Id3, Auth}]}]} == tangle:get_tangle(Id)).
180 |
181 | tangle4_test() ->
182 | {Auth, Priv, Feed} = init(),
183 | #message{id = Id} = make_msg_one(Auth, Priv, Feed),
184 | #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed),
185 | #message{id = Id3} = make_msg(3, Id2, Id, Id2, Auth, Priv, Feed),
186 |
187 | ?assert({Id, Auth, [{Id2, Auth,
188 | [{Id3, Auth}]}]} == tangle:get_tangle(Id)),
189 |
190 | %% Now create another feed
191 | {Auth2, Priv2, Feed2} = create_id(),
192 | #message{id = Id4} = make_msg(4, Id2, Id, Id2, Auth2, Priv2, Feed2),
193 | #message{id = Id5} = make_msg(5, Id4, Id, [Id4, Id3], Auth2, Priv2, Feed2),
194 |
195 |
196 | ?assert({Id, Auth, [{Id2, Auth,
197 | [{Id4, Auth2, [{Id5, Auth2}]},
198 | {Id3, Auth, [{Id5, Auth2}]}]}]} == tangle:get_tangle(Id)).
199 |
200 | init() ->
201 | keys:start_link(),
202 | config:start_link("test/ssb.cfg"),
203 | mess_auth:start_link(),
204 | create_id().
205 |
206 | create_id() ->
207 | {Pub, Priv} = utils:create_key_pair(),
208 | Auth = utils:display_pub(Pub),
209 | {ok, Feed} = ssb_feed:start_link(Auth),
210 | {Auth, Priv, Feed}.
211 |
212 | make_msg_one(Auth, Priv, Feed) ->
213 | Msg = message:new_msg(nil, 1, {[{<<"foo">>, <<"bar">>}]}, {Auth, Priv}),
214 | ssb_feed:store_msg(Feed, Msg),
215 | Msg.
216 |
217 | make_msg(N, Prev, Root, BranchList, Auth, Priv, Feed) ->
218 | Msg = message:new_msg(Prev, N, {[{<<"type">>, <<"post">>},
219 | {<<"test">>, <<"bar">>},
220 | {<<"root">>, Root},
221 | {<<"branch">>, BranchList}]}, {Auth, Priv}),
222 |
223 | ssb_feed:store_msg(Feed, Msg),
224 | Msg.
225 |
226 | -endif.
227 |
--------------------------------------------------------------------------------
/apps/ssb/src/utils.erl:
--------------------------------------------------------------------------------
1 | %% SPDX-License-Identifier: GPL-2.0-only
2 | %%
3 | %% Copyright (C) 2023 Charles Moid
4 | -module(utils).
5 | -include("ssb.hrl").
6 |
7 | -ifdef(TEST).
8 | -include_lib("eunit/include/eunit.hrl").
9 | -endif.
10 |
11 | -export([create_key_pair/0,
12 | base_64/1,
13 | display_pub/1,
14 | decode_id/1,
15 | encode_rec/1,
16 | concat/1,
17 | incr/1,
18 | combine/2,
19 | send_data/4,
20 | load_term/1,
21 | find_or_create_feed_pid/1,
22 | check_id/1,
23 | update_refs/1,
24 | log/1,
25 | ping_req/0,
26 | whoami_req/0,
27 | error_msg/2,
28 | nat_decode/1]).
29 |
30 | nat_decode(Msg) ->
31 | {Json, _, _} = json:decode(Msg,[], #{object_finish =>
32 | fun(Acc,OldAcc) ->
33 | {{lists:reverse(Acc)}, OldAcc} end}),
34 | Json.
35 |
36 |
37 | create_key_pair() ->
38 | {Pub, Priv} = shs:create_long_pair(),
39 | {?l2b(base_64(Pub)), ?l2b(base_64(Priv))}.
40 |
41 | base_64(Binary) ->
42 | base64:encode_to_string(Binary).
43 |
44 | display_pub(PubKey) ->
45 | ?l2b("@" ++ ?b2l(PubKey) ++ ".ed25519").
46 |
47 | decode_id(FeedId) ->
48 | <<"@",Id/binary>> = FeedId,
49 | RawId = hd(string:replace(Id,".ed25519","")),
50 | integer_to_binary(binary:decode_unsigned(base64:decode(RawId)),16).
51 |
52 | concat(ListOfBins) ->
53 | iolist_to_binary(ListOfBins).
54 |
55 | incr(Nonce) ->
56 | binary:encode_unsigned(binary:decode_unsigned(Nonce) + 1).
57 |
58 | combine(nil, Bin) ->
59 | Bin;
60 |
61 | combine(Bin1, Bin2) ->
62 | Bin1Len = size(Bin1),
63 | <>.
64 |
65 | send_data(Data, Socket, Nonce, SecretBoxKey) ->
66 |
67 | {EncBox, NewNonce} =
68 | boxstream:box(Data, Nonce, SecretBoxKey),
69 |
70 | gen_tcp:send(Socket, EncBox),
71 |
72 | NewNonce.
73 |
74 | load_term(IoDev) ->
75 | case file:read(IoDev, 4) of
76 | {ok, <>} ->
77 | case file:read(IoDev, TermLenInt) of
78 | {ok, TermData} ->
79 | check_data(IoDev, TermData, TermLenInt);
80 | {error, Reason} ->
81 | {error, Reason}
82 | end;
83 | eof ->
84 | {error, eof};
85 | {error, Reason} ->
86 | {error, Reason}
87 | end.
88 |
89 | check_data(IoDev, Data, Len) ->
90 | case file:read(IoDev, 4) of
91 | {ok, TermLen} ->
92 | <> = TermLen,
93 | %% the length of the term is also stored at the end of the term
94 | %% and can be used to check
95 | if TermLenInt == Len ->
96 | {ok, Data};
97 | true ->
98 | {error, data_size_no_match}
99 | end;
100 | {error, Reason} ->
101 | {error, Reason}
102 | end.
103 |
104 | find_or_create_feed_pid(Id) ->
105 | %% ugh, using process dictionary for global state :(
106 | case check_id(Id) of
107 | bad ->
108 | bad;
109 | ok ->
110 |
111 | Val = get(Id),
112 | case Val of
113 | undefined ->
114 | {ok, Pid} = ssb_feed:start_link(Id),
115 | put(Id, Pid),
116 | Pid;
117 | Pid when is_pid(Pid) ->
118 | Alive = is_process_alive(Pid),
119 | if Alive ->
120 | Pid;
121 | true ->
122 | erase(Id),
123 | find_or_create_feed_pid(Id)
124 | end;
125 | _Else ->
126 | erase(Id),
127 | find_or_create_feed_pid(Id)
128 | end
129 | end.
130 |
131 | update_refs(#message{id = Id, author = AuthId} = Msg) ->
132 | Branches = message:is_branch(Msg),
133 | case Branches of
134 | false ->
135 | none;
136 | {Root, BranchList} ->
137 | Target = {<<"tar">>, [Id, AuthId]},
138 | lists:map(fun(Bi) ->
139 | %% this is really ugly, branch most often is either a binary
140 | %% or a list of such, but occasionally it's an
141 | %% object like {<<"0">>:<<"%msgid....">>}
142 | %% this is the price one pays for immutable feeds, garbage
143 | %% lasts forever
144 | Ai = if is_binary(Bi) ->
145 | mess_auth:get(Bi);
146 | true ->
147 | not_found
148 | end,
149 | case Ai of
150 | not_found ->
151 | nop;
152 | _Else ->
153 | Record = {[{<<"root">>, Root},
154 | {<<"src">>, [Bi, Ai]},
155 | Target]},
156 | Pid = find_or_create_feed_pid(Ai),
157 | ssb_feed:store_ref(Pid, encode_rec(Record))
158 | end
159 | end, BranchList)
160 | end.
161 |
162 | encode_rec(Record) ->
163 | iolist_to_binary(message:ssb_encoder(Record, fun message:ssb_encoder/3, [])).
164 |
165 | check_id(<<"@",Id/binary>>) ->
166 | try
167 | case binary:matches(Id,[<<".ed25519">>]) of
168 | [] ->
169 | bad;
170 | _Else ->
171 | RawId = hd(string:replace(Id,".ed25519","")),
172 | integer_to_binary(binary:decode_unsigned(base64:decode(RawId)),16),
173 | ok
174 | end
175 | catch
176 | error:_Reason ->
177 | bad
178 | end;
179 | check_id(_Else) ->
180 | bad.
181 |
182 | ping_req() ->
183 | Flags = rpc_processor:create_flags(1,0,2),
184 | Body = encode_rec({[{<<"name">>,[<<"gossip">>,<<"ping">>]},
185 | {<<"args">>,[{[{<<"timeout">>, 300000}]}]},
186 | {<<"type">>,<<"duplex">>}]}),
187 | Header = rpc_processor:create_header(Flags, size(Body), 1),
188 | utils:combine(Header, Body).
189 |
190 | whoami_req() ->
191 | Flags = rpc_processor:create_flags(1,0,2),
192 | Body = encode_rec({[{<<"name">>,[?whoami]},
193 | {<<"args">>,[]},
194 | {<<"type">>,<<"sync">>}]}),
195 | Header = rpc_processor:create_header(Flags, size(Body), 1),
196 | utils:combine(Header, Body).
197 |
198 | error_msg(Name, Mess) ->
199 | encode_rec({[{<<"name">>, Name},
200 | {<<"message">>, Mess},
201 | {<<"stack">>, <<"_">>}
202 | ]}).
203 |
204 |
205 |
206 |
207 | log({Socket, Data}) ->
208 | ?LOG_DEBUG("received a tcp packet of size: ~p ~n on socket ~p ~n",
209 | [size(Data), Socket]);
210 |
211 | log(Info) ->
212 | ?LOG_DEBUG("received random info message ~p ~n",
213 | [Info]).
214 |
215 | -ifdef(TEST).
216 |
217 | combine_test() ->
218 | <<"foo">> = combine(nil, <<"foo">>),
219 | <<"foobar">> = combine(<<"foo">>,<<"bar">>).
220 |
221 | create_pid_test() ->
222 | erase(),
223 | config:start_link("test/ssb.cfg"),
224 | {Pub, _Priv} = create_key_pair(),
225 | FeedId1 = display_pub(Pub),
226 | find_or_create_feed_pid(FeedId1),
227 | {Pub2, _Priv2} = create_key_pair(),
228 | FeedId2 = display_pub(Pub2),
229 | find_or_create_feed_pid(FeedId2),
230 | ?assert(length(get()) == 2).
231 |
232 | create_pid_kill_test() ->
233 | erase(),
234 | config:start_link("test/ssb.cfg"),
235 | {Pub, _Priv} = create_key_pair(),
236 | FeedId1 = display_pub(Pub),
237 | find_or_create_feed_pid(FeedId1),
238 | {Pub2, _Priv2} = create_key_pair(),
239 | FeedId2 = display_pub(Pub2),
240 | find_or_create_feed_pid(FeedId2),
241 |
242 | ?assert(length(get()) == 2),
243 | erase(FeedId2),
244 | ?assert(length(get()) == 1),
245 | find_or_create_feed_pid(FeedId2),
246 | ?assert(length(get()) == 2).
247 |
248 |
249 |
250 |
251 |
252 | -endif.
253 |
--------------------------------------------------------------------------------
/archive/erlbutt-01-09-2025.tar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/archive/erlbutt-01-09-2025.tar
--------------------------------------------------------------------------------
/config/default.vars:
--------------------------------------------------------------------------------
1 | {feed_store_location, ".\/feeds\/"}.
2 |
3 | {network_id, "1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYnaR\/s="}.
--------------------------------------------------------------------------------
/config/ssb.cfg:
--------------------------------------------------------------------------------
1 | {feed_store_location, "{{feed_store_location}}"}.
2 |
3 | {network_id, "{{network_id}}"}.
--------------------------------------------------------------------------------
/config/sys.config.src:
--------------------------------------------------------------------------------
1 | [{kernel,
2 | [{logger,
3 | [{handler, default, logger_std_h,
4 | #{level => error,
5 | config => #{type => {file, "log/error.log"}}}},
6 | {handler, term, logger_std_h,
7 | #{formatter => {logger_formatter, #{single_line => true}}}},
8 | {handler, info, logger_std_h,
9 | #{level => info,
10 | config => #{type => {file, "log/info.log"}}}},
11 | {handler, debug, logger_std_h,
12 | #{level => debug,
13 | config => #{type => {file, "log/debug.log"}}}}
14 | ]}]},
15 | {ssb, [{ssb_log_level, ${SSB_LOG_LEVEL:-error}}]}].
16 |
17 |
--------------------------------------------------------------------------------
/config/vm.args.src:
--------------------------------------------------------------------------------
1 | -name erlbutt@localhost
2 | -setcookie erlbutt
3 | -pa /usr/local/lib/erlang/lib/syntax_tools-3.2/ebin/
4 | -pa /usr/local/lib/erlang/lib/tools-4.0/
5 | -pa ${HOME}/code/erlbutt/_build/default/lib/ssb/ebin
6 | -pa ${HOME}/code/erlbutt/_build/test/extras/test
7 | -pa ${HOME}/code/emacs-ext/distel/ebin
8 |
--------------------------------------------------------------------------------
/doc/dev-diary/02-21-2025.md:
--------------------------------------------------------------------------------
1 | ## [erlbutt](https://github.com/cmoid/erlbutt)
2 |
3 | [The Circle Game](https://www.youtube.com/watch?v=V9VoLCO-d6U)
4 |
5 | I recently resurrected an old [pub](%tjsHrezXfUUrO3NZGCeRNKzW+Up2wYE1+3H8BP3Oej4=.sha256) I have running on a thinkpad x230. I wanted to build `ssb-server` with the latest nodejs. I ended up deep down the rabbit hole as the latest node required a GLIBC-2.28, which meant the easiest path was to upgrade LinuxMint to the newest. Computers don't really work.
6 |
7 | Reviewing some old threads, Dominic's initial goal was not social media apps, but rather [decentralized social informational infrastructure](%NMyBuz2py2ZPXdrLuHrAj2WaEmvy6jrzuhMPdYfuxxo=.sha256). Poking around way back led me to earlier [comments on goals](%4JIwdelbMldvVlbNccvfHn8f/Ia6qMfwqCPQZY3pAg8=.sha256):
8 |
9 | > I first reached out to @paul because of his work on grimwire which used local sandboxing to build such a thing with some generic webrtc stuff. I said I’m building a p2p database, but it needs an application layer.
10 |
11 | Following some of those twitter threads revealed [cyphernet](https://github.com/dominictarr/cyphernet), some architectural musings that are pretty much at the core of what would become scuttlebutt's append-only feeds. Having worked with couchdb replication, the simplicity of the `SSB` approach was heavenly, it what piqued my interest.
12 |
13 | Patchwork embeds an `ssb-server`, but not in any useful way in terms of reuse. It just imports, more or less, the same node modules that `ssb-server` does. It's the more or less that kills you. It's clear that the intention was a separation of layers, with a foundational component that could serve multiple apps. What we ended up with was patchwork implementing lots of features based on message types that are now baked in and other clients need to respect.
14 |
15 | But the message format is still fine, maybe the content should be a blob reference as in GabbyGrove. I see 3 things that are worth changing, and can be done in a compatible way I think:
16 |
17 | * archiving the feeds - at some configurable sequence no., the ability to create a new nil post with a pointer to the blob that is the prefix of the feed. Users get the choice if they care to fetch and validate all the way back.
18 |
19 |
20 | * multiple network ids - this is only needed for `SHS` and provides a nice way to support multiple apps on the same machine using the same store. The store will need to handle concurrent writers, etc., .ie. be a real database.
21 |
22 |
23 | * trust net - this one is a larger change. Currently the social graph is used together with a hop count to determing which feeds to replicate. This leads to far too many useless feeds being replicated. I have almost 2M messages in my store and over 30K feeds!! Did anyone ever hear of dunbars number? :) We need to take that into account. Social graphs are highly connected so it's too easy to grow the number of feeds with a hop count. This is where I think some more complicated machinery could be used, involving trust net, to do a better job of minimizing the feeds of interest. Something like a version of appleseed, using different sets of weights for different contexts.
24 |
25 |
26 | All in all I still feel `SSB` unique among the alternatives in being `P2P`. The immutable append only log provides an excellent source of truth, with the end-user only known by a public key. Pubs are great in that they are really just the same as any peer. The only difference is that they are meant to run publicly at some ip and do the little invite/accept dance. They could be quite manageable if they had governance models that control invites rather than letting them be open and grow too large. Even so, with better management of which feeds are replicated, pubs that are large would be less an issue.
27 |
28 | I started adding `EBT` plus request skipping to erlbutt. The protocol doc seems pretty clear, but seems to be missing a bit of what's in the plumtree paper. Fortunately I have an erlang implementation of it that was part of the Basho riak stuff. I think I can reuse some of that.
29 |
30 | Progress is slow, too many other things to do. I spend more time thinking and reading than writing code, but I also think that if `SSB` has a change for longevity we need to take [Elavoie's comment](%N5FS7cUKunidZCHd62cy2OKWsrRGkjLw3QRfYBP7gu4=.sha256) about the economics into account. Open source programming needs to be open above all, but also sustainable and maintainable. This is where companies have the advantage as they can focus resources.
31 |
32 | I'd like erlbutt to be that foundational layer, essentially something like `ssb-server` that supports replication, search, and plugins that allow support for different apps. Erlang is good for this as it scales both up and down. A very small kernel can be packaged in the runtime. I've also been spoiled my whole life with REPLs, BEAM is awesome!
33 |
34 | That's all I know.
35 |
36 | cc: #erlbutt
37 |
38 | ## My Feed Is My Story
39 |
40 | `%sxppsHLguKM5wsu9h+X1Yeym45YVyCQ6wAVgUWc39q4=.sha256`
41 |
--------------------------------------------------------------------------------
/doc/dev-diary/06-26-2024.md:
--------------------------------------------------------------------------------
1 | ## [erlbutt](https://github.com/cmoid/erlbutt)
2 |
3 | I sometimes get obsessed with things, and the `SSB` immutable, append-only, signed log is one of them. I think it's the killer idea at the heart of scuttlebutt. This past year I haven't done much programming, instead I've bounced around a whole bunch of technologies trying to figure out what's next. I mean I even took up vim for a couple of months to see how others live.
4 |
5 | This prototype was started [six years ago](%d5gv/qcOJiI2ow7VWpZ20LJASksEOtP4asjW28nMyvw=.sha256), which has to be a record for my longest side project.
6 |
7 | Following [Cory's suggestion](%cH9X4ERD4yuKSwMFBxRVLVBOGEf2S290kzt1goUJcKk=.sha256), here's a dev-diary update:
8 |
9 | I've got my tools upgraded to the latest erlang OTP27. It took a while to fix Distel, but that's good now and I'd like to see that as a foundation for [maxbutt](https://github.com/cmoid/maxbutt), an emacs client for `SSB`.
10 |
11 | OTP27 introduces a native JSON module, so I've upgraded erlbutt to drop the dependency on Jiffy. [Jiffy](https://github.com/davisp/jiffy) was embedded as a NIF, and is awesome, I had to hack it slightly to accomodate the `SSB` quirky serialization. I still have to do that using the native JSON support, but it has callbacks so that I could write a custom [encode/decode](https://github.com/cmoid/erlbutt/blob/main/apps/ssb/src/message.erl#L213-#L279) function outside the module. I also took the opportunity to drop bitcask, which I was using as a simple key/value store to map messages to authors. Bitcask also works very well, it was built by Justin Sheehy at Basho, good stuff. But they are out of business and it broke in OTP27 so it was easier to just switch to DETS, another native module.
12 |
13 | So now I'm back to zero :), or where I left off, which was fleshing out the various muxrpc call and slogging thru all the undocumented details of the reference implementations. I'm down to two dependencies, [enacl](https://github.com/jlouis/enacl), a simple wrapper for libsodium, and [ranch](https://ninenines.eu), for a socket pool. Ranch is all erlang and well written and supported. You can even buy support for specific releases. 99s really seems to get the open source model.
14 |
15 | ## My Feed Is My Story
16 |
17 | `%suXg/Rrg27+sh7e8b8yemg9hNvnNaHYrcKO8AXA5t8Y=.sha256`
18 |
--------------------------------------------------------------------------------
/doc/project.md:
--------------------------------------------------------------------------------
1 | Project notes
2 | =============
3 | These notes are random thoughts about design I'm having while prototyping. I've been following the scuttlebutt community for 7 years now, and playing with some of the implementation details. Erlbutt wants to be something like an [`ssb-server`][4]. It implements the original core of the scuttlebutt [protocol][7]. At some point this doc will become an overview of the architecture and high level documentation of the code. I say something like an `ssb-server` because though I'd like to use it that way I have quite a different approach with respect to persistence. `ssb-server` is also in my mind a bad name. Peer to peer systems should not have servers and clients. All nodes are `peers` and should act like both clients and servers, so the distinction becomes moot.
4 |
5 | Introduction
6 | -------------
7 |
8 | Scuttlebutt is an interesting protocol. A feed is an immutable append-only log file, identified by a public key, where each message is signed by a private key and references the prior message. This ensures a single source of truth since only one peer can sign messages on a feed. At any time, different peers might have different versions of the same feed that only differ by the length. In other words one can be a prefix of the other.
9 |
10 | Messages are encoded as [json][8] (newer implementations have improved this with various binary formats). Messages have a content object that has a type. Messages of type `follow` form the basis for the social graph that is used to drive the replication process. Feeds follow other feeds more or less. This makes for a simple replication, where one node in the network asks a peer for all messages of a feed beyond the latest sequence number they have.
11 |
12 | It's unfortunate that the social graph definition is in the content part of the message. It seems to be more an application concern. At the system level of connections, feeds and replication, there shouldn't be any awareness of the content. It's hard to say. The social graph drives the replication, once connections to other peers are made. Regardless though, almost anything can be worked around becuase the feeds are immutable, so a collection of feeds will only ever grow and anything needed can be built and maintained incrementally.
13 |
14 |
15 | ----
16 | [0]: https://github.com/rebar/rebar3
17 | [1]: https://viewer.scuttlebot.io/%25pYmFr6d0QwLP%2BYG0VNoo75PP7eYNZ1Y8C2MC9IjF5aw%3D.sha256
18 | [2]: http://localhost:8989/blobs/get/&4DUnrqwI7xxUpP6omK1wiPSco5uLrNa6Ey7lNrXCzCU=.sha256
19 | [3]: https://github.com/cn-uofbasel/ssbdrv/blob/master/doc/tangle.md
20 | [4]: https://github.com/ssbc/ssb-server
21 | [5]: https://cloud.google.com/healthcare/
22 | [6]: https://github.com/flumedb/flumedb
23 | [7]: https://ssbc.github.io/scuttlebutt-protocol-guide/
24 | [8]: https://ssbc.github.io/scuttlebutt-protocol-guide/#message-format
25 |
--------------------------------------------------------------------------------
/doc/research/ByzantineEventualConsistency.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/doc/research/ByzantineEventualConsistency.pdf
--------------------------------------------------------------------------------
/doc/research/acmdl19-295.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/doc/research/acmdl19-295.pdf
--------------------------------------------------------------------------------
/doc/research/dicg20-paper90.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/doc/research/dicg20-paper90.pdf
--------------------------------------------------------------------------------
/doc/research/ebt.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/doc/research/ebt.pdf
--------------------------------------------------------------------------------
/doc/research/itc2008.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/doc/research/itc2008.pdf
--------------------------------------------------------------------------------
/doc/research/shs.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/doc/research/shs.pdf
--------------------------------------------------------------------------------
/doc/research/trustnet-cblgh.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/doc/research/trustnet-cblgh.pdf
--------------------------------------------------------------------------------
/doc/research/urls.md:
--------------------------------------------------------------------------------
1 | ## Some useful SSB threads and URLs
2 | %pYmFr6d0QwLP+YG0VNoo75PP7eYNZ1Y8C2MC9IjF5aw=.sha256 - Dominic on flumedb
3 | %f9pa8FparL/zQNwo+6qG9IBH4nxBfjeGgAAuIqdjtHg=.sha256 - Cryptix comments on EBT
4 | %HqvC29wmrW64/mbsL+6Je4mNwMNazxW9iSBb3Wya70c=.sha256 - Andre's ngi-pointer diary
5 | %+fBXl12aV1wpAdD62RMl1WRhwthDMuAuHH4iNWgB7jA=.sha256 - Mix fork/nested threads
6 | %L3qSfcRwZ1nJliIlzSOfVKf8d1X4guIjCsvrrDi1N3Q=.sha256 - Cel on forks
7 | %/aqqVCh//RuwapyeGHbUOE7OUlCrXF/BoVQUSCGzrrk=.sha256 - list of links on forks from Mikey
8 |
9 | ### This next one is an excellent thread on overall design
10 | %TOqTRFI+wUBLy5f6nDJrYjQcZ9U6GlNbdWGEVH/qy/U=.sha256 - Design patterns from Dom/Mikey
11 |
12 |
13 | https://github.com/ssb-ngi-pointer - NGI pointer repo for project work
14 | https://github.com/AljoschaMeyer/bamboo - Bamboo (partial replication)
15 | https://github.com/ssb-ngi-pointer/rooms2 - Andre's rooms 2.0
16 | %eVPRoYaDZCH/cz4WVYIFeCHzaNFOSEUS5uIv2gNVBW8=.sha256 - Links on URIs from Cel
17 | %1ts45jTyl1H+paGP9iUBa4D1/QX6UqDC+DJfpZ7Fc2U=.sha256 - Cryptix on EBT for NGI work
18 | %LKqAORPSwWHNrEzQGgXRVGzmy8xOej71685p26a6PSg=.sha256 - Andre's comments on moderation/blocks
19 | https://cblgh.org/articles/trustnet.html - Trustnet article by Cblgh
20 | %hW8m7+X5AmRkTDbMPgrnz8GE5BSdvOf6CA498iZENXM=.sha256 - Daan on re-sync
21 | https://github.com/ssb-ngi-pointer/ssb-meta-feed - arj03 meta feeds
22 | https://xlfoundation.com - Mitchell cross licensing foundtion
23 | %vb0PiP6hwU6GCXT0QWlHJAoZ/Al4Vzeo23mS4NHjYpM=.sha256 - Cel on cross licensing
24 | %3E++5IPsLer5UbYCLKkEzPIgp0nAh7AD952XCJ7TlDs=.sha256 - Cryptix development thread
25 | %vb0PiP6hwU6GCXT0QWlHJAoZ/Al4Vzeo23mS4NHjYpM=.sha256 - Licensing thread with Cel
26 | %YttiL9bGNlkqfkqykYZB6kOOGBN+V+Hrc9CqZd6xTPo=.sha256 - ERE thread from Andre
27 | https://github.com/timjrobinson/ssb-db2-examples - ssb-db2 query examples
28 | https://github.com/cn-uofbasel/ssbdrv/blob/master/doc/tangle.md - CFT Tangles
29 | %bbNqd5Zziop6A8m6ibLCrs21qRTUJ7uvfl3E6w0SDDA=.sha256 - cblgh's vision thread
30 | %PeGW29P0olzpQWwhZ7cizuXfrKhRUUv5LlFITeu0ZDs=.sha256 - Andre why stay on SSB
31 | https://www.moderndescartes.com/essays/deep_learning_emr/ - on data silos
32 | http://localhost:8989/blobs/get/&pyKqGIPMMtUMTzhZxt1f/jNmU9lal+0ogvqbmEYLNJI=.sha256?contentType=application%2Fpdf -- scuttlesort
33 |
--------------------------------------------------------------------------------
/jq:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/jq
--------------------------------------------------------------------------------
/rebar.config:
--------------------------------------------------------------------------------
1 | {require_otp_vsn, "R?21"}.
2 |
3 | %% Tell rebar about this directory's structure
4 | {lib_dirs, ["apps", "deps"]}.
5 | {sub_dirs, ["apps/*"]}.
6 |
7 | %% Build a release when compiling
8 | %%{post_hooks,[{compile, "./relx"}]}.
9 |
10 | %% These deps are temporary forks, that needed minor tweaks to make usable,
11 | %% or are not actively maintained
12 | %% TODO: push changes upstream or otherwise resolve
13 | {deps, [
14 | {ranch, "1.2.0", {git, "https://github.com/cmoid/ranch", {branch, "1.2.0"}}},
15 | {enacl, "1.1.1", {git, "https://github.com/cmoid/enacl", {branch, "moid-v1.1.1"}}}
16 | ]}.
17 | {plugins, [rebar3_auto]}.
18 | {relx, [{release, { ssb, {git, short} },
19 | [ssb,
20 | debugger,
21 | runtime_tools]},
22 |
23 | {sys_config_src, "./config/sys.config.src"},
24 | {vm_args_src, "./config/vm.args.src"},
25 |
26 | {extended_start_script, true},
27 |
28 | {overlay_vars, "config/default.vars"},
29 | {overlay, [
30 | {template, "config/ssb.cfg", "ssb.cfg"}
31 | ]}
32 |
33 | ]
34 | }.
35 |
36 | {profiles, [{dev, [{erl_opts, [debug_info]},
37 | {relx, [{dev_mode, true},
38 | {include_erts, false}]}]
39 | },
40 | {prod, [{erl_opts, [no_debug_info, warnings_as_errors]},
41 | {relx, [{dev_mode, false},
42 | {include_erts, true}]}]
43 | }]
44 | }.
45 |
--------------------------------------------------------------------------------
/rebar.lock:
--------------------------------------------------------------------------------
1 | [{<<"enacl">>,
2 | {git,"https://github.com/cmoid/enacl",
3 | {ref,"9b807afd3a177630b235694f1489ba0cbaa9bc92"}},
4 | 0},
5 | {<<"ranch">>,
6 | {git,"https://github.com/cmoid/ranch",
7 | {ref,"cbfed2c3c70f7ef4bef3479e65acc10d08903304"}},
8 | 0}].
9 |
--------------------------------------------------------------------------------
/rebar3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/rebar3
--------------------------------------------------------------------------------
/sbot.escript:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env escript
2 | %%! -noshell -noinput
3 | %% -*- mode: erlang;erlang-indent-level: 4;indent-tabs-mode: nil -*-
4 | %% ex: ft=erlang ts=4 sw=4 et
5 |
6 | -define(INFO(Fmt,Args), io:format(Fmt,Args)).
7 |
8 | main([Host, Command]) ->
9 | code:add_path("./_build/default/lib/ssb/ebin/"),
10 | code:add_path("./_build/default/lib/enacl/ebin/"),
11 | code:add_path("./_build/default/lib/ranch/ebin/"),
12 | logger:set_primary_config(level, error),
13 | keys:start_link(),
14 | config:start_link(),
15 | ?INFO("current working directory is ~p ~n",[file:get_cwd()]),
16 |
17 | %% invoke the command passed as argument
18 | F = fun() ->
19 | NewClient = secret_handshake(Host),
20 | ?INFO("~p~n",[NewClient]),
21 | ?INFO("~s~n",[Command]),
22 | Req = case Command of
23 | "whoami" ->
24 | utils:whoami_req();
25 | "menu" ->
26 | menu_req();
27 | "ping" ->
28 | utils:ping_req()
29 | end,
30 | Resp = ssb_peer:send(NewClient, Req),
31 | ?INFO("~s~n",[Resp])
32 | end,
33 | F();
34 |
35 | main(Args) ->
36 | ?INFO("unknown args: ~p\n", [Args]),
37 | erlang:halt(1).
38 |
39 | secret_handshake(Host) ->
40 | {ok, NewSbotClient} = ssb_peer:start_link(Host, remote_long_pk()),
41 | NewSbotClient.
42 |
43 | %%base64:decode(<<"ceHuIsvTt71cD5IsoXBlqwda8S+W9l5JKb5b89MbTo8=">>)
44 |
45 | %%base64:decode(<<"LrNsx/3v3rBPk1zFkDp3V8mdsNQrcup8iu4FdymtFm0=">>)
46 |
47 | %%base64:decode(<<"bombBa/UwB792ilEh7wXooqBSluIvzrJbrWzZAFhnxw=">>)
48 |
49 | %%base64:decode(<<"aBkmLQLxnsJleW1LyyCrS3DA6a/Wfz57vIK321vRumc=">>)
50 |
51 | %%base64:decode(<<"ceHuIsvTt71cD5IsoXBlqwda8S+W9l5JKb5b89MbTo8=">>)
52 |
53 |
54 | remote_long_pk() ->
55 | base64:decode(keys:pub_key()).
56 |
57 | menu_req() ->
58 | Flags = rpc_processor:create_flags(0,0,2),
59 | Body = iolist_to_binary(json:encode(maps:from_list([{<<"name">>,[<<"manifest">>]},
60 | {<<"args">>,[]},
61 | {<<"type">>,<<"sync">>}]))),
62 | Header = rpc_processor:create_header(Flags, size(Body), 1),
63 | utils:combine(Header, Body).
64 |
--------------------------------------------------------------------------------
/test/erlbutt_basic_SUITE.erl:
--------------------------------------------------------------------------------
1 | -module(erlbutt_basic_SUITE).
2 | -export([
3 | %% suite/0,
4 | init_per_suite/1,
5 | end_per_suite/1,
6 | init_per_testcase/2,
7 | end_per_testcase/2,
8 | all/0
9 | ]).
10 |
11 | -import(proplists, [get_value/2,
12 | get_value/3]).
13 |
14 | -export([connect_test/1,
15 | ping_test/1,
16 | whoami_test/1]).
17 |
18 | -include_lib("common_test/include/ct.hrl").
19 | -include_lib("eunit/include/eunit.hrl").
20 | -include_lib("ssb/include/ssb.hrl").
21 |
22 | %% ===================================================================
23 | %% common_test callbacks
24 | %% ===================================================================
25 | init_per_suite(_Config) ->
26 | cover:start(),
27 | application:ensure_all_started(ssb),
28 | _Config.
29 |
30 | end_per_suite(_Config) ->
31 | _Config.
32 |
33 | init_per_testcase(_Case, _Config) ->
34 | _Config.
35 |
36 | end_per_testcase(_, Config) ->
37 | Config.
38 |
39 | all() ->
40 | [connect_test,
41 | ping_test,
42 | whoami_test].
43 |
44 |
45 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
46 | %%% Actual Tests
47 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
48 | connect_test(Config) ->
49 | Host = get_value(hostname, Config, "localhost"),
50 | {ok, NewSbotPeer} = ssb_peer:start_link(Host, remote_long_pk()),
51 | ?assert(is_process_alive(NewSbotPeer)),
52 | Config.
53 |
54 |
55 | ping_test(Config) ->
56 | Host = get_value(hostname, Config, "localhost"),
57 | {ok, NewSbotPeer} = ssb_peer:start_link(Host, remote_long_pk()),
58 | Now = erlang:system_time(millisecond),
59 | Time = ssb_peer:send(NewSbotPeer, ping()),
60 | End = binary_to_integer(message:nat_decode(Time)),
61 | ?assert((End - Now) < 5),
62 | Config.
63 |
64 | whoami_test(Config) ->
65 | Host = get_value(hostname, Config, "localhost"),
66 | {ok, NewSbotClient} = ssb_peer:start_link(Host, remote_long_pk()),
67 | {WhoAmI} = message:nat_decode(ssb_peer:send(NewSbotClient, whoami_req())),
68 | ?assert(keys:pub_key_disp() == ?pgv(<<"id">>, WhoAmI)),
69 | Config.
70 |
71 |
72 | remote_long_pk() ->
73 | base64:decode(keys:pub_key()).
74 |
75 | ping() ->
76 | Flags = rpc_processor:create_flags(1,0,2),
77 | Body = utils:encode_rec({[{<<"name">>,[<<"gossip">>,<<"ping">>]},
78 | {<<"args">>,[{[{<<"timeout">>, 300000}]}]},
79 | {<<"type">>,<<"duplex">>}]}),
80 | Header = rpc_processor:create_header(Flags, size(Body), 1),
81 | utils:combine(Header, Body).
82 |
83 | whoami_req() ->
84 | Flags = rpc_processor:create_flags(1,0,2),
85 | Body = iolist_to_binary(message:ssb_encoder({[{<<"name">>,[?whoami]},
86 | {<<"args">>,[]},
87 | {<<"type">>,<<"async">>}]}, fun message:ssb_encoder/3, [])),
88 | Header = rpc_processor:create_header(Flags, size(Body), 1),
89 | utils:combine(Header, Body).
90 |
--------------------------------------------------------------------------------
/test/ssb.cfg:
--------------------------------------------------------------------------------
1 | {feed_store_location, "./_build/test/feeds/"}.
2 |
3 | {network_id, "1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYnaR/s="}.
--------------------------------------------------------------------------------
/testdata.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmoid/erlbutt/434737f2cad4258e05a53014aecc739fcacbe266/testdata.zip
--------------------------------------------------------------------------------
/testdata.zip.license:
--------------------------------------------------------------------------------
1 | SPDX-FileCopyrightText: 2021 The Go-SSB Authors
2 |
3 | SPDX-FileCopyrightText: 2021 Dionne Associates, LLC.
4 |
5 | SPDX-License-Identifier: MIT
--------------------------------------------------------------------------------