forked from bennyhodl/dlcdevkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p2p_derivatives.rs
179 lines (157 loc) Β· 5.06 KB
/
p2p_derivatives.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
//! rust-dlc <https://github.com/p2pderivatives/rust-dlc/blob/master/p2pd-oracle-client/src/lib.rs> (2024)
//! # cg-oracle-client
//! Http client wrapper for the Crypto Garage DLC oracle
use chrono::{DateTime, SecondsFormat, Utc};
use ddk_manager::error::Error as DlcManagerError;
use dlc::secp256k1_zkp::{schnorr::Signature, XOnlyPublicKey};
use dlc_messages::oracle_msgs::{OracleAnnouncement, OracleAttestation};
use crate::Oracle;
/// Enables interacting with a DLC oracle.
pub struct P2PDOracleClient {
host: String,
public_key: XOnlyPublicKey,
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct PublicKeyResponse {
public_key: XOnlyPublicKey,
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct EventDescriptor {
base: u16,
is_signed: bool,
unit: String,
precision: i32,
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct Event {
nonces: Vec<XOnlyPublicKey>,
event_maturity: DateTime<Utc>,
event_id: String,
event_descriptor: EventDescriptor,
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct AnnoucementResponse {
oracle_public_key: XOnlyPublicKey,
oracle_event: Event,
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct AttestationResponse {
event_id: String,
signatures: Vec<Signature>,
values: Vec<String>,
}
async fn get<T>(path: &str) -> Result<T, DlcManagerError>
where
T: serde::de::DeserializeOwned,
{
reqwest::get(path)
.await
.map_err(|x| {
ddk_manager::error::Error::IOError(
std::io::Error::new(std::io::ErrorKind::Other, x).into(),
)
})?
.json::<T>()
.await
.map_err(|e| ddk_manager::error::Error::OracleError(e.to_string()))
}
fn pubkey_path(host: &str) -> String {
format!("{}{}", host, "oracle/publickey")
}
fn announcement_path(host: &str, asset_id: &str, date_time: &DateTime<Utc>) -> String {
format!(
"{}asset/{}/announcement/{}",
host,
asset_id,
date_time.to_rfc3339_opts(SecondsFormat::Secs, true)
)
}
fn attestation_path(host: &str, asset_id: &str, date_time: &DateTime<Utc>) -> String {
format!(
"{}asset/{}/attestation/{}",
host,
asset_id,
date_time.to_rfc3339_opts(SecondsFormat::Secs, true)
)
}
impl P2PDOracleClient {
/// Try to create an instance of an oracle client connecting to the provided
/// host. Returns an error if the host could not be reached. Panics if the
/// oracle uses an incompatible format.
pub async fn new(host: &str) -> Result<P2PDOracleClient, DlcManagerError> {
if host.is_empty() {
return Err(DlcManagerError::InvalidParameters(
"Invalid host".to_string(),
));
}
let host = if !host.ends_with('/') {
format!("{}{}", host, "/")
} else {
host.to_string()
};
let public_key = get::<PublicKeyResponse>(&pubkey_path(&host))
.await?
.public_key;
Ok(P2PDOracleClient { host, public_key })
}
}
fn parse_event_id(event_id: &str) -> Result<(String, DateTime<Utc>), DlcManagerError> {
let asset_id = &event_id[..6];
let timestamp_str = &event_id[6..];
let timestamp: i64 = timestamp_str
.parse()
.map_err(|_| DlcManagerError::OracleError("Invalid timestamp format".to_string()))?;
let naive_date_time = DateTime::from_timestamp(timestamp, 0)
.ok_or_else(|| {
DlcManagerError::InvalidParameters(format!(
"Invalid timestamp {} in event id",
timestamp
))
})?
.naive_utc();
let date_time = DateTime::from_naive_utc_and_offset(naive_date_time, Utc);
Ok((asset_id.to_string(), date_time))
}
#[async_trait::async_trait]
impl ddk_manager::Oracle for P2PDOracleClient {
fn get_public_key(&self) -> XOnlyPublicKey {
self.public_key
}
async fn get_announcement(
&self,
event_id: &str,
) -> Result<OracleAnnouncement, DlcManagerError> {
let (asset_id, date_time) = parse_event_id(event_id)?;
let path = announcement_path(&self.host, &asset_id, &date_time);
let announcement = get(&path).await?;
Ok(announcement)
}
async fn get_attestation(
&self,
event_id: &str,
) -> Result<OracleAttestation, ddk_manager::error::Error> {
let (asset_id, date_time) = parse_event_id(event_id)?;
let path = attestation_path(&self.host, &asset_id, &date_time);
let AttestationResponse {
event_id,
signatures,
values,
} = get::<AttestationResponse>(&path).await?;
Ok(OracleAttestation {
event_id,
oracle_public_key: self.public_key,
signatures,
outcomes: values,
})
}
}
impl Oracle for P2PDOracleClient {
fn name(&self) -> String {
"p2pderivatives".into()
}
}