Skip to content

Commit

Permalink
Project import generated by Copybara.
Browse files Browse the repository at this point in the history
GitOrigin-RevId: 5baa230fce6915a14efe6c6ce6c891bef0eb4c91
  • Loading branch information
Lightspark Eng authored and zhenlu committed Sep 13, 2023
1 parent 7be7c04 commit d36151a
Show file tree
Hide file tree
Showing 185 changed files with 3,862 additions and 484 deletions.
6 changes: 6 additions & 0 deletions .fossa.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: 3

project:
id: lightspark/rust-sdk
name: rust-sdk
url: https://github.com/lightsparkdev/webdev
42 changes: 8 additions & 34 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,36 +1,10 @@
[package]
name = "lightspark"
description = "Lightspark Rust SDK"
authors = ["Lightspark Group, Inc. <[email protected]>"]
version = "0.5.0"
edition = "2021"
documentation = "https://app.lightspark.com/docs/sdk"
homepage = "https://www.lightspark.com/"
repository = "https://github.com/lightsparkdev/lightspark-rs"
license = "Apache-2.0"
readme = "README.md"
[workspace]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
resolver = "2"

[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
futures = "0.3"
tokio = { version = "1.12.0", features = ["full"] }
base64 = "0.21.0"
serde_json = "1.0.94"
serde = { version = "1.0.155", features = ["derive"] }
regex = "1.7.1"
chrono = "0.4.24"
openssl = "0.10.48"
aes-gcm = "0.10.1"
rand = "0.8.5"
block-modes = "0.9.1"
os-version = "0.2.0"
version_check = "0.9.4"
hex = "0.4.3"
hmac = "0.12.1"
sha2 = "0.10.7"
rand_core = "0.6.4"
ecies = "0.2.6"
bitcoin = "0.30.1"
url = "2.4.1"
members = [
"lightspark",
"lightspark-remote-signing",
"uma",
"examples/*",
]
23 changes: 8 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
# Lightspark Rust SDK - v0.5.0

# Lightspark Rust SDK
The Lightspark Rust SDK provides a convenient way to interact with the Lightspark services from applications written in the Rust language.

***WARNING: This SDK is in version 0.4.0 (active development). It means that its APIs may not be fully stable. Please expect that changes to the APIs may happen until we move to v1.0.0.***

## Documentation

The documentation for this SDK (installation, usage, etc.) is available at https://app.lightspark.com/docs/sdk

## Sample code

For your convenience, we included an example that shows you how to use the SDK.
Open the file `example/example.rs` and make sure to update the variables at the top of the page with your information, then run it using cargo:
## Project Structure
The rust-sdk consists of multiple crates that can be picked at your convenience:
- `lightspark`: The main crate that contains the SDK.
- `uma`: The UMA protocol implementation.
- `example`: Examples that shows you how to use the SDK.

```
cargo run --example example
```
## License
[Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0)
7 changes: 3 additions & 4 deletions copy.bara.sky
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ core.workflow(
mode = "SQUASH",

origin_files = glob(
["rust-sdk/lightspark/**", "copy.bara.sky"],
["rust-sdk/**", "copy.bara.sky"],
exclude = ["rust-sdk/lightspark/examples/internal_example.rs"],
),

Expand All @@ -27,7 +27,7 @@ core.workflow(
core.todo_replace(
mode = 'SCRUB_NAMES'
),
core.move("rust-sdk/lightspark/", "")
core.move("rust-sdk/", "")
],
)

Expand Down Expand Up @@ -68,8 +68,7 @@ core.workflow(
),
destination = git.github_destination(
url = "https://github.com/lightsparkdev/go-sdk.git",
# TODO: Move this back to main when we're ready to release.
push = "rc/remote-signing",
push = "main",
),
# Switch to ITERATIVE mode to import each commit separately.
mode = "SQUASH",
Expand Down
10 changes: 10 additions & 0 deletions examples/lightspark-remote-signing-server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Generated by Cargo
# will have compiled files and executables
/target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
!Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk
11 changes: 11 additions & 0 deletions examples/lightspark-remote-signing-server/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "lightspark-remote-signing-server"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
lightspark = { path = "../../lightspark" }
lightspark-remote-signing = { path = "../../lightspark-remote-signing" }
tokio = "1.32.0"
85 changes: 85 additions & 0 deletions examples/lightspark-remote-signing-server/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use std::{
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
};

use lightspark::{
client::LightsparkClient,
key::{OperationSigningKey, Secp256k1SigningKey},
request::auth_provider::AccountAuthProvider,
webhooks::{self, WebhookEvent},
};
use lightspark_remote_signing::{
handler::Handler,
signer::{self, LightsparkSigner, Seed},
validation::{PositiveValidator, Validation},
};

#[tokio::main]
async fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
let seed = Seed::new("test".as_bytes().to_vec());
let signer = LightsparkSigner::new(&seed, signer::Network::Bitcoin).unwrap();
let validator = PositiveValidator;
let handler = Handler::new(signer, validator);

let auth = AccountAuthProvider::new("test".to_owned(), "test".to_owned());
let client = LightsparkClient::<Secp256k1SigningKey>::new(auth).expect("Assume success");

for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream, &handler, &client).await;
}
}

