/jcli/src/jcli_app/transaction/add_witness.rs

https://github.com/input-output-hk/jormungandr · Rust · 66 lines · 57 code · 9 blank · 0 comment · 2 complexity · bd13515dc240ab3960bc54fab3fff7bd MD5 · raw file

  1. use crate::jcli_app::{
  2. transaction::{common, Error},
  3. utils::io,
  4. };
  5. use bech32::{self, FromBase32 as _};
  6. use chain_core::mempack::{ReadBuf, Readable as _};
  7. use chain_impl_mockchain::transaction::Witness;
  8. use std::path::PathBuf;
  9. use structopt::StructOpt;
  10. #[derive(StructOpt)]
  11. #[structopt(rename_all = "kebab-case")]
  12. pub struct AddWitness {
  13. #[structopt(flatten)]
  14. pub common: common::CommonTransaction,
  15. pub witness: PathBuf,
  16. }
  17. impl AddWitness {
  18. pub fn exec(self) -> Result<(), Error> {
  19. let mut transaction = self.common.load()?;
  20. let witness = self.witness()?;
  21. transaction.add_witness(witness)?;
  22. self.common.store(&transaction)?;
  23. Ok(())
  24. }
  25. fn witness(&self) -> Result<Witness, Error> {
  26. const HRP: &str = "witness";
  27. let bech32_str =
  28. io::read_line(&Some(&self.witness)).map_err(|source| Error::WitnessFileReadFailed {
  29. source,
  30. path: self.witness.clone(),
  31. })?;
  32. let (hrp, data) = bech32::decode(bech32_str.trim()).map_err(|source| {
  33. Error::WitnessFileBech32Malformed {
  34. source,
  35. path: self.witness.clone(),
  36. }
  37. })?;
  38. if hrp != HRP {
  39. return Err(Error::WitnessFileBech32HrpInvalid {
  40. expected: HRP,
  41. actual: hrp,
  42. path: self.witness.clone(),
  43. });
  44. }
  45. let bytes =
  46. Vec::from_base32(&data).map_err(|source| Error::WitnessFileBech32Malformed {
  47. source,
  48. path: self.witness.clone(),
  49. })?;
  50. Witness::read(&mut ReadBuf::from(&bytes)).map_err(|source| {
  51. Error::WitnessFileDeserializationFailed {
  52. source,
  53. path: self.witness.clone(),
  54. }
  55. })
  56. }
  57. }