Skip to content

Commit

Permalink
add an example for funding
Browse files Browse the repository at this point in the history
  • Loading branch information
doitian committed May 10, 2024
1 parent bd62174 commit 47487ba
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 67 deletions.
113 changes: 113 additions & 0 deletions examples/funding.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/// # How to Use This Example
///
/// Start CKB dev net first. Set the test account as the miner.
///
///
/// ```text
/// ckb init -c dev --force --ba-arg 0xc8328aabcd9b9e8e64fbc566c4385c3bdeb219d7
/// ```
///
/// Transfer some CKB to the address
///
/// ```text
/// ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqgx5lf4pczpamsfam48evs0c8nvwqqa59qapt46f`
/// ```
///
/// Run the example:
///
/// ```text
/// cargo run --example funding /tmp/ckb-local /tmp/ckb-remote
/// ```
use ckb_pcn_node::{
ckb::types::Hash256,
ckb_chain::{CkbChainActor, CkbChainConfig, CkbChainMessage},
};
use ractor::{Actor, ActorRef};
use std::{env, path::PathBuf};

#[tokio::main]
pub async fn main() {
env_logger::init();

let (local_config, remote_config) = prepare();

let (local_actor, local_handle) = Actor::spawn(
Some("local actor".to_string()),
CkbChainActor {},
local_config,
)
.await
.expect("start local actor");

let (remote_actor, remote_handle) = Actor::spawn(
Some("remote actor".to_string()),
CkbChainActor {},
remote_config,
)
.await
.expect("start remote actor");

run(&local_actor, &remote_actor).await;

local_actor.stop(None);
local_handle.await.expect("Actor failed to exit cleanly");
remote_actor.stop(None);
remote_handle.await.expect("Actor failed to exit cleanly");
}

async fn run(_local: &ActorRef<CkbChainMessage>, _remote: &ActorRef<CkbChainMessage>) {}

fn make_h256(hex: &str) -> Hash256 {
let mut buf = [0u8; 32];
hex::decode_to_slice(&hex[2..], &mut buf).expect("decode hash256");
Hash256::from(buf)
}

fn prepare() -> (CkbChainConfig, CkbChainConfig) {
let args: Vec<String> = env::args().collect();
let local_path = PathBuf::from(&args[1]);
let remote_path = PathBuf::from(&args[2]);
let _ = std::fs::create_dir_all(&local_path);
let _ = std::fs::create_dir_all(&remote_path);

// Dev net test account that has 20 billions of CKB tokens in the genesis block.
std::fs::write(
local_path.join("key"),
"d00c06bfd800d27397002dca6fb0993d5ba6399b4238b2f29ee9deb97593d2bc",
)
.expect("Unable to write to file");
// privkey for ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqgx5lf4pczpamsfam48evs0c8nvwqqa59qapt46f
std::fs::write(
remote_path.join("key"),
"cccd5f7e693b60447623fb71a5983f15a426938c33699b1a81d1239cfa656cd1",
)
.expect("Unable to write to file");

let rpc_url = "http://127.0.0.1:8114".to_string();
return (
CkbChainConfig {
base_dir: Some(local_path),
rpc_url: rpc_url.clone(),
funding_source_lock_script_code_hash: make_h256(
"0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",
),
funding_source_lock_script_hash_type: ckb_jsonrpc_types::ScriptHashType::Type,
funding_cell_lock_script_code_hash: make_h256(
"0x8090ce20be9976e2407511502acebf74ac1cfed10d7b35b7f33f56c9bd0daec6",
),
funding_cell_lock_script_hash_type: ckb_jsonrpc_types::ScriptHashType::Type,
},
CkbChainConfig {
base_dir: Some(remote_path),
rpc_url: rpc_url.clone(),
funding_source_lock_script_code_hash: make_h256(
"0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",
),
funding_source_lock_script_hash_type: ckb_jsonrpc_types::ScriptHashType::Type,
funding_cell_lock_script_code_hash: make_h256(
"0x8090ce20be9976e2407511502acebf74ac1cfed10d7b35b7f33f56c9bd0daec6",
),
funding_cell_lock_script_hash_type: ckb_jsonrpc_types::ScriptHashType::Type,
},
);
}
41 changes: 6 additions & 35 deletions src/ckb_chain/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ pub struct CkbChainState {
config: CkbChainConfig,
secret_key: secp256k1::SecretKey,
funding_source_lock_script: packed::Script,
funding_source_cell_dep: packed::CellDep,
}

