-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathconversions.rs
More file actions
375 lines (349 loc) · 16 KB
/
conversions.rs
File metadata and controls
375 lines (349 loc) · 16 KB
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
// Copyright (c) 2018-2022 The MobileCoin Foundation
//! Conversions between "API types" and "domain/persistence types".
//!
//! gRPC and Protobuf provide a reduced selection of types, and so there are
//! some differences between values stored in the ledger and values transmitted
//! over the API. This module provides conversions between "equivalent" types,
//! such as `mc_consensus_api::consensus_common::ProposeTxResult` and
//! `mc_transaction_core::validation::TransactionValidationError`.
use crate::{
consensus_client::{MintValidationResult, MintValidationResultCode},
consensus_common::ProposeTxResult,
consensus_config,
};
use mc_api::ConversionError;
use mc_transaction_core::{
mint::MintValidationError, validation::TransactionValidationError as Error, BlockVersion,
InputRuleError, RevealedTxOutError, TokenId,
};
/// Convert TransactionValidationError --> ProposeTxResult.
impl From<Error> for ProposeTxResult {
fn from(src: Error) -> Self {
match src {
Error::InputsProofsLengthMismatch => Self::InputsProofsLengthMismatch,
Error::NoInputs => Self::NoInputs,
Error::TooManyInputs => Self::TooManyInputs,
Error::InsufficientInputSignatures => Self::InsufficientInputSignatures,
Error::InvalidInputSignature => Self::InvalidInputSignature,
Error::InvalidTransactionSignature(_e) => Self::InvalidTransactionSignature,
Error::InvalidRangeProof => Self::InvalidRangeProof,
Error::InsufficientRingSize => Self::InsufficientRingSize,
Error::TombstoneBlockExceeded => Self::TombstoneBlockExceeded,
Error::TombstoneBlockTooFar => Self::TombstoneBlockTooFar,
Error::NoOutputs => Self::NoOutputs,
Error::TooManyOutputs => Self::TooManyOutputs,
Error::ExcessiveRingSize => Self::ExcessiveRingSize,
Error::DuplicateRingElements => Self::DuplicateRingElements,
Error::UnsortedRingElements => Self::UnsortedRingElements,
Error::UnequalRingSizes => Self::UnequalRingSizes,
Error::UnsortedKeyImages => Self::UnsortedKeyImages,
Error::ContainsSpentKeyImage => Self::ContainsSpentKeyImage,
Error::DuplicateKeyImages => Self::DuplicateKeyImages,
Error::DuplicateOutputPublicKey => Self::DuplicateOutputPublicKey,
Error::ContainsExistingOutputPublicKey => Self::ContainsExistingOutputPublicKey,
Error::MissingTxOutMembershipProof => Self::MissingTxOutMembershipProof,
Error::InvalidTxOutMembershipProof => Self::InvalidTxOutMembershipProof,
Error::InvalidRistrettoPublicKey => Self::InvalidRistrettoPublicKey,
Error::InvalidLedgerContext => Self::InvalidLedgerContext,
Error::Ledger(_) => Self::Ledger,
Error::LedgerTxOutIndexOutOfBounds(_) => Self::LedgerTxOutIndexOutOfBounds,
Error::MembershipProofValidationError => Self::MembershipProofValidationError,
Error::TxFeeError => Self::TxFeeError,
Error::KeyError => Self::KeyError,
Error::UnsortedInputs => Self::UnsortedInputs,
Error::MissingMemo => Self::MissingMemo,
Error::MemosNotAllowed => Self::MemosNotAllowed,
Error::TokenNotYetConfigured => Self::TokenNotYetConfigured,
Error::MissingMaskedTokenId => Self::MissingMaskedTokenId,
Error::MaskedTokenIdNotAllowed => Self::MaskedTokenIdNotAllowed,
Error::UnsortedOutputs => Self::UnsortedOutputs,
Error::InputRulesNotAllowed => Self::InputRulesNotAllowed,
Error::InputRule(ir) => ir.into(),
Error::UnknownMaskedAmountVersion => Self::UnknownMaskedAmountVersion,
Error::Timestamp(_) => Self::Timestamp,
}
}
}
impl From<InputRuleError> for ProposeTxResult {
fn from(src: InputRuleError) -> Self {
match src {
InputRuleError::MissingRequiredOutput => Self::InputRuleMissingRequiredOutput,
InputRuleError::MaxTombstoneBlockExceeded => Self::InputRuleMaxTombstoneBlockExceeded,
InputRuleError::PartialFillOutputsNotExpected
| InputRuleError::MinPartialFillValueNotExpected
| InputRuleError::MissingFractionalChangeOutput
| InputRuleError::MissingFractionalOutput
| InputRuleError::FractionalOutputTokenIdMismatch
| InputRuleError::ZeroPartialFillChange
| InputRuleError::MinPartialFillValueExceedsPartialFillChange
| InputRuleError::FractionalOutputAmountDoesNotRespectFillFraction
| InputRuleError::FractionalChangeOutputAmountExceedsLimit => {
Self::InputRulePartialFill
}
InputRuleError::RevealedTxOut(rtxo_err) => match rtxo_err {
RevealedTxOutError::InvalidAmountSharedSecret => {
Self::InputRuleInvalidAmountSharedSecret
}
RevealedTxOutError::TxOutConversion(_) => Self::InputRuleTxOutConversion,
RevealedTxOutError::Amount(_) => Self::InputRuleAmount,
},
}
}
}
/// Convert MintValidationError -> MintValidationResult.
impl From<MintValidationError> for MintValidationResult {
fn from(src: MintValidationError) -> Self {
match src {
MintValidationError::InvalidBlockVersion(block_version) => Self {
code: MintValidationResultCode::InvalidBlockVersion,
block_version: *block_version,
..Default::default()
},
MintValidationError::InvalidTokenId(token_id) => Self {
code: MintValidationResultCode::InvalidTokenId,
token_id: *token_id,
..Default::default()
},
MintValidationError::InvalidNonceLength(len) => Self {
code: MintValidationResultCode::InvalidNonceLength,
nonce_length: len as u64,
..Default::default()
},
MintValidationError::InvalidSignerSet => Self {
code: MintValidationResultCode::InvalidSignerSet,
..Default::default()
},
MintValidationError::InvalidSignature => Self {
code: MintValidationResultCode::InvalidSignature,
..Default::default()
},
MintValidationError::TombstoneBlockExceeded => Self {
code: MintValidationResultCode::TombstoneBlockExceeded,
..Default::default()
},
MintValidationError::TombstoneBlockTooFar => Self {
code: MintValidationResultCode::TombstoneBlockTooFar,
..Default::default()
},
MintValidationError::Unknown => Self {
code: MintValidationResultCode::Unknown,
..Default::default()
},
MintValidationError::AmountExceedsMintLimit => Self {
code: MintValidationResultCode::AmountExceedsMintLimit,
..Default::default()
},
MintValidationError::NoGovernors(token_id) => Self {
code: MintValidationResultCode::NoGovernors,
token_id: *token_id,
..Default::default()
},
MintValidationError::NonceAlreadyUsed => Self {
code: MintValidationResultCode::NonceAlreadyUsed,
..Default::default()
},
MintValidationError::NoMatchingMintConfig => Self {
code: MintValidationResultCode::NoMatchingMintConfig,
..Default::default()
},
MintValidationError::MintingToFogNotSupported => Self {
code: MintValidationResultCode::MintingToFogNotSupported,
..Default::default()
},
}
}
}
/// Convert MintValidationResult -> MintValidationError.
impl TryInto<MintValidationError> for MintValidationResult {
type Error = String;
fn try_into(self) -> Result<MintValidationError, Self::Error> {
match self.code {
MintValidationResultCode::Ok => {
Err("Ok value cannot be converted into MintValidationError".to_string())
}
MintValidationResultCode::InvalidBlockVersion => {
Ok(MintValidationError::InvalidBlockVersion(
BlockVersion::try_from(self.block_version).map_err(|err| err.to_string())?,
))
}
MintValidationResultCode::InvalidTokenId => {
Ok(MintValidationError::InvalidTokenId(self.token_id.into()))
}
MintValidationResultCode::InvalidNonceLength => Ok(
MintValidationError::InvalidNonceLength(self.nonce_length as usize),
),
MintValidationResultCode::InvalidSignerSet => Ok(MintValidationError::InvalidSignerSet),
MintValidationResultCode::InvalidSignature => Ok(MintValidationError::InvalidSignature),
MintValidationResultCode::TombstoneBlockExceeded => {
Ok(MintValidationError::TombstoneBlockExceeded)
}
MintValidationResultCode::TombstoneBlockTooFar => {
Ok(MintValidationError::TombstoneBlockTooFar)
}
MintValidationResultCode::Unknown => Ok(MintValidationError::Unknown),
MintValidationResultCode::AmountExceedsMintLimit => {
Ok(MintValidationError::AmountExceedsMintLimit)
}
MintValidationResultCode::NoGovernors => Ok(MintValidationError::NoGovernors(
TokenId::from(self.token_id),
)),
MintValidationResultCode::NonceAlreadyUsed => Ok(MintValidationError::NonceAlreadyUsed),
MintValidationResultCode::NoMatchingMintConfig => {
Ok(MintValidationError::NoMatchingMintConfig)
}
MintValidationResultCode::MintingToFogNotSupported => {
Ok(MintValidationError::MintingToFogNotSupported)
}
}
}
}
/// Convert mc_ledger_db::ActiveMintConfig -->
/// consensus_config::ActiveMintConfig
impl From<&mc_ledger_db::ActiveMintConfig> for consensus_config::ActiveMintConfig {
fn from(src: &mc_ledger_db::ActiveMintConfig) -> Self {
let mut dst = Self::new();
dst.set_mint_config((&src.mint_config).into());
dst.set_total_minted(src.total_minted);
dst
}
}
/// Convert consensus_config::ActiveMintConfig -->
/// mc_ledger_db::ActiveMintConfig
impl TryFrom<&consensus_config::ActiveMintConfig> for mc_ledger_db::ActiveMintConfig {
type Error = ConversionError;
fn try_from(src: &consensus_config::ActiveMintConfig) -> Result<Self, Self::Error> {
let mint_config = src.get_mint_config().try_into()?;
Ok(Self {
mint_config,
total_minted: src.get_total_minted(),
})
}
}
/// Convert mc_ledger_db::ActiveMintConfigs -->
/// consensus_config::ActiveMintConfigs
impl From<&mc_ledger_db::ActiveMintConfigs> for consensus_config::ActiveMintConfigs {
fn from(src: &mc_ledger_db::ActiveMintConfigs) -> Self {
let mut dst = Self::new();
dst.set_configs(src.configs.iter().map(|config| config.into()).collect());
dst.set_mint_config_tx((&src.mint_config_tx).into());
dst
}
}
/// Convert consensus_config::ActiveMintConfigs -->
/// mc_ledger_db::ActiveMintConfigs
impl TryFrom<&consensus_config::ActiveMintConfigs> for mc_ledger_db::ActiveMintConfigs {
type Error = ConversionError;
fn try_from(src: &consensus_config::ActiveMintConfigs) -> Result<Self, Self::Error> {
let configs = src
.get_configs()
.iter()
.map(TryInto::try_into)
.collect::<Result<Vec<_>, _>>()?;
let mint_config_tx = src.get_mint_config_tx().try_into()?;
Ok(Self {
configs,
mint_config_tx,
})
}
}
#[cfg(test)]
mod conversion_tests {
use super::*;
use mc_crypto_multisig::SignerSet;
use mc_transaction_core::mint::MintConfig;
use mc_transaction_core_test_utils::create_mint_config_tx_and_signers;
use mc_util_serial::{decode, encode};
use protobuf::Message;
use rand_core::SeedableRng;
use rand_hc::Hc128Rng;
#[test]
fn test_convert_active_mint_config() {
let mut rng = Hc128Rng::from_seed([1u8; 32]);
let (_mint_config_tx, signers) = create_mint_config_tx_and_signers(2.into(), &mut rng);
let signer_set = SignerSet::new(signers.iter().map(|s| s.public_key()).collect(), 1);
let source = mc_ledger_db::ActiveMintConfig {
mint_config: MintConfig {
token_id: 123,
signer_set,
mint_limit: 10000,
},
total_minted: 102,
};
// decode(encode(source)) should be the identity function.
{
let bytes = encode(&source);
let recovered = decode(&bytes).unwrap();
assert_eq!(source, recovered);
}
// Converting mc_ledger_db::ActiveMintConfig ->
// consensus_config::ActiveMintConfig -> mc_ledger_db::ActiveMintConfig
// should be the identity function.
{
let external = consensus_config::ActiveMintConfig::from(&source);
let recovered = mc_ledger_db::ActiveMintConfig::try_from(&external).unwrap();
assert_eq!(source, recovered);
}
// Encoding with prost, decoding with protobuf should be the identity
// function.
{
let bytes = encode(&source);
let recovered = consensus_config::ActiveMintConfig::parse_from_bytes(&bytes).unwrap();
assert_eq!(recovered, consensus_config::ActiveMintConfig::from(&source));
}
// Encoding with protobuf, decoding with prost should be the identity function.
{
let external = consensus_config::ActiveMintConfig::from(&source);
let bytes = external.write_to_bytes().unwrap();
let recovered: mc_ledger_db::ActiveMintConfig = decode(&bytes).unwrap();
assert_eq!(source, recovered);
}
}
#[test]
fn test_convert_active_mint_configs() {
let mut rng = Hc128Rng::from_seed([1u8; 32]);
let (mint_config_tx, signers) = create_mint_config_tx_and_signers(2.into(), &mut rng);
let signer_set = SignerSet::new(signers.iter().map(|s| s.public_key()).collect(), 1);
let source = mc_ledger_db::ActiveMintConfigs {
configs: vec![mc_ledger_db::ActiveMintConfig {
mint_config: MintConfig {
token_id: 123,
signer_set,
mint_limit: 10000,
},
total_minted: 102,
}],
mint_config_tx,
};
// decode(encode(source)) should be the identity function.
{
let bytes = encode(&source);
let recovered = decode(&bytes).unwrap();
assert_eq!(source, recovered);
}
// Converting mc_ledger_db::ActiveMintConfigs ->
// consensus_config::ActiveMintConfigs -> mc_ledger_db::ActiveMintConfigs
// should be the identity function.
{
let external = consensus_config::ActiveMintConfigs::from(&source);
let recovered = mc_ledger_db::ActiveMintConfigs::try_from(&external).unwrap();
assert_eq!(source, recovered);
}
// Encoding with prost, decoding with protobuf should be the identity
// function.
{
let bytes = encode(&source);
let recovered = consensus_config::ActiveMintConfigs::parse_from_bytes(&bytes).unwrap();
assert_eq!(
recovered,
consensus_config::ActiveMintConfigs::from(&source)
);
}
// Encoding with protobuf, decoding with prost should be the identity function.
{
let external = consensus_config::ActiveMintConfigs::from(&source);
let bytes = external.write_to_bytes().unwrap();
let recovered: mc_ledger_db::ActiveMintConfigs = decode(&bytes).unwrap();
assert_eq!(source, recovered);
}
}
}