Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove required electrum resolver #23

Merged
merged 6 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 22 additions & 19 deletions src/bin/rgb/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use amplify::confinement::U16;
use bitcoin::bip32::ExtendedPubKey;
use bitcoin::psbt::Psbt;
use bp::seals::txout::{CloseMethod, ExplicitSeal, TxPtr};
use rgb::{Runtime, RuntimeError};
use rgb::{BlockchainResolver, Runtime, RuntimeError};
use rgbstd::containers::{Bindle, Transfer, UniversalBindle};
use rgbstd::contract::{ContractId, GenesisSeal, GraphSeal, StateType};
use rgbstd::interface::{ContractBuilder, SchemaIfaces, TypedState};
Expand Down Expand Up @@ -224,7 +224,11 @@ pub enum Command {
}

impl Command {
pub fn exec(self, runtime: &mut Runtime) -> Result<(), RuntimeError> {
pub fn exec(
self,
runtime: &mut Runtime,
resolver: &mut BlockchainResolver,
) -> Result<(), RuntimeError> {
match self {
Command::Schemata => {
for id in runtime.schema_ids()? {
Expand Down Expand Up @@ -301,14 +305,10 @@ impl Command {
}
UniversalBindle::Contract(bindle) => {
let id = bindle.id();
let contract =
bindle
.unbindle()
.validate(runtime.resolver())
.map_err(|c| {
c.validation_status().expect("just validated").to_string()
})?;
runtime.import_contract(contract)?;
let contract = bindle.unbindle().validate(resolver).map_err(|c| {
c.validation_status().expect("just validated").to_string()
})?;
runtime.import_contract(contract, resolver)?;
eprintln!("Contract {id} imported to the stash");
}
UniversalBindle::Transfer(_) => {
Expand Down Expand Up @@ -341,7 +341,13 @@ impl Command {
contract_id,
iface,
} => {
let wallet = wallet.map(|w| runtime.wallet(&w)).transpose()?;
let wallet = wallet
.map(|w| -> Result<_, RuntimeError> {
let mut wallet = runtime.wallet(&w)?;
wallet.update(resolver)?;
Ok(wallet)
})
.transpose()?;

let iface = runtime.iface_by_name(&tn!(iface))?.clone();
let contract = runtime.contract_iface(contract_id, iface.iface_id())?;
Expand Down Expand Up @@ -516,10 +522,10 @@ impl Command {
let contract = builder.issue_contract().expect("failure issuing contract");
let id = contract.contract_id();
let validated_contract = contract
.validate(runtime.resolver())
.validate(resolver)
.map_err(|_| RuntimeError::IncompleteContract)?;
runtime
.import_contract(validated_contract)
.import_contract(validated_contract, resolver)
.expect("failure importing issued contract");
eprintln!(
"A new contract {id} is issued and added to the stash.\nUse `export` command \
Expand Down Expand Up @@ -681,7 +687,7 @@ impl Command {
}
Command::Validate { file } => {
let bindle = Bindle::<Transfer>::load(file)?;
let status = match bindle.unbindle().validate(runtime.resolver()) {
let status = match bindle.unbindle().validate(resolver) {
Ok(consignment) => consignment.into_validation_status(),
Err(consignment) => consignment.into_validation_status(),
}
Expand All @@ -690,12 +696,9 @@ impl Command {
}
Command::Accept { force, file } => {
let bindle = Bindle::<Transfer>::load(file)?;
let transfer = bindle
.unbindle()
.validate(runtime.resolver())
.unwrap_or_else(|c| c);
let transfer = bindle.unbindle().validate(resolver).unwrap_or_else(|c| c);
eprintln!("{}", transfer.validation_status().expect("just validated"));
runtime.accept_transfer(transfer, force)?;
runtime.accept_transfer(transfer, resolver, force)?;
eprintln!("Transfer accepted into the stash");
}
Command::SetHost { method, psbt_file } => {
Expand Down
7 changes: 4 additions & 3 deletions src/bin/rgb/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ mod command;
use std::process::ExitCode;

use clap::Parser;
use rgb::{DefaultResolver, Runtime, RuntimeError};
use rgb::{BlockchainResolver, DefaultResolver, Runtime, RuntimeError};

pub use crate::command::Command;
pub use crate::loglevel::LogLevel;
Expand Down Expand Up @@ -73,8 +73,9 @@ fn run() -> Result<(), RuntimeError> {
.electrum
.unwrap_or_else(|| opts.chain.default_resolver());

let mut runtime = Runtime::load(opts.data_dir.clone(), opts.chain, &electrum)?;
let mut resolver = BlockchainResolver::with(&electrum)?;
let mut runtime = Runtime::load(opts.data_dir.clone(), opts.chain)?;
debug!("Executing command: {}", opts.command);
opts.command.exec(&mut runtime)?;
opts.command.exec(&mut runtime, &mut resolver)?;
Ok(())
}
20 changes: 8 additions & 12 deletions src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,6 @@ pub struct Runtime {
wallets: HashMap<Ident, RgbDescr>,
#[getter(as_copy)]
chain: Chain,
#[getter(skip)]
resolver: BlockchainResolver,
}

impl Deref for Runtime {
Expand All @@ -118,7 +116,7 @@ impl DerefMut for Runtime {
}

impl Runtime {
pub fn load(mut data_dir: PathBuf, chain: Chain, electrum: &str) -> Result<Self, RuntimeError> {
pub fn load(mut data_dir: PathBuf, chain: Chain) -> Result<Self, RuntimeError> {
data_dir.push(chain.to_string());
debug!("Using data directory '{}'", data_dir.display());
fs::create_dir_all(&data_dir)?;
Expand Down Expand Up @@ -146,22 +144,17 @@ impl Runtime {
serde_yaml::from_reader(&wallets_fd)?
};

let resolver = BlockchainResolver::with(electrum)?;

Ok(Self {
stock_path,
wallets_path,
stock,
wallets,
chain,
resolver,
})
}

pub fn unload(self) -> () {}

pub fn resolver(&mut self) -> &mut BlockchainResolver { &mut self.resolver }

pub fn create_wallet(
&mut self,
name: &Ident,
Expand All @@ -183,35 +176,38 @@ impl Runtime {
.wallets
.get(name)
.ok_or(RuntimeError::WalletUnknown(name.clone()))?;
RgbWallet::with(descr.clone(), &mut self.resolver).map_err(RuntimeError::from)
Ok(RgbWallet::new(descr.clone()))
}

pub fn import_contract(
&mut self,
contract: Contract,
resolver: &mut BlockchainResolver,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need to take the resolver as a mutable reference? By looking to the code I cannot see where there's the need to change the struct. Making it immutable it would simplify its usage.
Same question applies to all runtime methods that take the resolver as a mutable reference

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason is that I assume resolver can be a caching resolver, significantly improving validation performance. I mean for the first time the resolver is asked for certain tx it goes to electrum/esplora, caches the answer - and the next time it uses the cache. Such a resolver need to be mutable.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So right now it's not necessary but in the near future it will be, therefore it makes sense defining it as a mutable reference right away

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, since otherwise it will be hard to adopt change to mutable type downstream in the future - and introduction of a simple caching resolver (which is trivial to do as a wrapper type and is not a breaking change) will become a breaking change requiring major version increase.

) -> Result<validation::Status, RuntimeError> {
self.stock
.import_contract(contract, &mut self.resolver)
.import_contract(contract, resolver)
.map_err(RuntimeError::from)
}

pub fn validate_transfer<'transfer>(
&mut self,
transfer: Transfer,
resolver: &mut BlockchainResolver,
) -> Result<Transfer, RuntimeError> {
transfer
.validate(&mut self.resolver)
.validate(resolver)
.map_err(|invalid| invalid.validation_status().expect("just validated").clone())
.map_err(RuntimeError::from)
}

pub fn accept_transfer(
&mut self,
transfer: Transfer,
resolver: &mut BlockchainResolver,
force: bool,
) -> Result<validation::Status, RuntimeError> {
self.stock
.accept_transfer(transfer, &mut self.resolver, force)
.accept_transfer(transfer, resolver, force)
.map_err(RuntimeError::from)
}
}
Expand Down
17 changes: 11 additions & 6 deletions src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,26 +59,31 @@ pub struct RgbWallet {
}

impl RgbWallet {
pub fn with(descr: RgbDescr, resolver: &mut impl Resolver) -> Result<Self, String> {
let mut utxos = BTreeSet::new();
pub fn new(descr: RgbDescr) -> Self {
Self {
descr,
utxos: empty!(),
}
}

pub fn update(&mut self, resolver: &mut impl Resolver) -> Result<(), String> {
const STEP: u32 = 20;
for app in [0, 1, 10, 20, 30, 40, 50, 60] {
for app in [0, 1, 9, 10] {
let mut index = 0;
loop {
debug!("Requesting {STEP} scripts from the Electrum server");
let scripts = descr.derive(app, index..(index + STEP));
let scripts = self.descr.derive(app, index..(index + STEP));
let set = resolver.resolve_utxo(scripts)?;
if set.is_empty() {
break;
}
debug!("Electrum server returned {} UTXOs", set.len());
utxos.extend(set);
self.utxos.extend(set);
index += STEP;
}
}

Ok(Self { descr, utxos })
Ok(())
}

pub fn utxo(&self, outpoint: Outpoint) -> Option<&Utxo> {
Expand Down
Loading