async fn handle_connection<T: Validation, K: OperationSigningKey>(
stream: TcpStream,
handler: &Handler<T>,
client: &LightsparkClient<K>,
) {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut name = String::new();
loop {
let r = reader.read_line(&mut name).unwrap();
if r < 3 {
break;
}
}
let mut size = 0;
let linesplit = name.split('\n');
let mut sig = "";
for l in linesplit {
if l.starts_with("Content-Length") {
let sizeplit = l.split(':');
for s in sizeplit {
if !(s.starts_with("Content-Length")) {
size = s.trim().parse::<usize>().unwrap();
}
}
} else if l.starts_with(webhooks::SIGNATURE_HEADER) {
let sigsplit = l.split(':');
for s in sigsplit {
if !(s.starts_with(webhooks::SIGNATURE_HEADER)) {
sig = s.trim();
}
}
}
}
let mut buffer = vec![0; size];
reader.read_exact(&mut buffer).unwrap();
let body = String::from_utf8(buffer.clone()).unwrap();

println!("Signature: {}", sig);
println!("Request: {}", body);

let event = WebhookEvent::verify_and_parse(
buffer.as_slice(),
sig.to_string(),
"webhook_secret".to_owned(),
)
.expect("Assume verified");
let response = handler.handle_remote_signing_webhook_msg(&event).expect("");
let _ = client
.execute_graphql_request_variable(&response.query, response.variables.clone())
.await;
}
10 changes: 10 additions & 0 deletions examples/uma-demo/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "uma-demo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
actix-web = "4.4.0"
lightspark = { path = "../../lightspark" }
2 changes: 2 additions & 0 deletions examples/uma-demo/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#[derive(Debug, Clone)]
pub struct Config {}
63 changes: 63 additions & 0 deletions examples/uma-demo/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
pub mod config;
pub mod vasp;
use actix_web::{get, post, web, App, HttpServer, Responder};

use crate::vasp::{VASPReceiving, VASPSending, VASP};

#[get("/api/umalookup/{receiver}")]
async fn uma_lookup(vasp: web::Data<VASP>, receiver: web::Path<String>) -> impl Responder {
vasp.handle_client_uma_lookup(receiver.as_str())
}

#[get("/api/umapayreq/{callback_uuid}")]
async fn client_payreq(vasp: web::Data<VASP>, callback_uuid: web::Path<String>) -> impl Responder {
vasp.handle_client_pay_req(callback_uuid.as_str())
}

