Compare commits
127 Commits
main
...
working-ch
Author | SHA1 | Date | |
---|---|---|---|
dc76e2126f | |||
40f8a6ec20 | |||
4582807822 | |||
ea3fe8b863 | |||
f25c6f27de | |||
a99f41f50e | |||
99c548c755 | |||
4c558589d0 | |||
544e8989c6 | |||
8d2c34b13b | |||
bac3e68400 | |||
d9d2bcd9d0 | |||
f0c52f6597 | |||
14c2174897 | |||
7775e3bd3c | |||
908155c939 | |||
8759efb582 | |||
feeaedc917 | |||
c0adce2b31 | |||
e92384fc93 | |||
d99d4f0067 | |||
9dc7e62f8f | |||
04b467cc97 | |||
060f1689af | |||
bdf75a6114 | |||
b2f7f68726 | |||
089b59136d | |||
4232f9aa62 | |||
cd48128255 | |||
8e0e7d0128 | |||
6d82333a49 | |||
7d0aa89387 | |||
3dab6ef2d6 | |||
9896532713 | |||
49637d9b40 | |||
![]() |
de5eb1b8cd | ||
![]() |
4c49cf1596 | ||
![]() |
ee777bbcbc | ||
![]() |
d54981f66e | ||
![]() |
76ce2c0672 | ||
![]() |
cc8d64f6ce | ||
![]() |
f899719cc1 | ||
![]() |
40dbc1b2ba | ||
![]() |
a919c6d83d | ||
![]() |
1106d25ea1 | ||
![]() |
92f4d62c88 | ||
![]() |
f789b30372 | ||
![]() |
166c7c993f | ||
![]() |
2afc6c9a85 | ||
![]() |
0c702de953 | ||
![]() |
3ed94c7538 | ||
![]() |
1bf8d91991 | ||
![]() |
8f089fd3db | ||
![]() |
af51c93087 | ||
![]() |
8a8eaec4fd | ||
![]() |
4362012fcb | ||
![]() |
bb1e5afb2f | ||
![]() |
1d5869561a | ||
![]() |
544c3256d6 | ||
![]() |
f95b6473e5 | ||
![]() |
ed7c5e5b0c | ||
![]() |
041cf55f58 | ||
![]() |
e90473d8be | ||
![]() |
ad632e40ce | ||
![]() |
ff47da3083 | ||
![]() |
0aa0c6817a | ||
![]() |
6350b29379 | ||
![]() |
5c77ae1b4f | ||
![]() |
d6f2202627 | ||
![]() |
359312574f | ||
![]() |
0d522182d6 | ||
![]() |
93ae65ece7 | ||
![]() |
2463b8f05b | ||
![]() |
494270b636 | ||
![]() |
124718a207 | ||
![]() |
30d7ddcf1a | ||
![]() |
e9421f2e04 | ||
![]() |
bfa60aa023 | ||
![]() |
0a81ce12df | ||
![]() |
7ba532cebe | ||
![]() |
2910125bd1 | ||
![]() |
56cadb71f6 | ||
078d2a0420 | |||
87113f5a34 | |||
3372bcb1ed | |||
d7cd98ffe8 | |||
4d04e50a65 | |||
![]() |
8b65463cd3 | ||
![]() |
caf620dd65 | ||
![]() |
43b4c5f4d2 | ||
![]() |
d121e8f7b2 | ||
![]() |
0c5ddefc4b | ||
![]() |
4b8d5c3611 | ||
![]() |
8ca4023d21 | ||
![]() |
cae49617d5 | ||
![]() |
7c9eecab7a | ||
![]() |
a592001fdb | ||
![]() |
6566f4c192 | ||
![]() |
4bd1393306 | ||
![]() |
0dc14dee4a | ||
![]() |
589e8d1d1d | ||
![]() |
836f6cf900 | ||
![]() |
1871dc9a5d | ||
![]() |
56558703c3 | ||
![]() |
b904f4ec81 | ||
![]() |
b7bffe7678 | ||
![]() |
cf3278dd3d | ||
![]() |
287f74136e | ||
![]() |
45628edb61 | ||
![]() |
d073b12340 | ||
![]() |
361a8aa409 | ||
![]() |
b2cab53188 | ||
![]() |
ec47592581 | ||
![]() |
08aea30e2b | ||
![]() |
52382c96a1 | ||
![]() |
9ce3918ff5 | ||
![]() |
d82e145f50 | ||
![]() |
30759027b0 | ||
![]() |
d737242bb5 | ||
![]() |
6f74996f39 | ||
![]() |
1e79dfd7f6 | ||
![]() |
28d4ad8d50 | ||
![]() |
42a7848025 | ||
![]() |
9adafc1212 | ||
![]() |
980bd390c6 | ||
![]() |
733d65b99b | ||
f899ee1369 |
3
.gitignore
vendored
3
.gitignore
vendored
@ -1,6 +1,3 @@
|
||||
target/
|
||||
pkg/
|
||||
Cargo.lock
|
||||
node_modules/
|
||||
dist/
|
||||
.vscode
|
29
Cargo.toml
29
Cargo.toml
@ -1,5 +1,24 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"crates/sp_client"
|
||||
]
|
||||
[package]
|
||||
name = "sdk_client"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "sdk_client"
|
||||
crate-type = ["lib", "cdylib"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
serde = { version = "1.0.188", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
wasm-bindgen = "0.2.91"
|
||||
getrandom = { version="0.2.12", features = ["js"] }
|
||||
wasm-logger = "0.2.0"
|
||||
rand = "0.8.5"
|
||||
tsify = { git = "https://github.com/Sosthene00/tsify", branch = "next" }
|
||||
# sdk_common = { path = "../sdk_common" }
|
||||
sdk_common = { git = "https://git.4nkweb.com/4nk/sdk_common.git", branch = "dev" }
|
||||
serde-wasm-bindgen = "0.6.5"
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen-test = "0.3"
|
||||
|
93
README.md
93
README.md
@ -1,93 +0,0 @@
|
||||
# sdk_client
|
||||
|
||||
|
||||
|
||||
## Getting started
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
|
||||
## Add your files
|
||||
|
||||
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin https://git.4nkweb.com/4nk/sdk_client.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
|
||||
- [ ] [Set up project integrations](https://git.4nkweb.com/4nk/sdk_client/-/settings/integrations)
|
||||
|
||||
## Collaborate with your team
|
||||
|
||||
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
||||
|
||||
## Test and Deploy
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
|
||||
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
||||
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||
|
||||
***
|
||||
|
||||
# Editing this README
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
|
||||
## Suggestions for a good README
|
||||
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
@ -1,27 +0,0 @@
|
||||
[package]
|
||||
name = "sdk_client"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "sdk_client"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
serde = { version = "1.0.188", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
wasm-bindgen = "0.2.91"
|
||||
getrandom = { version="0.2.12", features = ["js"] }
|
||||
wasm-logger = "0.2.0"
|
||||
rand = "0.8.5"
|
||||
log = "0.4.6"
|
||||
tsify = { git = "https://github.com/Sosthene00/tsify", branch = "next" }
|
||||
# sdk_common = { path = "../../../sdk_common" }
|
||||
# sdk_common = { git = "https://git.4nkweb.com/4nk/sdk_common.git", branch = "demo" }
|
||||
sdk_common = { git = "https://git.4nkweb.com/4nk/sdk_common.git", branch = "dev" }
|
||||
shamir = { git = "https://github.com/Sosthene00/shamir", branch = "master" }
|
||||
img-parts = "0.3.0"
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen-test = "0.3"
|
File diff suppressed because it is too large
Load Diff
@ -1,38 +0,0 @@
|
||||
use anyhow::{Error, Result};
|
||||
use img_parts::{jpeg::Jpeg, Bytes, ImageEXIF};
|
||||
use sdk_common::sp_client::bitcoin::secp256k1::SecretKey;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BackUpImage(Vec<u8>);
|
||||
|
||||
impl BackUpImage {
|
||||
pub fn new_recover(image: Vec<u8>, data: &[u8]) -> Result<Self> {
|
||||
// TODO: sanity check on data
|
||||
let img = write_exif(image, data)?;
|
||||
Ok(Self(img))
|
||||
}
|
||||
|
||||
pub fn new_revoke(image: Vec<u8>, data: &[u8]) -> Result<Self> {
|
||||
// TODO: sanity check on data
|
||||
let img = write_exif(image, data)?;
|
||||
Ok(Self(img))
|
||||
}
|
||||
|
||||
pub fn to_inner(&self) -> Vec<u8> {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
pub fn as_inner(&self) -> &[u8] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
fn write_exif(image: Vec<u8>, data: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut jpeg = Jpeg::from_bytes(Bytes::from(image))?;
|
||||
let data_bytes = Bytes::from(data.to_owned());
|
||||
jpeg.set_exif(Some(data_bytes));
|
||||
let output_image_bytes = jpeg.encoder().bytes();
|
||||
let output_image = output_image_bytes.to_vec();
|
||||
Ok(output_image)
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
#![allow(warnings)]
|
||||
use anyhow::Error;
|
||||
use sdk_common::crypto::AnkSharedSecret;
|
||||
use sdk_common::network::CachedMessage;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt::Debug;
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
use tsify::Tsify;
|
||||
|
||||
pub mod api;
|
||||
mod images;
|
||||
mod peers;
|
||||
mod process;
|
||||
mod user;
|
||||
|
||||
pub static CACHEDMESSAGES: OnceLock<Mutex<Vec<CachedMessage>>> = OnceLock::new();
|
||||
|
||||
pub fn lock_messages() -> Result<MutexGuard<'static, Vec<CachedMessage>>, Error> {
|
||||
CACHEDMESSAGES
|
||||
.get_or_init(|| Mutex::new(vec![]))
|
||||
.lock_anyhow()
|
||||
}
|
||||
|
||||
pub(crate) trait MutexExt<T> {
|
||||
fn lock_anyhow(&self) -> Result<MutexGuard<T>, Error>;
|
||||
}
|
||||
|
||||
impl<T: Debug> MutexExt<T> for Mutex<T> {
|
||||
fn lock_anyhow(&self) -> Result<MutexGuard<T>, Error> {
|
||||
self.lock()
|
||||
.map_err(|e| Error::msg(format!("Failed to lock: {}", e)))
|
||||
}
|
||||
}
|
@ -1,405 +0,0 @@
|
||||
use std::fmt::DebugStruct;
|
||||
|
||||
use sdk_common::sp_client::silentpayments::sending::SilentPaymentAddress;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use tsify::Tsify;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
pub const HTML_KOTPART: &str = "
|
||||
<div class='card'>
|
||||
<div class='side-by-side'>
|
||||
<h3>Send encrypted messages</h3>
|
||||
<div>
|
||||
<a href='#' id='send messages'>Send Messages</a>
|
||||
</div>
|
||||
</div>
|
||||
<form id='form4nk' action='#'>
|
||||
<label for='sp_address'>Send to:</label>
|
||||
<input type='text' id='sp_address' />
|
||||
<hr/>
|
||||
<label for='message'>Message:</label>
|
||||
<input type='message' id='message' />
|
||||
<hr/>
|
||||
<button type='submit' id='submitButton' class='recover bg-primary'>Send</button>
|
||||
</form>
|
||||
</div>
|
||||
";
|
||||
|
||||
pub const HTML_STORAGE: &str = "
|
||||
<div class='card'>
|
||||
<div class='side-by-side'>
|
||||
<h3>Send encrypted messages</h3>
|
||||
<div>
|
||||
<a href='#' id='send messages'>Send Messages</a>
|
||||
</div>
|
||||
</div>
|
||||
<form id='form4nk' action='#'>
|
||||
<label for='sp_address'>Send to:</label>
|
||||
<input type='text' id='sp_address' />
|
||||
<hr/>
|
||||
<label for='message'>Message:</label>
|
||||
<input type='message' id='message' />
|
||||
<hr/>
|
||||
<button type='submit' id='submitButton' class='recover bg-primary'>Send</button>
|
||||
</form>
|
||||
</div>
|
||||
";
|
||||
|
||||
pub const HTML_MESSAGING: &str = "
|
||||
<div class='card'>
|
||||
<div class='side-by-side'>
|
||||
<h3>Send encrypted messages</h3>
|
||||
<div>
|
||||
<a href='#' id='send messages'>Send Messages</a>
|
||||
</div>
|
||||
</div>
|
||||
<form id='form4nk' action='#'>
|
||||
<div id='our_address' class='our_address'></div>
|
||||
<label for='sp_address'>Send to:</label>
|
||||
<input type='text' id='sp_address' />
|
||||
<hr/>
|
||||
<label for='message'>Message:</label>
|
||||
<input type='message' id='message' />
|
||||
<hr/>
|
||||
<button type='submit' id='submitButton' class='recover bg-primary'>Send</button>
|
||||
</form>
|
||||
</div>
|
||||
";
|
||||
|
||||
pub const CSS: &str = "
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
background-color: #f4f4f4;
|
||||
font-family: 'Arial', sans-serif;
|
||||
}
|
||||
.container {
|
||||
text-align: center;
|
||||
}
|
||||
.card {
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
padding: 20px;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
background-color: #ffffff;
|
||||
border-radius: 8px;
|
||||
text-align: left;
|
||||
overflow: hidden;
|
||||
}
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
/* flex-wrap: wrap; */
|
||||
}
|
||||
label {
|
||||
font-weight: bold;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
hr {
|
||||
border: 0;
|
||||
height: 1px;
|
||||
background-color: #ddd;
|
||||
margin: 10px 0;
|
||||
}
|
||||
input, select {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
margin: 8px 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
select {
|
||||
padding: 10px;
|
||||
background-color: #f9f9f9;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
button {
|
||||
display: inline-block;
|
||||
background-color: #4caf50;
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 12px 17px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #45a049;
|
||||
}
|
||||
.side-by-side {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.side-by-side>* {
|
||||
display: inline-block;
|
||||
}
|
||||
button.recover {
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
background-color: #4caf50;
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 12px 17px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.recover:hover {
|
||||
background-color: #45a049;
|
||||
}
|
||||
a.btn {
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
background-color: #4caf50;
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 12px 17px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
a.btn:hover {
|
||||
background-color: #45a049;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #78a6de;
|
||||
}
|
||||
.bg-secondary {
|
||||
background-color: #2b81ed;
|
||||
}
|
||||
.bg-primary {
|
||||
background-color: #1A61ED;
|
||||
}
|
||||
.bg-primary:hover {
|
||||
background-color: #457be8;
|
||||
}
|
||||
.card-revoke {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
padding: 20px;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
background-color: #ffffff;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
.card-revoke a {
|
||||
max-width: 50px;
|
||||
width: 100%;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.card-revoke button {
|
||||
max-width: 200px;
|
||||
width: 100%;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
color: #78a6de;
|
||||
}
|
||||
.card-revoke svg {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
fill: #333;
|
||||
}
|
||||
.image-label {
|
||||
display: block;
|
||||
color: #fff;
|
||||
padding: 5px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.image-container {
|
||||
width: 400px;
|
||||
height: 300px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.image-container img {
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
object-position: center center;
|
||||
}
|
||||
.passwordalert {
|
||||
color: #FF0000;
|
||||
}
|
||||
";
|
||||
|
||||
pub const CSSUPDATE: &str = "
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
background-color: #f4f4f4;
|
||||
font-family: 'Arial', sans-serif;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
padding: 20px;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
background-color: #ffffff;
|
||||
border-radius: 8px;
|
||||
text-align: left;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
form {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(1fr, 2fr);
|
||||
gap: 10px;
|
||||
max-width: 400px;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
.bg-primary {
|
||||
background-color: #1a61ed;
|
||||
}
|
||||
|
||||
.bg-primary:hover {
|
||||
background-color: #457be8;
|
||||
}
|
||||
|
||||
.bg-secondary {
|
||||
background-color: #2b81ed;
|
||||
}
|
||||
|
||||
.bg-secondary:hover {
|
||||
background-color: #5f9bff;
|
||||
}
|
||||
|
||||
label {
|
||||
text-align: left;
|
||||
padding-right: 10px;
|
||||
line-height: 2;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
button {
|
||||
grid-column: span 2;
|
||||
display: inline-block;
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 12px 17px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.div-text-area {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.side-by-side {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.circle-btn {
|
||||
width: 25px;
|
||||
height: 25px;
|
||||
border-radius: 50%;
|
||||
border: none;
|
||||
color: white;
|
||||
padding: 0px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#fileInput {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
padding-left: 0px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
</style>
|
||||
";
|
||||
|
||||
pub const JSUPDATE: &str = "
|
||||
var addSpAddressBtn = document.getElementById('add-sp-address-btn');
|
||||
var removeSpAddressBtn = document.querySelectorAll('.minus-sp-address-btn');
|
||||
|
||||
addSpAddressBtn.addEventListener('click', function (event) {
|
||||
addDynamicField(this);
|
||||
});
|
||||
|
||||
function addDynamicField(element) {
|
||||
var addSpAddressBlock = document.getElementById('sp-address-block');
|
||||
var spAddress = addSpAddressBlock.querySelector('#sp-address').value;
|
||||
addSpAddressBlock.querySelector('#sp-address').value = '';
|
||||
spAddress = spAddress.trim();
|
||||
if (spAddress != '') {
|
||||
var sideBySideDiv = document.createElement('div');
|
||||
sideBySideDiv.className = 'side-by-side';
|
||||
|
||||
var inputElement = document.createElement('input');
|
||||
inputElement.type = 'text';
|
||||
inputElement.name = 'spAddresses[]';
|
||||
inputElement.setAttribute('form', 'no-form');
|
||||
inputElement.value = spAddress;
|
||||
inputElement.disabled = true;
|
||||
|
||||
var buttonElement = document.createElement('button');
|
||||
buttonElement.type = 'button';
|
||||
buttonElement.className =
|
||||
'circle-btn bg-secondary minus-sp-address-btn';
|
||||
buttonElement.innerHTML = '-';
|
||||
|
||||
buttonElement.addEventListener('click', function (event) {
|
||||
removeDynamicField(this.parentElement);
|
||||
});
|
||||
|
||||
sideBySideDiv.appendChild(inputElement);
|
||||
sideBySideDiv.appendChild(buttonElement);
|
||||
|
||||
addSpAddressBlock.appendChild(sideBySideDiv);
|
||||
}
|
||||
function removeDynamicField(element) {
|
||||
element.remove();
|
||||
}
|
||||
}
|
||||
";
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default, Tsify)]
|
||||
#[tsify(into_wasm_abi, from_wasm_abi)]
|
||||
pub struct Process {
|
||||
pub id: u32,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub members: Vec<String>,
|
||||
pub html: String,
|
||||
pub style: String,
|
||||
pub script: String,
|
||||
// Add conditions : process, member, peer, artefact
|
||||
}
|
@ -1,544 +0,0 @@
|
||||
use anyhow::{Error, Result};
|
||||
use rand::{self, thread_rng, Rng, RngCore};
|
||||
use sdk_common::sp_client::bitcoin::hashes::Hash;
|
||||
use sdk_common::sp_client::bitcoin::hashes::HashEngine;
|
||||
use sdk_common::sp_client::bitcoin::hex::{DisplayHex, FromHex};
|
||||
use sdk_common::sp_client::bitcoin::secp256k1::SecretKey;
|
||||
use sdk_common::sp_client::bitcoin::secp256k1::ThirtyTwoByteHash;
|
||||
use sdk_common::sp_client::spclient::SpClient;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use tsify::Tsify;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use shamir::SecretData;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{Cursor, Read, Write};
|
||||
use std::str::FromStr;
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
|
||||
use sdk_common::sp_client::bitcoin::secp256k1::constants::SECRET_KEY_SIZE;
|
||||
use sdk_common::sp_client::silentpayments::bitcoin_hashes::sha256;
|
||||
use sdk_common::sp_client::silentpayments::sending::SilentPaymentAddress;
|
||||
use sdk_common::sp_client::spclient::SpendKey;
|
||||
use sdk_common::sp_client::spclient::{OutputList, SpWallet};
|
||||
|
||||
use crate::peers::Peer;
|
||||
use crate::user;
|
||||
use crate::MutexExt;
|
||||
use sdk_common::crypto::{
|
||||
AeadCore, Aes256Decryption, Aes256Encryption, Aes256Gcm, HalfKey, KeyInit, Purpose,
|
||||
};
|
||||
|
||||
type PreId = String;
|
||||
|
||||
const MANAGERS_NUMBER: u8 = 10;
|
||||
const QUORUM_SHARD: f32 = 0.8;
|
||||
|
||||
pub static CONNECTED_USER: OnceLock<Mutex<UserWallets>> = OnceLock::new();
|
||||
|
||||
pub fn lock_connected_user() -> Result<MutexGuard<'static, UserWallets>> {
|
||||
CONNECTED_USER
|
||||
.get_or_init(|| Mutex::new(UserWallets::default()))
|
||||
.lock_anyhow()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct UserWallets {
|
||||
main: Option<SpWallet>,
|
||||
recover: Option<SpWallet>,
|
||||
revoke: Option<SpWallet>,
|
||||
}
|
||||
|
||||
impl UserWallets {
|
||||
pub fn new(
|
||||
main: Option<SpWallet>,
|
||||
recover: Option<SpWallet>,
|
||||
revoke: Option<SpWallet>,
|
||||
) -> Self {
|
||||
Self {
|
||||
main,
|
||||
recover,
|
||||
revoke,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_get_revoke(&self) -> Result<&SpWallet> {
|
||||
if let Some(revoke) = &self.revoke {
|
||||
Ok(revoke)
|
||||
} else {
|
||||
Err(Error::msg("No revoke wallet available"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_get_recover(&self) -> Result<&SpWallet> {
|
||||
if let Some(recover) = &self.recover {
|
||||
Ok(recover)
|
||||
} else {
|
||||
Err(Error::msg("No recover wallet available"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_get_main(&self) -> Result<&SpWallet> {
|
||||
if let Some(main) = &self.main {
|
||||
Ok(main)
|
||||
} else {
|
||||
Err(Error::msg("No main wallet available"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_get_mut_revoke(&mut self) -> Result<&mut SpWallet> {
|
||||
if let Some(revoke) = &mut self.revoke {
|
||||
Ok(revoke)
|
||||
} else {
|
||||
Err(Error::msg("No revoke wallet available"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_get_mut_recover(&mut self) -> Result<&mut SpWallet> {
|
||||
if let Some(recover) = &mut self.recover {
|
||||
Ok(recover)
|
||||
} else {
|
||||
Err(Error::msg("No recover wallet available"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_get_mut_main(&mut self) -> Result<&mut SpWallet> {
|
||||
if let Some(main) = &mut self.main {
|
||||
Ok(main)
|
||||
} else {
|
||||
Err(Error::msg("No main wallet available"))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_not_empty(&self) -> bool {
|
||||
self.get_all_outputs().len() > 0
|
||||
}
|
||||
|
||||
pub(crate) fn get_all_outputs(&self) -> Vec<OutputList> {
|
||||
let mut res = Vec::<OutputList>::new();
|
||||
if let Some(main) = &self.main {
|
||||
res.push(main.get_outputs().clone());
|
||||
}
|
||||
if let Some(revoke) = &self.revoke {
|
||||
res.push(revoke.get_outputs().clone());
|
||||
}
|
||||
if let Some(recover) = &self.recover {
|
||||
res.push(recover.get_outputs().clone());
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Tsify)]
|
||||
#[tsify(into_wasm_abi, from_wasm_abi)]
|
||||
pub struct User {
|
||||
pub pre_id: PreId,
|
||||
pub processes: Vec<String>,
|
||||
pub peers: Vec<Peer>,
|
||||
recover_data: Vec<u8>,
|
||||
revoke_data: Option<Vec<u8>>,
|
||||
shares: Vec<Vec<u8>>,
|
||||
outputs: Vec<OutputList>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn new(user_wallets: UserWallets, user_password: String, process: String) -> Result<Self> {
|
||||
// if we are already logged in, abort
|
||||
if lock_connected_user()?.is_not_empty() {
|
||||
return Err(Error::msg("User already logged in"));
|
||||
}
|
||||
|
||||
let mut rng = thread_rng();
|
||||
|
||||
// image revoke
|
||||
// We just take the 2 revoke keys
|
||||
let mut revoke_data = Vec::with_capacity(64);
|
||||
let revoke = user_wallets.try_get_revoke()?;
|
||||
revoke_data.extend_from_slice(revoke.get_client().get_scan_key().as_ref());
|
||||
revoke_data.extend_from_slice(revoke.get_client().try_get_secret_spend_key()?.as_ref());
|
||||
|
||||
// Take the 2 recover keys
|
||||
// split recover spend key
|
||||
let recover_spend_key = user_wallets
|
||||
.try_get_recover()?
|
||||
.get_client()
|
||||
.try_get_secret_spend_key()?
|
||||
.clone();
|
||||
let (part1_key, part2_key) = recover_spend_key.as_ref().split_at(SECRET_KEY_SIZE / 2);
|
||||
let mut recover_data = Vec::<u8>::with_capacity(180); // 32 * 3 + (12+16)*3
|
||||
|
||||
// generate 3 tokens of 32B entropy
|
||||
let mut entropy_1: [u8; 32] = Aes256Gcm::generate_key(&mut rng).into();
|
||||
let mut entropy_2: [u8; 32] = Aes256Gcm::generate_key(&mut rng).into();
|
||||
let mut entropy_3: [u8; 32] = Aes256Gcm::generate_key(&mut rng).into();
|
||||
|
||||
recover_data.extend_from_slice(&entropy_1);
|
||||
recover_data.extend_from_slice(&entropy_2);
|
||||
recover_data.extend_from_slice(&entropy_3);
|
||||
|
||||
// hash the concatenation
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
engine.write_all(&user_password.as_bytes());
|
||||
engine.write_all(&entropy_1);
|
||||
let hash1 = sha256::Hash::from_engine(engine);
|
||||
|
||||
// take it as a AES key
|
||||
let part1_encryption = Aes256Encryption::import_key(
|
||||
Purpose::Login,
|
||||
part1_key.to_vec(),
|
||||
hash1.to_byte_array(),
|
||||
Aes256Gcm::generate_nonce(&mut rng).into(),
|
||||
)?;
|
||||
|
||||
// encrypt the part1 of the key
|
||||
let cipher_recover_part1 = part1_encryption.encrypt_with_aes_key()?;
|
||||
|
||||
recover_data.extend_from_slice(&cipher_recover_part1);
|
||||
|
||||
//Pre ID
|
||||
let pre_id: PreId = Self::compute_pre_id(&user_password, &cipher_recover_part1);
|
||||
|
||||
// encrypt the part 2 of the key
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
engine.write_all(&user_password.as_bytes());
|
||||
engine.write_all(&entropy_2);
|
||||
let hash2 = sha256::Hash::from_engine(engine);
|
||||
|
||||
// take it as a AES key
|
||||
let part2_encryption = Aes256Encryption::import_key(
|
||||
Purpose::Login,
|
||||
part2_key.to_vec(),
|
||||
hash2.to_byte_array(),
|
||||
Aes256Gcm::generate_nonce(&mut rng).into(),
|
||||
)?;
|
||||
|
||||
// encrypt the part2 of the key
|
||||
let cipher_recover_part2 = part2_encryption.encrypt_with_aes_key()?;
|
||||
|
||||
//create shardings
|
||||
let threshold = (MANAGERS_NUMBER as f32 * QUORUM_SHARD).floor();
|
||||
debug_assert!(threshold > 0.0 && threshold <= u8::MAX as f32);
|
||||
let sharding = shamir::SecretData::with_secret(
|
||||
&cipher_recover_part2.to_lower_hex_string(),
|
||||
threshold as u8,
|
||||
);
|
||||
|
||||
let shares: Vec<Vec<u8>> = (1..MANAGERS_NUMBER)
|
||||
.map(|x| {
|
||||
sharding.get_share(x).unwrap() // Let's trust it for now
|
||||
})
|
||||
.collect();
|
||||
|
||||
//scan key:
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
engine.write_all(&user_password.as_bytes());
|
||||
engine.write_all(&entropy_3);
|
||||
let hash3 = sha256::Hash::from_engine(engine);
|
||||
|
||||
let scan_key_encryption = Aes256Encryption::import_key(
|
||||
Purpose::ThirtyTwoBytes,
|
||||
user_wallets
|
||||
.try_get_recover()?
|
||||
.get_client()
|
||||
.get_scan_key()
|
||||
.secret_bytes()
|
||||
.to_vec(),
|
||||
hash3.to_byte_array(),
|
||||
Aes256Gcm::generate_nonce(&mut rng).into(),
|
||||
)?;
|
||||
|
||||
// encrypt the scan key
|
||||
let cipher_scan_key = scan_key_encryption.encrypt_with_aes_key()?;
|
||||
|
||||
recover_data.extend_from_slice(&cipher_scan_key);
|
||||
|
||||
let all_outputs = user_wallets.get_all_outputs();
|
||||
|
||||
Ok(User {
|
||||
pre_id: pre_id.to_string(),
|
||||
processes: vec![process],
|
||||
peers: vec![],
|
||||
recover_data,
|
||||
revoke_data: Some(revoke_data),
|
||||
shares,
|
||||
outputs: all_outputs,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn logout() -> Result<()> {
|
||||
if let Ok(mut user) = lock_connected_user() {
|
||||
*user = UserWallets::default();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::msg("Failed to lock CONNECTED_USER"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn login(
|
||||
pre_id: PreId,
|
||||
user_password: String,
|
||||
recover_data: &[u8],
|
||||
shares: &[Vec<u8>],
|
||||
outputs: &[OutputList],
|
||||
) -> Result<()> {
|
||||
// if we are already logged in, abort
|
||||
if lock_connected_user()?.is_not_empty() {
|
||||
return Err(Error::msg("User already logged in"));
|
||||
}
|
||||
|
||||
let mut retrieved_spend_key = [0u8; 32];
|
||||
let mut retrieved_scan_key = [0u8; 32];
|
||||
let mut entropy1 = [0u8; 32];
|
||||
let mut entropy2 = [0u8; 32];
|
||||
let mut entropy3 = [0u8; 32];
|
||||
let mut cipher_scan_key = [0u8; 60]; // cipher length == plain.len() + 16 + nonce.len()
|
||||
let mut part1_ciphertext = [0u8; 44];
|
||||
|
||||
let mut reader = Cursor::new(recover_data);
|
||||
reader.read_exact(&mut entropy1)?;
|
||||
reader.read_exact(&mut entropy2)?;
|
||||
reader.read_exact(&mut entropy3)?;
|
||||
reader.read_exact(&mut part1_ciphertext)?;
|
||||
reader.read_exact(&mut cipher_scan_key)?;
|
||||
|
||||
// We can retrieve the pre_id and check that it matches
|
||||
let retrieved_pre_id = Self::compute_pre_id(&user_password, &part1_ciphertext);
|
||||
|
||||
// If pre_id is not the same, password is probably false, or the client is feeding us garbage
|
||||
if retrieved_pre_id != pre_id {
|
||||
return Err(Error::msg("pre_id and recover_data don't match"));
|
||||
}
|
||||
|
||||
retrieved_spend_key[..16].copy_from_slice(&Self::recover_part1(
|
||||
&user_password,
|
||||
&entropy1,
|
||||
part1_ciphertext.to_vec(),
|
||||
)?);
|
||||
|
||||
retrieved_spend_key[16..].copy_from_slice(&Self::recover_part2(
|
||||
&user_password,
|
||||
&entropy2,
|
||||
shares,
|
||||
)?);
|
||||
|
||||
retrieved_scan_key.copy_from_slice(&Self::recover_key_slice(
|
||||
&user_password,
|
||||
&entropy3,
|
||||
cipher_scan_key.to_vec(),
|
||||
)?);
|
||||
|
||||
// we can create the recover sp_client
|
||||
let recover_client = SpClient::new(
|
||||
"".to_owned(),
|
||||
SecretKey::from_slice(&retrieved_scan_key)?,
|
||||
SpendKey::Secret(SecretKey::from_slice(&retrieved_spend_key)?),
|
||||
None,
|
||||
true,
|
||||
)?;
|
||||
|
||||
let recover_outputs = outputs
|
||||
.iter()
|
||||
.find(|o| o.check_fingerprint(&recover_client))
|
||||
.cloned();
|
||||
|
||||
let recover_wallet = SpWallet::new(recover_client, recover_outputs)?;
|
||||
|
||||
let user_wallets = UserWallets::new(None, Some(recover_wallet), None);
|
||||
|
||||
if let Ok(mut user) = lock_connected_user() {
|
||||
*user = user_wallets;
|
||||
} else {
|
||||
return Err(Error::msg("Failed to lock CONNECTED_USER"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn recover_key_slice(password: &str, entropy: &[u8], ciphertext: Vec<u8>) -> Result<Vec<u8>> {
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
engine.write_all(&password.as_bytes());
|
||||
engine.write_all(&entropy);
|
||||
let hash = sha256::Hash::from_engine(engine);
|
||||
|
||||
let aes_dec =
|
||||
Aes256Decryption::new(Purpose::ThirtyTwoBytes, ciphertext, hash.to_byte_array())?;
|
||||
|
||||
aes_dec.decrypt_with_key()
|
||||
}
|
||||
|
||||
fn recover_part1(password: &str, entropy: &[u8], ciphertext: Vec<u8>) -> Result<Vec<u8>> {
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
engine.write_all(&password.as_bytes());
|
||||
engine.write_all(&entropy);
|
||||
let hash = sha256::Hash::from_engine(engine);
|
||||
|
||||
let aes_dec = Aes256Decryption::new(Purpose::Login, ciphertext, hash.to_byte_array())?;
|
||||
|
||||
aes_dec.decrypt_with_key()
|
||||
}
|
||||
|
||||
fn recover_part2(password: &str, entropy: &[u8], shares: &[Vec<u8>]) -> Result<Vec<u8>> {
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
engine.write_all(&password.as_bytes());
|
||||
engine.write_all(&entropy);
|
||||
let hash = sha256::Hash::from_engine(engine);
|
||||
|
||||
let threshold = (MANAGERS_NUMBER as f32 * QUORUM_SHARD).floor();
|
||||
debug_assert!(threshold > 0.0 && threshold <= u8::MAX as f32);
|
||||
|
||||
let part2_key_enc = Vec::from_hex(
|
||||
&SecretData::recover_secret(threshold as u8, shares.to_vec())
|
||||
.ok_or_else(|| anyhow::Error::msg("Failed to retrieve the sharded secret"))?,
|
||||
)?;
|
||||
|
||||
let aes_dec = Aes256Decryption::new(Purpose::Login, part2_key_enc, hash.to_byte_array())?;
|
||||
|
||||
aes_dec.decrypt_with_key()
|
||||
}
|
||||
|
||||
fn compute_pre_id(user_password: &str, cipher_recover_part1: &[u8]) -> PreId {
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
engine.write_all(&user_password.as_bytes());
|
||||
engine.write_all(&cipher_recover_part1);
|
||||
let pre_id = sha256::Hash::from_engine(engine);
|
||||
|
||||
pre_id.to_string()
|
||||
}
|
||||
|
||||
//not used
|
||||
// pub fn pbkdf2(password: &str, data: &str) -> String {
|
||||
// let data_salt = data.trim_end_matches('=');
|
||||
// let salt = SaltString::from_b64(data_salt)
|
||||
// .map(|s| s)
|
||||
// .unwrap_or_else(|_| panic!("Failed to parse salt value from base64 string"));
|
||||
|
||||
// let mut password_hash = String::new();
|
||||
// if let Ok(pwd) = Scrypt.hash_password(password.as_bytes(), &salt) {
|
||||
// password_hash.push_str(&pwd.to_string());
|
||||
// }
|
||||
// sha_256(&password_hash)
|
||||
// }
|
||||
|
||||
// // Test sharing JS side
|
||||
// pub fn get_shares(&self) -> Vec<String> {
|
||||
// self.sharding.shares_format_str.clone()
|
||||
// }
|
||||
|
||||
// //Test sharing Js side
|
||||
// pub fn get_secret(&self, shardings: Vec<String>) -> String {
|
||||
// let mut shares_vec = Vec::new();
|
||||
|
||||
// for s in shardings.iter() {
|
||||
// let bytes_vec: Vec<u8> = s
|
||||
// .trim_matches(|c| c == '[' || c == ']')
|
||||
// .split(',')
|
||||
// .filter_map(|s| s.trim().parse().ok())
|
||||
// .collect();
|
||||
// shares_vec.push(bytes_vec);
|
||||
// }
|
||||
// self.sharding.recover_secrete(shares_vec.clone())
|
||||
// }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*; // Import everything from the outer module
|
||||
|
||||
const RECOVER_SPEND: &str = "394ef7757f5bc8cd692337c62abf6fa0ce9932fd4ec6676daddfbe3c1b3b9d11";
|
||||
const RECOVER_SCAN: &str = "3aa8cc570d17ec3a4dc4136e50151cc6de26052d968abfe02a5fea724ce38205";
|
||||
const REVOKE_SPEND: &str = "821c1a84fa9ee718c02005505fb8315bd479c7b9a878b1eff45929c48dfcaf28";
|
||||
const REVOKE_SCAN: &str = "a0f36cbc380624fa7eef022f39cab2716333451649dd8eb78e86d2e76bdb3f47";
|
||||
const MAIN_SPEND: &str = "b9098a6598ac55d8dd0e6b7aab0d1f63eb8792d06143f3c0fb6f5b80476a1c0d";
|
||||
const MAIN_SCAN: &str = "79dda4031663ac2cb250c46d896dc92b3c027a48a761b2342fabf1e441ea2857";
|
||||
const USER_PASSWORD: &str = "correct horse battery staple";
|
||||
const PROCESS: &str = "example";
|
||||
|
||||
fn helper_create_user_wallets() -> UserWallets {
|
||||
let label = "default".to_owned();
|
||||
let sp_main = SpClient::new(
|
||||
label.clone(),
|
||||
SecretKey::from_str(MAIN_SCAN).unwrap(),
|
||||
SpendKey::Secret(SecretKey::from_str(MAIN_SPEND).unwrap()),
|
||||
None,
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
let sp_recover = SpClient::new(
|
||||
label.clone(),
|
||||
SecretKey::from_str(RECOVER_SCAN).unwrap(),
|
||||
SpendKey::Secret(SecretKey::from_str(RECOVER_SPEND).unwrap()),
|
||||
None,
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
let sp_revoke = SpClient::new(
|
||||
label.clone(),
|
||||
SecretKey::from_str(REVOKE_SCAN).unwrap(),
|
||||
SpendKey::Secret(SecretKey::from_str(REVOKE_SPEND).unwrap()),
|
||||
None,
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
let user_wallets = UserWallets::new(
|
||||
Some(SpWallet::new(sp_main, None).unwrap()),
|
||||
Some(SpWallet::new(sp_recover, None).unwrap()),
|
||||
Some(SpWallet::new(sp_revoke, None).unwrap()),
|
||||
);
|
||||
|
||||
user_wallets
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_successful_creation() {
|
||||
let user_wallets = helper_create_user_wallets();
|
||||
let result = User::new(user_wallets, USER_PASSWORD.to_owned(), PROCESS.to_owned());
|
||||
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_logout() {
|
||||
let res = User::logout();
|
||||
|
||||
assert!(res.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_login() {
|
||||
let user_wallets = helper_create_user_wallets();
|
||||
let user = User::new(
|
||||
user_wallets.clone(),
|
||||
USER_PASSWORD.to_owned(),
|
||||
PROCESS.to_owned(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let res = User::login(
|
||||
user.pre_id.clone(),
|
||||
USER_PASSWORD.to_owned(),
|
||||
&user.recover_data,
|
||||
&user.shares,
|
||||
&user_wallets.get_all_outputs(),
|
||||
);
|
||||
|
||||
assert!(res.is_ok());
|
||||
|
||||
let connected = lock_connected_user().unwrap();
|
||||
|
||||
let recover = connected.try_get_recover().unwrap();
|
||||
|
||||
assert!(
|
||||
format!(
|
||||
"{}",
|
||||
recover
|
||||
.get_client()
|
||||
.try_get_secret_spend_key()
|
||||
.unwrap()
|
||||
.display_secret()
|
||||
) == RECOVER_SPEND
|
||||
)
|
||||
}
|
||||
}
|
4765
package-lock.json
generated
4765
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
24
package.json
24
package.json
@ -1,24 +0,0 @@
|
||||
{
|
||||
"name": "sdk_client",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"build_wasm": "wasm-pack build --out-dir ../../dist/pkg ./crates/sp_client --target bundler --dev",
|
||||
"start": "webpack serve",
|
||||
"build": "webpack"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"copy-webpack-plugin": "^12.0.2",
|
||||
"html-webpack-plugin": "^5.6.0",
|
||||
"ts-loader": "^9.5.1",
|
||||
"typescript": "^5.3.3",
|
||||
"webpack": "^5.90.3",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-dev-server": "^5.0.2"
|
||||
}
|
||||
}
|
1661
src/api.rs
Normal file
1661
src/api.rs
Normal file
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Before Width: | Height: | Size: 61 KiB |
Binary file not shown.
Before Width: | Height: | Size: 67 KiB |
178
src/database.ts
178
src/database.ts
@ -1,178 +0,0 @@
|
||||
class Database {
|
||||
private static instance: Database;
|
||||
private db: IDBDatabase | null = null;
|
||||
private dbName: string = '4nk';
|
||||
private dbVersion: number = 1;
|
||||
private storeDefinitions = {
|
||||
AnkUser: {
|
||||
name: "user",
|
||||
options: {'keyPath': 'pre_id'},
|
||||
indices: []
|
||||
},
|
||||
AnkSession: {
|
||||
name: "session",
|
||||
options: {},
|
||||
indices: []
|
||||
},
|
||||
AnkProcess: {
|
||||
name: "process",
|
||||
options: {'keyPath': 'id'},
|
||||
indices: [{
|
||||
name: 'by_name',
|
||||
keyPath: 'name',
|
||||
options: {
|
||||
'unique': true
|
||||
}
|
||||
}]
|
||||
},
|
||||
AnkMessages: {
|
||||
name: "messages",
|
||||
options: {'keyPath': 'id'},
|
||||
indices: []
|
||||
}
|
||||
}
|
||||
|
||||
// Private constructor to prevent direct instantiation from outside
|
||||
private constructor() {}
|
||||
|
||||
// Method to access the singleton instance of Database
|
||||
public static async getInstance(): Promise<Database> {
|
||||
if (!Database.instance) {
|
||||
Database.instance = new Database();
|
||||
await Database.instance.init();
|
||||
}
|
||||
return Database.instance;
|
||||
}
|
||||
|
||||
// Initialize the database
|
||||
private async init(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(this.dbName, this.dbVersion);
|
||||
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
|
||||
Object.values(this.storeDefinitions).forEach(({name, options, indices}) => {
|
||||
if (!db.objectStoreNames.contains(name)) {
|
||||
let store = db.createObjectStore(name, options);
|
||||
|
||||
indices.forEach(({name, keyPath, options}) => {
|
||||
store.createIndex(name, keyPath, options);
|
||||
})
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
request.onsuccess = () => {
|
||||
this.db = request.result;
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
console.error("Database error:", request.error);
|
||||
reject(request.error);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public async getDb(): Promise<IDBDatabase> {
|
||||
if (!this.db) {
|
||||
await this.init();
|
||||
}
|
||||
return this.db!;
|
||||
}
|
||||
|
||||
public getStoreList(): {[key: string]: string} {
|
||||
const objectList: {[key: string]: string} = {};
|
||||
Object.keys(this.storeDefinitions).forEach(key => {
|
||||
objectList[key] = this.storeDefinitions[key as keyof typeof this.storeDefinitions].name;
|
||||
});
|
||||
return objectList;
|
||||
}
|
||||
|
||||
public writeObject(db: IDBDatabase, storeName: string, obj: any, key: IDBValidKey | null): Promise<IDBRequest> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction(storeName, 'readwrite');
|
||||
const store = transaction.objectStore(storeName);
|
||||
let request: IDBRequest<any>;
|
||||
if (key) {
|
||||
request = store.add(obj, key);
|
||||
} else {
|
||||
request = store.add(obj);
|
||||
}
|
||||
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
});
|
||||
}
|
||||
|
||||
public getObject<T>(db: IDBDatabase, storeName: string, key: IDBValidKey): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction(storeName, 'readonly');
|
||||
const store = transaction.objectStore(storeName);
|
||||
const request = store.get(key);
|
||||
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
});
|
||||
}
|
||||
|
||||
public rmObject(db: IDBDatabase, storeName: string, key: IDBValidKey): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction(storeName, 'readwrite');
|
||||
const store = transaction.objectStore(storeName);
|
||||
const request = store.delete(key);
|
||||
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
});
|
||||
}
|
||||
|
||||
public getFirstMatchWithIndex<T>(db: IDBDatabase, storeName: string, indexName: string, lookup: string): Promise<T | null> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction(storeName, 'readonly');
|
||||
const store = transaction.objectStore(storeName);
|
||||
const index = store.index(indexName);
|
||||
const request = index.openCursor(IDBKeyRange.only(lookup));
|
||||
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => {
|
||||
const cursor = request.result;
|
||||
if (cursor) {
|
||||
resolve(cursor.value);
|
||||
} else {
|
||||
resolve(null)
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public setObject(db: IDBDatabase, storeName: string, obj: any, key: string | null): Promise<IDBRequest> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction(storeName, 'readwrite');
|
||||
const store = transaction.objectStore(storeName);
|
||||
let request: IDBRequest<any>;
|
||||
if (key) {
|
||||
request = store.put(obj, key);
|
||||
} else {
|
||||
request = store.put(obj);
|
||||
}
|
||||
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
});
|
||||
}
|
||||
|
||||
public getAll<T>(db: IDBDatabase, storeName: string): Promise<T[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction(storeName, 'readonly');
|
||||
const store = transaction.objectStore(storeName);
|
||||
const request = store.getAll();
|
||||
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Database;
|
@ -1,17 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="author" content="4NK">
|
||||
<meta name="description" content="4NK Web5 Platform">
|
||||
<meta name="keywords" content="4NK web5 bitcoin blockchain decentralize dapps relay contract">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="stylesheet" href="style/4nk.css">
|
||||
<title>4NK Application</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="containerId" class="container">
|
||||
<!-- 4NK Web5 Solution -->
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
20
src/index.ts
20
src/index.ts
@ -1,20 +0,0 @@
|
||||
import Services from './services';
|
||||
import { WebSocketClient } from './websockets';
|
||||
|
||||
const wsurl = "ws://localhost:8090";
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
try {
|
||||
const services = await Services.getInstance();
|
||||
await services.addWebsocketConnection(wsurl);
|
||||
|
||||
if ((await services.isNewUser())) {
|
||||
await services.displayCreateId();
|
||||
}
|
||||
else {
|
||||
await services.displayRecover()
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
});
|
||||
|
8
src/lib.rs
Normal file
8
src/lib.rs
Normal file
@ -0,0 +1,8 @@
|
||||
#![allow(warnings)]
|
||||
use anyhow::Error;
|
||||
use sdk_common::MutexExt;
|
||||
|
||||
pub mod api;
|
||||
mod peers;
|
||||
mod user;
|
||||
mod wallet;
|
909
src/services.ts
909
src/services.ts
@ -1,909 +0,0 @@
|
||||
import { createUserReturn, User, Process, createTransactionReturn, outputs_list, FaucetMessage, AnkFlag, NewTxMessage, CipherMessage, CachedMessage } from '../dist/pkg/sdk_client';
|
||||
import IndexedDB from './database'
|
||||
import { WebSocketClient } from './websockets';
|
||||
|
||||
class Services {
|
||||
private static instance: Services;
|
||||
private sdkClient: any;
|
||||
private current_process: string | null = null;
|
||||
private websocketConnection: WebSocketClient[] = [];
|
||||
private sp_address: string | null = null;
|
||||
|
||||
// Private constructor to prevent direct instantiation from outside
|
||||
private constructor() {}
|
||||
|
||||
// Method to access the singleton instance of Services
|
||||
public static async getInstance(): Promise<Services> {
|
||||
if (!Services.instance) {
|
||||
Services.instance = new Services();
|
||||
await Services.instance.init();
|
||||
}
|
||||
return Services.instance;
|
||||
}
|
||||
|
||||
// The init method is now part of the instance, and should only be called once
|
||||
private async init(): Promise<void> {
|
||||
this.sdkClient = await import("../dist/pkg/sdk_client");
|
||||
this.sdkClient.setup();
|
||||
await this.updateProcesses();
|
||||
}
|
||||
|
||||
public async addWebsocketConnection(url: string): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
const newClient = new WebSocketClient(url, services);
|
||||
if (!services.websocketConnection.includes(newClient)) {
|
||||
services.websocketConnection.push(newClient);
|
||||
}
|
||||
}
|
||||
|
||||
public async isNewUser(): Promise<boolean> {
|
||||
let isNew = false;
|
||||
try {
|
||||
const indexedDB = await IndexedDB.getInstance();
|
||||
const db = await indexedDB.getDb();
|
||||
let userListObject = await indexedDB.getAll<User>(db, indexedDB.getStoreList().AnkUser);
|
||||
if (userListObject.length == 0) {
|
||||
isNew = true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to retrieve isNewUser :", error);
|
||||
}
|
||||
return isNew;
|
||||
}
|
||||
|
||||
public async displayCreateId(): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
await services.createIdInjectHtml();
|
||||
services.attachSubmitListener("form4nk", (event) => services.createId(event));
|
||||
services.attachClickListener("displayrecover", services.displayRecover);
|
||||
await services.displayProcess();
|
||||
}
|
||||
|
||||
public async displaySendMessage(): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
await services.injectHtml('Messaging');
|
||||
services.attachSubmitListener("form4nk", (event) => services.sendMessage(event));
|
||||
// const ourAddress = document.getElementById('our_address');
|
||||
// if (ourAddress) {
|
||||
// ourAddress.innerHTML = `<strong>Our Address:</strong> ${this.sp_address}`
|
||||
// }
|
||||
// services.attachClickListener("displaysendmessage", services.displaySendMessage);
|
||||
// await services.displayProcess();
|
||||
}
|
||||
|
||||
public async sendMessage(event: Event): Promise<void> {
|
||||
event.preventDefault();
|
||||
|
||||
const services = await Services.getInstance();
|
||||
let availableAmt: number = 0;
|
||||
|
||||
// check available amount
|
||||
try {
|
||||
availableAmt = await services.sdkClient.get_available_amount_for_user(true);
|
||||
} catch (error) {
|
||||
console.error('Failed to get available amount');
|
||||
return;
|
||||
}
|
||||
|
||||
if (availableAmt < 2000) {
|
||||
try {
|
||||
await services.obtainTokenWithFaucet();
|
||||
} catch (error) {
|
||||
console.error('Failed to obtain faucet token:', error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const spAddressElement = document.getElementById("sp_address") as HTMLInputElement;
|
||||
const messageElement = document.getElementById("message") as HTMLInputElement;
|
||||
|
||||
if (!spAddressElement || !messageElement) {
|
||||
console.error("One or more elements not found");
|
||||
return;
|
||||
}
|
||||
|
||||
const recipientSpAddress = spAddressElement.value;
|
||||
const message = messageElement.value;
|
||||
|
||||
const msg_payload: CipherMessage = {sender: this.sp_address!, message: message, error: null};
|
||||
|
||||
let notificationInfo = await services.notify_address_for_message(recipientSpAddress, msg_payload);
|
||||
if (notificationInfo) {
|
||||
let networkMsg = notificationInfo.new_network_msg;
|
||||
console.debug(networkMsg);
|
||||
|
||||
const connection = await services.pickWebsocketConnectionRandom();
|
||||
const flag: AnkFlag = 'Cipher';
|
||||
try {
|
||||
// send message (transaction in envelope)
|
||||
await services.updateMessages(networkMsg);
|
||||
connection?.sendMessage(flag, networkMsg.ciphertext!);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
// add peers list
|
||||
// add processes list
|
||||
}
|
||||
}
|
||||
|
||||
public async createId(event: Event): Promise<void> {
|
||||
event.preventDefault();
|
||||
|
||||
// verify we don't already have an user
|
||||
const services = await Services.getInstance();
|
||||
try {
|
||||
let user = await services.getUserInfo();
|
||||
if (user) {
|
||||
console.error("User already exists, please recover");
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const passwordElement = document.getElementById("password") as HTMLInputElement;
|
||||
const processElement = document.getElementById("selectProcess") as HTMLSelectElement;
|
||||
|
||||
if (!passwordElement || !processElement) {
|
||||
throw 'One or more elements not found';
|
||||
}
|
||||
|
||||
const password = passwordElement.value;
|
||||
this.current_process = processElement.value;
|
||||
// console.log("JS password: " + password + " process: " + this.current_process);
|
||||
// To comment if test
|
||||
// if (!Services.instance.isPasswordValid(password)) return;
|
||||
|
||||
const label = null;
|
||||
const birthday_signet = 50000;
|
||||
const birthday_main = 500000;
|
||||
|
||||
let createUserReturn: createUserReturn;
|
||||
try {
|
||||
createUserReturn = services.sdkClient.create_user(password, label, birthday_main, birthday_signet, this.current_process);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
let user = createUserReturn.user;
|
||||
|
||||
// const shares = user.shares;
|
||||
// send the shares on the network
|
||||
const revokeData = user.revoke_data;
|
||||
if (!revokeData) {
|
||||
throw 'Failed to get revoke data from wasm';
|
||||
}
|
||||
|
||||
// user.shares = [];
|
||||
user.revoke_data = null;
|
||||
|
||||
try {
|
||||
const indexedDb = await IndexedDB.getInstance();
|
||||
const db = await indexedDb.getDb();
|
||||
await indexedDb.writeObject(db, indexedDb.getStoreList().AnkUser, user, null);
|
||||
} catch (error) {
|
||||
throw `Failed to write user object: ${error}`;
|
||||
}
|
||||
|
||||
try {
|
||||
await services.obtainTokenWithFaucet();
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
await services.displayRevokeImage(new Uint8Array(revokeData));
|
||||
}
|
||||
|
||||
public async displayRecover(): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
await services.recoverInjectHtml();
|
||||
services.attachSubmitListener("form4nk", (event) => services.recover(event));
|
||||
services.attachClickListener("displaycreateid", services.displayCreateId);
|
||||
services.attachClickListener("displayrevoke", services.displayRevoke);
|
||||
services.attachClickListener("submitButtonRevoke", services.revoke);
|
||||
await services.displayProcess();
|
||||
}
|
||||
|
||||
public async recover(event: Event) {
|
||||
event.preventDefault();
|
||||
|
||||
const passwordElement = document.getElementById("password") as HTMLInputElement;
|
||||
const processElement = document.getElementById("selectProcess") as HTMLSelectElement;
|
||||
|
||||
if (!passwordElement || !processElement) {
|
||||
console.error("One or more elements not found");
|
||||
return;
|
||||
}
|
||||
|
||||
const password = passwordElement.value;
|
||||
const process = processElement.value;
|
||||
// console.log("JS password: " + password + " process: " + process);
|
||||
// To comment if test
|
||||
// if (!Services.instance.isPasswordValid(password)) return;
|
||||
|
||||
// Get user in db
|
||||
const services = await Services.getInstance();
|
||||
try {
|
||||
const user = await services.getUserInfo();
|
||||
if (user) {
|
||||
services.sdkClient.login_user(password, user.pre_id, user.recover_data, user.shares, user.outputs);
|
||||
this.sp_address = services.sdkClient.get_recover_address();
|
||||
if (this.sp_address) {
|
||||
console.info('Using sp_address:', this.sp_address);
|
||||
await services.obtainTokenWithFaucet();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
console.info(this.sp_address);
|
||||
|
||||
// TODO: check blocks since last_scan and update outputs
|
||||
|
||||
await services.displaySendMessage();
|
||||
}
|
||||
|
||||
public async displayRevokeImage(revokeData: Uint8Array): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
await services.revokeImageInjectHtml();
|
||||
services.attachClickListener("displayupdateanid", services.displayUpdateAnId);
|
||||
|
||||
let imageBytes = await services.getRecoverImage('assets/4nk_revoke.jpg');
|
||||
if (imageBytes != null) {
|
||||
var elem = document.getElementById("revoke") as HTMLAnchorElement;
|
||||
if (elem != null) {
|
||||
let imageWithData = services.sdkClient.add_data_to_image(imageBytes, revokeData, true);
|
||||
const blob = new Blob([imageWithData], { type: 'image/jpeg' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
// Set the href attribute for download
|
||||
elem.href = url;
|
||||
elem.download = 'revoke_4NK.jpg';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async getRecoverImage(imageUrl:string): Promise<Uint8Array|null> {
|
||||
let imageBytes = null;
|
||||
try {
|
||||
const response = await fetch(imageUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch image: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
imageBytes = new Uint8Array(arrayBuffer);
|
||||
} catch (error) {
|
||||
console.error("Failed to get image : "+imageUrl, error);
|
||||
}
|
||||
return imageBytes;
|
||||
}
|
||||
|
||||
public async displayRevoke(): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
await services.revokeInjectHtml();
|
||||
services.attachClickListener("displayrecover", Services.instance.displayRecover);
|
||||
services.attachSubmitListener("form4nk", Services.instance.revoke);
|
||||
}
|
||||
|
||||
public async revoke(event: Event): Promise<void> {
|
||||
event.preventDefault();
|
||||
console.log("JS revoke click ");
|
||||
// TODO
|
||||
alert("revoke click to do ...");
|
||||
}
|
||||
|
||||
public async displayUpdateAnId() {
|
||||
const services = await Services.getInstance();
|
||||
|
||||
await services.updateIdInjectHtml();
|
||||
|
||||
services.attachSubmitListener("form4nk", services.updateAnId);
|
||||
}
|
||||
|
||||
public async parseNetworkMessage(raw: string, feeRate: number): Promise<CachedMessage> {
|
||||
const services = await Services.getInstance();
|
||||
try {
|
||||
const msg: CachedMessage = services.sdkClient.parse_network_msg(raw, feeRate);
|
||||
return msg;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async updateAnId(event: Event): Promise<void> {
|
||||
event.preventDefault();
|
||||
|
||||
// TODO get values
|
||||
const firstNameElement = 'firstName';
|
||||
const lastNameElement = 'lastName';
|
||||
const firstName = document.getElementById(firstNameElement) as HTMLInputElement;
|
||||
const lastName = document.getElementById(lastNameElement) as HTMLInputElement;
|
||||
|
||||
console.log("JS updateAnId submit ");
|
||||
// TODO
|
||||
alert("updateAnId submit to do ... Name : "+firstName.value + " "+lastName.value);
|
||||
|
||||
// TODO Mock add user member to process
|
||||
}
|
||||
|
||||
public async displayProcess(): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
const processList = await services.getAllProcess();
|
||||
const selectProcess = document.getElementById("selectProcess");
|
||||
if (selectProcess) {
|
||||
processList.forEach((process) => {
|
||||
let child = new Option(process.name, process.name);
|
||||
if (!selectProcess.contains(child)) {
|
||||
selectProcess.appendChild(child);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
public async addProcess(process: Process): Promise<void> {
|
||||
try {
|
||||
const indexedDB = await IndexedDB.getInstance();
|
||||
const db = await indexedDB.getDb();
|
||||
await indexedDB.writeObject(db, indexedDB.getStoreList().AnkProcess, process, null);
|
||||
} catch (error) {
|
||||
console.log('addProcess failed: ',error);
|
||||
}
|
||||
}
|
||||
|
||||
public async getAllProcess(): Promise<Process[]> {
|
||||
try {
|
||||
const indexedDB = await IndexedDB.getInstance();
|
||||
const db = await indexedDB.getDb();
|
||||
let processListObject = await indexedDB.getAll<Process>(db, indexedDB.getStoreList().AnkProcess);
|
||||
return processListObject;
|
||||
} catch (error) {
|
||||
console.log('getAllProcess failed: ',error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public async updateOwnedOutputsForUser(): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
let latest_outputs: outputs_list;
|
||||
try {
|
||||
latest_outputs = services.sdkClient.get_outpoints_for_user();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let user = await services.getUserInfo();
|
||||
if (user) {
|
||||
user.outputs = latest_outputs;
|
||||
// console.warn(user);
|
||||
await services.updateUser(user);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
public async getAllProcessForUser(pre_id: string): Promise<Process[]> {
|
||||
const services = await Services.getInstance();
|
||||
let user: User;
|
||||
let userProcessList: Process[] = [];
|
||||
try {
|
||||
const indexedDB = await IndexedDB.getInstance();
|
||||
const db = await indexedDB.getDb();
|
||||
user = await indexedDB.getObject<User>(db, indexedDB.getStoreList().AnkUser, pre_id);
|
||||
} catch (error) {
|
||||
console.error('getAllUserProcess failed: ',error);
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const processListObject = await services.getAllProcess();
|
||||
processListObject.forEach(async (processObject) => {
|
||||
if (processObject.members.includes(user.pre_id)) {
|
||||
userProcessList.push(processObject);
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('getAllUserProcess failed: ',error);
|
||||
return [];
|
||||
}
|
||||
return userProcessList;
|
||||
}
|
||||
|
||||
public async getProcessByName(name: string): Promise<Process | null> {
|
||||
console.log('getProcessByName name: '+name);
|
||||
const indexedDB = await IndexedDB.getInstance();
|
||||
const db = await indexedDB.getDb();
|
||||
const process = await indexedDB.getFirstMatchWithIndex<Process>(db, indexedDB.getStoreList().AnkProcess, 'by_name', name);
|
||||
console.log('getProcessByName process: '+process);
|
||||
|
||||
return process;
|
||||
}
|
||||
|
||||
public async updateMessages(message: CachedMessage): Promise<void> {
|
||||
const indexedDb = await IndexedDB.getInstance();
|
||||
const db = await indexedDb.getDb();
|
||||
|
||||
try {
|
||||
await indexedDb.setObject(db, indexedDb.getStoreList().AnkMessages, message, null);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async removeMessage(id: number): Promise<void> {
|
||||
const indexedDb = await IndexedDB.getInstance();
|
||||
const db = await indexedDb.getDb();
|
||||
|
||||
try {
|
||||
await indexedDb.rmObject(db, indexedDb.getStoreList().AnkMessages, id);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async updateProcesses(): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
const processList: Process[] = services.sdkClient.get_processes();
|
||||
|
||||
processList.forEach(async (process: Process) => {
|
||||
const indexedDB = await IndexedDB.getInstance();
|
||||
const db = await indexedDB.getDb();
|
||||
try {
|
||||
const processStore = await indexedDB.getObject<Process>(db, indexedDB.getStoreList().AnkProcess, process.id);
|
||||
if (!processStore) {
|
||||
await indexedDB.writeObject(db, indexedDB.getStoreList().AnkProcess, process, null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error while writing process', process.name, 'to indexedDB:', error);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
public attachClickListener(elementId: string, callback: (event: Event) => void): void {
|
||||
const element = document.getElementById(elementId);
|
||||
element?.removeEventListener("click", callback);
|
||||
element?.addEventListener("click", callback);
|
||||
}
|
||||
|
||||
public attachSubmitListener(elementId: string, callback: (event: Event) => void): void {
|
||||
const element = document.getElementById(elementId);
|
||||
element?.removeEventListener("submit", callback);
|
||||
element?.addEventListener("submit", callback);
|
||||
}
|
||||
public async revokeInjectHtml() {
|
||||
const container = document.getElementById('containerId');
|
||||
|
||||
if (!container) {
|
||||
console.error("No html container");
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML =
|
||||
` <div class='card'>
|
||||
<div class='side-by-side'>
|
||||
<h3>Revoke an Id</h3>
|
||||
<div>
|
||||
<a href='#' id='displayrecover'>Recover</a>
|
||||
</div>
|
||||
</div>
|
||||
<form id='form4nk' action='#'>
|
||||
<label for='password'>Password :</label>
|
||||
<input type='password' id='password' />
|
||||
<hr/>
|
||||
<div class='image-container'>
|
||||
<label class='image-label'>Revoke image</label>
|
||||
<img src='assets/revoke.jpeg' alt='' />
|
||||
</div>
|
||||
<hr/>
|
||||
<button type='submit' id='submitButton' class='recover bg-primary'>Revoke</button>
|
||||
</form>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
public async revokeImageInjectHtml() {
|
||||
const container = document.getElementById('containerId');
|
||||
|
||||
if (!container) {
|
||||
console.error("No html container");
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML =
|
||||
`<div class='card'>
|
||||
<div class='side-by-side'>
|
||||
<h3>Revoke image</h3>
|
||||
<div><a href='#' id='displayupdateanid'>Update an Id</a></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class='card-revoke'>
|
||||
<a href='#' download='revoke_4NK.jpg' id='revoke'>
|
||||
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 448 512'>
|
||||
<path
|
||||
d='M246.6 9.4c-12.5-12.5-32.8-12.5-45.3 0l-128 128c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 109.3V320c0 17.7 14.3 32 32 32s32-14.3 32-32V109.3l73.4 73.4c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3l-128-128zM64 352c0-17.7-14.3-32-32-32s-32 14.3-32 32v64c0 53 43 96 96 96H352c53 0 96-43 96-96V352c0-17.7-14.3-32-32-32s-32 14.3-32 32v64c0 17.7-14.3 32-32 32H96c-17.7 0-32-14.3-32-32V352z'
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
<div class='image-container'>
|
||||
<img src='assets/4nk_revoke.jpg' alt='' />
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
public async recoverInjectHtml() {
|
||||
const container = document.getElementById('containerId');
|
||||
|
||||
if (!container) {
|
||||
console.error("No html container");
|
||||
return;
|
||||
}
|
||||
|
||||
const services = await Services.getInstance();
|
||||
await services.updateProcesses();
|
||||
|
||||
container.innerHTML =
|
||||
`<div class='card'>
|
||||
<div class='side-by-side'>
|
||||
<h3>Recover my Id</h3>
|
||||
<div><a href='#'>Processes</a></div>
|
||||
</div>
|
||||
<form id='form4nk' action='#'>
|
||||
<label for='password'>Password :</label>
|
||||
<input type='password' id='password' />
|
||||
<input type='hidden' id='currentpage' value='recover' />
|
||||
<select id='selectProcess' class='custom-select'></select><hr/>
|
||||
<div class='side-by-side'>
|
||||
<button type='submit' id='submitButton' class='recover bg-primary'>Recover</button>
|
||||
<div>
|
||||
<a href='#' id='displaycreateid'>Create an Id</a>
|
||||
</div>
|
||||
</div><hr/>
|
||||
<a href='#' id='displayrevoke' class='btn'>Revoke</a>
|
||||
</form><br/>
|
||||
<div id='passwordalert' class='passwordalert'></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
public async createIdInjectHtml() {
|
||||
const container = document.getElementById('containerId');
|
||||
|
||||
if (!container) {
|
||||
console.error("No html container");
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML =
|
||||
`<div class='card'>
|
||||
<div class='side-by-side'>
|
||||
<h3>Create an Id</h3>
|
||||
<div><a href='#'>Processes</a></div>
|
||||
</div>
|
||||
<form id='form4nk' action='#'>
|
||||
<label for='password'>Password :</label>
|
||||
<input type='password' id='password' /><hr/>
|
||||
<input type='hidden' id='currentpage' value='creatid' />
|
||||
<select id='selectProcess' class='custom-select'></select><hr/>
|
||||
<div class='side-by-side'>
|
||||
<button type='submit' id='submitButton' class='bg-primary'>Create</button>
|
||||
<div>
|
||||
<a href='#' id='displayrecover'>Recover</a>
|
||||
</div>
|
||||
</div>
|
||||
</form><br/>
|
||||
<div id='passwordalert' class='passwordalert'></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
public async updateIdInjectHtml() {
|
||||
const container = document.getElementById('containerId');
|
||||
|
||||
if (!container) {
|
||||
console.error("No html container");
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML =
|
||||
`<body>
|
||||
<div class='container'>
|
||||
<div>
|
||||
<h3>Update an Id</h3>
|
||||
</div>
|
||||
<hr />
|
||||
<form id='form4nk' action='#'>
|
||||
<label for='firstName'>First Name:</label>
|
||||
<input type='text' id='firstName' name='firstName' required />
|
||||
|
||||
<label for='lastName'>Last Name:</label>
|
||||
<input type='text' id='lastName' name='lastName' required />
|
||||
|
||||
<label for='Birthday'>Birthday:</label>
|
||||
<input type='date' id='Birthday' name='birthday' />
|
||||
|
||||
<label for='file'>File:</label>
|
||||
<input type='file' id='fileInput' name='file' />
|
||||
|
||||
<label>Third parties:</label>
|
||||
<div id='sp-address-block'>
|
||||
<div class='side-by-side'>
|
||||
<input
|
||||
type='text'
|
||||
name='sp-address'
|
||||
id='sp-address'
|
||||
placeholder='sp address'
|
||||
form='no-form'
|
||||
/>
|
||||
<button
|
||||
type='button'
|
||||
class='circle-btn bg-secondary'
|
||||
id='add-sp-address-btn'
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class='div-text-area'>
|
||||
<textarea
|
||||
name='bio'
|
||||
id=''
|
||||
cols='30'
|
||||
rows='10'
|
||||
placeholder='Bio'
|
||||
></textarea>
|
||||
</div>
|
||||
<button type='submit' class='bg-primary'>Update</button>
|
||||
</form>
|
||||
</div>
|
||||
</body>`;
|
||||
}
|
||||
|
||||
public async injectHtml(processName: string) {
|
||||
const container = document.getElementById('containerId');
|
||||
|
||||
if (!container) {
|
||||
console.error("No html container");
|
||||
return;
|
||||
}
|
||||
|
||||
const services = await Services.getInstance();
|
||||
|
||||
// do we have all processes in db?
|
||||
const knownProcesses = await services.getAllProcess();
|
||||
const processesFromNetwork: Process[] = services.sdkClient.get_processes();
|
||||
|
||||
const processToAdd = processesFromNetwork.filter(processFromNetwork => !knownProcesses.some(knownProcess => knownProcess.id === processFromNetwork.id));
|
||||
|
||||
processToAdd.forEach(async p => {
|
||||
await services.addProcess(p);
|
||||
})
|
||||
|
||||
// get the process we need
|
||||
const process = await services.getProcessByName(processName);
|
||||
if (process) {
|
||||
container.innerHTML = process.html;
|
||||
} else {
|
||||
console.error("No process ", processName);
|
||||
}
|
||||
}
|
||||
|
||||
// public async getCurrentProcess(): Promise<string> {
|
||||
// let currentProcess = "";
|
||||
// try {
|
||||
// const indexedDB = await IndexedDB.getInstance();
|
||||
// const db = indexedDB.getDb();
|
||||
// currentProcess = await indexedDB.getObject<string>(db, indexedDB.getStoreList().AnkSession, Services.CURRENT_PROCESS);
|
||||
// } catch (error) {
|
||||
// console.error("Failed to retrieve currentprocess object :", error);
|
||||
// }
|
||||
// return currentProcess;
|
||||
// }
|
||||
|
||||
public isPasswordValid(password: string) {
|
||||
var alertElem = document.getElementById("passwordalert");
|
||||
var success = true;
|
||||
var strength = 0;
|
||||
if (password.match(/[a-z]+/)) {
|
||||
var strength = 0;
|
||||
strength += 1;
|
||||
}
|
||||
if (password.match(/[A-Z]+/)) {
|
||||
strength += 1;
|
||||
}
|
||||
if (password.match(/[0-9]+/)) {
|
||||
strength += 1;
|
||||
}
|
||||
if (password.match(/[$@#&!]+/)) {
|
||||
strength += 1;
|
||||
}
|
||||
if (alertElem !== null) {
|
||||
// TODO Passer à 18
|
||||
if (password.length < 4) {
|
||||
alertElem.innerHTML = "Password size is < 4";
|
||||
success = false;
|
||||
} else {
|
||||
if (password.length > 30) {
|
||||
alertElem.innerHTML = "Password size is > 30";
|
||||
success = false;
|
||||
} else {
|
||||
if (strength < 4) {
|
||||
alertElem.innerHTML = "Password need [a-z] [A-Z] [0-9]+ [$@#&!]+";
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
private async pickWebsocketConnectionRandom(): Promise<WebSocketClient | null> {
|
||||
const services = await Services.getInstance();
|
||||
const websockets = services.websocketConnection;
|
||||
if (websockets.length === 0) {
|
||||
console.error("No websocket connection available at the moment");
|
||||
return null;
|
||||
} else {
|
||||
const random = Math.floor(Math.random() * websockets.length);
|
||||
return websockets[random];
|
||||
}
|
||||
}
|
||||
|
||||
public async obtainTokenWithFaucet(): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
const connection = await services.pickWebsocketConnectionRandom();
|
||||
if (!connection) {
|
||||
throw 'no available relay connections';
|
||||
}
|
||||
|
||||
let cachedMsg: CachedMessage;
|
||||
try {
|
||||
const flag: AnkFlag = 'Faucet';
|
||||
cachedMsg = services.sdkClient.create_faucet_msg();
|
||||
if (cachedMsg.commitment && cachedMsg.recipient) {
|
||||
let faucetMsg: FaucetMessage = {
|
||||
sp_address: cachedMsg.recipient,
|
||||
commitment: cachedMsg.commitment,
|
||||
error: null,
|
||||
}
|
||||
connection.sendMessage(flag, JSON.stringify(faucetMsg));
|
||||
}
|
||||
} catch (error) {
|
||||
throw `Failed to obtain tokens with relay ${connection.getUrl()}: ${error}`;
|
||||
}
|
||||
|
||||
try {
|
||||
await services.updateMessages(cachedMsg);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async updateUser(user: User): Promise<void> {
|
||||
try {
|
||||
const indexedDB = await IndexedDB.getInstance();
|
||||
const db = await indexedDB.getDb();
|
||||
await indexedDB.setObject(db, indexedDB.getStoreList().AnkUser, user, null);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async getUserInfo(): Promise<User | null> {
|
||||
try {
|
||||
const indexedDB = await IndexedDB.getInstance();
|
||||
const db = await indexedDB.getDb();
|
||||
let user = await indexedDB.getAll<User>(db, indexedDB.getStoreList().AnkUser);
|
||||
// This should never happen
|
||||
if (user.length > 1) {
|
||||
throw "Multiple users in db";
|
||||
} else {
|
||||
let res = user.pop();
|
||||
if (res === undefined) {
|
||||
return null;
|
||||
} else {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async answer_confirmation_message(msg: CachedMessage): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
const connection = await services.pickWebsocketConnectionRandom();
|
||||
if (!connection) {
|
||||
throw new Error("No connection to relay");
|
||||
}
|
||||
let user: User;
|
||||
try {
|
||||
let possibleUser = await services.getUserInfo();
|
||||
if (!possibleUser) {
|
||||
throw new Error("No user loaded, please first create a new user or login");
|
||||
} else {
|
||||
user = possibleUser;
|
||||
}
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
let notificationInfo: createTransactionReturn;
|
||||
try {
|
||||
const feeRate = 1;
|
||||
notificationInfo = services.sdkClient.answer_confirmation_transaction(msg.id, feeRate);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to create confirmation transaction: ${error}`);
|
||||
}
|
||||
const flag: AnkFlag = "NewTx";
|
||||
const newTxMsg: NewTxMessage = {
|
||||
'transaction': notificationInfo.transaction,
|
||||
'tweak_data': null,
|
||||
'error': null,
|
||||
}
|
||||
connection.sendMessage(flag, JSON.stringify(newTxMsg));
|
||||
await services.updateMessages(notificationInfo.new_network_msg);
|
||||
return;
|
||||
}
|
||||
|
||||
public async confirm_sender_address(msg: CachedMessage): Promise<void> {
|
||||
const services = await Services.getInstance();
|
||||
const connection = await services.pickWebsocketConnectionRandom();
|
||||
if (!connection) {
|
||||
throw new Error("No connection to relay");
|
||||
}
|
||||
let user: User;
|
||||
try {
|
||||
let possibleUser = await services.getUserInfo();
|
||||
if (!possibleUser) {
|
||||
throw new Error("No user loaded, please first create a new user or login");
|
||||
} else {
|
||||
user = possibleUser;
|
||||
}
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
let notificationInfo: createTransactionReturn;
|
||||
try {
|
||||
const feeRate = 1;
|
||||
notificationInfo = services.sdkClient.create_confirmation_transaction(msg.id, feeRate);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to create confirmation transaction: ${error}`);
|
||||
}
|
||||
const flag: AnkFlag = "NewTx";
|
||||
const newTxMsg: NewTxMessage = {
|
||||
'transaction': notificationInfo.transaction,
|
||||
'tweak_data': null,
|
||||
'error': null,
|
||||
}
|
||||
connection.sendMessage(flag, JSON.stringify(newTxMsg));
|
||||
await services.updateMessages(notificationInfo.new_network_msg);
|
||||
return;
|
||||
}
|
||||
|
||||
public async notify_address_for_message(sp_address: string, message: CipherMessage): Promise<createTransactionReturn> {
|
||||
const services = await Services.getInstance();
|
||||
const connection = await services.pickWebsocketConnectionRandom();
|
||||
if (!connection) {
|
||||
throw 'No available connection';
|
||||
}
|
||||
|
||||
try {
|
||||
const feeRate = 1;
|
||||
let notificationInfo: createTransactionReturn = services.sdkClient.create_notification_transaction(sp_address, message, feeRate);
|
||||
const flag: AnkFlag = "NewTx";
|
||||
const newTxMsg: NewTxMessage = {
|
||||
'transaction': notificationInfo.transaction,
|
||||
'tweak_data': null,
|
||||
'error': null,
|
||||
}
|
||||
connection.sendMessage(flag, JSON.stringify(newTxMsg));
|
||||
console.info('Successfully sent notification transaction');
|
||||
return notificationInfo;
|
||||
} catch (error) {
|
||||
throw 'Failed to create notification transaction:", error';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Services;
|
@ -1,170 +0,0 @@
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
background-color: #f4f4f4;
|
||||
font-family: 'Arial', sans-serif;
|
||||
}
|
||||
.container {
|
||||
text-align: center;
|
||||
}
|
||||
.card {
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
padding: 20px;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
background-color: #ffffff;
|
||||
border-radius: 8px;
|
||||
text-align: left;
|
||||
overflow: hidden;
|
||||
}
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
/* flex-wrap: wrap; */
|
||||
}
|
||||
label {
|
||||
font-weight: bold;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
hr {
|
||||
border: 0;
|
||||
height: 1px;
|
||||
background-color: #ddd;
|
||||
margin: 10px 0;
|
||||
}
|
||||
input, select {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
margin: 8px 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
select {
|
||||
padding: 10px;
|
||||
background-color: #f9f9f9;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
button {
|
||||
display: inline-block;
|
||||
background-color: #4caf50;
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 12px 17px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #45a049;
|
||||
}
|
||||
.side-by-side {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.side-by-side>* {
|
||||
display: inline-block;
|
||||
}
|
||||
button.recover {
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
background-color: #4caf50;
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 12px 17px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.recover:hover {
|
||||
background-color: #45a049;
|
||||
}
|
||||
a.btn {
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
background-color: #4caf50;
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 12px 17px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
a.btn:hover {
|
||||
background-color: #45a049;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #78a6de;
|
||||
}
|
||||
.bg-secondary {
|
||||
background-color: #2b81ed;
|
||||
}
|
||||
.bg-primary {
|
||||
background-color: #1A61ED;
|
||||
}
|
||||
.bg-primary:hover {
|
||||
background-color: #457be8;
|
||||
}
|
||||
.card-revoke {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
padding: 20px;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
background-color: #ffffff;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
.card-revoke a {
|
||||
max-width: 50px;
|
||||
width: 100%;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.card-revoke button {
|
||||
max-width: 200px;
|
||||
width: 100%;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
color: #78a6de;
|
||||
}
|
||||
.card-revoke svg {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
fill: #333;
|
||||
}
|
||||
.image-label {
|
||||
display: block;
|
||||
color: #fff;
|
||||
padding: 5px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.image-container {
|
||||
width: 400px;
|
||||
height: 300px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.image-container img {
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
object-position: center center;
|
||||
}
|
||||
.passwordalert {
|
||||
color: #FF0000;
|
||||
}
|
59
src/user.rs
Normal file
59
src/user.rs
Normal file
@ -0,0 +1,59 @@
|
||||
use anyhow::{Error, Result};
|
||||
use rand::{self, thread_rng, Rng, RngCore};
|
||||
use sdk_common::sp_client::bitcoin::consensus::{deserialize, serialize};
|
||||
use sdk_common::sp_client::bitcoin::hashes::{Hash, HashEngine};
|
||||
use sdk_common::sp_client::bitcoin::hex::{DisplayHex, FromHex};
|
||||
use sdk_common::sp_client::bitcoin::key::{Parity, Secp256k1};
|
||||
use sdk_common::sp_client::bitcoin::secp256k1::{PublicKey, SecretKey, ThirtyTwoByteHash};
|
||||
use sdk_common::sp_client::bitcoin::{
|
||||
Network, OutPoint, ScriptBuf, Transaction, Txid, XOnlyPublicKey,
|
||||
};
|
||||
use sdk_common::sp_client::spclient::SpClient;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use tsify::Tsify;
|
||||
use wasm_bindgen::convert::VectorFromWasmAbi;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{Cursor, Read, Write};
|
||||
use std::str::FromStr;
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
|
||||
use sdk_common::device::Device;
|
||||
use sdk_common::sp_client::bitcoin::secp256k1::constants::SECRET_KEY_SIZE;
|
||||
use sdk_common::sp_client::silentpayments::bitcoin_hashes::sha256;
|
||||
use sdk_common::sp_client::silentpayments::utils::{Network as SpNetwork, SilentPaymentAddress};
|
||||
use sdk_common::sp_client::spclient::{OutputList, SpWallet, SpendKey};
|
||||
|
||||
use crate::peers::Peer;
|
||||
use crate::wallet::generate_sp_wallet;
|
||||
use crate::MutexExt;
|
||||
use sdk_common::crypto::{AeadCore, Aes256Gcm, KeyInit};
|
||||
|
||||
pub static LOCAL_DEVICE: OnceLock<Mutex<Device>> = OnceLock::new();
|
||||
|
||||
pub fn set_new_device(sp_wallet: SpWallet) -> Result<String> {
|
||||
let mut device = Device::new(sp_wallet);
|
||||
|
||||
let mut local_device = lock_local_device()?;
|
||||
if *local_device.get_wallet().get_client() != SpClient::default() {
|
||||
return Err(Error::msg("Device already initialized".to_owned()));
|
||||
} else {
|
||||
*local_device = device;
|
||||
}
|
||||
|
||||
let our_address = local_device
|
||||
.get_wallet()
|
||||
.get_client()
|
||||
.get_receiving_address();
|
||||
|
||||
Ok(our_address)
|
||||
}
|
||||
|
||||
pub fn lock_local_device() -> Result<MutexGuard<'static, Device>> {
|
||||
LOCAL_DEVICE
|
||||
.get_or_init(|| Mutex::new(Device::default()))
|
||||
.lock_anyhow()
|
||||
}
|
44
src/wallet.rs
Normal file
44
src/wallet.rs
Normal file
@ -0,0 +1,44 @@
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
sync::{Mutex, MutexGuard, OnceLock},
|
||||
};
|
||||
|
||||
use anyhow::Error;
|
||||
use rand::Rng;
|
||||
use sdk_common::sp_client::{
|
||||
bitcoin::{Network, OutPoint},
|
||||
silentpayments::utils::SilentPaymentAddress,
|
||||
spclient::{derive_keys_from_seed, SpClient, SpWallet, SpendKey},
|
||||
};
|
||||
|
||||
use crate::MutexExt;
|
||||
|
||||
pub static FREEZED_UTXOS: OnceLock<Mutex<HashSet<OutPoint>>> = OnceLock::new();
|
||||
|
||||
pub fn lock_freezed_utxos() -> Result<MutexGuard<'static, HashSet<OutPoint>>, Error> {
|
||||
FREEZED_UTXOS
|
||||
.get_or_init(|| Mutex::new(HashSet::new()))
|
||||
.lock_anyhow()
|
||||
}
|
||||
|
||||
pub fn generate_sp_wallet(label: Option<String>, network: Network) -> anyhow::Result<SpWallet> {
|
||||
let mut seed = [0u8; 64];
|
||||
rand::thread_rng().fill(&mut seed);
|
||||
let (scan_sk, spend_sk) = derive_keys_from_seed(&seed, network)?;
|
||||
let sp_client = SpClient::new(
|
||||
label.unwrap_or("default".into()),
|
||||
scan_sk,
|
||||
SpendKey::Secret(spend_sk),
|
||||
None,
|
||||
network,
|
||||
)?;
|
||||
let our_address: SilentPaymentAddress = sp_client.get_receiving_address().try_into()?;
|
||||
sdk_common::log::info!(
|
||||
"Created client for sp with address: {}",
|
||||
our_address.to_string()
|
||||
);
|
||||
|
||||
let res = SpWallet::new(sp_client, None, vec![])?;
|
||||
|
||||
Ok(res)
|
||||
}
|
@ -1,117 +0,0 @@
|
||||
import Services from "./services";
|
||||
import { AnkFlag, AnkNetworkMsg, CachedMessage } from "../dist/pkg/sdk_client";
|
||||
|
||||
class WebSocketClient {
|
||||
private ws: WebSocket;
|
||||
private messageQueue: string[] = [];
|
||||
|
||||
constructor(url: string, private services: Services) {
|
||||
this.ws = new WebSocket(url);
|
||||
|
||||
this.ws.addEventListener('open', (event) => {
|
||||
console.log('WebSocket connection established');
|
||||
// Once the connection is open, send all messages in the queue
|
||||
while (this.messageQueue.length > 0) {
|
||||
const message = this.messageQueue.shift();
|
||||
if (message) {
|
||||
this.ws.send(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for messages
|
||||
this.ws.addEventListener('message', (event) => {
|
||||
const msgData = event.data;
|
||||
|
||||
(async () => {
|
||||
if (typeof(msgData) === 'string') {
|
||||
console.log("Received text message: "+msgData);
|
||||
try {
|
||||
const feeRate = 1;
|
||||
// By parsing the message, we can link it with existing cached message and return the updated version of the message
|
||||
let res: CachedMessage = await services.parseNetworkMessage(msgData, feeRate);
|
||||
console.debug(res);
|
||||
if (res.status === 'FaucetComplete') {
|
||||
// we received a faucet tx, there's nothing else to do
|
||||
window.alert(`New faucet output\n${res.commited_in}`);
|
||||
await services.updateMessages(res);
|
||||
await services.updateOwnedOutputsForUser();
|
||||
} else if (res.status === 'TxWaitingCipher') {
|
||||
// we received a tx but we don't have the cipher
|
||||
console.debug(`received notification in output ${res.commited_in}, waiting for cipher message`);
|
||||
await services.updateMessages(res);
|
||||
await services.updateOwnedOutputsForUser();
|
||||
} else if (res.status === 'CipherWaitingTx') {
|
||||
// we received a cipher but we don't have the key
|
||||
console.debug(`received a cipher`);
|
||||
await services.updateMessages(res);
|
||||
} else if (res.status === 'SentWaitingConfirmation') {
|
||||
// We are sender and we're waiting for the challenge that will confirm recipient got the transaction and the message
|
||||
await services.updateMessages(res);
|
||||
await services.updateOwnedOutputsForUser();
|
||||
} else if (res.status === 'MustSpendConfirmation') {
|
||||
// we received a challenge for a notification we made
|
||||
// that means we can stop rebroadcasting the tx and we must spend the challenge to confirm
|
||||
window.alert(`Spending ${res.confirmed_by} to prove our identity`);
|
||||
console.debug(`sending confirm message to ${res.recipient}`);
|
||||
await services.updateMessages(res);
|
||||
await services.answer_confirmation_message(res);
|
||||
} else if (res.status === 'ReceivedMustConfirm') {
|
||||
// we found a notification and decrypted the cipher
|
||||
window.alert(`Received message from ${res.sender}\n${res.plaintext}`);
|
||||
// we must spend the commited_in output to sender
|
||||
await services.updateMessages(res);
|
||||
await services.confirm_sender_address(res);
|
||||
} else if (res.status === 'Complete') {
|
||||
window.alert(`Received confirmation that ${res.sender} is the author of message ${res.plaintext}`)
|
||||
await services.updateMessages(res);
|
||||
await services.updateOwnedOutputsForUser();
|
||||
} else {
|
||||
console.debug('Received an unimplemented valid message');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Received an invalid message:', error);
|
||||
}
|
||||
} else {
|
||||
console.error('Received a non-string message');
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
// Listen for possible errors
|
||||
this.ws.addEventListener('error', (event) => {
|
||||
console.error('WebSocket error:', event);
|
||||
});
|
||||
|
||||
// Listen for when the connection is closed
|
||||
this.ws.addEventListener('close', (event) => {
|
||||
console.log('WebSocket is closed now.');
|
||||
});
|
||||
}
|
||||
|
||||
// Method to send messages
|
||||
public sendMessage(flag: AnkFlag, message: string): void {
|
||||
if (this.ws.readyState === WebSocket.OPEN) {
|
||||
const networkMessage: AnkNetworkMsg = {
|
||||
'flag': flag,
|
||||
'content': message
|
||||
}
|
||||
// console.debug("Sending message:", JSON.stringify(networkMessage));
|
||||
this.ws.send(JSON.stringify(networkMessage));
|
||||
} else {
|
||||
console.warn('WebSocket is not open. ReadyState:', this.ws.readyState);
|
||||
this.messageQueue.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
public getUrl(): string {
|
||||
return this.ws.url;
|
||||
}
|
||||
|
||||
// Method to close the WebSocket connection
|
||||
public close(): void {
|
||||
this.ws.close();
|
||||
}
|
||||
}
|
||||
|
||||
export { WebSocketClient };
|
199
tests/connect.rs
Normal file
199
tests/connect.rs
Normal file
@ -0,0 +1,199 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use sdk_client::api::{
|
||||
create_connect_transaction, create_device_from_sp_wallet, dump_device, get_address, get_outputs, parse_cipher, reset_device, reset_shared_secrets, restore_device, set_shared_secrets, setup, ApiReturn
|
||||
};
|
||||
use sdk_common::log::debug;
|
||||
use sdk_common::pcd::Member;
|
||||
use sdk_common::secrets::SecretsStore;
|
||||
use sdk_common::sp_client::bitcoin::OutPoint;
|
||||
use sdk_common::sp_client::spclient::OwnedOutput;
|
||||
use sdk_common::sp_client::silentpayments::utils::SilentPaymentAddress;
|
||||
|
||||
use tsify::JsValueSerdeExt;
|
||||
use wasm_bindgen_test::*;
|
||||
|
||||
mod utils;
|
||||
|
||||
use utils::*;
|
||||
|
||||
wasm_bindgen_test_configure!(run_in_browser);
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
/// Tests the connection process between two devices, Alice and Bob, by executing a secure
|
||||
/// transaction to establish a shared secret for encrypted communication.
|
||||
///
|
||||
/// The basics are that one device will initiate the process by sending a transaction that pays another device.
|
||||
/// The recipient of the transaction as soon as it finds it, can extract a shared secret and send an encrypted
|
||||
/// message back. Upon receiving this message, the initiator answers with a similar message similarly encrypted.
|
||||
/// Upon receiving this message, the recipient can be assured that the communication is safe, and start using
|
||||
/// the secret to communicate.
|
||||
///
|
||||
/// The security of the shared secret rest on the soundness of the silent payment protocol for Bitcoin.
|
||||
/// In its encrypted response, the initiator adds a signature that is proof that it indeed controls the
|
||||
/// private key for the silent payment address it announced, so recipient knows there's no mitm or impostor.
|
||||
///
|
||||
/// # Detailed Process
|
||||
///
|
||||
/// ## Alice sends a transaction that pays Bob:
|
||||
/// - Alice initializes her device from an `sp_wallet` object and sets it as the local device.
|
||||
/// - She retrieves her own address and obtains Bob’s address.
|
||||
/// - Alice creates a new member using Bob’s device address (this is mainly for testing purpose,
|
||||
/// because `create_connection_transaction` would take members as argument).
|
||||
/// - She generates a connection transaction (`connect_tx`) targeting Bob's device.
|
||||
/// - Alice processes her own transaction and stores the derived shared secrets in `alice_secrets_store`,
|
||||
/// associating the shared secret with Bob's addresses.
|
||||
///
|
||||
/// ## Bob parses the transaction:
|
||||
/// - Bob initializes his device from his own `sp_wallet`.
|
||||
/// - He parses Alice’s connection transaction to retrieve the shared secret Alice created for him.
|
||||
/// - Bob saves these derived shared secrets in `bob_secrets_store` but can't index it with Alice's address yet.
|
||||
///
|
||||
/// ## Prd Connect exchange
|
||||
/// - Bob then responds by sending a prd connect back to Alice encrypted with the shared secret.
|
||||
/// This prd is very simple and basically contains the following:
|
||||
/// * All Bob's devices addresses
|
||||
/// * a commitment to the shared secret
|
||||
/// * a proof signed with Bob's device spend key
|
||||
/// - Alice receives and decrypts the message from Bob.
|
||||
/// - She replies to Bob by encrypting another prd connect which is basically the same, but keeping Bob's proof and adding her own.
|
||||
/// - **Bob’s Confirmation**: Bob receives Alice’s confirmation message, decrypts it, and updates his secret in `bob_secrets_store`.
|
||||
///
|
||||
/// ## Verification:
|
||||
/// - Finally, the function asserts that Alice and Bob now share the same secrets, confirming successful
|
||||
/// connection and mutual authentication between the devices.
|
||||
fn test_connect() {
|
||||
setup();
|
||||
let mut alice_secrets_store = SecretsStore::new();
|
||||
let mut bob_secrets_store = SecretsStore::new();
|
||||
|
||||
debug!("==============================================\nStarting test_connect\n==============================================");
|
||||
|
||||
// ========================= Alice
|
||||
reset_device().unwrap();
|
||||
create_device_from_sp_wallet(ALICE_LOGIN_WALLET.to_owned()).unwrap();
|
||||
|
||||
// we get our own address
|
||||
let alice_address = get_address().unwrap();
|
||||
|
||||
// we scan the qr code or get the address by any other means
|
||||
let bob_address = helper_get_bob_address();
|
||||
|
||||
debug!("Alice establishes a shared secret with Bob");
|
||||
// We just send a transaction to Bob device to allow them to share encrypted message
|
||||
// Since we're not paired we can just put bob's address in a disposable member
|
||||
// create_connect_transaction needs to take members though because most of the time we'd rather create secrets with all the devices of a member
|
||||
let bob_member = Member::new(vec![SilentPaymentAddress::try_from(bob_address.as_str()).unwrap()]).unwrap();
|
||||
let alice_connect_return = create_connect_transaction(vec![serde_json::to_string(&bob_member).unwrap()], 1).unwrap();
|
||||
|
||||
debug!("alice_connect_return: {:#?}", alice_connect_return);
|
||||
|
||||
let connect_tx_msg = alice_connect_return.new_tx_to_send.unwrap();
|
||||
|
||||
// This is only for testing, the relay takes care of that in prod
|
||||
let get_outputs_result = get_outputs().unwrap();
|
||||
|
||||
let alice_outputs: HashMap<OutPoint, OwnedOutput> = get_outputs_result.into_serde().unwrap();
|
||||
|
||||
let alice_pairing_tweak_data =
|
||||
helper_get_tweak_data(&connect_tx_msg.transaction, alice_outputs);
|
||||
|
||||
// End of the test only part
|
||||
|
||||
// Alice parses her own transaction
|
||||
helper_parse_transaction(&connect_tx_msg.transaction, &alice_pairing_tweak_data);
|
||||
|
||||
let alice_connect_transaction = connect_tx_msg.transaction;
|
||||
|
||||
let alice_device = dump_device().unwrap();
|
||||
|
||||
// Below is how to update our secrets store when secrets is Some
|
||||
let secrets_update = alice_connect_return.secrets.unwrap();
|
||||
let unconfirmed_secrets = secrets_update.get_all_unconfirmed_secrets();
|
||||
if !unconfirmed_secrets.is_empty() {
|
||||
for secret in unconfirmed_secrets {
|
||||
alice_secrets_store.add_unconfirmed_secret(secret);
|
||||
}
|
||||
}
|
||||
let updated_confirmed_secrets = secrets_update.get_all_confirmed_secrets();
|
||||
if !updated_confirmed_secrets.is_empty() {
|
||||
for (address, secret) in updated_confirmed_secrets {
|
||||
alice_secrets_store.confirm_secret_for_address(secret, address);
|
||||
}
|
||||
}
|
||||
|
||||
// ======================= Bob
|
||||
reset_device().unwrap();
|
||||
reset_shared_secrets().unwrap();
|
||||
create_device_from_sp_wallet(BOB_LOGIN_WALLET.to_owned()).unwrap();
|
||||
|
||||
debug!("Bob parses Alice connect transaction");
|
||||
let bob_parsed_transaction_return = helper_parse_transaction(&alice_connect_transaction, &alice_pairing_tweak_data);
|
||||
|
||||
let bob_to_alice_cipher = &bob_parsed_transaction_return.ciphers_to_send[0];
|
||||
|
||||
let bob_device = dump_device().unwrap();
|
||||
let updated_secrets = bob_parsed_transaction_return.secrets.unwrap();
|
||||
let updated_unconfirmed_secrets = updated_secrets.get_all_unconfirmed_secrets();
|
||||
if !updated_unconfirmed_secrets.is_empty() {
|
||||
for secret in updated_unconfirmed_secrets {
|
||||
bob_secrets_store.add_unconfirmed_secret(secret);
|
||||
}
|
||||
}
|
||||
let updated_confirmed_secrets = updated_secrets.get_all_confirmed_secrets();
|
||||
if !updated_confirmed_secrets.is_empty() {
|
||||
for (address, secret) in updated_confirmed_secrets {
|
||||
bob_secrets_store.confirm_secret_for_address(secret, address);
|
||||
}
|
||||
}
|
||||
|
||||
// ======================= Alice
|
||||
reset_device().unwrap();
|
||||
restore_device(alice_device).unwrap();
|
||||
set_shared_secrets(serde_json::to_string(&alice_secrets_store).unwrap()).unwrap();
|
||||
|
||||
debug!("Alice receives the connect Prd");
|
||||
let alice_parsed_connect = parse_cipher(bob_to_alice_cipher.clone()).unwrap();
|
||||
|
||||
// debug!("alice_parsed_confirm: {:#?}", alice_parsed_confirm);
|
||||
|
||||
let alice_to_bob_cipher = alice_parsed_connect.ciphers_to_send.get(0).unwrap();
|
||||
let secrets_update = alice_parsed_connect.secrets.unwrap();
|
||||
let unconfirmed_secrets = secrets_update.get_all_unconfirmed_secrets();
|
||||
if !unconfirmed_secrets.is_empty() {
|
||||
for secret in unconfirmed_secrets {
|
||||
alice_secrets_store.add_unconfirmed_secret(secret);
|
||||
}
|
||||
}
|
||||
let updated_confirmed_secrets = secrets_update.get_all_confirmed_secrets();
|
||||
if !updated_confirmed_secrets.is_empty() {
|
||||
for (address, secret) in updated_confirmed_secrets {
|
||||
alice_secrets_store.confirm_secret_for_address(secret, address);
|
||||
}
|
||||
}
|
||||
|
||||
// ======================= Bob
|
||||
reset_device().unwrap();
|
||||
restore_device(bob_device).unwrap();
|
||||
set_shared_secrets(serde_json::to_string(&bob_secrets_store).unwrap()).unwrap();
|
||||
|
||||
debug!("Bob parses alice prd connect");
|
||||
let bob_parsed_connect = parse_cipher(alice_to_bob_cipher.clone()).unwrap();
|
||||
|
||||
let updated_secrets = bob_parsed_connect.secrets.unwrap();
|
||||
let updated_unconfirmed_secrets = updated_secrets.get_all_unconfirmed_secrets();
|
||||
if !updated_unconfirmed_secrets.is_empty() {
|
||||
for secret in updated_unconfirmed_secrets {
|
||||
bob_secrets_store.add_unconfirmed_secret(secret);
|
||||
}
|
||||
}
|
||||
let updated_confirmed_secrets = updated_secrets.get_all_confirmed_secrets();
|
||||
if !updated_confirmed_secrets.is_empty() {
|
||||
for (address, secret) in updated_confirmed_secrets {
|
||||
bob_secrets_store.confirm_secret_for_address(secret, address);
|
||||
}
|
||||
}
|
||||
|
||||
// Assert that Alice and Bob now has the same secret
|
||||
assert!(alice_secrets_store.get_secret_for_address(bob_address.try_into().unwrap()) == bob_secrets_store.get_secret_for_address(alice_address.try_into().unwrap()));
|
||||
}
|
317
tests/pairing.rs
Normal file
317
tests/pairing.rs
Normal file
@ -0,0 +1,317 @@
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
|
||||
use sdk_client::api::{
|
||||
create_device_from_sp_wallet, create_new_process, create_response_prd, create_update_message, dump_device, get_address, pair_device, parse_cipher, reset_device, restore_device, set_process_cache, set_shared_secrets, setup, update_process_state, validate_state
|
||||
};
|
||||
use sdk_common::crypto::AnkSharedSecretHash;
|
||||
use sdk_common::log::debug;
|
||||
use sdk_common::pcd::{Member, Pcd, RoleDefinition};
|
||||
use sdk_common::secrets::SecretsStore;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use wasm_bindgen_test::*;
|
||||
|
||||
mod utils;
|
||||
|
||||
use utils::*;
|
||||
|
||||
wasm_bindgen_test_configure!(run_in_browser);
|
||||
|
||||
/// # Pairing Process Documentation between Alice and Bob
|
||||
///
|
||||
/// This test describes the secure pairing process between two devices, Alice and Bob.
|
||||
///
|
||||
/// ## What's pairing?
|
||||
/// Pairing is a process, and abide by the same rules than any other process. The goal of pairing
|
||||
/// is to define an identity on the network as a set of devices (defined by their sp_address).
|
||||
/// Being a process it is public and can be audited by anyone, and be used as one's proof of identity.
|
||||
/// It also contains a session keypair that is updated as necessary. Since all devices are needed to
|
||||
/// update the key in the process it can then be used to sign a proof that someone was indeed in control
|
||||
/// of all the devices for some amount of time in a MFA setup.
|
||||
/// It contains the following mandatory fields:
|
||||
/// * `roles`: multiple devices represented as sp adresses linked together in the same member. It is recommended
|
||||
/// to have one `owner` role with one member which is the actual identity and whose signatures are all
|
||||
/// needed to modify anything in the process.
|
||||
/// * `session_privkey`: a private key visible by all devices of the member defined in the process, but
|
||||
/// not by other members. It *must* be changed at every update of the process. This key will be used
|
||||
/// to sign documents and validate actions for other processes. It's valid as soon as the commitment
|
||||
/// transaction for the process udpate is seen and it stays valid for _n_ blocks after the update being mined.
|
||||
/// * `session_pubkey`: the x-only public key derived from the session private key. It's visible by everyone and
|
||||
/// used for validation by any third party. Obviously it changes with the private key at any update.
|
||||
/// * `parity`: the parity of the session_pubkey. We could use 33 bytes compressed public key format
|
||||
/// but using 32 bytes publick key + parity allows for more standard serialization.
|
||||
///
|
||||
/// ## Detailed protocol
|
||||
/// (Here Alice and Bob are used as a convention, but keep in mind they're not 2 different users, but
|
||||
/// 2 devices belonging to the same user)
|
||||
/// ## Step 0 - Preliminary step
|
||||
/// 1. **Establishing a Shared Secret**: A shared secret is established to secure
|
||||
/// communication between Alice and Bob (see `connect.rs`).
|
||||
/// ## Step 1 - Pairing Preparation by Alice
|
||||
/// 1. **Pairing Status Check**: Alice verifies that it's not already paired.
|
||||
/// 2. **Adding Bob's Address**: Alice adds Bob’s address to her own, setting the base for creating
|
||||
/// a new `Member` object.
|
||||
/// 3. **Creation of the pairing process**: Alice initializes pairing by creating a prd update that contains
|
||||
/// both its address and Bob's, and send it to Bob.
|
||||
///
|
||||
/// ## Step 2 - Receiving and Confirming the `prd` by Bob
|
||||
/// 1. **Receiving and Verifying**: Bob receives and decrypts the update `prd` message sent by Alice.
|
||||
/// 2. **Updating Process State**: Bob identifies the new process and store it, but it doesn't have access
|
||||
/// to the actual data for now.
|
||||
/// 3. **Creating and Sending `Prd Confirm`**: Bob creates a confirmation `prd`, which he then
|
||||
/// sends to Alice to get the pcd containing the state for this new process.
|
||||
///
|
||||
/// ## Step 3 - Alice gets confirmation and answers with a pcd
|
||||
/// 1. **Receiving and Verifying**: Alice receives the `Prd Confirm` sent by Bob.
|
||||
/// 2. **Sending PCD**: Alice having confirmation that Bob got the update proposal,
|
||||
/// it now sends the actual data in a pcd.
|
||||
/// 3. **User confirmation**: At this step we must get the approval of the user. If user confirms
|
||||
/// the pairing we create a prd response with a valid signature from Alice spend key and send
|
||||
/// it to Bob.
|
||||
///
|
||||
/// ## Step 4 - Finalizing Pairing by Bob
|
||||
/// 1. **Receiving and Verifying `pcd`**: Bob received the `pcd` and only now can tell what's the
|
||||
/// process was about.
|
||||
/// 2. **Validating Pairing State**: Bob retrieves the latest process state and the state change
|
||||
/// request, in this case, the pairing. User is prompted for validation, and if confirmed a prd response
|
||||
/// is created and sent(see the **User confirmation** step for Alice).
|
||||
///
|
||||
/// ## Commiting the process state
|
||||
/// 1. **Creating the `commit_msg`**: The first device that got both validations creates the commit_msg that
|
||||
/// contains a transaction paying a relay to generate the first outpoint to commit the state of the process,
|
||||
/// the hash of the encrypted state of the process (relay must have access to roles though, either it is clear
|
||||
/// all along or it was provided with the encryption keys) and the proofs that all devices validated this state.
|
||||
/// 2. **Actual commitment**: As soon as the relay validated the proofs it spends the outpoint and puts the hash of
|
||||
/// the whole prd response (including pcd hash and all the proofs) in an OP_RETURN output. The process is now
|
||||
/// public and can be used to prove identity for other processes.
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_pairing() {
|
||||
const RELAY_ADDRESS: &str = "tsp1qqvfm6wvd55r68ltysdhmagg7qavxrzlmm9a7tujsp8qqy6x2vr0muqajt5p2jdxfw450wyeygevypxte29sxlxzgprmh2gwnutnt09slrcqqy5h4";
|
||||
|
||||
setup();
|
||||
let mut alice_process_cache = HashMap::new();
|
||||
let mut bob_process_cache = HashMap::new();
|
||||
let mut alice_secrets_store = SecretsStore::new();
|
||||
let mut bob_secrets_store = SecretsStore::new();
|
||||
let mut alice_diff_cache = Vec::new();
|
||||
let mut bob_diff_cache = Vec::new();
|
||||
|
||||
debug!("==============================================\nStarting test_pairing\n==============================================");
|
||||
|
||||
// ========================= Alice
|
||||
reset_device().unwrap();
|
||||
create_device_from_sp_wallet(ALICE_LOGIN_WALLET.to_owned()).unwrap();
|
||||
|
||||
// we get our own address
|
||||
let alice_address = get_address().unwrap();
|
||||
debug!("alice address: {}", alice_address);
|
||||
|
||||
// we scan the qr code or get the address by any other means
|
||||
let bob_address = helper_get_bob_address();
|
||||
debug!("bob_address: {}", bob_address);
|
||||
|
||||
// we add some shared_secret in both secrets_store
|
||||
let shared_secret = AnkSharedSecretHash::from_str("c3f1a64e15d2e8d50f852c20b7f0b47cbe002d9ef80bc79582d09d6f38612d45").unwrap();
|
||||
alice_secrets_store.confirm_secret_for_address(shared_secret, bob_address.as_str().try_into().unwrap());
|
||||
bob_secrets_store.confirm_secret_for_address(shared_secret, alice_address.as_str().try_into().unwrap());
|
||||
|
||||
set_shared_secrets(serde_json::to_string(&alice_secrets_store).unwrap()).unwrap();
|
||||
|
||||
// Alice creates the new member with Bob address
|
||||
let new_member = Member::new(vec![
|
||||
alice_address.as_str().try_into().unwrap(),
|
||||
bob_address.as_str().try_into().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let initial_session_privkey = [0u8; 32]; // In reality we would generate a random new key here
|
||||
let initial_session_pubkey = [0u8; 32];
|
||||
|
||||
let pairing_init_state = json!({
|
||||
"html": "",
|
||||
"js": "",
|
||||
"style": "",
|
||||
"zones": [],
|
||||
"description": "AliceBob",
|
||||
"roles": {
|
||||
"owner": {
|
||||
"members":
|
||||
[
|
||||
new_member
|
||||
],
|
||||
"validation_rules":
|
||||
[
|
||||
{
|
||||
"quorum": 1.0,
|
||||
"fields": [
|
||||
"description",
|
||||
"roles",
|
||||
"session_privkey",
|
||||
"session_pubkey",
|
||||
"key_parity"
|
||||
],
|
||||
"min_sig_member": 1.0
|
||||
}
|
||||
],
|
||||
"storages": []
|
||||
}
|
||||
},
|
||||
"session_privkey": initial_session_privkey,
|
||||
"session_pubkey": initial_session_pubkey,
|
||||
"key_parity": true, // This allows us to use a 32 bytes array in serialization
|
||||
});
|
||||
|
||||
debug!("Alice creates the pairing process");
|
||||
let create_process_return = create_new_process(pairing_init_state.to_string(), None, RELAY_ADDRESS.to_owned(), 1).unwrap();
|
||||
|
||||
let commit_msg = create_process_return.commit_to_send.unwrap();
|
||||
|
||||
let secrets_update = create_process_return.secrets.unwrap();
|
||||
let unconfirmed_secrets = secrets_update.get_all_unconfirmed_secrets();
|
||||
if !unconfirmed_secrets.is_empty() {
|
||||
for secret in unconfirmed_secrets {
|
||||
alice_secrets_store.add_unconfirmed_secret(secret);
|
||||
}
|
||||
}
|
||||
let updated_confirmed_secrets = secrets_update.get_all_confirmed_secrets();
|
||||
if !updated_confirmed_secrets.is_empty() {
|
||||
for (address, secret) in updated_confirmed_secrets {
|
||||
alice_secrets_store.confirm_secret_for_address(secret, address);
|
||||
}
|
||||
}
|
||||
|
||||
let updated_process = create_process_return.updated_process.unwrap();
|
||||
alice_process_cache.insert(updated_process.commitment_tx, updated_process.current_process);
|
||||
|
||||
// Alice keeps track of the change she needs to validate
|
||||
let create_process_diffs = updated_process.new_diffs;
|
||||
|
||||
let new_state_id = &create_process_diffs.get(0).unwrap().state_id;
|
||||
|
||||
alice_diff_cache.extend(create_process_diffs.iter());
|
||||
|
||||
// We send the commit_msg to the relay we got the address from
|
||||
|
||||
// now we create prd update for this new process
|
||||
debug!("Alice creates an update prd to Bob");
|
||||
let create_update_return = create_update_message(updated_process.commitment_tx.to_string(), new_state_id.clone()).unwrap();
|
||||
|
||||
let updated_process = create_update_return.updated_process.unwrap();
|
||||
alice_process_cache.insert(updated_process.commitment_tx, updated_process.current_process);
|
||||
|
||||
debug!("Alice pairs her device");
|
||||
pair_device(updated_process.commitment_tx.to_string(), vec![helper_get_bob_address()]).unwrap();
|
||||
|
||||
let alice_to_bob_cipher = &create_update_return.ciphers_to_send[0];
|
||||
|
||||
// this is only for testing, as we're playing both parts
|
||||
let alice_device = dump_device().unwrap();
|
||||
|
||||
// ======================= Bob
|
||||
reset_device().unwrap();
|
||||
create_device_from_sp_wallet(BOB_LOGIN_WALLET.to_owned()).unwrap();
|
||||
set_shared_secrets(serde_json::to_string(&bob_secrets_store).unwrap()).unwrap();
|
||||
|
||||
debug!("Bob receives the update prd");
|
||||
let bob_parsed_return = parse_cipher(alice_to_bob_cipher.to_owned()).unwrap();
|
||||
|
||||
let updated_process = bob_parsed_return.updated_process.unwrap();
|
||||
|
||||
let parsed_prd_diffs = updated_process.new_diffs;
|
||||
|
||||
// debug!("Bob creates process {} with state {}", updated_process.commitment_tx, new_state_id);
|
||||
bob_process_cache.insert(updated_process.commitment_tx, updated_process.current_process);
|
||||
|
||||
// Bob also keeps track of changes
|
||||
|
||||
bob_diff_cache.extend(parsed_prd_diffs.into_iter());
|
||||
|
||||
debug!("Bob can now fetch the data from storage using the hashes");
|
||||
// We have to cheat here and let Bob access Alice process cache
|
||||
let process = alice_process_cache.get(&updated_process.commitment_tx).unwrap();
|
||||
|
||||
let state = process.get_state_for_id(&new_state_id).unwrap();
|
||||
|
||||
let hash2values: Map<String, Value> = bob_diff_cache.iter()
|
||||
.filter(|diff| diff.state_id == *new_state_id)
|
||||
.map(|diff| {
|
||||
let encrypted_value = state.encrypted_pcd.as_object().unwrap().get(&diff.field).unwrap();
|
||||
(diff.value_commitment.clone(), encrypted_value.clone())
|
||||
})
|
||||
.collect();
|
||||
let update_process_res = update_process_state(updated_process.commitment_tx.to_string(), new_state_id.clone(), serde_json::to_string(&Value::Object(hash2values)).unwrap()).unwrap();
|
||||
|
||||
let updated_process = update_process_res.updated_process.unwrap();
|
||||
|
||||
let parsed_prd_diffs = updated_process.new_diffs;
|
||||
|
||||
bob_process_cache.insert(updated_process.commitment_tx, updated_process.current_process);
|
||||
|
||||
bob_diff_cache.extend(parsed_prd_diffs);
|
||||
|
||||
// We can also prune the old diffs from the cache
|
||||
bob_diff_cache.retain(|diff| diff.new_value != Value::Null);
|
||||
|
||||
// this is only for testing, as we're playing both parts
|
||||
let bob_device = dump_device().unwrap();
|
||||
|
||||
// ======================= Alice
|
||||
reset_device().unwrap();
|
||||
restore_device(alice_device).unwrap();
|
||||
set_process_cache(serde_json::to_string(&alice_process_cache).unwrap()).unwrap();
|
||||
set_shared_secrets(serde_json::to_string(&alice_secrets_store).unwrap()).unwrap();
|
||||
|
||||
let commitment_outpoint = alice_process_cache.keys().next().unwrap();
|
||||
|
||||
debug!("Alice can validate the new state of the process");
|
||||
let relevant_process = alice_process_cache.get(&commitment_outpoint).unwrap();
|
||||
|
||||
for diff in alice_diff_cache {
|
||||
debug!("User validate diff: {:#?}", diff);
|
||||
}
|
||||
|
||||
// Alice can also sign her response and send it to Bob
|
||||
let validate_state_return = validate_state(commitment_outpoint.to_string(), new_state_id.clone()).unwrap();
|
||||
|
||||
let updated_process = validate_state_return.updated_process.unwrap();
|
||||
|
||||
alice_process_cache.insert(updated_process.commitment_tx, updated_process.current_process);
|
||||
|
||||
let alice_response = create_response_prd(updated_process.commitment_tx.to_string(), new_state_id.clone()).unwrap();
|
||||
|
||||
// ======================= Bob
|
||||
reset_device().unwrap();
|
||||
restore_device(bob_device).unwrap();
|
||||
set_process_cache(serde_json::to_string(&bob_process_cache).unwrap()).unwrap();
|
||||
set_shared_secrets(serde_json::to_string(&bob_secrets_store).unwrap()).unwrap();
|
||||
|
||||
for diff in &bob_diff_cache {
|
||||
if diff.need_validation {
|
||||
debug!("Pop-up: User confirmation");
|
||||
debug!("{:#?}", diff);
|
||||
}
|
||||
}
|
||||
|
||||
// If user is ok, we can add our own validation token
|
||||
// Get the whole commitment from the process
|
||||
let bob_validated_process = validate_state(updated_process.commitment_tx.to_string(), new_state_id.clone()).unwrap();
|
||||
|
||||
let updated_process = bob_validated_process.updated_process.unwrap();
|
||||
|
||||
bob_process_cache.insert(updated_process.commitment_tx, updated_process.current_process);
|
||||
|
||||
let bob_response = create_response_prd(updated_process.commitment_tx.to_string(), new_state_id.clone()).unwrap();
|
||||
|
||||
let ciphers = bob_response.ciphers_to_send; // We would send it to Alice to let her know we agree
|
||||
|
||||
debug!("Bob pairs device with Alice");
|
||||
let roles: HashMap<String, RoleDefinition> = serde_json::from_value(bob_diff_cache.iter().find(|diff| diff.field == "roles").unwrap().new_value.clone()).unwrap();
|
||||
let owner = roles.get("owner").unwrap();
|
||||
let members_to_pair: Vec<String> = owner.members.iter().flat_map(|m| m.get_addresses()).collect();
|
||||
pair_device(updated_process.commitment_tx.to_string(), members_to_pair).unwrap();
|
||||
|
||||
// We can also check alice response
|
||||
let parsed_alice_response = parse_cipher(alice_response.ciphers_to_send[0].clone()).unwrap();
|
||||
}
|
77
tests/utils.rs
Normal file
77
tests/utils.rs
Normal file
@ -0,0 +1,77 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use sdk_client::api::{parse_new_tx, ApiReturn};
|
||||
use sdk_common::network::NewTxMessage;
|
||||
use sdk_common::sp_client::bitcoin::consensus::{deserialize, serialize};
|
||||
use sdk_common::sp_client::bitcoin::hex::{DisplayHex, FromHex};
|
||||
use sdk_common::sp_client::bitcoin::secp256k1::PublicKey;
|
||||
use sdk_common::sp_client::bitcoin::{OutPoint, ScriptBuf, Transaction};
|
||||
use sdk_common::sp_client::silentpayments::utils::receiving::{
|
||||
calculate_tweak_data, get_pubkey_from_input,
|
||||
};
|
||||
use sdk_common::sp_client::spclient::{OwnedOutput, SpWallet};
|
||||
use serde_json::{self, json, Value};
|
||||
|
||||
// We're using alice and bob for clarity, but it's important to remember that for pairing and login Alice and Bob are the same person
|
||||
pub const ALICE_START_WALLET: &str = "{\"client\":{\"network\":\"testnet\",\"label\":\"default\",\"scan_sk\":\"e3d8922a41a7cb1a84a90f4334e987bb5ea2df6a1fdf44f789b5302de119f9e2\",\"spend_key\":{\"Secret\":\"93292e5b21042c6cfc742ba30e9d2a1e01609b12d154a1825184ed12c7b9631b\"},\"mnemonic\":null,\"sp_receiver\":{\"version\":0,\"network\":\"Testnet\",\"scan_pubkey\":[2,104,242,105,185,6,124,208,34,44,149,52,163,38,63,221,150,12,198,24,95,143,126,235,37,149,233,88,118,32,86,233,152],\"spend_pubkey\":[3,198,82,196,243,12,59,126,109,143,144,157,128,176,168,94,54,134,232,139,115,102,11,178,128,244,239,251,40,228,67,153,72],\"change_label\":\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",\"labels\":[[\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",[2,244,223,255,57,50,216,27,133,112,138,69,120,126,85,110,6,242,141,33,136,191,82,164,241,54,179,115,84,161,145,174,154]]]}},\"outputs\":{\"wallet_fingerprint\":[187,119,108,230,171,125,106,11],\"birthday\":1620,\"last_scan\":2146,\"outputs\":{\"9a4a67cc5a40bf882d8b300d91024d7c97024b3b68b2df7745a5b9ea1df1888c:1\":{\"blockheight\":1620,\"tweak\":\"b8b63b3ed97d297b744135cfac2fb4a344c881a77543b71f1fcd16bc67514f26\",\"amount\":3938643,\"script\":\"51205b7b324bb71d411e32f2c61fda5d1db23f5c7d6d416a77fab87c913a1b120be1\",\"label\":\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",\"spend_status\":\"Unspent\"}}},\"tx_history\":[]}";
|
||||
pub const ALICE_LOGIN_WALLET: &str = "{\"client\":{\"label\":\"default\",\"scan_sk\":\"e3d8922a41a7cb1a84a90f4334e987bb5ea2df6a1fdf44f789b5302de119f9e2\",\"spend_key\":{\"Secret\":\"93292e5b21042c6cfc742ba30e9d2a1e01609b12d154a1825184ed12c7b9631b\"},\"mnemonic\":null,\"sp_receiver\":{\"version\":0,\"network\":\"Testnet\",\"scan_pubkey\":[2,104,242,105,185,6,124,208,34,44,149,52,163,38,63,221,150,12,198,24,95,143,126,235,37,149,233,88,118,32,86,233,152],\"spend_pubkey\":[3,198,82,196,243,12,59,126,109,143,144,157,128,176,168,94,54,134,232,139,115,102,11,178,128,244,239,251,40,228,67,153,72],\"change_label\":\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",\"labels\":[[\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",[2,244,223,255,57,50,216,27,133,112,138,69,120,126,85,110,6,242,141,33,136,191,82,164,241,54,179,115,84,161,145,174,154]]]},\"network\":\"testnet\"},\"outputs\":{\"wallet_fingerprint\":[187,119,108,230,171,125,106,11],\"birthday\":1620,\"last_scan\":2146,\"outputs\":{\"e2c6ff9927c8a5f7a60087117732c07ab7cd82c0c65462e9c780eb5ce9c35292:1\":{\"blockheight\":0,\"tweak\":\"7c84a3074c18c23a65eceaca49a327989ef6e7240e0e080421afb80f06906d73\",\"amount\":306,\"script\":\"5120eb78084d7a2ccbdb7eb7e9bba7cf875c4e54a5aba0beac57c5d3e41133bd8fdd\",\"label\":null,\"spend_status\":\"Unspent\"},\"e2c6ff9927c8a5f7a60087117732c07ab7cd82c0c65462e9c780eb5ce9c35292:2\":{\"blockheight\":0,\"tweak\":\"e3e21d551e933199f8c977bc0362616bdfb128da7ca9728bd7254977541c39cc\",\"amount\":3936897,\"script\":\"5120df3af55a63bd056c5d6d09f47a3a19c382d938c08db8bc41a59c5235970209ad\",\"label\":\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",\"spend_status\":\"Unspent\"},\"576c2e53fe924d68deb7262cfc0e4023b5889652dec35671e1e7cf255d61c28f:0\":{\"blockheight\":0,\"tweak\":\"6e5c1d4690b9ff4fa26e5185ada25af5c2987650e629a518db8a43fdaad7a26c\",\"amount\":349,\"script\":\"512088ac90e180c87b7fa6aa33db4c72a8620cd08fda3ba1c71430b904eb068c587f\",\"label\":null,\"spend_status\":\"Unspent\"},\"9a4a67cc5a40bf882d8b300d91024d7c97024b3b68b2df7745a5b9ea1df1888c:1\":{\"blockheight\":1620,\"tweak\":\"b8b63b3ed97d297b744135cfac2fb4a344c881a77543b71f1fcd16bc67514f26\",\"amount\":3938643,\"script\":\"51205b7b324bb71d411e32f2c61fda5d1db23f5c7d6d416a77fab87c913a1b120be1\",\"label\":\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",\"spend_status\":{\"Spent\":\"e2c6ff9927c8a5f7a60087117732c07ab7cd82c0c65462e9c780eb5ce9c35292\"}}}},\"tx_history\":[]}";
|
||||
pub const BOB_START_WALLET: &str = "{\"client\":{\"label\":\"default\",\"scan_sk\":\"0de90b7195c1380d5fde13de3f1d66d53423a9896314839e36ba672653af60b4\",\"spend_key\":{\"Secret\":\"affe686075ecbe17b8ce7de45ec31314804259d0a4bc1c863de21ffd6dc598f8\"},\"mnemonic\":null,\"sp_receiver\":{\"version\":0,\"network\":\"Testnet\",\"scan_pubkey\":[2,85,96,92,243,247,237,192,205,9,178,146,101,237,132,232,15,2,69,138,31,118,76,140,142,207,90,13,192,94,254,150,133],\"spend_pubkey\":[3,5,157,91,250,169,41,61,190,37,30,98,152,253,180,138,250,86,162,102,82,148,130,220,44,153,127,83,43,246,93,17,232],\"change_label\":\"56572fc770b52096879662f97f98263d3e126f5a4a38f00f2895a9dde4c47c1c\",\"labels\":[[\"56572fc770b52096879662f97f98263d3e126f5a4a38f00f2895a9dde4c47c1c\",[2,237,237,247,213,154,87,34,239,168,235,87,122,152,94,41,35,101,184,201,58,201,6,185,58,157,52,208,129,167,2,224,198]]]},\"network\":\"testnet\"},\"outputs\":{\"wallet_fingerprint\":[203,200,4,248,139,36,241,232],\"birthday\":2146,\"last_scan\":2146,\"outputs\":{\"fbd9c63e0dd08c2569b51a0d6095a79ee2acfcac66acdb594328a095f1fadb63:1\":{\"blockheight\":2146,\"tweak\":\"678dbcbdb40cd3733c8dbbd508761a0937009cf75a9f466e3c98877e79037cbc\",\"amount\":99896595,\"script\":\"5120deab0c5a3d23de30477b0b5a95a261c96e29afdd9813c665d2bf025ad2b3f919\",\"label\":null,\"spend_status\":\"Unspent\"}}},\"tx_history\":[]}";
|
||||
pub const BOB_LOGIN_WALLET: &str = "{\"client\":{\"label\":\"default\",\"scan_sk\":\"0de90b7195c1380d5fde13de3f1d66d53423a9896314839e36ba672653af60b4\",\"spend_key\":{\"Secret\":\"affe686075ecbe17b8ce7de45ec31314804259d0a4bc1c863de21ffd6dc598f8\"},\"mnemonic\":null,\"sp_receiver\":{\"version\":0,\"network\":\"Testnet\",\"scan_pubkey\":[2,85,96,92,243,247,237,192,205,9,178,146,101,237,132,232,15,2,69,138,31,118,76,140,142,207,90,13,192,94,254,150,133],\"spend_pubkey\":[3,5,157,91,250,169,41,61,190,37,30,98,152,253,180,138,250,86,162,102,82,148,130,220,44,153,127,83,43,246,93,17,232],\"change_label\":\"56572fc770b52096879662f97f98263d3e126f5a4a38f00f2895a9dde4c47c1c\",\"labels\":[[\"56572fc770b52096879662f97f98263d3e126f5a4a38f00f2895a9dde4c47c1c\",[2,237,237,247,213,154,87,34,239,168,235,87,122,152,94,41,35,101,184,201,58,201,6,185,58,157,52,208,129,167,2,224,198]]]},\"network\":\"testnet\"},\"outputs\":{\"wallet_fingerprint\":[203,200,4,248,139,36,241,232],\"birthday\":2146,\"last_scan\":2146,\"outputs\":{\"93722ea2fb9b74954210b4cdd1360e280b7ff1bc156d6b75f847e62411c588fb:0\":{\"blockheight\":0,\"tweak\":\"da5e3aa2378e3a257f99eb1e0ae4c672916f6a2f32a8ed9a8e146f2074da981b\",\"amount\":443,\"script\":\"51209eb9e950127b6a7d81668f25b4d5b164b42dafe59ce40b80e6c489ec983540d7\",\"label\":null,\"spend_status\":\"Unspent\"},\"e2c6ff9927c8a5f7a60087117732c07ab7cd82c0c65462e9c780eb5ce9c35292:0\":{\"blockheight\":0,\"tweak\":\"0e3395ff27bde9187ffaeeb2521f6277d3b83911f16ccbaf59a1a68d99a0ab93\",\"amount\":1200,\"script\":\"512010f06f764cbc923ec3198db946307bf0c06a1b4f09206055e47a6fec0a33d52c\",\"label\":null,\"spend_status\":{\"Spent\":\"576c2e53fe924d68deb7262cfc0e4023b5889652dec35671e1e7cf255d61c28f\"}},\"576c2e53fe924d68deb7262cfc0e4023b5889652dec35671e1e7cf255d61c28f:1\":{\"blockheight\":0,\"tweak\":\"f0ad83734cdc7d73575e5a32651390cf30b92cc7e44cf94ec37da46900ecaf71\",\"amount\":654,\"script\":\"5120230cc1e85829be238e666f469653cbc2f1c0e3675a9bf33e1d1f91115f5dd306\",\"label\":\"56572fc770b52096879662f97f98263d3e126f5a4a38f00f2895a9dde4c47c1c\",\"spend_status\":\"Unspent\"},\"fbd9c63e0dd08c2569b51a0d6095a79ee2acfcac66acdb594328a095f1fadb63:1\":{\"blockheight\":2146,\"tweak\":\"678dbcbdb40cd3733c8dbbd508761a0937009cf75a9f466e3c98877e79037cbc\",\"amount\":99896595,\"script\":\"5120deab0c5a3d23de30477b0b5a95a261c96e29afdd9813c665d2bf025ad2b3f919\",\"label\":null,\"spend_status\":\"Unspent\"}}},\"tx_history\":[]}";
|
||||
pub const ALICE_PAIRED_DEVICE: &str = "{\"sp_wallet\":{\"client\":{\"label\":\"default\",\"scan_sk\":\"e3d8922a41a7cb1a84a90f4334e987bb5ea2df6a1fdf44f789b5302de119f9e2\",\"spend_key\":{\"Secret\":\"93292e5b21042c6cfc742ba30e9d2a1e01609b12d154a1825184ed12c7b9631b\"},\"mnemonic\":null,\"sp_receiver\":{\"version\":0,\"network\":\"Testnet\",\"scan_pubkey\":[2,104,242,105,185,6,124,208,34,44,149,52,163,38,63,221,150,12,198,24,95,143,126,235,37,149,233,88,118,32,86,233,152],\"spend_pubkey\":[3,198,82,196,243,12,59,126,109,143,144,157,128,176,168,94,54,134,232,139,115,102,11,178,128,244,239,251,40,228,67,153,72],\"change_label\":\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",\"labels\":[[\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",[2,244,223,255,57,50,216,27,133,112,138,69,120,126,85,110,6,242,141,33,136,191,82,164,241,54,179,115,84,161,145,174,154]]]},\"network\":\"testnet\"},\"outputs\":{\"wallet_fingerprint\":[187,119,108,230,171,125,106,11],\"birthday\":1620,\"last_scan\":2146,\"outputs\":{\"9a4a67cc5a40bf882d8b300d91024d7c97024b3b68b2df7745a5b9ea1df1888c:1\":{\"blockheight\":1620,\"tweak\":\"b8b63b3ed97d297b744135cfac2fb4a344c881a77543b71f1fcd16bc67514f26\",\"amount\":3938643,\"script\":\"51205b7b324bb71d411e32f2c61fda5d1db23f5c7d6d416a77fab87c913a1b120be1\",\"label\":\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",\"spend_status\":{\"Spent\":\"e2c6ff9927c8a5f7a60087117732c07ab7cd82c0c65462e9c780eb5ce9c35292\"}},\"576c2e53fe924d68deb7262cfc0e4023b5889652dec35671e1e7cf255d61c28f:0\":{\"blockheight\":0,\"tweak\":\"6e5c1d4690b9ff4fa26e5185ada25af5c2987650e629a518db8a43fdaad7a26c\",\"amount\":349,\"script\":\"512088ac90e180c87b7fa6aa33db4c72a8620cd08fda3ba1c71430b904eb068c587f\",\"label\":null,\"spend_status\":{\"Spent\":\"8c701e6b62f4d2c4ddc779262f368dd156ea1c75a7097247fbdb6d344ac9c165\"}},\"8c701e6b62f4d2c4ddc779262f368dd156ea1c75a7097247fbdb6d344ac9c165:3\":{\"blockheight\":0,\"tweak\":\"ad5d59f98e2a49f2097d6847c4be66ab6e2125d3620924c5135c178afe0c450f\",\"amount\":3935006,\"script\":\"5120da6a7f478a357e277b4ebd295d65cc58900b29236f57cdf2d1541363c8eddd9d\",\"label\":\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",\"spend_status\":\"Unspent\"},\"e2c6ff9927c8a5f7a60087117732c07ab7cd82c0c65462e9c780eb5ce9c35292:1\":{\"blockheight\":0,\"tweak\":\"7c84a3074c18c23a65eceaca49a327989ef6e7240e0e080421afb80f06906d73\",\"amount\":306,\"script\":\"5120eb78084d7a2ccbdb7eb7e9bba7cf875c4e54a5aba0beac57c5d3e41133bd8fdd\",\"label\":null,\"spend_status\":{\"Spent\":\"8c701e6b62f4d2c4ddc779262f368dd156ea1c75a7097247fbdb6d344ac9c165\"}},\"e2c6ff9927c8a5f7a60087117732c07ab7cd82c0c65462e9c780eb5ce9c35292:2\":{\"blockheight\":0,\"tweak\":\"e3e21d551e933199f8c977bc0362616bdfb128da7ca9728bd7254977541c39cc\",\"amount\":3936897,\"script\":\"5120df3af55a63bd056c5d6d09f47a3a19c382d938c08db8bc41a59c5235970209ad\",\"label\":\"ac14a827e2d023b8f7804303a47259366117d99ed932b641d4a8eaf1b82cc992\",\"spend_status\":{\"Spent\":\"8c701e6b62f4d2c4ddc779262f368dd156ea1c75a7097247fbdb6d344ac9c165\"}},\"8c701e6b62f4d2c4ddc779262f368dd156ea1c75a7097247fbdb6d344ac9c165:2\":{\"blockheight\":0,\"tweak\":\"c2ab55a30f0a575d139639ab2bc78e5e524dd85e5f1981297f601e890760c6d7\",\"amount\":546,\"script\":\"512040fb549d9cbb51f01fc29df8cd0714d33e3608507d1e3adaf015e35ed5e87b9f\",\"label\":null,\"spend_status\":\"Unspent\"},\"8c701e6b62f4d2c4ddc779262f368dd156ea1c75a7097247fbdb6d344ac9c165:0\":{\"blockheight\":0,\"tweak\":\"cfea493360d6ffe2bfd13e4c5c2f677351e0c038f1ce0cd5383fadad6adc79f1\",\"amount\":602,\"script\":\"51200f008ff13f876bf328c69f10ad8621c9770ff8d5eb1861cb67199189a6308bb9\",\"label\":null,\"spend_status\":\"Unspent\"}}},\"tx_history\":[]},\"pairing_process_commitment\":\"8c701e6b62f4d2c4ddc779262f368dd156ea1c75a7097247fbdb6d344ac9c165\",\"paired_member\":{\"sp_addresses\":[\"sprt1qqf2kqh8n7lkupngfk2fxtmvyaq8sy3v2ramyeryweadqmsz7l6tg2qc9n4dl42ff8klz28nznr7mfzh6263xv555stwzextl2v4lvhg3aqq7ru8u\",\"sprt1qqf50y6deqe7dqg3vj562xf3lmktqe3sct78ha6e9jh54sa3q2m5esq7x2tz0xrpm0ekclyyaszc2sh3ksm5gkumxpwegpa80lv5wgsuefqaufx8q\"]}}";
|
||||
pub const BOB_PAIRED_DEVICE: &str = "{\"sp_wallet\":{\"client\":{\"label\":\"default\",\"scan_sk\":\"0de90b7195c1380d5fde13de3f1d66d53423a9896314839e36ba672653af60b4\",\"spend_key\":{\"Secret\":\"affe686075ecbe17b8ce7de45ec31314804259d0a4bc1c863de21ffd6dc598f8\"},\"mnemonic\":null,\"sp_receiver\":{\"version\":0,\"network\":\"Testnet\",\"scan_pubkey\":[2,85,96,92,243,247,237,192,205,9,178,146,101,237,132,232,15,2,69,138,31,118,76,140,142,207,90,13,192,94,254,150,133],\"spend_pubkey\":[3,5,157,91,250,169,41,61,190,37,30,98,152,253,180,138,250,86,162,102,82,148,130,220,44,153,127,83,43,246,93,17,232],\"change_label\":\"56572fc770b52096879662f97f98263d3e126f5a4a38f00f2895a9dde4c47c1c\",\"labels\":[[\"56572fc770b52096879662f97f98263d3e126f5a4a38f00f2895a9dde4c47c1c\",[2,237,237,247,213,154,87,34,239,168,235,87,122,152,94,41,35,101,184,201,58,201,6,185,58,157,52,208,129,167,2,224,198]]]},\"network\":\"testnet\"},\"outputs\":{\"wallet_fingerprint\":[203,200,4,248,139,36,241,232],\"birthday\":2146,\"last_scan\":2146,\"outputs\":{\"576c2e53fe924d68deb7262cfc0e4023b5889652dec35671e1e7cf255d61c28f:1\":{\"blockheight\":0,\"tweak\":\"f0ad83734cdc7d73575e5a32651390cf30b92cc7e44cf94ec37da46900ecaf71\",\"amount\":654,\"script\":\"5120230cc1e85829be238e666f469653cbc2f1c0e3675a9bf33e1d1f91115f5dd306\",\"label\":\"56572fc770b52096879662f97f98263d3e126f5a4a38f00f2895a9dde4c47c1c\",\"spend_status\":\"Unspent\"},\"93722ea2fb9b74954210b4cdd1360e280b7ff1bc156d6b75f847e62411c588fb:0\":{\"blockheight\":0,\"tweak\":\"da5e3aa2378e3a257f99eb1e0ae4c672916f6a2f32a8ed9a8e146f2074da981b\",\"amount\":443,\"script\":\"51209eb9e950127b6a7d81668f25b4d5b164b42dafe59ce40b80e6c489ec983540d7\",\"label\":null,\"spend_status\":\"Unspent\"},\"8c701e6b62f4d2c4ddc779262f368dd156ea1c75a7097247fbdb6d344ac9c165:1\":{\"blockheight\":0,\"tweak\":\"898284108952bd8b0e74030e00b81c1b387ee151a810ca3b40143da227707df2\",\"amount\":1000,\"script\":\"5120c0ff94a1318f0061960a713c927ff175a0d71a791497e94e70601c3baae739b8\",\"label\":null,\"spend_status\":\"Unspent\"},\"e2c6ff9927c8a5f7a60087117732c07ab7cd82c0c65462e9c780eb5ce9c35292:0\":{\"blockheight\":0,\"tweak\":\"0e3395ff27bde9187ffaeeb2521f6277d3b83911f16ccbaf59a1a68d99a0ab93\",\"amount\":1200,\"script\":\"512010f06f764cbc923ec3198db946307bf0c06a1b4f09206055e47a6fec0a33d52c\",\"label\":null,\"spend_status\":{\"Spent\":\"576c2e53fe924d68deb7262cfc0e4023b5889652dec35671e1e7cf255d61c28f\"}},\"fbd9c63e0dd08c2569b51a0d6095a79ee2acfcac66acdb594328a095f1fadb63:1\":{\"blockheight\":2146,\"tweak\":\"678dbcbdb40cd3733c8dbbd508761a0937009cf75a9f466e3c98877e79037cbc\",\"amount\":99896595,\"script\":\"5120deab0c5a3d23de30477b0b5a95a261c96e29afdd9813c665d2bf025ad2b3f919\",\"label\":null,\"spend_status\":\"Unspent\"}}},\"tx_history\":[]},\"pairing_process_commitment\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"paired_member\":{\"sp_addresses\":[\"sprt1qqf50y6deqe7dqg3vj562xf3lmktqe3sct78ha6e9jh54sa3q2m5esq7x2tz0xrpm0ekclyyaszc2sh3ksm5gkumxpwegpa80lv5wgsuefqaufx8q\",\"sprt1qqf2kqh8n7lkupngfk2fxtmvyaq8sy3v2ramyeryweadqmsz7l6tg2qc9n4dl42ff8klz28nznr7mfzh6263xv555stwzextl2v4lvhg3aqq7ru8u\"]}}";
|
||||
|
||||
pub const PAIRING_PROCESS: &str = "{\"816fc00efc0e4ead5c6683f51e74433ea8b9a520cda48b23cdae6c42639c540f:0\":{\"states\":[],\"shared_secrets\":{\"sprt1qqf50y6deqe7dqg3vj562xf3lmktqe3sct78ha6e9jh54sa3q2m5esq7x2tz0xrpm0ekclyyaszc2sh3ksm5gkumxpwegpa80lv5wgsuefqaufx8q\":\"a86c30250a8e6a8dc9581b3ab2dacafda6446f6c65f4debe124f5870b6796ea1\"},\"impending_requests\":[{\"prd_type\":\"Update\",\"root_commitment\":\"816fc00efc0e4ead5c6683f51e74433ea8b9a520cda48b23cdae6c42639c540f:4294967295\",\"sender\":\"{\\\"sp_addresses\\\":[\\\"sprt1qqf2kqh8n7lkupngfk2fxtmvyaq8sy3v2ramyeryweadqmsz7l6tg2qc9n4dl42ff8klz28nznr7mfzh6263xv555stwzextl2v4lvhg3aqq7ru8u\\\",\\\"sprt1qqf50y6deqe7dqg3vj562xf3lmktqe3sct78ha6e9jh54sa3q2m5esq7x2tz0xrpm0ekclyyaszc2sh3ksm5gkumxpwegpa80lv5wgsuefqaufx8q\\\"]}\",\"keys\":{\"roles\":\"eb4e967297c40d55d96d61568849df75bf42ddd756a14b3309aa774f9d58cff1\",\"pairing_tx\":\"6484145ebc037a0b0033c103e47e211699473eef6172348e9a40a4d4c4d8c0ac\"},\"validation_tokens\":[],\"payload\":\"{\\\"html\\\":\\\"cd0e3fdb60ec8da76c16ca727e4bb486937f82e081cee8abc1ea6a5dbde8\\\",\\\"style\\\":\\\"24f6169aa2c4e9e46f34ac477347215f0b87f54cc333f24cf4f9b788e09f\\\",\\\"script\\\":\\\"ab6880c844ba8d3a14a47ae5ac586f60ac77aa8945288246d3894526c054\\\",\\\"description\\\":\\\"e30f5aa7999a169defb65f586d15764f80c952e9bfb6e864759cae9eea1184febb31d2d542c5\\\",\\\"roles\\\":\\\"849c2dca2c8bc9e28a7f22bc98a4e9a1ef18d9daea4c956421a6f66161cf6f2b1e0ed438814699b69770e9c6feb2ca62696a6d4800fa9c8973c989d35fdff01a1c72619510bceb025f020ad62e772924b9fa693ce10836ac542b754c8ef18788a34a01ca03fb3ed732db960a6a74b3ad22a2f638214c153a6c2586095f945c08df90cfa3e42686715cac878095228ad38de955a678d8f628eb85e894631d204b8441db7b87b5c67664831ed6dc97eba0334e15cbbe036b9767de703414277a08e40af83259a93e6aaaeff9471fb4e3a8a1f351d0a61450996288df8ecfe3b006c40d7e93f7f1b66267300c9e570dc425ed2d2cc6584b938f01dde2472c00f4a5b6122659ef834ec114abeceac9ed37be44faf99fa92f421b669818f40ae6a5c8d3092a76e17c478caa9ae43eef8e2ab60ad73d430637ad4056e0fc3547ab85ca859b2cda6dadd3f40c1dc297b9874ec5174f6a154ecd4a295d502ea497da534fb56294514713f3837950a30685d67e0dd2823855a0f4a35f86675ce8c4da2b254d6406b432a96dba5cc9503afc00490fb4\\\",\\\"pairing_tx\\\":\\\"95eb6b93f53d0909dc72ad53a1d0d3e54426276e0b3b360d44e6392fa1af01f64aac00a9ef633170186a13c2924d6397f3a8364d8921f2614dbb748090d90815842d48f5165e3f0782e0e648f017848c83a1b497b3a0ef1417dde26523b34e0234758f9719ecc21b43\\\"}\",\"proof\":{\"signature\":\"2f6a504567b53565a48e94b3bb21c2493d208534045dab69e68e813c466cd580058518d1f452cadabb51252b643a5bd1db515d4b157b61adffa28ba7b57b5266\",\"message\":{\"Message\":\"f4eea3b2932fc02aab2b84fbdc071b50b93f544fb4e2f732d6491d5c64f9af5b\"},\"key\":\"c652c4f30c3b7e6d8f909d80b0a85e3686e88b73660bb280f4effb28e4439948\"}}]}}";
|
||||
|
||||
pub const RELAY_ADDRESS: &str = "sprt1qqfmqt0ngq99y8t4ke6uhtm2a2vc2zxvhj7hjrqu599kn30d4cs9rwqn6n079mdr4dfqg72yrtvuxf43yswscw86nvvl09mc5ljx65vfh75fkza35";
|
||||
pub const DEFAULT_NYM: &str = "AliceBob";
|
||||
|
||||
pub fn helper_get_alice_address() -> String {
|
||||
let wallet: SpWallet = serde_json::from_str(ALICE_START_WALLET).unwrap();
|
||||
wallet.get_client().get_receiving_address()
|
||||
}
|
||||
|
||||
pub fn helper_get_bob_address() -> String {
|
||||
let wallet: SpWallet = serde_json::from_str(BOB_START_WALLET).unwrap();
|
||||
wallet.get_client().get_receiving_address()
|
||||
}
|
||||
|
||||
pub fn helper_get_tweak_data(tx: &str, outpoints: HashMap<OutPoint, OwnedOutput>) -> String {
|
||||
let tx: Transaction = deserialize(&Vec::from_hex(tx).unwrap()).unwrap();
|
||||
let mut outpoint_data = vec![];
|
||||
let mut witnesses = vec![];
|
||||
let mut spks = vec![];
|
||||
for prevout in tx.input.iter() {
|
||||
outpoint_data.push((
|
||||
prevout.previous_output.txid.to_string(),
|
||||
prevout.previous_output.vout,
|
||||
));
|
||||
witnesses.push(prevout.witness.clone());
|
||||
if let Some(output) = outpoints.get(&prevout.previous_output) {
|
||||
spks.push(ScriptBuf::from_hex(&output.script).unwrap());
|
||||
}
|
||||
}
|
||||
let mut input_pubkeys = vec![];
|
||||
for (spk, witness) in spks.iter().zip(witnesses) {
|
||||
let input_pubkey =
|
||||
get_pubkey_from_input(&vec![], &witness.to_vec(), spk.as_bytes()).unwrap();
|
||||
input_pubkeys.push(input_pubkey.unwrap());
|
||||
}
|
||||
let ref_pubkeys: Vec<&PublicKey> = input_pubkeys.iter().collect();
|
||||
let tweak_data = calculate_tweak_data(&ref_pubkeys, &outpoint_data).unwrap();
|
||||
tweak_data.to_string()
|
||||
}
|
||||
|
||||
pub fn helper_parse_transaction(transaction: &str, tweak_data: &str) -> ApiReturn {
|
||||
let tx: Transaction = deserialize(&Vec::from_hex(transaction).unwrap()).unwrap();
|
||||
let new_tx_msg = serde_json::to_string(&NewTxMessage::new(
|
||||
serialize(&tx).to_lower_hex_string(),
|
||||
Some(tweak_data.to_owned()),
|
||||
))
|
||||
.unwrap();
|
||||
// debug!("new_tx_msg: {:?}", new_tx_msg);
|
||||
let result = parse_new_tx(new_tx_msg, 0);
|
||||
match result {
|
||||
Ok(m) => m,
|
||||
Err(e) => panic!("Unexpected error: {}", e.message),
|
||||
}
|
||||
}
|
110
tsconfig.json
110
tsconfig.json
@ -1,110 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "ES2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "ESNext", /* Specify what module code is generated. */
|
||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
|
||||
/* Emit */
|
||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
|
||||
/* Type Checking */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
},
|
||||
"include": ["./src/**/*"]
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
const path = require('path');
|
||||
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||
const CopyWebpackPlugin = require('copy-webpack-plugin');
|
||||
|
||||
module.exports = {
|
||||
mode: 'development',
|
||||
entry: './src/index.ts',
|
||||
devtool: 'inline-source-map',
|
||||
experiments: {
|
||||
asyncWebAssembly: true,
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
use: 'ts-loader',
|
||||
exclude: /node_modules/,
|
||||
},
|
||||
{
|
||||
test: /\.wasm$/,
|
||||
type: 'webassembly/async',
|
||||
}
|
||||
],
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
},
|
||||
output: {
|
||||
filename: 'index.js',
|
||||
path: path.resolve(__dirname, 'dist'),
|
||||
},
|
||||
plugins: [
|
||||
new HtmlWebpackPlugin({
|
||||
template: 'src/index.html'
|
||||
}),
|
||||
new CopyWebpackPlugin({
|
||||
patterns: [
|
||||
{ from: 'src/assets', to: './assets' },
|
||||
{ from: 'src/style', to: './style' }
|
||||
],
|
||||
}),
|
||||
],
|
||||
devServer: {
|
||||
static: './dist',
|
||||
},
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user