#[derive(Debug)]
Expand All @@ -31,7 +30,7 @@ impl Actor for CkbChainActor {

async fn pre_start(
&self,
_myself: ActorRef<Self::Msg>,
myself: ActorRef<Self::Msg>,
config: Self::Arguments,
) -> Result<Self::State, ActorProcessingErr> {
let secret_key = config.read_secret_key()?;
Expand All @@ -41,47 +40,19 @@ impl Actor for CkbChainActor {
let pub_key_hash = ckb_hash::blake2b_256(pub_key.serialize());
let funding_source_lock_script =
config.build_funding_source_lock_script((&pub_key_hash[0..20]).pack());

let funding_source_cell_dep = config.build_funding_source_cell_dep();
log::info!(
"[{}] funding lock args: {}",
myself.get_name().unwrap_or_default(),
funding_source_lock_script.args()
);

Ok(CkbChainState {
config,
secret_key,
funding_source_lock_script,
funding_source_cell_dep,
})
}

// TODO: delete me
async fn post_start(
&self,
_myself: ActorRef<Self::Msg>,
state: &mut Self::State,
) -> Result<(), ActorProcessingErr> {
let tx = FundingTx::new();
let request = FundingRequest {
udt_info: None,
funding_cell_lock_script_args: Default::default(),
local_amount: 5000,
local_fee_rate: 1000,
remote_amount: 0,
};
let context = state.build_funding_context(&request);
tokio::task::spawn_blocking(move || match tx.fulfill(request, context) {
Ok(tx) => {
let tx: ckb_jsonrpc_types::TransactionView = tx.into_inner().unwrap().into();
log::info!(
"Funding tx: {}",
serde_json::to_string_pretty(&tx).unwrap_or_default()
);
}
Err(err) => {
log::error!("Failed to build funding tx: {:?}", err);
}
});
Ok(())
}

async fn handle(
&self,
_myself: ActorRef<Self::Msg>,
Expand Down
32 changes: 2 additions & 30 deletions src/ckb_chain/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,6 @@ pub struct CkbChainConfig {
)]
pub rpc_url: String,

#[arg(skip)]
pub funding_source_lock_script_tx_hash: Hash256,

#[default(0)]
#[arg(skip)]
pub funding_source_lock_script_tx_index: u32,

#[default(ckb_jsonrpc_types::DepType::DepGroup)]
#[arg(skip)]
pub funding_source_lock_script_dep_type: ckb_jsonrpc_types::DepType,

#[arg(skip)]
pub funding_source_lock_script_code_hash: Hash256,

Expand Down Expand Up @@ -113,7 +102,7 @@ impl CkbChainConfig {
packed::Script::new_builder()
.code_hash(self.funding_source_lock_script_code_hash.into())
.hash_type(packed::Byte::new(
Into::<ckb_types::core::ScriptHashType>::into(
ckb_types::core::ScriptHashType::from(
self.funding_source_lock_script_hash_type.clone(),
)
.into(),
Expand All @@ -122,28 +111,11 @@ impl CkbChainConfig {
.build()
}

pub fn build_funding_source_cell_dep(&self) -> packed::CellDep {
packed::CellDep::new_builder()
.out_point(
packed::OutPoint::new_builder()
.tx_hash(self.funding_source_lock_script_tx_hash.into())
.index(self.funding_source_lock_script_tx_index.pack())
.build(),
)
.dep_type(packed::Byte::new(
Into::<ckb_types::core::DepType>::into(
self.funding_source_lock_script_dep_type.clone(),
)
.into(),
))
.build()
}

pub fn build_funding_cell_lock_script(&self, args: packed::Bytes) -> packed::Script {
packed::Script::new_builder()
.code_hash(self.funding_cell_lock_script_code_hash.into())
.hash_type(Byte::new(
Into::<ckb_types::core::ScriptHashType>::into(
ckb_types::core::ScriptHashType::from(
self.funding_cell_lock_script_hash_type.clone(),
)
.into(),
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ pub async fn main() {

if let Some(ckb_chain_config) = config.ckb_chain {
let (_wallet_actor, _wallet_handle) = Actor::spawn_linked(
Some("wallet actor".to_string()),
Some("ckb-chain".to_string()),
CkbChainActor {},
ckb_chain_config,
root_actor.get_cell(),
)
.await
.expect("start wallet actor");
.expect("start ckb-chain actor");
}

let ckb_command_sender = match config.ckb {
Expand Down

0 comments on commit 47487ba

Please sign in to comment.