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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use anyhow::{anyhow, Result};
use diem_logger::info;
use diem_sdk::{
client::{AccountAddress, Client, SignedTransaction},
transaction_builder::{Currency, TransactionFactory},
types::{chain_id::ChainId, transaction::authenticator::AuthenticationKey, LocalAccount},
};
use reqwest::StatusCode;
use serde::Deserialize;
use std::{
convert::Infallible,
fmt,
sync::{Arc, Mutex},
};
use warp::{Filter, Rejection, Reply};
pub mod mint;
pub struct Service {
treasury_compliance_account: Mutex<LocalAccount>,
designated_dealer_account: Mutex<LocalAccount>,
transaction_factory: TransactionFactory,
client: Client,
jsonrpc_endpoint: String,
}
impl Service {
pub fn new(
jsonrpc_endpoint: String,
chain_id: ChainId,
treasury_compliance_account: LocalAccount,
designated_dealer_account: LocalAccount,
) -> Self {
let client = Client::new(&jsonrpc_endpoint);
Service {
treasury_compliance_account: Mutex::new(treasury_compliance_account),
designated_dealer_account: Mutex::new(designated_dealer_account),
transaction_factory: TransactionFactory::new(chain_id)
.with_transaction_expiration_time(30),
client,
jsonrpc_endpoint,
}
}
pub fn jsonrpc_endpoint(&self) -> &str {
&self.jsonrpc_endpoint
}
}
pub fn routes(
service: Arc<Service>,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
let mint = mint::mint_routes(service.clone());
let accounts = accounts_routes(service);
let health = warp::path!("-" / "healthy").map(|| "diem-faucet:ok");
health
.or(mint)
.or(accounts)
.with(warp::log::custom(|info| {
info!(
"{} \"{} {} {:?}\" {} \"{}\" \"{}\" {:?}",
OptFmt(info.remote_addr()),
info.method(),
info.path(),
info.version(),
info.status().as_u16(),
OptFmt(info.referer()),
OptFmt(info.user_agent()),
info.elapsed(),
)
}))
.with(warp::cors().allow_any_origin().allow_methods(vec!["POST"]))
}
fn accounts_routes(
service: Arc<Service>,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
create_account_route(service.clone()).or(fund_account_route(service))
}
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
struct CreateAccountParams {
authentication_key: AuthenticationKey,
currency: Currency,
}
fn create_account_route(
service: Arc<Service>,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
warp::path::path("accounts")
.and(warp::post())
.and(warp::any().map(move || service.clone()))
.and(warp::query().map(move |params: CreateAccountParams| params))
.and_then(handle_create_account)
}
async fn handle_create_account(
service: Arc<Service>,
params: CreateAccountParams,
) -> Result<Box<dyn warp::Reply>, Infallible> {
match create_account(service, params).await {
Ok(txn) => Ok(Box::new(hex::encode(bcs::to_bytes(&txn).unwrap()))),
Err(err) => Ok(Box::new(warp::reply::with_status(
err.to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
))),
}
}
async fn create_account(
service: Arc<Service>,
params: CreateAccountParams,
) -> Result<SignedTransaction> {
if service
.client
.get_account(params.authentication_key.derived_address())
.await?
.into_inner()
.is_some()
{
return Err(anyhow!("account already exists"));
}
let tc_account_address = service
.treasury_compliance_account
.lock()
.unwrap()
.address();
let tc_sequence_number = service
.client
.get_account(tc_account_address)
.await?
.into_inner()
.ok_or_else(|| anyhow::format_err!("treasury compliance account not found"))?
.sequence_number;
let txn = {
let mut treasury_account = service.treasury_compliance_account.lock().unwrap();
if tc_sequence_number > treasury_account.sequence_number() {
*treasury_account.sequence_number_mut() = tc_sequence_number;
}
let builder = service.transaction_factory.create_parent_vasp_account(
params.currency,
0,
params.authentication_key,
&format!("No. {}", treasury_account.sequence_number()),
false,
);
treasury_account.sign_with_transaction_builder(builder)
};
service.client.submit(&txn).await?;
Ok(txn)
}
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
struct FundAccountParams {
amount: u64,
currency: Currency,
}
fn fund_account_route(
service: Arc<Service>,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
warp::path!("accounts" / AccountAddress / "fund")
.and(warp::post())
.and(warp::any().map(move || service.clone()))
.and(warp::query().map(move |params: FundAccountParams| params))
.and_then(handle_fund_account)
}
async fn handle_fund_account(
address: AccountAddress,
service: Arc<Service>,
params: FundAccountParams,
) -> Result<Box<dyn warp::Reply>, Infallible> {
match fund_account(service, address, params).await {
Ok(txn) => Ok(Box::new(hex::encode(bcs::to_bytes(&txn).unwrap()))),
Err(err) => Ok(Box::new(warp::reply::with_status(
err.to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
))),
}
}
async fn fund_account(
service: Arc<Service>,
address: AccountAddress,
params: FundAccountParams,
) -> Result<SignedTransaction> {
if service
.client
.get_account(address)
.await?
.into_inner()
.is_none()
{
return Err(anyhow!("account doesn't exist"));
}
let dd_account_address = service.designated_dealer_account.lock().unwrap().address();
let dd_sequence_number = service
.client
.get_account(dd_account_address)
.await?
.into_inner()
.ok_or_else(|| anyhow::format_err!("treasury compliance account not found"))?
.sequence_number;
let txn = {
let mut dd_account = service.designated_dealer_account.lock().unwrap();
if dd_sequence_number > dd_account.sequence_number() {
*dd_account.sequence_number_mut() = dd_sequence_number;
}
dd_account.sign_with_transaction_builder(
service.transaction_factory.peer_to_peer_with_metadata(
params.currency,
address,
params.amount,
vec![],
vec![],
),
)
};
service.client.submit(&txn).await?;
Ok(txn)
}
struct OptFmt<T>(Option<T>);
impl<T: fmt::Display> fmt::Display for OptFmt<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(t) = &self.0 {
fmt::Display::fmt(t, f)
} else {
f.write_str("-")
}
}
}