penumbra_asset/asset/registry.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
use std::sync::Arc;
use once_cell::sync::Lazy;
use regex::{Regex, RegexSet};
use crate::asset::{denom_metadata, Metadata, Unit};
use super::denom_metadata::Inner;
/// A registry of known assets, providing metadata related to a denomination string.
///
/// The [`REGISTRY`] constant provides an instance of the registry.
pub struct Registry {
/// Individual regexes for base denominations
base_regexes: Vec<Regex>,
/// Set of regexes that matches any base denomination.
base_set: RegexSet,
/// Individual regexes for the display denominations, grouped by their base denomination.
display_regexes: Vec<Vec<Regex>>,
/// Set of regexes that matches any display denomination.
display_set: RegexSet,
/// Mapping from indices of `display_set` to indices of `base_regexes`.
///
/// This allows looking up the base denomination for each display denomination.
display_to_base: Vec<usize>,
/// List of constructors for asset metadata, indexed by base denomination.
///
/// Each constructor maps the value of the `data` named capture from the
/// base OR display regex to the asset metadata.
//
// If we wanted to load registry data from a file in the future (would
// require working out how to write closures), we could use boxed closures
// instead of a function.
constructors: Vec<fn(&str) -> denom_metadata::Inner>,
}
impl Registry {
/// Attempt to parse the provided `raw_denom` as a base denomination.
///
/// If the denomination is a known base denomination, returns `Some` with
/// the parsed base denomination and associated display units.
///
/// If the denomination is a known display unit, returns `None`.
///
/// If the denomination is unknown, returns `Some` with the parsed base
/// denomination and default display denomination (base = display).
pub fn parse_denom(&self, raw_denom: &str) -> Option<Metadata> {
// We hope that our regexes are disjoint (TODO: add code to test this)
// so that there will only ever be one match from the RegexSet.
if let Some(base_index) = self.base_set.matches(raw_denom).iter().next() {
// We've matched a base denomination.
// Rematch with the specific pattern to obtain captured denomination data.
let data = self.base_regexes[base_index]
.captures(raw_denom)
.expect("already checked this regex matches")
.name("data")
.map(|m| m.as_str())
.unwrap_or("");
Some(Metadata {
inner: Arc::new(self.constructors[base_index](data)),
})
} else if self.display_set.matches(raw_denom).iter().next().is_some() {
// 2. This denom isn't a base denom, it's a display denom
None
} else {
// 3. Fallthrough: create default base denom
Some(Metadata {
inner: Arc::new(Inner::new(raw_denom.to_string(), Vec::new())),
})
}
}
/// Parses the provided `raw_unit`, determining whether it is a display unit
/// for another denomination or a base denomination itself.
///
/// If the denomination is a known display denomination, returns a display
/// denomination associated with that display denomination's base
/// denomination. Otherwise, returns a display denomination associated with
/// the input parsed as a base denomination.
pub fn parse_unit(&self, raw_unit: &str) -> Unit {
if let Some(display_index) = self.display_set.matches(raw_unit).iter().next() {
let base_index = self.display_to_base[display_index];
// We need to determine which unit we matched
for (unit_index, regex) in self.display_regexes[base_index].iter().enumerate() {
if let Some(capture) = regex.captures(raw_unit) {
let data = capture.name("data").map(|m| m.as_str()).unwrap_or("");
return Unit {
inner: Arc::new(self.constructors[base_index](data)),
unit_index,
};
}
}
unreachable!("we matched one of the display regexes");
} else {
self.parse_denom(raw_unit)
.expect("parse_base only returns None on display denom input")
.base_unit()
}
}
}
#[derive(Default)]
struct Builder {
base_regexes: Vec<&'static str>,
constructors: Vec<fn(&str) -> denom_metadata::Inner>,
unit_regexes: Vec<Vec<&'static str>>,
}
impl Builder {
/// Add an asset to the registry.
///
/// - `base_regex`: matches the base denomination, with optional named capture `data`.
/// - `unit_regexes`: match display units, with optional named capture `data`.
/// - `constructor`: maps `data` captured by a base OR display regex to the asset metadata,
/// recorded as a `denom::Inner`.
///
/// If the `data` capture is present in *any* base or display regex, it must
/// match *exactly* the same pattern in all of them, as it is the input to
/// the constructor. Also, the `units` passed to `denom::Inner` must be in
/// the same order as the `display_regexes`.
fn add_asset(
mut self,
base_regex: &'static str,
unit_regexes: &[&'static str],
constructor: fn(&str) -> denom_metadata::Inner,
) -> Self {
self.base_regexes.push(base_regex);
self.constructors.push(constructor);
self.unit_regexes.push(unit_regexes.to_vec());
self
}
fn build(self) -> Registry {
let mut display_to_base = Vec::new();
let mut display_regexes = Vec::new();
for (base_index, displays) in self.unit_regexes.iter().enumerate() {
for _d in displays.iter() {
display_to_base.push(base_index);
}
display_regexes.push(
displays
.iter()
.map(|d| Regex::new(d).expect("unable to parse display regex"))
.collect(),
);
}
Registry {
base_set: RegexSet::new(self.base_regexes.iter())
.expect("unable to parse base regexes"),
base_regexes: self
.base_regexes
.iter()
.map(|r| Regex::new(r).expect("unable to parse base regex"))
.collect(),
constructors: self.constructors,
display_set: RegexSet::new(
self.unit_regexes
.iter()
.flat_map(|displays| displays.iter()),
)
.expect("unable to parse display regexes"),
display_to_base,
display_regexes,
}
}
}
/// A fixed registry of known asset families.
pub static REGISTRY: Lazy<Registry> = Lazy::new(|| {
Builder::default()
.add_asset(
"^upenumbra$",
&["^penumbra$", "^mpenumbra$"],
(|data: &str| {
assert!(data.is_empty());
denom_metadata::Inner::new(
"upenumbra".to_string(),
vec![
denom_metadata::BareDenomUnit {
exponent: 6,
denom: "penumbra".to_string(),
},
denom_metadata::BareDenomUnit {
exponent: 3,
denom: "mpenumbra".to_string(),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
"^ugm$",
&["^gm$", "^mgm$"],
(|data: &str| {
assert!(data.is_empty());
denom_metadata::Inner::new(
"ugm".to_string(),
vec![
denom_metadata::BareDenomUnit {
exponent: 6,
denom: "gm".to_string(),
},
denom_metadata::BareDenomUnit {
exponent: 3,
denom: "mgm".to_string(),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
"^ugn$",
&["^gn$", "^mgn$"],
(|data: &str| {
assert!(data.is_empty());
denom_metadata::Inner::new(
"ugn".to_string(),
vec![
denom_metadata::BareDenomUnit {
exponent: 6,
denom: "gn".to_string(),
},
denom_metadata::BareDenomUnit {
exponent: 3,
denom: "mgn".to_string(),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
"^wtest_usd$",
&["^test_usd$"],
(|data: &str| {
assert!(data.is_empty());
denom_metadata::Inner::new(
"wtest_usd".to_string(),
vec![
denom_metadata::BareDenomUnit {
exponent: 18,
denom: "test_usd".to_string(),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
"^wtest_eth$",
&["^test_eth$"],
(|data: &str| {
assert!(data.is_empty());
denom_metadata::Inner::new(
"wtest_eth".to_string(),
vec![
denom_metadata::BareDenomUnit {
exponent: 18,
denom: "test_eth".to_string(),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
"^test_sat$",
&["^test_btc$"],
(|data: &str| {
assert!(data.is_empty());
denom_metadata::Inner::new(
"test_sat".to_string(),
vec![
denom_metadata::BareDenomUnit {
exponent: 8,
denom: "test_btc".to_string(),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
"^utest_atom$",
&["^test_atom$", "^mtest_atom$"],
(|data: &str| {
assert!(data.is_empty());
denom_metadata::Inner::new(
"utest_atom".to_string(),
vec![
denom_metadata::BareDenomUnit {
exponent: 6,
denom: "test_atom".to_string(),
},
denom_metadata::BareDenomUnit {
exponent: 3,
denom: "mtest_atom".to_string(),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
"^utest_osmo$",
&["^test_osmo$", "^mtest_osmo$"],
(|data: &str| {
assert!(data.is_empty());
denom_metadata::Inner::new(
"utest_osmo".to_string(),
vec![
denom_metadata::BareDenomUnit {
exponent: 6,
denom: "test_osmo".to_string(),
},
denom_metadata::BareDenomUnit {
exponent: 3,
denom: "mtest_osmo".to_string(),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
// Note: this regex must be in sync with DelegationToken::try_from
// and VALIDATOR_IDENTITY_BECH32_PREFIX in the penumbra-stake crate
// TODO: this doesn't restrict the length of the bech32 encoding
"^udelegation_(?P<data>penumbravalid1[a-zA-HJ-NP-Z0-9]+)$",
&[
"^delegation_(?P<data>penumbravalid1[a-zA-HJ-NP-Z0-9]+)$",
"^mdelegation_(?P<data>penumbravalid1[a-zA-HJ-NP-Z0-9]+)$",
],
(|data: &str| {
assert!(!data.is_empty());
denom_metadata::Inner::new(
format!("udelegation_{data}"),
vec![
denom_metadata::BareDenomUnit {
exponent: 6,
denom: format!("delegation_{data}"),
},
denom_metadata::BareDenomUnit {
exponent: 3,
denom: format!("mdelegation_{data}"),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
// Note: this regex must be in sync with UnbondingToken::try_from
// and VALIDATOR_IDENTITY_BECH32_PREFIX in the penumbra-stake crate
// TODO: this doesn't restrict the length of the bech32 encoding
"^uunbonding_(?P<data>start_at_(?P<start>[0-9]+)_(?P<validator>penumbravalid1[a-zA-HJ-NP-Z0-9]+))$",
&[
"^unbonding_(?P<data>start_at_(?P<start>[0-9]+)_(?P<validator>penumbravalid1[a-zA-HJ-NP-Z0-9]+))$",
"^munbonding_(?P<data>start_at_(?P<start>[0-9]+)_(?P<validator>penumbravalid1[a-zA-HJ-NP-Z0-9]+))$",
],
(|data: &str| {
assert!(!data.is_empty());
denom_metadata::Inner::new(
format!("uunbonding_{data}"),
vec![
denom_metadata::BareDenomUnit {
exponent: 6,
denom: format!("unbonding_{data}"),
},
denom_metadata::BareDenomUnit {
exponent: 3,
denom: format!("munbonding_{data}"),
},
],
)
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
// Note: this regex must be in sync with LpNft::try_from
// and the bech32 prefix for LP IDs defined in the proto crate.
// TODO: this doesn't restrict the length of the bech32 encoding
"^lpnft_(?P<data>[a-z_0-9]+_plpid1[a-zA-HJ-NP-Z0-9]+)$",
&[ /* no display units - nft, unit 1 */ ],
(|data: &str| {
assert!(!data.is_empty());
denom_metadata::Inner::new(format!("lpnft_{data}"), vec![])
}) as for<'r> fn(&'r str) -> _,
)
.add_asset(
// Note: this regex must be in sync with ProposalNft::try_from
"^proposal_(?P<data>(?P<proposal_id>[0-9]+)_(?P<proposal_state>deposit|unbonding_deposit|passed|failed|slashed))$",
&[ /* no display units - nft, unit 1 */ ],
(|data: &str| {
assert!(!data.is_empty());
denom_metadata::Inner::new(format!("proposal_{data}"), vec![])
}) as for<'r> fn(&'r str) -> _,
)
// Note: this regex must be in sync with VoteReceiptToken::try_from
.add_asset("^uvoted_on_(?P<data>(?P<proposal_id>[0-9]+))$",
&[
"^mvoted_on_(?P<data>(?P<proposal_id>[0-9]+))$",
"^voted_on_(?P<data>(?P<proposal_id>[0-9]+))$",
],
(|data: &str| {
assert!(!data.is_empty());
denom_metadata::Inner::new(format!("uvoted_on_{data}"), vec![
denom_metadata::BareDenomUnit {
exponent: 6,
denom: format!("voted_on_{data}"),
},
denom_metadata::BareDenomUnit {
exponent: 3,
denom: format!("mvoted_on_{data}"),
},
])
}) as for<'r> fn(&'r str) -> _
)
.add_asset(
"^auctionnft_(?P<data>[a-z_0-9]+_pauctid1[a-zA-HJ-NP-Z0-9]+)$",
&[ /* no display units - nft, unit 1 */ ],
(|data: &str| {
assert!(!data.is_empty());
denom_metadata::Inner::new(format!("auctionnft_{data}"), vec![])
}) as for<'r> fn(&'r str) -> _,
)
.build()
});