mirror of
https://github.com/vacp2p/de-mls.git
synced 2026-01-06 20:23:55 -05:00
Update frontend and prepare architecture to multi-steward support (#46)
* start to update ui * remove websocket ui * refactor code after ws removing * update frontend * Unable real consensus result * update proposal ui * add current pending proposal to ui section * Refactor UI and backend for ban request feature - Updated `build.rs` to ensure proper protobuf compilation. - Removed `tracing-subscriber` dependency from `Cargo.toml` and `Cargo.lock`. - Refactored `main.rs` in the desktop UI to improve state management and UI interactions for group chat. - Enhanced `Gateway` and `User` structs to support sending ban requests and processing related events. - Updated UI components to reflect changes in proposal handling and improve user experience during voting and group management. - Added tests for new functionality and improved error handling across modules. * Add mls_crypto integration and group member management features - Introduced `mls_crypto` as a dependency for wallet address normalization. - Enhanced the desktop UI to support group member management, including requesting user bans. - Implemented new commands and events in the `Gateway` and `User` structs for retrieving group members and processing ban requests. - Updated the `User` struct to include methods for fetching group members and validating wallet addresses. - Refactored various components to improve state management and UI interactions related to group chat and member actions. - Added error handling for invalid wallet addresses and improved overall user experience in group management features. * Replace Apache License with a new version and add MIT License; update README to reflect new licensing information and enhance user module documentation. Refactor user module to improve group management, consensus handling, and messaging features, including ban request processing and proposal management. * Update dependencies and refactor package names for consistency * update ci * update ci * - Added `mls_crypto` as a dependency for wallet address normalization. - Introduced a new CSS file for styling the desktop UI, improving overall aesthetics and user experience. - Enhanced the `User` and `Gateway` structs to support group member management, including ban requests and proposal handling. - Implemented new commands and events for retrieving group members and processing ban requests. - Refactored various components to improve state management and UI interactions related to group chat and member actions. - Updated the `Cargo.toml` and `Cargo.lock` files to reflect new dependencies and configurations. - Added new profiles for development builds targeting WebAssembly, server, and Android environments.
This commit is contained in:
committed by
GitHub
parent
4ea1136012
commit
ae4ee902d5
@@ -1,4 +0,0 @@
|
||||
.env/
|
||||
.idea/
|
||||
target/
|
||||
frontend/
|
||||
14
.github/workflows/ci.yml
vendored
14
.github/workflows/ci.yml
vendored
@@ -27,10 +27,22 @@ jobs:
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: protoc@${{ env.PROTOC_VERSION }}
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install libwebkit2gtk-4.1-dev \
|
||||
build-essential \
|
||||
curl \
|
||||
wget \
|
||||
file \
|
||||
libxdo-dev \
|
||||
libssl-dev \
|
||||
libayatana-appindicator3-dev \
|
||||
librsvg2-dev
|
||||
- name: Check formatting
|
||||
run: cargo fmt --all --check
|
||||
- name: Run clippy
|
||||
run: cargo clippy --all-features --tests -- -D warnings
|
||||
run: cargo clippy -p de_mls_desktop_ui --all-features --tests -- -D warnings
|
||||
|
||||
docs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -12,6 +12,7 @@ target/
|
||||
.DS_Store
|
||||
src/.DS_Store
|
||||
.idea
|
||||
apps/de_mls_desktop_ui/logs
|
||||
|
||||
# files
|
||||
*.env
|
||||
|
||||
5349
Cargo.lock
generated
5349
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
49
Cargo.toml
49
Cargo.toml
@@ -1,21 +1,18 @@
|
||||
[workspace]
|
||||
members = ["ds", "mls_crypto"]
|
||||
# [workspace.dependencies]
|
||||
# foundry-contracts = { path = "crates/bindings" }
|
||||
members = [
|
||||
"apps/de_mls_desktop_ui",
|
||||
"crates/de_mls_gateway",
|
||||
"crates/de_mls_ui_protocol",
|
||||
"crates/ui_bridge",
|
||||
"ds",
|
||||
"mls_crypto",
|
||||
]
|
||||
|
||||
[package]
|
||||
name = "de-mls"
|
||||
version = "2.0.0"
|
||||
name = "de_mls"
|
||||
version = "2.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[[bin]]
|
||||
name = "de-mls"
|
||||
path = "src/main.rs"
|
||||
bench = false
|
||||
|
||||
# [lib]
|
||||
# bench = false
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
@@ -25,12 +22,11 @@ openmls_basic_credential = "0.3.0"
|
||||
openmls_rust_crypto = "0.3.0"
|
||||
openmls_traits = "0.3.0"
|
||||
|
||||
axum = { version = "0.6.10", features = ["ws"] }
|
||||
futures = "0.3.26"
|
||||
tower-http = { version = "0.4.0", features = ["cors"] }
|
||||
tokio = { version = "1.43.0", features = ["macros", "rt-multi-thread", "full"] }
|
||||
futures = "0.3.31"
|
||||
tower-http = { version = "0.6.6", features = ["cors"] }
|
||||
tokio = { version = "1.47.1", features = ["macros", "rt-multi-thread", "full"] }
|
||||
tokio-util = "0.7.13"
|
||||
alloy = { version = "0.11.0", features = [
|
||||
alloy = { version = "1.0.37", features = [
|
||||
"providers",
|
||||
"node-bindings",
|
||||
"network",
|
||||
@@ -62,13 +58,26 @@ anyhow = "1.0.81"
|
||||
thiserror = "1.0.39"
|
||||
uuid = "1.11.0"
|
||||
|
||||
env_logger = "0.11.5"
|
||||
log = "0.4.22"
|
||||
tracing = "0.1.41"
|
||||
|
||||
ds = { path = "ds" }
|
||||
mls_crypto = { path = "mls_crypto" }
|
||||
prost = "0.13.5"
|
||||
bytes = "1.10.1"
|
||||
tower-layer = "0.3.3"
|
||||
http = "1.3.1"
|
||||
|
||||
[build-dependencies]
|
||||
prost-build = "0.13.5"
|
||||
|
||||
[profile]
|
||||
|
||||
[profile.wasm-dev]
|
||||
inherits = "dev"
|
||||
opt-level = 1
|
||||
|
||||
[profile.server-dev]
|
||||
inherits = "dev"
|
||||
|
||||
[profile.android-dev]
|
||||
inherits = "dev"
|
||||
|
||||
21
Dockerfile
21
Dockerfile
@@ -1,21 +0,0 @@
|
||||
####################################################################################################
|
||||
## Build image
|
||||
####################################################################################################
|
||||
FROM rust:latest
|
||||
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y libssl-dev pkg-config gcc clang
|
||||
|
||||
# Cache build dependencies
|
||||
RUN echo "fn main() {}" > dummy.rs
|
||||
COPY ["Cargo.toml", "./Cargo.toml"]
|
||||
COPY ["ds/", "./ds/"]
|
||||
COPY ["mls_crypto/", "./mls_crypto/"]
|
||||
RUN sed -i 's#src/main.rs#dummy.rs#' Cargo.toml
|
||||
RUN cargo build
|
||||
RUN sed -i 's#dummy.rs#src/main.rs#' Cargo.toml
|
||||
# Build the actual app
|
||||
COPY ["src/", "./src/"]
|
||||
RUN cargo build
|
||||
|
||||
CMD ["/app/target/debug/de-mls"]
|
||||
201
LICENSE
201
LICENSE
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
203
LICENSE-APACHE
Normal file
203
LICENSE-APACHE
Normal file
@@ -0,0 +1,203 @@
|
||||
Copyright (c) 2022 Vac Research
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
25
LICENSE-MIT
Normal file
25
LICENSE-MIT
Normal file
@@ -0,0 +1,25 @@
|
||||
Copyright (c) 2022 Vac Research
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE O THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
140
README.md
140
README.md
@@ -1,96 +1,120 @@
|
||||
# de-mls
|
||||
# De-MLS
|
||||
|
||||
Decentralized MLS PoC using a smart contract for group coordination
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
> Note: The frontend implementation is based on [chatr](https://github.com/0xLaurens/chatr),
|
||||
> a real-time chat application built with Rust and SvelteKit
|
||||
Decentralized MLS proof-of-concept that coordinates secure group membership through
|
||||
off-chain consensus and a Waku relay.
|
||||
This repository now ships a native desktop client built with Dioxus that drives the MLS core directly.
|
||||
|
||||
## Run Test Waku Node
|
||||
## What’s Included
|
||||
|
||||
This node is used to easially connect different instances of the app between each other.
|
||||
- **de-mls** – core library that manages MLS groups, consensus, and Waku integration
|
||||
- **crates/de_mls_gateway** – bridges UI commands (`AppCmd`) to the core runtime and streams `AppEvent`s back
|
||||
- **crates/ui_bridge** – bootstrap glue that hosts the async command loop for desktop clients
|
||||
- **apps/de_mls_desktop_ui** – Dioxus desktop UI with login, chat, stewardship, and voting flows
|
||||
- **tests/** – integration tests that exercise the MLS state machine and consensus paths
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Launch a test Waku relay
|
||||
|
||||
Run a lightweight `nwaku` node that your local clients can connect to:
|
||||
|
||||
```bash
|
||||
docker run -p 8645:8645 -p 60000:60000 wakuorg/nwaku:v0.33.1 --cluster-id=15 --rest --relay --rln-relay=false --pubsub-topic=/waku/2/rs/15/1
|
||||
docker run \
|
||||
-p 8645:8645 \
|
||||
-p 60000:60000 \
|
||||
wakuorg/nwaku:v0.33.1 \
|
||||
--cluster-id=15 \
|
||||
--rest \
|
||||
--relay \
|
||||
--rln-relay=false \
|
||||
--pubsub-topic=/waku/2/rs/15/1
|
||||
```
|
||||
|
||||
## Run User Instance
|
||||
Take note of the node multiaddr printed in the logs (looks like `/ip4/127.0.0.1/tcp/60000/p2p/<peer-id>`).
|
||||
|
||||
Create a `.env` file in the `.env` folder for each client containing the following variables:
|
||||
### 2. Set the runtime environment
|
||||
|
||||
```text
|
||||
NAME=client1
|
||||
BACKEND_PORT=3000
|
||||
FRONTEND_PORT=4000
|
||||
NODE_PORT=60000
|
||||
PEER_ADDRESSES=[/ip4/x.x.x.x/tcp/60000/p2p/xxxx...xxxx]
|
||||
```
|
||||
|
||||
Run docker compose up for the user instance
|
||||
The desktop app reads the same environment variables the MLS core uses:
|
||||
|
||||
```bash
|
||||
docker-compose --env-file ./.env/client1.env up --build
|
||||
export NODE_PORT=60001 # UDP/TCP port the embedded Waku client will bind to
|
||||
export PEER_ADDRESSES=/ip4/127.0.0.1/tcp/60000/p2p/<peer-id>
|
||||
export RUST_LOG=info,de_mls_gateway=info # optional; controls UI + gateway logging
|
||||
```
|
||||
|
||||
For each client, run the following command to start the frontend on the local host with the port specified in the `.env` file
|
||||
Use a unique `NODE_PORT` per local client so the embedded Waku nodes do not collide.
|
||||
`PEER_ADDRESSES` accepts a comma-separated list if you want to bootstrap from multiple relays.
|
||||
|
||||
Run from the frontend directory
|
||||
### 3. Launch the desktop application
|
||||
|
||||
```bash
|
||||
PUBLIC_API_URL=http://0.0.0.0:3000 PUBLIC_WEBSOCKET_URL=ws://localhost:3000 npm run dev
|
||||
cargo run -p de_mls_desktop_ui
|
||||
```
|
||||
|
||||
Run from the root directory
|
||||
The first run creates `apps/de_mls_desktop_ui/logs/de_mls_ui.log` and starts the event bridge
|
||||
and embedded Waku client.
|
||||
Repeat steps 2–3 in another terminal with a different `NODE_PORT` to simulate multiple users.
|
||||
|
||||
```bash
|
||||
RUST_BACKTRACE=full RUST_LOG=info NODE_PORT=60001 PEER_ADDRESSES=/ip4/x.x.x.x/tcp/60000/p2p/xxxx...xxxx,/ip4/y.y.y.y/tcp/60000/p2p/yyyy...yyyy cargo run -- --nocapture
|
||||
```
|
||||
## Using the Desktop UI
|
||||
|
||||
## Steward State Management
|
||||
- **Login screen** – paste an Ethereum-compatible secp256k1 private key (hex, with or without `0x`)
|
||||
and click `Enter`.
|
||||
On success the app derives your wallet address, stores it in session state,
|
||||
and navigates to the home layout.
|
||||
|
||||
The system implements a robust state machine for managing steward epochs with the following states:
|
||||
- **Header bar** – shows the derived address and allows runtime log-level changes (`error`→`trace`).
|
||||
Log files rotate daily under `apps/de_mls_desktop_ui/logs/`.
|
||||
|
||||
### States
|
||||
- **Groups panel** – lists every MLS group returned by the gateway.
|
||||
Use `Create` or `Join` to open a modal, enter the group name,
|
||||
and the UI automatically refreshes the list and opens the group.
|
||||
|
||||
- **Working**: Normal operation where all users can send any message type freely
|
||||
- **Waiting**: Steward epoch active, only steward can send BATCH_PROPOSALS_MESSAGE
|
||||
- **Voting**: Consensus voting phase with only voting-related messages:
|
||||
- Everyone: VOTE, USER_VOTE
|
||||
- Steward only: VOTING_PROPOSAL, PROPOSAL
|
||||
- All other messages blocked during voting
|
||||
- **Chat panel** – displays live conversation messages for the active group.
|
||||
Compose text messages at the bottom; the UI also offers:
|
||||
- `Leave group` to request a self-ban (the backend fills in your address)
|
||||
- `Request ban` to request ban for another user
|
||||
Member lists are fetched automatically when a group is opened so you can
|
||||
pick existing members from the ban modal.
|
||||
|
||||
### State Transitions
|
||||
- **Consensus panel** – keeps stewards and members aligned:
|
||||
- Shows whether you are a steward for the active group
|
||||
- Lists pending steward requests collected during the current epoch
|
||||
- Surfaces the proposal currently open for voting with `YES`/`NO` buttons
|
||||
- Stores the latest proposal decisions with timestamps for quick auditing
|
||||
|
||||
## Steward State Machine
|
||||
|
||||
- **Working** – normal mode; all MLS messages are allowed
|
||||
- **Waiting** – a steward epoch is active; only the steward may push `BATCH_PROPOSALS_MESSAGE`
|
||||
- **Voting** – the consensus phase; everyone may submit `VOTE`/`USER_VOTE`,
|
||||
the steward can still publish proposal metadata
|
||||
|
||||
Transitions:
|
||||
|
||||
```text
|
||||
Working --start_steward_epoch()--> Waiting (if proposals exist)
|
||||
Working --start_steward_epoch()--> Working (if no proposals - no state change)
|
||||
Working --start_steward_epoch()--> Working (if no proposals)
|
||||
Waiting --start_voting()---------> Voting
|
||||
Waiting --no_proposals_found()---> Working (edge case: proposals disappear)
|
||||
Waiting --no_proposals_found()---> Working
|
||||
Voting --complete_voting(YES)----> Waiting --apply_proposals()--> Working
|
||||
Voting --complete_voting(NO)-----> Working
|
||||
```
|
||||
|
||||
### Steward Flow Scenarios
|
||||
Stewards always return to `Working` after an epoch finishes;
|
||||
edge cases such as missing proposals are handled defensively with detailed tracing.
|
||||
|
||||
1. **No Proposals**: Steward stays in Working state throughout epoch
|
||||
2. **Successful Vote**:
|
||||
- **Steward**: Working → Waiting → Voting → Waiting → Working
|
||||
- **Non-Steward**: Working → Waiting → Voting → Working
|
||||
3. **Failed Vote**:
|
||||
- **Steward**: Working → Waiting → Voting → Working
|
||||
- **Non-Steward**: Working → Waiting → Voting → Working
|
||||
4. **Edge Case**: Working → Waiting → Working (if proposals disappear during voting)
|
||||
## Development Tips
|
||||
|
||||
### Guarantees
|
||||
- `cargo test` – runs the Rust unit + integration test suite
|
||||
- `cargo fmt --all check` / `cargo clippy` – keep formatting and linting consistent with the codebase
|
||||
- `RUST_BACKTRACE=full` – helpful when debugging state-machine transitions during development
|
||||
|
||||
- Steward always returns to Working state after epoch completion
|
||||
- No infinite loops or stuck states
|
||||
- All edge cases properly handled
|
||||
- Robust error handling with detailed logging
|
||||
Logs for the desktop UI live in `apps/de_mls_desktop_ui/logs/`; core logs are emitted to stdout as well.
|
||||
|
||||
### Example of ban user
|
||||
## Contributing
|
||||
|
||||
In chat message block run ban command, note that user wallet address should be in the format without `0x`
|
||||
|
||||
```bash
|
||||
/ban f39555ce6ab55579cfffb922665825e726880af6
|
||||
```
|
||||
Issues and pull requests are welcome. Please include reproduction steps, relevant logs,
|
||||
and test coverage where possible.
|
||||
|
||||
32
apps/de_mls_desktop_ui/Cargo.toml
Normal file
32
apps/de_mls_desktop_ui/Cargo.toml
Normal file
@@ -0,0 +1,32 @@
|
||||
[package]
|
||||
name = "de_mls_desktop_ui"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
de_mls_ui_protocol = { path = "../../crates/de_mls_ui_protocol" }
|
||||
de_mls_gateway = { path = "../../crates/de_mls_gateway" }
|
||||
ui_bridge = { path = "../../crates/ui_bridge" }
|
||||
de_mls = { path = "../../" }
|
||||
mls_crypto = { path = "../../mls_crypto" }
|
||||
|
||||
dioxus = { version = "0.6.2", features = ["signals", "router", "desktop"] }
|
||||
dioxus-desktop = "0.6.3"
|
||||
tokio = { version = "1.47.1", features = [
|
||||
"rt-multi-thread",
|
||||
"macros",
|
||||
"sync",
|
||||
"time",
|
||||
] }
|
||||
futures = "0.3.31"
|
||||
anyhow = "1.0.100"
|
||||
thiserror = "2.0.17"
|
||||
uuid = { version = "1.18.1", features = ["v4", "serde"] }
|
||||
once_cell = "1.21.3"
|
||||
parking_lot = "0.12.5"
|
||||
tracing = "0.1.41"
|
||||
tracing-subscriber = { version = "0.3.20", features = ["fmt", "env-filter"] }
|
||||
tracing-appender = "0.2.3"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
hex = "0.4"
|
||||
619
apps/de_mls_desktop_ui/assets/main.css
Normal file
619
apps/de_mls_desktop_ui/assets/main.css
Normal file
@@ -0,0 +1,619 @@
|
||||
:root {
|
||||
--bg: #0b0d10;
|
||||
--card: #14161c;
|
||||
--text: #e5e7ec;
|
||||
--muted: #9094a2;
|
||||
--primary: #00b2ff;
|
||||
--primary-2: #007ad9;
|
||||
--border: #1c1e25;
|
||||
--good: #00f5a0;
|
||||
--bad: #ff005c;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#main {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, Noto Sans, Apple Color Emoji, Segoe UI Emoji;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0 0 16px 0;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
.header .brand {
|
||||
font-weight: 700;
|
||||
letter-spacing: .5px;
|
||||
}
|
||||
|
||||
.header .user-hint {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
padding: 4px 8px;
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: 8px;
|
||||
max-width: 420px;
|
||||
}
|
||||
|
||||
.header .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.header .label {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.header .level {
|
||||
padding: 6px 8px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--card);
|
||||
color: var(--text);
|
||||
outline: none;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.page.login {
|
||||
max-width: 520px;
|
||||
margin-top: 32px;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
padding: 10px 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--card);
|
||||
color: var(--text);
|
||||
outline: none;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.input-error {
|
||||
color: var(--bad);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
button {
|
||||
border: 1px solid var(--border);
|
||||
background: var(--card);
|
||||
color: var(--text);
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
background: var(--primary);
|
||||
border-color: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
button.primary:hover {
|
||||
background: var(--primary-2);
|
||||
}
|
||||
|
||||
button.secondary {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
button.ghost {
|
||||
background: transparent;
|
||||
border-color: var(--border);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
button.icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
button.mini {
|
||||
padding: 4px 8px;
|
||||
border-radius: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.alerts {
|
||||
position: fixed;
|
||||
top: 64px;
|
||||
right: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
z-index: 20;
|
||||
}
|
||||
|
||||
.alert {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
min-width: 260px;
|
||||
max-width: 420px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--card);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.alert.error {
|
||||
border-color: rgba(255, 0, 92, 0.4);
|
||||
background: rgba(255, 0, 92, 0.1);
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
.alert .message {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.member-picker {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.member-picker .helper {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.member-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
max-height: 260px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.member-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 10px;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
border: none;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.member-item .member-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.member-item .member-id {
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--text);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
overflow-wrap: anywhere;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.member-item .member-choose {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: none;
|
||||
padding: 6px 12px;
|
||||
border-radius: 999px;
|
||||
border: none;
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 6px 18px rgba(0, 178, 255, 0.35);
|
||||
}
|
||||
|
||||
.member-item .member-choose:hover {
|
||||
background: var(--primary-2);
|
||||
box-shadow: 0 6px 18px rgba(0, 122, 217, 0.45);
|
||||
}
|
||||
|
||||
/* Home layout */
|
||||
.page.home {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.layout {
|
||||
display: grid;
|
||||
grid-template-columns: 280px 1fr 500px;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
}
|
||||
|
||||
.ellipsis {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
|
||||
.panel {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.panel h2 {
|
||||
margin: 0 0 6px 0;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: var(--muted);
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.panel.groups .group-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* Group list a bit wider rows to align with long names */
|
||||
.group-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.group-row .title {
|
||||
font-weight: 600;
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.panel.groups .footer {
|
||||
margin-top: auto;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.panel.groups .footer .primary {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Chat */
|
||||
.panel.chat .messages {
|
||||
min-height: 360px;
|
||||
height: 58vh;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.panel.chat .chat-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.msg {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.msg.me {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.msg.me .body {
|
||||
background: rgba(79, 140, 255, 0.15);
|
||||
border: 1px solid rgba(79, 140, 255, 0.35);
|
||||
padding: 8px 10px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.msg.system {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.msg.system .body {
|
||||
font-style: italic;
|
||||
color: var(--muted);
|
||||
background: transparent;
|
||||
border: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.msg .from {
|
||||
color: var(--muted);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.msg .body {
|
||||
color: var(--text);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid var(--border);
|
||||
padding: 8px 10px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.composer {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.composer input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.composer button {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
/* Consensus panel */
|
||||
.panel.consensus .status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.panel.consensus .status .good {
|
||||
color: var(--good);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.panel.consensus .status .bad {
|
||||
color: var(--bad);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.panel.consensus .proposal-item {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(6rem, max-content) 1fr;
|
||||
align-items: start;
|
||||
gap: 8px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.panel.consensus .proposal-item .action {
|
||||
color: var(--primary);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.panel.consensus .proposal-item .value {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
color: var(--text);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.panel.consensus .proposal-item.proposal-id {
|
||||
background: rgba(0, 178, 255, 0.08);
|
||||
border-color: rgba(0, 178, 255, 0.45);
|
||||
box-shadow: inset 0 0 0 1px rgba(0, 178, 255, 0.15);
|
||||
}
|
||||
|
||||
.panel.consensus .proposal-item.proposal-id .action {
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.panel.consensus .proposal-item.proposal-id .value {
|
||||
font-weight: 700;
|
||||
font-size: 13px;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
/* Consensus sections */
|
||||
.panel.consensus {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.panel.consensus .status {
|
||||
flex-shrink: 0;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.panel.consensus .consensus-section {
|
||||
margin: 8px 0;
|
||||
padding: 12px;
|
||||
border-radius: 10px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.panel.consensus .consensus-section h3 {
|
||||
margin: 0 0 12px 0;
|
||||
font-size: 14px;
|
||||
color: var(--primary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.panel.consensus .no-data {
|
||||
color: var(--muted);
|
||||
font-style: italic;
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.panel.consensus .proposals-window {
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.panel.consensus .vote-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
/* Consensus results window */
|
||||
.panel.consensus .results-window {
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 8px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
max-height: 200px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.panel.consensus .result-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid var(--border);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.panel.consensus .result-item .proposal-id {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.panel.consensus .result-item .outcome {
|
||||
font-weight: 600;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.panel.consensus .result-item .outcome.accepted {
|
||||
color: var(--good);
|
||||
background: rgba(23, 201, 100, 0.1);
|
||||
}
|
||||
|
||||
.panel.consensus .result-item .outcome.rejected {
|
||||
color: var(--bad);
|
||||
background: rgba(243, 18, 96, 0.1);
|
||||
}
|
||||
|
||||
.panel.consensus .result-item .outcome.unspecified {
|
||||
color: var(--muted);
|
||||
background: rgba(163, 167, 179, 0.1);
|
||||
}
|
||||
|
||||
.panel.consensus .result-item .timestamp {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, .45);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal {
|
||||
width: 520px;
|
||||
max-width: calc(100vw - 32px);
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
box-shadow: 0 0 6px var(--primary);
|
||||
}
|
||||
|
||||
.modal-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
margin-top: 6px;
|
||||
}
|
||||
63
apps/de_mls_desktop_ui/src/logging.rs
Normal file
63
apps/de_mls_desktop_ui/src/logging.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use once_cell::sync::OnceCell;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use tracing_appender::rolling;
|
||||
use tracing_subscriber::{
|
||||
fmt,
|
||||
layer::SubscriberExt,
|
||||
reload::{Handle, Layer as ReloadLayer},
|
||||
util::SubscriberInitExt,
|
||||
EnvFilter, Registry,
|
||||
};
|
||||
|
||||
/// Global reload handle so the UI can change the filter at runtime.
|
||||
static RELOAD: OnceCell<Mutex<Handle<EnvFilter, Registry>>> = OnceCell::new();
|
||||
|
||||
/// Initialize logging: console + rolling daily file ("logs/de_mls_ui.log").
|
||||
/// Returns the initial level string actually applied.
|
||||
pub fn init_logging(default_level: &str) -> String {
|
||||
// Use env var if present, else the provided default
|
||||
let env_level = std::env::var("RUST_LOG").unwrap_or_else(|_| default_level.to_string());
|
||||
|
||||
// Build a reloadable EnvFilter
|
||||
let filter = EnvFilter::try_new(&env_level).unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
let (reload_layer, handle) = ReloadLayer::new(filter);
|
||||
|
||||
// File sink (non-blocking)
|
||||
let file_appender = rolling::daily("logs", "de_mls_ui.log");
|
||||
let (file_writer, guard) = tracing_appender::non_blocking(file_appender);
|
||||
// Keep guard alive for the whole process to flush on drop
|
||||
Box::leak(Box::new(guard));
|
||||
|
||||
// Build the subscriber: registry + reloadable filter + console + file
|
||||
tracing_subscriber::registry()
|
||||
.with(reload_layer)
|
||||
.with(fmt::layer().with_writer(std::io::stdout)) // console
|
||||
.with(fmt::layer().with_writer(file_writer).with_ansi(false)) // file
|
||||
.init();
|
||||
|
||||
RELOAD.set(Mutex::new(handle)).ok();
|
||||
|
||||
// Return the level we consider “active” for the UI dropdown
|
||||
std::env::var("RUST_LOG").unwrap_or(env_level)
|
||||
}
|
||||
|
||||
/// Set the global log level dynamically, e.g. "error", "warn", "info", "debug", "trace",
|
||||
/// or a full filter string like "info,de_mls_gateway=debug".
|
||||
pub fn set_level(new_level: &str) -> Result<(), String> {
|
||||
let handle = RELOAD
|
||||
.get()
|
||||
.ok_or_else(|| "logger not initialized".to_string())?
|
||||
.lock()
|
||||
.map_err(|_| "reload handle poisoned".to_string())?;
|
||||
|
||||
let filter = EnvFilter::try_new(new_level)
|
||||
.map_err(|e| format!("invalid level/filter '{new_level}': {e}"))?;
|
||||
|
||||
// Replace the inner EnvFilter of the reloadable layer
|
||||
handle
|
||||
.modify(|inner: &mut EnvFilter| *inner = filter)
|
||||
.map_err(|e| format!("failed to apply filter: {e}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
971
apps/de_mls_desktop_ui/src/main.rs
Normal file
971
apps/de_mls_desktop_ui/src/main.rs
Normal file
@@ -0,0 +1,971 @@
|
||||
// apps/de_mls_desktop_ui/src/main.rs
|
||||
#![allow(non_snake_case)]
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_desktop::{launch::launch as desktop_launch, Config, LogicalSize, WindowBuilder};
|
||||
use std::sync::{
|
||||
atomic::{AtomicU64, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use de_mls::{
|
||||
bootstrap_core_from_env,
|
||||
message::convert_group_requests_to_display,
|
||||
protos::{
|
||||
consensus::v1::{Outcome, ProposalResult, VotePayload},
|
||||
de_mls::messages::v1::ConversationMessage,
|
||||
},
|
||||
};
|
||||
use de_mls_gateway::GATEWAY;
|
||||
use de_mls_ui_protocol::v1::{AppCmd, AppEvent};
|
||||
use mls_crypto::normalize_wallet_address_str;
|
||||
|
||||
mod logging;
|
||||
|
||||
static CSS: Asset = asset!("/assets/main.css");
|
||||
static NEXT_ALERT_ID: AtomicU64 = AtomicU64::new(1);
|
||||
const MAX_VISIBLE_ALERTS: usize = 5;
|
||||
|
||||
// Helper function to format timestamps
|
||||
fn format_timestamp(timestamp_ms: u64) -> String {
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
// Convert to SystemTime and format
|
||||
let timestamp = UNIX_EPOCH + std::time::Duration::from_secs(timestamp_ms);
|
||||
let datetime: chrono::DateTime<chrono::Utc> = timestamp.into();
|
||||
datetime.format("%H:%M:%S").to_string()
|
||||
}
|
||||
|
||||
// ─────────────────────────── App state ───────────────────────────
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct SessionState {
|
||||
address: String,
|
||||
key: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct GroupsState {
|
||||
items: Vec<String>, // names only
|
||||
loaded: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct ChatState {
|
||||
opened_group: Option<String>, // which group is “Open” in the UI
|
||||
messages: Vec<ConversationMessage>, // all messages; filtered per view
|
||||
members: Vec<String>, // cached member addresses for opened group
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct ConsensusState {
|
||||
is_steward: bool,
|
||||
pending: Option<VotePayload>, // active/pending proposal for opened group
|
||||
// Store results with timestamps for better display
|
||||
latest_results: Vec<(u32, Outcome, u64)>, // (vote_id, result, timestamp_ms)
|
||||
// Store current epoch proposals for stewards
|
||||
current_epoch_proposals: Vec<(String, String)>, // (action, address) pairs
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Alert {
|
||||
id: u64,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct AlertsState {
|
||||
errors: Vec<Alert>,
|
||||
}
|
||||
|
||||
fn record_error(alerts: &mut Signal<AlertsState>, message: impl Into<String>) {
|
||||
let raw = message.into();
|
||||
let summary = summarize_error(&raw);
|
||||
tracing::error!("ui error: {}", raw);
|
||||
let id = NEXT_ALERT_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let mut state = alerts.write();
|
||||
state.errors.push(Alert {
|
||||
id,
|
||||
message: summary,
|
||||
});
|
||||
if state.errors.len() > MAX_VISIBLE_ALERTS {
|
||||
state.errors.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn dismiss_error(alerts: &mut Signal<AlertsState>, alert_id: u64) {
|
||||
alerts.write().errors.retain(|alert| alert.id != alert_id);
|
||||
}
|
||||
|
||||
fn summarize_error(raw: &str) -> String {
|
||||
let mut summary = raw
|
||||
.lines()
|
||||
.next()
|
||||
.map(|line| line.trim().to_string())
|
||||
.unwrap_or_else(|| raw.trim().to_string());
|
||||
const MAX_LEN: usize = 160;
|
||||
if summary.len() > MAX_LEN {
|
||||
summary.truncate(MAX_LEN.saturating_sub(1));
|
||||
summary.push('…');
|
||||
}
|
||||
if summary.is_empty() {
|
||||
"Unexpected error".to_string()
|
||||
} else {
|
||||
summary
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── Routing ───────────────────────────
|
||||
|
||||
#[derive(Routable, Clone, PartialEq)]
|
||||
enum Route {
|
||||
#[route("/")]
|
||||
Login,
|
||||
#[route("/home")]
|
||||
Home, // unified page
|
||||
}
|
||||
|
||||
// ─────────────────────────── Entry ───────────────────────────
|
||||
|
||||
fn main() {
|
||||
let initial_level = logging::init_logging("info");
|
||||
tracing::info!("🚀 DE-MLS Desktop UI starting… level={}", initial_level);
|
||||
|
||||
// Build a small RT to run the async bootstrap before the UI
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("rt");
|
||||
|
||||
rt.block_on(async {
|
||||
let boot = bootstrap_core_from_env()
|
||||
.await
|
||||
.expect("bootstrap_core_from_env failed");
|
||||
// hand CoreCtx to the gateway via the UI bridge
|
||||
ui_bridge::start_ui_bridge(boot.core.clone());
|
||||
boot.core
|
||||
});
|
||||
|
||||
let config = Config::new().with_window(
|
||||
WindowBuilder::new()
|
||||
.with_title("DE-MLS Desktop UI")
|
||||
.with_inner_size(LogicalSize::new(1280, 820))
|
||||
.with_resizable(true),
|
||||
);
|
||||
|
||||
tracing::info!("Launching desktop application");
|
||||
desktop_launch(App, vec![], vec![Box::new(config)]);
|
||||
}
|
||||
|
||||
fn App() -> Element {
|
||||
use_context_provider(|| Signal::new(AlertsState::default()));
|
||||
use_context_provider(|| Signal::new(SessionState::default()));
|
||||
use_context_provider(|| Signal::new(GroupsState::default()));
|
||||
use_context_provider(|| Signal::new(ChatState::default()));
|
||||
use_context_provider(|| Signal::new(ConsensusState::default()));
|
||||
|
||||
rsx! {
|
||||
document::Stylesheet { href: CSS }
|
||||
HeaderBar {}
|
||||
AlertsCenter {}
|
||||
Router::<Route> {}
|
||||
}
|
||||
}
|
||||
|
||||
fn HeaderBar() -> Element {
|
||||
// local signal to reflect current level in the select
|
||||
let mut level = use_signal(|| std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string()));
|
||||
let session = use_context::<Signal<SessionState>>();
|
||||
let my_addr = session.read().address.clone();
|
||||
|
||||
let on_change = {
|
||||
move |evt: FormEvent| {
|
||||
let new_val = evt.value();
|
||||
if let Err(e) = crate::logging::set_level(&new_val) {
|
||||
tracing::warn!("failed to set log level: {}", e);
|
||||
} else {
|
||||
level.set(new_val);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
rsx! {
|
||||
div { class: "header",
|
||||
div { class: "brand", "DE-MLS" }
|
||||
if !my_addr.is_empty() {
|
||||
span { class: "user-hint mono ellipsis", title: "{my_addr}", "{my_addr}" }
|
||||
}
|
||||
div { class: "spacer" }
|
||||
label { class: "label", "Log level" }
|
||||
select {
|
||||
class: "level",
|
||||
value: "{level}",
|
||||
oninput: on_change,
|
||||
option { value: "error", "error" }
|
||||
option { value: "warn", "warn" }
|
||||
option { value: "info", "info" }
|
||||
option { value: "debug", "debug" }
|
||||
option { value: "trace", "trace" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── Pages ───────────────────────────
|
||||
|
||||
fn Login() -> Element {
|
||||
let nav = use_navigator();
|
||||
let mut session = use_context::<Signal<SessionState>>();
|
||||
let mut key = use_signal(String::new);
|
||||
let mut alerts = use_context::<Signal<AlertsState>>();
|
||||
|
||||
// Local single-consumer loop: only Login() steals LoggedIn events
|
||||
use_future({
|
||||
move || async move {
|
||||
loop {
|
||||
match GATEWAY.next_event().await {
|
||||
Some(AppEvent::LoggedIn(name)) => {
|
||||
session.write().address = name;
|
||||
nav.replace(Route::Home);
|
||||
break;
|
||||
}
|
||||
Some(AppEvent::Error(error)) => {
|
||||
record_error(&mut alerts, error);
|
||||
}
|
||||
Some(other) => {
|
||||
tracing::debug!("login view ignored event: {:?}", other);
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let oninput_key = { move |e: FormEvent| key.set(e.value()) };
|
||||
|
||||
let mut on_submit = move |_| {
|
||||
let k = key.read().trim().to_string();
|
||||
if k.is_empty() {
|
||||
return;
|
||||
}
|
||||
session.write().key = k.clone();
|
||||
spawn(async move {
|
||||
let _ = GATEWAY.send(AppCmd::Login { private_key: k }).await;
|
||||
});
|
||||
};
|
||||
|
||||
rsx! {
|
||||
div { class: "page login",
|
||||
h1 { "DE-MLS — Login" }
|
||||
div { class: "form-row",
|
||||
label { "Private key" }
|
||||
input {
|
||||
r#type: "password",
|
||||
value: "{key}",
|
||||
oninput: oninput_key,
|
||||
placeholder: "0x...",
|
||||
}
|
||||
}
|
||||
button { class: "primary", onclick: move |_| { on_submit(()); }, "Enter" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn Home() -> Element {
|
||||
let mut groups = use_context::<Signal<GroupsState>>();
|
||||
let mut chat = use_context::<Signal<ChatState>>();
|
||||
let mut cons = use_context::<Signal<ConsensusState>>();
|
||||
let mut alerts = use_context::<Signal<AlertsState>>();
|
||||
|
||||
use_future({
|
||||
move || async move {
|
||||
if !groups.read().loaded {
|
||||
let _ = GATEWAY.send(AppCmd::ListGroups).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Local event loop for handling events from the gateway
|
||||
use_future({
|
||||
move || async move {
|
||||
loop {
|
||||
match GATEWAY.next_event().await {
|
||||
Some(AppEvent::StewardStatus {
|
||||
group_id,
|
||||
is_steward,
|
||||
}) => {
|
||||
// only update if it is the currently opened group
|
||||
if chat.read().opened_group.as_deref() == Some(group_id.as_str()) {
|
||||
cons.write().is_steward = is_steward;
|
||||
}
|
||||
}
|
||||
Some(AppEvent::CurrentEpochProposals {
|
||||
group_id,
|
||||
proposals,
|
||||
}) => {
|
||||
// only update if it is the currently opened group
|
||||
if chat.read().opened_group.as_deref() == Some(group_id.as_str()) {
|
||||
cons.write().current_epoch_proposals = proposals;
|
||||
}
|
||||
}
|
||||
Some(AppEvent::GroupMembers { group_id, members }) => {
|
||||
if chat.read().opened_group.as_deref() == Some(group_id.as_str()) {
|
||||
chat.write().members = members;
|
||||
}
|
||||
}
|
||||
Some(AppEvent::ProposalAdded {
|
||||
group_id,
|
||||
action,
|
||||
address,
|
||||
}) => {
|
||||
// only update if it is the currently opened group
|
||||
if chat.read().opened_group.as_deref() == Some(group_id.as_str()) {
|
||||
// Avoid duplicates: do not enqueue if the same (action, address) already exists
|
||||
let exists = {
|
||||
cons.read().current_epoch_proposals.iter().any(|(a, addr)| {
|
||||
a == &action && addr.eq_ignore_ascii_case(&address)
|
||||
})
|
||||
};
|
||||
if !exists {
|
||||
cons.write().current_epoch_proposals.push((action, address));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(AppEvent::CurrentEpochProposalsCleared { group_id }) => {
|
||||
// only update if it is the currently opened group
|
||||
if chat.read().opened_group.as_deref() == Some(group_id.as_str()) {
|
||||
cons.write().current_epoch_proposals.clear();
|
||||
}
|
||||
}
|
||||
Some(AppEvent::Groups(names)) => {
|
||||
groups.write().items = names;
|
||||
groups.write().loaded = true;
|
||||
}
|
||||
Some(AppEvent::ChatMessage(msg)) => {
|
||||
chat.write().messages.push(msg);
|
||||
}
|
||||
Some(AppEvent::VoteRequested(vp)) => {
|
||||
let opened = chat.read().opened_group.clone();
|
||||
if opened.as_deref() == Some(vp.group_id.as_str()) {
|
||||
cons.write().pending = Some(vp);
|
||||
}
|
||||
}
|
||||
Some(AppEvent::ProposalDecided(ProposalResult {
|
||||
group_id,
|
||||
proposal_id,
|
||||
outcome,
|
||||
decided_at_ms,
|
||||
})) => {
|
||||
if chat.read().opened_group.as_deref() == Some(group_id.as_str()) {
|
||||
cons.write().latest_results.push((
|
||||
proposal_id,
|
||||
Outcome::try_from(outcome).unwrap_or(Outcome::Unspecified),
|
||||
decided_at_ms,
|
||||
));
|
||||
}
|
||||
cons.write().pending = None;
|
||||
}
|
||||
Some(AppEvent::GroupRemoved(name)) => {
|
||||
let mut g = groups.write();
|
||||
g.items.retain(|n| n != &name);
|
||||
if chat.read().opened_group.as_deref() == Some(name.as_str()) {
|
||||
chat.write().opened_group = None;
|
||||
chat.write().members.clear();
|
||||
}
|
||||
}
|
||||
Some(AppEvent::Error(error)) => {
|
||||
record_error(&mut alerts, error);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
rsx! {
|
||||
div { class: "page home",
|
||||
div { class: "layout",
|
||||
GroupListSection {}
|
||||
ChatSection {}
|
||||
ConsensusSection {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn AlertsCenter() -> Element {
|
||||
let alerts = use_context::<Signal<AlertsState>>();
|
||||
let items = alerts.read().errors.clone();
|
||||
rsx! {
|
||||
div { class: "alerts",
|
||||
for alert in items.iter() {
|
||||
AlertItem {
|
||||
key: "{alert.id}",
|
||||
alert_id: alert.id,
|
||||
message: alert.message.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Props, PartialEq, Clone)]
|
||||
struct AlertItemProps {
|
||||
alert_id: u64,
|
||||
message: String,
|
||||
}
|
||||
|
||||
fn AlertItem(props: AlertItemProps) -> Element {
|
||||
let mut alerts = use_context::<Signal<AlertsState>>();
|
||||
let alert_id = props.alert_id;
|
||||
let message = props.message.clone();
|
||||
let dismiss = move |_| {
|
||||
dismiss_error(&mut alerts, alert_id);
|
||||
};
|
||||
|
||||
rsx! {
|
||||
div { class: "alert error",
|
||||
span { class: "message", "{message}" }
|
||||
button { class: "ghost icon", onclick: dismiss, "✕" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── Sections ───────────────────────────
|
||||
|
||||
fn GroupListSection() -> Element {
|
||||
let groups_state = use_context::<Signal<GroupsState>>();
|
||||
let mut chat = use_context::<Signal<ChatState>>();
|
||||
let mut show_modal = use_signal(|| false);
|
||||
let mut new_name = use_signal(String::new);
|
||||
let mut create_mode = use_signal(|| true); // true=create, false=join
|
||||
|
||||
let items_snapshot: Vec<String> = groups_state.read().items.clone();
|
||||
let loaded = groups_state.read().loaded;
|
||||
|
||||
let mut open_group = {
|
||||
move |name: String| {
|
||||
chat.write().opened_group = Some(name.clone());
|
||||
chat.write().members.clear();
|
||||
let group_id = name.clone();
|
||||
spawn(async move {
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::EnterGroup {
|
||||
group_id: group_id.clone(),
|
||||
})
|
||||
.await;
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::LoadHistory {
|
||||
group_id: group_id.clone(),
|
||||
})
|
||||
.await;
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::GetStewardStatus {
|
||||
group_id: group_id.clone(),
|
||||
})
|
||||
.await;
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::GetCurrentEpochProposals {
|
||||
group_id: group_id.clone(),
|
||||
})
|
||||
.await;
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::GetGroupMembers {
|
||||
group_id: group_id.clone(),
|
||||
})
|
||||
.await;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let mut modal_submit = {
|
||||
move |_| {
|
||||
let name = new_name.read().trim().to_string();
|
||||
if name.is_empty() {
|
||||
return;
|
||||
}
|
||||
let action_name = name.clone();
|
||||
if *create_mode.read() {
|
||||
spawn(async move {
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::CreateGroup {
|
||||
name: action_name.clone(),
|
||||
})
|
||||
.await;
|
||||
let _ = GATEWAY.send(AppCmd::ListGroups).await;
|
||||
});
|
||||
} else {
|
||||
spawn(async move {
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::JoinGroup {
|
||||
name: action_name.clone(),
|
||||
})
|
||||
.await;
|
||||
let _ = GATEWAY.send(AppCmd::ListGroups).await;
|
||||
});
|
||||
}
|
||||
open_group(name);
|
||||
new_name.set(String::new());
|
||||
show_modal.set(false);
|
||||
}
|
||||
};
|
||||
|
||||
rsx! {
|
||||
div { class: "panel groups",
|
||||
h2 { "Groups" }
|
||||
|
||||
if !loaded {
|
||||
div { class: "hint", "Loading groups…" }
|
||||
} else if items_snapshot.is_empty() {
|
||||
div { class: "hint", "No groups yet." }
|
||||
} else {
|
||||
ul { class: "group-list",
|
||||
for name in items_snapshot.into_iter() {
|
||||
li {
|
||||
key: "{name}",
|
||||
class: "group-row",
|
||||
div { class: "title", "{name}" }
|
||||
button {
|
||||
class: "secondary",
|
||||
onclick: move |_| { open_group(name.clone()); },
|
||||
"Open"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
div { class: "footer",
|
||||
button { class: "primary", onclick: move |_| { create_mode.set(true); show_modal.set(true); }, "Create" }
|
||||
button { class: "primary", onclick: move |_| { create_mode.set(false); show_modal.set(true); }, "Join" }
|
||||
}
|
||||
|
||||
if *show_modal.read() {
|
||||
Modal {
|
||||
title: if *create_mode.read() { "Create Group".to_string() } else { "Join Group".to_string() },
|
||||
on_close: move || { show_modal.set(false); },
|
||||
div { class: "form-row",
|
||||
label { "Group name" }
|
||||
input {
|
||||
r#type: "text",
|
||||
value: "{new_name}",
|
||||
oninput: move |e| new_name.set(e.value()),
|
||||
placeholder: "mls-devs",
|
||||
}
|
||||
}
|
||||
|
||||
div { class: "actions",
|
||||
button { class: "primary", onclick: move |_| { modal_submit(()); }, "Confirm" }
|
||||
button { class: "ghost", onclick: move |_| { show_modal.set(false); }, "Cancel" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ChatSection() -> Element {
|
||||
let chat = use_context::<Signal<ChatState>>();
|
||||
let session = use_context::<Signal<SessionState>>();
|
||||
let mut msg_input = use_signal(String::new);
|
||||
let mut show_ban_modal = use_signal(|| false);
|
||||
let mut ban_address = use_signal(String::new);
|
||||
let mut ban_error = use_signal(|| Option::<String>::None);
|
||||
|
||||
let send_msg = {
|
||||
move |_| {
|
||||
let text = msg_input.read().trim().to_string();
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(gid) = chat.read().opened_group.clone() else {
|
||||
return;
|
||||
};
|
||||
|
||||
msg_input.set(String::new());
|
||||
spawn(async move {
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::SendMessage {
|
||||
group_id: gid,
|
||||
body: text,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let open_ban_modal = {
|
||||
move |_| {
|
||||
if let Some(gid) = chat.read().opened_group.clone() {
|
||||
spawn(async move {
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::GetGroupMembers {
|
||||
group_id: gid.clone(),
|
||||
})
|
||||
.await;
|
||||
});
|
||||
}
|
||||
ban_error.set(None);
|
||||
show_ban_modal.set(true);
|
||||
}
|
||||
};
|
||||
|
||||
let submit_ban_request = {
|
||||
move |_| {
|
||||
let raw = ban_address.read().to_string();
|
||||
let target = match normalize_wallet_address_str(&raw) {
|
||||
Ok(addr) => addr,
|
||||
Err(err) => {
|
||||
ban_error.set(Some(err.to_string()));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let opened = chat.read().opened_group.clone();
|
||||
let Some(group_id) = opened else {
|
||||
return;
|
||||
};
|
||||
|
||||
ban_error.set(None);
|
||||
show_ban_modal.set(false);
|
||||
ban_address.set(String::new());
|
||||
|
||||
let addr_to_ban = target.clone();
|
||||
spawn(async move {
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::SendBanRequest {
|
||||
group_id: group_id.clone(),
|
||||
user_to_ban: addr_to_ban,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let oninput_ban_address = {
|
||||
move |e: FormEvent| {
|
||||
ban_error.set(None);
|
||||
ban_address.set(e.value())
|
||||
}
|
||||
};
|
||||
|
||||
let close_ban_modal = {
|
||||
move || {
|
||||
ban_address.set(String::new());
|
||||
ban_error.set(None);
|
||||
show_ban_modal.set(false);
|
||||
}
|
||||
};
|
||||
|
||||
let cancel_ban_modal = {
|
||||
move |_| {
|
||||
ban_address.set(String::new());
|
||||
ban_error.set(None);
|
||||
show_ban_modal.set(false);
|
||||
}
|
||||
};
|
||||
|
||||
let msgs_for_group = {
|
||||
let opened = chat.read().opened_group.clone();
|
||||
chat.read()
|
||||
.messages
|
||||
.iter()
|
||||
.filter(|m| Some(m.group_name.as_str()) == opened.as_deref())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
let my_name = Arc::new(session.read().address.clone());
|
||||
let my_name_for_leave = my_name.clone();
|
||||
|
||||
let members_snapshot = chat.read().members.clone();
|
||||
let my_address = (*my_name).clone();
|
||||
let selectable_members: Vec<String> = members_snapshot
|
||||
.into_iter()
|
||||
.filter(|member| !member.eq_ignore_ascii_case(&my_address))
|
||||
.collect();
|
||||
|
||||
let pick_member_handler = {
|
||||
move |member: String| {
|
||||
move |_| {
|
||||
ban_error.set(None);
|
||||
ban_address.set(member.clone());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
rsx! {
|
||||
div { class: "panel chat",
|
||||
div { class: "chat-header",
|
||||
h2 { "Chat" }
|
||||
if let Some(gid) = chat.read().opened_group.clone() {
|
||||
button {
|
||||
class: "ghost mini",
|
||||
onclick: move |_| {
|
||||
let group_id = gid.clone();
|
||||
let addr = my_name_for_leave.clone();
|
||||
// Send a self-ban (leave) request: requester filled by backend
|
||||
spawn(async move {
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::SendBanRequest { group_id: group_id.clone(), user_to_ban: (*addr).clone() })
|
||||
.await;
|
||||
});
|
||||
},
|
||||
"Leave group"
|
||||
}
|
||||
button {
|
||||
class: "ghost mini",
|
||||
onclick: open_ban_modal,
|
||||
"Request ban"
|
||||
}
|
||||
}
|
||||
}
|
||||
if chat.read().opened_group.is_none() {
|
||||
div { class: "hint", "Pick a group to chat." }
|
||||
} else {
|
||||
div { class: "messages",
|
||||
for (i, m) in msgs_for_group.iter().enumerate() {
|
||||
if (*my_name).clone() == m.sender || m.sender.eq_ignore_ascii_case("me") {
|
||||
div { key: "{i}", class: "msg me",
|
||||
span { class: "from", "{m.sender}" }
|
||||
span { class: "body", "{String::from_utf8_lossy(&m.message)}" }
|
||||
}
|
||||
} else if m.sender.eq_ignore_ascii_case("system") {
|
||||
div { key: "{i}", class: "msg system",
|
||||
span { class: "body", "{String::from_utf8_lossy(&m.message)}" }
|
||||
}
|
||||
} else {
|
||||
div { key: "{i}", class: "msg",
|
||||
span { class: "from", "{m.sender}" }
|
||||
span { class: "body", "{String::from_utf8_lossy(&m.message)}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "composer",
|
||||
input {
|
||||
r#type: "text",
|
||||
value: "{msg_input}",
|
||||
oninput: move |e| msg_input.set(e.value()),
|
||||
placeholder: "Type a message…",
|
||||
}
|
||||
button { class: "primary", onclick: send_msg, "Send" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if *show_ban_modal.read() {
|
||||
Modal {
|
||||
title: "Request user ban".to_string(),
|
||||
on_close: close_ban_modal,
|
||||
div { class: "form-row",
|
||||
label { "User address" }
|
||||
input {
|
||||
r#type: "text",
|
||||
value: "{ban_address}",
|
||||
oninput: oninput_ban_address,
|
||||
placeholder: "0x...",
|
||||
}
|
||||
if let Some(error) = &*ban_error.read() {
|
||||
span { class: "input-error", "{error}" }
|
||||
}
|
||||
}
|
||||
if selectable_members.is_empty() {
|
||||
div { class: "hint muted", "No members loaded yet." }
|
||||
} else {
|
||||
div { class: "member-picker",
|
||||
span { class: "helper", "Or pick a member:" }
|
||||
div { class: "member-list",
|
||||
for member in selectable_members.iter() {
|
||||
div {
|
||||
key: "{member}",
|
||||
class: "member-item",
|
||||
div { class: "member-actions",
|
||||
span { class: "member-id mono", "{member}" }
|
||||
button {
|
||||
class: "member-choose",
|
||||
onclick: pick_member_handler(member.clone()),
|
||||
"Choose"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "actions",
|
||||
button { class: "primary", onclick: submit_ban_request, "Submit" }
|
||||
button {
|
||||
class: "ghost",
|
||||
onclick: cancel_ban_modal,
|
||||
"Cancel"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ConsensusSection() -> Element {
|
||||
let chat = use_context::<Signal<ChatState>>();
|
||||
let mut cons = use_context::<Signal<ConsensusState>>();
|
||||
|
||||
let vote_yes = {
|
||||
move |_| {
|
||||
let pending_proposal = cons.read().pending.clone();
|
||||
if let Some(v) = pending_proposal {
|
||||
// Clear the pending proposal immediately to close the vote window
|
||||
cons.write().pending = None;
|
||||
spawn(async move {
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::Vote {
|
||||
group_id: v.group_id.clone(),
|
||||
proposal_id: v.proposal_id,
|
||||
choice: true,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
let vote_no = {
|
||||
move |_| {
|
||||
let pending_proposal = cons.read().pending.clone();
|
||||
if let Some(v) = pending_proposal {
|
||||
// Clear the pending proposal immediately to close the vote window
|
||||
cons.write().pending = None;
|
||||
spawn(async move {
|
||||
let _ = GATEWAY
|
||||
.send(AppCmd::Vote {
|
||||
group_id: v.group_id.clone(),
|
||||
proposal_id: v.proposal_id,
|
||||
choice: false,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let opened = chat.read().opened_group.clone();
|
||||
let pending = cons
|
||||
.read()
|
||||
.pending
|
||||
.clone()
|
||||
.filter(|p| Some(p.group_id.as_str()) == opened.as_deref());
|
||||
|
||||
rsx! {
|
||||
div { class: "panel consensus",
|
||||
h2 { "Consensus" }
|
||||
|
||||
if let Some(_group) = opened {
|
||||
// Steward status
|
||||
div { class: "status",
|
||||
span { class: "muted", "You are " }
|
||||
if cons.read().is_steward {
|
||||
span { class: "good", "a steward" }
|
||||
} else {
|
||||
span { class: "bad", "not a steward" }
|
||||
}
|
||||
}
|
||||
|
||||
// Pending Requests section
|
||||
div { class: "consensus-section",
|
||||
h3 { "Pending Requests" }
|
||||
if cons.read().is_steward && !cons.read().current_epoch_proposals.is_empty() {
|
||||
div { class: "proposals-window",
|
||||
for (action, address) in &cons.read().current_epoch_proposals {
|
||||
div { class: "proposal-item",
|
||||
span { class: "action", "{action}:" }
|
||||
span { class: "value", "{address}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
div { class: "no-data", "No pending requests" }
|
||||
}
|
||||
}
|
||||
|
||||
// Proposal for Vote section
|
||||
div { class: "consensus-section",
|
||||
h3 { "Proposal for Vote" }
|
||||
if let Some(v) = pending {
|
||||
div { class: "proposals-window",
|
||||
div { class: "proposal-item proposal-id",
|
||||
span { class: "action", "Proposal ID:" }
|
||||
span { class: "value", "{v.proposal_id}" }
|
||||
}
|
||||
for (action, id) in convert_group_requests_to_display(&v.group_requests) {
|
||||
div { class: "proposal-item",
|
||||
span { class: "action", "{action}:" }
|
||||
span { class: "value", "{id}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "vote-actions",
|
||||
button { class: "primary", onclick: vote_yes, "YES" }
|
||||
button { class: "ghost", onclick: vote_no, "NO" }
|
||||
}
|
||||
} else {
|
||||
div { class: "no-data", "No proposal for vote" }
|
||||
}
|
||||
}
|
||||
|
||||
// Latest Decisions section
|
||||
div { class: "consensus-section",
|
||||
h3 { "Latest Decisions" }
|
||||
if cons.read().latest_results.is_empty() {
|
||||
div { class: "no-data", "No latest decisions" }
|
||||
} else {
|
||||
div { class: "results-window",
|
||||
for (vid, res, timestamp_ms) in cons.read().latest_results.iter().rev() {
|
||||
div { class: "result-item",
|
||||
span { class: "proposal-id", "{vid}" }
|
||||
span {
|
||||
class: match res {
|
||||
Outcome::Accepted => "outcome accepted",
|
||||
Outcome::Rejected => "outcome rejected",
|
||||
Outcome::Unspecified => "outcome unspecified",
|
||||
},
|
||||
match res {
|
||||
Outcome::Accepted => "Accepted",
|
||||
Outcome::Rejected => "Rejected",
|
||||
Outcome::Unspecified => "Unspecified",
|
||||
}
|
||||
}
|
||||
span { class: "timestamp",
|
||||
"{format_timestamp(*timestamp_ms)}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
div { class: "hint", "Open a group to see proposals & voting." }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── Modal ───────────────────────────
|
||||
|
||||
#[derive(Props, PartialEq, Clone)]
|
||||
struct ModalProps {
|
||||
title: String,
|
||||
children: Element,
|
||||
on_close: EventHandler,
|
||||
}
|
||||
fn Modal(props: ModalProps) -> Element {
|
||||
rsx! {
|
||||
div { class: "modal-backdrop", onclick: move |_| (props.on_close)(()),
|
||||
div { class: "modal", onclick: move |e| e.stop_propagation(),
|
||||
div { class: "modal-head",
|
||||
h3 { "{props.title}" }
|
||||
button { class: "icon", onclick: move |_| (props.on_close)(()), "✕" }
|
||||
}
|
||||
div { class: "modal-body", {props.children} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
build.rs
2
build.rs
@@ -1,9 +1,9 @@
|
||||
fn main() -> Result<(), std::io::Error> {
|
||||
prost_build::compile_protos(
|
||||
&[
|
||||
"src/protos/messages/v1/consensus.proto",
|
||||
"src/protos/messages/v1/welcome.proto",
|
||||
"src/protos/messages/v1/application.proto",
|
||||
"src/protos/messages/v1/consensus.proto",
|
||||
],
|
||||
&["src/protos/"],
|
||||
)?;
|
||||
|
||||
27
crates/de_mls_gateway/Cargo.toml
Normal file
27
crates/de_mls_gateway/Cargo.toml
Normal file
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "de_mls_gateway"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
tokio = { version = "1.43.0", features = [
|
||||
"macros",
|
||||
"rt-multi-thread",
|
||||
"sync",
|
||||
"time",
|
||||
] }
|
||||
anyhow = "1.0.100"
|
||||
kameo = "0.13.0"
|
||||
futures = "0.3.31"
|
||||
uuid = { version = "1.18.1", features = ["v4", "serde"] }
|
||||
|
||||
de_mls_ui_protocol = { path = "../de_mls_ui_protocol" }
|
||||
ds = { path = "../../ds" }
|
||||
mls_crypto = { path = "../../mls_crypto" }
|
||||
once_cell = "1.21.3"
|
||||
parking_lot = "0.12.5"
|
||||
de_mls = { path = "../../" }
|
||||
tracing = "0.1.41"
|
||||
tracing-subscriber = "0.3.20"
|
||||
hex = "0.4"
|
||||
151
crates/de_mls_gateway/src/forwarder.rs
Normal file
151
crates/de_mls_gateway/src/forwarder.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
use kameo::actor::ActorRef;
|
||||
|
||||
use std::sync::{atomic::Ordering, Arc};
|
||||
use tracing::info;
|
||||
|
||||
use de_mls::{
|
||||
message::MessageType,
|
||||
protos::de_mls::messages::v1::{app_message, ConversationMessage},
|
||||
user::{User, UserAction},
|
||||
user_actor::LeaveGroupRequest,
|
||||
user_app_instance::CoreCtx,
|
||||
};
|
||||
use de_mls_ui_protocol::v1::AppEvent;
|
||||
|
||||
use crate::Gateway;
|
||||
|
||||
impl Gateway {
|
||||
pub(crate) fn spawn_consensus_forwarder(&self, core: Arc<CoreCtx>) -> anyhow::Result<()> {
|
||||
let evt_tx = self.evt_tx.clone();
|
||||
let mut rx = core.consensus.subscribe_decisions();
|
||||
|
||||
tokio::spawn(async move {
|
||||
tracing::info!("gateway: consensus forwarder started");
|
||||
while let Ok(res) = rx.recv().await {
|
||||
let _ = evt_tx.unbounded_send(AppEvent::ProposalDecided(res));
|
||||
}
|
||||
tracing::info!("gateway: consensus forwarder ended");
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Spawn the pubsub forwarder once, after first successful login.
|
||||
pub(crate) fn spawn_waku_forwarder(&self, core: Arc<CoreCtx>, user: ActorRef<User>) {
|
||||
if self.started.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
|
||||
let evt_tx = self.evt_tx.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut rx = core.app_state.pubsub.subscribe();
|
||||
tracing::info!("gateway: pubsub forwarder started");
|
||||
|
||||
while let Ok(wmsg) = rx.recv().await {
|
||||
let content_topic = wmsg.content_topic.clone();
|
||||
|
||||
// fast-topic filter
|
||||
if !core.topics.contains(&content_topic).await {
|
||||
continue;
|
||||
}
|
||||
|
||||
// hand over to user actor to decide action
|
||||
let action = match user.ask(wmsg).await {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
tracing::warn!("user.ask failed: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// route the action
|
||||
let res = match action {
|
||||
UserAction::SendToWaku(msg) => core
|
||||
.app_state
|
||||
.waku_node
|
||||
.send(msg)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("error sending waku message: {e}")),
|
||||
|
||||
UserAction::SendToApp(app_msg) => {
|
||||
// voting
|
||||
let res = match &app_msg.payload {
|
||||
Some(app_message::Payload::VotePayload(vp)) => evt_tx
|
||||
.unbounded_send(AppEvent::VoteRequested(vp.clone()))
|
||||
.map_err(|e| {
|
||||
anyhow::anyhow!("error sending vote requested event: {e}")
|
||||
})
|
||||
.and_then(|_| {
|
||||
// Also clear current epoch proposals when voting starts
|
||||
evt_tx.unbounded_send(AppEvent::CurrentEpochProposalsCleared {
|
||||
group_id: vp.group_id.clone(),
|
||||
})
|
||||
.map_err(|e| {
|
||||
anyhow::anyhow!("error sending clear current epoch proposals event: {e}")
|
||||
})
|
||||
}),
|
||||
Some(app_message::Payload::ProposalAdded(pa)) => evt_tx
|
||||
.unbounded_send(AppEvent::from(pa.clone()))
|
||||
.map_err(|e| {
|
||||
anyhow::anyhow!("error sending proposal added event: {e}")
|
||||
}),
|
||||
Some(app_message::Payload::BanRequest(br)) => evt_tx
|
||||
.unbounded_send(AppEvent::from(br.clone()))
|
||||
.map_err(|e| {
|
||||
anyhow::anyhow!("error sending proposal added event (ban request): {e}")
|
||||
}),
|
||||
Some(app_message::Payload::ConversationMessage(cm)) => evt_tx
|
||||
.unbounded_send(AppEvent::ChatMessage(ConversationMessage {
|
||||
message: cm.message.clone(),
|
||||
sender: cm.sender.clone(),
|
||||
group_name: cm.group_name.clone(),
|
||||
}))
|
||||
.map_err(|e| anyhow::anyhow!("error sending chat message: {e}")),
|
||||
_ => {
|
||||
AppEvent::Error(format!("Invalid app message: {:?}", app_msg.payload.unwrap().message_type()));
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
};
|
||||
match res {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => Err(anyhow::anyhow!("error sending app message: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
UserAction::LeaveGroup(group_name) => {
|
||||
let _ = user
|
||||
.ask(LeaveGroupRequest {
|
||||
group_name: group_name.clone(),
|
||||
})
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("error leaving group: {e}"));
|
||||
|
||||
core.topics.remove_many(&group_name).await;
|
||||
info!("Leave group: {:?}", &group_name);
|
||||
|
||||
let _ = evt_tx
|
||||
.unbounded_send(AppEvent::GroupRemoved(group_name.clone()))
|
||||
.map_err(|e| anyhow::anyhow!("error sending group removed event: {e}"));
|
||||
|
||||
let _ = evt_tx
|
||||
.unbounded_send(AppEvent::ChatMessage(ConversationMessage {
|
||||
message: format!("You're removed from the group {group_name}")
|
||||
.into_bytes(),
|
||||
sender: "system".to_string(),
|
||||
group_name: group_name.clone(),
|
||||
}))
|
||||
.map_err(|e| anyhow::anyhow!("error sending chat message: {e}"));
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
UserAction::DoNothing => Ok(()),
|
||||
};
|
||||
|
||||
if let Err(e) = res {
|
||||
tracing::warn!("error handling waku action: {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!("gateway: pubsub forwarder ended");
|
||||
});
|
||||
}
|
||||
}
|
||||
281
crates/de_mls_gateway/src/group.rs
Normal file
281
crates/de_mls_gateway/src/group.rs
Normal file
@@ -0,0 +1,281 @@
|
||||
use std::time::Duration;
|
||||
use tracing::info;
|
||||
|
||||
use de_mls::{
|
||||
protos::de_mls::messages::v1::{app_message, BanRequest},
|
||||
steward,
|
||||
user::UserAction,
|
||||
user_actor::{
|
||||
CreateGroupRequest, GetCurrentEpochProposalsRequest, GetGroupMembersRequest,
|
||||
GetProposalsForStewardVotingRequest, IsStewardStatusRequest, SendGroupMessage,
|
||||
StartStewardEpochRequest, StewardMessageRequest, UserVoteRequest,
|
||||
},
|
||||
user_app_instance::STEWARD_EPOCH,
|
||||
};
|
||||
use de_mls_ui_protocol::v1::AppEvent;
|
||||
|
||||
use crate::Gateway;
|
||||
|
||||
impl Gateway {
|
||||
pub async fn create_group(&self, group_name: String) -> anyhow::Result<()> {
|
||||
let core = self.core();
|
||||
let user = self.user()?;
|
||||
user.ask(CreateGroupRequest {
|
||||
group_name: group_name.clone(),
|
||||
is_creation: true,
|
||||
})
|
||||
.await?;
|
||||
core.topics.add_many(&group_name).await;
|
||||
core.groups.insert(group_name.clone()).await;
|
||||
info!("User start sending steward message for group {group_name:?}");
|
||||
let user_clone = user.clone();
|
||||
let group_name_clone = group_name.clone();
|
||||
let evt_tx_clone = self.evt_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(STEWARD_EPOCH));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
// Step 1: Start steward epoch - check for proposals and start epoch if needed
|
||||
let proposals_count = match user_clone
|
||||
.ask(StartStewardEpochRequest {
|
||||
group_name: group_name.clone(),
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(count) => count,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"start steward epoch request failed for group {group_name:?}: {e}"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Step 2: Send new steward key to the waku node for new epoch
|
||||
let msg = match user_clone
|
||||
.ask(StewardMessageRequest {
|
||||
group_name: group_name.clone(),
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(msg) => msg,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"steward message request failed for group {group_name:?}: {e}"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Err(e) = core.app_state.waku_node.send(msg).await {
|
||||
tracing::warn!("failed to send steward message for group {group_name:?}: {e}");
|
||||
continue;
|
||||
}
|
||||
|
||||
if proposals_count == 0 {
|
||||
info!("No proposals to vote on for group: {group_name}, completing epoch without voting");
|
||||
} else {
|
||||
info!("Found {proposals_count} proposals to vote on for group: {group_name}");
|
||||
|
||||
// Step 3: Start voting process - steward gets proposals for voting
|
||||
let action = match user_clone
|
||||
.ask(GetProposalsForStewardVotingRequest {
|
||||
group_name: group_name.clone(),
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(action) => action,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"get proposals for steward voting failed for group {group_name:?}: {e}"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Step 4: Send proposals to ws to steward to vote or do nothing if no proposals
|
||||
// After voting, steward sends vote and proposal to waku node and start consensus process
|
||||
match action {
|
||||
UserAction::SendToApp(app_msg) => {
|
||||
if let Some(app_message::Payload::VotePayload(vp)) = &app_msg.payload {
|
||||
if let Err(e) =
|
||||
evt_tx_clone.unbounded_send(AppEvent::VoteRequested(vp.clone()))
|
||||
{
|
||||
tracing::warn!("failed to send vote requested event: {e}");
|
||||
}
|
||||
|
||||
// Also clear current epoch proposals when voting starts
|
||||
if let Err(e) = evt_tx_clone.unbounded_send(
|
||||
AppEvent::CurrentEpochProposalsCleared {
|
||||
group_id: group_name.clone(),
|
||||
},
|
||||
) {
|
||||
tracing::warn!("failed to send proposals cleared event: {e}");
|
||||
}
|
||||
}
|
||||
if let Some(app_message::Payload::ProposalAdded(pa)) = &app_msg.payload
|
||||
{
|
||||
if let Err(e) =
|
||||
evt_tx_clone.unbounded_send(AppEvent::from(pa.clone()))
|
||||
{
|
||||
tracing::warn!("failed to send proposal added event: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
UserAction::DoNothing => {
|
||||
info!("No action to take for group: {group_name}");
|
||||
return Ok(());
|
||||
}
|
||||
_ => {
|
||||
return Err(anyhow::anyhow!("Invalid user action: {action}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
tracing::debug!("User started sending steward message for group {group_name_clone:?}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn join_group(&self, group_name: String) -> anyhow::Result<()> {
|
||||
let core = self.core();
|
||||
let user = self.user()?;
|
||||
user.ask(CreateGroupRequest {
|
||||
group_name: group_name.clone(),
|
||||
is_creation: false,
|
||||
})
|
||||
.await?;
|
||||
core.topics.add_many(&group_name).await;
|
||||
core.groups.insert(group_name.clone()).await;
|
||||
tracing::debug!("User joined group {group_name}");
|
||||
tracing::debug!(
|
||||
"User have topic for group {:?}",
|
||||
core.topics.snapshot().await
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_message(&self, group_name: String, message: String) -> anyhow::Result<()> {
|
||||
let core = self.core();
|
||||
let user = self.user()?;
|
||||
let pmt = user
|
||||
.ask(SendGroupMessage {
|
||||
message: message.clone().into_bytes(),
|
||||
group_name: group_name.clone(),
|
||||
})
|
||||
.await?;
|
||||
core.app_state.waku_node.send(pmt).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_ban_request(
|
||||
&self,
|
||||
group_name: String,
|
||||
user_to_ban: String,
|
||||
) -> anyhow::Result<()> {
|
||||
let core = self.core();
|
||||
let user = self.user()?;
|
||||
|
||||
let ban_request = BanRequest {
|
||||
user_to_ban: user_to_ban.clone(),
|
||||
requester: String::new(),
|
||||
group_name: group_name.clone(),
|
||||
};
|
||||
|
||||
let msg = user
|
||||
.ask(de_mls::user_actor::BuildBanMessage {
|
||||
ban_request,
|
||||
group_name: group_name.clone(),
|
||||
})
|
||||
.await?;
|
||||
match msg {
|
||||
UserAction::SendToWaku(msg) => {
|
||||
core.app_state.waku_node.send(msg).await?;
|
||||
}
|
||||
UserAction::SendToApp(app_msg) => {
|
||||
let event = match app_msg.payload {
|
||||
Some(app_message::Payload::ProposalAdded(ref proposal)) => {
|
||||
AppEvent::from(proposal.clone())
|
||||
}
|
||||
Some(app_message::Payload::BanRequest(ref ban_request)) => {
|
||||
AppEvent::from(ban_request.clone())
|
||||
}
|
||||
_ => return Err(anyhow::anyhow!("Invalid user action")),
|
||||
};
|
||||
self.push_event(event);
|
||||
}
|
||||
_ => return Err(anyhow::anyhow!("Invalid user action")),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn process_user_vote(
|
||||
&self,
|
||||
group_name: String,
|
||||
proposal_id: u32,
|
||||
vote: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
let user = self.user()?;
|
||||
|
||||
let user_vote_result = user
|
||||
.ask(UserVoteRequest {
|
||||
group_name: group_name.clone(),
|
||||
proposal_id,
|
||||
vote,
|
||||
})
|
||||
.await?;
|
||||
if let Some(waku_msg) = user_vote_result {
|
||||
self.core().app_state.waku_node.send(waku_msg).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn group_list(&self) -> Vec<String> {
|
||||
let core = self.core();
|
||||
core.groups.all().await
|
||||
}
|
||||
|
||||
pub async fn get_steward_status(&self, group_name: String) -> anyhow::Result<bool> {
|
||||
let user = self.user()?;
|
||||
let is_steward = user.ask(IsStewardStatusRequest { group_name }).await?;
|
||||
Ok(is_steward)
|
||||
}
|
||||
|
||||
/// Get current epoch proposals for the given group
|
||||
pub async fn get_current_epoch_proposals(
|
||||
&self,
|
||||
group_name: String,
|
||||
) -> anyhow::Result<Vec<(String, String)>> {
|
||||
let user = self.user()?;
|
||||
|
||||
let proposals = user
|
||||
.ask(GetCurrentEpochProposalsRequest { group_name })
|
||||
.await?;
|
||||
let display_proposals: Vec<(String, String)> = proposals
|
||||
.iter()
|
||||
.map(|proposal| match proposal {
|
||||
steward::GroupUpdateRequest::AddMember(kp) => {
|
||||
let address = format!(
|
||||
"0x{}",
|
||||
hex::encode(kp.leaf_node().credential().serialized_content())
|
||||
);
|
||||
("Add Member".to_string(), address)
|
||||
}
|
||||
steward::GroupUpdateRequest::RemoveMember(id) => {
|
||||
("Remove Member".to_string(), id.clone())
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Ok(display_proposals)
|
||||
}
|
||||
|
||||
pub async fn get_group_members(&self, group_name: String) -> anyhow::Result<Vec<String>> {
|
||||
let user = self.user()?;
|
||||
let members = user
|
||||
.ask(GetGroupMembersRequest {
|
||||
group_name: group_name.clone(),
|
||||
})
|
||||
.await?;
|
||||
Ok(members)
|
||||
}
|
||||
}
|
||||
138
crates/de_mls_gateway/src/lib.rs
Normal file
138
crates/de_mls_gateway/src/lib.rs
Normal file
@@ -0,0 +1,138 @@
|
||||
//! de_mls_gateway: a thin facade between UI (AppCmd/AppEvent) and the core runtime.
|
||||
//!
|
||||
//! Responsibilities:
|
||||
//! - Own a single event pipe UI <- gateway (`AppEvent`)
|
||||
//! - Provide a command entrypoint UI -> gateway (`send(AppCmd)`)
|
||||
//! - Hold references to the core context (`CoreCtx`) and current user actor
|
||||
//! - Offer small helper methods (login_with_private_key, etc.)
|
||||
use futures::{
|
||||
channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
|
||||
StreamExt,
|
||||
};
|
||||
use kameo::actor::ActorRef;
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::RwLock;
|
||||
use std::sync::{atomic::AtomicBool, Arc};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use de_mls::{
|
||||
user::User,
|
||||
user_app_instance::{create_user_instance, CoreCtx},
|
||||
};
|
||||
use de_mls_ui_protocol::v1::{AppCmd, AppEvent};
|
||||
|
||||
mod forwarder;
|
||||
mod group;
|
||||
// Global, process-wide gateway instance
|
||||
pub static GATEWAY: Lazy<Gateway> = Lazy::new(Gateway::new);
|
||||
|
||||
/// Helper to set the core context once during startup (called by ui_bridge).
|
||||
pub fn init_core(core: Arc<CoreCtx>) {
|
||||
GATEWAY.set_core(core);
|
||||
}
|
||||
|
||||
pub struct Gateway {
|
||||
// UI events (gateway -> UI)
|
||||
// A channel that sends AppEvents to the UI.
|
||||
evt_tx: UnboundedSender<AppEvent>,
|
||||
// A channel that receives AppEvents from the UI.
|
||||
evt_rx: Mutex<UnboundedReceiver<AppEvent>>,
|
||||
|
||||
// UI commands (UI -> gateway)
|
||||
// A channel that sends AppCommands to the gateway (ui_bridge registers the sender here).
|
||||
// It gives the UI an async door to submit AppCmds back to the gateway (`Gateway::send(AppCmd)`).
|
||||
cmd_tx: RwLock<Option<UnboundedSender<AppCmd>>>,
|
||||
|
||||
// It anchors the shared references to consensus, topics, app_state, etc.
|
||||
core: RwLock<Option<Arc<CoreCtx>>>, // set once during startup
|
||||
|
||||
// Current logged-in user actor
|
||||
user: RwLock<Option<ActorRef<User>>>,
|
||||
// Flag that guards against spawning the Waku forwarder more than once.
|
||||
// It's initialized to false and set to true after the first successful login.
|
||||
started: AtomicBool,
|
||||
}
|
||||
|
||||
impl Gateway {
|
||||
fn new() -> Self {
|
||||
let (evt_tx, evt_rx) = unbounded();
|
||||
Self {
|
||||
evt_tx,
|
||||
evt_rx: Mutex::new(evt_rx),
|
||||
cmd_tx: RwLock::new(None),
|
||||
core: RwLock::new(None),
|
||||
user: RwLock::new(None),
|
||||
started: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Called once by the bootstrap (ui_bridge) to provide the core context.
|
||||
pub fn set_core(&self, core: Arc<CoreCtx>) {
|
||||
*self.core.write() = Some(core);
|
||||
}
|
||||
|
||||
pub fn core(&self) -> Arc<CoreCtx> {
|
||||
self.core
|
||||
.read()
|
||||
.as_ref()
|
||||
.expect("Gateway core not initialized")
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// ui_bridge registers its command sender so `send` can work.
|
||||
pub fn register_cmd_sink(&self, tx: UnboundedSender<AppCmd>) {
|
||||
*self.cmd_tx.write() = Some(tx);
|
||||
}
|
||||
|
||||
/// Push an event to the UI.
|
||||
pub fn push_event(&self, evt: AppEvent) {
|
||||
let _ = self.evt_tx.unbounded_send(evt);
|
||||
}
|
||||
|
||||
/// Await next event on the UI side.
|
||||
pub async fn next_event(&self) -> Option<AppEvent> {
|
||||
let mut rx = self.evt_rx.lock().await;
|
||||
rx.next().await
|
||||
}
|
||||
|
||||
/// UI convenience: enqueue a command (UI -> gateway).
|
||||
pub async fn send(&self, cmd: AppCmd) -> anyhow::Result<()> {
|
||||
if let Some(tx) = self.cmd_tx.read().clone() {
|
||||
tx.unbounded_send(cmd)
|
||||
.map_err(|e| anyhow::anyhow!("send cmd failed: {e}"))
|
||||
} else {
|
||||
Err(anyhow::anyhow!("cmd sink not registered"))
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── High-level helpers ───────────────────────────
|
||||
|
||||
/// Create the user actor with a private key (no group yet).
|
||||
/// Returns a derived display name (e.g., address string).
|
||||
pub async fn login_with_private_key(&self, private_key: String) -> anyhow::Result<String> {
|
||||
let core = self.core();
|
||||
let consensus_service = core.consensus.as_ref().clone();
|
||||
|
||||
// Create user actor via core helper (you implement this inside your core)
|
||||
let (user_ref, user_address) = create_user_instance(
|
||||
private_key.clone(),
|
||||
core.app_state.clone(),
|
||||
&consensus_service,
|
||||
)
|
||||
.await?;
|
||||
|
||||
*self.user.write() = Some(user_ref.clone());
|
||||
|
||||
self.spawn_waku_forwarder(core.clone(), user_ref.clone());
|
||||
self.spawn_consensus_forwarder(core.clone())?;
|
||||
Ok(user_address)
|
||||
}
|
||||
|
||||
/// Get a copy of the current user ref (if logged in).
|
||||
pub fn user(&self) -> anyhow::Result<ActorRef<User>> {
|
||||
self.user
|
||||
.read()
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("user not logged in"))
|
||||
}
|
||||
}
|
||||
15
crates/de_mls_ui_protocol/Cargo.toml
Normal file
15
crates/de_mls_ui_protocol/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "de_mls_ui_protocol"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1.0"
|
||||
serde = { version = "1.0.163", features = ["derive"] }
|
||||
uuid = { version = "1.18.1", features = ["v4", "serde"] }
|
||||
thiserror = "2.0.17"
|
||||
|
||||
de_mls = { path = "../../" }
|
||||
mls_crypto = { path = "../../mls_crypto" }
|
||||
127
crates/de_mls_ui_protocol/src/lib.rs
Normal file
127
crates/de_mls_ui_protocol/src/lib.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
//! UI <-> Gateway protocol (PoC). Keep it dependency-light (serde only).
|
||||
// crates/de_mls_ui_protocol/src/lib.rs
|
||||
pub mod v1 {
|
||||
use de_mls::{
|
||||
message::MessageType,
|
||||
protos::{
|
||||
consensus::v1::{ProposalResult, VotePayload},
|
||||
de_mls::messages::v1::{BanRequest, ConversationMessage, ProposalAdded},
|
||||
},
|
||||
};
|
||||
use mls_crypto::identity::normalize_wallet_address;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub enum AppCmd {
|
||||
Login {
|
||||
private_key: String,
|
||||
},
|
||||
ListGroups,
|
||||
CreateGroup {
|
||||
name: String,
|
||||
},
|
||||
JoinGroup {
|
||||
name: String,
|
||||
},
|
||||
EnterGroup {
|
||||
group_id: String,
|
||||
},
|
||||
SendMessage {
|
||||
group_id: String,
|
||||
body: String,
|
||||
},
|
||||
LoadHistory {
|
||||
group_id: String,
|
||||
},
|
||||
Vote {
|
||||
group_id: String,
|
||||
proposal_id: u32,
|
||||
choice: bool,
|
||||
},
|
||||
LeaveGroup {
|
||||
group_id: String,
|
||||
},
|
||||
GetStewardStatus {
|
||||
group_id: String,
|
||||
},
|
||||
GetCurrentEpochProposals {
|
||||
group_id: String,
|
||||
},
|
||||
SendBanRequest {
|
||||
group_id: String,
|
||||
user_to_ban: String,
|
||||
},
|
||||
GetGroupMembers {
|
||||
group_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[non_exhaustive]
|
||||
pub enum AppEvent {
|
||||
LoggedIn(String),
|
||||
Groups(Vec<String>),
|
||||
GroupCreated(String),
|
||||
GroupRemoved(String),
|
||||
EnteredGroup {
|
||||
group_id: String,
|
||||
},
|
||||
ChatMessage(ConversationMessage),
|
||||
LeaveGroup {
|
||||
group_id: String,
|
||||
},
|
||||
|
||||
StewardStatus {
|
||||
group_id: String,
|
||||
is_steward: bool,
|
||||
},
|
||||
|
||||
VoteRequested(VotePayload),
|
||||
ProposalDecided(ProposalResult),
|
||||
CurrentEpochProposals {
|
||||
group_id: String,
|
||||
proposals: Vec<(String, String)>,
|
||||
},
|
||||
ProposalAdded {
|
||||
group_id: String,
|
||||
action: String,
|
||||
address: String,
|
||||
},
|
||||
CurrentEpochProposalsCleared {
|
||||
group_id: String,
|
||||
},
|
||||
GroupMembers {
|
||||
group_id: String,
|
||||
members: Vec<String>,
|
||||
},
|
||||
Error(String),
|
||||
}
|
||||
|
||||
impl From<ProposalAdded> for AppEvent {
|
||||
fn from(proposal_added: ProposalAdded) -> Self {
|
||||
AppEvent::ProposalAdded {
|
||||
group_id: proposal_added.group_id.clone(),
|
||||
action: proposal_added
|
||||
.request
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.message_type()
|
||||
.to_string(),
|
||||
address: normalize_wallet_address(
|
||||
&proposal_added.request.as_ref().unwrap().wallet_address,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BanRequest> for AppEvent {
|
||||
fn from(ban_request: BanRequest) -> Self {
|
||||
AppEvent::ProposalAdded {
|
||||
group_id: ban_request.group_name.clone(),
|
||||
action: "Remove Member".to_string(),
|
||||
address: ban_request.user_to_ban.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
15
crates/ui_bridge/Cargo.toml
Normal file
15
crates/ui_bridge/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "ui_bridge"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
futures = "0.3.31"
|
||||
anyhow = "1.0.100"
|
||||
uuid = { version = "1.18.1", features = ["v4", "serde"] }
|
||||
tracing = "0.1.41"
|
||||
tokio = { version = "1.47.1", features = ["macros", "rt-multi-thread"] }
|
||||
|
||||
de_mls_gateway = { path = "../de_mls_gateway" }
|
||||
de_mls_ui_protocol = { path = "../de_mls_ui_protocol" }
|
||||
de_mls = { path = "../../" }
|
||||
201
crates/ui_bridge/src/lib.rs
Normal file
201
crates/ui_bridge/src/lib.rs
Normal file
@@ -0,0 +1,201 @@
|
||||
//! ui_bridge
|
||||
//!
|
||||
//! Owns the command loop translating `AppCmd` -> core calls
|
||||
//! and pushing `AppEvent` back to the UI via the Gateway.
|
||||
//!
|
||||
//! It ensures there is a Tokio runtime (desktop app may not have one yet).
|
||||
|
||||
// crates/ui_bridge/src/lib.rs
|
||||
use futures::channel::mpsc::{unbounded, UnboundedReceiver};
|
||||
use futures::StreamExt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use de_mls::protos::de_mls::messages::v1::ConversationMessage;
|
||||
use de_mls::user_app_instance::CoreCtx;
|
||||
use de_mls_gateway::{init_core, GATEWAY};
|
||||
use de_mls_ui_protocol::v1::{AppCmd, AppEvent};
|
||||
|
||||
/// Call once during process startup (before launching the Dioxus UI).
|
||||
pub fn start_ui_bridge(core: Arc<CoreCtx>) {
|
||||
// 1) Give the gateway access to the core context.
|
||||
init_core(core);
|
||||
|
||||
// 2) Create a command channel UI -> gateway and register the sender.
|
||||
let (cmd_tx, cmd_rx) = unbounded::<AppCmd>();
|
||||
GATEWAY.register_cmd_sink(cmd_tx);
|
||||
|
||||
// 3) Drive the dispatcher loop on a Tokio runtime
|
||||
if let Ok(handle) = tokio::runtime::Handle::try_current() {
|
||||
handle.spawn(async move {
|
||||
if let Err(e) = ui_loop(cmd_rx).await {
|
||||
tracing::error!("ui_loop crashed: {e}");
|
||||
}
|
||||
});
|
||||
} else {
|
||||
std::thread::Builder::new()
|
||||
.name("ui-bridge".into())
|
||||
.spawn(move || {
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("tokio runtime");
|
||||
rt.block_on(async move {
|
||||
if let Err(e) = ui_loop(cmd_rx).await {
|
||||
eprintln!("ui_loop crashed: {e:?}");
|
||||
}
|
||||
});
|
||||
})
|
||||
.expect("spawn ui-bridge");
|
||||
}
|
||||
}
|
||||
|
||||
async fn ui_loop(mut cmd_rx: UnboundedReceiver<AppCmd>) -> anyhow::Result<()> {
|
||||
while let Some(cmd) = cmd_rx.next().await {
|
||||
match cmd {
|
||||
// ───────────── Authentication / session ─────────────
|
||||
AppCmd::Login { private_key } => {
|
||||
match GATEWAY.login_with_private_key(private_key).await {
|
||||
Ok(derived_name) => GATEWAY.push_event(AppEvent::LoggedIn(derived_name)),
|
||||
Err(e) => GATEWAY.push_event(AppEvent::Error(format!("Login failed: {e}"))),
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────── Groups ─────────────
|
||||
AppCmd::ListGroups => {
|
||||
let groups = GATEWAY.group_list().await;
|
||||
GATEWAY.push_event(AppEvent::Groups(groups));
|
||||
}
|
||||
|
||||
AppCmd::CreateGroup { name } => {
|
||||
GATEWAY.create_group(name.clone()).await?;
|
||||
|
||||
let groups = GATEWAY.group_list().await;
|
||||
GATEWAY.push_event(AppEvent::Groups(groups));
|
||||
}
|
||||
|
||||
AppCmd::JoinGroup { name } => {
|
||||
GATEWAY.join_group(name.clone()).await?;
|
||||
|
||||
let groups = GATEWAY.group_list().await;
|
||||
GATEWAY.push_event(AppEvent::Groups(groups));
|
||||
}
|
||||
|
||||
AppCmd::EnterGroup { group_id } => {
|
||||
GATEWAY.push_event(AppEvent::EnteredGroup { group_id });
|
||||
}
|
||||
|
||||
AppCmd::LeaveGroup { group_id } => {
|
||||
GATEWAY.push_event(AppEvent::LeaveGroup { group_id });
|
||||
}
|
||||
|
||||
AppCmd::GetGroupMembers { group_id } => {
|
||||
match GATEWAY.get_group_members(group_id.clone()).await {
|
||||
Ok(members) => {
|
||||
GATEWAY.push_event(AppEvent::GroupMembers { group_id, members });
|
||||
}
|
||||
Err(e) => {
|
||||
GATEWAY
|
||||
.push_event(AppEvent::Error(format!("Get group members failed: {e}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AppCmd::SendBanRequest {
|
||||
group_id,
|
||||
user_to_ban,
|
||||
} => {
|
||||
if let Err(e) = GATEWAY
|
||||
.send_ban_request(group_id.clone(), user_to_ban.clone())
|
||||
.await
|
||||
{
|
||||
GATEWAY.push_event(AppEvent::Error(format!("Send ban request failed: {e}")));
|
||||
} else {
|
||||
GATEWAY.push_event(AppEvent::ChatMessage(ConversationMessage {
|
||||
message: "You requested to leave or ban user from the group"
|
||||
.to_string()
|
||||
.into_bytes(),
|
||||
sender: "system".to_string(),
|
||||
group_name: group_id.clone(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────── Chat ─────────────
|
||||
AppCmd::SendMessage { group_id, body } => {
|
||||
GATEWAY.push_event(AppEvent::ChatMessage(ConversationMessage {
|
||||
message: body.as_bytes().to_vec(),
|
||||
sender: "me".to_string(),
|
||||
group_name: group_id.clone(),
|
||||
}));
|
||||
|
||||
GATEWAY.send_message(group_id, body).await?;
|
||||
}
|
||||
|
||||
AppCmd::LoadHistory { group_id } => {
|
||||
// TODO: load from storage; stub:
|
||||
GATEWAY.push_event(AppEvent::ChatMessage(ConversationMessage {
|
||||
message: "History loaded (stub)".as_bytes().to_vec(),
|
||||
sender: "system".to_string(),
|
||||
group_name: group_id.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
// ───────────── Consensus ─────────────
|
||||
AppCmd::Vote {
|
||||
group_id,
|
||||
proposal_id,
|
||||
choice,
|
||||
} => {
|
||||
// Process the user vote:
|
||||
// if it come from the user, send the vote result to Waku
|
||||
// if it come from the steward, just process it and return None
|
||||
GATEWAY
|
||||
.process_user_vote(group_id.clone(), proposal_id, choice)
|
||||
.await?;
|
||||
|
||||
GATEWAY.push_event(AppEvent::ChatMessage(ConversationMessage {
|
||||
message: format!(
|
||||
"Your vote ({}) has been submitted for proposal {proposal_id}",
|
||||
if choice { "YES" } else { "NO" }
|
||||
)
|
||||
.as_bytes()
|
||||
.to_vec(),
|
||||
sender: "system".to_string(),
|
||||
group_name: group_id.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
AppCmd::GetCurrentEpochProposals { group_id } => {
|
||||
match GATEWAY.get_current_epoch_proposals(group_id.clone()).await {
|
||||
Ok(proposals) => {
|
||||
GATEWAY.push_event(AppEvent::CurrentEpochProposals {
|
||||
group_id,
|
||||
proposals,
|
||||
});
|
||||
}
|
||||
Err(e) => GATEWAY.push_event(AppEvent::Error(format!(
|
||||
"Get current epoch proposals failed: {e}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
AppCmd::GetStewardStatus { group_id } => {
|
||||
match GATEWAY.get_steward_status(group_id.clone()).await {
|
||||
Ok(is_steward) => {
|
||||
GATEWAY.push_event(AppEvent::StewardStatus {
|
||||
group_id,
|
||||
is_steward,
|
||||
});
|
||||
}
|
||||
Err(e) => GATEWAY
|
||||
.push_event(AppEvent::Error(format!("Get steward status failed: {e}"))),
|
||||
}
|
||||
}
|
||||
|
||||
other => {
|
||||
tracing::warn!("unhandled AppCmd: {:?}", other);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
name: ${NAME}
|
||||
services:
|
||||
frontend:
|
||||
build:
|
||||
context: frontend
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- ${FRONTEND_PORT}:5173
|
||||
environment:
|
||||
- PUBLIC_API_URL=http://127.0.0.1:${BACKEND_PORT}
|
||||
- PUBLIC_WEBSOCKET_URL=ws://127.0.0.1:${BACKEND_PORT}
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- ${BACKEND_PORT}:3000
|
||||
environment:
|
||||
- RUST_LOG=info
|
||||
- NODE_PORT=${NODE_PORT}
|
||||
- PEER_ADDRESSES=${PEER_ADDRESSES}
|
||||
@@ -26,5 +26,5 @@ thiserror = "1.0.39"
|
||||
serde_json = "1.0"
|
||||
serde = "1.0.163"
|
||||
|
||||
env_logger = "0.11.5"
|
||||
log = "0.4.22"
|
||||
tracing = "0.1.41"
|
||||
tracing-subscriber = "0.3.20"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::borrow::Cow;
|
||||
use waku_bindings::{node::PubsubTopic, Encoding, WakuContentTopic};
|
||||
|
||||
pub mod topic_filter;
|
||||
pub mod waku_actor;
|
||||
|
||||
pub const GROUP_VERSION: &str = "1";
|
||||
|
||||
52
ds/src/topic_filter.rs
Normal file
52
ds/src/topic_filter.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
//! This module contains the topic filter for the Waku node
|
||||
use tokio::sync::RwLock;
|
||||
use waku_bindings::WakuContentTopic;
|
||||
|
||||
use crate::build_content_topics;
|
||||
|
||||
/// Fast allowlist for content topics without requiring Hash.
|
||||
/// Internally uses a Vec and dedupes on insert.
|
||||
#[derive(Default, Debug)]
|
||||
pub struct TopicFilter {
|
||||
list: RwLock<Vec<WakuContentTopic>>,
|
||||
}
|
||||
|
||||
impl TopicFilter {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Build and add topics if not already present.
|
||||
pub async fn add_many(&self, group_name: &str) {
|
||||
let topics = build_content_topics(group_name);
|
||||
self.list.write().await.extend(topics);
|
||||
}
|
||||
|
||||
/// Remove any matching topics.
|
||||
pub async fn remove_many(&self, group_name: &str) {
|
||||
let topics = build_content_topics(group_name);
|
||||
self.list
|
||||
.write()
|
||||
.await
|
||||
.retain(|x| !topics.iter().any(|t| t == x));
|
||||
}
|
||||
|
||||
/// Membership test (first-stage filter).
|
||||
#[inline]
|
||||
pub async fn contains(&self, t: &WakuContentTopic) -> bool {
|
||||
self.list.read().await.iter().any(|x| x == t)
|
||||
}
|
||||
|
||||
pub async fn snapshot(&self) -> Vec<WakuContentTopic> {
|
||||
self.list.read().await.clone()
|
||||
}
|
||||
|
||||
pub async fn get_group_name(&self, t: &WakuContentTopic) -> Option<String> {
|
||||
self.list
|
||||
.read()
|
||||
.await
|
||||
.iter()
|
||||
.find(|x| x == &t)
|
||||
.map(|x| x.application_name.clone().to_string())
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use log::{debug, error, info};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{thread::sleep, time::Duration};
|
||||
use tokio::sync::mpsc::{Receiver, Sender};
|
||||
use tracing::{debug, error, info};
|
||||
use waku_bindings::{
|
||||
node::{WakuNodeConfig, WakuNodeHandle},
|
||||
waku_new, Initialized, LibwakuResponse, Multiaddr, Running, WakuEvent, WakuMessage,
|
||||
@@ -24,7 +24,7 @@ impl WakuNode<Initialized> {
|
||||
tcp_port: Some(port),
|
||||
cluster_id: Some(15),
|
||||
shards: vec![1],
|
||||
log_level: Some("INFO"), // Supported: TRACE, DEBUG, INFO, NOTICE, WARN, ERROR or FATAL
|
||||
log_level: Some("FATAL"), // Supported: TRACE, DEBUG, INFO, NOTICE, WARN, ERROR or FATAL
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
@@ -43,16 +43,16 @@ impl WakuNode<Initialized> {
|
||||
serde_json::from_str(v.unwrap().as_str()).expect("Parsing event to succeed");
|
||||
match event {
|
||||
WakuEvent::WakuMessage(evt) => {
|
||||
info!("WakuMessage event received: {:?}", evt.message_hash);
|
||||
debug!("WakuMessage event received: {:?}", evt.message_hash);
|
||||
waku_sender
|
||||
.blocking_send(evt.waku_message.clone())
|
||||
.expect("Failed to send message to waku");
|
||||
}
|
||||
WakuEvent::RelayTopicHealthChange(evt) => {
|
||||
info!("Relay topic change evt: {evt:?}");
|
||||
debug!("Relay topic change evt: {evt:?}");
|
||||
}
|
||||
WakuEvent::ConnectionChange(evt) => {
|
||||
info!("Conn change evt: {evt:?}");
|
||||
debug!("Conn change evt: {evt:?}");
|
||||
}
|
||||
WakuEvent::Unrecognized(e) => panic!("Unrecognized waku event: {e:?}"),
|
||||
_ => panic!("event case not expected"),
|
||||
@@ -197,9 +197,9 @@ pub async fn run_waku_node(
|
||||
|
||||
info!("Waiting for message to send to waku");
|
||||
while let Some(msg) = receiver.recv().await {
|
||||
info!("Received message to send to waku");
|
||||
debug!("Received message to send to waku");
|
||||
let id = waku_node.send_message(msg).await?;
|
||||
info!("Successfully publish message with id: {id:?}");
|
||||
debug!("Successfully publish message with id: {id:?}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -7,8 +7,8 @@ use kameo::{
|
||||
message::{Context, Message},
|
||||
Actor,
|
||||
};
|
||||
use log::info;
|
||||
use tokio::sync::mpsc::channel;
|
||||
use tracing::info;
|
||||
use waku_bindings::WakuMessage;
|
||||
|
||||
#[derive(Debug, Clone, Actor)]
|
||||
@@ -44,7 +44,7 @@ impl Message<WakuMessage> for Application {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_waku_client() {
|
||||
env_logger::init();
|
||||
tracing_subscriber::fmt::init();
|
||||
let group_name = "new_group";
|
||||
let mut pubsub = PubSub::<WakuMessage>::new();
|
||||
|
||||
|
||||
10
frontend/.gitignore
vendored
10
frontend/.gitignore
vendored
@@ -1,10 +0,0 @@
|
||||
.DS_Store
|
||||
node_modules
|
||||
/build
|
||||
/.svelte-kit
|
||||
/package
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
@@ -1 +0,0 @@
|
||||
{"config":{"nodeModuleFormat":"esm"},"version":1}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { init } from '../serverless.js';
|
||||
|
||||
export const handler = init({
|
||||
appDir: "_app",
|
||||
appPath: "_app",
|
||||
assets: new Set(["favicon.png"]),
|
||||
mimeTypes: {".png":"image/png"},
|
||||
_: {
|
||||
client: {"start":{"file":"_app/immutable/entry/start.530cd74f.js","imports":["_app/immutable/entry/start.530cd74f.js","_app/immutable/chunks/index.b5cfe40e.js","_app/immutable/chunks/singletons.995fdd8e.js","_app/immutable/chunks/index.0a9737cc.js"],"stylesheets":[],"fonts":[]},"app":{"file":"_app/immutable/entry/app.e73d9bc3.js","imports":["_app/immutable/entry/app.e73d9bc3.js","_app/immutable/chunks/index.b5cfe40e.js"],"stylesheets":[],"fonts":[]}},
|
||||
nodes: [
|
||||
() => import('../server/nodes/0.js'),
|
||||
() => import('../server/nodes/1.js'),
|
||||
() => import('../server/nodes/2.js'),
|
||||
() => import('../server/nodes/3.js')
|
||||
],
|
||||
routes: [
|
||||
{
|
||||
id: "/",
|
||||
pattern: /^\/$/,
|
||||
params: [],
|
||||
page: { layouts: [0], errors: [1], leaf: 2 },
|
||||
endpoint: null
|
||||
},
|
||||
{
|
||||
id: "/chat",
|
||||
pattern: /^\/chat\/?$/,
|
||||
params: [],
|
||||
page: { layouts: [0], errors: [1], leaf: 3 },
|
||||
endpoint: null
|
||||
}
|
||||
],
|
||||
matchers: async () => {
|
||||
|
||||
return { };
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1 +0,0 @@
|
||||
div.svelte-lzwg39{width:20px;opacity:0;height:20px;border-radius:10px;background:var(--primary, #61d345);position:relative;transform:rotate(45deg);animation:svelte-lzwg39-circleAnimation 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;animation-delay:100ms}div.svelte-lzwg39::after{content:'';box-sizing:border-box;animation:svelte-lzwg39-checkmarkAnimation 0.2s ease-out forwards;opacity:0;animation-delay:200ms;position:absolute;border-right:2px solid;border-bottom:2px solid;border-color:var(--secondary, #fff);bottom:6px;left:6px;height:10px;width:6px}@keyframes svelte-lzwg39-circleAnimation{from{transform:scale(0) rotate(45deg);opacity:0}to{transform:scale(1) rotate(45deg);opacity:1}}@keyframes svelte-lzwg39-checkmarkAnimation{0%{height:0;width:0;opacity:0}40%{height:0;width:6px;opacity:1}100%{opacity:1;height:10px}}div.svelte-10jnndo{width:20px;opacity:0;height:20px;border-radius:10px;background:var(--primary, #ff4b4b);position:relative;transform:rotate(45deg);animation:svelte-10jnndo-circleAnimation 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;animation-delay:100ms}div.svelte-10jnndo::after,div.svelte-10jnndo::before{content:'';animation:svelte-10jnndo-firstLineAnimation 0.15s ease-out forwards;animation-delay:150ms;position:absolute;border-radius:3px;opacity:0;background:var(--secondary, #fff);bottom:9px;left:4px;height:2px;width:12px}div.svelte-10jnndo:before{animation:svelte-10jnndo-secondLineAnimation 0.15s ease-out forwards;animation-delay:180ms;transform:rotate(90deg)}@keyframes svelte-10jnndo-circleAnimation{from{transform:scale(0) rotate(45deg);opacity:0}to{transform:scale(1) rotate(45deg);opacity:1}}@keyframes svelte-10jnndo-firstLineAnimation{from{transform:scale(0);opacity:0}to{transform:scale(1);opacity:1}}@keyframes svelte-10jnndo-secondLineAnimation{from{transform:scale(0) rotate(90deg);opacity:0}to{transform:scale(1) rotate(90deg);opacity:1}}div.svelte-bj4lu8{width:12px;height:12px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--secondary, #e0e0e0);border-right-color:var(--primary, #616161);animation:svelte-bj4lu8-rotate 1s linear infinite}@keyframes svelte-bj4lu8-rotate{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}.indicator.svelte-1c92bpz{position:relative;display:flex;justify-content:center;align-items:center;min-width:20px;min-height:20px}.status.svelte-1c92bpz{position:absolute}.animated.svelte-1c92bpz{position:relative;transform:scale(0.6);opacity:0.4;min-width:20px;animation:svelte-1c92bpz-enter 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards}@keyframes svelte-1c92bpz-enter{from{transform:scale(0.6);opacity:0.4}to{transform:scale(1);opacity:1}}.message.svelte-o805t1{display:flex;justify-content:center;margin:4px 10px;color:inherit;flex:1 1 auto;white-space:pre-line}@keyframes svelte-15lyehg-enterAnimation{0%{transform:translate3d(0, calc(var(--factor) * -200%), 0) scale(0.6);opacity:0.5}100%{transform:translate3d(0, 0, 0) scale(1);opacity:1}}@keyframes svelte-15lyehg-exitAnimation{0%{transform:translate3d(0, 0, -1px) scale(1);opacity:1}100%{transform:translate3d(0, calc(var(--factor) * -150%), -1px) scale(0.6);opacity:0}}@keyframes svelte-15lyehg-fadeInAnimation{0%{opacity:0}100%{opacity:1}}@keyframes svelte-15lyehg-fadeOutAnimation{0%{opacity:1}100%{opacity:0}}.base.svelte-15lyehg{display:flex;align-items:center;background:#fff;color:#363636;line-height:1.3;will-change:transform;box-shadow:0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05);max-width:350px;pointer-events:auto;padding:8px 10px;border-radius:8px}.transparent.svelte-15lyehg{opacity:0}.enter.svelte-15lyehg{animation:svelte-15lyehg-enterAnimation 0.35s cubic-bezier(0.21, 1.02, 0.73, 1) forwards}.exit.svelte-15lyehg{animation:svelte-15lyehg-exitAnimation 0.4s cubic-bezier(0.06, 0.71, 0.55, 1) forwards}.fadeIn.svelte-15lyehg{animation:svelte-15lyehg-fadeInAnimation 0.35s cubic-bezier(0.21, 1.02, 0.73, 1) forwards}.fadeOut.svelte-15lyehg{animation:svelte-15lyehg-fadeOutAnimation 0.4s cubic-bezier(0.06, 0.71, 0.55, 1) forwards}.wrapper.svelte-1pakgpd{left:0;right:0;display:flex;position:absolute;transform:translateY(calc(var(--offset, 16px) * var(--factor) * 1px))}.transition.svelte-1pakgpd{transition:all 230ms cubic-bezier(0.21, 1.02, 0.73, 1)}.active.svelte-1pakgpd{z-index:9999}.active.svelte-1pakgpd>*{pointer-events:auto}.toaster.svelte-jyff3d{--default-offset:16px;position:fixed;z-index:9999;top:var(--default-offset);left:var(--default-offset);right:var(--default-offset);bottom:var(--default-offset);pointer-events:none}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,242 +0,0 @@
|
||||
import { d as derived, w as writable } from "./index2.js";
|
||||
import { k as get_store_value } from "./index3.js";
|
||||
function writableDerived(origins, derive, reflect, initial) {
|
||||
var childDerivedSetter, originValues, blockNextDerive = false;
|
||||
var reflectOldValues = reflect.length >= 2;
|
||||
var wrappedDerive = (got, set) => {
|
||||
childDerivedSetter = set;
|
||||
if (reflectOldValues) {
|
||||
originValues = got;
|
||||
}
|
||||
if (!blockNextDerive) {
|
||||
let returned = derive(got, set);
|
||||
if (derive.length < 2) {
|
||||
set(returned);
|
||||
} else {
|
||||
return returned;
|
||||
}
|
||||
}
|
||||
blockNextDerive = false;
|
||||
};
|
||||
var childDerived = derived(origins, wrappedDerive, initial);
|
||||
var singleOrigin = !Array.isArray(origins);
|
||||
function doReflect(reflecting) {
|
||||
var setWith = reflect(reflecting, originValues);
|
||||
if (singleOrigin) {
|
||||
blockNextDerive = true;
|
||||
origins.set(setWith);
|
||||
} else {
|
||||
setWith.forEach((value, i) => {
|
||||
blockNextDerive = true;
|
||||
origins[i].set(value);
|
||||
});
|
||||
}
|
||||
blockNextDerive = false;
|
||||
}
|
||||
var tryingSet = false;
|
||||
function update2(fn) {
|
||||
var isUpdated, mutatedBySubscriptions, oldValue, newValue;
|
||||
if (tryingSet) {
|
||||
newValue = fn(get_store_value(childDerived));
|
||||
childDerivedSetter(newValue);
|
||||
return;
|
||||
}
|
||||
var unsubscribe = childDerived.subscribe((value) => {
|
||||
if (!tryingSet) {
|
||||
oldValue = value;
|
||||
} else if (!isUpdated) {
|
||||
isUpdated = true;
|
||||
} else {
|
||||
mutatedBySubscriptions = true;
|
||||
}
|
||||
});
|
||||
newValue = fn(oldValue);
|
||||
tryingSet = true;
|
||||
childDerivedSetter(newValue);
|
||||
unsubscribe();
|
||||
tryingSet = false;
|
||||
if (mutatedBySubscriptions) {
|
||||
newValue = get_store_value(childDerived);
|
||||
}
|
||||
if (isUpdated) {
|
||||
doReflect(newValue);
|
||||
}
|
||||
}
|
||||
return {
|
||||
subscribe: childDerived.subscribe,
|
||||
set(value) {
|
||||
update2(() => value);
|
||||
},
|
||||
update: update2
|
||||
};
|
||||
}
|
||||
const TOAST_LIMIT = 20;
|
||||
const toasts = writable([]);
|
||||
const pausedAt = writable(null);
|
||||
const toastTimeouts = /* @__PURE__ */ new Map();
|
||||
const addToRemoveQueue = (toastId) => {
|
||||
if (toastTimeouts.has(toastId)) {
|
||||
return;
|
||||
}
|
||||
const timeout = setTimeout(() => {
|
||||
toastTimeouts.delete(toastId);
|
||||
remove(toastId);
|
||||
}, 1e3);
|
||||
toastTimeouts.set(toastId, timeout);
|
||||
};
|
||||
const clearFromRemoveQueue = (toastId) => {
|
||||
const timeout = toastTimeouts.get(toastId);
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
};
|
||||
function update(toast2) {
|
||||
if (toast2.id) {
|
||||
clearFromRemoveQueue(toast2.id);
|
||||
}
|
||||
toasts.update(($toasts) => $toasts.map((t) => t.id === toast2.id ? { ...t, ...toast2 } : t));
|
||||
}
|
||||
function add(toast2) {
|
||||
toasts.update(($toasts) => [toast2, ...$toasts].slice(0, TOAST_LIMIT));
|
||||
}
|
||||
function upsert(toast2) {
|
||||
if (get_store_value(toasts).find((t) => t.id === toast2.id)) {
|
||||
update(toast2);
|
||||
} else {
|
||||
add(toast2);
|
||||
}
|
||||
}
|
||||
function dismiss(toastId) {
|
||||
toasts.update(($toasts) => {
|
||||
if (toastId) {
|
||||
addToRemoveQueue(toastId);
|
||||
} else {
|
||||
$toasts.forEach((toast2) => {
|
||||
addToRemoveQueue(toast2.id);
|
||||
});
|
||||
}
|
||||
return $toasts.map((t) => t.id === toastId || toastId === void 0 ? { ...t, visible: false } : t);
|
||||
});
|
||||
}
|
||||
function remove(toastId) {
|
||||
toasts.update(($toasts) => {
|
||||
if (toastId === void 0) {
|
||||
return [];
|
||||
}
|
||||
return $toasts.filter((t) => t.id !== toastId);
|
||||
});
|
||||
}
|
||||
function startPause(time) {
|
||||
pausedAt.set(time);
|
||||
}
|
||||
function endPause(time) {
|
||||
let diff;
|
||||
pausedAt.update(($pausedAt) => {
|
||||
diff = time - ($pausedAt || 0);
|
||||
return null;
|
||||
});
|
||||
toasts.update(($toasts) => $toasts.map((t) => ({
|
||||
...t,
|
||||
pauseDuration: t.pauseDuration + diff
|
||||
})));
|
||||
}
|
||||
const defaultTimeouts = {
|
||||
blank: 4e3,
|
||||
error: 4e3,
|
||||
success: 2e3,
|
||||
loading: Infinity,
|
||||
custom: 4e3
|
||||
};
|
||||
function useToasterStore(toastOptions = {}) {
|
||||
const mergedToasts = writableDerived(toasts, ($toasts) => $toasts.map((t) => ({
|
||||
...toastOptions,
|
||||
...toastOptions[t.type],
|
||||
...t,
|
||||
duration: t.duration || toastOptions[t.type]?.duration || toastOptions?.duration || defaultTimeouts[t.type],
|
||||
style: [toastOptions.style, toastOptions[t.type]?.style, t.style].join(";")
|
||||
})), ($toasts) => $toasts);
|
||||
return {
|
||||
toasts: mergedToasts,
|
||||
pausedAt
|
||||
};
|
||||
}
|
||||
const isFunction = (valOrFunction) => typeof valOrFunction === "function";
|
||||
const resolveValue = (valOrFunction, arg) => isFunction(valOrFunction) ? valOrFunction(arg) : valOrFunction;
|
||||
const genId = (() => {
|
||||
let count = 0;
|
||||
return () => {
|
||||
count += 1;
|
||||
return count.toString();
|
||||
};
|
||||
})();
|
||||
const prefersReducedMotion = (() => {
|
||||
let shouldReduceMotion;
|
||||
return () => {
|
||||
if (shouldReduceMotion === void 0 && typeof window !== "undefined") {
|
||||
const mediaQuery = matchMedia("(prefers-reduced-motion: reduce)");
|
||||
shouldReduceMotion = !mediaQuery || mediaQuery.matches;
|
||||
}
|
||||
return shouldReduceMotion;
|
||||
};
|
||||
})();
|
||||
const createToast = (message, type = "blank", opts) => ({
|
||||
createdAt: Date.now(),
|
||||
visible: true,
|
||||
type,
|
||||
ariaProps: {
|
||||
role: "status",
|
||||
"aria-live": "polite"
|
||||
},
|
||||
message,
|
||||
pauseDuration: 0,
|
||||
...opts,
|
||||
id: opts?.id || genId()
|
||||
});
|
||||
const createHandler = (type) => (message, options) => {
|
||||
const toast2 = createToast(message, type, options);
|
||||
upsert(toast2);
|
||||
return toast2.id;
|
||||
};
|
||||
const toast = (message, opts) => createHandler("blank")(message, opts);
|
||||
toast.error = createHandler("error");
|
||||
toast.success = createHandler("success");
|
||||
toast.loading = createHandler("loading");
|
||||
toast.custom = createHandler("custom");
|
||||
toast.dismiss = (toastId) => {
|
||||
dismiss(toastId);
|
||||
};
|
||||
toast.remove = (toastId) => remove(toastId);
|
||||
toast.promise = (promise, msgs, opts) => {
|
||||
const id = toast.loading(msgs.loading, { ...opts, ...opts?.loading });
|
||||
promise.then((p) => {
|
||||
toast.success(resolveValue(msgs.success, p), {
|
||||
id,
|
||||
...opts,
|
||||
...opts?.success
|
||||
});
|
||||
return p;
|
||||
}).catch((e) => {
|
||||
toast.error(resolveValue(msgs.error, e), {
|
||||
id,
|
||||
...opts,
|
||||
...opts?.error
|
||||
});
|
||||
});
|
||||
return promise;
|
||||
};
|
||||
const CheckmarkIcon_svelte_svelte_type_style_lang = "";
|
||||
const ErrorIcon_svelte_svelte_type_style_lang = "";
|
||||
const LoaderIcon_svelte_svelte_type_style_lang = "";
|
||||
const ToastIcon_svelte_svelte_type_style_lang = "";
|
||||
const ToastMessage_svelte_svelte_type_style_lang = "";
|
||||
const ToastBar_svelte_svelte_type_style_lang = "";
|
||||
const ToastWrapper_svelte_svelte_type_style_lang = "";
|
||||
const Toaster_svelte_svelte_type_style_lang = "";
|
||||
export {
|
||||
update as a,
|
||||
endPause as e,
|
||||
prefersReducedMotion as p,
|
||||
startPause as s,
|
||||
toast as t,
|
||||
useToasterStore as u
|
||||
};
|
||||
@@ -1,78 +0,0 @@
|
||||
let HttpError = class HttpError2 {
|
||||
/**
|
||||
* @param {number} status
|
||||
* @param {{message: string} extends App.Error ? (App.Error | string | undefined) : App.Error} body
|
||||
*/
|
||||
constructor(status, body) {
|
||||
this.status = status;
|
||||
if (typeof body === "string") {
|
||||
this.body = { message: body };
|
||||
} else if (body) {
|
||||
this.body = body;
|
||||
} else {
|
||||
this.body = { message: `Error: ${status}` };
|
||||
}
|
||||
}
|
||||
toString() {
|
||||
return JSON.stringify(this.body);
|
||||
}
|
||||
};
|
||||
let Redirect = class Redirect2 {
|
||||
/**
|
||||
* @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status
|
||||
* @param {string} location
|
||||
*/
|
||||
constructor(status, location) {
|
||||
this.status = status;
|
||||
this.location = location;
|
||||
}
|
||||
};
|
||||
let ActionFailure = class ActionFailure2 {
|
||||
/**
|
||||
* @param {number} status
|
||||
* @param {T} [data]
|
||||
*/
|
||||
constructor(status, data) {
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
};
|
||||
function error(status, message) {
|
||||
if (isNaN(status) || status < 400 || status > 599) {
|
||||
throw new Error(`HTTP error status codes must be between 400 and 599 — ${status} is invalid`);
|
||||
}
|
||||
return new HttpError(status, message);
|
||||
}
|
||||
function json(data, init) {
|
||||
const body = JSON.stringify(data);
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!headers.has("content-length")) {
|
||||
headers.set("content-length", encoder.encode(body).byteLength.toString());
|
||||
}
|
||||
if (!headers.has("content-type")) {
|
||||
headers.set("content-type", "application/json");
|
||||
}
|
||||
return new Response(body, {
|
||||
...init,
|
||||
headers
|
||||
});
|
||||
}
|
||||
const encoder = new TextEncoder();
|
||||
function text(body, init) {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!headers.has("content-length")) {
|
||||
headers.set("content-length", encoder.encode(body).byteLength.toString());
|
||||
}
|
||||
return new Response(body, {
|
||||
...init,
|
||||
headers
|
||||
});
|
||||
}
|
||||
export {
|
||||
ActionFailure as A,
|
||||
HttpError as H,
|
||||
Redirect as R,
|
||||
error as e,
|
||||
json as j,
|
||||
text as t
|
||||
};
|
||||
@@ -1,92 +0,0 @@
|
||||
import { n as noop, l as safe_not_equal, h as subscribe, r as run_all, p as is_function } from "./index3.js";
|
||||
const subscriber_queue = [];
|
||||
function readable(value, start) {
|
||||
return {
|
||||
subscribe: writable(value, start).subscribe
|
||||
};
|
||||
}
|
||||
function writable(value, start = noop) {
|
||||
let stop;
|
||||
const subscribers = /* @__PURE__ */ new Set();
|
||||
function set(new_value) {
|
||||
if (safe_not_equal(value, new_value)) {
|
||||
value = new_value;
|
||||
if (stop) {
|
||||
const run_queue = !subscriber_queue.length;
|
||||
for (const subscriber of subscribers) {
|
||||
subscriber[1]();
|
||||
subscriber_queue.push(subscriber, value);
|
||||
}
|
||||
if (run_queue) {
|
||||
for (let i = 0; i < subscriber_queue.length; i += 2) {
|
||||
subscriber_queue[i][0](subscriber_queue[i + 1]);
|
||||
}
|
||||
subscriber_queue.length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function update(fn) {
|
||||
set(fn(value));
|
||||
}
|
||||
function subscribe2(run, invalidate = noop) {
|
||||
const subscriber = [run, invalidate];
|
||||
subscribers.add(subscriber);
|
||||
if (subscribers.size === 1) {
|
||||
stop = start(set) || noop;
|
||||
}
|
||||
run(value);
|
||||
return () => {
|
||||
subscribers.delete(subscriber);
|
||||
if (subscribers.size === 0 && stop) {
|
||||
stop();
|
||||
stop = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
return { set, update, subscribe: subscribe2 };
|
||||
}
|
||||
function derived(stores, fn, initial_value) {
|
||||
const single = !Array.isArray(stores);
|
||||
const stores_array = single ? [stores] : stores;
|
||||
const auto = fn.length < 2;
|
||||
return readable(initial_value, (set) => {
|
||||
let started = false;
|
||||
const values = [];
|
||||
let pending = 0;
|
||||
let cleanup = noop;
|
||||
const sync = () => {
|
||||
if (pending) {
|
||||
return;
|
||||
}
|
||||
cleanup();
|
||||
const result = fn(single ? values[0] : values, set);
|
||||
if (auto) {
|
||||
set(result);
|
||||
} else {
|
||||
cleanup = is_function(result) ? result : noop;
|
||||
}
|
||||
};
|
||||
const unsubscribers = stores_array.map((store, i) => subscribe(store, (value) => {
|
||||
values[i] = value;
|
||||
pending &= ~(1 << i);
|
||||
if (started) {
|
||||
sync();
|
||||
}
|
||||
}, () => {
|
||||
pending |= 1 << i;
|
||||
}));
|
||||
started = true;
|
||||
sync();
|
||||
return function stop() {
|
||||
run_all(unsubscribers);
|
||||
cleanup();
|
||||
started = false;
|
||||
};
|
||||
});
|
||||
}
|
||||
export {
|
||||
derived as d,
|
||||
readable as r,
|
||||
writable as w
|
||||
};
|
||||
@@ -1,250 +0,0 @@
|
||||
function noop() {
|
||||
}
|
||||
function run(fn) {
|
||||
return fn();
|
||||
}
|
||||
function blank_object() {
|
||||
return /* @__PURE__ */ Object.create(null);
|
||||
}
|
||||
function run_all(fns) {
|
||||
fns.forEach(run);
|
||||
}
|
||||
function is_function(thing) {
|
||||
return typeof thing === "function";
|
||||
}
|
||||
function safe_not_equal(a, b) {
|
||||
return a != a ? b == b : a !== b || (a && typeof a === "object" || typeof a === "function");
|
||||
}
|
||||
function subscribe(store, ...callbacks) {
|
||||
if (store == null) {
|
||||
return noop;
|
||||
}
|
||||
const unsub = store.subscribe(...callbacks);
|
||||
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
|
||||
}
|
||||
function get_store_value(store) {
|
||||
let value;
|
||||
subscribe(store, (_) => value = _)();
|
||||
return value;
|
||||
}
|
||||
let current_component;
|
||||
function set_current_component(component) {
|
||||
current_component = component;
|
||||
}
|
||||
function get_current_component() {
|
||||
if (!current_component)
|
||||
throw new Error("Function called outside component initialization");
|
||||
return current_component;
|
||||
}
|
||||
function onDestroy(fn) {
|
||||
get_current_component().$$.on_destroy.push(fn);
|
||||
}
|
||||
function setContext(key, context) {
|
||||
get_current_component().$$.context.set(key, context);
|
||||
return context;
|
||||
}
|
||||
function getContext(key) {
|
||||
return get_current_component().$$.context.get(key);
|
||||
}
|
||||
const _boolean_attributes = [
|
||||
"allowfullscreen",
|
||||
"allowpaymentrequest",
|
||||
"async",
|
||||
"autofocus",
|
||||
"autoplay",
|
||||
"checked",
|
||||
"controls",
|
||||
"default",
|
||||
"defer",
|
||||
"disabled",
|
||||
"formnovalidate",
|
||||
"hidden",
|
||||
"inert",
|
||||
"ismap",
|
||||
"itemscope",
|
||||
"loop",
|
||||
"multiple",
|
||||
"muted",
|
||||
"nomodule",
|
||||
"novalidate",
|
||||
"open",
|
||||
"playsinline",
|
||||
"readonly",
|
||||
"required",
|
||||
"reversed",
|
||||
"selected"
|
||||
];
|
||||
const boolean_attributes = /* @__PURE__ */ new Set([..._boolean_attributes]);
|
||||
const invalid_attribute_name_character = /[\s'">/=\u{FDD0}-\u{FDEF}\u{FFFE}\u{FFFF}\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/u;
|
||||
function spread(args, attrs_to_add) {
|
||||
const attributes = Object.assign({}, ...args);
|
||||
if (attrs_to_add) {
|
||||
const classes_to_add = attrs_to_add.classes;
|
||||
const styles_to_add = attrs_to_add.styles;
|
||||
if (classes_to_add) {
|
||||
if (attributes.class == null) {
|
||||
attributes.class = classes_to_add;
|
||||
} else {
|
||||
attributes.class += " " + classes_to_add;
|
||||
}
|
||||
}
|
||||
if (styles_to_add) {
|
||||
if (attributes.style == null) {
|
||||
attributes.style = style_object_to_string(styles_to_add);
|
||||
} else {
|
||||
attributes.style = style_object_to_string(merge_ssr_styles(attributes.style, styles_to_add));
|
||||
}
|
||||
}
|
||||
}
|
||||
let str = "";
|
||||
Object.keys(attributes).forEach((name) => {
|
||||
if (invalid_attribute_name_character.test(name))
|
||||
return;
|
||||
const value = attributes[name];
|
||||
if (value === true)
|
||||
str += " " + name;
|
||||
else if (boolean_attributes.has(name.toLowerCase())) {
|
||||
if (value)
|
||||
str += " " + name;
|
||||
} else if (value != null) {
|
||||
str += ` ${name}="${value}"`;
|
||||
}
|
||||
});
|
||||
return str;
|
||||
}
|
||||
function merge_ssr_styles(style_attribute, style_directive) {
|
||||
const style_object = {};
|
||||
for (const individual_style of style_attribute.split(";")) {
|
||||
const colon_index = individual_style.indexOf(":");
|
||||
const name = individual_style.slice(0, colon_index).trim();
|
||||
const value = individual_style.slice(colon_index + 1).trim();
|
||||
if (!name)
|
||||
continue;
|
||||
style_object[name] = value;
|
||||
}
|
||||
for (const name in style_directive) {
|
||||
const value = style_directive[name];
|
||||
if (value) {
|
||||
style_object[name] = value;
|
||||
} else {
|
||||
delete style_object[name];
|
||||
}
|
||||
}
|
||||
return style_object;
|
||||
}
|
||||
const ATTR_REGEX = /[&"]/g;
|
||||
const CONTENT_REGEX = /[&<]/g;
|
||||
function escape(value, is_attr = false) {
|
||||
const str = String(value);
|
||||
const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;
|
||||
pattern.lastIndex = 0;
|
||||
let escaped = "";
|
||||
let last = 0;
|
||||
while (pattern.test(str)) {
|
||||
const i = pattern.lastIndex - 1;
|
||||
const ch = str[i];
|
||||
escaped += str.substring(last, i) + (ch === "&" ? "&" : ch === '"' ? """ : "<");
|
||||
last = i + 1;
|
||||
}
|
||||
return escaped + str.substring(last);
|
||||
}
|
||||
function escape_attribute_value(value) {
|
||||
const should_escape = typeof value === "string" || value && typeof value === "object";
|
||||
return should_escape ? escape(value, true) : value;
|
||||
}
|
||||
function escape_object(obj) {
|
||||
const result = {};
|
||||
for (const key in obj) {
|
||||
result[key] = escape_attribute_value(obj[key]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function each(items, fn) {
|
||||
let str = "";
|
||||
for (let i = 0; i < items.length; i += 1) {
|
||||
str += fn(items[i], i);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
const missing_component = {
|
||||
$$render: () => ""
|
||||
};
|
||||
function validate_component(component, name) {
|
||||
if (!component || !component.$$render) {
|
||||
if (name === "svelte:component")
|
||||
name += " this={...}";
|
||||
throw new Error(`<${name}> is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules. Otherwise you may need to fix a <${name}>.`);
|
||||
}
|
||||
return component;
|
||||
}
|
||||
let on_destroy;
|
||||
function create_ssr_component(fn) {
|
||||
function $$render(result, props, bindings, slots, context) {
|
||||
const parent_component = current_component;
|
||||
const $$ = {
|
||||
on_destroy,
|
||||
context: new Map(context || (parent_component ? parent_component.$$.context : [])),
|
||||
// these will be immediately discarded
|
||||
on_mount: [],
|
||||
before_update: [],
|
||||
after_update: [],
|
||||
callbacks: blank_object()
|
||||
};
|
||||
set_current_component({ $$ });
|
||||
const html = fn(result, props, bindings, slots);
|
||||
set_current_component(parent_component);
|
||||
return html;
|
||||
}
|
||||
return {
|
||||
render: (props = {}, { $$slots = {}, context = /* @__PURE__ */ new Map() } = {}) => {
|
||||
on_destroy = [];
|
||||
const result = { title: "", head: "", css: /* @__PURE__ */ new Set() };
|
||||
const html = $$render(result, props, {}, $$slots, context);
|
||||
run_all(on_destroy);
|
||||
return {
|
||||
html,
|
||||
css: {
|
||||
code: Array.from(result.css).map((css) => css.code).join("\n"),
|
||||
map: null
|
||||
// TODO
|
||||
},
|
||||
head: result.title + result.head
|
||||
};
|
||||
},
|
||||
$$render
|
||||
};
|
||||
}
|
||||
function add_attribute(name, value, boolean) {
|
||||
if (value == null || boolean && !value)
|
||||
return "";
|
||||
const assignment = boolean && value === true ? "" : `="${escape(value, true)}"`;
|
||||
return ` ${name}${assignment}`;
|
||||
}
|
||||
function style_object_to_string(style_object) {
|
||||
return Object.keys(style_object).filter((key) => style_object[key]).map((key) => `${key}: ${escape_attribute_value(style_object[key])};`).join(" ");
|
||||
}
|
||||
function add_styles(style_object) {
|
||||
const styles = style_object_to_string(style_object);
|
||||
return styles ? ` style="${styles}"` : "";
|
||||
}
|
||||
export {
|
||||
add_styles as a,
|
||||
spread as b,
|
||||
create_ssr_component as c,
|
||||
escape_object as d,
|
||||
escape as e,
|
||||
merge_ssr_styles as f,
|
||||
add_attribute as g,
|
||||
subscribe as h,
|
||||
each as i,
|
||||
getContext as j,
|
||||
get_store_value as k,
|
||||
safe_not_equal as l,
|
||||
missing_component as m,
|
||||
noop as n,
|
||||
onDestroy as o,
|
||||
is_function as p,
|
||||
run_all as r,
|
||||
setContext as s,
|
||||
validate_component as v
|
||||
};
|
||||
@@ -1,179 +0,0 @@
|
||||
import { c as create_ssr_component, s as setContext, v as validate_component, m as missing_component } from "./index3.js";
|
||||
import "./shared-server.js";
|
||||
let base = "";
|
||||
let assets = base;
|
||||
const initial = { base, assets };
|
||||
function reset() {
|
||||
base = initial.base;
|
||||
assets = initial.assets;
|
||||
}
|
||||
function set_assets(path) {
|
||||
assets = initial.assets = path;
|
||||
}
|
||||
function afterUpdate() {
|
||||
}
|
||||
function set_building() {
|
||||
}
|
||||
const Root = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let { stores } = $$props;
|
||||
let { page } = $$props;
|
||||
let { constructors } = $$props;
|
||||
let { components = [] } = $$props;
|
||||
let { form } = $$props;
|
||||
let { data_0 = null } = $$props;
|
||||
let { data_1 = null } = $$props;
|
||||
{
|
||||
setContext("__svelte__", stores);
|
||||
}
|
||||
afterUpdate(stores.page.notify);
|
||||
if ($$props.stores === void 0 && $$bindings.stores && stores !== void 0)
|
||||
$$bindings.stores(stores);
|
||||
if ($$props.page === void 0 && $$bindings.page && page !== void 0)
|
||||
$$bindings.page(page);
|
||||
if ($$props.constructors === void 0 && $$bindings.constructors && constructors !== void 0)
|
||||
$$bindings.constructors(constructors);
|
||||
if ($$props.components === void 0 && $$bindings.components && components !== void 0)
|
||||
$$bindings.components(components);
|
||||
if ($$props.form === void 0 && $$bindings.form && form !== void 0)
|
||||
$$bindings.form(form);
|
||||
if ($$props.data_0 === void 0 && $$bindings.data_0 && data_0 !== void 0)
|
||||
$$bindings.data_0(data_0);
|
||||
if ($$props.data_1 === void 0 && $$bindings.data_1 && data_1 !== void 0)
|
||||
$$bindings.data_1(data_1);
|
||||
let $$settled;
|
||||
let $$rendered;
|
||||
do {
|
||||
$$settled = true;
|
||||
{
|
||||
stores.page.set(page);
|
||||
}
|
||||
$$rendered = `
|
||||
|
||||
|
||||
${constructors[1] ? `${validate_component(constructors[0] || missing_component, "svelte:component").$$render(
|
||||
$$result,
|
||||
{ data: data_0, this: components[0] },
|
||||
{
|
||||
this: ($$value) => {
|
||||
components[0] = $$value;
|
||||
$$settled = false;
|
||||
}
|
||||
},
|
||||
{
|
||||
default: () => {
|
||||
return `${validate_component(constructors[1] || missing_component, "svelte:component").$$render(
|
||||
$$result,
|
||||
{ data: data_1, form, this: components[1] },
|
||||
{
|
||||
this: ($$value) => {
|
||||
components[1] = $$value;
|
||||
$$settled = false;
|
||||
}
|
||||
},
|
||||
{}
|
||||
)}`;
|
||||
}
|
||||
}
|
||||
)}` : `${validate_component(constructors[0] || missing_component, "svelte:component").$$render(
|
||||
$$result,
|
||||
{ data: data_0, form, this: components[0] },
|
||||
{
|
||||
this: ($$value) => {
|
||||
components[0] = $$value;
|
||||
$$settled = false;
|
||||
}
|
||||
},
|
||||
{}
|
||||
)}`}
|
||||
|
||||
${``}`;
|
||||
} while (!$$settled);
|
||||
return $$rendered;
|
||||
});
|
||||
const options = {
|
||||
app_template_contains_nonce: false,
|
||||
csp: { "mode": "auto", "directives": { "upgrade-insecure-requests": false, "block-all-mixed-content": false }, "reportOnly": { "upgrade-insecure-requests": false, "block-all-mixed-content": false } },
|
||||
csrf_check_origin: true,
|
||||
embedded: false,
|
||||
env_public_prefix: "PUBLIC_",
|
||||
hooks: null,
|
||||
// added lazily, via `get_hooks`
|
||||
preload_strategy: "modulepreload",
|
||||
root: Root,
|
||||
service_worker: false,
|
||||
templates: {
|
||||
app: ({ head, body, assets: assets2, nonce, env }) => '<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <link rel="icon" href="' + assets2 + '/favicon.png" />\n <meta name="viewport" content="width=device-width" />\n ' + head + '\n </head>\n <body data-sveltekit-preload-data="hover">\n <div style="display: contents">' + body + "</div>\n </body>\n</html>\n",
|
||||
error: ({ status, message }) => '<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>' + message + `</title>
|
||||
|
||||
<style>
|
||||
body {
|
||||
--bg: white;
|
||||
--fg: #222;
|
||||
--divider: #ccc;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
|
||||
Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
max-width: 32rem;
|
||||
margin: 0 1rem;
|
||||
}
|
||||
|
||||
.status {
|
||||
font-weight: 200;
|
||||
font-size: 3rem;
|
||||
line-height: 1;
|
||||
position: relative;
|
||||
top: -0.05rem;
|
||||
}
|
||||
|
||||
.message {
|
||||
border-left: 1px solid var(--divider);
|
||||
padding: 0 0 0 1rem;
|
||||
margin: 0 0 0 1rem;
|
||||
min-height: 2.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.message h1 {
|
||||
font-weight: 400;
|
||||
font-size: 1em;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
--bg: #222;
|
||||
--fg: #ddd;
|
||||
--divider: #666;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="error">
|
||||
<span class="status">` + status + '</span>\n <div class="message">\n <h1>' + message + "</h1>\n </div>\n </div>\n </body>\n</html>\n"
|
||||
},
|
||||
version_hash: "1vmmy0u"
|
||||
};
|
||||
function get_hooks() {
|
||||
return {};
|
||||
}
|
||||
export {
|
||||
assets as a,
|
||||
base as b,
|
||||
set_building as c,
|
||||
get_hooks as g,
|
||||
options as o,
|
||||
reset as r,
|
||||
set_assets as s
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
let public_env = {};
|
||||
function set_private_env(environment) {
|
||||
}
|
||||
function set_public_env(environment) {
|
||||
public_env = environment;
|
||||
}
|
||||
export {
|
||||
set_private_env as a,
|
||||
public_env as p,
|
||||
set_public_env as s
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
import { j as getContext, c as create_ssr_component, h as subscribe, e as escape } from "../../chunks/index3.js";
|
||||
const getStores = () => {
|
||||
const stores = getContext("__svelte__");
|
||||
return {
|
||||
page: {
|
||||
subscribe: stores.page.subscribe
|
||||
},
|
||||
navigating: {
|
||||
subscribe: stores.navigating.subscribe
|
||||
},
|
||||
updated: stores.updated
|
||||
};
|
||||
};
|
||||
const page = {
|
||||
/** @param {(value: any) => void} fn */
|
||||
subscribe(fn) {
|
||||
const store = getStores().page;
|
||||
return store.subscribe(fn);
|
||||
}
|
||||
};
|
||||
const Error$1 = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let $page, $$unsubscribe_page;
|
||||
$$unsubscribe_page = subscribe(page, (value) => $page = value);
|
||||
$$unsubscribe_page();
|
||||
return `<h1>${escape($page.status)}</h1>
|
||||
<p>${escape($page.error?.message)}</p>`;
|
||||
});
|
||||
export {
|
||||
Error$1 as default
|
||||
};
|
||||
@@ -1,289 +0,0 @@
|
||||
import { o as onDestroy, c as create_ssr_component, a as add_styles, e as escape, v as validate_component, m as missing_component, b as spread, d as escape_object, f as merge_ssr_styles, g as add_attribute, h as subscribe, i as each } from "../../chunks/index3.js";
|
||||
import { u as useToasterStore, t as toast, s as startPause, e as endPause, a as update, p as prefersReducedMotion } from "../../chunks/Toaster.svelte_svelte_type_style_lang.js";
|
||||
const app = "";
|
||||
function calculateOffset(toast2, $toasts, opts) {
|
||||
const { reverseOrder, gutter = 8, defaultPosition } = opts || {};
|
||||
const relevantToasts = $toasts.filter((t) => (t.position || defaultPosition) === (toast2.position || defaultPosition) && t.height);
|
||||
const toastIndex = relevantToasts.findIndex((t) => t.id === toast2.id);
|
||||
const toastsBefore = relevantToasts.filter((toast3, i) => i < toastIndex && toast3.visible).length;
|
||||
const offset = relevantToasts.filter((t) => t.visible).slice(...reverseOrder ? [toastsBefore + 1] : [0, toastsBefore]).reduce((acc, t) => acc + (t.height || 0) + gutter, 0);
|
||||
return offset;
|
||||
}
|
||||
const handlers = {
|
||||
startPause() {
|
||||
startPause(Date.now());
|
||||
},
|
||||
endPause() {
|
||||
endPause(Date.now());
|
||||
},
|
||||
updateHeight: (toastId, height) => {
|
||||
update({ id: toastId, height });
|
||||
},
|
||||
calculateOffset
|
||||
};
|
||||
function useToaster(toastOptions) {
|
||||
const { toasts, pausedAt } = useToasterStore(toastOptions);
|
||||
const timeouts = /* @__PURE__ */ new Map();
|
||||
let _pausedAt;
|
||||
const unsubscribes = [
|
||||
pausedAt.subscribe(($pausedAt) => {
|
||||
if ($pausedAt) {
|
||||
for (const [, timeoutId] of timeouts) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
timeouts.clear();
|
||||
}
|
||||
_pausedAt = $pausedAt;
|
||||
}),
|
||||
toasts.subscribe(($toasts) => {
|
||||
if (_pausedAt) {
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
for (const t of $toasts) {
|
||||
if (timeouts.has(t.id)) {
|
||||
continue;
|
||||
}
|
||||
if (t.duration === Infinity) {
|
||||
continue;
|
||||
}
|
||||
const durationLeft = (t.duration || 0) + t.pauseDuration - (now - t.createdAt);
|
||||
if (durationLeft < 0) {
|
||||
if (t.visible) {
|
||||
toast.dismiss(t.id);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
timeouts.set(t.id, setTimeout(() => toast.dismiss(t.id), durationLeft));
|
||||
}
|
||||
})
|
||||
];
|
||||
onDestroy(() => {
|
||||
for (const unsubscribe of unsubscribes) {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
return { toasts, handlers };
|
||||
}
|
||||
const css$7 = {
|
||||
code: "div.svelte-lzwg39{width:20px;opacity:0;height:20px;border-radius:10px;background:var(--primary, #61d345);position:relative;transform:rotate(45deg);animation:svelte-lzwg39-circleAnimation 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;animation-delay:100ms}div.svelte-lzwg39::after{content:'';box-sizing:border-box;animation:svelte-lzwg39-checkmarkAnimation 0.2s ease-out forwards;opacity:0;animation-delay:200ms;position:absolute;border-right:2px solid;border-bottom:2px solid;border-color:var(--secondary, #fff);bottom:6px;left:6px;height:10px;width:6px}@keyframes svelte-lzwg39-circleAnimation{from{transform:scale(0) rotate(45deg);opacity:0}to{transform:scale(1) rotate(45deg);opacity:1}}@keyframes svelte-lzwg39-checkmarkAnimation{0%{height:0;width:0;opacity:0}40%{height:0;width:6px;opacity:1}100%{opacity:1;height:10px}}",
|
||||
map: null
|
||||
};
|
||||
const CheckmarkIcon = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let { primary = "#61d345" } = $$props;
|
||||
let { secondary = "#fff" } = $$props;
|
||||
if ($$props.primary === void 0 && $$bindings.primary && primary !== void 0)
|
||||
$$bindings.primary(primary);
|
||||
if ($$props.secondary === void 0 && $$bindings.secondary && secondary !== void 0)
|
||||
$$bindings.secondary(secondary);
|
||||
$$result.css.add(css$7);
|
||||
return `
|
||||
|
||||
|
||||
<div class="svelte-lzwg39"${add_styles({
|
||||
"--primary": primary,
|
||||
"--secondary": secondary
|
||||
})}></div>`;
|
||||
});
|
||||
const css$6 = {
|
||||
code: "div.svelte-10jnndo{width:20px;opacity:0;height:20px;border-radius:10px;background:var(--primary, #ff4b4b);position:relative;transform:rotate(45deg);animation:svelte-10jnndo-circleAnimation 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;animation-delay:100ms}div.svelte-10jnndo::after,div.svelte-10jnndo::before{content:'';animation:svelte-10jnndo-firstLineAnimation 0.15s ease-out forwards;animation-delay:150ms;position:absolute;border-radius:3px;opacity:0;background:var(--secondary, #fff);bottom:9px;left:4px;height:2px;width:12px}div.svelte-10jnndo:before{animation:svelte-10jnndo-secondLineAnimation 0.15s ease-out forwards;animation-delay:180ms;transform:rotate(90deg)}@keyframes svelte-10jnndo-circleAnimation{from{transform:scale(0) rotate(45deg);opacity:0}to{transform:scale(1) rotate(45deg);opacity:1}}@keyframes svelte-10jnndo-firstLineAnimation{from{transform:scale(0);opacity:0}to{transform:scale(1);opacity:1}}@keyframes svelte-10jnndo-secondLineAnimation{from{transform:scale(0) rotate(90deg);opacity:0}to{transform:scale(1) rotate(90deg);opacity:1}}",
|
||||
map: null
|
||||
};
|
||||
const ErrorIcon = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let { primary = "#ff4b4b" } = $$props;
|
||||
let { secondary = "#fff" } = $$props;
|
||||
if ($$props.primary === void 0 && $$bindings.primary && primary !== void 0)
|
||||
$$bindings.primary(primary);
|
||||
if ($$props.secondary === void 0 && $$bindings.secondary && secondary !== void 0)
|
||||
$$bindings.secondary(secondary);
|
||||
$$result.css.add(css$6);
|
||||
return `
|
||||
|
||||
|
||||
<div class="svelte-10jnndo"${add_styles({
|
||||
"--primary": primary,
|
||||
"--secondary": secondary
|
||||
})}></div>`;
|
||||
});
|
||||
const css$5 = {
|
||||
code: "div.svelte-bj4lu8{width:12px;height:12px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--secondary, #e0e0e0);border-right-color:var(--primary, #616161);animation:svelte-bj4lu8-rotate 1s linear infinite}@keyframes svelte-bj4lu8-rotate{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",
|
||||
map: null
|
||||
};
|
||||
const LoaderIcon = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let { primary = "#616161" } = $$props;
|
||||
let { secondary = "#e0e0e0" } = $$props;
|
||||
if ($$props.primary === void 0 && $$bindings.primary && primary !== void 0)
|
||||
$$bindings.primary(primary);
|
||||
if ($$props.secondary === void 0 && $$bindings.secondary && secondary !== void 0)
|
||||
$$bindings.secondary(secondary);
|
||||
$$result.css.add(css$5);
|
||||
return `
|
||||
|
||||
|
||||
<div class="svelte-bj4lu8"${add_styles({
|
||||
"--primary": primary,
|
||||
"--secondary": secondary
|
||||
})}></div>`;
|
||||
});
|
||||
const css$4 = {
|
||||
code: ".indicator.svelte-1c92bpz{position:relative;display:flex;justify-content:center;align-items:center;min-width:20px;min-height:20px}.status.svelte-1c92bpz{position:absolute}.animated.svelte-1c92bpz{position:relative;transform:scale(0.6);opacity:0.4;min-width:20px;animation:svelte-1c92bpz-enter 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards}@keyframes svelte-1c92bpz-enter{from{transform:scale(0.6);opacity:0.4}to{transform:scale(1);opacity:1}}",
|
||||
map: null
|
||||
};
|
||||
const ToastIcon = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let type;
|
||||
let icon;
|
||||
let iconTheme;
|
||||
let { toast: toast2 } = $$props;
|
||||
if ($$props.toast === void 0 && $$bindings.toast && toast2 !== void 0)
|
||||
$$bindings.toast(toast2);
|
||||
$$result.css.add(css$4);
|
||||
({ type, icon, iconTheme } = toast2);
|
||||
return `${typeof icon === "string" ? `<div class="animated svelte-1c92bpz">${escape(icon)}</div>` : `${typeof icon !== "undefined" ? `${validate_component(icon || missing_component, "svelte:component").$$render($$result, {}, {}, {})}` : `${type !== "blank" ? `<div class="indicator svelte-1c92bpz">${validate_component(LoaderIcon, "LoaderIcon").$$render($$result, Object.assign({}, iconTheme), {}, {})}
|
||||
${type !== "loading" ? `<div class="status svelte-1c92bpz">${type === "error" ? `${validate_component(ErrorIcon, "ErrorIcon").$$render($$result, Object.assign({}, iconTheme), {}, {})}` : `${validate_component(CheckmarkIcon, "CheckmarkIcon").$$render($$result, Object.assign({}, iconTheme), {}, {})}`}</div>` : ``}</div>` : ``}`}`}`;
|
||||
});
|
||||
const css$3 = {
|
||||
code: ".message.svelte-o805t1{display:flex;justify-content:center;margin:4px 10px;color:inherit;flex:1 1 auto;white-space:pre-line}",
|
||||
map: null
|
||||
};
|
||||
const ToastMessage = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let { toast: toast2 } = $$props;
|
||||
if ($$props.toast === void 0 && $$bindings.toast && toast2 !== void 0)
|
||||
$$bindings.toast(toast2);
|
||||
$$result.css.add(css$3);
|
||||
return `<div${spread([{ class: "message" }, escape_object(toast2.ariaProps)], { classes: "svelte-o805t1" })}>${typeof toast2.message === "string" ? `${escape(toast2.message)}` : `${validate_component(toast2.message || missing_component, "svelte:component").$$render($$result, { toast: toast2 }, {}, {})}`}
|
||||
</div>`;
|
||||
});
|
||||
const css$2 = {
|
||||
code: "@keyframes svelte-15lyehg-enterAnimation{0%{transform:translate3d(0, calc(var(--factor) * -200%), 0) scale(0.6);opacity:0.5}100%{transform:translate3d(0, 0, 0) scale(1);opacity:1}}@keyframes svelte-15lyehg-exitAnimation{0%{transform:translate3d(0, 0, -1px) scale(1);opacity:1}100%{transform:translate3d(0, calc(var(--factor) * -150%), -1px) scale(0.6);opacity:0}}@keyframes svelte-15lyehg-fadeInAnimation{0%{opacity:0}100%{opacity:1}}@keyframes svelte-15lyehg-fadeOutAnimation{0%{opacity:1}100%{opacity:0}}.base.svelte-15lyehg{display:flex;align-items:center;background:#fff;color:#363636;line-height:1.3;will-change:transform;box-shadow:0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05);max-width:350px;pointer-events:auto;padding:8px 10px;border-radius:8px}.transparent.svelte-15lyehg{opacity:0}.enter.svelte-15lyehg{animation:svelte-15lyehg-enterAnimation 0.35s cubic-bezier(0.21, 1.02, 0.73, 1) forwards}.exit.svelte-15lyehg{animation:svelte-15lyehg-exitAnimation 0.4s cubic-bezier(0.06, 0.71, 0.55, 1) forwards}.fadeIn.svelte-15lyehg{animation:svelte-15lyehg-fadeInAnimation 0.35s cubic-bezier(0.21, 1.02, 0.73, 1) forwards}.fadeOut.svelte-15lyehg{animation:svelte-15lyehg-fadeOutAnimation 0.4s cubic-bezier(0.06, 0.71, 0.55, 1) forwards}",
|
||||
map: null
|
||||
};
|
||||
const ToastBar = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let { toast: toast2 } = $$props;
|
||||
let { position = void 0 } = $$props;
|
||||
let { style = "" } = $$props;
|
||||
let { Component = void 0 } = $$props;
|
||||
let factor;
|
||||
let animation;
|
||||
if ($$props.toast === void 0 && $$bindings.toast && toast2 !== void 0)
|
||||
$$bindings.toast(toast2);
|
||||
if ($$props.position === void 0 && $$bindings.position && position !== void 0)
|
||||
$$bindings.position(position);
|
||||
if ($$props.style === void 0 && $$bindings.style && style !== void 0)
|
||||
$$bindings.style(style);
|
||||
if ($$props.Component === void 0 && $$bindings.Component && Component !== void 0)
|
||||
$$bindings.Component(Component);
|
||||
$$result.css.add(css$2);
|
||||
{
|
||||
{
|
||||
const top = (toast2.position || position || "top-center").includes("top");
|
||||
factor = top ? 1 : -1;
|
||||
const [enter, exit] = prefersReducedMotion() ? ["fadeIn", "fadeOut"] : ["enter", "exit"];
|
||||
animation = toast2.visible ? enter : exit;
|
||||
}
|
||||
}
|
||||
return `<div class="${"base " + escape(toast2.height ? animation : "transparent", true) + " " + escape(toast2.className || "", true) + " svelte-15lyehg"}"${add_styles(merge_ssr_styles(escape(style, true) + "; " + escape(toast2.style, true), { "--factor": factor }))}>${Component ? `${validate_component(Component || missing_component, "svelte:component").$$render($$result, {}, {}, {
|
||||
message: () => {
|
||||
return `${validate_component(ToastMessage, "ToastMessage").$$render($$result, { toast: toast2, slot: "message" }, {}, {})}`;
|
||||
},
|
||||
icon: () => {
|
||||
return `${validate_component(ToastIcon, "ToastIcon").$$render($$result, { toast: toast2, slot: "icon" }, {}, {})}`;
|
||||
}
|
||||
})}` : `${slots.default ? slots.default({ ToastIcon, ToastMessage, toast: toast2 }) : `
|
||||
${validate_component(ToastIcon, "ToastIcon").$$render($$result, { toast: toast2 }, {}, {})}
|
||||
${validate_component(ToastMessage, "ToastMessage").$$render($$result, { toast: toast2 }, {}, {})}
|
||||
`}`}
|
||||
</div>`;
|
||||
});
|
||||
const css$1 = {
|
||||
code: ".wrapper.svelte-1pakgpd{left:0;right:0;display:flex;position:absolute;transform:translateY(calc(var(--offset, 16px) * var(--factor) * 1px))}.transition.svelte-1pakgpd{transition:all 230ms cubic-bezier(0.21, 1.02, 0.73, 1)}.active.svelte-1pakgpd{z-index:9999}.active.svelte-1pakgpd>*{pointer-events:auto}",
|
||||
map: null
|
||||
};
|
||||
const ToastWrapper = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let top;
|
||||
let bottom;
|
||||
let factor;
|
||||
let justifyContent;
|
||||
let { toast: toast2 } = $$props;
|
||||
let { setHeight } = $$props;
|
||||
let wrapperEl;
|
||||
if ($$props.toast === void 0 && $$bindings.toast && toast2 !== void 0)
|
||||
$$bindings.toast(toast2);
|
||||
if ($$props.setHeight === void 0 && $$bindings.setHeight && setHeight !== void 0)
|
||||
$$bindings.setHeight(setHeight);
|
||||
$$result.css.add(css$1);
|
||||
top = toast2.position?.includes("top") ? 0 : null;
|
||||
bottom = toast2.position?.includes("bottom") ? 0 : null;
|
||||
factor = toast2.position?.includes("top") ? 1 : -1;
|
||||
justifyContent = toast2.position?.includes("center") && "center" || toast2.position?.includes("right") && "flex-end" || null;
|
||||
return `<div class="${[
|
||||
"wrapper svelte-1pakgpd",
|
||||
(toast2.visible ? "active" : "") + " " + (!prefersReducedMotion() ? "transition" : "")
|
||||
].join(" ").trim()}"${add_styles({
|
||||
"--factor": factor,
|
||||
"--offset": toast2.offset,
|
||||
top,
|
||||
bottom,
|
||||
"justify-content": justifyContent
|
||||
})}${add_attribute("this", wrapperEl, 0)}>${toast2.type === "custom" ? `${validate_component(ToastMessage, "ToastMessage").$$render($$result, { toast: toast2 }, {}, {})}` : `${slots.default ? slots.default({ toast: toast2 }) : `
|
||||
${validate_component(ToastBar, "ToastBar").$$render($$result, { toast: toast2, position: toast2.position }, {}, {})}
|
||||
`}`}
|
||||
</div>`;
|
||||
});
|
||||
const css = {
|
||||
code: ".toaster.svelte-jyff3d{--default-offset:16px;position:fixed;z-index:9999;top:var(--default-offset);left:var(--default-offset);right:var(--default-offset);bottom:var(--default-offset);pointer-events:none}",
|
||||
map: null
|
||||
};
|
||||
const Toaster = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let $toasts, $$unsubscribe_toasts;
|
||||
let { reverseOrder = false } = $$props;
|
||||
let { position = "top-center" } = $$props;
|
||||
let { toastOptions = void 0 } = $$props;
|
||||
let { gutter = 8 } = $$props;
|
||||
let { containerStyle = void 0 } = $$props;
|
||||
let { containerClassName = void 0 } = $$props;
|
||||
const { toasts, handlers: handlers2 } = useToaster(toastOptions);
|
||||
$$unsubscribe_toasts = subscribe(toasts, (value) => $toasts = value);
|
||||
let _toasts;
|
||||
if ($$props.reverseOrder === void 0 && $$bindings.reverseOrder && reverseOrder !== void 0)
|
||||
$$bindings.reverseOrder(reverseOrder);
|
||||
if ($$props.position === void 0 && $$bindings.position && position !== void 0)
|
||||
$$bindings.position(position);
|
||||
if ($$props.toastOptions === void 0 && $$bindings.toastOptions && toastOptions !== void 0)
|
||||
$$bindings.toastOptions(toastOptions);
|
||||
if ($$props.gutter === void 0 && $$bindings.gutter && gutter !== void 0)
|
||||
$$bindings.gutter(gutter);
|
||||
if ($$props.containerStyle === void 0 && $$bindings.containerStyle && containerStyle !== void 0)
|
||||
$$bindings.containerStyle(containerStyle);
|
||||
if ($$props.containerClassName === void 0 && $$bindings.containerClassName && containerClassName !== void 0)
|
||||
$$bindings.containerClassName(containerClassName);
|
||||
$$result.css.add(css);
|
||||
_toasts = $toasts.map((toast2) => ({
|
||||
...toast2,
|
||||
position: toast2.position || position,
|
||||
offset: handlers2.calculateOffset(toast2, $toasts, {
|
||||
reverseOrder,
|
||||
gutter,
|
||||
defaultPosition: position
|
||||
})
|
||||
}));
|
||||
$$unsubscribe_toasts();
|
||||
return `<div class="${"toaster " + escape(containerClassName || "", true) + " svelte-jyff3d"}"${add_attribute("style", containerStyle, 0)}>${each(_toasts, (toast2) => {
|
||||
return `${validate_component(ToastWrapper, "ToastWrapper").$$render(
|
||||
$$result,
|
||||
{
|
||||
toast: toast2,
|
||||
setHeight: (height) => handlers2.updateHeight(toast2.id, height)
|
||||
},
|
||||
{},
|
||||
{}
|
||||
)}`;
|
||||
})}
|
||||
</div>`;
|
||||
});
|
||||
const Layout = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
return `${validate_component(Toaster, "Toaster").$$render($$result, {}, {}, {})}
|
||||
<div class="flex flex-col h-screen sm:justify-center sm:items-center"><div class="mx-auto px-3 md:px-0 sm:w-full md:w-4/5 lg:w-3/5 pt-24 sm:pt-0">${slots.default ? slots.default({}) : ``}</div></div>`;
|
||||
});
|
||||
export {
|
||||
Layout as default
|
||||
};
|
||||
@@ -1,39 +0,0 @@
|
||||
import { c as create_ssr_component, e as escape, i as each, g as add_attribute } from "../../chunks/index3.js";
|
||||
import "../../chunks/Toaster.svelte_svelte_type_style_lang.js";
|
||||
const Page = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let status, rooms;
|
||||
let { data } = $$props;
|
||||
let eth_pk = "";
|
||||
let room = "";
|
||||
let create_new_room = false;
|
||||
const filled_in = () => {
|
||||
return !(eth_pk.length > 0 && room.length > 0);
|
||||
};
|
||||
if ($$props.data === void 0 && $$bindings.data && data !== void 0)
|
||||
$$bindings.data(data);
|
||||
({ status, rooms } = data);
|
||||
return `<div class="flex flex-col justify-center"><div class="title"><h1 class="text-3xl font-bold text-center">Chatr: a Websocket chatroom</h1></div>
|
||||
<div class="join self-center"></div>
|
||||
<div class="rooms self-center my-5"><div class="flex justify-between py-2"><h2 class="text-xl font-bold ">List of active chatroom's
|
||||
</h2>
|
||||
<button class="btn btn-square btn-sm btn-accent">↻</button></div>
|
||||
${status && rooms.length < 1 ? `<div class="card bg-base-300 w-96 shadow-xl text-center"><div class="card-body"><h3 class="card-title ">${escape(status)}</h3></div></div>` : ``}
|
||||
${rooms ? `${each(rooms, (room2) => {
|
||||
return `<button class="card bg-base-300 w-96 shadow-xl my-3 w-full"><div class="card-body"><div class="flex justify-between"><h2 class="card-title">${escape(room2)}</h2>
|
||||
<button class="btn btn-primary btn-md">Select Room</button>
|
||||
</div></div>
|
||||
</button>`;
|
||||
})}` : ``}</div>
|
||||
<div class="create self-center my-5 w-[40rem]"><div><label class="label" for="eth-private-key"><span class="label-text">Eth Private Key</span></label>
|
||||
<input id="eth-private-key" placeholder="Eth Private Key" class="input input-bordered input-primary w-full bg-base-200 mb-4 mr-3"${add_attribute("value", eth_pk, 0)}></div>
|
||||
<div><label class="label" for="room-name"><span class="label-text">Room name</span></label>
|
||||
<input id="room-name" placeholder="Room Name" class="input input-bordered input-primary w-full bg-base-200 mb-4 mr-3"${add_attribute("value", room, 0)}></div>
|
||||
<div class="form-control"><label class="label cursor-pointer"><span class="label-text">Create Room</span>
|
||||
<input type="checkbox" class="checkbox checkbox-primary"${add_attribute("checked", create_new_room, 1)}></label></div>
|
||||
<button class="btn btn-primary" ${filled_in() ? "disabled" : ""}>Join Room.</button></div>
|
||||
<div class="github self-center"><p>Check out <a class="link link-accent" href="https://github.com/0xLaurens/chatr" target="_blank" rel="noreferrer">Chatr</a>, to view the source code!
|
||||
</p></div></div>`;
|
||||
});
|
||||
export {
|
||||
Page as default
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
import { p as public_env } from "../../chunks/shared-server.js";
|
||||
const load = async ({ fetch }) => {
|
||||
try {
|
||||
let url = `${public_env.PUBLIC_API_URL}`;
|
||||
if (url.endsWith("/")) {
|
||||
url = url.slice(0, -1);
|
||||
}
|
||||
const res = await fetch(`${url}/rooms`);
|
||||
return await res.json();
|
||||
} catch (e) {
|
||||
return {
|
||||
status: "API offline (try again in a min)",
|
||||
rooms: []
|
||||
};
|
||||
}
|
||||
};
|
||||
export {
|
||||
load
|
||||
};
|
||||
@@ -1,128 +0,0 @@
|
||||
import { c as create_ssr_component, h as subscribe, o as onDestroy, g as add_attribute, e as escape, i as each } from "../../../chunks/index3.js";
|
||||
import { w as writable } from "../../../chunks/index2.js";
|
||||
import { p as public_env } from "../../../chunks/shared-server.js";
|
||||
import { t as toast } from "../../../chunks/Toaster.svelte_svelte_type_style_lang.js";
|
||||
import "../../../chunks/index.js";
|
||||
const eth_private_key = writable("");
|
||||
const group = writable("");
|
||||
const createNewRoom = writable(false);
|
||||
function guard(name) {
|
||||
return () => {
|
||||
throw new Error(`Cannot call ${name}(...) on the server`);
|
||||
};
|
||||
}
|
||||
const goto = guard("goto");
|
||||
const Page = create_ssr_component(($$result, $$props, $$bindings, slots) => {
|
||||
let $group, $$unsubscribe_group;
|
||||
let $eth_private_key, $$unsubscribe_eth_private_key;
|
||||
let $createNewRoom, $$unsubscribe_createNewRoom;
|
||||
$$unsubscribe_group = subscribe(group, (value) => $group = value);
|
||||
$$unsubscribe_eth_private_key = subscribe(eth_private_key, (value) => $eth_private_key = value);
|
||||
$$unsubscribe_createNewRoom = subscribe(createNewRoom, (value) => $createNewRoom = value);
|
||||
let status = "🔴";
|
||||
let statusTip = "Disconnected";
|
||||
let message = "";
|
||||
let messages = [];
|
||||
let socket;
|
||||
let interval;
|
||||
let delay = 2e3;
|
||||
let timeout = false;
|
||||
let currentVotingProposal = null;
|
||||
let showVotingUI = false;
|
||||
function connect() {
|
||||
socket = new WebSocket(`${public_env.PUBLIC_WEBSOCKET_URL}/ws`);
|
||||
socket.addEventListener("open", () => {
|
||||
status = "🟢";
|
||||
statusTip = "Connected";
|
||||
timeout = false;
|
||||
socket.send(JSON.stringify({
|
||||
eth_private_key: $eth_private_key,
|
||||
group_id: $group,
|
||||
should_create: $createNewRoom
|
||||
}));
|
||||
});
|
||||
socket.addEventListener("close", () => {
|
||||
status = "🔴";
|
||||
statusTip = "Disconnected";
|
||||
if (timeout == false) {
|
||||
delay = 2e3;
|
||||
timeout = true;
|
||||
}
|
||||
});
|
||||
socket.addEventListener("message", function(event) {
|
||||
if (event.data == "Username already taken.") {
|
||||
toast.error(event.data);
|
||||
goto("/");
|
||||
} else {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === "voting_proposal") {
|
||||
currentVotingProposal = data.proposal;
|
||||
showVotingUI = true;
|
||||
toast.success("New voting proposal received!");
|
||||
} else {
|
||||
messages = [...messages, event.data];
|
||||
}
|
||||
} catch (e) {
|
||||
messages = [...messages, event.data];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
onDestroy(() => {
|
||||
if (socket) {
|
||||
socket.close();
|
||||
}
|
||||
if (interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
timeout = false;
|
||||
});
|
||||
{
|
||||
{
|
||||
if (interval || !timeout && interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
if (timeout == true) {
|
||||
interval = setInterval(
|
||||
() => {
|
||||
if (delay < 3e4)
|
||||
delay = delay * 2;
|
||||
console.log("reconnecting in:", delay);
|
||||
connect();
|
||||
},
|
||||
delay
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
$$unsubscribe_group();
|
||||
$$unsubscribe_eth_private_key();
|
||||
$$unsubscribe_createNewRoom();
|
||||
return `<div class="container mx-auto p-4 max-w-4xl"><div class="flex justify-between items-center mb-8"><h1 class="text-3xl font-bold">MLS Chat <span class="tooltip"${add_attribute("data-tip", statusTip, 0)}>${escape(status)}</span></h1>
|
||||
<button class="btn btn-accent">Clear Messages</button></div>
|
||||
|
||||
|
||||
<div class="text-center mb-4"><button class="btn btn-warning btn-outline">🧪 Test Voting Proposal
|
||||
</button></div>
|
||||
|
||||
|
||||
${showVotingUI && currentVotingProposal ? `<div class="card bg-warning shadow-xl my-5"><div class="card-body"><h2 class="card-title text-warning-content">Voting Proposal</h2>
|
||||
<div class="text-warning-content"><p><strong>Group Name:</strong> ${escape(currentVotingProposal.group_name)}</p>
|
||||
<p><strong>Proposal ID:</strong> ${escape(currentVotingProposal.proposal_id)}</p>
|
||||
<p><strong>Proposal Payload:</strong></p>
|
||||
<div class="ml-4 whitespace-pre-line">${escape(currentVotingProposal.payload)}</div></div>
|
||||
<div class="card-actions justify-end mt-4"><button class="btn btn-success">Vote YES</button>
|
||||
<button class="btn btn-error">Vote NO</button>
|
||||
<button class="btn btn-ghost">Dismiss</button></div></div></div>` : ``}
|
||||
|
||||
<div class="card h-96 flex-grow bg-base-300 shadow-xl my-10"><div class="card-body"><div class="flex flex-col overflow-y-auto max-h-80 scroll-smooth">${each(messages, (msg) => {
|
||||
return `<div class="my-2">${escape(msg)}</div>`;
|
||||
})}</div></div></div>
|
||||
|
||||
<div class="message-box flex justify-end"><form><input placeholder="Message" class="input input-bordered input-primary w-[51rem] bg-base-200 mb-2"${add_attribute("value", message, 0)}>
|
||||
<button class="btn btn-primary w-full sm:w-auto btn-wide">Send</button></form></div></div>`;
|
||||
});
|
||||
export {
|
||||
Page as default
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,10 +0,0 @@
|
||||
import { g, o, s, c } from "./chunks/internal.js";
|
||||
import { a, s as s2 } from "./chunks/shared-server.js";
|
||||
export {
|
||||
g as get_hooks,
|
||||
o as options,
|
||||
s as set_assets,
|
||||
c as set_building,
|
||||
a as set_private_env,
|
||||
s2 as set_public_env
|
||||
};
|
||||
@@ -1,35 +0,0 @@
|
||||
export const manifest = {
|
||||
appDir: "_app",
|
||||
appPath: "_app",
|
||||
assets: new Set(["favicon.png"]),
|
||||
mimeTypes: {".png":"image/png"},
|
||||
_: {
|
||||
client: {"start":{"file":"_app/immutable/entry/start.530cd74f.js","imports":["_app/immutable/entry/start.530cd74f.js","_app/immutable/chunks/index.b5cfe40e.js","_app/immutable/chunks/singletons.995fdd8e.js","_app/immutable/chunks/index.0a9737cc.js"],"stylesheets":[],"fonts":[]},"app":{"file":"_app/immutable/entry/app.e73d9bc3.js","imports":["_app/immutable/entry/app.e73d9bc3.js","_app/immutable/chunks/index.b5cfe40e.js"],"stylesheets":[],"fonts":[]}},
|
||||
nodes: [
|
||||
() => import('./nodes/0.js'),
|
||||
() => import('./nodes/1.js'),
|
||||
() => import('./nodes/2.js'),
|
||||
() => import('./nodes/3.js')
|
||||
],
|
||||
routes: [
|
||||
{
|
||||
id: "/",
|
||||
pattern: /^\/$/,
|
||||
params: [],
|
||||
page: { layouts: [0], errors: [1], leaf: 2 },
|
||||
endpoint: null
|
||||
},
|
||||
{
|
||||
id: "/chat",
|
||||
pattern: /^\/chat\/?$/,
|
||||
params: [],
|
||||
page: { layouts: [0], errors: [1], leaf: 3 },
|
||||
endpoint: null
|
||||
}
|
||||
],
|
||||
matchers: async () => {
|
||||
|
||||
return { };
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,35 +0,0 @@
|
||||
export const manifest = {
|
||||
appDir: "_app",
|
||||
appPath: "_app",
|
||||
assets: new Set(["favicon.png"]),
|
||||
mimeTypes: {".png":"image/png"},
|
||||
_: {
|
||||
client: {"start":{"file":"_app/immutable/entry/start.530cd74f.js","imports":["_app/immutable/entry/start.530cd74f.js","_app/immutable/chunks/index.b5cfe40e.js","_app/immutable/chunks/singletons.995fdd8e.js","_app/immutable/chunks/index.0a9737cc.js"],"stylesheets":[],"fonts":[]},"app":{"file":"_app/immutable/entry/app.e73d9bc3.js","imports":["_app/immutable/entry/app.e73d9bc3.js","_app/immutable/chunks/index.b5cfe40e.js"],"stylesheets":[],"fonts":[]}},
|
||||
nodes: [
|
||||
() => import('./nodes/0.js'),
|
||||
() => import('./nodes/1.js'),
|
||||
() => import('./nodes/2.js'),
|
||||
() => import('./nodes/3.js')
|
||||
],
|
||||
routes: [
|
||||
{
|
||||
id: "/",
|
||||
pattern: /^\/$/,
|
||||
params: [],
|
||||
page: { layouts: [0], errors: [1], leaf: 2 },
|
||||
endpoint: null
|
||||
},
|
||||
{
|
||||
id: "/chat",
|
||||
pattern: /^\/chat\/?$/,
|
||||
params: [],
|
||||
page: { layouts: [0], errors: [1], leaf: 3 },
|
||||
endpoint: null
|
||||
}
|
||||
],
|
||||
matchers: async () => {
|
||||
|
||||
return { };
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,8 +0,0 @@
|
||||
|
||||
|
||||
export const index = 0;
|
||||
export const component = async () => (await import('../entries/pages/_layout.svelte.js')).default;
|
||||
export const file = '_app/immutable/entry/_layout.svelte.04ad52d9.js';
|
||||
export const imports = ["_app/immutable/entry/_layout.svelte.04ad52d9.js","_app/immutable/chunks/index.b5cfe40e.js","_app/immutable/chunks/Toaster.svelte_svelte_type_style_lang.9dbf3392.js","_app/immutable/chunks/index.0a9737cc.js"];
|
||||
export const stylesheets = ["_app/immutable/assets/_layout.785cca11.css","_app/immutable/assets/Toaster.5032d475.css"];
|
||||
export const fonts = [];
|
||||
@@ -1,8 +0,0 @@
|
||||
|
||||
|
||||
export const index = 1;
|
||||
export const component = async () => (await import('../entries/fallbacks/error.svelte.js')).default;
|
||||
export const file = '_app/immutable/entry/error.svelte.6777b5ad.js';
|
||||
export const imports = ["_app/immutable/entry/error.svelte.6777b5ad.js","_app/immutable/chunks/index.b5cfe40e.js","_app/immutable/chunks/singletons.995fdd8e.js","_app/immutable/chunks/index.0a9737cc.js"];
|
||||
export const stylesheets = [];
|
||||
export const fonts = [];
|
||||
@@ -1,10 +0,0 @@
|
||||
import * as universal from '../entries/pages/_page.ts.js';
|
||||
|
||||
export const index = 2;
|
||||
export const component = async () => (await import('../entries/pages/_page.svelte.js')).default;
|
||||
export const file = '_app/immutable/entry/_page.svelte.0bc1703f.js';
|
||||
export { universal };
|
||||
export const universal_id = "src/routes/+page.ts";
|
||||
export const imports = ["_app/immutable/entry/_page.svelte.0bc1703f.js","_app/immutable/chunks/index.b5cfe40e.js","_app/immutable/chunks/navigation.6147d380.js","_app/immutable/chunks/index.0a9737cc.js","_app/immutable/chunks/singletons.995fdd8e.js","_app/immutable/chunks/public.f5860d05.js","_app/immutable/chunks/Toaster.svelte_svelte_type_style_lang.9dbf3392.js","_app/immutable/entry/_page.ts.703a6e58.js","_app/immutable/chunks/public.f5860d05.js","_app/immutable/chunks/_page.55f56988.js"];
|
||||
export const stylesheets = ["_app/immutable/assets/Toaster.5032d475.css"];
|
||||
export const fonts = [];
|
||||
@@ -1,8 +0,0 @@
|
||||
|
||||
|
||||
export const index = 3;
|
||||
export const component = async () => (await import('../entries/pages/chat/_page.svelte.js')).default;
|
||||
export const file = '_app/immutable/entry/chat-page.svelte.d01d3c01.js';
|
||||
export const imports = ["_app/immutable/entry/chat-page.svelte.d01d3c01.js","_app/immutable/chunks/index.b5cfe40e.js","_app/immutable/chunks/navigation.6147d380.js","_app/immutable/chunks/index.0a9737cc.js","_app/immutable/chunks/singletons.995fdd8e.js","_app/immutable/chunks/public.f5860d05.js","_app/immutable/chunks/Toaster.svelte_svelte_type_style_lang.9dbf3392.js"];
|
||||
export const stylesheets = ["_app/immutable/assets/Toaster.5032d475.css"];
|
||||
export const fonts = [];
|
||||
@@ -1,361 +0,0 @@
|
||||
import './shims.js';
|
||||
import { Server } from './server/index.js';
|
||||
import 'assert';
|
||||
import 'net';
|
||||
import 'http';
|
||||
import 'stream';
|
||||
import 'buffer';
|
||||
import 'util';
|
||||
import 'querystring';
|
||||
import 'stream/web';
|
||||
import 'worker_threads';
|
||||
import 'perf_hooks';
|
||||
import 'util/types';
|
||||
import 'url';
|
||||
import 'string_decoder';
|
||||
import 'events';
|
||||
import 'tls';
|
||||
import 'async_hooks';
|
||||
import 'console';
|
||||
import 'zlib';
|
||||
import 'crypto';
|
||||
|
||||
var setCookie = {exports: {}};
|
||||
|
||||
var defaultParseOptions = {
|
||||
decodeValues: true,
|
||||
map: false,
|
||||
silent: false,
|
||||
};
|
||||
|
||||
function isNonEmptyString(str) {
|
||||
return typeof str === "string" && !!str.trim();
|
||||
}
|
||||
|
||||
function parseString(setCookieValue, options) {
|
||||
var parts = setCookieValue.split(";").filter(isNonEmptyString);
|
||||
|
||||
var nameValuePairStr = parts.shift();
|
||||
var parsed = parseNameValuePair(nameValuePairStr);
|
||||
var name = parsed.name;
|
||||
var value = parsed.value;
|
||||
|
||||
options = options
|
||||
? Object.assign({}, defaultParseOptions, options)
|
||||
: defaultParseOptions;
|
||||
|
||||
try {
|
||||
value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
|
||||
} catch (e) {
|
||||
console.error(
|
||||
"set-cookie-parser encountered an error while decoding a cookie with value '" +
|
||||
value +
|
||||
"'. Set options.decodeValues to false to disable this feature.",
|
||||
e
|
||||
);
|
||||
}
|
||||
|
||||
var cookie = {
|
||||
name: name,
|
||||
value: value,
|
||||
};
|
||||
|
||||
parts.forEach(function (part) {
|
||||
var sides = part.split("=");
|
||||
var key = sides.shift().trimLeft().toLowerCase();
|
||||
var value = sides.join("=");
|
||||
if (key === "expires") {
|
||||
cookie.expires = new Date(value);
|
||||
} else if (key === "max-age") {
|
||||
cookie.maxAge = parseInt(value, 10);
|
||||
} else if (key === "secure") {
|
||||
cookie.secure = true;
|
||||
} else if (key === "httponly") {
|
||||
cookie.httpOnly = true;
|
||||
} else if (key === "samesite") {
|
||||
cookie.sameSite = value;
|
||||
} else {
|
||||
cookie[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return cookie;
|
||||
}
|
||||
|
||||
function parseNameValuePair(nameValuePairStr) {
|
||||
// Parses name-value-pair according to rfc6265bis draft
|
||||
|
||||
var name = "";
|
||||
var value = "";
|
||||
var nameValueArr = nameValuePairStr.split("=");
|
||||
if (nameValueArr.length > 1) {
|
||||
name = nameValueArr.shift();
|
||||
value = nameValueArr.join("="); // everything after the first =, joined by a "=" if there was more than one part
|
||||
} else {
|
||||
value = nameValuePairStr;
|
||||
}
|
||||
|
||||
return { name: name, value: value };
|
||||
}
|
||||
|
||||
function parse(input, options) {
|
||||
options = options
|
||||
? Object.assign({}, defaultParseOptions, options)
|
||||
: defaultParseOptions;
|
||||
|
||||
if (!input) {
|
||||
if (!options.map) {
|
||||
return [];
|
||||
} else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
if (input.headers && input.headers["set-cookie"]) {
|
||||
// fast-path for node.js (which automatically normalizes header names to lower-case
|
||||
input = input.headers["set-cookie"];
|
||||
} else if (input.headers) {
|
||||
// slow-path for other environments - see #25
|
||||
var sch =
|
||||
input.headers[
|
||||
Object.keys(input.headers).find(function (key) {
|
||||
return key.toLowerCase() === "set-cookie";
|
||||
})
|
||||
];
|
||||
// warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
|
||||
if (!sch && input.headers.cookie && !options.silent) {
|
||||
console.warn(
|
||||
"Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
|
||||
);
|
||||
}
|
||||
input = sch;
|
||||
}
|
||||
if (!Array.isArray(input)) {
|
||||
input = [input];
|
||||
}
|
||||
|
||||
options = options
|
||||
? Object.assign({}, defaultParseOptions, options)
|
||||
: defaultParseOptions;
|
||||
|
||||
if (!options.map) {
|
||||
return input.filter(isNonEmptyString).map(function (str) {
|
||||
return parseString(str, options);
|
||||
});
|
||||
} else {
|
||||
var cookies = {};
|
||||
return input.filter(isNonEmptyString).reduce(function (cookies, str) {
|
||||
var cookie = parseString(str, options);
|
||||
cookies[cookie.name] = cookie;
|
||||
return cookies;
|
||||
}, cookies);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
|
||||
that are within a single set-cookie field-value, such as in the Expires portion.
|
||||
|
||||
This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
|
||||
Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
|
||||
React Native's fetch does this for *every* header, including set-cookie.
|
||||
|
||||
Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
|
||||
Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
|
||||
*/
|
||||
function splitCookiesString(cookiesString) {
|
||||
if (Array.isArray(cookiesString)) {
|
||||
return cookiesString;
|
||||
}
|
||||
if (typeof cookiesString !== "string") {
|
||||
return [];
|
||||
}
|
||||
|
||||
var cookiesStrings = [];
|
||||
var pos = 0;
|
||||
var start;
|
||||
var ch;
|
||||
var lastComma;
|
||||
var nextStart;
|
||||
var cookiesSeparatorFound;
|
||||
|
||||
function skipWhitespace() {
|
||||
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
|
||||
pos += 1;
|
||||
}
|
||||
return pos < cookiesString.length;
|
||||
}
|
||||
|
||||
function notSpecialChar() {
|
||||
ch = cookiesString.charAt(pos);
|
||||
|
||||
return ch !== "=" && ch !== ";" && ch !== ",";
|
||||
}
|
||||
|
||||
while (pos < cookiesString.length) {
|
||||
start = pos;
|
||||
cookiesSeparatorFound = false;
|
||||
|
||||
while (skipWhitespace()) {
|
||||
ch = cookiesString.charAt(pos);
|
||||
if (ch === ",") {
|
||||
// ',' is a cookie separator if we have later first '=', not ';' or ','
|
||||
lastComma = pos;
|
||||
pos += 1;
|
||||
|
||||
skipWhitespace();
|
||||
nextStart = pos;
|
||||
|
||||
while (pos < cookiesString.length && notSpecialChar()) {
|
||||
pos += 1;
|
||||
}
|
||||
|
||||
// currently special character
|
||||
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
|
||||
// we found cookies separator
|
||||
cookiesSeparatorFound = true;
|
||||
// pos is inside the next cookie, so back up and return it.
|
||||
pos = nextStart;
|
||||
cookiesStrings.push(cookiesString.substring(start, lastComma));
|
||||
start = pos;
|
||||
} else {
|
||||
// in param ',' or param separator ';',
|
||||
// we continue from that comma
|
||||
pos = lastComma + 1;
|
||||
}
|
||||
} else {
|
||||
pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
|
||||
cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
|
||||
}
|
||||
}
|
||||
|
||||
return cookiesStrings;
|
||||
}
|
||||
|
||||
setCookie.exports = parse;
|
||||
setCookie.exports.parse = parse;
|
||||
setCookie.exports.parseString = parseString;
|
||||
var splitCookiesString_1 = setCookie.exports.splitCookiesString = splitCookiesString;
|
||||
|
||||
/**
|
||||
* Splits headers into two categories: single value and multi value
|
||||
* @param {Headers} headers
|
||||
* @returns {{
|
||||
* headers: Record<string, string>,
|
||||
* multiValueHeaders: Record<string, string[]>
|
||||
* }}
|
||||
*/
|
||||
function split_headers(headers) {
|
||||
/** @type {Record<string, string>} */
|
||||
const h = {};
|
||||
|
||||
/** @type {Record<string, string[]>} */
|
||||
const m = {};
|
||||
|
||||
headers.forEach((value, key) => {
|
||||
if (key === 'set-cookie') {
|
||||
m[key] = splitCookiesString_1(value);
|
||||
} else {
|
||||
h[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
headers: h,
|
||||
multiValueHeaders: m
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('@sveltejs/kit').SSRManifest} manifest
|
||||
* @returns {import('@netlify/functions').Handler}
|
||||
*/
|
||||
function init(manifest) {
|
||||
const server = new Server(manifest);
|
||||
|
||||
let init_promise = server.init({
|
||||
env: process.env
|
||||
});
|
||||
|
||||
return async (event, context) => {
|
||||
if (init_promise !== null) {
|
||||
await init_promise;
|
||||
init_promise = null;
|
||||
}
|
||||
|
||||
const response = await server.respond(to_request(event), {
|
||||
platform: { context },
|
||||
getClientAddress() {
|
||||
return event.headers['x-nf-client-connection-ip'];
|
||||
}
|
||||
});
|
||||
|
||||
const partial_response = {
|
||||
statusCode: response.status,
|
||||
...split_headers(response.headers)
|
||||
};
|
||||
|
||||
if (!is_text(response.headers.get('content-type'))) {
|
||||
// Function responses should be strings (or undefined), and responses with binary
|
||||
// content should be base64 encoded and set isBase64Encoded to true.
|
||||
// https://github.com/netlify/functions/blob/main/src/function/response.ts
|
||||
return {
|
||||
...partial_response,
|
||||
isBase64Encoded: true,
|
||||
body: Buffer.from(await response.arrayBuffer()).toString('base64')
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...partial_response,
|
||||
body: await response.text()
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('@netlify/functions').HandlerEvent} event
|
||||
* @returns {Request}
|
||||
*/
|
||||
function to_request(event) {
|
||||
const { httpMethod, headers, rawUrl, body, isBase64Encoded } = event;
|
||||
|
||||
/** @type {RequestInit} */
|
||||
const init = {
|
||||
method: httpMethod,
|
||||
headers: new Headers(headers)
|
||||
};
|
||||
|
||||
if (httpMethod !== 'GET' && httpMethod !== 'HEAD') {
|
||||
const encoding = isBase64Encoded ? 'base64' : 'utf-8';
|
||||
init.body = typeof body === 'string' ? Buffer.from(body, encoding) : body;
|
||||
}
|
||||
|
||||
return new Request(rawUrl, init);
|
||||
}
|
||||
|
||||
const text_types = new Set([
|
||||
'application/xml',
|
||||
'application/json',
|
||||
'application/x-www-form-urlencoded',
|
||||
'multipart/form-data'
|
||||
]);
|
||||
|
||||
/**
|
||||
* Decides how the body should be parsed based on its mime type
|
||||
*
|
||||
* @param {string | undefined | null} content_type The `content-type` header of a request/response.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function is_text(content_type) {
|
||||
if (!content_type) return true; // defaults to json
|
||||
const type = content_type.split(';')[0].toLowerCase(); // get the mime type
|
||||
|
||||
return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
|
||||
}
|
||||
|
||||
export { init };
|
||||
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
|
||||
engine-strict=true
|
||||
@@ -1,11 +0,0 @@
|
||||
FROM node:18-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm install
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 5173
|
||||
CMD [ "npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
|
||||
2656
frontend/package-lock.json
generated
2656
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,33 +0,0 @@
|
||||
{
|
||||
"name": "client",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-auto": "^2.0.0",
|
||||
"@sveltejs/adapter-netlify": "^1.0.0-next.88",
|
||||
"@sveltejs/kit": "^1.15.2",
|
||||
"@tailwindcss/typography": "^0.5.9",
|
||||
"autoprefixer": "^10.4.14",
|
||||
"daisyui": "^2.51.3",
|
||||
"postcss": "^8.4.21",
|
||||
"svelte": "^3.54.0",
|
||||
"svelte-check": "^3.0.1",
|
||||
"tailwindcss": "^3.2.7",
|
||||
"tslib": "^2.4.1",
|
||||
"typescript": "^4.9.3",
|
||||
"vite": "^4.5.2"
|
||||
},
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@sveltejs/adapter-static": "^2.0.1",
|
||||
"svelte-french-toast": "^1.0.4-beta.0",
|
||||
"svelte-preprocess": "^5.0.1"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
12
frontend/src/app.d.ts
vendored
12
frontend/src/app.d.ts
vendored
@@ -1,12 +0,0 @@
|
||||
// See https://kit.svelte.dev/docs/types#app
|
||||
// for information about these interfaces
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
// interface Locals {}
|
||||
// interface PageData {}
|
||||
// interface Platform {}
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -1,12 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||
<meta name="viewport" content="width=device-width" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,7 +0,0 @@
|
||||
import { writable } from "svelte/store";
|
||||
|
||||
export const user = writable("");
|
||||
export const channel = writable("");
|
||||
export const eth_private_key = writable("");
|
||||
export const group = writable("");
|
||||
export const createNewRoom = writable(false);
|
||||
@@ -1,11 +0,0 @@
|
||||
<script>
|
||||
import "../app.css"
|
||||
import {Toaster} from 'svelte-french-toast';
|
||||
</script>
|
||||
|
||||
<Toaster/>
|
||||
<div class="flex flex-col h-screen sm:justify-center sm:items-center">
|
||||
<div class="mx-auto px-3 md:px-0 sm:w-full md:w-4/5 lg:w-3/5 pt-24 sm:pt-0">
|
||||
<slot/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,99 +0,0 @@
|
||||
<script lang="ts">
|
||||
import {user, channel, eth_private_key, group, createNewRoom} from "$lib/stores/user"
|
||||
import {goto, invalidate} from '$app/navigation';
|
||||
import { env } from '$env/dynamic/public'
|
||||
import toast from 'svelte-french-toast';
|
||||
|
||||
let status, rooms;
|
||||
export let data;
|
||||
$:({status, rooms} = data);
|
||||
|
||||
let eth_pk = "";
|
||||
let room = "";
|
||||
let create_new_room = false;
|
||||
const join_room = () => {
|
||||
eth_private_key.set(eth_pk);
|
||||
group.set(room);
|
||||
createNewRoom.set(create_new_room);
|
||||
goto("/chat");
|
||||
}
|
||||
const select_room = (selected_room: string) => {
|
||||
room = selected_room;
|
||||
};
|
||||
const filled_in = () => {
|
||||
return !(eth_pk.length > 0 && room.length > 0);
|
||||
};
|
||||
|
||||
const reload = () => {
|
||||
toast.success("Reloaded rooms")
|
||||
let url = `${env.PUBLIC_API_URL}`;
|
||||
if (url.endsWith("/")) {
|
||||
url = url.slice(0, -1);
|
||||
}
|
||||
invalidate(`${url}/rooms`);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col justify-center">
|
||||
<div class="title">
|
||||
<h1 class="text-3xl font-bold text-center">Chatr: a Websocket chatroom</h1>
|
||||
</div>
|
||||
<div class="join self-center">
|
||||
</div>
|
||||
<div class="rooms self-center my-5">
|
||||
<div class="flex justify-between py-2">
|
||||
<h2 class="text-xl font-bold ">
|
||||
List of active chatroom's
|
||||
</h2>
|
||||
<button class="btn btn-square btn-sm btn-accent" on:click={reload}>↻</button>
|
||||
</div>
|
||||
{#if status && rooms.length < 1}
|
||||
<div class="card bg-base-300 w-96 shadow-xl text-center">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title ">{status}</h3>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{#if rooms}
|
||||
{#each rooms as room}
|
||||
<button class="card bg-base-300 w-96 shadow-xl my-3 w-full" on:click={() => select_room(room)}>
|
||||
<div class="card-body">
|
||||
<div class="flex justify-between">
|
||||
<h2 class="card-title">{room}</h2>
|
||||
<button class="btn btn-primary btn-md">Select Room</button>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
<div class="create self-center my-5 w-[40rem]">
|
||||
<div>
|
||||
<label class="label" for="eth-private-key">
|
||||
<span class="label-text">Eth Private Key</span>
|
||||
</label>
|
||||
<input id="eth-private-key" placeholder="Eth Private Key" bind:value={eth_pk}
|
||||
class="input input-bordered input-primary w-full bg-base-200 mb-4 mr-3">
|
||||
</div>
|
||||
<div>
|
||||
<label class="label" for="room-name">
|
||||
<span class="label-text">Room name</span>
|
||||
</label>
|
||||
<input id="room-name" placeholder="Room Name" bind:value={room}
|
||||
class="input input-bordered input-primary w-full bg-base-200 mb-4 mr-3">
|
||||
</div>
|
||||
<div class="form-control">
|
||||
<label class="label cursor-pointer">
|
||||
<span class="label-text">Create Room</span>
|
||||
<input type="checkbox" class="checkbox checkbox-primary" bind:checked={create_new_room} />
|
||||
</label>
|
||||
</div>
|
||||
<button class="btn btn-primary" disabled="{filled_in(eth_pk, room, create_new_room)}" on:click={join_room}>Join Room.</button>
|
||||
</div>
|
||||
<div class="github self-center">
|
||||
<p>
|
||||
Check out <a class="link link-accent" href="https://github.com/0xLaurens/chatr" target="_blank"
|
||||
rel="noreferrer">Chatr</a>, to view the source code!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,18 +0,0 @@
|
||||
import type {PageLoad} from './$types';
|
||||
import {env} from "$env/dynamic/public";
|
||||
|
||||
export const load: PageLoad = async ({fetch}) => {
|
||||
try {
|
||||
let url = `${env.PUBLIC_API_URL}`;
|
||||
if (url.endsWith("/")) {
|
||||
url = url.slice(0, -1);
|
||||
}
|
||||
const res = await fetch(`${url}/rooms`);
|
||||
return await res.json();
|
||||
} catch (e) {
|
||||
return {
|
||||
status: "API offline (try again in a min)",
|
||||
rooms: []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import {
|
||||
user,
|
||||
channel,
|
||||
eth_private_key,
|
||||
group,
|
||||
createNewRoom,
|
||||
} from "../../lib/stores/user";
|
||||
import { goto } from "$app/navigation";
|
||||
import { env } from "$env/dynamic/public";
|
||||
import toast from "svelte-french-toast";
|
||||
import { json } from "@sveltejs/kit";
|
||||
|
||||
let status = "🔴";
|
||||
let statusTip = "Disconnected";
|
||||
let message = "";
|
||||
let messages: any[] = [];
|
||||
let socket: WebSocket;
|
||||
let interval: number;
|
||||
let delay = 2000;
|
||||
let timeout = false;
|
||||
|
||||
// Voting state
|
||||
let currentVotingProposal: any = null;
|
||||
let showVotingUI = false;
|
||||
|
||||
$: {
|
||||
if (interval || (!timeout && interval)) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
if (timeout == true) {
|
||||
interval = setInterval(() => {
|
||||
if (delay < 30_000) delay = delay * 2;
|
||||
console.log("reconnecting in:", delay);
|
||||
connect();
|
||||
}, delay);
|
||||
}
|
||||
}
|
||||
|
||||
function connect() {
|
||||
socket = new WebSocket(`${env.PUBLIC_WEBSOCKET_URL}/ws`);
|
||||
socket.addEventListener("open", () => {
|
||||
status = "🟢";
|
||||
statusTip = "Connected";
|
||||
timeout = false;
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
eth_private_key: $eth_private_key,
|
||||
group_id: $group,
|
||||
should_create: $createNewRoom,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
socket.addEventListener("close", () => {
|
||||
status = "🔴";
|
||||
statusTip = "Disconnected";
|
||||
if (timeout == false) {
|
||||
delay = 2000;
|
||||
timeout = true;
|
||||
}
|
||||
});
|
||||
|
||||
socket.addEventListener("message", function (event) {
|
||||
if (event.data == "Username already taken.") {
|
||||
toast.error(event.data);
|
||||
goto("/");
|
||||
} else {
|
||||
// Try to parse as JSON to check for voting proposals
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === "voting_proposal") {
|
||||
currentVotingProposal = data.proposal;
|
||||
showVotingUI = true;
|
||||
toast.success("New voting proposal received!");
|
||||
} else {
|
||||
messages = [...messages, event.data];
|
||||
}
|
||||
} catch (e) {
|
||||
// If not JSON, treat as regular message
|
||||
messages = [...messages, event.data];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if ($eth_private_key.length < 1 || $group.length < 1) {
|
||||
toast.error("Something went wrong!");
|
||||
goto("/");
|
||||
} else {
|
||||
connect();
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (socket) {
|
||||
socket.close();
|
||||
}
|
||||
if (interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
timeout = false;
|
||||
});
|
||||
|
||||
const sendMessage = () => {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
message: message,
|
||||
group_id: $group,
|
||||
})
|
||||
);
|
||||
message = "";
|
||||
};
|
||||
|
||||
const clear_messages = () => {
|
||||
messages = [];
|
||||
};
|
||||
|
||||
const submitVote = (vote: boolean) => {
|
||||
if (currentVotingProposal) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: "user_vote",
|
||||
proposal_id: currentVotingProposal.proposal_id,
|
||||
vote: vote,
|
||||
group_id: $group,
|
||||
})
|
||||
);
|
||||
|
||||
toast.success(`Vote submitted: ${vote ? "YES" : "NO"}`);
|
||||
showVotingUI = false;
|
||||
currentVotingProposal = null;
|
||||
}
|
||||
};
|
||||
|
||||
const dismissVoting = () => {
|
||||
showVotingUI = false;
|
||||
currentVotingProposal = null;
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class="title flex justify-between">
|
||||
<h1 class="text-3xl font-bold cursor-default">
|
||||
Chat Room <span class="tooltip" data-tip={statusTip}>{status}</span>
|
||||
</h1>
|
||||
<button class="btn btn-accent" on:click={clear_messages}>clear</button>
|
||||
</div>
|
||||
|
||||
<!-- Voting UI -->
|
||||
{#if showVotingUI && currentVotingProposal}
|
||||
<div class="card bg-warning shadow-xl my-5">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title text-warning-content">Voting Proposal</h2>
|
||||
<div class="text-warning-content">
|
||||
<p><strong>Group Name:</strong> {currentVotingProposal.group_name}</p>
|
||||
<p><strong>Proposal ID:</strong> {currentVotingProposal.proposal_id}</p>
|
||||
<p><strong>Proposal Payload:</strong></p>
|
||||
<div class="ml-4 whitespace-pre-line">
|
||||
{currentVotingProposal.payload}
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-actions justify-end mt-4">
|
||||
<button class="btn btn-success" on:click={() => submitVote(true)}
|
||||
>Vote YES</button
|
||||
>
|
||||
<button class="btn btn-error" on:click={() => submitVote(false)}
|
||||
>Vote NO</button
|
||||
>
|
||||
<button class="btn btn-ghost" on:click={dismissVoting}>Dismiss</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="card h-96 flex-grow bg-base-300 shadow-xl my-10">
|
||||
<div class="card-body">
|
||||
<div class="flex flex-col overflow-y-auto max-h-80 scroll-smooth">
|
||||
{#each messages as msg}
|
||||
<div class="my-2">{msg}</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="message-box flex justify-end">
|
||||
<form on:submit|preventDefault={sendMessage}>
|
||||
<input
|
||||
placeholder="Message"
|
||||
class="input input-bordered input-primary w-[51rem] bg-base-200 mb-2"
|
||||
bind:value={message}
|
||||
/>
|
||||
<button class="btn btn-primary w-full sm:w-auto btn-wide">Send</button>
|
||||
</form>
|
||||
</div>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.5 KiB |
@@ -1,16 +0,0 @@
|
||||
import adapter from '@sveltejs/adapter-netlify';
|
||||
import preprocess from 'svelte-preprocess';
|
||||
|
||||
/** @type {import('@sveltejs/kit').Config} */
|
||||
const config = {
|
||||
preprocess: preprocess({
|
||||
postcss: true
|
||||
}),
|
||||
|
||||
kit: {
|
||||
adapter: adapter()
|
||||
}
|
||||
};
|
||||
|
||||
export default config;
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: ['./src/**/*.{html,js,svelte,ts}'],
|
||||
theme: {
|
||||
extend: {}
|
||||
},
|
||||
plugins: [require('@tailwindcss/typography'), require('daisyui')],
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"extends": "./.svelte-kit/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"paths": {
|
||||
"$lib": ["./src/lib"],
|
||||
"$lib/*": ["./src/lib/*"]
|
||||
}
|
||||
}
|
||||
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
|
||||
//
|
||||
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
|
||||
// from the referenced tsconfig.json - TypeScript does not merge them in
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import {sveltekit} from '@sveltejs/kit/vite';
|
||||
import {defineConfig} from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [sveltekit()],
|
||||
});
|
||||
@@ -14,7 +14,7 @@ openmls_traits = "0.3.0"
|
||||
anyhow = "1.0.81"
|
||||
thiserror = "1.0.39"
|
||||
|
||||
alloy = { version = "0.11.0", features = [
|
||||
alloy = { version = "1.0.37", features = [
|
||||
"providers",
|
||||
"node-bindings",
|
||||
"network",
|
||||
|
||||
@@ -17,4 +17,6 @@ pub enum IdentityError {
|
||||
UnableToSaveSignatureKey(#[from] MemoryStorageError),
|
||||
#[error("Unable to create credential: {0}")]
|
||||
UnableToCreateCredential(#[from] CredentialError),
|
||||
#[error("Invalid wallet address: {0}")]
|
||||
InvalidWalletAddress(String),
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use alloy::{primitives::Address, signers::local::PrivateKeySigner};
|
||||
use alloy::{hex, primitives::Address, signers::local::PrivateKeySigner};
|
||||
use openmls::{credentials::CredentialWithKey, key_packages::KeyPackage, prelude::BasicCredential};
|
||||
use openmls_basic_credential::SignatureKeyPair;
|
||||
use openmls_traits::{types::Ciphersuite, OpenMlsProvider};
|
||||
use std::{collections::HashMap, fmt::Display};
|
||||
use std::{collections::HashMap, fmt::Display, str::FromStr};
|
||||
|
||||
use crate::error::IdentityError;
|
||||
use crate::openmls_provider::{MlsProvider, CIPHERSUITE};
|
||||
@@ -102,3 +102,105 @@ pub fn random_identity() -> Result<Identity, IdentityError> {
|
||||
let id = Identity::new(CIPHERSUITE, &crypto, user_address.as_slice())?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Validates and normalizes Ethereum-style wallet addresses.
|
||||
///
|
||||
/// Accepts either `0x`-prefixed or raw 40-character hex strings, returning a lowercase,
|
||||
/// `0x`-prefixed representation on success.
|
||||
pub fn normalize_wallet_address_str(address: &str) -> Result<String, IdentityError> {
|
||||
parse_wallet_address(address).map(|addr| addr.to_string())
|
||||
}
|
||||
|
||||
/// Parses an Ethereum wallet address into an [`Address`] after validation.
|
||||
///
|
||||
/// This ensures the address is 20 bytes / 40 hex chars and contains only hexadecimal digits.
|
||||
pub fn parse_wallet_address(address: &str) -> Result<Address, IdentityError> {
|
||||
let trimmed = address.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err(IdentityError::InvalidWalletAddress(address.to_string()));
|
||||
}
|
||||
|
||||
let hex_part = trimmed
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| trimmed.strip_prefix("0X"))
|
||||
.unwrap_or(trimmed);
|
||||
|
||||
if hex_part.len() != 40 || !hex_part.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(IdentityError::InvalidWalletAddress(trimmed.to_string()));
|
||||
}
|
||||
|
||||
let normalized = format!("0x{}", hex_part.to_ascii_lowercase());
|
||||
Address::from_str(&normalized)
|
||||
.map_err(|_| IdentityError::InvalidWalletAddress(trimmed.to_string()))
|
||||
}
|
||||
|
||||
fn is_prefixed_hex(input: &str) -> bool {
|
||||
let rest = input
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| input.strip_prefix("0X"));
|
||||
match rest {
|
||||
Some(hex_part) if !hex_part.is_empty() => hex_part.chars().all(|c| c.is_ascii_hexdigit()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_raw_hex(input: &str) -> bool {
|
||||
!input.is_empty() && input.chars().all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
pub fn normalize_wallet_address(raw: &[u8]) -> String {
|
||||
let as_utf8 = std::str::from_utf8(raw)
|
||||
.map(|s| s.trim())
|
||||
.unwrap_or_default();
|
||||
|
||||
if is_prefixed_hex(as_utf8) {
|
||||
return as_utf8.to_string();
|
||||
}
|
||||
|
||||
if is_raw_hex(as_utf8) {
|
||||
return format!("0x{}", as_utf8);
|
||||
}
|
||||
|
||||
if raw.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("0x{}", hex::encode(raw))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{is_prefixed_hex, normalize_wallet_address};
|
||||
|
||||
#[test]
|
||||
fn keeps_prefixed_hex() {
|
||||
let addr = normalize_wallet_address(b"0xAbCd1234");
|
||||
assert_eq!(addr, "0xAbCd1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixes_raw_hex() {
|
||||
let addr = normalize_wallet_address(b"ABCD1234");
|
||||
assert_eq!(addr, "0xABCD1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encodes_binary_bytes() {
|
||||
let addr = normalize_wallet_address(&[0x11, 0x22, 0x33]);
|
||||
assert_eq!(addr, "0x112233");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trims_ascii_input() {
|
||||
let addr = normalize_wallet_address(b" 0x1F ");
|
||||
assert_eq!(addr, "0x1F");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixed_hex_helper() {
|
||||
assert!(is_prefixed_hex("0xabc"));
|
||||
assert!(is_prefixed_hex("0XABC"));
|
||||
assert!(!is_prefixed_hex("abc"));
|
||||
assert!(!is_prefixed_hex("0x"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
pub mod error;
|
||||
pub mod identity;
|
||||
pub mod openmls_provider;
|
||||
|
||||
pub use identity::{normalize_wallet_address_str, parse_wallet_address};
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
use kameo::actor::ActorRef;
|
||||
use log::info;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::Sender;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use waku_bindings::WakuMessage;
|
||||
|
||||
use crate::{
|
||||
protos::messages::v1::{AppMessage, BanRequest, ConversationMessage},
|
||||
user::{User, UserAction},
|
||||
user_actor::{BuildBanMessage, LeaveGroupRequest, SendGroupMessage, UserVoteRequest},
|
||||
ws_actor::{RawWsMessage, WsAction, WsActor},
|
||||
AppState,
|
||||
};
|
||||
use ds::waku_actor::WakuMessageToSend;
|
||||
|
||||
pub async fn handle_user_actions(
|
||||
msg: WakuMessage,
|
||||
waku_node: Sender<WakuMessageToSend>,
|
||||
ws_actor: ActorRef<WsActor>,
|
||||
user_actor: ActorRef<User>,
|
||||
app_state: Arc<AppState>,
|
||||
cancel_token: CancellationToken,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let action = user_actor.ask(msg).await?;
|
||||
match action {
|
||||
UserAction::SendToWaku(msg) => {
|
||||
waku_node.send(msg).await?;
|
||||
}
|
||||
UserAction::SendToApp(msg) => {
|
||||
ws_actor.ask(msg).await?;
|
||||
}
|
||||
UserAction::LeaveGroup(group_name) => {
|
||||
user_actor
|
||||
.ask(LeaveGroupRequest {
|
||||
group_name: group_name.clone(),
|
||||
})
|
||||
.await?;
|
||||
|
||||
app_state
|
||||
.content_topics
|
||||
.write()
|
||||
.await
|
||||
.retain(|topic| topic.application_name != group_name);
|
||||
info!("Leave group: {:?}", &group_name);
|
||||
let app_message: AppMessage = ConversationMessage {
|
||||
message: format!("You're removed from the group {group_name}").into_bytes(),
|
||||
sender: "SYSTEM".to_string(),
|
||||
group_name: group_name.clone(),
|
||||
}
|
||||
.into();
|
||||
ws_actor.ask(app_message).await?;
|
||||
cancel_token.cancel();
|
||||
}
|
||||
UserAction::DoNothing => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn handle_ws_action(
|
||||
msg: RawWsMessage,
|
||||
ws_actor: ActorRef<WsActor>,
|
||||
user_actor: ActorRef<User>,
|
||||
waku_node: Sender<WakuMessageToSend>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let action = ws_actor.ask(msg).await?;
|
||||
match action {
|
||||
WsAction::Connect(connect) => {
|
||||
info!("Got unexpected connect: {:?}", &connect);
|
||||
}
|
||||
WsAction::UserMessage(msg) => {
|
||||
let app_message: AppMessage = ConversationMessage {
|
||||
message: msg.message.clone(),
|
||||
sender: "me".to_string(),
|
||||
group_name: msg.group_id.clone(),
|
||||
}
|
||||
.into();
|
||||
ws_actor.ask(app_message).await?;
|
||||
|
||||
let pmt = user_actor
|
||||
.ask(SendGroupMessage {
|
||||
message: msg.message.clone(),
|
||||
group_name: msg.group_id,
|
||||
})
|
||||
.await?;
|
||||
waku_node.send(pmt).await?;
|
||||
}
|
||||
WsAction::RemoveUser(user_to_ban, group_name) => {
|
||||
info!("Got remove user: {:?}", &user_to_ban);
|
||||
|
||||
// Create a ban request message to send to the group
|
||||
let ban_request_msg = BanRequest {
|
||||
user_to_ban: user_to_ban.clone(),
|
||||
requester: "someone".to_string(), // The current user is the requester
|
||||
group_name: group_name.clone(),
|
||||
};
|
||||
|
||||
// Send the ban request directly via Waku if the user is not the steward
|
||||
// If steward, need to add remove proposal to the group and sent notification to the group
|
||||
let waku_msg = user_actor
|
||||
.ask(BuildBanMessage {
|
||||
ban_request: ban_request_msg,
|
||||
group_name: group_name.clone(),
|
||||
})
|
||||
.await?;
|
||||
waku_node.send(waku_msg).await?;
|
||||
|
||||
// Send a local confirmation message
|
||||
let app_message: AppMessage = ConversationMessage {
|
||||
message: format!("Ban request for user {user_to_ban} sent to group").into_bytes(),
|
||||
sender: "system".to_string(),
|
||||
group_name: group_name.clone(),
|
||||
}
|
||||
.into();
|
||||
ws_actor.ask(app_message).await?;
|
||||
}
|
||||
WsAction::UserVote {
|
||||
proposal_id,
|
||||
vote,
|
||||
group_id,
|
||||
} => {
|
||||
info!("Got user vote: proposal_id={proposal_id}, vote={vote}, group={group_id}");
|
||||
|
||||
// Process the user vote:
|
||||
// if it come from the user, send the vote result to Waku
|
||||
// if it come from the steward, just process it and return None
|
||||
let user_vote_result = user_actor
|
||||
.ask(UserVoteRequest {
|
||||
group_name: group_id.clone(),
|
||||
proposal_id,
|
||||
vote,
|
||||
})
|
||||
.await?;
|
||||
|
||||
// Send a local confirmation message
|
||||
let app_message: AppMessage = ConversationMessage {
|
||||
message: format!(
|
||||
"Your vote ({}) has been submitted for proposal {proposal_id}",
|
||||
if vote { "YES" } else { "NO" },
|
||||
)
|
||||
.into_bytes(),
|
||||
sender: "SYSTEM".to_string(),
|
||||
group_name: group_id.clone(),
|
||||
}
|
||||
.into();
|
||||
ws_actor.ask(app_message).await?;
|
||||
|
||||
// Send the vote result to Waku
|
||||
if let Some(waku_msg) = user_vote_result {
|
||||
waku_node.send(waku_msg).await?;
|
||||
}
|
||||
}
|
||||
WsAction::DoNothing => {}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
108
src/bootstrap.rs
Normal file
108
src/bootstrap.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
// de_mls/src/bootstrap.rs
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::{error, info};
|
||||
use waku_bindings::{Multiaddr, WakuMessage};
|
||||
|
||||
use ds::waku_actor::{run_waku_node, WakuMessageToSend};
|
||||
|
||||
use crate::user_app_instance::{AppState, CoreCtx};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BootstrapConfig {
|
||||
/// TCP/UDP port for the embedded Waku node
|
||||
pub node_port: String,
|
||||
/// Comma-separated peer multiaddrs parsed into a vec
|
||||
pub peers: Vec<Multiaddr>,
|
||||
}
|
||||
|
||||
pub struct Bootstrap {
|
||||
pub core: Arc<CoreCtx>,
|
||||
/// Cancels the Waku→broadcast forwarder task
|
||||
pub cancel: CancellationToken,
|
||||
/// The thread running the Waku node runtime; join on shutdown if you want
|
||||
pub waku_thread: std::thread::JoinHandle<()>,
|
||||
}
|
||||
|
||||
/// Same wiring you previously did in `main.rs`, now reusable for server & desktop.
|
||||
pub async fn bootstrap_core(cfg: BootstrapConfig) -> anyhow::Result<Bootstrap> {
|
||||
// Channels used by AppState and Waku runtime
|
||||
let (waku_in_tx, mut waku_in_rx) = mpsc::channel::<WakuMessage>(100);
|
||||
let (to_waku_tx, mut to_waku_rx) = mpsc::channel::<WakuMessageToSend>(100);
|
||||
let (pubsub_tx, _) = broadcast::channel::<WakuMessage>(100);
|
||||
|
||||
let app_state = Arc::new(AppState {
|
||||
waku_node: to_waku_tx.clone(),
|
||||
pubsub: pubsub_tx.clone(),
|
||||
});
|
||||
|
||||
let core = Arc::new(CoreCtx::new(app_state.clone()));
|
||||
|
||||
// Forward Waku messages into broadcast
|
||||
let forward_cancel = CancellationToken::new();
|
||||
{
|
||||
let forward_cancel = forward_cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
info!("Forwarding Waku → broadcast started");
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = forward_cancel.cancelled() => break,
|
||||
maybe = waku_in_rx.recv() => {
|
||||
if let Some(msg) = maybe {
|
||||
let _ = pubsub_tx.send(msg);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("Forwarding Waku → broadcast stopped");
|
||||
});
|
||||
}
|
||||
|
||||
// Start Waku node on a dedicated thread with its own Tokio runtime
|
||||
let node_port = cfg.node_port.clone();
|
||||
let peers = cfg.peers.clone();
|
||||
let waku_thread = std::thread::Builder::new()
|
||||
.name("waku-node".into())
|
||||
.spawn(move || {
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("waku tokio runtime");
|
||||
rt.block_on(async move {
|
||||
if let Err(e) =
|
||||
run_waku_node(node_port, Some(peers), waku_in_tx, &mut to_waku_rx).await
|
||||
{
|
||||
error!("run_waku_node failed: {e}");
|
||||
}
|
||||
});
|
||||
})?;
|
||||
|
||||
Ok(Bootstrap {
|
||||
core,
|
||||
cancel: forward_cancel,
|
||||
waku_thread,
|
||||
})
|
||||
}
|
||||
|
||||
/// Helper that exactly mirrors your current env usage:
|
||||
/// - requires NODE_PORT
|
||||
/// - requires PEER_ADDRESSES (comma-separated multiaddrs)
|
||||
pub async fn bootstrap_core_from_env() -> anyhow::Result<Bootstrap> {
|
||||
use anyhow::Context;
|
||||
|
||||
let node_port = std::env::var("NODE_PORT").context("NODE_PORT is not set")?;
|
||||
let peer_addresses = std::env::var("PEER_ADDRESSES").context("PEER_ADDRESSES is not set")?;
|
||||
let peers = peer_addresses
|
||||
.split(',')
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.map(|s| {
|
||||
s.parse::<Multiaddr>()
|
||||
.context(format!("Failed to parse peer address: {s}"))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
bootstrap_core(BootstrapConfig { node_port, peers }).await
|
||||
}
|
||||
@@ -6,25 +6,19 @@
|
||||
//! - Proposal management
|
||||
//! - Vote collection and validation
|
||||
//! - Consensus reached detection
|
||||
|
||||
use crate::error::ConsensusError;
|
||||
use crate::protos::messages::v1::consensus::v1::{Proposal, Vote};
|
||||
use crate::LocalSigner;
|
||||
use log::info;
|
||||
use prost::Message;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::sync::broadcast;
|
||||
use tracing::info;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::ConsensusError;
|
||||
use crate::protos::consensus::v1::{Outcome, Proposal, ProposalResult, Vote};
|
||||
use crate::LocalSigner;
|
||||
|
||||
pub mod service;
|
||||
|
||||
// Re-export protobuf types for compatibility with generated code
|
||||
pub mod v1 {
|
||||
pub use crate::protos::messages::v1::consensus::v1::{Proposal, Vote};
|
||||
}
|
||||
|
||||
pub use service::ConsensusService;
|
||||
|
||||
/// Consensus events emitted when consensus state changes
|
||||
@@ -81,7 +75,8 @@ pub struct ConsensusSession {
|
||||
pub votes: HashMap<Vec<u8>, Vote>, // vote_owner -> Vote
|
||||
pub created_at: u64,
|
||||
pub config: ConsensusConfig,
|
||||
pub event_sender: Option<broadcast::Sender<(String, ConsensusEvent)>>,
|
||||
pub event_sender: broadcast::Sender<(String, ConsensusEvent)>,
|
||||
pub decisions_tx: broadcast::Sender<ProposalResult>,
|
||||
pub group_name: String,
|
||||
}
|
||||
|
||||
@@ -89,7 +84,8 @@ impl ConsensusSession {
|
||||
pub fn new(
|
||||
proposal: Proposal,
|
||||
config: ConsensusConfig,
|
||||
event_sender: Option<broadcast::Sender<(String, ConsensusEvent)>>,
|
||||
event_sender: broadcast::Sender<(String, ConsensusEvent)>,
|
||||
decisions_tx: broadcast::Sender<ProposalResult>,
|
||||
group_name: &str,
|
||||
) -> Self {
|
||||
let now = SystemTime::now()
|
||||
@@ -104,6 +100,7 @@ impl ConsensusSession {
|
||||
created_at: now,
|
||||
config,
|
||||
event_sender,
|
||||
decisions_tx,
|
||||
group_name: group_name.to_string(),
|
||||
}
|
||||
}
|
||||
@@ -131,7 +128,7 @@ impl ConsensusSession {
|
||||
}
|
||||
ConsensusState::ConsensusReached(_) => {
|
||||
info!(
|
||||
"[consensus::mod::add_vote]: Consensus already reached for proposal {}, skipping vote",
|
||||
"[mod::add_vote]: Consensus already reached for proposal {}, skipping vote",
|
||||
self.proposal.proposal_id
|
||||
);
|
||||
Ok(())
|
||||
@@ -173,7 +170,7 @@ impl ConsensusSession {
|
||||
if yes_votes > no_votes {
|
||||
self.state = ConsensusState::ConsensusReached(true);
|
||||
info!(
|
||||
"[consensus::mod::check_consensus]: Enough votes received {yes_votes}-{no_votes} - consensus reached: YES"
|
||||
"[mod::check_consensus]: Enough votes received {yes_votes}-{no_votes} - consensus reached: YES"
|
||||
);
|
||||
self.emit_consensus_event(ConsensusEvent::ConsensusReached {
|
||||
proposal_id: self.proposal.proposal_id,
|
||||
@@ -182,7 +179,7 @@ impl ConsensusSession {
|
||||
} else if no_votes > yes_votes {
|
||||
self.state = ConsensusState::ConsensusReached(false);
|
||||
info!(
|
||||
"[consensus::mod::check_consensus]: Enough votes received {yes_votes}-{no_votes} - consensus reached: NO"
|
||||
"[mod::check_consensus]: Enough votes received {yes_votes}-{no_votes} - consensus reached: NO"
|
||||
);
|
||||
self.emit_consensus_event(ConsensusEvent::ConsensusReached {
|
||||
proposal_id: self.proposal.proposal_id,
|
||||
@@ -193,7 +190,7 @@ impl ConsensusSession {
|
||||
if total_votes == expected_voters {
|
||||
self.state = ConsensusState::ConsensusReached(false);
|
||||
info!(
|
||||
"[consensus::mod::check_consensus]: All votes received and tie - consensus not reached"
|
||||
"[mod::check_consensus]: All votes received and tie - consensus not reached"
|
||||
);
|
||||
self.emit_consensus_event(ConsensusEvent::ConsensusReached {
|
||||
proposal_id: self.proposal.proposal_id,
|
||||
@@ -203,7 +200,7 @@ impl ConsensusSession {
|
||||
// Tie - if it's not all votes, we wait for more votes
|
||||
self.state = ConsensusState::Active;
|
||||
info!(
|
||||
"[consensus::mod::check_consensus]: Not enough votes received - consensus not reached"
|
||||
"[mod::check_consensus]: Not enough votes received - consensus not reached"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -212,13 +209,19 @@ impl ConsensusSession {
|
||||
|
||||
/// Emit a consensus event
|
||||
fn emit_consensus_event(&self, event: ConsensusEvent) {
|
||||
if let Some(sender) = &self.event_sender {
|
||||
info!(
|
||||
"[consensus::mod::emit_consensus_event]: Emitting consensus event: {event:?} for proposal {}",
|
||||
self.proposal.proposal_id
|
||||
);
|
||||
let _ = sender.send((self.group_name.clone(), event));
|
||||
}
|
||||
info!("[mod::emit_consensus_event]: Emitting consensus event: {event:?}");
|
||||
let _ = self
|
||||
.event_sender
|
||||
.send((self.group_name.clone(), event.clone()));
|
||||
let _ = self.decisions_tx.send(ProposalResult {
|
||||
group_id: self.group_name.clone(),
|
||||
proposal_id: self.proposal.proposal_id,
|
||||
outcome: Outcome::from(event) as i32,
|
||||
decided_at_ms: SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("Failed to get current time")
|
||||
.as_secs(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Check if the session is still active
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
//! Consensus service for managing consensus sessions and HashGraph integration
|
||||
use prost::Message;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::sync::{broadcast, RwLock};
|
||||
use tracing::info;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::consensus::{
|
||||
compute_vote_hash, create_vote_for_proposal, ConsensusConfig, ConsensusEvent, ConsensusSession,
|
||||
ConsensusState, ConsensusStats,
|
||||
};
|
||||
use crate::error::ConsensusError;
|
||||
use crate::protos::messages::v1::consensus::v1::{Proposal, Vote};
|
||||
use crate::protos::consensus::v1::{Proposal, ProposalResult, UpdateRequest, Vote};
|
||||
use crate::{verify_vote_hash, LocalSigner};
|
||||
use log::info;
|
||||
use prost::Message;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::sync::{broadcast, RwLock};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Consensus service that manages multiple consensus sessions for multiple groups
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ConsensusService {
|
||||
/// Active consensus sessions organized by group: group_name -> proposal_id -> session
|
||||
sessions: Arc<RwLock<HashMap<String, HashMap<u32, ConsensusSession>>>>,
|
||||
@@ -24,26 +24,32 @@ pub struct ConsensusService {
|
||||
max_sessions_per_group: usize,
|
||||
/// Event sender for consensus events
|
||||
event_sender: broadcast::Sender<(String, ConsensusEvent)>,
|
||||
/// Event sender for consensus results for UI
|
||||
decisions_tx: broadcast::Sender<ProposalResult>,
|
||||
}
|
||||
|
||||
impl ConsensusService {
|
||||
/// Create a new consensus service
|
||||
pub fn new() -> Self {
|
||||
let (event_sender, _) = broadcast::channel(1000);
|
||||
let (decisions_tx, _) = broadcast::channel(128);
|
||||
Self {
|
||||
sessions: Arc::new(RwLock::new(HashMap::new())),
|
||||
max_sessions_per_group: 10,
|
||||
event_sender,
|
||||
decisions_tx,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new consensus service with custom max sessions per group
|
||||
pub fn new_with_max_sessions(max_sessions_per_group: usize) -> Self {
|
||||
let (event_sender, _) = broadcast::channel(1000);
|
||||
let (decisions_tx, _) = broadcast::channel(128);
|
||||
Self {
|
||||
sessions: Arc::new(RwLock::new(HashMap::new())),
|
||||
max_sessions_per_group,
|
||||
event_sender,
|
||||
decisions_tx,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +58,16 @@ impl ConsensusService {
|
||||
self.event_sender.subscribe()
|
||||
}
|
||||
|
||||
/// Subscribe to consensus decisions
|
||||
pub fn subscribe_decisions(&self) -> broadcast::Receiver<ProposalResult> {
|
||||
self.decisions_tx.subscribe()
|
||||
}
|
||||
|
||||
// /// Send consensus decision to UI
|
||||
// pub fn send_decision(&self, res: ProposalResult) {
|
||||
// let _ = self.decisions_tx.send(res);
|
||||
// }
|
||||
|
||||
pub async fn set_consensus_threshold_for_group_session(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
@@ -76,7 +92,7 @@ impl ConsensusService {
|
||||
&self,
|
||||
group_name: &str,
|
||||
name: String,
|
||||
payload: String,
|
||||
group_requests: Vec<UpdateRequest>,
|
||||
proposal_owner: Vec<u8>,
|
||||
expected_voters_count: u32,
|
||||
expiration_time: u64,
|
||||
@@ -91,7 +107,7 @@ impl ConsensusService {
|
||||
// Create proposal with steward's vote
|
||||
let proposal = Proposal {
|
||||
name,
|
||||
payload,
|
||||
group_requests,
|
||||
proposal_id,
|
||||
proposal_owner,
|
||||
votes: vec![],
|
||||
@@ -107,7 +123,8 @@ impl ConsensusService {
|
||||
let session = ConsensusSession::new(
|
||||
proposal.clone(),
|
||||
config.clone(),
|
||||
Some(self.event_sender.clone()),
|
||||
self.event_sender.clone(),
|
||||
self.decisions_tx.clone(),
|
||||
group_name,
|
||||
);
|
||||
|
||||
@@ -120,22 +137,7 @@ impl ConsensusService {
|
||||
let group_sessions = sessions
|
||||
.entry(group_name.to_string())
|
||||
.or_insert_with(HashMap::new);
|
||||
group_sessions.insert(proposal_id, session);
|
||||
|
||||
// Clean up old sessions if we exceed the limit (within the same lock)
|
||||
if group_sessions.len() > self.max_sessions_per_group {
|
||||
// Sort sessions by creation time and keep the most recent ones
|
||||
let mut session_entries: Vec<_> = group_sessions.drain().collect();
|
||||
session_entries.sort_by(|a, b| b.1.created_at.cmp(&a.1.created_at));
|
||||
|
||||
// Keep only the most recent sessions
|
||||
for (proposal_id, session) in session_entries
|
||||
.into_iter()
|
||||
.take(self.max_sessions_per_group)
|
||||
{
|
||||
group_sessions.insert(proposal_id, session);
|
||||
}
|
||||
}
|
||||
self.insert_session(group_sessions, proposal_id, session);
|
||||
}
|
||||
|
||||
// Start automatic timeout handling for this proposal using session config
|
||||
@@ -151,7 +153,7 @@ impl ConsensusService {
|
||||
.is_some()
|
||||
{
|
||||
info!(
|
||||
"Consensus result already exists for proposal {proposal_id}, skipping timeout"
|
||||
"[create_proposal]:Consensus result already exists for proposal {proposal_id}, skipping timeout"
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -163,7 +165,7 @@ impl ConsensusService {
|
||||
.is_ok()
|
||||
{
|
||||
info!(
|
||||
"Automatic timeout applied for proposal {proposal_id} after {timeout_seconds}s"
|
||||
"[create_proposal]: Automatic timeout applied for proposal {proposal_id} after {timeout_seconds}s"
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -308,6 +310,32 @@ impl ConsensusService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_session(
|
||||
&self,
|
||||
group_sessions: &mut HashMap<u32, ConsensusSession>,
|
||||
proposal_id: u32,
|
||||
session: ConsensusSession,
|
||||
) {
|
||||
group_sessions.insert(proposal_id, session);
|
||||
self.prune_sessions(group_sessions);
|
||||
}
|
||||
|
||||
fn prune_sessions(&self, group_sessions: &mut HashMap<u32, ConsensusSession>) {
|
||||
if group_sessions.len() <= self.max_sessions_per_group {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut session_entries: Vec<_> = group_sessions.drain().collect();
|
||||
session_entries.sort_by(|a, b| b.1.created_at.cmp(&a.1.created_at));
|
||||
|
||||
for (proposal_id, session) in session_entries
|
||||
.into_iter()
|
||||
.take(self.max_sessions_per_group)
|
||||
{
|
||||
group_sessions.insert(proposal_id, session);
|
||||
}
|
||||
}
|
||||
|
||||
/// Process incoming proposal message
|
||||
pub async fn process_incoming_proposal(
|
||||
&self,
|
||||
@@ -315,7 +343,7 @@ impl ConsensusService {
|
||||
proposal: Proposal,
|
||||
) -> Result<(), ConsensusError> {
|
||||
info!(
|
||||
"[consensus::service::process_incoming_proposal]: Processing incoming proposal for group {group_name}"
|
||||
"[service::process_incoming_proposal]: Processing incoming proposal for group {group_name}"
|
||||
);
|
||||
let mut sessions = self.sessions.write().await;
|
||||
let group_sessions = sessions
|
||||
@@ -334,29 +362,16 @@ impl ConsensusService {
|
||||
let mut session = ConsensusSession::new(
|
||||
proposal.clone(),
|
||||
ConsensusConfig::default(),
|
||||
Some(self.event_sender.clone()),
|
||||
self.event_sender.clone(),
|
||||
self.decisions_tx.clone(),
|
||||
group_name,
|
||||
);
|
||||
|
||||
session.add_vote(proposal.votes[0].clone())?;
|
||||
group_sessions.insert(proposal.proposal_id, session);
|
||||
self.insert_session(group_sessions, proposal.proposal_id, session);
|
||||
|
||||
// Clean up old sessions if we exceed the limit (within the same lock)
|
||||
if group_sessions.len() > self.max_sessions_per_group {
|
||||
// Sort sessions by creation time and keep the most recent ones
|
||||
let mut session_entries: Vec<_> = group_sessions.drain().collect();
|
||||
session_entries.sort_by(|a, b| b.1.created_at.cmp(&a.1.created_at));
|
||||
info!("[service::process_incoming_proposal]: Proposal stored, waiting for user vote");
|
||||
|
||||
// Keep only the most recent sessions
|
||||
for (proposal_id, session) in session_entries
|
||||
.into_iter()
|
||||
.take(self.max_sessions_per_group)
|
||||
{
|
||||
group_sessions.insert(proposal_id, session);
|
||||
}
|
||||
}
|
||||
|
||||
info!("[consensus::service::process_incoming_proposal]: Proposal stored, waiting for user vote");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -397,9 +412,7 @@ impl ConsensusService {
|
||||
group_name: &str,
|
||||
vote: Vote,
|
||||
) -> Result<(), ConsensusError> {
|
||||
info!(
|
||||
"[consensus::service::process_incoming_vote]: Processing incoming vote for group {group_name}"
|
||||
);
|
||||
info!("[service::process_incoming_vote]: Processing incoming vote for group {group_name}");
|
||||
let mut sessions = self.sessions.write().await;
|
||||
let group_sessions = sessions
|
||||
.get_mut(group_name)
|
||||
@@ -600,7 +613,7 @@ impl ConsensusService {
|
||||
// Check if consensus was already reached
|
||||
match session.state {
|
||||
crate::consensus::ConsensusState::ConsensusReached(result) => {
|
||||
info!("Consensus already reached for proposal {proposal_id}, skipping timeout");
|
||||
info!("[handle_consensus_timeout]: Consensus already reached for proposal {proposal_id}, skipping timeout");
|
||||
Ok(result)
|
||||
}
|
||||
_ => {
|
||||
@@ -624,7 +637,7 @@ impl ConsensusService {
|
||||
|
||||
// Apply timeout consensus
|
||||
session.state = crate::consensus::ConsensusState::ConsensusReached(result);
|
||||
info!("Timeout consensus applied for proposal {proposal_id}: {result} (liveness criteria)");
|
||||
info!("[handle_consensus_timeout]: Timeout consensus applied for proposal {proposal_id}: {result} (liveness criteria)");
|
||||
|
||||
// Emit consensus event
|
||||
session.emit_consensus_event(
|
||||
@@ -663,7 +676,7 @@ impl ConsensusService {
|
||||
) -> bool {
|
||||
let required_votes = self.calculate_required_votes(expected_voters, consensus_threshold);
|
||||
println!(
|
||||
"[consensus::service::check_sufficient_votes]: Total votes: {total_votes}, Expected voters: {expected_voters}, Consensus threshold: {consensus_threshold}, Required votes: {required_votes}"
|
||||
"[service::check_sufficient_votes]: Total votes: {total_votes}, Expected voters: {expected_voters}, Consensus threshold: {consensus_threshold}, Required votes: {required_votes}"
|
||||
);
|
||||
total_votes >= required_votes
|
||||
}
|
||||
|
||||
20
src/error.rs
20
src/error.rs
@@ -11,7 +11,7 @@ use openmls::{
|
||||
use openmls_rust_crypto::MemoryStorageError;
|
||||
use std::string::FromUtf8Error;
|
||||
|
||||
use ds::{waku_actor::WakuMessageToSend, DeliveryServiceError};
|
||||
use ds::DeliveryServiceError;
|
||||
use mls_crypto::error::IdentityError;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -78,6 +78,8 @@ pub enum MessageError {
|
||||
pub enum GroupError {
|
||||
#[error(transparent)]
|
||||
MessageError(#[from] MessageError),
|
||||
#[error(transparent)]
|
||||
IdentityError(#[from] IdentityError),
|
||||
|
||||
#[error("Steward not set")]
|
||||
StewardNotSet,
|
||||
@@ -145,22 +147,10 @@ pub enum UserError {
|
||||
FailedToExtractWelcomeMessage,
|
||||
#[error("Message verification failed")]
|
||||
MessageVerificationFailed,
|
||||
#[error("Failed to create group: {0}")]
|
||||
UnableToCreateGroup(String),
|
||||
#[error("Failed to send message to user: {0}")]
|
||||
UnableToHandleStewardEpoch(String),
|
||||
#[error("Failed to process steward message: {0}")]
|
||||
ProcessStewardMessageError(String),
|
||||
#[error("Failed to get group update requests: {0}")]
|
||||
GetGroupUpdateRequestsError(String),
|
||||
#[error("Invalid user action: {0}")]
|
||||
InvalidUserAction(String),
|
||||
#[error("Failed to start voting: {0}")]
|
||||
UnableToStartVoting(String),
|
||||
#[error("Unknown content topic type: {0}")]
|
||||
UnknownContentTopicType(String),
|
||||
#[error("Failed to send message to ws: {0}")]
|
||||
UnableToSendMessageToWs(String),
|
||||
#[error("Invalid group state: {0}")]
|
||||
InvalidGroupState(String),
|
||||
#[error("No proposals found")]
|
||||
@@ -180,6 +170,6 @@ pub enum UserError {
|
||||
MlsMessageInDeserializeError(#[from] openmls::prelude::Error),
|
||||
#[error("Failed to try into protocol message: {0}")]
|
||||
TryIntoProtocolMessageError(#[from] openmls::framing::errors::ProtocolMessageError),
|
||||
#[error("Failed to send message to waku: {0}")]
|
||||
WakuSendMessageError(#[from] tokio::sync::mpsc::error::SendError<WakuMessageToSend>),
|
||||
#[error("Failed to get current time")]
|
||||
FailedToGetCurrentTime(#[from] std::time::SystemTimeError),
|
||||
}
|
||||
|
||||
98
src/group.rs
98
src/group.rs
@@ -1,6 +1,4 @@
|
||||
use alloy::hex;
|
||||
use kameo::Actor;
|
||||
use log::{error, info};
|
||||
use openmls::{
|
||||
group::{GroupEpoch, GroupId, MlsGroup, MlsGroupCreateConfig},
|
||||
prelude::{
|
||||
@@ -12,18 +10,21 @@ use openmls_basic_credential::SignatureKeyPair;
|
||||
use prost::Message;
|
||||
use std::{fmt::Display, sync::Arc};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use tracing::{error, info};
|
||||
use uuid;
|
||||
|
||||
use crate::{
|
||||
consensus::v1::{Proposal, Vote},
|
||||
error::GroupError,
|
||||
message::{message_types, MessageType},
|
||||
protos::messages::v1::{app_message, AppMessage, BatchProposalsMessage, WelcomeMessage},
|
||||
protos::{
|
||||
consensus::v1::{Proposal, RequestType, UpdateRequest, Vote},
|
||||
de_mls::messages::v1::{app_message, AppMessage, BatchProposalsMessage, WelcomeMessage},
|
||||
},
|
||||
state_machine::{GroupState, GroupStateMachine},
|
||||
steward::GroupUpdateRequest,
|
||||
};
|
||||
use ds::{waku_actor::WakuMessageToSend, APP_MSG_SUBTOPIC, WELCOME_SUBTOPIC};
|
||||
use mls_crypto::openmls_provider::MlsProvider;
|
||||
use mls_crypto::{identity::normalize_wallet_address_str, openmls_provider::MlsProvider};
|
||||
|
||||
/// Represents the action to take after processing a group message or event.
|
||||
///
|
||||
@@ -62,7 +63,7 @@ impl Display for GroupAction {
|
||||
/// - State machine integration for proper workflow enforcement
|
||||
/// - Member addition/removal through proposals
|
||||
/// - Message validation and permission checking
|
||||
#[derive(Clone, Debug, Actor)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Group {
|
||||
group_name: String,
|
||||
mls_group: Option<Arc<Mutex<MlsGroup>>>,
|
||||
@@ -304,15 +305,26 @@ impl Group {
|
||||
/// ## Effects:
|
||||
/// - Adds an AddMember proposal to the current epoch
|
||||
/// - Proposal will be processed in the next steward epoch
|
||||
/// - Returns a serialized `UiUpdateRequest` for UI notification
|
||||
pub async fn store_invite_proposal(
|
||||
&mut self,
|
||||
key_package: Box<KeyPackage>,
|
||||
) -> Result<(), GroupError> {
|
||||
) -> Result<UpdateRequest, GroupError> {
|
||||
let mut state_machine = self.state_machine.write().await;
|
||||
state_machine
|
||||
.add_proposal(GroupUpdateRequest::AddMember(key_package))
|
||||
.add_proposal(GroupUpdateRequest::AddMember(key_package.clone()))
|
||||
.await;
|
||||
Ok(())
|
||||
|
||||
let wallet_bytes = key_package
|
||||
.leaf_node()
|
||||
.credential()
|
||||
.serialized_content()
|
||||
.to_vec();
|
||||
|
||||
Ok(UpdateRequest {
|
||||
request_type: RequestType::AddMember as i32,
|
||||
wallet_address: wallet_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Store a remove proposal in the steward queue for the current epoch.
|
||||
@@ -320,15 +332,31 @@ impl Group {
|
||||
/// ## Parameters:
|
||||
/// - `identity`: The identity string of the member to remove
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Adds a RemoveMember proposal to the current epoch
|
||||
/// - Proposal will be processed in the next steward epoch
|
||||
pub async fn store_remove_proposal(&mut self, identity: String) -> Result<(), GroupError> {
|
||||
/// ## Returns:
|
||||
/// - Returns a serialized `UiUpdateRequest` for UI notification
|
||||
/// - `GroupError::InvalidIdentity` if the identity is invalid
|
||||
pub async fn store_remove_proposal(
|
||||
&mut self,
|
||||
identity: String,
|
||||
) -> Result<UpdateRequest, GroupError> {
|
||||
let normalized_identity = normalize_wallet_address_str(&identity)?;
|
||||
let mut state_machine = self.state_machine.write().await;
|
||||
state_machine
|
||||
.add_proposal(GroupUpdateRequest::RemoveMember(identity))
|
||||
.add_proposal(GroupUpdateRequest::RemoveMember(
|
||||
normalized_identity.clone(),
|
||||
))
|
||||
.await;
|
||||
Ok(())
|
||||
|
||||
let wallet_bytes = hex::decode(
|
||||
normalized_identity
|
||||
.strip_prefix("0x")
|
||||
.unwrap_or(&normalized_identity),
|
||||
)?;
|
||||
|
||||
Ok(UpdateRequest {
|
||||
request_type: RequestType::RemoveMember as i32,
|
||||
wallet_address: wallet_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Process an application message and determine the appropriate action.
|
||||
@@ -355,30 +383,31 @@ impl Group {
|
||||
let app_msg = AppMessage::decode(message.into_bytes().as_slice())?;
|
||||
match app_msg.payload {
|
||||
Some(app_message::Payload::ConversationMessage(conversation_message)) => {
|
||||
info!("[group::process_application_message]: Processing conversation message");
|
||||
info!("[process_application_message]: Processing conversation message");
|
||||
Ok(GroupAction::GroupAppMsg(conversation_message.into()))
|
||||
}
|
||||
Some(app_message::Payload::Proposal(proposal)) => {
|
||||
info!("[group::process_application_message]: Processing proposal message");
|
||||
info!("[process_application_message]: Processing proposal message");
|
||||
Ok(GroupAction::GroupProposal(proposal))
|
||||
}
|
||||
Some(app_message::Payload::Vote(vote)) => {
|
||||
info!("[group::process_application_message]: Processing vote message");
|
||||
info!("[process_application_message]: Processing vote message");
|
||||
Ok(GroupAction::GroupVote(vote))
|
||||
}
|
||||
Some(app_message::Payload::BanRequest(ban_request)) => {
|
||||
info!("[group::process_application_message]: Processing ban request message");
|
||||
info!("[process_application_message]: Processing ban request message");
|
||||
|
||||
if self.is_steward().await {
|
||||
info!(
|
||||
"[group::process_application_message]: Steward adding remove proposal for user {}",
|
||||
"[process_application_message]: Steward adding remove proposal for user {}",
|
||||
ban_request.user_to_ban.clone()
|
||||
);
|
||||
self.store_remove_proposal(ban_request.user_to_ban.clone())
|
||||
let _ = self
|
||||
.store_remove_proposal(ban_request.user_to_ban.clone())
|
||||
.await?;
|
||||
} else {
|
||||
info!(
|
||||
"[group::process_application_message]: Non-steward received ban request message"
|
||||
"[process_application_message]: Non-steward received ban request message"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -534,6 +563,15 @@ impl Group {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get the current epoch proposals for UI display.
|
||||
pub async fn get_current_epoch_proposals(&self) -> Vec<GroupUpdateRequest> {
|
||||
self.state_machine
|
||||
.read()
|
||||
.await
|
||||
.get_current_epoch_proposals()
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get the number of pending proposals for the voting epoch
|
||||
pub async fn get_voting_proposals_count(&self) -> usize {
|
||||
self.state_machine
|
||||
@@ -552,6 +590,14 @@ impl Group {
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_proposals_for_voting_epoch_as_ui_update_requests(&self) -> Vec<UpdateRequest> {
|
||||
self.get_proposals_for_voting_epoch()
|
||||
.await
|
||||
.iter()
|
||||
.map(|p| p.clone().into())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Start voting on proposals for the current epoch
|
||||
pub async fn start_voting(&mut self) -> Result<(), GroupError> {
|
||||
self.state_machine.write().await.start_voting()
|
||||
@@ -575,14 +621,6 @@ impl Group {
|
||||
self.state_machine.write().await.start_consensus_reached();
|
||||
}
|
||||
|
||||
/// Recover from consensus failure by transitioning back to Working state
|
||||
pub async fn recover_from_consensus_failure(&mut self) -> Result<(), GroupError> {
|
||||
self.state_machine
|
||||
.write()
|
||||
.await
|
||||
.recover_from_consensus_failure()
|
||||
}
|
||||
|
||||
/// Start waiting state (for non-steward peers after consensus or edge case recovery)
|
||||
pub async fn start_waiting(&mut self) {
|
||||
self.state_machine.write().await.start_waiting();
|
||||
|
||||
31
src/group_registry.rs
Normal file
31
src/group_registry.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use std::collections::HashSet;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
// src/group_registry.rs
|
||||
#[derive(Default, Debug)]
|
||||
pub struct GroupRegistry {
|
||||
names: RwLock<HashSet<String>>,
|
||||
}
|
||||
|
||||
impl GroupRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub async fn exists(&self, name: &str) -> bool {
|
||||
self.names.read().await.contains(name)
|
||||
}
|
||||
|
||||
pub async fn insert(&self, name: String) -> bool {
|
||||
let mut g = self.names.write().await;
|
||||
if g.contains(&name) {
|
||||
return false;
|
||||
}
|
||||
g.insert(name);
|
||||
true
|
||||
}
|
||||
|
||||
pub async fn all(&self) -> Vec<String> {
|
||||
self.names.read().await.iter().cloned().collect()
|
||||
}
|
||||
}
|
||||
56
src/lib.rs
56
src/lib.rs
@@ -33,7 +33,7 @@
|
||||
//!
|
||||
//! 1. **Working State**: Normal operation, all users can send any message freely
|
||||
//! 2. **Waiting State**: Steward epoch active, only steward can send BATCH_PROPOSALS_MESSAGE
|
||||
//! 3. **Voting State**: Consensus voting, restricted message types (VOTE/USER_VOTE for all, VOTING_PROPOSAL/PROPOSAL for steward only)
|
||||
//! 3. **Voting State**: Consensus voting, restricted message types (VOTE/USER_VOTE for all, VOTE_PAYLOAD/PROPOSAL for steward only)
|
||||
//!
|
||||
//! ### Complete State Transitions
|
||||
//!
|
||||
@@ -92,57 +92,42 @@
|
||||
//! - **Waku**: Decentralized messaging protocol
|
||||
//! - **Alloy**: Ethereum wallet and signing
|
||||
|
||||
use alloy::primitives::{Address, PrimitiveSignature};
|
||||
use alloy::primitives::{Address, Signature};
|
||||
use ecies::{decrypt, encrypt};
|
||||
use libsecp256k1::{sign, verify, Message, PublicKey, SecretKey, Signature as libSignature};
|
||||
use rand::thread_rng;
|
||||
use secp256k1::hashes::{sha256, Hash};
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use tokio::sync::{mpsc::Sender, RwLock};
|
||||
use waku_bindings::{WakuContentTopic, WakuMessage};
|
||||
|
||||
use ds::waku_actor::WakuMessageToSend;
|
||||
use error::{GroupError, MessageError};
|
||||
|
||||
pub mod action_handlers;
|
||||
pub mod bootstrap;
|
||||
pub use bootstrap::{bootstrap_core, bootstrap_core_from_env, Bootstrap, BootstrapConfig};
|
||||
|
||||
pub mod consensus;
|
||||
pub mod error;
|
||||
pub mod group;
|
||||
pub mod group_registry;
|
||||
pub mod message;
|
||||
pub mod state_machine;
|
||||
pub mod steward;
|
||||
pub mod user;
|
||||
pub mod user_actor;
|
||||
pub mod user_app_instance;
|
||||
pub mod ws_actor;
|
||||
|
||||
pub mod protos {
|
||||
pub mod messages {
|
||||
pub mod consensus {
|
||||
pub mod v1 {
|
||||
pub mod consensus {
|
||||
pub mod v1 {
|
||||
include!(concat!(env!("OUT_DIR"), "/consensus.v1.rs"));
|
||||
}
|
||||
}
|
||||
include!(concat!(env!("OUT_DIR"), "/de_mls.messages.v1.rs"));
|
||||
include!(concat!(env!("OUT_DIR"), "/consensus.v1.rs"));
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct AppState {
|
||||
pub waku_node: Sender<WakuMessageToSend>,
|
||||
pub rooms: Mutex<HashSet<String>>,
|
||||
pub content_topics: Arc<RwLock<Vec<WakuContentTopic>>>,
|
||||
pub pubsub: tokio::sync::broadcast::Sender<WakuMessage>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Connection {
|
||||
pub eth_private_key: String,
|
||||
pub group_id: String,
|
||||
pub should_create_group: bool,
|
||||
pub mod de_mls {
|
||||
pub mod messages {
|
||||
pub mod v1 {
|
||||
include!(concat!(env!("OUT_DIR"), "/de_mls.messages.v1.rs"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_keypair() -> (PublicKey, SecretKey) {
|
||||
@@ -186,15 +171,6 @@ pub fn decrypt_message(message: &[u8], secret_key: SecretKey) -> Result<Vec<u8>,
|
||||
Ok(decrypted)
|
||||
}
|
||||
|
||||
/// Check if a content topic exists in a list of topics or if the list is empty
|
||||
pub async fn match_content_topic(
|
||||
content_topics: &Arc<RwLock<Vec<WakuContentTopic>>>,
|
||||
topic: &WakuContentTopic,
|
||||
) -> bool {
|
||||
let locked_topics = content_topics.read().await;
|
||||
locked_topics.is_empty() || locked_topics.iter().any(|t| t == topic)
|
||||
}
|
||||
|
||||
pub trait LocalSigner {
|
||||
fn local_sign_message(
|
||||
&self,
|
||||
@@ -218,7 +194,7 @@ pub fn verify_vote_hash(
|
||||
expect: 65,
|
||||
actual: signature.len(),
|
||||
})?;
|
||||
let signature = PrimitiveSignature::from_raw_array(&signature_bytes)?;
|
||||
let signature = Signature::from_raw_array(&signature_bytes)?;
|
||||
let address = signature.recover_address_from_msg(message)?;
|
||||
let address_bytes = address.as_slice().to_vec();
|
||||
Ok(address_bytes == public_key)
|
||||
|
||||
267
src/main.rs
267
src/main.rs
@@ -1,267 +0,0 @@
|
||||
use axum::{
|
||||
extract::ws::{Message, WebSocket, WebSocketUpgrade},
|
||||
extract::State,
|
||||
http::Method,
|
||||
response::IntoResponse,
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use futures::StreamExt;
|
||||
use log::{error, info};
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
net::SocketAddr,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use tokio::sync::{mpsc::channel, RwLock};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
use waku_bindings::{Multiaddr, WakuMessage};
|
||||
|
||||
use de_mls::{
|
||||
action_handlers::{handle_user_actions, handle_ws_action},
|
||||
match_content_topic,
|
||||
user_app_instance::create_user_instance,
|
||||
ws_actor::{RawWsMessage, WsAction, WsActor},
|
||||
AppState, Connection,
|
||||
};
|
||||
use ds::waku_actor::{run_waku_node, WakuMessageToSend};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
env_logger::init();
|
||||
let port = std::env::var("PORT")
|
||||
.map(|val| val.parse::<u16>())
|
||||
.unwrap_or(Ok(3000))?;
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], port));
|
||||
let node_port = std::env::var("NODE_PORT").expect("NODE_PORT is not set");
|
||||
let peer_addresses = std::env::var("PEER_ADDRESSES")
|
||||
.map(|val| {
|
||||
val.split(",")
|
||||
.map(|addr| {
|
||||
addr.parse::<Multiaddr>()
|
||||
.expect("Failed to parse peer address")
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.expect("PEER_ADDRESSES is not set");
|
||||
|
||||
let content_topics = Arc::new(RwLock::new(Vec::new()));
|
||||
|
||||
let (waku_sender, mut waku_receiver) = channel::<WakuMessage>(100);
|
||||
let (sender, mut receiver) = channel::<WakuMessageToSend>(100);
|
||||
let (tx, _) = tokio::sync::broadcast::channel(100);
|
||||
|
||||
let app_state = Arc::new(AppState {
|
||||
waku_node: sender,
|
||||
rooms: Mutex::new(HashSet::new()),
|
||||
content_topics,
|
||||
pubsub: tx.clone(),
|
||||
});
|
||||
info!("App state initialized");
|
||||
|
||||
let recv_messages = tokio::spawn(async move {
|
||||
info!("Running recv messages from waku");
|
||||
while let Some(msg) = waku_receiver.recv().await {
|
||||
let _ = tx.send(msg);
|
||||
}
|
||||
});
|
||||
info!("Waku receiver initialized");
|
||||
|
||||
let server_task = tokio::spawn(async move {
|
||||
info!("Running server");
|
||||
run_server(app_state, addr)
|
||||
.await
|
||||
.expect("Failed to run server")
|
||||
});
|
||||
|
||||
info!("Starting waku node");
|
||||
tokio::task::block_in_place(move || {
|
||||
tokio::runtime::Handle::current().block_on(async move {
|
||||
run_waku_node(node_port, Some(peer_addresses), waku_sender, &mut receiver).await
|
||||
})
|
||||
})?;
|
||||
|
||||
tokio::select! {
|
||||
result = recv_messages => {
|
||||
if let Err(w) = result {
|
||||
error!("Error receiving messages from waku: {w}");
|
||||
}
|
||||
}
|
||||
result = server_task => {
|
||||
if let Err(e) = result {
|
||||
error!("Error hosting server: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_server(
|
||||
app_state: Arc<AppState>,
|
||||
addr: SocketAddr,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let cors = CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
.allow_methods(vec![Method::GET]);
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(|| async { "Hello World!" }))
|
||||
.route("/ws", get(handler))
|
||||
.route("/rooms", get(get_rooms))
|
||||
.with_state(app_state)
|
||||
.layer(cors);
|
||||
|
||||
info!("Hosted on {addr:?}");
|
||||
|
||||
axum::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handler(ws: WebSocketUpgrade, State(state): State<Arc<AppState>>) -> impl IntoResponse {
|
||||
ws.on_upgrade(|socket| handle_socket(socket, state))
|
||||
}
|
||||
|
||||
async fn handle_socket(socket: WebSocket, state: Arc<AppState>) {
|
||||
info!("Handling socket");
|
||||
let (ws_sender, mut ws_receiver) = socket.split();
|
||||
let ws_actor = kameo::spawn(WsActor::new(ws_sender));
|
||||
let mut main_loop_connection = None::<Connection>;
|
||||
let cancel_token = CancellationToken::new();
|
||||
while let Some(Ok(Message::Text(data))) = ws_receiver.next().await {
|
||||
let res = ws_actor.ask(RawWsMessage { message: data }).await;
|
||||
match res {
|
||||
Ok(WsAction::Connect(connect)) => {
|
||||
info!("Got connect: {:?}", &connect);
|
||||
main_loop_connection = Some(Connection {
|
||||
eth_private_key: connect.eth_private_key.clone(),
|
||||
group_id: connect.group_id.clone(),
|
||||
should_create_group: connect.should_create,
|
||||
});
|
||||
let mut rooms = match state.rooms.lock() {
|
||||
Ok(rooms) => rooms,
|
||||
Err(e) => {
|
||||
log::error!("Failed to acquire rooms lock: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !rooms.contains(&connect.group_id.clone()) {
|
||||
rooms.insert(connect.group_id.clone());
|
||||
}
|
||||
info!("Prepare info for main loop: {main_loop_connection:?}");
|
||||
break;
|
||||
}
|
||||
Ok(_) => {
|
||||
info!("Got chat message for non-existent user");
|
||||
}
|
||||
|
||||
Err(e) => error!("Error handling message: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
let user_actor = create_user_instance(
|
||||
main_loop_connection.unwrap().clone(),
|
||||
state.clone(),
|
||||
ws_actor.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("Failed to create user instance");
|
||||
|
||||
let user_actor_clone = user_actor.clone();
|
||||
let state_clone = state.clone();
|
||||
let ws_actor_clone = ws_actor.clone();
|
||||
let cancel_token_clone = cancel_token.clone();
|
||||
|
||||
let mut user_waku_receiver = state.pubsub.subscribe();
|
||||
let mut recv_messages_waku = tokio::spawn(async move {
|
||||
info!("Running recv messages from waku for current user");
|
||||
while let Ok(msg) = user_waku_receiver.recv().await {
|
||||
let content_topic = msg.content_topic.clone();
|
||||
// Check if message belongs to a relevant topic
|
||||
if !match_content_topic(&state_clone.content_topics, &content_topic).await {
|
||||
error!("Content topic not match: {content_topic:?}");
|
||||
return;
|
||||
};
|
||||
info!("[handle_socket]: Received message from waku that matches content topic");
|
||||
let res = handle_user_actions(
|
||||
msg,
|
||||
state_clone.waku_node.clone(),
|
||||
ws_actor_clone.clone(),
|
||||
user_actor_clone.clone(),
|
||||
state_clone.clone(),
|
||||
cancel_token_clone.clone(),
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = res {
|
||||
error!("Error handling waku message: {e}");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let user_ref_clone = user_actor.clone();
|
||||
let mut recv_messages_ws = {
|
||||
tokio::spawn(async move {
|
||||
info!("Running receive messages from websocket");
|
||||
while let Some(Ok(Message::Text(text))) = ws_receiver.next().await {
|
||||
let res = handle_ws_action(
|
||||
RawWsMessage { message: text },
|
||||
ws_actor.clone(),
|
||||
user_ref_clone.clone(),
|
||||
state.waku_node.clone(),
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = res {
|
||||
error!("Error handling websocket message: {e}");
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
tokio::select! {
|
||||
_ = (&mut recv_messages_waku) => {
|
||||
info!("recv messages from waku finished");
|
||||
recv_messages_ws.abort();
|
||||
}
|
||||
_ = (&mut recv_messages_ws) => {
|
||||
info!("receive messages from websocket finished");
|
||||
recv_messages_ws.abort();
|
||||
}
|
||||
_ = cancel_token.cancelled() => {
|
||||
info!("Cancel token cancelled");
|
||||
recv_messages_ws.abort();
|
||||
recv_messages_waku.abort();
|
||||
}
|
||||
};
|
||||
|
||||
info!("Main loop finished");
|
||||
}
|
||||
|
||||
async fn get_rooms(State(state): State<Arc<AppState>>) -> String {
|
||||
let rooms = match state.rooms.lock() {
|
||||
Ok(rooms) => rooms,
|
||||
Err(e) => {
|
||||
log::error!("Failed to acquire rooms lock: {e}");
|
||||
return json!({
|
||||
"status": "Error acquiring rooms lock",
|
||||
"rooms": []
|
||||
})
|
||||
.to_string();
|
||||
}
|
||||
};
|
||||
let vec = rooms.iter().collect::<Vec<&String>>();
|
||||
match vec.len() {
|
||||
0 => json!({
|
||||
"status": "No rooms found yet!",
|
||||
"rooms": []
|
||||
})
|
||||
.to_string(),
|
||||
_ => json!({
|
||||
"status": "Success!",
|
||||
"rooms": vec
|
||||
})
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
197
src/message.rs
197
src/message.rs
@@ -17,24 +17,28 @@
|
||||
//! - [`ConversationMessage`]
|
||||
//! - [`BatchProposalsMessage`]
|
||||
//! - [`BanRequest`]
|
||||
//! - [`VotingProposal`]
|
||||
//! - [`VotePayload`]
|
||||
//! - [`UserVote`]
|
||||
//!
|
||||
use alloy::hex;
|
||||
use mls_crypto::identity::normalize_wallet_address;
|
||||
use openmls::prelude::{KeyPackage, MlsMessageOut};
|
||||
use std::convert::TryFrom;
|
||||
|
||||
use crate::{
|
||||
consensus::v1::{Proposal, Vote},
|
||||
consensus::ConsensusEvent,
|
||||
encrypt_message,
|
||||
protos::messages::v1::{app_message, UserKeyPackage, UserVote, VotingProposal},
|
||||
protos::{
|
||||
consensus::v1::{Outcome, Proposal, RequestType, UpdateRequest, Vote, VotePayload},
|
||||
de_mls::messages::v1::{
|
||||
app_message, welcome_message, AppMessage, BanRequest, BatchProposalsMessage,
|
||||
ConversationMessage, GroupAnnouncement, InvitationToJoin, ProposalAdded,
|
||||
UserKeyPackage, UserVote, WelcomeMessage,
|
||||
},
|
||||
},
|
||||
steward::GroupUpdateRequest,
|
||||
verify_message, MessageError,
|
||||
};
|
||||
use openmls::prelude::{KeyPackage, MlsMessageOut};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt::Display;
|
||||
|
||||
use crate::protos::messages::v1::{
|
||||
welcome_message, AppMessage, BanRequest, BatchProposalsMessage, ConversationMessage,
|
||||
GroupAnnouncement, InvitationToJoin, WelcomeMessage,
|
||||
};
|
||||
|
||||
// Message type constants for consistency and type safety
|
||||
pub mod message_types {
|
||||
@@ -43,8 +47,9 @@ pub mod message_types {
|
||||
pub const BAN_REQUEST: &str = "BanRequest";
|
||||
pub const PROPOSAL: &str = "Proposal";
|
||||
pub const VOTE: &str = "Vote";
|
||||
pub const VOTING_PROPOSAL: &str = "VotingProposal";
|
||||
pub const VOTE_PAYLOAD: &str = "VotePayload";
|
||||
pub const USER_VOTE: &str = "UserVote";
|
||||
pub const PROPOSAL_ADDED: &str = "ProposalAdded";
|
||||
pub const UNKNOWN: &str = "Unknown";
|
||||
}
|
||||
|
||||
@@ -62,8 +67,19 @@ impl MessageType for app_message::Payload {
|
||||
app_message::Payload::BanRequest(_) => BAN_REQUEST,
|
||||
app_message::Payload::Proposal(_) => PROPOSAL,
|
||||
app_message::Payload::Vote(_) => VOTE,
|
||||
app_message::Payload::VotingProposal(_) => VOTING_PROPOSAL,
|
||||
app_message::Payload::VotePayload(_) => VOTE_PAYLOAD,
|
||||
app_message::Payload::UserVote(_) => USER_VOTE,
|
||||
app_message::Payload::ProposalAdded(_) => PROPOSAL_ADDED,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MessageType for UpdateRequest {
|
||||
fn message_type(&self) -> &'static str {
|
||||
match RequestType::try_from(self.request_type) {
|
||||
Ok(RequestType::AddMember) => "Add Member",
|
||||
Ok(RequestType::RemoveMember) => "Remove Member",
|
||||
_ => "Unknown",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,76 +137,10 @@ impl From<UserKeyPackage> for WelcomeMessage {
|
||||
}
|
||||
}
|
||||
|
||||
// APP MESSAGE SUBTOPIC
|
||||
impl Display for AppMessage {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self.payload {
|
||||
Some(app_message::Payload::ConversationMessage(conversation_message)) => {
|
||||
write!(
|
||||
f,
|
||||
"{}: {}",
|
||||
conversation_message.sender,
|
||||
String::from_utf8_lossy(&conversation_message.message)
|
||||
)
|
||||
}
|
||||
Some(app_message::Payload::BatchProposalsMessage(batch_msg)) => {
|
||||
write!(
|
||||
f,
|
||||
"BatchProposalsMessage: {} proposals for group {}",
|
||||
batch_msg.mls_proposals.len(),
|
||||
String::from_utf8_lossy(&batch_msg.group_name)
|
||||
)
|
||||
}
|
||||
Some(app_message::Payload::BanRequest(ban_request)) => {
|
||||
write!(
|
||||
f,
|
||||
"SYSTEM: {} wants to ban {}",
|
||||
ban_request.requester, ban_request.user_to_ban
|
||||
)
|
||||
}
|
||||
Some(app_message::Payload::Proposal(proposal)) => {
|
||||
write!(
|
||||
f,
|
||||
"Proposal: ID {} with {} votes for {} voters",
|
||||
proposal.proposal_id,
|
||||
proposal.votes.len(),
|
||||
proposal.expected_voters_count
|
||||
)
|
||||
}
|
||||
Some(app_message::Payload::Vote(vote)) => {
|
||||
write!(
|
||||
f,
|
||||
"Vote: {} for proposal {} ({})",
|
||||
if vote.vote { "YES" } else { "NO" },
|
||||
vote.proposal_id,
|
||||
vote.vote_id
|
||||
)
|
||||
}
|
||||
Some(app_message::Payload::VotingProposal(voting_proposal)) => {
|
||||
write!(
|
||||
f,
|
||||
"VotingProposal: ID {} for group {}",
|
||||
voting_proposal.proposal_id, voting_proposal.group_name
|
||||
)
|
||||
}
|
||||
Some(app_message::Payload::UserVote(user_vote)) => {
|
||||
write!(
|
||||
f,
|
||||
"UserVote: {} for proposal {} in group {}",
|
||||
if user_vote.vote { "YES" } else { "NO" },
|
||||
user_vote.proposal_id,
|
||||
user_vote.group_name
|
||||
)
|
||||
}
|
||||
None => write!(f, "Empty message"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<VotingProposal> for AppMessage {
|
||||
fn from(voting_proposal: VotingProposal) -> Self {
|
||||
impl From<VotePayload> for AppMessage {
|
||||
fn from(vote_payload: VotePayload) -> Self {
|
||||
AppMessage {
|
||||
payload: Some(app_message::Payload::VotingProposal(voting_proposal)),
|
||||
payload: Some(app_message::Payload::VotePayload(vote_payload)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -246,20 +196,75 @@ impl From<Vote> for AppMessage {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// This struct is used to represent the message from the user that we got from web socket
|
||||
#[derive(Deserialize, Debug, PartialEq, Serialize)]
|
||||
pub struct UserMessage {
|
||||
pub message: Vec<u8>,
|
||||
pub group_id: String,
|
||||
|
||||
impl From<ProposalAdded> for AppMessage {
|
||||
fn from(proposal_added: ProposalAdded) -> Self {
|
||||
AppMessage {
|
||||
payload: Some(app_message::Payload::ProposalAdded(proposal_added)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This struct is used to represent the connection data that web socket sends to the user
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
||||
pub struct ConnectMessage {
|
||||
/// This is the private key of the user that we will use to authenticate the user
|
||||
pub eth_private_key: String,
|
||||
/// This is the id of the group that the user is joining
|
||||
pub group_id: String,
|
||||
/// This is the flag that indicates if the user should create a new group or subscribe to an existing one
|
||||
pub should_create: bool,
|
||||
impl From<ConsensusEvent> for Outcome {
|
||||
fn from(consensus_event: ConsensusEvent) -> Self {
|
||||
match consensus_event {
|
||||
ConsensusEvent::ConsensusReached {
|
||||
proposal_id: _,
|
||||
result: true,
|
||||
} => Outcome::Accepted,
|
||||
ConsensusEvent::ConsensusReached {
|
||||
proposal_id: _,
|
||||
result: false,
|
||||
} => Outcome::Rejected,
|
||||
ConsensusEvent::ConsensusFailed {
|
||||
proposal_id: _,
|
||||
reason: _,
|
||||
} => Outcome::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<GroupUpdateRequest> for UpdateRequest {
|
||||
fn from(group_update_request: GroupUpdateRequest) -> Self {
|
||||
match group_update_request {
|
||||
GroupUpdateRequest::AddMember(kp) => UpdateRequest {
|
||||
request_type: RequestType::AddMember as i32,
|
||||
wallet_address: kp.leaf_node().credential().serialized_content().to_vec(),
|
||||
},
|
||||
GroupUpdateRequest::RemoveMember(id) => UpdateRequest {
|
||||
request_type: RequestType::RemoveMember as i32,
|
||||
wallet_address: hex::decode(id.strip_prefix("0x").unwrap_or(&id))
|
||||
.unwrap_or_else(|_| id.into_bytes()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to convert protobuf UpdateRequest to display format
|
||||
pub fn convert_group_requests_to_display(
|
||||
group_requests: &[UpdateRequest],
|
||||
) -> Vec<(String, String)> {
|
||||
let mut results = Vec::new();
|
||||
|
||||
for req in group_requests {
|
||||
match RequestType::try_from(req.request_type) {
|
||||
Ok(RequestType::AddMember) => {
|
||||
results.push((
|
||||
"Add Member".to_string(),
|
||||
normalize_wallet_address(&req.wallet_address),
|
||||
));
|
||||
}
|
||||
Ok(RequestType::RemoveMember) => {
|
||||
results.push((
|
||||
"Remove Member".to_string(),
|
||||
normalize_wallet_address(&req.wallet_address),
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
results.push(("Unknown".to_string(), "Invalid request".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
@@ -13,8 +13,9 @@ message AppMessage {
|
||||
BanRequest ban_request = 3;
|
||||
consensus.v1.Proposal proposal = 4;
|
||||
consensus.v1.Vote vote = 5;
|
||||
VotingProposal voting_proposal = 6;
|
||||
consensus.v1.VotePayload vote_payload = 6;
|
||||
UserVote user_vote = 7;
|
||||
ProposalAdded proposal_added = 8;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,15 +37,15 @@ message BatchProposalsMessage {
|
||||
bytes commit_message = 3; // MLS commit message
|
||||
}
|
||||
|
||||
// New message types for voting
|
||||
message VotingProposal {
|
||||
uint32 proposal_id = 1;
|
||||
string group_name = 2;
|
||||
string payload = 3;
|
||||
}
|
||||
|
||||
// Yes/No vote for a given proposal. Based on the result, the `consensus.v1.Vote` will be created.
|
||||
message UserVote {
|
||||
uint32 proposal_id = 1;
|
||||
bool vote = 2;
|
||||
string group_name = 3;
|
||||
}
|
||||
|
||||
// Proposal added message is sent to the UI when a new proposal is added to the group.
|
||||
message ProposalAdded {
|
||||
string group_id = 1;
|
||||
consensus.v1.UpdateRequest request = 2;
|
||||
}
|
||||
|
||||
@@ -2,10 +2,16 @@ syntax = "proto3";
|
||||
|
||||
package consensus.v1;
|
||||
|
||||
enum RequestType {
|
||||
REQUEST_TYPE_UNSPECIFIED = 0;
|
||||
REQUEST_TYPE_ADD_MEMBER = 1;
|
||||
REQUEST_TYPE_REMOVE_MEMBER = 2;
|
||||
}
|
||||
|
||||
// Proposal represents a consensus proposal that needs voting
|
||||
message Proposal {
|
||||
string name = 10; // Proposal name
|
||||
string payload = 11; // Payload of the proposal
|
||||
repeated UpdateRequest group_requests = 11; // Structured group update requests
|
||||
uint32 proposal_id = 12; // Unique identifier of the proposal
|
||||
bytes proposal_owner = 13; // Public key of the creator
|
||||
repeated Vote votes = 14; // Vote list in the proposal
|
||||
@@ -28,3 +34,28 @@ message Vote {
|
||||
bytes vote_hash = 27; // Hash of all previously defined fields in Vote
|
||||
bytes signature = 28; // Signature of vote_hash
|
||||
}
|
||||
|
||||
enum Outcome {
|
||||
OUTCOME_UNSPECIFIED = 0;
|
||||
OUTCOME_ACCEPTED = 1;
|
||||
OUTCOME_REJECTED = 2;
|
||||
}
|
||||
|
||||
message ProposalResult {
|
||||
string group_id = 31;
|
||||
uint32 proposal_id = 32;
|
||||
Outcome outcome = 33;
|
||||
uint64 decided_at_ms = 34;
|
||||
}
|
||||
|
||||
message VotePayload {
|
||||
string group_id = 41;
|
||||
uint32 proposal_id = 42;
|
||||
repeated UpdateRequest group_requests = 43; // Structured group update requests
|
||||
uint64 timestamp = 44;
|
||||
}
|
||||
|
||||
message UpdateRequest {
|
||||
RequestType request_type = 51;
|
||||
bytes wallet_address = 52;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//!
|
||||
//! - **Working**: Normal operation state where users can send any message freely
|
||||
//! - **Waiting**: Steward epoch state where only steward can send BATCH_PROPOSALS_MESSAGE (if proposals exist)
|
||||
//! - **Voting**: Voting state where everyone can send VOTE/USER_VOTE, only steward can send VOTING_PROPOSAL/PROPOSAL
|
||||
//! - **Voting**: Voting state where everyone can send VOTE/USER_VOTE, only steward can send VOTE_PAYLOAD/PROPOSAL
|
||||
//! - **ConsensusReached**: Consensus achieved, waiting for steward to send batch proposals
|
||||
//! - **ConsensusFailed**: Consensus failed due to timeout or other reasons
|
||||
//!
|
||||
@@ -36,7 +36,7 @@
|
||||
//!
|
||||
//! ## Voting State
|
||||
//! - **All users**: Can send VOTE and USER_VOTE
|
||||
//! - **Steward only**: Can send VOTING_PROPOSAL and PROPOSAL
|
||||
//! - **Steward only**: Can send VOTE_PAYLOAD and PROPOSAL
|
||||
//! - **All users**: All other message types blocked
|
||||
//!
|
||||
//! ## ConsensusReached State
|
||||
@@ -96,8 +96,7 @@
|
||||
//! - Failed votes result in proposals being discarded and return to working state
|
||||
|
||||
use std::fmt::Display;
|
||||
|
||||
use log::info;
|
||||
use tracing::info;
|
||||
|
||||
use crate::message::message_types;
|
||||
use crate::steward::Steward;
|
||||
@@ -110,12 +109,10 @@ pub enum GroupState {
|
||||
Working,
|
||||
/// Waiting state during steward epoch - only steward can send BATCH_PROPOSALS_MESSAGE
|
||||
Waiting,
|
||||
/// Voting state - everyone can send VOTE/USER_VOTE, only steward can send VOTING_PROPOSAL/PROPOSAL
|
||||
/// Voting state - everyone can send VOTE/USER_VOTE, only steward can send VOTE_PAYLOAD/PROPOSAL
|
||||
Voting,
|
||||
/// Consensus reached state - consensus achieved, waiting for steward to send batch proposals
|
||||
ConsensusReached,
|
||||
/// Consensus failed state - consensus failed due to timeout or other reasons
|
||||
ConsensusFailed,
|
||||
}
|
||||
|
||||
impl Display for GroupState {
|
||||
@@ -125,7 +122,6 @@ impl Display for GroupState {
|
||||
GroupState::Waiting => "Waiting",
|
||||
GroupState::Voting => "Voting",
|
||||
GroupState::ConsensusReached => "ConsensusReached",
|
||||
GroupState::ConsensusFailed => "ConsensusFailed",
|
||||
};
|
||||
write!(f, "{state}")
|
||||
}
|
||||
@@ -193,10 +189,10 @@ impl GroupStateMachine {
|
||||
GroupState::Voting => {
|
||||
// In voting state, only voting-related messages allowed
|
||||
match message_type {
|
||||
message_types::VOTE => true, // Everyone can send votes
|
||||
message_types::USER_VOTE => true, // Everyone can send user votes
|
||||
message_types::VOTING_PROPOSAL => is_steward, // Only steward can send voting proposals
|
||||
message_types::PROPOSAL => is_steward, // Only steward can send proposals
|
||||
message_types::VOTE => true, // Everyone can send votes
|
||||
message_types::USER_VOTE => true, // Everyone can send user votes
|
||||
message_types::VOTE_PAYLOAD => is_steward, // Only steward can send voting proposals
|
||||
message_types::PROPOSAL => is_steward, // Only steward can send proposals
|
||||
_ => false, // All other messages blocked during voting
|
||||
}
|
||||
}
|
||||
@@ -207,10 +203,6 @@ impl GroupStateMachine {
|
||||
_ => false, // All other messages blocked during ConsensusReached
|
||||
}
|
||||
}
|
||||
GroupState::ConsensusFailed => {
|
||||
// In ConsensusFailed state, no messages are allowed
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,33 +272,6 @@ impl GroupStateMachine {
|
||||
info!("[start_consensus_reached] Transitioning to ConsensusReached state");
|
||||
}
|
||||
|
||||
/// Start consensus failed state (for peers after consensus failure).
|
||||
///
|
||||
/// ## State Transition:
|
||||
/// Any State → ConsensusFailed
|
||||
///
|
||||
/// ## Usage:
|
||||
/// Called when consensus fails due to timeout or other reasons.
|
||||
/// This state blocks all message types until recovery is initiated.
|
||||
pub fn start_consensus_failed(&mut self) {
|
||||
self.state = GroupState::ConsensusFailed;
|
||||
info!("[start_consensus_failed] Transitioning to ConsensusFailed state");
|
||||
}
|
||||
|
||||
/// Recover from consensus failure by transitioning back to Working state
|
||||
pub fn recover_from_consensus_failure(&mut self) -> Result<(), GroupError> {
|
||||
if self.state != GroupState::ConsensusFailed {
|
||||
return Err(GroupError::InvalidStateTransition {
|
||||
from: self.state.to_string(),
|
||||
to: "Working".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
self.state = GroupState::Working;
|
||||
info!("[recover_from_consensus_failure] Recovering from consensus failure, transitioning to Working state");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start working state (for non-steward peers after consensus or edge case recovery).
|
||||
///
|
||||
/// ## State Transition:
|
||||
@@ -354,6 +319,21 @@ impl GroupStateMachine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the current epoch proposals for UI display.
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Vector of proposals currently collected for the next steward epoch
|
||||
///
|
||||
/// ## Usage:
|
||||
/// Used to display current proposals in the UI for stewards.
|
||||
pub async fn get_current_epoch_proposals(&self) -> Vec<crate::steward::GroupUpdateRequest> {
|
||||
if let Some(steward) = &self.steward {
|
||||
steward.get_current_epoch_proposals().await
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the count of proposals in the voting epoch.
|
||||
///
|
||||
/// ## Returns:
|
||||
@@ -670,7 +650,7 @@ mod tests {
|
||||
));
|
||||
assert!(!state_machine.can_send_message_type(false, false, message_types::VOTE));
|
||||
assert!(!state_machine.can_send_message_type(false, false, message_types::USER_VOTE));
|
||||
assert!(!state_machine.can_send_message_type(false, false, message_types::VOTING_PROPOSAL));
|
||||
assert!(!state_machine.can_send_message_type(false, false, message_types::VOTE_PAYLOAD));
|
||||
assert!(!state_machine.can_send_message_type(false, false, message_types::PROPOSAL));
|
||||
|
||||
// BatchProposalsMessage should only be allowed from steward with proposals
|
||||
@@ -701,8 +681,8 @@ mod tests {
|
||||
assert!(state_machine.can_send_message_type(false, false, message_types::USER_VOTE));
|
||||
|
||||
// Only steward can send voting proposals and proposals
|
||||
assert!(!state_machine.can_send_message_type(false, false, message_types::VOTING_PROPOSAL));
|
||||
assert!(state_machine.can_send_message_type(true, false, message_types::VOTING_PROPOSAL));
|
||||
assert!(!state_machine.can_send_message_type(false, false, message_types::VOTE_PAYLOAD));
|
||||
assert!(state_machine.can_send_message_type(true, false, message_types::VOTE_PAYLOAD));
|
||||
assert!(!state_machine.can_send_message_type(false, false, message_types::PROPOSAL));
|
||||
assert!(state_machine.can_send_message_type(true, false, message_types::PROPOSAL));
|
||||
|
||||
|
||||
@@ -4,7 +4,10 @@ use openmls::prelude::KeyPackage;
|
||||
use std::{fmt::Display, str::FromStr, sync::Arc};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{protos::messages::v1::GroupAnnouncement, *};
|
||||
use crate::{
|
||||
decrypt_message, error::MessageError, generate_keypair,
|
||||
protos::de_mls::messages::v1::GroupAnnouncement, sign_message,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Steward {
|
||||
@@ -101,6 +104,11 @@ impl Steward {
|
||||
self.voting_epoch_proposals.lock().await.len()
|
||||
}
|
||||
|
||||
/// Get the current epoch proposals for UI display.
|
||||
pub async fn get_current_epoch_proposals(&self) -> Vec<GroupUpdateRequest> {
|
||||
self.current_epoch_proposals.lock().await.clone()
|
||||
}
|
||||
|
||||
/// Apply proposals for the current epoch (called after successful voting).
|
||||
pub async fn empty_voting_epoch_proposals(&mut self) {
|
||||
self.voting_epoch_proposals.lock().await.clear();
|
||||
|
||||
1666
src/user.rs
1666
src/user.rs
File diff suppressed because it is too large
Load Diff
133
src/user/README.md
Normal file
133
src/user/README.md
Normal file
@@ -0,0 +1,133 @@
|
||||
# User Module
|
||||
|
||||
The `user` module encapsulates everything the desktop gateway needs to manage a single MLS participant.
|
||||
It owns the MLS identity, tracks the local view of every group the user joined,
|
||||
drives steward epochs, and bridges consensus messages between the core runtime, Waku network, and UI.
|
||||
|
||||
## Directory Layout
|
||||
|
||||
``` bash
|
||||
src/user/
|
||||
├── consensus.rs # Voting lifecycle, consensus event fan-in/out
|
||||
├── groups.rs # Group creation/join/leave utilities and state queries
|
||||
├── messaging.rs # Application-level messaging helpers (ban requests, signing)
|
||||
├── mod.rs # `User` actor definition and shared types
|
||||
├── proposals.rs # Steward batch proposal processing and pending queues
|
||||
├── README.md # This file
|
||||
├── steward.rs # Steward-only helpers: epochs, proposals, apply flow
|
||||
└── waku.rs # Waku ingestion + routing to per-topic handlers
|
||||
```
|
||||
|
||||
Each file extends `impl User` with domain-specific responsibilities,
|
||||
keeping the top-level actor (`mod.rs`) lean.
|
||||
|
||||
## Core Concepts
|
||||
|
||||
- **`User` actor** – Holds one `Identity`, an `MlsProvider`,
|
||||
a map of per-group `Arc<RwLock<Group>>`, the consensus facade, and the Ethereum signer.
|
||||
|
||||
- **`UserAction` enum (`mod.rs`)** – Return type for most handlers.
|
||||
Signals what the caller (gateway) should do next:
|
||||
- `SendToWaku(WakuMessageToSend)`
|
||||
- `SendToApp(AppMessage)`
|
||||
- `LeaveGroup(String)` (triggers UI + cleanup)
|
||||
- `DoNothing` (no side effects)
|
||||
|
||||
- **Per-group concurrency** – Keeps a `HashMap<String, Arc<RwLock<Group>>>`.
|
||||
Each group has its own `RwLock`, allowing independent state transitions without blocking unrelated groups.
|
||||
|
||||
- **Pending batches (`proposals.rs`)** – Non-steward clients may receive `BatchProposalsMessage` while
|
||||
still catching up to state `Waiting`.
|
||||
`PendingBatches` stores the payload until the group is ready to apply it.
|
||||
|
||||
## Lifecycle Overview
|
||||
|
||||
1. **Login** – The gateway calls `User::new` with a private key.
|
||||
The actor derives an MLS identity (`mls_crypto::Identity`)
|
||||
and keeps an `alloy::PrivateKeySigner` for consensus signatures.
|
||||
|
||||
2. **Group discovery** – `groups.rs` exposes helpers:
|
||||
- `create_group` – Either launches a steward-owned MLS group or prepares a placeholder for later joining.
|
||||
- `join_group` – Applies a received `Welcome` message to hydrate the MLS state.
|
||||
- `get_group_members` / `get_group_state` / `leave_group` – Used by the UI for metadata and teardown.
|
||||
|
||||
3. **Message routing** – Incoming Waku traffic is delivered to `waku.rs::process_waku_message`, which:
|
||||
- Filters out self-originated packets (matching `msg.meta` to the group `app_id`).
|
||||
- Routes `WELCOME_SUBTOPIC` payloads to `process_welcome_subtopic`.
|
||||
- Routes `APP_MSG_SUBTOPIC` payloads to `process_app_subtopic`.
|
||||
- Converts MLS protocol messages into `GroupAction`s,
|
||||
mapping them back into `UserAction`s so the gateway can forward data to the UI or back onto Waku.
|
||||
|
||||
4. **Consensus bridge** – `consensus.rs` is the glue to `ConsensusService`:
|
||||
- `process_consensus_proposal` and `process_consensus_vote` persist incoming messages and
|
||||
transition group state.
|
||||
- `process_user_vote` produces either consensus votes (steward) or user votes (regular members)
|
||||
and wraps them for Waku transmission.
|
||||
- `handle_consensus_event` reacts to events emitted by the service,
|
||||
ensuring the MLS state machine aligns with voting outcomes.
|
||||
It reuses `handle_consensus_result` to collapse steward/non-steward flows
|
||||
and trigger follow-up actions (apply proposals, queue batch data, or leave the group).
|
||||
|
||||
5. **Steward duties** – `steward.rs` layers steward-only APIs:
|
||||
- Introspection helpers (`is_user_steward_for_group`, `get_current_epoch_proposals`, etc.).
|
||||
- Epoch management (`start_steward_epoch`, `get_proposals_for_steward_voting`),
|
||||
which kicks the MLS state machine into `Waiting` / `Voting`.
|
||||
- Proposal actions (`add_remove_proposal`, `apply_proposals`) that serialize MLS proposals,
|
||||
commits, and optional welcomes into `WakuMessageToSend` objects for broadcast.
|
||||
|
||||
6. **Application-facing messaging** – `messaging.rs` contains:
|
||||
- `build_group_message` – Wraps an `AppMessage` in MLS encryption for the target group.
|
||||
- `process_ban_request` – Normalizes addresses, routes steward vs. member behavior
|
||||
(queueing steward removal proposals or forwarding the request back to the group).
|
||||
- An implementation of `LocalSigner` for `PrivateKeySigner`,
|
||||
allowing consensus code to request signatures uniformly.
|
||||
|
||||
7. **Proposal batches** – `proposals.rs` handles the post-consensus MLS churn:
|
||||
- `process_batch_proposals_message` – Applies proposals, deserializes MLS commits,
|
||||
and emits the resulting `UserAction`.
|
||||
- `process_stored_batch_proposals` – Replays a deferred batch once the group transitions into `Waiting`.
|
||||
|
||||
## Waku Topics & Message Types
|
||||
|
||||
| Subtopic | Handler | Purpose |
|
||||
|---------------------|-------------------------------|---------|
|
||||
| `WELCOME_SUBTOPIC` | `process_welcome_subtopic` | Steward announcements, encrypted key packages, welcome messages |
|
||||
| `APP_MSG_SUBTOPIC` | `process_app_subtopic` | Batch proposals, encrypted MLS traffic, consensus proposals/votes |
|
||||
|
||||
`process_welcome_subtopic` contains the joining handshake logic:
|
||||
|
||||
- **GroupAnnouncement** → Non-stewards encrypt and send their key package back.
|
||||
- **UserKeyPackage** → Stewards decrypt, store invite proposals, and notify the UI.
|
||||
- **InvitationToJoin** → Non-stewards validate, call `join_group`, and broadcast a system chat message.
|
||||
|
||||
## State Machine Touch Points
|
||||
|
||||
Although the primary MLS state machine lives in `crate::state_machine`, the user module coordinates transitions by calling:
|
||||
|
||||
- `start_steward_epoch_with_validation`
|
||||
- `start_voting`, `complete_voting`, `handle_yes_vote`, `handle_no_vote`
|
||||
- `start_waiting`, `start_consensus_reached`, `start_working`
|
||||
|
||||
This ensures both steward and non-steward clients converge on the same `GroupState` after each consensus result or batch commit.
|
||||
|
||||
## Extending the Module
|
||||
|
||||
When adding new functionality:
|
||||
|
||||
1. Decide whether the behavior is steward-specific, consensus-related,
|
||||
or generic per-group logic, then extend the appropriate file.
|
||||
Keeping concerns separated avoids monolithic impl blocks.
|
||||
2. Return a `UserAction` so the caller (gateway) can decide where to forward the outcome.
|
||||
3. Prefer reusing `group_ref(group_name)` to fetch the per-group lock; release the lock (`drop`) before performing long-running work to avoid deadlocks.
|
||||
4. If new Waku payloads are introduced, update `process_waku_message` with a deterministic routing branch and ensure the UI/gateway understands the resulting `AppMessage`.
|
||||
|
||||
## Related Tests
|
||||
|
||||
Integration scenarios that exercise this module live under:
|
||||
|
||||
- `tests/user_test.rs`
|
||||
- `tests/consensus_realtime_test.rs`
|
||||
- `tests/state_machine_test.rs`
|
||||
- `tests/consensus_multi_group_test.rs`
|
||||
|
||||
These are good references when updating state transitions or consensus flows.
|
||||
355
src/user/consensus.rs
Normal file
355
src/user/consensus.rs
Normal file
@@ -0,0 +1,355 @@
|
||||
use tracing::{error, info};
|
||||
|
||||
use ds::waku_actor::WakuMessageToSend;
|
||||
|
||||
use crate::{
|
||||
consensus::ConsensusEvent,
|
||||
error::UserError,
|
||||
protos::{
|
||||
consensus::v1::{Proposal, Vote, VotePayload},
|
||||
de_mls::messages::v1::AppMessage,
|
||||
},
|
||||
state_machine::GroupState,
|
||||
user::{User, UserAction},
|
||||
};
|
||||
|
||||
impl User {
|
||||
pub async fn set_up_consensus_threshold_for_group(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
proposal_id: u32,
|
||||
consensus_threshold: f64,
|
||||
) -> Result<(), UserError> {
|
||||
self.consensus_service
|
||||
.set_consensus_threshold_for_group_session(group_name, proposal_id, consensus_threshold)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
/// Handle consensus result after it's determined.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group the consensus is for
|
||||
/// - `vote_result`: Whether the consensus passed (true) or failed (false)
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Vector of Waku messages to send (if any)
|
||||
///
|
||||
/// ## State Transitions:
|
||||
/// **Steward:**
|
||||
/// - **Vote YES**: Voting → ConsensusReached → Waiting → Working (creates and sends batch proposals, then applies them)
|
||||
/// - **Vote NO**: Voting → Working (discards proposals)
|
||||
///
|
||||
/// **Non-Steward:**
|
||||
/// - **Vote YES**: Voting → ConsensusReached → Waiting → Working (waits for consensus + batch proposals, then applies them)
|
||||
/// - **Vote NO**: Voting → Working (no proposals to apply)
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Completes voting in the group
|
||||
/// - Handles proposal application or cleanup based on result
|
||||
/// - Manages state transitions for both steward and non-steward users
|
||||
/// - Processes pending batch proposals if available
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - Various state machine and proposal processing errors
|
||||
async fn handle_consensus_result(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
vote_result: bool,
|
||||
) -> Result<Vec<WakuMessageToSend>, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
group.write().await.complete_voting(vote_result).await?;
|
||||
|
||||
// Handle vote result based on steward status
|
||||
if group.read().await.is_steward().await {
|
||||
if vote_result {
|
||||
// Vote YES: Apply proposals and send commit messages
|
||||
info!("[handle_consensus_result]: Vote YES, sending commit message");
|
||||
|
||||
// Apply proposals and complete (state must be ConsensusReached for this)
|
||||
let messages = self.apply_proposals(group_name).await?;
|
||||
group.write().await.handle_yes_vote().await?;
|
||||
Ok(messages)
|
||||
} else {
|
||||
// Vote NO: Empty proposal queue without applying, no commit messages
|
||||
info!(
|
||||
"[handle_consensus_result]: Vote NO, emptying proposal queue without applying"
|
||||
);
|
||||
|
||||
// Empty proposals without state requirement (direct steward call)
|
||||
group.write().await.handle_no_vote().await?;
|
||||
|
||||
Ok(vec![])
|
||||
}
|
||||
} else if vote_result {
|
||||
// Vote YES: Group already moved to ConsensusReached during complete_voting; transition to Waiting
|
||||
{
|
||||
let mut group_guard = group.write().await;
|
||||
group_guard.start_waiting_after_consensus().await?;
|
||||
}
|
||||
info!("[handle_consensus_result]: Non-steward user transitioning to Waiting state to await batch proposals");
|
||||
|
||||
// Check if there are pending batch proposals that can now be processed
|
||||
if self.pending_batch_proposals.contains(group_name).await {
|
||||
info!("[handle_consensus_result]: Non-steward user has pending batch proposals, processing them now");
|
||||
let action = self.process_stored_batch_proposals(group_name).await?;
|
||||
info!("[handle_consensus_result]: Successfully processed pending batch proposals");
|
||||
if let Some(action) = action {
|
||||
match action {
|
||||
UserAction::SendToWaku(waku_message) => {
|
||||
info!("[handle_consensus_result]: Sending waku message to backend");
|
||||
Ok(vec![waku_message])
|
||||
}
|
||||
UserAction::LeaveGroup(group_name) => {
|
||||
self.leave_group(group_name.as_str()).await?;
|
||||
info!("[handle_consensus_result]: Non-steward user left group {group_name}");
|
||||
Ok(vec![])
|
||||
}
|
||||
UserAction::DoNothing => {
|
||||
info!("[handle_consensus_result]: No action to process");
|
||||
Ok(vec![])
|
||||
}
|
||||
_ => {
|
||||
error!("[handle_consensus_result]: Invalid action to process");
|
||||
Err(UserError::InvalidUserAction(action.to_string()))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("[handle_consensus_result]: No action to process");
|
||||
Ok(vec![])
|
||||
}
|
||||
} else {
|
||||
info!("[handle_consensus_result]: No pending batch proposals to process");
|
||||
Ok(vec![])
|
||||
}
|
||||
} else {
|
||||
// Vote NO: Transition to Working state
|
||||
group.write().await.start_working().await;
|
||||
info!("[handle_consensus_result]: Non-steward user transitioning to Working state after failed vote");
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle incoming consensus events and return commit messages if needed.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group the consensus event is for
|
||||
/// - `event`: The consensus event to handle
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Vector of Waku messages to send (if any)
|
||||
///
|
||||
/// ## Event Types Handled:
|
||||
/// - **ConsensusReached**: Handles successful consensus with result
|
||||
/// - **ConsensusFailed**: Handles consensus failure with liveness criteria
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Routes consensus events to appropriate handlers
|
||||
/// - Manages state transitions based on consensus results
|
||||
/// - Applies liveness criteria for failed consensus
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - `UserError::InvalidGroupState` if group is in invalid state
|
||||
/// - Various consensus handling errors
|
||||
pub async fn handle_consensus_event(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
event: ConsensusEvent,
|
||||
) -> Result<Vec<WakuMessageToSend>, UserError> {
|
||||
match event {
|
||||
ConsensusEvent::ConsensusReached {
|
||||
proposal_id,
|
||||
result,
|
||||
} => {
|
||||
info!(
|
||||
"[handle_consensus_event]: Consensus reached for proposal {proposal_id} in group {group_name}: {result}"
|
||||
);
|
||||
|
||||
let group = self.group_ref(group_name).await?;
|
||||
|
||||
let current_state = group.read().await.get_state().await;
|
||||
info!(
|
||||
"[handle_consensus_event]: Current state: {:?} for proposal {proposal_id}",
|
||||
current_state
|
||||
);
|
||||
|
||||
// Handle the consensus result and return commit messages
|
||||
let messages = self.handle_consensus_result(group_name, result).await?;
|
||||
Ok(messages)
|
||||
}
|
||||
ConsensusEvent::ConsensusFailed {
|
||||
proposal_id,
|
||||
reason,
|
||||
} => {
|
||||
info!(
|
||||
"[handle_consensus_event]: Consensus failed for proposal {proposal_id} in group {group_name}: {reason}"
|
||||
);
|
||||
|
||||
let group = self.group_ref(group_name).await?;
|
||||
|
||||
let current_state = group.read().await.get_state().await;
|
||||
|
||||
info!("[handle_consensus_event]: Handling consensus failure in {:?} state for proposal {proposal_id}", current_state);
|
||||
|
||||
// Handle consensus failure based on current state
|
||||
match current_state {
|
||||
GroupState::Voting => {
|
||||
// If we're in Voting state, complete voting with liveness criteria
|
||||
// Get liveness criteria from the actual proposal
|
||||
let liveness_result = self
|
||||
.consensus_service
|
||||
.get_proposal_liveness_criteria(group_name, proposal_id)
|
||||
.await
|
||||
.unwrap_or(false); // Default to false if proposal not found
|
||||
|
||||
info!("[handle_consensus_result]:Applying liveness criteria for failed proposal {proposal_id}: {liveness_result}");
|
||||
let messages = self
|
||||
.handle_consensus_result(group_name, liveness_result)
|
||||
.await?;
|
||||
Ok(messages)
|
||||
}
|
||||
_ => Err(UserError::InvalidGroupState(current_state.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Process incoming consensus proposal.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `proposal`: The consensus proposal to process
|
||||
/// - `group_name`: The name of the group the proposal is for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `UserAction` indicating what action should be taken
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Stores proposal in consensus service
|
||||
/// - Starts voting phase in the group
|
||||
/// - Creates voting proposal for frontend
|
||||
///
|
||||
/// ## State Transitions:
|
||||
/// - Any state → Voting (starts voting phase)
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - Various consensus service errors
|
||||
pub async fn process_consensus_proposal(
|
||||
&mut self,
|
||||
proposal: Proposal,
|
||||
group_name: &str,
|
||||
) -> Result<UserAction, UserError> {
|
||||
self.consensus_service
|
||||
.process_incoming_proposal(group_name, proposal.clone())
|
||||
.await?;
|
||||
|
||||
let group = self.group_ref(group_name).await?;
|
||||
group.write().await.start_voting().await?;
|
||||
info!(
|
||||
"[process_consensus_proposal]: Starting voting for proposal {}",
|
||||
proposal.proposal_id
|
||||
);
|
||||
|
||||
// Send voting proposal to frontend
|
||||
let voting_proposal: AppMessage = VotePayload {
|
||||
group_id: group_name.to_string(),
|
||||
proposal_id: proposal.proposal_id,
|
||||
group_requests: proposal.group_requests.clone(),
|
||||
timestamp: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)?
|
||||
.as_secs(),
|
||||
}
|
||||
.into();
|
||||
|
||||
Ok(UserAction::SendToApp(voting_proposal))
|
||||
}
|
||||
|
||||
/// Process user vote from frontend.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `proposal_id`: The ID of the proposal to vote on
|
||||
/// - `user_vote`: The user's vote (true for yes, false for no)
|
||||
/// - `group_name`: The name of the group the vote is for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `UserAction` indicating what action should be taken
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - For stewards: Creates consensus vote and sends to group
|
||||
/// - For regular users: Processes user vote in consensus service
|
||||
/// - Builds and sends appropriate message to group
|
||||
///
|
||||
/// ## Message Types:
|
||||
/// - **Steward**: Sends consensus vote message
|
||||
/// - **Regular User**: Sends user vote message
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - Various consensus service and message building errors
|
||||
pub async fn process_user_vote(
|
||||
&mut self,
|
||||
proposal_id: u32,
|
||||
user_vote: bool,
|
||||
group_name: &str,
|
||||
) -> Result<UserAction, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let app_message = if group.read().await.is_steward().await {
|
||||
info!(
|
||||
"[process_user_vote]: Steward voting for proposal {proposal_id} in group {group_name}"
|
||||
);
|
||||
let proposal = self
|
||||
.consensus_service
|
||||
.vote_on_proposal(group_name, proposal_id, user_vote, self.eth_signer.clone())
|
||||
.await?;
|
||||
proposal.into()
|
||||
} else {
|
||||
info!(
|
||||
"[process_user_vote]: User voting for proposal {proposal_id} in group {group_name}"
|
||||
);
|
||||
let vote = self
|
||||
.consensus_service
|
||||
.process_user_vote(group_name, proposal_id, user_vote, self.eth_signer.clone())
|
||||
.await?;
|
||||
vote.into()
|
||||
};
|
||||
|
||||
let waku_msg = self.build_group_message(app_message, group_name).await?;
|
||||
|
||||
Ok(UserAction::SendToWaku(waku_msg))
|
||||
}
|
||||
|
||||
/// Process incoming consensus vote and handle immediate state transitions.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `vote`: The consensus vote to process
|
||||
/// - `group_name`: The name of the group the vote is for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `UserAction` indicating what action should be taken
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Stores vote in consensus service
|
||||
/// - Handles immediate state transitions if consensus is reached
|
||||
///
|
||||
/// ## State Transitions:
|
||||
/// When consensus is reached immediately after processing a vote:
|
||||
/// - **Vote YES**: Non-steward transitions to Waiting state to await batch proposals
|
||||
/// - **Vote NO**: Non-steward transitions to Working state immediately
|
||||
/// - **Steward**: Relies on event-driven system for full proposal management
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - Various consensus service errors
|
||||
pub(crate) async fn process_consensus_vote(
|
||||
&mut self,
|
||||
vote: Vote,
|
||||
group_name: &str,
|
||||
) -> Result<UserAction, UserError> {
|
||||
self.consensus_service
|
||||
.process_incoming_vote(group_name, vote.clone())
|
||||
.await?;
|
||||
|
||||
Ok(UserAction::DoNothing)
|
||||
}
|
||||
}
|
||||
184
src/user/groups.rs
Normal file
184
src/user/groups.rs
Normal file
@@ -0,0 +1,184 @@
|
||||
use openmls::{
|
||||
group::MlsGroupJoinConfig,
|
||||
prelude::{StagedWelcome, Welcome},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::info;
|
||||
|
||||
use crate::{error::UserError, group::Group, state_machine::GroupState, user::User};
|
||||
use mls_crypto::identity::normalize_wallet_address;
|
||||
|
||||
impl User {
|
||||
/// Fetch the shared reference to a group by name.
|
||||
pub(crate) async fn group_ref(&self, name: &str) -> Result<Arc<RwLock<Group>>, UserError> {
|
||||
self.groups
|
||||
.read()
|
||||
.await
|
||||
.get(name)
|
||||
.cloned()
|
||||
.ok_or(UserError::GroupNotFoundError)
|
||||
}
|
||||
|
||||
/// Create a new group for this user.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to create
|
||||
/// - `is_creation`: Whether this is a group creation (true) or joining (false)
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - If `is_creation` is true: Creates MLS group with steward capabilities
|
||||
/// - If `is_creation` is false: Creates empty group for later joining
|
||||
/// - Adds group to user's groups map
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupAlreadyExistsError` if group already exists
|
||||
/// - Various MLS group creation errors
|
||||
pub async fn create_group(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
is_creation: bool,
|
||||
) -> Result<(), UserError> {
|
||||
let mut groups = self.groups.write().await;
|
||||
if groups.contains_key(group_name) {
|
||||
return Err(UserError::GroupAlreadyExistsError);
|
||||
}
|
||||
let group = if is_creation {
|
||||
Group::new(
|
||||
group_name,
|
||||
true,
|
||||
Some(&self.provider),
|
||||
Some(self.identity.signer()),
|
||||
Some(&self.identity.credential_with_key()),
|
||||
)?
|
||||
} else {
|
||||
Group::new(group_name, false, None, None, None)?
|
||||
};
|
||||
|
||||
groups.insert(group_name.to_string(), Arc::new(RwLock::new(group)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Join a group after receiving a welcome message.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `welcome`: The MLS welcome message containing group information
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Creates new MLS group from welcome message
|
||||
/// - Sets the MLS group in the user's group instance
|
||||
/// - Updates group state to reflect successful joining
|
||||
///
|
||||
/// ## Preconditions:
|
||||
/// - Group must already exist in user's groups map
|
||||
/// - Welcome message must be valid and contain proper group data
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - Various MLS group creation errors
|
||||
pub(crate) async fn join_group(&mut self, welcome: Welcome) -> Result<(), UserError> {
|
||||
let group_config = MlsGroupJoinConfig::builder().build();
|
||||
let mls_group =
|
||||
StagedWelcome::new_from_welcome(&self.provider, &group_config, welcome, None)?
|
||||
.into_group(&self.provider)?;
|
||||
|
||||
let group_id = mls_group.group_id().to_vec();
|
||||
let group_name = String::from_utf8(group_id)?;
|
||||
|
||||
let group = self.group_ref(&group_name).await?;
|
||||
group.write().await.set_mls_group(mls_group)?;
|
||||
|
||||
info!("[join_group]: User joined group {group_name}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the state of a group.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to get the state of
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `GroupState` of the group
|
||||
pub async fn get_group_state(&self, group_name: &str) -> Result<GroupState, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let state = group.read().await.get_state().await;
|
||||
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
/// Get the number of members in a group.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to get the number of members of
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - The number of members in the group
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
pub async fn get_group_number_of_members(&self, group_name: &str) -> Result<usize, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let members = group.read().await.members_identity().await?;
|
||||
Ok(members.len())
|
||||
}
|
||||
|
||||
/// Retrieve the list of member identities for a group.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: Target group
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Vector of normalized wallet addresses (e.g., `0xabc...`)
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group is missing
|
||||
pub async fn get_group_members(&self, group_name: &str) -> Result<Vec<String>, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
if !group.read().await.is_mls_group_initialized() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let members = group.read().await.members_identity().await?;
|
||||
Ok(members
|
||||
.into_iter()
|
||||
.map(|raw| normalize_wallet_address(raw.as_slice()).to_string())
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Get the MLS epoch of a group.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to get the MLS epoch of
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - The MLS epoch of the group
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
pub async fn get_group_mls_epoch(&self, group_name: &str) -> Result<u64, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let epoch = group.read().await.epoch().await?;
|
||||
Ok(epoch.as_u64())
|
||||
}
|
||||
|
||||
/// Leave a group and clean up associated resources.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to leave
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Removes group from user's groups map
|
||||
/// - Cleans up all group-related resources
|
||||
///
|
||||
/// ## Preconditions:
|
||||
/// - Group must exist in user's groups map
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
pub async fn leave_group(&mut self, group_name: &str) -> Result<(), UserError> {
|
||||
info!("[leave_group]: Leaving group {group_name}");
|
||||
let group = self.group_ref(group_name).await?;
|
||||
self.groups.write().await.remove(group_name);
|
||||
drop(group);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
139
src/user/messaging.rs
Normal file
139
src/user/messaging.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
use alloy::{
|
||||
primitives::Address,
|
||||
signers::{local::PrivateKeySigner, Signer},
|
||||
};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{
|
||||
error::UserError,
|
||||
protos::de_mls::messages::v1::{AppMessage, BanRequest, ProposalAdded},
|
||||
user::{User, UserAction},
|
||||
LocalSigner,
|
||||
};
|
||||
use ds::waku_actor::WakuMessageToSend;
|
||||
use mls_crypto::normalize_wallet_address_str;
|
||||
|
||||
impl User {
|
||||
/// Prepare data to build a waku message for a group.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `app_message`: The application message to send to the group
|
||||
/// - `group_name`: The name of the group to send the message to
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Waku message ready for transmission
|
||||
///
|
||||
/// ## Preconditions:
|
||||
/// - Group must be initialized with MLS group
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Preserves original AppMessage structure without wrapping
|
||||
/// - Builds MLS message through the group
|
||||
///
|
||||
/// ## Usage:
|
||||
/// Used for consensus-related messages like proposals and votes
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - `UserError::MlsGroupNotInitialized` if MLS group not initialized
|
||||
/// - Various MLS message building errors
|
||||
pub async fn build_group_message(
|
||||
&mut self,
|
||||
app_message: AppMessage,
|
||||
group_name: &str,
|
||||
) -> Result<WakuMessageToSend, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
if !group.read().await.is_mls_group_initialized() {
|
||||
return Err(UserError::MlsGroupNotInitialized);
|
||||
}
|
||||
|
||||
let msg_to_send = group
|
||||
.write()
|
||||
.await
|
||||
.build_message(&self.provider, self.identity.signer(), &app_message)
|
||||
.await?;
|
||||
|
||||
Ok(msg_to_send)
|
||||
}
|
||||
|
||||
/// Process incoming ban request.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `ban_request`: The ban request to process
|
||||
/// - `group_name`: The name of the group the ban request is for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Waku message to send to the group
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - **For stewards**: Adds remove proposal to steward queue and sends system message
|
||||
/// - **For regular users**: Forwards ban request to the group
|
||||
///
|
||||
/// ## Message Types:
|
||||
/// - **Steward**: Sends system message about proposal addition
|
||||
/// - **Regular User**: Sends ban request message to group
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - Various message building errors
|
||||
pub async fn process_ban_request(
|
||||
&mut self,
|
||||
ban_request: BanRequest,
|
||||
group_name: &str,
|
||||
) -> Result<UserAction, UserError> {
|
||||
let normalized_user_to_ban = normalize_wallet_address_str(&ban_request.user_to_ban)?;
|
||||
info!("[process_ban_request]: Processing ban request for user {normalized_user_to_ban} in group {group_name}");
|
||||
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let is_steward = group.read().await.is_steward().await;
|
||||
if is_steward {
|
||||
// Steward: add the remove proposal to the queue
|
||||
info!(
|
||||
"[process_ban_request]: Steward adding remove proposal for user {normalized_user_to_ban}"
|
||||
);
|
||||
let request = self
|
||||
.add_remove_proposal(group_name, normalized_user_to_ban.clone())
|
||||
.await?;
|
||||
|
||||
// Send notification to UI about the new proposal
|
||||
let proposal_added_msg: AppMessage = ProposalAdded {
|
||||
group_id: group_name.to_string(),
|
||||
request: request.into(),
|
||||
}
|
||||
.into();
|
||||
|
||||
Ok(UserAction::SendToApp(proposal_added_msg))
|
||||
} else {
|
||||
// Regular user: send the ban request to the group
|
||||
let updated_ban_request = BanRequest {
|
||||
user_to_ban: normalized_user_to_ban,
|
||||
requester: self.identity_string(),
|
||||
group_name: ban_request.group_name,
|
||||
};
|
||||
let msg = self
|
||||
.build_group_message(updated_ban_request.into(), group_name)
|
||||
.await?;
|
||||
Ok(UserAction::SendToWaku(msg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalSigner for PrivateKeySigner {
|
||||
async fn local_sign_message(&self, message: &[u8]) -> Result<Vec<u8>, anyhow::Error> {
|
||||
let signature = self.sign_message(message).await?;
|
||||
let signature_bytes = signature.as_bytes().to_vec();
|
||||
Ok(signature_bytes)
|
||||
}
|
||||
|
||||
fn address(&self) -> Address {
|
||||
self.address()
|
||||
}
|
||||
|
||||
fn address_string(&self) -> String {
|
||||
self.address().to_string()
|
||||
}
|
||||
|
||||
fn address_bytes(&self) -> Vec<u8> {
|
||||
self.address().as_slice().to_vec()
|
||||
}
|
||||
}
|
||||
122
src/user/mod.rs
Normal file
122
src/user/mod.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
pub mod consensus;
|
||||
pub mod groups;
|
||||
pub mod messaging;
|
||||
pub mod proposals;
|
||||
pub mod steward;
|
||||
pub mod waku;
|
||||
|
||||
use alloy::signers::local::PrivateKeySigner;
|
||||
use kameo::Actor;
|
||||
use std::{collections::HashMap, fmt::Display, str::FromStr, sync::Arc};
|
||||
use tokio::sync::{broadcast, RwLock};
|
||||
|
||||
use ds::waku_actor::WakuMessageToSend;
|
||||
use mls_crypto::{
|
||||
identity::Identity,
|
||||
openmls_provider::{MlsProvider, CIPHERSUITE},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
consensus::{ConsensusEvent, ConsensusService},
|
||||
error::UserError,
|
||||
group::Group,
|
||||
protos::de_mls::messages::v1::AppMessage,
|
||||
user::proposals::PendingBatches,
|
||||
};
|
||||
|
||||
/// Represents the action to take after processing a user message or event.
|
||||
///
|
||||
/// This enum defines the possible outcomes when processing user-related operations,
|
||||
/// allowing the caller to determine the appropriate next steps for message handling,
|
||||
/// group management, and network communication.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum UserAction {
|
||||
SendToWaku(WakuMessageToSend),
|
||||
SendToApp(AppMessage),
|
||||
LeaveGroup(String),
|
||||
DoNothing,
|
||||
}
|
||||
|
||||
impl Display for UserAction {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
UserAction::SendToWaku(_) => write!(f, "SendToWaku"),
|
||||
UserAction::SendToApp(_) => write!(f, "SendToApp"),
|
||||
UserAction::LeaveGroup(group_name) => write!(f, "LeaveGroup({group_name})"),
|
||||
UserAction::DoNothing => write!(f, "DoNothing"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a user in the MLS-based messaging system.
|
||||
///
|
||||
/// The User struct manages the lifecycle of multiple groups, handles consensus operations,
|
||||
/// and coordinates communication between the application layer and the Waku network.
|
||||
/// It integrates with the consensus service for proposal management and voting.
|
||||
///
|
||||
/// ## Key Features:
|
||||
/// - Multi-group management and coordination
|
||||
/// - Consensus service integration for proposal handling
|
||||
/// - Waku message processing and routing
|
||||
/// - Steward epoch coordination
|
||||
/// - Member management through proposals
|
||||
#[derive(Actor)]
|
||||
pub struct User {
|
||||
identity: Identity,
|
||||
// Each group has its own lock for better concurrency
|
||||
groups: Arc<RwLock<HashMap<String, Arc<RwLock<Group>>>>>,
|
||||
provider: MlsProvider,
|
||||
consensus_service: ConsensusService,
|
||||
eth_signer: PrivateKeySigner,
|
||||
// Queue for batch proposals that arrive before consensus is reached
|
||||
pending_batch_proposals: PendingBatches,
|
||||
}
|
||||
|
||||
impl User {
|
||||
/// Create a new user instance with the specified Ethereum private key.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `user_eth_priv_key`: The user's Ethereum private key as a hex string
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - New User instance with initialized identity and services
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError` if private key parsing or identity creation fails
|
||||
pub fn new(
|
||||
user_eth_priv_key: &str,
|
||||
consensus_service: &ConsensusService,
|
||||
) -> Result<Self, UserError> {
|
||||
let signer = PrivateKeySigner::from_str(user_eth_priv_key)?;
|
||||
let user_address = signer.address();
|
||||
|
||||
let crypto = MlsProvider::default();
|
||||
let id = Identity::new(CIPHERSUITE, &crypto, user_address.as_slice())?;
|
||||
|
||||
let user = User {
|
||||
groups: Arc::new(RwLock::new(HashMap::new())),
|
||||
identity: id,
|
||||
eth_signer: signer,
|
||||
provider: crypto,
|
||||
consensus_service: consensus_service.clone(),
|
||||
pending_batch_proposals: PendingBatches::default(),
|
||||
};
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
/// Get a subscription to consensus events
|
||||
pub fn subscribe_to_consensus_events(&self) -> broadcast::Receiver<(String, ConsensusEvent)> {
|
||||
self.consensus_service.subscribe_to_events()
|
||||
}
|
||||
|
||||
/// Get the identity string for debugging and identification purposes.
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - String representation of the user's identity
|
||||
///
|
||||
/// ## Usage:
|
||||
/// Primarily used for debugging, logging, and user identification
|
||||
pub fn identity_string(&self) -> String {
|
||||
self.identity.identity_string()
|
||||
}
|
||||
}
|
||||
146
src/user/proposals.rs
Normal file
146
src/user/proposals.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use openmls::prelude::{DeserializeBytes, MlsMessageIn};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{
|
||||
error::UserError,
|
||||
group::GroupAction,
|
||||
protos::de_mls::messages::v1::BatchProposalsMessage,
|
||||
state_machine::GroupState,
|
||||
user::{User, UserAction},
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct PendingBatches {
|
||||
inner: Arc<RwLock<HashMap<String, BatchProposalsMessage>>>,
|
||||
}
|
||||
|
||||
impl PendingBatches {
|
||||
pub(crate) async fn store(&self, group: &str, batch: BatchProposalsMessage) {
|
||||
self.inner.write().await.insert(group.to_string(), batch);
|
||||
}
|
||||
|
||||
pub(crate) async fn take(&self, group: &str) -> Option<BatchProposalsMessage> {
|
||||
self.inner.write().await.remove(group)
|
||||
}
|
||||
|
||||
pub(crate) async fn contains(&self, group: &str) -> bool {
|
||||
self.inner.read().await.contains_key(group)
|
||||
}
|
||||
}
|
||||
|
||||
impl User {
|
||||
/// Process batch proposals message from the steward.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `batch_msg`: The batch proposals message to process
|
||||
/// - `group_name`: The name of the group these proposals are for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `UserAction` indicating what action should be taken
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Processes all MLS proposals in the batch
|
||||
/// - Applies the commit message to complete the group update
|
||||
/// - Transitions group to Working state after successful processing
|
||||
///
|
||||
/// ## State Requirements:
|
||||
/// - Group must be in Waiting state to process batch proposals
|
||||
/// - If not in correct state, stores proposals for later processing
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - Various MLS processing errors
|
||||
pub(crate) async fn process_batch_proposals_message(
|
||||
&mut self,
|
||||
batch_msg: BatchProposalsMessage,
|
||||
group_name: &str,
|
||||
) -> Result<UserAction, UserError> {
|
||||
// Get the group lock
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let initial_state = group.read().await.get_state().await;
|
||||
if initial_state != GroupState::Waiting {
|
||||
info!(
|
||||
"[process_batch_proposals_message]: Cannot process batch proposals in {initial_state} state, storing for later processing"
|
||||
);
|
||||
// Store the batch proposals for later processing
|
||||
self.pending_batch_proposals
|
||||
.store(group_name, batch_msg)
|
||||
.await;
|
||||
return Ok(UserAction::DoNothing);
|
||||
}
|
||||
|
||||
// Process all proposals before the commit
|
||||
for proposal_bytes in batch_msg.mls_proposals {
|
||||
let (mls_message_in, _) = MlsMessageIn::tls_deserialize_bytes(&proposal_bytes)?;
|
||||
let protocol_message = mls_message_in.try_into_protocol_message()?;
|
||||
|
||||
let _res = group
|
||||
.write()
|
||||
.await
|
||||
.process_protocol_msg(protocol_message, &self.provider)
|
||||
.await?;
|
||||
}
|
||||
|
||||
// Then process the commit message
|
||||
let (mls_message_in, _) = MlsMessageIn::tls_deserialize_bytes(&batch_msg.commit_message)?;
|
||||
let protocol_message = mls_message_in.try_into_protocol_message()?;
|
||||
|
||||
let res = group
|
||||
.write()
|
||||
.await
|
||||
.process_protocol_msg(protocol_message, &self.provider)
|
||||
.await?;
|
||||
|
||||
group.write().await.start_working().await;
|
||||
|
||||
match res {
|
||||
GroupAction::GroupAppMsg(msg) => Ok(UserAction::SendToApp(msg)),
|
||||
GroupAction::LeaveGroup => Ok(UserAction::LeaveGroup(group_name.to_string())),
|
||||
GroupAction::DoNothing => Ok(UserAction::DoNothing),
|
||||
GroupAction::GroupProposal(proposal) => {
|
||||
self.process_consensus_proposal(proposal, group_name).await
|
||||
}
|
||||
GroupAction::GroupVote(vote) => self.process_consensus_vote(vote, group_name).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to process a batch proposals message that was deferred earlier.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group whose stored batch should be retried
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `Some(UserAction)` if a stored batch was processed, `None` otherwise
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Checks for a cached `BatchProposalsMessage` and processes it immediately if present
|
||||
/// - Removes the stored batch once processing succeeds
|
||||
///
|
||||
/// ## Usage:
|
||||
/// Call after transitioning into `Waiting` so any deferred steward batch can be replayed.
|
||||
pub(crate) async fn process_stored_batch_proposals(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
) -> Result<Option<UserAction>, UserError> {
|
||||
if self.pending_batch_proposals.contains(group_name).await {
|
||||
if let Some(batch_msg) = self.pending_batch_proposals.take(group_name).await {
|
||||
info!(
|
||||
"[process_stored_batch_proposals]: Processing stored batch proposals for group {}",
|
||||
group_name
|
||||
);
|
||||
let action = self
|
||||
.process_batch_proposals_message(batch_msg, group_name)
|
||||
.await?;
|
||||
Ok(Some(action))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
279
src/user/steward.rs
Normal file
279
src/user/steward.rs
Normal file
@@ -0,0 +1,279 @@
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::{
|
||||
error::UserError,
|
||||
protos::{
|
||||
consensus::v1::{UpdateRequest, VotePayload},
|
||||
de_mls::messages::v1::AppMessage,
|
||||
},
|
||||
user::{User, UserAction},
|
||||
};
|
||||
use ds::waku_actor::WakuMessageToSend;
|
||||
|
||||
impl User {
|
||||
/// Check if the user is a steward for the given group.
|
||||
/// ## Returns:
|
||||
/// - Serialized `UiUpdateRequest` representing the removal request for UI consumption
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to check
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `true` if the user is a steward for the group, `false` otherwise
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if the group does not exist
|
||||
pub async fn is_user_steward_for_group(&self, group_name: &str) -> Result<bool, UserError> {
|
||||
let group = {
|
||||
let groups = self.groups.read().await;
|
||||
groups
|
||||
.get(group_name)
|
||||
.cloned()
|
||||
.ok_or_else(|| UserError::GroupNotFoundError)?
|
||||
};
|
||||
let is_steward = group.read().await.is_steward().await;
|
||||
Ok(is_steward)
|
||||
}
|
||||
|
||||
/// Check if the MLS group is initialized for the given group.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to check
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `true` if the MLS group is initialized for the group, `false` otherwise
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if the group does not exist
|
||||
pub async fn is_user_mls_group_initialized_for_group(
|
||||
&self,
|
||||
group_name: &str,
|
||||
) -> Result<bool, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let is_initialized = group.read().await.is_mls_group_initialized();
|
||||
Ok(is_initialized)
|
||||
}
|
||||
|
||||
/// Get the current epoch proposals for the given group.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to get the proposals for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - A vector of `GroupUpdateRequest` representing the current epoch proposals
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if the group does not exist
|
||||
pub async fn get_current_epoch_proposals(
|
||||
&self,
|
||||
group_name: &str,
|
||||
) -> Result<Vec<crate::steward::GroupUpdateRequest>, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let proposals = group.read().await.get_current_epoch_proposals().await;
|
||||
Ok(proposals)
|
||||
}
|
||||
|
||||
/// Prepare a steward announcement message for a group.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to prepare the message for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Waku message containing the steward announcement
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - `GroupError::StewardNotSet` if no steward is configured
|
||||
pub async fn prepare_steward_msg(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
) -> Result<WakuMessageToSend, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let msg_to_send = group.write().await.generate_steward_message().await?;
|
||||
Ok(msg_to_send)
|
||||
}
|
||||
|
||||
/// Start a new steward epoch for the given group. It includes validation of the current state
|
||||
/// and the number of proposals. If there are no proposals, it will stay in the Working state and return 0.
|
||||
/// If there are proposals, it will change the state to Waiting and return the number of proposals.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to start steward epoch for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Number of proposals that will be voted on (0 if no proposals)
|
||||
///
|
||||
/// ## State Transitions:
|
||||
/// - **With proposals**: Working → Waiting (returns proposal count)
|
||||
/// - **No proposals**: Working → Working (stays in Working, returns 0)
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - `GroupError::InvalidStateTransition` if the group is not in the Working state
|
||||
/// - `GroupError::StewardNotSet` if no steward is configured
|
||||
pub async fn start_steward_epoch(&mut self, group_name: &str) -> Result<usize, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let proposal_count = group
|
||||
.write()
|
||||
.await
|
||||
.start_steward_epoch_with_validation()
|
||||
.await?;
|
||||
|
||||
if proposal_count == 0 {
|
||||
info!("[start_steward_epoch]: No proposals to vote on, skipping steward epoch");
|
||||
} else {
|
||||
info!("[start_steward_epoch]: Started steward epoch with {proposal_count} proposals");
|
||||
}
|
||||
|
||||
Ok(proposal_count)
|
||||
}
|
||||
/// Start voting for the given group, returning the proposal ID.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to start voting for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Tuple of (proposal_id, UserAction) for steward actions
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Starts voting phase in the group
|
||||
/// - Creates consensus proposal for voting
|
||||
/// - Sends voting proposal to frontend
|
||||
///
|
||||
/// ## State Transitions:
|
||||
/// - **Waiting → Voting**: If proposals found and steward starts voting
|
||||
/// - **Waiting → Working**: If no proposals found (edge case fix)
|
||||
///
|
||||
/// ## Edge Case Handling:
|
||||
/// If no proposals are found during voting phase (rare edge case where proposals
|
||||
/// disappear between epoch start and voting), transitions back to Working state
|
||||
/// to prevent getting stuck in Waiting state.
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - `UserError::NoProposalsFound` if no proposals exist
|
||||
/// - `ConsensusError::SystemTimeError` if the system time creation fails
|
||||
pub async fn get_proposals_for_steward_voting(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
) -> Result<(u32, UserAction), UserError> {
|
||||
info!(
|
||||
"[get_proposals_for_steward_voting]: Getting proposals for steward voting in group {group_name}"
|
||||
);
|
||||
|
||||
let group = self.group_ref(group_name).await?;
|
||||
|
||||
// If this is the steward, create proposal with vote and send to group
|
||||
if group.read().await.is_steward().await {
|
||||
let proposals = group
|
||||
.read()
|
||||
.await
|
||||
.get_proposals_for_voting_epoch_as_ui_update_requests()
|
||||
.await;
|
||||
if !proposals.is_empty() {
|
||||
group.write().await.start_voting().await?;
|
||||
|
||||
// Get group members for expected voters count
|
||||
let members = group.read().await.members_identity().await?;
|
||||
let participant_ids: Vec<Vec<u8>> = members.into_iter().collect();
|
||||
let expected_voters_count = participant_ids.len() as u32;
|
||||
|
||||
// Create consensus proposal
|
||||
let proposal = self
|
||||
.consensus_service
|
||||
.create_proposal(
|
||||
group_name,
|
||||
uuid::Uuid::new_v4().to_string(),
|
||||
proposals.clone(),
|
||||
self.identity.identity_string().into(),
|
||||
expected_voters_count,
|
||||
3600, // 1 hour expiration
|
||||
true, // liveness criteria
|
||||
)
|
||||
.await?;
|
||||
|
||||
info!(
|
||||
"[get_proposals_for_steward_voting]: Created consensus proposal with ID {} and {} expected voters",
|
||||
proposal.proposal_id, expected_voters_count
|
||||
);
|
||||
|
||||
// Send voting proposal to frontend
|
||||
let voting_proposal: AppMessage = VotePayload {
|
||||
group_id: group_name.to_string(),
|
||||
proposal_id: proposal.proposal_id,
|
||||
group_requests: proposal.group_requests.clone(),
|
||||
timestamp: proposal.timestamp,
|
||||
}
|
||||
.into();
|
||||
|
||||
Ok((proposal.proposal_id, UserAction::SendToApp(voting_proposal)))
|
||||
} else {
|
||||
error!("[get_proposals_for_steward_voting]: No proposals found");
|
||||
Err(UserError::NoProposalsFound)
|
||||
}
|
||||
} else {
|
||||
// Not steward, do nothing
|
||||
info!("[get_proposals_for_steward_voting]: Not steward, doing nothing");
|
||||
Ok((0, UserAction::DoNothing))
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a remove proposal into the `steward::current_epoch_proposals` vector for the given group.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to add the proposal to
|
||||
/// - `identity`: The identity string of the member to remove
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - `GroupError::InvalidIdentity` if the identity is invalid
|
||||
pub async fn add_remove_proposal(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
identity: String,
|
||||
) -> Result<UpdateRequest, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let request = group.write().await.store_remove_proposal(identity).await?;
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
/// Apply proposals for the given group, returning the batch message(s).
|
||||
/// - Creates MLS proposals for all pending group updates
|
||||
/// - Commits all proposals to the MLS group
|
||||
/// - Generates batch proposals message and welcome message if needed
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `group_name`: The name of the group to apply proposals for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - Vector of Waku messages containing batch proposals and welcome messages
|
||||
///
|
||||
/// ## Preconditions:
|
||||
/// - Group must be initialized with MLS group
|
||||
/// - User must be steward for the group
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - `UserError::MlsGroupNotInitialized` if MLS group not initialized
|
||||
/// - `GroupError::StewardNotSet` if no steward is configured
|
||||
/// - `GroupError::EmptyProposals` if no proposals exist
|
||||
/// - `GroupError::InvalidStateTransition` if the group is not in the Waiting state
|
||||
pub async fn apply_proposals(
|
||||
&mut self,
|
||||
group_name: &str,
|
||||
) -> Result<Vec<WakuMessageToSend>, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
|
||||
if !group.read().await.is_mls_group_initialized() {
|
||||
return Err(UserError::MlsGroupNotInitialized);
|
||||
}
|
||||
|
||||
let messages = group
|
||||
.write()
|
||||
.await
|
||||
.create_batch_proposals_message(&self.provider, self.identity.signer())
|
||||
.await?;
|
||||
info!("[apply_proposals]: Applied proposals for group {group_name}");
|
||||
Ok(messages)
|
||||
}
|
||||
}
|
||||
304
src/user/waku.rs
Normal file
304
src/user/waku.rs
Normal file
@@ -0,0 +1,304 @@
|
||||
use openmls::prelude::{DeserializeBytes, MlsMessageBodyIn, MlsMessageIn};
|
||||
use prost::Message;
|
||||
use tracing::{debug, error, info};
|
||||
use waku_bindings::WakuMessage;
|
||||
|
||||
use ds::waku_actor::WakuMessageToSend;
|
||||
use ds::{APP_MSG_SUBTOPIC, WELCOME_SUBTOPIC};
|
||||
|
||||
use crate::error::UserError;
|
||||
use crate::group::GroupAction;
|
||||
use crate::message::MessageType;
|
||||
use crate::protos::de_mls::messages::v1::{
|
||||
app_message, welcome_message, AppMessage, ConversationMessage, ProposalAdded, UserKeyPackage,
|
||||
WelcomeMessage,
|
||||
};
|
||||
use crate::user::{User, UserAction};
|
||||
|
||||
impl User {
|
||||
/// Process messages from the welcome subtopic.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `msg`: The Waku message to process
|
||||
/// - `group_name`: The name of the group this message is for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `UserAction` indicating what action should be taken
|
||||
///
|
||||
/// ## Message Types Handled:
|
||||
/// - **GroupAnnouncement**: Steward announcements for group joining
|
||||
/// - **UserKeyPackage**: Encrypted key packages from new members
|
||||
/// - **InvitationToJoin**: MLS welcome messages for group joining
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - For group announcements: Generates and sends key package
|
||||
/// - For user key packages: Decrypts and stores invite proposals (steward only)
|
||||
/// - For invitations: Processes MLS welcome and joins group
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - `UserError::MessageVerificationFailed` if announcement verification fails
|
||||
/// - Various MLS and encryption errors
|
||||
pub async fn process_welcome_subtopic(
|
||||
&mut self,
|
||||
msg: WakuMessage,
|
||||
group_name: &str,
|
||||
) -> Result<UserAction, UserError> {
|
||||
// Get the group lock first
|
||||
let group = self.group_ref(group_name).await?;
|
||||
|
||||
let is_steward = {
|
||||
let group = group.read().await;
|
||||
group.is_steward().await
|
||||
};
|
||||
let is_kp_shared = {
|
||||
let group = group.read().await;
|
||||
group.is_kp_shared()
|
||||
};
|
||||
let is_mls_group_initialized = {
|
||||
let group = group.read().await;
|
||||
group.is_mls_group_initialized()
|
||||
};
|
||||
|
||||
let received_msg = WelcomeMessage::decode(msg.payload())?;
|
||||
if let Some(payload) = &received_msg.payload {
|
||||
match payload {
|
||||
welcome_message::Payload::GroupAnnouncement(group_announcement) => {
|
||||
if is_steward || is_kp_shared {
|
||||
Ok(UserAction::DoNothing)
|
||||
} else {
|
||||
info!(
|
||||
"[process_welcome_subtopic]: User received group announcement msg for group {group_name}"
|
||||
);
|
||||
if !group_announcement.verify()? {
|
||||
return Err(UserError::MessageVerificationFailed);
|
||||
}
|
||||
|
||||
let new_kp = self.identity.generate_key_package(&self.provider)?;
|
||||
let encrypted_key_package = group_announcement.encrypt(new_kp)?;
|
||||
group.write().await.set_kp_shared(true);
|
||||
|
||||
let welcome_msg: WelcomeMessage = UserKeyPackage {
|
||||
encrypt_kp: encrypted_key_package,
|
||||
}
|
||||
.into();
|
||||
Ok(UserAction::SendToWaku(WakuMessageToSend::new(
|
||||
welcome_msg.encode_to_vec(),
|
||||
WELCOME_SUBTOPIC,
|
||||
group_name,
|
||||
group.read().await.app_id(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
welcome_message::Payload::UserKeyPackage(user_key_package) => {
|
||||
if is_steward {
|
||||
info!(
|
||||
"[process_welcome_subtopic]: Steward received key package for the group {group_name}"
|
||||
);
|
||||
let key_package = group
|
||||
.write()
|
||||
.await
|
||||
.decrypt_steward_msg(user_key_package.encrypt_kp.clone())
|
||||
.await?;
|
||||
|
||||
let request = group
|
||||
.write()
|
||||
.await
|
||||
.store_invite_proposal(Box::new(key_package))
|
||||
.await?;
|
||||
|
||||
// Send notification to UI about the new proposal
|
||||
let proposal_added_msg: AppMessage = ProposalAdded {
|
||||
group_id: group_name.to_string(),
|
||||
request: Some(request),
|
||||
}
|
||||
.into();
|
||||
|
||||
Ok(UserAction::SendToApp(proposal_added_msg))
|
||||
} else {
|
||||
Ok(UserAction::DoNothing)
|
||||
}
|
||||
}
|
||||
welcome_message::Payload::InvitationToJoin(invitation_to_join) => {
|
||||
if is_steward || is_mls_group_initialized {
|
||||
Ok(UserAction::DoNothing)
|
||||
} else {
|
||||
// Release the lock before calling join_group
|
||||
drop(group);
|
||||
|
||||
// Parse the MLS message to get the welcome
|
||||
let (mls_in, _) = MlsMessageIn::tls_deserialize_bytes(
|
||||
&invitation_to_join.mls_message_out_bytes,
|
||||
)?;
|
||||
|
||||
let welcome = match mls_in.extract() {
|
||||
MlsMessageBodyIn::Welcome(welcome) => welcome,
|
||||
_ => return Err(UserError::FailedToExtractWelcomeMessage),
|
||||
};
|
||||
|
||||
if welcome.secrets().iter().any(|egs| {
|
||||
let hash_ref = egs.new_member().as_slice().to_vec();
|
||||
self.identity.is_key_package_exists(&hash_ref)
|
||||
}) {
|
||||
self.join_group(welcome).await?;
|
||||
let app_msg = ConversationMessage {
|
||||
message: format!(
|
||||
"User {} joined to the group",
|
||||
self.identity.identity_string()
|
||||
)
|
||||
.as_bytes()
|
||||
.to_vec(),
|
||||
sender: "SYSTEM".to_string(),
|
||||
group_name: group_name.to_string(),
|
||||
}
|
||||
.into();
|
||||
let msg = self.build_group_message(app_msg, group_name).await?;
|
||||
Ok(UserAction::SendToWaku(msg))
|
||||
} else {
|
||||
Ok(UserAction::DoNothing)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Err(UserError::EmptyWelcomeMessageError)
|
||||
}
|
||||
}
|
||||
|
||||
/// Process messages from the application message subtopic.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `msg`: The Waku message to process
|
||||
/// - `group_name`: The name of the group this message is for
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `UserAction` indicating what action should be taken
|
||||
///
|
||||
/// ## Message Types Handled:
|
||||
/// - **BatchProposalsMessage**: Batch proposals from steward
|
||||
/// - **MLS Protocol Messages**: Encrypted group messages
|
||||
/// - **Application Messages**: Various app-level messages
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Processes batch proposals and applies them to the group
|
||||
/// - Handles MLS protocol messages through the group
|
||||
/// - Routes consensus proposals and votes to appropriate handlers
|
||||
///
|
||||
/// ## Preconditions:
|
||||
/// - Group must be initialized with MLS group
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - Various MLS processing errors
|
||||
pub async fn process_app_subtopic(
|
||||
&mut self,
|
||||
msg: WakuMessage,
|
||||
group_name: &str,
|
||||
) -> Result<UserAction, UserError> {
|
||||
let group = self.group_ref(group_name).await?;
|
||||
|
||||
if !group.read().await.is_mls_group_initialized() {
|
||||
return Ok(UserAction::DoNothing);
|
||||
}
|
||||
|
||||
// Try to parse as AppMessage first
|
||||
// This one required for commit messages as they are sent as AppMessage
|
||||
// without group encryption
|
||||
if let Ok(app_message) = AppMessage::decode(msg.payload()) {
|
||||
match app_message.payload {
|
||||
Some(app_message::Payload::BatchProposalsMessage(batch_msg)) => {
|
||||
info!(
|
||||
"[process_app_subtopic]: Processing batch proposals message for group {group_name}"
|
||||
);
|
||||
// Release the lock before calling self methods
|
||||
return self
|
||||
.process_batch_proposals_message(batch_msg, group_name)
|
||||
.await;
|
||||
}
|
||||
_ => {
|
||||
error!(
|
||||
"[process_app_subtopic]: Cannot process another app message here: {:?}",
|
||||
app_message.payload.unwrap().message_type()
|
||||
);
|
||||
return Err(UserError::InvalidAppMessageType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to MLS protocol message
|
||||
let (mls_message_in, _) = MlsMessageIn::tls_deserialize_bytes(msg.payload())?;
|
||||
let mls_message = mls_message_in.try_into_protocol_message()?;
|
||||
|
||||
let group = self.group_ref(group_name).await?;
|
||||
let res = group
|
||||
.write()
|
||||
.await
|
||||
.process_protocol_msg(mls_message, &self.provider)
|
||||
.await?;
|
||||
|
||||
// Handle the result outside of any lock scope
|
||||
match res {
|
||||
GroupAction::GroupAppMsg(msg) => {
|
||||
info!("[process_app_subtopic]: sending to app");
|
||||
Ok(UserAction::SendToApp(msg))
|
||||
}
|
||||
GroupAction::LeaveGroup => {
|
||||
info!("[process_app_subtopic]: leaving group");
|
||||
Ok(UserAction::LeaveGroup(group_name.to_string()))
|
||||
}
|
||||
GroupAction::DoNothing => {
|
||||
info!("[process_app_subtopic]: doing nothing");
|
||||
Ok(UserAction::DoNothing)
|
||||
}
|
||||
GroupAction::GroupProposal(proposal) => {
|
||||
info!("[process_app_subtopic]: processing consensus proposal");
|
||||
self.process_consensus_proposal(proposal, group_name).await
|
||||
}
|
||||
GroupAction::GroupVote(vote) => {
|
||||
info!("[process_app_subtopic]: processing consensus vote");
|
||||
self.process_consensus_vote(vote, group_name).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Process incoming Waku messages and route them to appropriate handlers.
|
||||
///
|
||||
/// ## Parameters:
|
||||
/// - `msg`: The Waku message to process
|
||||
///
|
||||
/// ## Returns:
|
||||
/// - `UserAction` indicating what action should be taken
|
||||
///
|
||||
/// ## Message Routing:
|
||||
/// - **Welcome Subtopic**: Routes to `process_welcome_subtopic()`
|
||||
/// - **App Message Subtopic**: Routes to `process_app_subtopic()`
|
||||
/// - **Unknown Topics**: Returns error
|
||||
///
|
||||
/// ## Effects:
|
||||
/// - Processes messages based on content topic
|
||||
/// - Skips messages from the same app instance
|
||||
/// - Routes to appropriate subtopic handlers
|
||||
///
|
||||
/// ## Errors:
|
||||
/// - `UserError::GroupNotFoundError` if group doesn't exist
|
||||
/// - `UserError::UnknownContentTopicType` for unsupported topics
|
||||
/// - Various processing errors from subtopic handlers
|
||||
pub async fn process_waku_message(
|
||||
&mut self,
|
||||
msg: WakuMessage,
|
||||
) -> Result<UserAction, UserError> {
|
||||
let group_name = msg.content_topic.application_name.to_string();
|
||||
let group = self.group_ref(&group_name).await?;
|
||||
if msg.meta == group.read().await.app_id() {
|
||||
debug!("[process_waku_message]: Message is from the same app, skipping");
|
||||
return Ok(UserAction::DoNothing);
|
||||
}
|
||||
|
||||
let ct_name = msg.content_topic.content_topic_name.to_string();
|
||||
match ct_name.as_str() {
|
||||
WELCOME_SUBTOPIC => self.process_welcome_subtopic(msg, &group_name).await,
|
||||
APP_MSG_SUBTOPIC => self.process_app_subtopic(msg, &group_name).await,
|
||||
_ => Err(UserError::UnknownContentTopicType(ct_name)),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user