-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmod.rs
264 lines (243 loc) · 7.6 KB
/
mod.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
//! D-parameter is stored on chain in an UTXO at the D-parameter validator address.
//! There should be at most one UTXO at the validator address and it should contain the D-parameter.
//! This UTXO should have 1 token of the D-parameter policy with an empty asset name.
//! The datum encodes D-parameter using VersionedGenericDatum envelope with the D-parameter being
//! `datum` field being `[num_permissioned_candidates, num_registered_candidates]`.
use crate::await_tx::{AwaitTx, FixedDelayRetries};
use crate::cardano_keys::CardanoPaymentSigningKey;
use crate::csl::{
empty_asset_name, get_builder_config, unit_plutus_data, CostStore, Costs, InputsBuilderExt,
TransactionBuilderExt, TransactionContext, TransactionExt,
};
use crate::governance::GovernanceData;
use crate::plutus_script::PlutusScript;
use anyhow::anyhow;
use cardano_serialization_lib::{PlutusData, Transaction, TransactionBuilder, TxInputsBuilder};
use ogmios_client::query_ledger_state::QueryUtxoByUtxoId;
use ogmios_client::{
query_ledger_state::QueryLedgerState, query_network::QueryNetwork, transactions::Transactions,
types::OgmiosUtxo,
};
use partner_chains_plutus_data::d_param::{d_parameter_to_plutus_data, DParamDatum};
use sidechain_domain::{DParameter, McTxHash, UtxoId};
#[cfg(test)]
mod tests;
pub trait UpsertDParam {
#[allow(async_fn_in_trait)]
async fn upsert_d_param(
&self,
genesis_utxo: UtxoId,
d_parameter: &DParameter,
payment_signing_key: &CardanoPaymentSigningKey,
) -> anyhow::Result<Option<McTxHash>>;
}
impl<C: QueryLedgerState + QueryNetwork + Transactions + QueryUtxoByUtxoId> UpsertDParam for C {
async fn upsert_d_param(
&self,
genesis_utxo: UtxoId,
d_parameter: &DParameter,
payment_signing_key: &CardanoPaymentSigningKey,
) -> anyhow::Result<Option<McTxHash>> {
upsert_d_param(
genesis_utxo,
d_parameter,
payment_signing_key,
self,
&FixedDelayRetries::two_minutes(),
)
.await
}
}
pub async fn upsert_d_param<
C: QueryLedgerState + QueryNetwork + Transactions + QueryUtxoByUtxoId,
A: AwaitTx,
>(
genesis_utxo: UtxoId,
d_parameter: &DParameter,
payment_signing_key: &CardanoPaymentSigningKey,
ogmios_client: &C,
await_tx: &A,
) -> anyhow::Result<Option<McTxHash>> {
let ctx = TransactionContext::for_payment_key(payment_signing_key, ogmios_client).await?;
let (validator, policy) = crate::scripts_data::d_parameter_scripts(genesis_utxo, ctx.network)?;
let validator_address = validator.address_bech32(ctx.network)?;
let validator_utxos = ogmios_client.query_utxos(&[validator_address]).await?;
let tx_hash_opt = match get_current_d_parameter(validator_utxos)? {
Some((_, current_d_param)) if current_d_param == *d_parameter => {
log::info!("Current D-parameter value is equal to the one to be set.");
None
},
Some((current_utxo, _)) => {
log::info!("Current D-parameter is different to the one to be set. Updating.");
Some(
update_d_param(
&validator,
&policy,
d_parameter,
¤t_utxo,
ctx,
genesis_utxo,
ogmios_client,
)
.await?,
)
},
None => {
log::info!("There is no D-parameter set. Inserting new one.");
Some(
insert_d_param(&validator, &policy, d_parameter, ctx, genesis_utxo, ogmios_client)
.await?,
)
},
};
if let Some(tx_hash) = tx_hash_opt {
await_tx.await_tx_output(ogmios_client, UtxoId::new(tx_hash.0, 0)).await?;
}
Ok(tx_hash_opt)
}
fn get_current_d_parameter(
validator_utxos: Vec<OgmiosUtxo>,
) -> Result<Option<(OgmiosUtxo, DParameter)>, anyhow::Error> {
if let Some(utxo) = validator_utxos.first() {
let datum = utxo.datum.clone().ok_or_else(|| {
anyhow!("Invalid state: an UTXO at the validator script address does not have a datum")
})?;
let datum_plutus_data = PlutusData::from_bytes(datum.bytes).map_err(|e| {
anyhow!("Internal error: could not decode datum of D-parameter validator script: {}", e)
})?;
let current_d_param: DParameter =
DParamDatum::try_from(datum_plutus_data)
.map_err(|e| {
anyhow!("Internal error: could not decode datum of D-parameter validator script: {}", e)
})?
.into();
Ok(Some((utxo.clone(), current_d_param)))
} else {
Ok(None)
}
}
async fn insert_d_param<C: QueryLedgerState + Transactions + QueryNetwork>(
validator: &PlutusScript,
policy: &PlutusScript,
d_parameter: &DParameter,
ctx: TransactionContext,
genesis_utxo: UtxoId,
client: &C,
) -> anyhow::Result<McTxHash> {
let gov_data = GovernanceData::get(genesis_utxo, client).await?;
let tx = Costs::calculate_costs(
|costs| mint_d_param_token_tx(validator, policy, d_parameter, &gov_data, costs, &ctx),
client,
)
.await?;
let signed_tx = ctx.sign(&tx).to_bytes();
let res = client.submit_transaction(&signed_tx).await.map_err(|e| {
anyhow!(
"Submit insert D-parameter transaction request failed: {}, bytes: {}",
e,
hex::encode(signed_tx)
)
})?;
let tx_id = McTxHash(res.transaction.id);
log::info!("Transaction submitted: {}", hex::encode(tx_id.0));
Ok(tx_id)
}
async fn update_d_param<C: QueryLedgerState + Transactions + QueryNetwork>(
validator: &PlutusScript,
policy: &PlutusScript,
d_parameter: &DParameter,
current_utxo: &OgmiosUtxo,
ctx: TransactionContext,
genesis_utxo: UtxoId,
client: &C,
) -> anyhow::Result<McTxHash> {
let governance_data = GovernanceData::get(genesis_utxo, client).await?;
let tx = Costs::calculate_costs(
|costs| {
update_d_param_tx(
validator,
policy,
d_parameter,
current_utxo,
&governance_data,
costs,
&ctx,
)
},
client,
)
.await?;
let signed_tx = ctx.sign(&tx).to_bytes();
let res = client.submit_transaction(&signed_tx).await.map_err(|e| {
anyhow!(
"Submit D-parameter update transaction request failed: {}, bytes: {}",
e,
hex::encode(signed_tx)
)
})?;
let tx_id = McTxHash(res.transaction.id);
log::info!("Update D-parameter transaction submitted: {}", hex::encode(tx_id.0));
Ok(tx_id)
}
fn mint_d_param_token_tx(
validator: &PlutusScript,
policy: &PlutusScript,
d_parameter: &DParameter,
governance_data: &GovernanceData,
costs: Costs,
ctx: &TransactionContext,
) -> anyhow::Result<Transaction> {
let mut tx_builder = TransactionBuilder::new(&get_builder_config(ctx)?);
// The essence of transaction: mint D-Param token and set output with it, mint a governance token.
tx_builder.add_mint_one_script_token(
policy,
&empty_asset_name(),
&unit_plutus_data(),
&costs.get_mint(&policy.clone().into()),
)?;
tx_builder.add_output_with_one_script_token(
validator,
policy,
&d_parameter_to_plutus_data(d_parameter),
ctx,
)?;
let gov_tx_input = governance_data.utxo_id_as_tx_input();
tx_builder.add_mint_one_script_token_using_reference_script(
&governance_data.policy.script(),
&gov_tx_input,
&costs,
)?;
Ok(tx_builder.balance_update_and_build(ctx)?.remove_native_script_witnesses())
}
fn update_d_param_tx(
validator: &PlutusScript,
policy: &PlutusScript,
d_parameter: &DParameter,
script_utxo: &OgmiosUtxo,
governance_data: &GovernanceData,
costs: Costs,
ctx: &TransactionContext,
) -> anyhow::Result<Transaction> {
let mut tx_builder = TransactionBuilder::new(&get_builder_config(ctx)?);
let mut inputs = TxInputsBuilder::new();
inputs.add_script_utxo_input(
script_utxo,
validator,
&unit_plutus_data(),
&costs.get_one_spend(),
)?;
tx_builder.set_inputs(&inputs);
tx_builder.add_output_with_one_script_token(
validator,
policy,
&d_parameter_to_plutus_data(d_parameter),
ctx,
)?;
let gov_tx_input = governance_data.utxo_id_as_tx_input();
tx_builder.add_mint_one_script_token_using_reference_script(
&governance_data.policy.script(),
&gov_tx_input,
&costs,
)?;
Ok(tx_builder.balance_update_and_build(ctx)?.remove_native_script_witnesses())
}