This repository has been archived by the owner on Jul 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 80
/
staking_rpc.rs
477 lines (432 loc) · 14.7 KB
/
staking_rpc.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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use std::collections::BTreeSet;
use std::str::FromStr;
use jsonrpc_core::Result;
use jsonrpc_derive::rpc;
use crate::{rpc_error_from_string, to_rpc_error};
use chain_core::init::coin::Coin;
use chain_core::state::account::{
ConfidentialInit, CouncilNode, StakedState, StakedStateAddress, StakedStateOpAttributes,
};
use chain_core::state::tendermint::TendermintValidatorPubKey;
use chain_core::tx::data::access::{TxAccess, TxAccessPolicy};
use chain_core::tx::data::address::ExtendedAddr;
use chain_core::tx::data::attribute::TxAttributes;
use chain_core::tx::data::input::TxoPointer;
use chain_core::tx::data::output::TxOut;
use client_common::{Error, ErrorKind, PublicKey, Result as CommonResult, ResultExt, Transaction};
use client_core::wallet::WalletRequest;
use client_core::{MultiSigWalletClient, WalletClient};
use client_network::NetworkOpsClient;
#[rpc(server)]
pub trait StakingRpc: Send + Sync {
#[rpc(name = "staking_depositStake")]
fn deposit_stake(
&self,
request: WalletRequest,
to_address: String,
inputs: Vec<TxoPointer>,
) -> Result<String>;
#[rpc(name = "staking_depositAmountStake")]
fn deposit_amount_stake(
&self,
request: WalletRequest,
to_address: String,
amount: Coin,
) -> Result<String>;
#[rpc(name = "staking_state")]
fn state(&self, name: String, address: StakedStateAddress) -> Result<StakedState>;
#[rpc(name = "staking_unbondStake")]
fn unbond_stake(
&self,
request: WalletRequest,
staking_address: String,
amount: Coin,
) -> Result<String>;
#[rpc(name = "staking_withdrawAllUnbondedStake")]
fn withdraw_all_unbonded_stake(
&self,
request: WalletRequest,
from_address: String,
to_address: String,
view_keys: Vec<String>,
) -> Result<String>;
#[rpc(name = "staking_unjail")]
fn unjail(&self, request: WalletRequest, unjail_address: String) -> Result<String>;
#[rpc(name = "staking_validatorNodeJoin")]
fn node_join(
&self,
request: WalletRequest,
validator_node_name: String,
validator_pubkey: String,
staking_address: String,
keypackage: String,
) -> Result<String>;
}
pub struct StakingRpcImpl<T, N>
where
T: WalletClient,
N: NetworkOpsClient,
{
client: T,
ops_client: N,
network_id: u8,
}
impl<T, N> StakingRpcImpl<T, N>
where
T: WalletClient,
N: NetworkOpsClient,
{
pub fn new(client: T, ops_client: N, network_id: u8) -> Self {
StakingRpcImpl {
client,
ops_client,
network_id,
}
}
}
impl<T, N> StakingRpc for StakingRpcImpl<T, N>
where
T: WalletClient + MultiSigWalletClient + 'static,
N: NetworkOpsClient + 'static,
{
fn deposit_stake(
&self,
request: WalletRequest,
to_address: String,
inputs: Vec<TxoPointer>,
) -> Result<String> {
let to_address = StakedStateAddress::from_str(&to_address)
.chain(|| {
(
ErrorKind::DeserializationError,
format!("Unable to deserialize to_address ({})", to_address),
)
})
.map_err(to_rpc_error)?;
let attributes = StakedStateOpAttributes::new(self.network_id);
if !self
.client
.has_unspent_transactions(&request.name, &request.enckey, &inputs)
.map_err(to_rpc_error)?
{
return Err( rpc_error_from_string("Given transaction inputs are not present in unspent transactions (synchronizing your wallet may help)".into()));
}
let transactions = inputs
.into_iter()
.map(|txo_pointer| {
let output = self
.client
.output(&request.name, &request.enckey, &txo_pointer)
.map_err(to_rpc_error)?;
Ok((txo_pointer, output))
})
.collect::<Result<Vec<(TxoPointer, TxOut)>>>()
.map_err(to_rpc_error)?;
let (transaction, tx_pending) = self
.ops_client
.create_deposit_bonded_stake_transaction(
&request.name,
&request.enckey,
transactions,
to_address,
attributes,
true,
)
.map_err(to_rpc_error)?;
self.client
.broadcast_transaction(&transaction)
.map_err(to_rpc_error)?;
// update the wallet pending transaction state
self.client
.update_tx_pending_state(
&request.name,
&request.enckey,
transaction.tx_id(),
tx_pending,
)
.map_err(to_rpc_error)?;
Ok(hex::encode(transaction.tx_id()))
}
/// deposit amount coin to a deposit address
/// 1. build a transfer transaction to make a UTXO which amount is `deposit_amount + fee`
/// 2. send to a self created transfer address, waiting it confirmed
/// 3. use the `outputs[0]` of the transfer transaction to deposit
/// 4. broadcast the deposit transaction, return tx_id
fn deposit_amount_stake(
&self,
request: WalletRequest,
to_address: String,
amount: Coin,
) -> Result<String> {
let to_staking_address = StakedStateAddress::from_str(&to_address)
.chain(|| {
(
ErrorKind::DeserializationError,
format!("Unable to deserialize to_staking_address ({})", to_address),
)
})
.map_err(to_rpc_error)?;
let attr = StakedStateOpAttributes::new(self.network_id);
let fee = self
.ops_client
.calculate_deposit_fee()
.map_err(to_rpc_error)?;
let total_amount = (amount + fee).map_err(to_rpc_error)?;
// 1. build a transfer transaction to make a UTXO which amount is `deposit_amount + fee`
let to_transfer_address = self
.client
.new_transfer_address(&request.name, &request.enckey)
.map_err(to_rpc_error)?;
let tx_id = self
.client
.send_to_address_commit(
&request.name,
&request.enckey,
total_amount,
to_transfer_address,
&mut BTreeSet::new(),
self.network_id,
)
.map_err(to_rpc_error)?;
// 2. use the outputs[0] to deposit
let transaction = self
.client
.get_transaction(&request.name, &request.enckey, tx_id)
.map_err(to_rpc_error)?;
let output = match transaction {
Transaction::TransferTransaction(tx) => {
if tx.outputs.is_empty() {
return Err(rpc_error_from_string("invalid transaction".into()));
}
tx.outputs[0].clone()
}
_ => return Err(rpc_error_from_string("invalid transaction type".into())),
};
let txo_pointer = TxoPointer::new(tx_id, 0);
let transactions = vec![(txo_pointer, output)];
let (transaction, tx_pending) = self
.ops_client
.create_deposit_bonded_stake_transaction(
&request.name,
&request.enckey,
transactions,
to_staking_address,
attr,
true,
)
.map_err(to_rpc_error)?;
// 4. broadcast the deposit transaction and waiting it confirmed
self.client
.broadcast_transaction(&transaction)
.map_err(to_rpc_error)?;
// update the wallet pending transaction state
self.client
.update_tx_pending_state(
&request.name,
&request.enckey,
transaction.tx_id(),
tx_pending,
)
.map_err(to_rpc_error)?;
Ok(hex::encode(transaction.tx_id()))
}
fn state(&self, name: String, address: StakedStateAddress) -> Result<StakedState> {
self.ops_client
.get_staked_state(&name, &address, true)
.map_err(to_rpc_error)
}
fn unbond_stake(
&self,
request: WalletRequest,
staking_address: String,
amount: Coin,
) -> Result<String> {
let attr = StakedStateOpAttributes::new(self.network_id);
let addr = StakedStateAddress::from_str(&staking_address)
.chain(|| {
(
ErrorKind::DeserializationError,
format!(
"Unable to deserialize staking address ({})",
staking_address
),
)
})
.map_err(to_rpc_error)?;
let transaction = self
.ops_client
.create_unbond_stake_transaction(
&request.name,
&request.enckey,
addr,
amount,
attr,
true,
)
.map_err(to_rpc_error)?;
self.client
.broadcast_transaction(&transaction)
.map_err(to_rpc_error)?;
Ok(hex::encode(transaction.tx_id()))
}
fn withdraw_all_unbonded_stake(
&self,
request: WalletRequest,
from_address: String,
to_address: String,
view_keys: Vec<String>,
) -> Result<String> {
let from_address = StakedStateAddress::from_str(&from_address)
.chain(|| {
(
ErrorKind::DeserializationError,
format!("Unable to deserialize from_address ({})", from_address),
)
})
.map_err(to_rpc_error)?;
let to_address = ExtendedAddr::from_str(&to_address)
.chain(|| {
(
ErrorKind::DeserializationError,
format!("Unable to deserialize to_address ({})", to_address),
)
})
.map_err(to_rpc_error)?;
let mut view_keys = view_keys
.iter()
.map(|key| PublicKey::from_str(key))
.collect::<CommonResult<BTreeSet<PublicKey>>>()
.map_err(to_rpc_error)?;
let view_key = self
.client
.view_key(&request.name, &request.enckey)
.map_err(to_rpc_error)?;
view_keys.insert(view_key);
let access_policies: BTreeSet<_> = view_keys
.iter()
.map(|key| TxAccessPolicy {
view_key: key.into(),
access: TxAccess::AllData,
})
.collect();
let attributes =
TxAttributes::new_with_access(self.network_id, access_policies.into_iter().collect());
let (transaction, tx_pending) = self
.ops_client
.create_withdraw_all_unbonded_stake_transaction(
&request.name,
&request.enckey,
&from_address,
to_address,
attributes,
true,
)
.map_err(to_rpc_error)?;
self.client
.broadcast_transaction(&transaction)
.map_err(to_rpc_error)?;
// update the wallet pending transaction state
self.client
.update_tx_pending_state(
&request.name,
&request.enckey,
transaction.tx_id(),
tx_pending,
)
.map_err(to_rpc_error)?;
Ok(hex::encode(transaction.tx_id()))
}
fn unjail(&self, request: WalletRequest, unjail_address: String) -> Result<String> {
let unjail_address = StakedStateAddress::from_str(&unjail_address)
.chain(|| {
(
ErrorKind::DeserializationError,
format!("Unable to deserialize unjail_address ({})", unjail_address),
)
})
.map_err(to_rpc_error)?;
let attributes = StakedStateOpAttributes::new(self.network_id);
let transaction = self
.ops_client
.create_unjail_transaction(
&request.name,
&request.enckey,
unjail_address,
attributes,
true,
)
.map_err(to_rpc_error)?;
self.client
.broadcast_transaction(&transaction)
.map_err(to_rpc_error)?;
Ok(hex::encode(transaction.tx_id()))
}
fn node_join(
&self,
request: WalletRequest,
validator_node_name: String,
validator_pubkey: String,
staking_addr: String,
keypackage: String,
) -> Result<String> {
let attributes = StakedStateOpAttributes::new(self.network_id);
let staking_account_address = staking_addr
.parse::<StakedStateAddress>()
.chain(|| {
(
ErrorKind::DeserializationError,
"Unable to deserialize staking address",
)
})
.map_err(to_rpc_error)?;
let node_metadata =
get_node_metadata(&validator_node_name, &validator_pubkey, &keypackage)?;
let transaction = self
.ops_client
.create_node_join_transaction(
&request.name,
&request.enckey,
staking_account_address,
attributes,
node_metadata,
true,
)
.map_err(to_rpc_error)?;
self.client
.broadcast_transaction(&transaction)
.map_err(to_rpc_error)?;
Ok(hex::encode(transaction.tx_id()))
}
}
fn get_node_metadata(
validator_name: &str,
validator_pubkey: &str,
keypackage: &str,
) -> Result<CouncilNode> {
let decoded_pubkey = base64::decode(validator_pubkey)
.chain(|| {
(
ErrorKind::DeserializationError,
"Unable to decode base64 encoded bytes of validator pubkey",
)
})
.map_err(to_rpc_error)?;
if decoded_pubkey.len() != 32 {
return Err(Error::new(
ErrorKind::InvalidInput,
"Expected validator pubkey of 32 bytes",
))
.map_err(to_rpc_error);
}
let mut pubkey_bytes = [0; 32];
pubkey_bytes.copy_from_slice(&decoded_pubkey);
let keypackage = base64::decode(keypackage)
.err_kind(ErrorKind::InvalidInput, || "invalid base64")
.map_err(to_rpc_error)?;
Ok(CouncilNode {
name: validator_name.to_string(),
security_contact: None,
consensus_pubkey: TendermintValidatorPubKey::Ed25519(pubkey_bytes),
confidential_init: ConfidentialInit { keypackage },
})
}