Skip to content

Commit

Permalink
Merge pull request #216 from RGB-WG/runtime
Browse files Browse the repository at this point in the history
Refactor runtime and fs persistence
  • Loading branch information
dr-orlovsky authored Jul 10, 2024
2 parents 811e6ec + 0b98e6e commit 58afafe
Show file tree
Hide file tree
Showing 15 changed files with 244 additions and 1,002 deletions.
651 changes: 12 additions & 639 deletions Cargo.lock

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,17 @@ log = { workspace = true, optional = true }

[features]
default = ["esplora_blocking"]
all = ["esplora_blocking", "electrum_blocking", "serde", "log", "fs"]
all = ["esplora_blocking", "electrum_blocking", "serde", "log", "fs", "cli"]
fs = ["serde", "bp-wallet/fs"]
cli = ["fs"]
esplora_blocking = ["bp-esplora"]
electrum_blocking = ["bp-electrum"]
serde = ["serde_crate", "serde_yaml", "bp-std/serde", "descriptors/serde", "rgb-psbt/serde"]

[package.metadata.docs.rs]
features = ["all"]

[patch.crates-io]
bp-wallet = { git = "https://github.com/BP-WG/bp-wallet", branch = "runtime" }
rgb-core = { git = "https://github.com/RGB-WG/rgb-core", branch = "master" }
rgb-std = { git = "https://github.com/RGB-WG/rgb-std", branch = "runtime" }
2 changes: 1 addition & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ bp-wallet = { workspace = true, features = ["cli"] }
psbt = { workspace = true }
rgb-std = { workspace = true, features = ["serde"] }
rgb-interfaces = { workspace = true }
rgb-runtime = { version = "0.11.0-beta.6", path = "..", features = ["electrum_blocking", "esplora_blocking", "log", "serde", "fs"] }
rgb-runtime = { version = "0.11.0-beta.6", path = "..", features = ["electrum_blocking", "esplora_blocking", "log", "serde", "fs", "cli"] }
log = { workspace = true }
env_logger = "0.11.3"
clap = { version = "4.4.8", features = ["derive", "env"] }
Expand Down
54 changes: 30 additions & 24 deletions cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@

use std::fs;
use std::io::ErrorKind;
use std::path::Path;
use std::path::PathBuf;

use bpstd::{Wpkh, XpubDerivable};
use bpwallet::cli::{Args as BpArgs, Config, DescriptorOpts};
use bpwallet::Wallet;
use rgb::{AnyResolver, RgbDescr, StoredStock, StoredWallet, TapretKey, WalletError};
use rgbstd::persistence::fs::{LoadFs, StoreFs};
use rgbstd::persistence::Stock;
use rgb::persistence::Stock;
use rgb::resolvers::AnyResolver;
use rgb::{RgbDescr, RgbWallet, TapretKey, WalletError};
use strict_types::encoding::{DecodeError, DeserializeError};

use crate::Command;
Expand Down Expand Up @@ -77,53 +77,59 @@ impl Default for RgbArgs {
}

