Skip to content

Commit

Permalink
docs: document ScriptUnlocker
Browse files Browse the repository at this point in the history
  • Loading branch information
doitian committed Sep 6, 2023
1 parent 94ce437 commit 6ba5d8d
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 2 deletions.
124 changes: 124 additions & 0 deletions examples/script_unlocker_example.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
use ckb_sdk::{
traits::TransactionDependencyProvider,
unlock::{ScriptUnlocker, UnlockError},
ScriptGroup, ScriptId,
};
use ckb_types::{
bytes::Bytes,
core::{ScriptHashType, TransactionView},
h256,
packed::{self, WitnessArgs},
prelude::*,
};
use std::collections::HashMap;

/// An unlocker for the example script [CapacityDiff].
///
/// [CapacityDiff]: https://github.com/doitian/ckb-sdk-examples-capacity-diff
struct CapacityDiffUnlocker {}

impl ScriptUnlocker for CapacityDiffUnlocker {
// This works for any args
fn match_args(&self, _args: &[u8]) -> bool {
true
}

fn unlock(
&self,
tx: &TransactionView,
script_group: &ScriptGroup,
tx_dep_provider: &dyn TransactionDependencyProvider,
) -> std::result::Result<TransactionView, UnlockError> {
let witness_index = script_group.input_indices[0];
let mut witnesses: Vec<packed::Bytes> = tx.witnesses().into_iter().collect();
while witnesses.len() <= witness_index {
witnesses.push(Default::default());
}
let witness_bytes = &witnesses[witness_index];
let builder = if witness_bytes.is_empty() {
WitnessArgs::new_builder()
} else {
WitnessArgs::from_slice(witness_bytes.raw_data().as_ref())
.map_err(|_| UnlockError::InvalidWitnessArgs(witness_index))?
.as_builder()
};

let mut total = 0i64;
for i in &script_group.input_indices {
let cell = tx_dep_provider.get_cell(
&tx.inputs()
.get(*i)
.ok_or_else(|| other_unlock_error("input index out of bound"))?
.previous_output(),
)?;
let capacity: u64 = cell.capacity().unpack();
total -= capacity as i64;
}
for output in tx.outputs() {
if output.lock().as_slice() == script_group.script.as_slice() {
let capacity: u64 = output.capacity().unpack();
total += capacity as i64;
}
}

witnesses[witness_index] = builder
.lock(Some(Bytes::from(total.to_le_bytes().to_vec())).pack())
.build()
.as_bytes()
.pack();
Ok(tx.as_advanced_builder().set_witnesses(witnesses).build())
}

// This is called before balancer. It's responsible to fill witness for inputs added manually
// by users.
fn fill_placeholder_witness(
&self,
tx: &TransactionView,
script_group: &ScriptGroup,
_tx_dep_provider: &dyn TransactionDependencyProvider,
) -> std::result::Result<TransactionView, UnlockError> {
let witness_index = script_group.input_indices[0];
let witness_args_opt = tx
.witnesses()
.get(witness_index)
.map_or(Ok(None), |bytes| {
if bytes.is_empty() {
Ok(None)
} else {
WitnessArgs::from_slice(bytes.raw_data().as_ref()).map(Some)
}
})
.map_err(|_| UnlockError::InvalidWitnessArgs(witness_index))?;
let witness_lock_len = witness_args_opt
.as_ref()
.map_or(0, |args| args.lock().to_opt().map_or(0, |lock| lock.len()));
if witness_lock_len < 8 {
let mut witnesses: Vec<packed::Bytes> = tx.witnesses().into_iter().collect();
while witnesses.len() <= witness_index {
witnesses.push(Default::default());
}
let witness_args = witness_args_opt
.map_or_else(WitnessArgs::new_builder, WitnessArgs::as_builder)
.lock(Some(Bytes::from(vec![0u8; 8])).pack())
.build();
witnesses[witness_index] = witness_args.as_bytes().pack();
Ok(tx.as_advanced_builder().set_witnesses(witnesses).build())
} else {
Ok(tx.clone())
}
}
}

fn other_unlock_error(message: &str) -> UnlockError {
UnlockError::Other(std::io::Error::new(std::io::ErrorKind::Other, message).into())
}

fn main() {
let script_id = ScriptId {
code_hash: h256!("0x3e6dd90e2d6d8d7a17c5ddce9c257f638545d991a6eba7e4c82879f395b6883c"),
hash_type: ScriptHashType::Data1,
};

let capacity_diff_unlocker: Box<dyn ScriptUnlocker> = Box::new(CapacityDiffUnlocker {});
let _unlockers = HashMap::from([(script_id.clone(), capacity_diff_unlocker)]);
}
4 changes: 3 additions & 1 deletion src/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,9 @@ pub trait CellCollector: DynClone {
}

pub trait CellDepResolver {
/// Resolve cell dep by script
/// Resolve cell dep by script.
///
/// When a new script is added, transaction builders use CellDepResolver to find the corresponding cell deps and add them to the transaction.
fn resolve(&self, script: &Script) -> Option<CellDep>;
}
pub trait HeaderDepResolver {
Expand Down
13 changes: 12 additions & 1 deletion src/tx_builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,9 @@ pub enum BalanceTxCapacityError {
AlreadyBalance(u64, u64),
}

/// Transaction capacity balancer config
/// Transaction capacity balancer config.
///
/// CapacityBalancer will try to balance the transaction capacity by adding inputs from CapacityProvider.
#[derive(Debug, Clone)]
pub struct CapacityBalancer {
pub fee_rate: FeeRate,
Expand All @@ -411,6 +413,15 @@ pub struct CapacityBalancer {
}

impl CapacityBalancer {
/// Create a new balancer.
///
/// # Arguments
///
/// * `capacity_provider` - Use live cells with this lock script as capacity provider.
/// * `placeholder_witness` - The witness used as a placeholder when adding new inputs.
/// This placeholder ensures that the transaction size does not increase after signing,
/// thus maintaining the validity of fee calculation.
/// * `fee_rate` - The fee rate used to calculate the transaction fee.
pub fn new_simple(
capacity_provider: Script,
placeholder_witness: WitnessArgs,
Expand Down
2 changes: 2 additions & 0 deletions src/unlock/unlocker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ pub enum UnlockError {
/// * Parse the script.args
/// * Sign the transaction
/// * Put extra unlock information into transaction (e.g. SMT proof in omni-lock case)
///
/// See example in `examples/script_unlocker_example.rs`
pub trait ScriptUnlocker {
fn match_args(&self, args: &[u8]) -> bool;

Expand Down

0 comments on commit 6ba5d8d

Please sign in to comment.