#[get("/api/sendpayment/{callback_uuid}")]
async fn send_payment(vasp: web::Data<VASP>, callback_uuid: web::Path<String>) -> impl Responder {
vasp.handle_client_payment_confirm(callback_uuid.as_str())
}

#[get("/.well-known/lnurlp/{username}")]
async fn well_known_lnurlp(vasp: web::Data<VASP>, username: web::Path<String>) -> impl Responder {
vasp.handle_well_known_lnurlp(username.as_str())
}

#[get("/api/uma/payreq/{uuid}")]
async fn lnurl_payreq(vasp: web::Data<VASP>, uuid: web::Path<String>) -> impl Responder {
vasp.handle_lnurl_payreq(uuid.as_str())
}

#[post("/api/uma/payreq/{uuid}")]
async fn uma_payreq(vasp: web::Data<VASP>, uuid: web::Path<String>) -> impl Responder {
vasp.handle_uma_payreq(uuid.as_str())
}

#[get("/.well-known/lnurlpubkey")]
async fn pubkey_request(vasp: web::Data<VASP>) -> impl Responder {
vasp.handle_pubkey_request()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
let port = std::env::var("VASP_SERVER_PORT")
.unwrap()
.parse::<u16>()
.unwrap();
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(VASP {
config: config::Config {},
}))
.service(uma_lookup)
.service(client_payreq)
.service(send_payment)
.service(well_known_lnurlp)
.service(lnurl_payreq)
.service(uma_payreq)
})
.bind(("127.0.0.1", port))?
.run()
.await
}
58 changes: 58 additions & 0 deletions examples/uma-demo/src/vasp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use std::fmt::format;

use crate::config::Config;

pub trait VASPSending {
fn handle_client_uma_lookup(&self, receiver: &str) -> String;
fn handle_client_pay_req(&self, callback_uuid: &str) -> String;
fn handle_client_payment_confirm(&self, callback_uuid: &str) -> String;
}

pub trait VASPReceiving {
fn handle_well_known_lnurlp(&self, username: &str) -> String;
fn handle_lnurl_payreq(&self, uuid: &str) -> String;
fn handle_uma_payreq(&self, uuid: &str) -> String;
}

#[derive(Debug)]
pub struct VASP {
pub config: Config,
}

impl VASP {
pub fn new(config: Config) -> VASP {
VASP { config }
}

pub fn handle_pubkey_request(&self) -> String {
format(format_args!("Hello {}!", "pubkey_request"))
}
}

impl VASPSending for VASP {
fn handle_client_uma_lookup(&self, receiver: &str) -> String {
format(format_args!("Hello {}!", receiver))
}

fn handle_client_pay_req(&self, callback_uuid: &str) -> String {
format(format_args!("Hello {}!", callback_uuid))
}

fn handle_client_payment_confirm(&self, callback_uuid: &str) -> String {
format(format_args!("Hello {}!", callback_uuid))
}
}

impl VASPReceiving for VASP {
fn handle_well_known_lnurlp(&self, username: &str) -> String {
format(format_args!("Hello {}!", username))
}

fn handle_lnurl_payreq(&self, uuid: &str) -> String {
format(format_args!("Hello {}!", uuid))
}

fn handle_uma_payreq(&self, uuid: &str) -> String {
format(format_args!("Hello {}!", uuid))
}
}
10 changes: 10 additions & 0 deletions lightspark-remote-signing/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Generated by Cargo
# will have compiled files and executables
/target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk
16 changes: 16 additions & 0 deletions lightspark-remote-signing/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "lightspark-remote-signing"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
lightspark = { path = "../lightspark" }
bip39 = { "version" = "2.0.0", features = ["rand"]}
bitcoin = "0.30.1"
hex = "0.4.3"
rand_core = { "version" = "0.6.4", features = ["getrandom"] }
serde_json = "1.0.104"
log = "0.4.20"
serde = "1.0.183"
Loading

0 comments on commit d36151a

Please sign in to comment.