Skip to content

Commit

Permalink
feat: add hmac authentication to the kormir client
Browse files Browse the repository at this point in the history
  • Loading branch information
rorp committed Dec 26, 2024
1 parent 81736ab commit 2574f6c
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 16 deletions.
10 changes: 6 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion ddk-node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl DdkNode {
)?);

// let oracle = Arc::new(P2PDOracleClient::new(&oracle_host).await?);
let oracle = Arc::new(KormirOracleClient::new(&opts.oracle_host).await?);
let oracle = Arc::new(KormirOracleClient::new(&opts.oracle_host, None).await?);

let mut builder = Builder::new();
builder.set_seed_bytes(seed_bytes.private_key.secret_bytes());
Expand Down
2 changes: 2 additions & 0 deletions ddk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ lightning-net-tokio = { version = "0.0.125", optional = true }
reqwest = { version = "0.12.9", features = ["blocking"], optional = true }
kormir = "0.4.1"
# kormir = { path = "../../kormir/kormir" }
hmac = "0.12.1"
sha2 = "0.10"

[dev-dependencies]
test-log = { version = "0.2.16", features = ["trace"] }
Expand Down
2 changes: 1 addition & 1 deletion ddk/examples/ddk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type ApplicationDdk = ddk::DlcDevKit<LightningTransport, SledStorage, KormirOrac
async fn main() -> Result<()> {
let transport = Arc::new(LightningTransport::new(&[0u8; 32], 1776)?);
let storage = Arc::new(SledStorage::new(current_dir()?.to_str().unwrap())?);
let oracle_client = Arc::new(KormirOracleClient::new("host").await?);
let oracle_client = Arc::new(KormirOracleClient::new("host", None).await?);

let mut seed_bytes = [0u8; 32];
seed_bytes.try_fill(&mut bitcoin::key::rand::thread_rng())?;
Expand Down
55 changes: 45 additions & 10 deletions ddk/src/oracle/kormir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ use kormir::storage::OracleEventData;
use lightning::{io::Cursor, util::ser::Readable};
use serde::Serialize;
use std::str::FromStr;
use hmac::{Hmac, Mac};
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use sha2::Sha256;
use uuid::Uuid;

async fn get<T>(host: &str, path: &str) -> anyhow::Result<T>
Expand All @@ -17,20 +20,20 @@ where
Ok(request)
}

#[derive(Serialize)]
#[derive(Debug, Serialize)]
pub struct CreateEnumEvent {
pub event_id: String,
pub outcomes: Vec<String>,
pub event_maturity_epoch: u32,
}

#[derive(Serialize)]
#[derive(Debug, Serialize)]
struct SignEnumEvent {
pub event_id: String,
pub outcome: String,
}

#[derive(Serialize)]
#[derive(Debug, Serialize)]
pub struct CreateNumericEvent {
pub event_id: String,
pub num_digits: Option<u16>,
Expand All @@ -40,7 +43,7 @@ pub struct CreateNumericEvent {
pub event_maturity_epoch: u32,
}

#[derive(Serialize)]
#[derive(Debug, Serialize)]
pub struct SignNumericEvent {
pub event_id: String,
pub outcome: i64,
Expand All @@ -54,10 +57,11 @@ pub struct KormirOracleClient {
pubkey: XOnlyPublicKey,
client: reqwest::Client,
host: String,
hmac_secret: Option<Vec<u8>>
}

impl KormirOracleClient {
pub async fn new(host: &str) -> anyhow::Result<KormirOracleClient> {
pub async fn new(host: &str, hmac_secret: Option<Vec<u8>>) -> anyhow::Result<KormirOracleClient> {
let request: String = get(host, "pubkey").await?;
let pubkey = XOnlyPublicKey::from_str(&request)?;
let client = reqwest::Client::new();
Expand All @@ -71,6 +75,7 @@ impl KormirOracleClient {
pubkey,
client,
host: host.to_string(),
hmac_secret,
})
}

Expand Down Expand Up @@ -105,10 +110,13 @@ impl KormirOracleClient {
event_maturity_epoch: maturity,
};

let (body, headers) = self.body_and_headers(&create_event_request)?;

let announcement = self
.client
.post(format!("{}/create-enum", self.host))
.json(&create_event_request)
.body(body)
.headers(headers)
.send()
.await?
.text()
Expand All @@ -134,10 +142,13 @@ impl KormirOracleClient {

let event = SignEnumEvent { event_id, outcome };

let (body, headers) = self.body_and_headers(&event)?;

let hex = self
.client
.post(format!("{}/sign-enum", &self.host))
.json(&event)
.body(body)
.headers(headers)
.send()
.await?
.text()
Expand Down Expand Up @@ -180,10 +191,13 @@ impl KormirOracleClient {
event_maturity_epoch: maturity,
};

let (body, headers) = self.body_and_headers(&create_event_request)?;

let announcement = self
.client
.post(format!("{}/create-numeric", self.host))
.json(&create_event_request)
.body(body)
.headers(headers)
.send()
.await?
.text()
Expand All @@ -209,10 +223,13 @@ impl KormirOracleClient {

let event = SignNumericEvent { event_id, outcome };

let (body, headers) = self.body_and_headers(&event)?;

let hex = self
.client
.post(format!("{}/sign-numeric", &self.host))
.json(&event)
.body(body)
.headers(headers)
.send()
.await?
.text()
Expand All @@ -230,6 +247,24 @@ impl KormirOracleClient {

Ok(attestation)
}

fn body_and_headers<T: Serialize + ?Sized>(&self, json: &T) -> anyhow::Result<(Vec<u8>, HeaderMap)> {
let body = serde_json::to_vec(json)?;
let mut headers = HeaderMap::new();
headers.append(CONTENT_TYPE, HeaderValue::from_static("application/json"));
if let Some(secret) = &self.hmac_secret {
let hmac = Self::calculate_hmac(&body, secret)?;
headers.append("X-Signature", HeaderValue::from_bytes(hmac.as_bytes())?);
}
Ok((body, headers))
}

fn calculate_hmac(payload: &[u8], secret: &[u8]) -> anyhow::Result<String> {
let mut mac = Hmac::<Sha256>::new_from_slice(secret)?;
mac.update(payload);
let result = mac.finalize().into_bytes();
Ok(hex::encode(result))
}
}

#[async_trait::async_trait]
Expand Down Expand Up @@ -283,7 +318,7 @@ mod tests {
use super::*;

async fn create_kormir() -> KormirOracleClient {
KormirOracleClient::new("https://kormir.dlcdevkit.com")
KormirOracleClient::new("https://kormir.dlcdevkit.com", None)
.await
.unwrap()
}
Expand Down

0 comments on commit 2574f6c

Please sign in to comment.