Struct cardano_serialization_lib::crypto::Bip32PublicKey
source · pub struct Bip32PublicKey(_);
Implementations§
source§impl Bip32PublicKey
impl Bip32PublicKey
sourcepub fn derive(&self, index: u32) -> Result<Bip32PublicKey, JsError>
pub fn derive(&self, index: u32) -> Result<Bip32PublicKey, JsError>
derive this public key with the given index.
Errors
If the index is not a soft derivation index (< 0x80000000) then calling this method will fail.
Security considerations
- hard derivation index cannot be soft derived with the public key
Hard derivation vs Soft derivation
If you pass an index below 0x80000000 then it is a soft derivation. The advantage of soft derivation is that it is possible to derive the public key too. I.e. derivation the private key with a soft derivation index and then retrieving the associated public key is equivalent to deriving the public key associated to the parent private key.
Hard derivation index does not allow public key derivation.
This is why deriving the private key should not fail while deriving the public key may fail (if the derivation index is invalid).
sourcepub fn to_raw_key(&self) -> PublicKey
pub fn to_raw_key(&self) -> PublicKey
Examples found in repository?
More examples
src/utils.rs (line 1192)
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
pub fn make_daedalus_bootstrap_witness(
tx_body_hash: &TransactionHash,
addr: &ByronAddress,
key: &LegacyDaedalusPrivateKey,
) -> BootstrapWitness {
let chain_code = key.chaincode();
let pubkey = Bip32PublicKey::from_bytes(&key.0.to_public().as_ref()).unwrap();
let vkey = Vkey::new(&pubkey.to_raw_key());
let signature =
Ed25519Signature::from_bytes(key.0.sign(&tx_body_hash.to_bytes()).as_ref().to_vec())
.unwrap();
BootstrapWitness::new(&vkey, &signature, chain_code, addr.attributes())
}
#[wasm_bindgen]
pub fn make_icarus_bootstrap_witness(
tx_body_hash: &TransactionHash,
addr: &ByronAddress,
key: &Bip32PrivateKey,
) -> BootstrapWitness {
let chain_code = key.chaincode();
let raw_key = key.to_raw_key();
let vkey = Vkey::new(&raw_key.to_public());
let signature = raw_key.sign(&tx_body_hash.to_bytes());
BootstrapWitness::new(&vkey, &signature, chain_code, addr.attributes())
}
#[wasm_bindgen]
pub fn make_vkey_witness(tx_body_hash: &TransactionHash, sk: &PrivateKey) -> Vkeywitness {
let sig = sk.sign(tx_body_hash.0.as_ref());
Vkeywitness::new(&Vkey::new(&sk.to_public()), &sig)
}
#[wasm_bindgen]
pub fn hash_auxiliary_data(auxiliary_data: &AuxiliaryData) -> AuxiliaryDataHash {
AuxiliaryDataHash::from(blake2b256(&auxiliary_data.to_bytes()))
}
#[wasm_bindgen]
pub fn hash_transaction(tx_body: &TransactionBody) -> TransactionHash {
TransactionHash::from(crypto::blake2b256(tx_body.to_bytes().as_ref()))
}
#[wasm_bindgen]
pub fn hash_plutus_data(plutus_data: &PlutusData) -> DataHash {
DataHash::from(blake2b256(&plutus_data.to_bytes()))
}
#[wasm_bindgen]
pub fn hash_script_data(
redeemers: &Redeemers,
cost_models: &Costmdls,
datums: Option<PlutusList>,
) -> ScriptDataHash {
let mut buf = Vec::new();
if redeemers.len() == 0 && datums.is_some() {
/*
; Finally, note that in the case that a transaction includes datums but does not
; include any redeemers, the script data format becomes (in hex):
; [ 80 | datums | A0 ]
; corresponding to a CBOR empty list and an empty map (our apologies).
*/
buf.push(0x80);
if let Some(d) = &datums {
buf.extend(d.to_bytes());
}
buf.push(0xA0);
} else {
/*
; script data format:
; [ redeemers | datums | language views ]
; The redeemers are exactly the data present in the transaction witness set.
; Similarly for the datums, if present. If no datums are provided, the middle
; field is an empty string.
*/
buf.extend(redeemers.to_bytes());
if let Some(d) = &datums {
buf.extend(d.to_bytes());
}
buf.extend(cost_models.language_views_encoding());
}
ScriptDataHash::from(blake2b256(&buf))
}
// wasm-bindgen can't accept Option without clearing memory, so we avoid exposing this in WASM
pub fn internal_get_implicit_input(
withdrawals: &Option<Withdrawals>,
certs: &Option<Certificates>,
pool_deposit: &BigNum, // // protocol parameter
key_deposit: &BigNum, // protocol parameter
) -> Result<Value, JsError> {
let withdrawal_sum = match &withdrawals {
None => to_bignum(0),
Some(x) => {
x.0.values()
.try_fold(to_bignum(0), |acc, ref withdrawal_amt| {
acc.checked_add(&withdrawal_amt)
})?
}
};
let certificate_refund = match &certs {
None => to_bignum(0),
Some(certs) => certs
.0
.iter()
.try_fold(to_bignum(0), |acc, ref cert| match &cert.0 {
CertificateEnum::PoolRetirement(_cert) => acc.checked_add(&pool_deposit),
CertificateEnum::StakeDeregistration(_cert) => acc.checked_add(&key_deposit),
_ => Ok(acc),
})?,
};
Ok(Value::new(
&withdrawal_sum.checked_add(&certificate_refund)?,
))
}
pub fn internal_get_deposit(
certs: &Option<Certificates>,
pool_deposit: &BigNum, // // protocol parameter
key_deposit: &BigNum, // protocol parameter
) -> Result<Coin, JsError> {
let certificate_refund = match &certs {
None => to_bignum(0),
Some(certs) => certs
.0
.iter()
.try_fold(to_bignum(0), |acc, ref cert| match &cert.0 {
CertificateEnum::PoolRegistration(_cert) => acc.checked_add(&pool_deposit),
CertificateEnum::StakeRegistration(_cert) => acc.checked_add(&key_deposit),
_ => Ok(acc),
})?,
};
Ok(certificate_refund)
}
#[wasm_bindgen]
pub fn get_implicit_input(
txbody: &TransactionBody,
pool_deposit: &BigNum, // // protocol parameter
key_deposit: &BigNum, // protocol parameter
) -> Result<Value, JsError> {
internal_get_implicit_input(
&txbody.withdrawals,
&txbody.certs,
&pool_deposit,
&key_deposit,
)
}
#[wasm_bindgen]
pub fn get_deposit(
txbody: &TransactionBody,
pool_deposit: &BigNum, // // protocol parameter
key_deposit: &BigNum, // protocol parameter
) -> Result<Coin, JsError> {
internal_get_deposit(&txbody.certs, &pool_deposit, &key_deposit)
}
#[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct MinOutputAdaCalculator {
output: TransactionOutput,
data_cost: DataCost,
}
impl MinOutputAdaCalculator {
pub fn new(output: &TransactionOutput, data_cost: &DataCost) -> Self {
Self {
output: output.clone(),
data_cost: data_cost.clone(),
}
}
pub fn new_empty(data_cost: &DataCost) -> Result<MinOutputAdaCalculator, JsError> {
Ok(Self {
output: MinOutputAdaCalculator::create_fake_output()?,
data_cost: data_cost.clone(),
})
}
pub fn set_address(&mut self, address: &Address) {
self.output.address = address.clone();
}
pub fn set_plutus_data(&mut self, data: &PlutusData) {
self.output.plutus_data = Some(DataOption::Data(data.clone()));
}
pub fn set_data_hash(&mut self, data_hash: &DataHash) {
self.output.plutus_data = Some(DataOption::DataHash(data_hash.clone()));
}
pub fn set_amount(&mut self, amount: &Value) {
self.output.amount = amount.clone();
}
pub fn set_script_ref(&mut self, script_ref: &ScriptRef) {
self.output.script_ref = Some(script_ref.clone());
}
pub fn calculate_ada(&self) -> Result<BigNum, JsError> {
let mut output: TransactionOutput = self.output.clone();
for _ in 0..3 {
let required_coin = Self::calc_required_coin(&output, &self.data_cost)?;
if output.amount.coin.less_than(&required_coin) {
output.amount.coin = required_coin.clone();
} else {
return Ok(required_coin);
}
}
output.amount.coin = to_bignum(u64::MAX);
Ok(Self::calc_required_coin(&output, &self.data_cost)?)
}
fn create_fake_output() -> Result<TransactionOutput, JsError> {
let fake_base_address: Address = Address::from_bech32("addr_test1qpu5vlrf4xkxv2qpwngf6cjhtw542ayty80v8dyr49rf5ewvxwdrt70qlcpeeagscasafhffqsxy36t90ldv06wqrk2qum8x5w")?;
let fake_value: Value = Value::new(&to_bignum(1000000));
Ok(TransactionOutput::new(&fake_base_address, &fake_value))
}
pub fn calc_size_cost(data_cost: &DataCost, size: usize) -> Result<Coin, JsError> {
//according to https://hydra.iohk.io/build/15339994/download/1/babbage-changes.pdf
//See on the page 9 getValue txout
to_bignum(size as u64).checked_add(&to_bignum(160))?
.checked_mul(&data_cost.coins_per_byte())
}
pub fn calc_required_coin(output: &TransactionOutput, data_cost: &DataCost) -> Result<Coin, JsError> {
//according to https://hydra.iohk.io/build/15339994/download/1/babbage-changes.pdf
//See on the page 9 getValue txout
Self::calc_size_cost(data_cost,output.to_bytes().len())
}
}
///returns minimal amount of ada for the output for case when the amount is included to the output
#[wasm_bindgen]
pub fn min_ada_for_output(
output: &TransactionOutput,
data_cost: &DataCost,
) -> Result<BigNum, JsError> {
MinOutputAdaCalculator::new(output, data_cost).calculate_ada()
}
/// !!! DEPRECATED !!!
/// This function uses outdated set of arguments.
/// Use `min_ada_for_output` instead
#[wasm_bindgen]
#[deprecated(since = "11.0.0", note = "Use `min_ada_for_output` instead")]
pub fn min_ada_required(
assets: &Value,
has_data_hash: bool, // whether the output includes a data hash
coins_per_utxo_word: &BigNum, // protocol parameter (in lovelace)
) -> Result<BigNum, JsError> {
let data_cost = DataCost::new_coins_per_word(coins_per_utxo_word);
let mut calc = MinOutputAdaCalculator::new_empty(&data_cost)?;
calc.set_amount(assets);
if has_data_hash {
calc.set_data_hash(&fake_data_hash(0));
}
calc.calculate_ada()
}
/// Used to choosed the schema for a script JSON string
#[wasm_bindgen]
pub enum ScriptSchema {
Wallet,
Node,
}
/// Receives a script JSON string
/// and returns a NativeScript.
/// Cardano Wallet and Node styles are supported.
///
/// * wallet: https://github.com/input-output-hk/cardano-wallet/blob/master/specifications/api/swagger.yaml
/// * node: https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/simple-scripts.md
///
/// self_xpub is expected to be a Bip32PublicKey as hex-encoded bytes
#[wasm_bindgen]
pub fn encode_json_str_to_native_script(
json: &str,
self_xpub: &str,
schema: ScriptSchema,
) -> Result<NativeScript, JsError> {
let value: serde_json::Value =
serde_json::from_str(&json).map_err(|e| JsError::from_str(&e.to_string()))?;
let native_script = match schema {
ScriptSchema::Wallet => encode_wallet_value_to_native_script(value, self_xpub)?,
ScriptSchema::Node => todo!(),
};
Ok(native_script)
}
fn encode_wallet_value_to_native_script(
value: serde_json::Value,
self_xpub: &str,
) -> Result<NativeScript, JsError> {
match value {
serde_json::Value::Object(map)
if map.contains_key("cosigners") && map.contains_key("template") =>
{
let mut cosigners = HashMap::new();
if let serde_json::Value::Object(cosigner_map) = map.get("cosigners").unwrap() {
for (key, value) in cosigner_map.iter() {
if let serde_json::Value::String(xpub) = value {
if xpub == "self" {
cosigners.insert(key.to_owned(), self_xpub.to_owned());
} else {
cosigners.insert(key.to_owned(), xpub.to_owned());
}
} else {
return Err(JsError::from_str("cosigner value must be a string"));
}
}
} else {
return Err(JsError::from_str("cosigners must be a map"));
}
let template = map.get("template").unwrap();
let template_native_script = encode_template_to_native_script(template, &cosigners)?;
Ok(template_native_script)
}
_ => Err(JsError::from_str(
"top level must be an object. cosigners and template keys are required",
)),
}
}
fn encode_template_to_native_script(
template: &serde_json::Value,
cosigners: &HashMap<String, String>,
) -> Result<NativeScript, JsError> {
match template {
serde_json::Value::String(cosigner) => {
if let Some(xpub) = cosigners.get(cosigner) {
let bytes = Vec::from_hex(xpub).map_err(|e| JsError::from_str(&e.to_string()))?;
let public_key = Bip32PublicKey::from_bytes(&bytes)?;
Ok(NativeScript::new_script_pubkey(&ScriptPubkey::new(
&public_key.to_raw_key().hash(),
)))
} else {
Err(JsError::from_str(&format!(
"cosigner {} not found",
cosigner
)))
}
}
serde_json::Value::Object(map) if map.contains_key("all") => {
let mut all = NativeScripts::new();
if let serde_json::Value::Array(array) = map.get("all").unwrap() {
for val in array {
all.add(&encode_template_to_native_script(val, cosigners)?);
}
} else {
return Err(JsError::from_str("all must be an array"));
}
Ok(NativeScript::new_script_all(&ScriptAll::new(&all)))
}
serde_json::Value::Object(map) if map.contains_key("any") => {
let mut any = NativeScripts::new();
if let serde_json::Value::Array(array) = map.get("any").unwrap() {
for val in array {
any.add(&encode_template_to_native_script(val, cosigners)?);
}
} else {
return Err(JsError::from_str("any must be an array"));
}
Ok(NativeScript::new_script_any(&ScriptAny::new(&any)))
}
serde_json::Value::Object(map) if map.contains_key("some") => {
if let serde_json::Value::Object(some) = map.get("some").unwrap() {
if some.contains_key("at_least") && some.contains_key("from") {
let n = if let serde_json::Value::Number(at_least) =
some.get("at_least").unwrap()
{
if let Some(n) = at_least.as_u64() {
n as u32
} else {
return Err(JsError::from_str("at_least must be an integer"));
}
} else {
return Err(JsError::from_str("at_least must be an integer"));
};
let mut from_scripts = NativeScripts::new();
if let serde_json::Value::Array(array) = some.get("from").unwrap() {
for val in array {
from_scripts.add(&encode_template_to_native_script(val, cosigners)?);
}
} else {
return Err(JsError::from_str("from must be an array"));
}
Ok(NativeScript::new_script_n_of_k(&ScriptNOfK::new(
n,
&from_scripts,
)))
} else {
Err(JsError::from_str("some must contain at_least and from"))
}
} else {
Err(JsError::from_str("some must be an object"))
}
}
serde_json::Value::Object(map) if map.contains_key("active_from") => {
if let serde_json::Value::Number(active_from) = map.get("active_from").unwrap() {
if let Some(n) = active_from.as_u64() {
let slot: SlotBigNum = n.into();
let time_lock_start = TimelockStart::new_timelockstart(&slot);
Ok(NativeScript::new_timelock_start(&time_lock_start))
} else {
Err(JsError::from_str(
"active_from slot must be an integer greater than or equal to 0",
))
}
} else {
Err(JsError::from_str("active_from slot must be a number"))
}
}
serde_json::Value::Object(map) if map.contains_key("active_until") => {
if let serde_json::Value::Number(active_until) = map.get("active_until").unwrap() {
if let Some(n) = active_until.as_u64() {
let slot: SlotBigNum = n.into();
let time_lock_expiry = TimelockExpiry::new_timelockexpiry(&slot);
Ok(NativeScript::new_timelock_expiry(&time_lock_expiry))
} else {
Err(JsError::from_str(
"active_until slot must be an integer greater than or equal to 0",
))
}
} else {
Err(JsError::from_str("active_until slot must be a number"))
}
}
_ => Err(JsError::from_str("invalid template format")),
}
}
sourcepub fn from_bytes(bytes: &[u8]) -> Result<Bip32PublicKey, JsError>
pub fn from_bytes(bytes: &[u8]) -> Result<Bip32PublicKey, JsError>
Examples found in repository?
More examples
src/utils.rs (line 1191)
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
pub fn make_daedalus_bootstrap_witness(
tx_body_hash: &TransactionHash,
addr: &ByronAddress,
key: &LegacyDaedalusPrivateKey,
) -> BootstrapWitness {
let chain_code = key.chaincode();
let pubkey = Bip32PublicKey::from_bytes(&key.0.to_public().as_ref()).unwrap();
let vkey = Vkey::new(&pubkey.to_raw_key());
let signature =
Ed25519Signature::from_bytes(key.0.sign(&tx_body_hash.to_bytes()).as_ref().to_vec())
.unwrap();
BootstrapWitness::new(&vkey, &signature, chain_code, addr.attributes())
}
#[wasm_bindgen]
pub fn make_icarus_bootstrap_witness(
tx_body_hash: &TransactionHash,
addr: &ByronAddress,
key: &Bip32PrivateKey,
) -> BootstrapWitness {
let chain_code = key.chaincode();
let raw_key = key.to_raw_key();
let vkey = Vkey::new(&raw_key.to_public());
let signature = raw_key.sign(&tx_body_hash.to_bytes());
BootstrapWitness::new(&vkey, &signature, chain_code, addr.attributes())
}
#[wasm_bindgen]
pub fn make_vkey_witness(tx_body_hash: &TransactionHash, sk: &PrivateKey) -> Vkeywitness {
let sig = sk.sign(tx_body_hash.0.as_ref());
Vkeywitness::new(&Vkey::new(&sk.to_public()), &sig)
}
#[wasm_bindgen]
pub fn hash_auxiliary_data(auxiliary_data: &AuxiliaryData) -> AuxiliaryDataHash {
AuxiliaryDataHash::from(blake2b256(&auxiliary_data.to_bytes()))
}
#[wasm_bindgen]
pub fn hash_transaction(tx_body: &TransactionBody) -> TransactionHash {
TransactionHash::from(crypto::blake2b256(tx_body.to_bytes().as_ref()))
}
#[wasm_bindgen]
pub fn hash_plutus_data(plutus_data: &PlutusData) -> DataHash {
DataHash::from(blake2b256(&plutus_data.to_bytes()))
}
#[wasm_bindgen]
pub fn hash_script_data(
redeemers: &Redeemers,
cost_models: &Costmdls,
datums: Option<PlutusList>,
) -> ScriptDataHash {
let mut buf = Vec::new();
if redeemers.len() == 0 && datums.is_some() {
/*
; Finally, note that in the case that a transaction includes datums but does not
; include any redeemers, the script data format becomes (in hex):
; [ 80 | datums | A0 ]
; corresponding to a CBOR empty list and an empty map (our apologies).
*/
buf.push(0x80);
if let Some(d) = &datums {
buf.extend(d.to_bytes());
}
buf.push(0xA0);
} else {
/*
; script data format:
; [ redeemers | datums | language views ]
; The redeemers are exactly the data present in the transaction witness set.
; Similarly for the datums, if present. If no datums are provided, the middle
; field is an empty string.
*/
buf.extend(redeemers.to_bytes());
if let Some(d) = &datums {
buf.extend(d.to_bytes());
}
buf.extend(cost_models.language_views_encoding());
}
ScriptDataHash::from(blake2b256(&buf))
}
// wasm-bindgen can't accept Option without clearing memory, so we avoid exposing this in WASM
pub fn internal_get_implicit_input(
withdrawals: &Option<Withdrawals>,
certs: &Option<Certificates>,
pool_deposit: &BigNum, // // protocol parameter
key_deposit: &BigNum, // protocol parameter
) -> Result<Value, JsError> {
let withdrawal_sum = match &withdrawals {
None => to_bignum(0),
Some(x) => {
x.0.values()
.try_fold(to_bignum(0), |acc, ref withdrawal_amt| {
acc.checked_add(&withdrawal_amt)
})?
}
};
let certificate_refund = match &certs {
None => to_bignum(0),
Some(certs) => certs
.0
.iter()
.try_fold(to_bignum(0), |acc, ref cert| match &cert.0 {
CertificateEnum::PoolRetirement(_cert) => acc.checked_add(&pool_deposit),
CertificateEnum::StakeDeregistration(_cert) => acc.checked_add(&key_deposit),
_ => Ok(acc),
})?,
};
Ok(Value::new(
&withdrawal_sum.checked_add(&certificate_refund)?,
))
}
pub fn internal_get_deposit(
certs: &Option<Certificates>,
pool_deposit: &BigNum, // // protocol parameter
key_deposit: &BigNum, // protocol parameter
) -> Result<Coin, JsError> {
let certificate_refund = match &certs {
None => to_bignum(0),
Some(certs) => certs
.0
.iter()
.try_fold(to_bignum(0), |acc, ref cert| match &cert.0 {
CertificateEnum::PoolRegistration(_cert) => acc.checked_add(&pool_deposit),
CertificateEnum::StakeRegistration(_cert) => acc.checked_add(&key_deposit),
_ => Ok(acc),
})?,
};
Ok(certificate_refund)
}
#[wasm_bindgen]
pub fn get_implicit_input(
txbody: &TransactionBody,
pool_deposit: &BigNum, // // protocol parameter
key_deposit: &BigNum, // protocol parameter
) -> Result<Value, JsError> {
internal_get_implicit_input(
&txbody.withdrawals,
&txbody.certs,
&pool_deposit,
&key_deposit,
)
}
#[wasm_bindgen]
pub fn get_deposit(
txbody: &TransactionBody,
pool_deposit: &BigNum, // // protocol parameter
key_deposit: &BigNum, // protocol parameter
) -> Result<Coin, JsError> {
internal_get_deposit(&txbody.certs, &pool_deposit, &key_deposit)
}
#[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct MinOutputAdaCalculator {
output: TransactionOutput,
data_cost: DataCost,
}
impl MinOutputAdaCalculator {
pub fn new(output: &TransactionOutput, data_cost: &DataCost) -> Self {
Self {
output: output.clone(),
data_cost: data_cost.clone(),
}
}
pub fn new_empty(data_cost: &DataCost) -> Result<MinOutputAdaCalculator, JsError> {
Ok(Self {
output: MinOutputAdaCalculator::create_fake_output()?,
data_cost: data_cost.clone(),
})
}
pub fn set_address(&mut self, address: &Address) {
self.output.address = address.clone();
}
pub fn set_plutus_data(&mut self, data: &PlutusData) {
self.output.plutus_data = Some(DataOption::Data(data.clone()));
}
pub fn set_data_hash(&mut self, data_hash: &DataHash) {
self.output.plutus_data = Some(DataOption::DataHash(data_hash.clone()));
}
pub fn set_amount(&mut self, amount: &Value) {
self.output.amount = amount.clone();
}
pub fn set_script_ref(&mut self, script_ref: &ScriptRef) {
self.output.script_ref = Some(script_ref.clone());
}
pub fn calculate_ada(&self) -> Result<BigNum, JsError> {
let mut output: TransactionOutput = self.output.clone();
for _ in 0..3 {
let required_coin = Self::calc_required_coin(&output, &self.data_cost)?;
if output.amount.coin.less_than(&required_coin) {
output.amount.coin = required_coin.clone();
} else {
return Ok(required_coin);
}
}
output.amount.coin = to_bignum(u64::MAX);
Ok(Self::calc_required_coin(&output, &self.data_cost)?)
}
fn create_fake_output() -> Result<TransactionOutput, JsError> {
let fake_base_address: Address = Address::from_bech32("addr_test1qpu5vlrf4xkxv2qpwngf6cjhtw542ayty80v8dyr49rf5ewvxwdrt70qlcpeeagscasafhffqsxy36t90ldv06wqrk2qum8x5w")?;
let fake_value: Value = Value::new(&to_bignum(1000000));
Ok(TransactionOutput::new(&fake_base_address, &fake_value))
}
pub fn calc_size_cost(data_cost: &DataCost, size: usize) -> Result<Coin, JsError> {
//according to https://hydra.iohk.io/build/15339994/download/1/babbage-changes.pdf
//See on the page 9 getValue txout
to_bignum(size as u64).checked_add(&to_bignum(160))?
.checked_mul(&data_cost.coins_per_byte())
}
pub fn calc_required_coin(output: &TransactionOutput, data_cost: &DataCost) -> Result<Coin, JsError> {
//according to https://hydra.iohk.io/build/15339994/download/1/babbage-changes.pdf
//See on the page 9 getValue txout
Self::calc_size_cost(data_cost,output.to_bytes().len())
}
}
///returns minimal amount of ada for the output for case when the amount is included to the output
#[wasm_bindgen]
pub fn min_ada_for_output(
output: &TransactionOutput,
data_cost: &DataCost,
) -> Result<BigNum, JsError> {
MinOutputAdaCalculator::new(output, data_cost).calculate_ada()
}
/// !!! DEPRECATED !!!
/// This function uses outdated set of arguments.
/// Use `min_ada_for_output` instead
#[wasm_bindgen]
#[deprecated(since = "11.0.0", note = "Use `min_ada_for_output` instead")]
pub fn min_ada_required(
assets: &Value,
has_data_hash: bool, // whether the output includes a data hash
coins_per_utxo_word: &BigNum, // protocol parameter (in lovelace)
) -> Result<BigNum, JsError> {
let data_cost = DataCost::new_coins_per_word(coins_per_utxo_word);
let mut calc = MinOutputAdaCalculator::new_empty(&data_cost)?;
calc.set_amount(assets);
if has_data_hash {
calc.set_data_hash(&fake_data_hash(0));
}
calc.calculate_ada()
}
/// Used to choosed the schema for a script JSON string
#[wasm_bindgen]
pub enum ScriptSchema {
Wallet,
Node,
}
/// Receives a script JSON string
/// and returns a NativeScript.
/// Cardano Wallet and Node styles are supported.
///
/// * wallet: https://github.com/input-output-hk/cardano-wallet/blob/master/specifications/api/swagger.yaml
/// * node: https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/simple-scripts.md
///
/// self_xpub is expected to be a Bip32PublicKey as hex-encoded bytes
#[wasm_bindgen]
pub fn encode_json_str_to_native_script(
json: &str,
self_xpub: &str,
schema: ScriptSchema,
) -> Result<NativeScript, JsError> {
let value: serde_json::Value =
serde_json::from_str(&json).map_err(|e| JsError::from_str(&e.to_string()))?;
let native_script = match schema {
ScriptSchema::Wallet => encode_wallet_value_to_native_script(value, self_xpub)?,
ScriptSchema::Node => todo!(),
};
Ok(native_script)
}
fn encode_wallet_value_to_native_script(
value: serde_json::Value,
self_xpub: &str,
) -> Result<NativeScript, JsError> {
match value {
serde_json::Value::Object(map)
if map.contains_key("cosigners") && map.contains_key("template") =>
{
let mut cosigners = HashMap::new();
if let serde_json::Value::Object(cosigner_map) = map.get("cosigners").unwrap() {
for (key, value) in cosigner_map.iter() {
if let serde_json::Value::String(xpub) = value {
if xpub == "self" {
cosigners.insert(key.to_owned(), self_xpub.to_owned());
} else {
cosigners.insert(key.to_owned(), xpub.to_owned());
}
} else {
return Err(JsError::from_str("cosigner value must be a string"));
}
}
} else {
return Err(JsError::from_str("cosigners must be a map"));
}
let template = map.get("template").unwrap();
let template_native_script = encode_template_to_native_script(template, &cosigners)?;
Ok(template_native_script)
}
_ => Err(JsError::from_str(
"top level must be an object. cosigners and template keys are required",
)),
}
}
fn encode_template_to_native_script(
template: &serde_json::Value,
cosigners: &HashMap<String, String>,
) -> Result<NativeScript, JsError> {
match template {
serde_json::Value::String(cosigner) => {
if let Some(xpub) = cosigners.get(cosigner) {
let bytes = Vec::from_hex(xpub).map_err(|e| JsError::from_str(&e.to_string()))?;
let public_key = Bip32PublicKey::from_bytes(&bytes)?;
Ok(NativeScript::new_script_pubkey(&ScriptPubkey::new(
&public_key.to_raw_key().hash(),
)))
} else {
Err(JsError::from_str(&format!(
"cosigner {} not found",
cosigner
)))
}
}
serde_json::Value::Object(map) if map.contains_key("all") => {
let mut all = NativeScripts::new();
if let serde_json::Value::Array(array) = map.get("all").unwrap() {
for val in array {
all.add(&encode_template_to_native_script(val, cosigners)?);
}
} else {
return Err(JsError::from_str("all must be an array"));
}
Ok(NativeScript::new_script_all(&ScriptAll::new(&all)))
}
serde_json::Value::Object(map) if map.contains_key("any") => {
let mut any = NativeScripts::new();
if let serde_json::Value::Array(array) = map.get("any").unwrap() {
for val in array {
any.add(&encode_template_to_native_script(val, cosigners)?);
}
} else {
return Err(JsError::from_str("any must be an array"));
}
Ok(NativeScript::new_script_any(&ScriptAny::new(&any)))
}
serde_json::Value::Object(map) if map.contains_key("some") => {
if let serde_json::Value::Object(some) = map.get("some").unwrap() {
if some.contains_key("at_least") && some.contains_key("from") {
let n = if let serde_json::Value::Number(at_least) =
some.get("at_least").unwrap()
{
if let Some(n) = at_least.as_u64() {
n as u32
} else {
return Err(JsError::from_str("at_least must be an integer"));
}
} else {
return Err(JsError::from_str("at_least must be an integer"));
};
let mut from_scripts = NativeScripts::new();
if let serde_json::Value::Array(array) = some.get("from").unwrap() {
for val in array {
from_scripts.add(&encode_template_to_native_script(val, cosigners)?);
}
} else {
return Err(JsError::from_str("from must be an array"));
}
Ok(NativeScript::new_script_n_of_k(&ScriptNOfK::new(
n,
&from_scripts,
)))
} else {
Err(JsError::from_str("some must contain at_least and from"))
}
} else {
Err(JsError::from_str("some must be an object"))
}
}
serde_json::Value::Object(map) if map.contains_key("active_from") => {
if let serde_json::Value::Number(active_from) = map.get("active_from").unwrap() {
if let Some(n) = active_from.as_u64() {
let slot: SlotBigNum = n.into();
let time_lock_start = TimelockStart::new_timelockstart(&slot);
Ok(NativeScript::new_timelock_start(&time_lock_start))
} else {
Err(JsError::from_str(
"active_from slot must be an integer greater than or equal to 0",
))
}
} else {
Err(JsError::from_str("active_from slot must be a number"))
}
}
serde_json::Value::Object(map) if map.contains_key("active_until") => {
if let serde_json::Value::Number(active_until) = map.get("active_until").unwrap() {
if let Some(n) = active_until.as_u64() {
let slot: SlotBigNum = n.into();
let time_lock_expiry = TimelockExpiry::new_timelockexpiry(&slot);
Ok(NativeScript::new_timelock_expiry(&time_lock_expiry))
} else {
Err(JsError::from_str(
"active_until slot must be an integer greater than or equal to 0",
))
}
} else {
Err(JsError::from_str("active_until slot must be a number"))
}
}
_ => Err(JsError::from_str("invalid template format")),
}
}
sourcepub fn as_bytes(&self) -> Vec<u8>
pub fn as_bytes(&self) -> Vec<u8>
Examples found in repository?
More examples
src/address.rs (line 297)
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
pub fn icarus_from_key(key: &Bip32PublicKey, protocol_magic: u32) -> ByronAddress {
let mut out = [0u8; 64];
out.clone_from_slice(&key.as_bytes());
// need to ensure we use None for mainnet since Byron-era addresses omitted the network id
let filtered_protocol_magic = if protocol_magic == NetworkInfo::mainnet().protocol_magic() {
None
} else {
Some(protocol_magic)
};
ByronAddress(ExtendedAddr::new_simple(
&XPub::from_bytes(out),
filtered_protocol_magic,
))
}