impl RgbArgs {
pub(crate) fn load_stock(&self, stock_path: &Path) -> Result<Stock, WalletError> {
pub(crate) fn load_stock(
&self,
stock_path: impl ToOwned<Owned = PathBuf>,
) -> Result<Stock, WalletError> {
let stock_path = stock_path.to_owned();

if self.verbose > 1 {
eprint!("Loading stock ... ");
eprint!("Loading stock from `{}` ... ", stock_path.display());
}

Stock::load(stock_path).map_err(WalletError::from).or_else(|err| {
let stock = Stock::load(stock_path.clone()).map_err(WalletError::from).or_else(|err| {
if matches!(err, WalletError::Deserialize(DeserializeError::Decode(DecodeError::Io(ref err))) if err.kind() == ErrorKind::NotFound) {
if self.verbose > 1 {
eprint!("stock file is absent, creating a new one ... ");
}
let stock = Stock::default();
fs::create_dir_all(stock_path)?;
stock.store(stock_path)?;
if self.verbose > 1 {
eprintln!("success");
}
fs::create_dir_all(stock_path.to_owned())?;
let stock = Stock::new(stock_path.to_owned());
stock.store()?;
return Ok(stock)
}
eprintln!("stock file is damaged, failing");
Err(err)
})
})?;

if self.verbose > 1 {
eprintln!("success");
}

Ok(stock)
}

pub fn rgb_stock(&self) -> Result<StoredStock, WalletError> {
pub fn rgb_stock(&self) -> Result<Stock, WalletError> {
let stock_path = self.general.base_dir();
let stock = self.load_stock(&stock_path)?;
Ok(StoredStock::attach(stock_path, stock))
let stock = self.load_stock(stock_path)?;
Ok(stock)
}

pub fn rgb_wallet(
&self,
config: &Config,
) -> Result<StoredWallet<Wallet<XpubDerivable, RgbDescr>>, WalletError> {
) -> Result<RgbWallet<Wallet<XpubDerivable, RgbDescr>>, WalletError> {
let stock_path = self.general.base_dir();
let stock = self.load_stock(&stock_path)?;
let stock = self.load_stock(stock_path)?;
self.rgb_wallet_from_stock(config, stock)
}

pub fn rgb_wallet_from_stock(
&self,
config: &Config,
stock: Stock,
) -> Result<StoredWallet<Wallet<XpubDerivable, RgbDescr>>, WalletError> {
let stock_path = self.general.base_dir();
let wallet = self.inner.bp_runtime::<RgbDescr>(config)?;
let wallet_path = wallet.path().clone();
let wallet = StoredWallet::attach(stock_path, wallet_path, stock, wallet.detach());
) -> Result<RgbWallet<Wallet<XpubDerivable, RgbDescr>>, WalletError> {
let wallet = self.inner.bp_wallet::<RgbDescr>(config)?;
let wallet = RgbWallet::new(stock, wallet);

Ok(wallet)
}
Expand Down
11 changes: 5 additions & 6 deletions cli/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,17 @@ use rgb::containers::{
BuilderSeal, ContainerVer, ContentId, ContentSigs, Contract, FileContent, Supplement, Terminal,
Transfer, UniversalFile,
};
use rgb::interface::{AmountChange, IfaceId};
use rgb::interface::{AmountChange, IfaceId, OutpointFilter};
use rgb::invoice::{Beneficiary, Pay2Vout, RgbInvoice, RgbInvoiceBuilder, XChainNet};
use rgb::persistence::StashReadProvider;
use rgb::schema::SchemaId;
use rgb::validation::Validity;
use rgb::vm::RgbIsa;
use rgb::{
BundleId, ContractId, DescriptorRgb, GenesisSeal, GraphSeal, Identity, OutputSeal, RgbDescr,
RgbKeychain, StateType, StoredWallet, TransferParams, WalletError, WalletProvider, XChain,
RgbKeychain, RgbWallet, StateType, TransferParams, WalletError, WalletProvider, XChain,
XOutpoint, XOutputSeal,
};
use rgbstd::interface::OutpointFilter;
use serde_crate::{Deserialize, Serialize};
use strict_types::encoding::{FieldName, TypeName};
use strict_types::StrictVal;
Expand Down Expand Up @@ -485,7 +484,7 @@ impl Exec for RgbArgs {
all,
} => {
let stock_path = self.general.base_dir();
let stock = self.load_stock(&stock_path)?;
let stock = self.load_stock(stock_path)?;

let contract = stock.contract_iface(*contract_id, tn!(iface.to_owned()))?;

Expand All @@ -508,8 +507,8 @@ impl Exec for RgbArgs {
}

enum Filter {
Wallet(StoredWallet<Wallet<XpubDerivable, RgbDescr>>),
WalletAll(StoredWallet<Wallet<XpubDerivable, RgbDescr>>),
Wallet(RgbWallet<Wallet<XpubDerivable, RgbDescr>>),
WalletAll(RgbWallet<Wallet<XpubDerivable, RgbDescr>>),
NoWallet,
}
impl OutpointFilter for Filter {
Expand Down
15 changes: 9 additions & 6 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,15 @@ pub enum WalletError {
Deserialize(DeserializeError),

#[from]
Load(LoadError),
StockLoad(LoadError),

#[cfg(feature = "fs")]
#[from]
WalletLoad(bpwallet::fs::LoadError),

#[cfg(feature = "cli")]
#[from]
WalletExect(bpwallet::cli::ExecError),

#[from]
Builder(BuilderError),
Expand Down Expand Up @@ -82,11 +90,6 @@ pub enum WalletError {
#[display(doc_comments)]
IncompleteContract(validation::Status),

#[cfg(feature = "fs")]
#[from]
#[from(bpwallet::LoadError)]
Bp(bpwallet::RuntimeError),

/// resolver error: {0}
#[display(doc_comments)]
Resolver(String),
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
22 changes: 12 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,22 @@ extern crate amplify;
extern crate serde_crate as serde;

mod descriptor;
#[allow(hidden_glob_reexports)]
mod resolvers;
mod wallet;
mod indexers;
mod wrapper;
pub mod pay;
mod errors;
#[cfg(feature = "fs")]
mod store;
mod wallet;

pub use descriptor::{DescriptorRgb, RgbDescr, RgbKeychain, TapTweakAlreadyAssigned, TapretKey};
pub use errors::{CompletionError, CompositionError, HistoryError, PayError, WalletError};
pub use pay::{TransferParams, WalletProvider};
#[cfg(any(feature = "electrum_blocking", feature = "esplora_blocking"))]
pub use resolvers::*;
pub use rgbstd::*;
#[cfg(feature = "fs")]
pub use store::{StoredStock, StoredWallet};
pub use wallet::{WalletStock, WalletWrapper};
pub mod resolvers {
pub use rgbstd::resolvers::*;

#[cfg(any(feature = "electrum_blocking", feature = "esplora_blocking"))]
pub use super::indexers::*;
pub use super::indexers::{AnyResolver, RgbResolver};
}
pub use wallet::RgbWallet;
pub use wrapper::WalletWrapper;
18 changes: 10 additions & 8 deletions src/pay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,12 @@

use std::collections::{BTreeMap, BTreeSet};
use std::marker::PhantomData;
use std::ops::DerefMut;

use bp::dbc::tapret::TapretProof;
use bp::seals::txout::ExplicitSeal;
use bp::{Outpoint, Sats, ScriptPubkey, Vout};
use bpstd::{psbt, Address};
use bpwallet::Wallet;
use bpwallet::{Save, Wallet, WalletDescr};
use psrgbt::{
Beneficiary as BpBeneficiary, Psbt, PsbtConstructor, PsbtMeta, RgbPsbt, TapretKeyError,
TxParams,
Expand All @@ -39,7 +38,7 @@ use rgbstd::persistence::{IndexProvider, StashProvider, StateProvider, Stock};
use rgbstd::{ContractId, DataState, XChain, XOutpoint};

use crate::invoice::NonFungible;
use crate::wallet::WalletWrapper;
use crate::wrapper::WalletWrapper;
use crate::{CompletionError, CompositionError, DescriptorRgb, PayError, RgbKeychain, Txid};

#[derive(Clone, PartialEq, Debug)]
Expand Down Expand Up @@ -99,7 +98,7 @@ where Self::Descr: DescriptorRgb<K>
type Filter<'a>: Copy + WitnessFilter + OutpointFilter
where Self: 'a;
fn filter(&self) -> Self::Filter<'_>;
fn descriptor_mut(&mut self) -> &mut Self::Descr;
fn descriptor_mut<R>(&mut self, f: impl FnOnce(&mut WalletDescr<K, Self::Descr>) -> R) -> R;
fn outpoints(&self) -> impl Iterator<Item = Outpoint>;
fn txids(&self) -> impl Iterator<Item = Txid>;

Expand Down Expand Up @@ -291,8 +290,7 @@ where Self::Descr: DescriptorRgb<K>
.terminal_derivation()
.ok_or(CompletionError::InconclusiveDerivation)?;
let tapret_commitment = output.tapret_commitment()?;
self.descriptor_mut()
.add_tapret_tweak(terminal, tapret_commitment)?;
self.descriptor_mut(|descr| descr.add_tapret_tweak(terminal, tapret_commitment))?;
}

let witness_txid = psbt.txid();
Expand Down Expand Up @@ -322,10 +320,14 @@ where Self::Descr: DescriptorRgb<K>
}
}

impl<K, D: DescriptorRgb<K>> WalletProvider<K> for Wallet<K, D> {
impl<K, D: DescriptorRgb<K>> WalletProvider<K> for Wallet<K, D>
where Wallet<K, D>: Save
{
type Filter<'a> = WalletWrapper<'a, K, D> where Self: 'a;
fn filter(&self) -> Self::Filter<'_> { WalletWrapper(self) }
fn descriptor_mut(&mut self) -> &mut Self::Descr { self.deref_mut() }
fn descriptor_mut<R>(&mut self, f: impl FnOnce(&mut WalletDescr<K, D>) -> R) -> R {
self.descriptor_mut(f)
}
fn outpoints(&self) -> impl Iterator<Item = Outpoint> { self.coins().map(|coin| coin.outpoint) }
fn txids(&self) -> impl Iterator<Item = Txid> { self.transactions().keys().copied() }
}
Loading

0 comments on commit 58afafe

Please sign in to comment.