Skip to content

Commit

Permalink
Merge pull request #37 from chenyukang/add-udt
Browse files Browse the repository at this point in the history
Add UDT support
  • Loading branch information
chenyukang authored Jun 13, 2024
2 parents 6f2a1c1 + 12e4b50 commit cc3b808
Show file tree
Hide file tree
Showing 38 changed files with 3,771 additions and 154 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ jobs:
- 3-nodes-transfer
- invoice-ops
- open-use-close-a-channel
- udt
release:
- "0.116.1"
name: e2e test for ${{ matrix.workflow }}
Expand All @@ -30,6 +31,7 @@ jobs:
run: |
# Prebuild the program so that we can run the following script faster
cargo build
cd tests/deploy/udt-init && cargo build && cd -
./tests/nodes/start.sh &
# Wait for the nodes to start, the initialization takes some time
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
/result*

/tests/nodes/*/ckb/store
/tests/deploy/udt-init/target
282 changes: 200 additions & 82 deletions src/ckb/channel.rs

Large diffs are not rendered by default.

26 changes: 13 additions & 13 deletions src/ckb/gen/pcn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2896,8 +2896,8 @@ impl ::core::fmt::Display for OpenChannel {
write!(
f,
", {}: {}",
"funding_type_script",
self.funding_type_script()
"funding_udt_type_script",
self.funding_udt_type_script()
)?;
write!(f, ", {}: {}", "funding_amount", self.funding_amount())?;
write!(f, ", {}: {}", "funding_fee_rate", self.funding_fee_rate())?;
Expand Down Expand Up @@ -3008,7 +3008,7 @@ impl OpenChannel {
let end = molecule::unpack_number(&slice[12..]) as usize;
Byte32::new_unchecked(self.0.slice(start..end))
}
pub fn funding_type_script(&self) -> ScriptOpt {
pub fn funding_udt_type_script(&self) -> ScriptOpt {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
let end = molecule::unpack_number(&slice[16..]) as usize;
Expand Down Expand Up @@ -3143,7 +3143,7 @@ impl molecule::prelude::Entity for OpenChannel {
Self::new_builder()
.chain_hash(self.chain_hash())
.channel_id(self.channel_id())
.funding_type_script(self.funding_type_script())
.funding_udt_type_script(self.funding_udt_type_script())
.funding_amount(self.funding_amount())
.funding_fee_rate(self.funding_fee_rate())
.commitment_fee_rate(self.commitment_fee_rate())
Expand Down Expand Up @@ -3186,8 +3186,8 @@ impl<'r> ::core::fmt::Display for OpenChannelReader<'r> {
write!(
f,
", {}: {}",
"funding_type_script",
self.funding_type_script()
"funding_udt_type_script",
self.funding_udt_type_script()
)?;
write!(f, ", {}: {}", "funding_amount", self.funding_amount())?;
write!(f, ", {}: {}", "funding_fee_rate", self.funding_fee_rate())?;
Expand Down Expand Up @@ -3272,7 +3272,7 @@ impl<'r> OpenChannelReader<'r> {
let end = molecule::unpack_number(&slice[12..]) as usize;
Byte32Reader::new_unchecked(&self.as_slice()[start..end])
}
pub fn funding_type_script(&self) -> ScriptOptReader<'r> {
pub fn funding_udt_type_script(&self) -> ScriptOptReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
let end = molecule::unpack_number(&slice[16..]) as usize;
Expand Down Expand Up @@ -3451,7 +3451,7 @@ impl<'r> molecule::prelude::Reader<'r> for OpenChannelReader<'r> {
pub struct OpenChannelBuilder {
pub(crate) chain_hash: Byte32,
pub(crate) channel_id: Byte32,
pub(crate) funding_type_script: ScriptOpt,
pub(crate) funding_udt_type_script: ScriptOpt,
pub(crate) funding_amount: Uint128,
pub(crate) funding_fee_rate: Uint64,
pub(crate) commitment_fee_rate: Uint64,
Expand Down Expand Up @@ -3479,8 +3479,8 @@ impl OpenChannelBuilder {
self.channel_id = v;
self
}
pub fn funding_type_script(mut self, v: ScriptOpt) -> Self {
self.funding_type_script = v;
pub fn funding_udt_type_script(mut self, v: ScriptOpt) -> Self {
self.funding_udt_type_script = v;
self
}
pub fn funding_amount(mut self, v: Uint128) -> Self {
Expand Down Expand Up @@ -3555,7 +3555,7 @@ impl molecule::prelude::Builder for OpenChannelBuilder {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1)
+ self.chain_hash.as_slice().len()
+ self.channel_id.as_slice().len()
+ self.funding_type_script.as_slice().len()
+ self.funding_udt_type_script.as_slice().len()
+ self.funding_amount.as_slice().len()
+ self.funding_fee_rate.as_slice().len()
+ self.commitment_fee_rate.as_slice().len()
Expand All @@ -3581,7 +3581,7 @@ impl molecule::prelude::Builder for OpenChannelBuilder {
offsets.push(total_size);
total_size += self.channel_id.as_slice().len();
offsets.push(total_size);
total_size += self.funding_type_script.as_slice().len();
total_size += self.funding_udt_type_script.as_slice().len();
offsets.push(total_size);
total_size += self.funding_amount.as_slice().len();
offsets.push(total_size);
Expand Down Expand Up @@ -3620,7 +3620,7 @@ impl molecule::prelude::Builder for OpenChannelBuilder {
}
writer.write_all(self.chain_hash.as_slice())?;
writer.write_all(self.channel_id.as_slice())?;
writer.write_all(self.funding_type_script.as_slice())?;
writer.write_all(self.funding_udt_type_script.as_slice())?;
writer.write_all(self.funding_amount.as_slice())?;
writer.write_all(self.funding_fee_rate.as_slice())?;
writer.write_all(self.commitment_fee_rate.as_slice())?;
Expand Down
53 changes: 45 additions & 8 deletions src/ckb/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ use super::{

use crate::ckb::channel::{TxCollaborationCommand, TxUpdateCommand};
use crate::ckb::types::TxSignatures;
use crate::ckb_chain::{CkbChainMessage, FundingRequest, FundingTx, TraceTxRequest};
use crate::ckb_chain::{
CkbChainMessage, FundingRequest, FundingTx, FundingUdtInfo, TraceTxRequest,
};
use crate::{unwrap_or_return, Error};

pub const PCN_PROTOCOL_ID: ProtocolId = ProtocolId::new(42);
Expand Down Expand Up @@ -97,6 +99,7 @@ pub enum NetworkActorCommand {
pub struct OpenChannelCommand {
pub peer_id: PeerId,
pub funding_amount: u128,
pub funding_udt_type_script: Option<Script>,
}

#[derive(Debug)]
Expand Down Expand Up @@ -152,7 +155,17 @@ pub enum NetworkActorEvent {
/// The two Hash256 are respectively newly agreed channel id and temp channel id,
/// The two u128 are respectively local and remote funding amount,
/// and the script is the lock script of the agreed funding cell.
ChannelAccepted(PeerId, Hash256, Hash256, u128, u128, Script),
ChannelAccepted(
PeerId,
Hash256,
Hash256,
u128,
u128,
Script,
Option<Script>,
u64,
u64,
),
/// A channel is ready to use.
ChannelReady(Hash256, PeerId),
/// A channel is being shutting down.
Expand Down Expand Up @@ -382,6 +395,7 @@ where
}
},
Ok(Err(err)) => {
// FIXME(yukang): we need to handle this error properly
error!("Failed to fund channel: {}", err);
return Ok(());
}
Expand Down Expand Up @@ -554,13 +568,19 @@ impl NetworkActorState {
let OpenChannelCommand {
peer_id,
funding_amount,
funding_udt_type_script,
} = open_channel;
let seed = self.generate_channel_seed();
let (tx, rx) = oneshot::channel::<Hash256>();
let channel = Actor::spawn_linked(
None,
ChannelActor::new(peer_id.clone(), network.clone(), store),
ChannelInitializationParameter::OpenChannel(funding_amount, seed, tx),
ChannelInitializationParameter::OpenChannel(
funding_amount,
seed,
funding_udt_type_script,
tx,
),
network.clone().get_cell(),
)
.await?
Expand Down Expand Up @@ -720,7 +740,7 @@ impl NetworkActorState {
peer_id: PeerId,
open_channel: OpenChannel,
) -> ProcessingChannelResult {
if open_channel.funding_type_script.is_none()
if open_channel.funding_udt_type_script.is_none()
&& open_channel.funding_amount < self.open_channel_min_ckb_funding_amount
{
return Err(ProcessingChannelError::InvalidParameter(format!(
Expand Down Expand Up @@ -993,7 +1013,17 @@ where
))
.expect("myself alive");
}
NetworkActorEvent::ChannelAccepted(peer_id, new, old, local, remote, script) => {
NetworkActorEvent::ChannelAccepted(
peer_id,
new,
old,
local,
remote,
script,
funding_script,
local_ckb_amount,
remote_ckb_amount,
) => {
assert_ne!(new, old, "new and old channel id must be different");
if let Some(session) = state.get_peer_session(&peer_id) {
if let Some(channel) = state.channels.remove(&old) {
Expand All @@ -1005,15 +1035,22 @@ where
});

debug!("Starting funding channel");
// TODO: Here we imply that the one who receives AcceptChannel message
// (i.e. the channel initiator) will send TxUpdate message first.
// TODO: Here we implies the one who receives AcceptChannel message
// (i.e. the channel initiator) will send TxUpdate message first.
dbg!(&script);
myself
.send_message(NetworkActorMessage::new_command(
NetworkActorCommand::UpdateChannelFunding(
new,
Default::default(),
FundingRequest {
udt_info: None,
udt_info: funding_script.as_ref().map(|type_script| {
FundingUdtInfo::new(
type_script,
local_ckb_amount,
remote_ckb_amount,
)
}),
script,
local_amount: local as u64,
local_fee_rate: 0,
Expand Down
2 changes: 1 addition & 1 deletion src/ckb/schema/pcn.mol
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ vector SignatureVec <Signature>;
table OpenChannel {
chain_hash: Byte32,
channel_id: Byte32,
funding_type_script: ScriptOpt,
funding_udt_type_script: ScriptOpt,
funding_amount: Uint128,
funding_fee_rate: Uint64,
commitment_fee_rate: Uint64,
Expand Down
8 changes: 4 additions & 4 deletions src/ckb/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ impl TryFrom<Byte66> for PubNonce {
pub struct OpenChannel {
pub chain_hash: Hash256,
pub channel_id: Hash256,
pub funding_type_script: Option<Script>,
pub funding_udt_type_script: Option<Script>,
pub funding_amount: u128,
pub funding_fee_rate: u64,
pub commitment_fee_rate: u64,
Expand All @@ -451,7 +451,7 @@ impl From<OpenChannel> for molecule_pcn::OpenChannel {
molecule_pcn::OpenChannel::new_builder()
.chain_hash(open_channel.chain_hash.into())
.channel_id(open_channel.channel_id.into())
.funding_type_script(open_channel.funding_type_script.pack())
.funding_udt_type_script(open_channel.funding_udt_type_script.pack())
.funding_amount(open_channel.funding_amount.pack())
.funding_fee_rate(open_channel.funding_fee_rate.pack())
.commitment_fee_rate(open_channel.commitment_fee_rate.pack())
Expand Down Expand Up @@ -479,7 +479,7 @@ impl TryFrom<molecule_pcn::OpenChannel> for OpenChannel {
Ok(OpenChannel {
chain_hash: open_channel.chain_hash().into(),
channel_id: open_channel.channel_id().into(),
funding_type_script: open_channel.funding_type_script().to_opt(),
funding_udt_type_script: open_channel.funding_udt_type_script().to_opt(),
funding_amount: open_channel.funding_amount().unpack(),
funding_fee_rate: open_channel.funding_fee_rate().unpack(),
commitment_fee_rate: open_channel.commitment_fee_rate().unpack(),
Expand All @@ -503,7 +503,7 @@ impl TryFrom<molecule_pcn::OpenChannel> for OpenChannel {
}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone)]
pub struct AcceptChannel {
pub channel_id: Hash256,
pub funding_amount: u128,
Expand Down
8 changes: 5 additions & 3 deletions src/ckb_chain/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,17 @@ impl Actor for CkbChainActor {
if (e.code.code() == -1107 || e.code.code() == -1111) =>
{
log::warn!(
"[{}] transaction already in pool",
myself.get_name().unwrap_or_default()
"[{}] transaction { } already in pool",
myself.get_name().unwrap_or_default(),
tx.hash(),
);
Ok(())
}
_ => {
log::error!(
"[{}] send transaction failed: {:?}",
"[{}] send transaction {} failed: {:?}",
myself.get_name().unwrap_or_default(),
tx.hash(),
err
);
Err(err)
Expand Down
4 changes: 2 additions & 2 deletions src/ckb_chain/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ pub enum Contract {
Secp256k1Lock,
AlwaysSuccess,
CkbAuth,
#[allow(dead_code)]
SimpleUDT,
}

Expand Down Expand Up @@ -155,7 +154,6 @@ impl std::fmt::Debug for ContractsContext {

enum EnvironmentVariableType {
CodeHash,
// FIXME(yukang): warning suppression
#[allow(dead_code)]
TypeHash,
TxIndex,
Expand Down Expand Up @@ -189,6 +187,7 @@ fn get_environment_variable(
Contract::FundingLock => "FUNDING_LOCK",
Contract::CommitmentLock => "COMMITMENT_LOCK",
Contract::AlwaysSuccess => "ALWAYS_SUCCESS",
Contract::SimpleUDT => "SIMPLE_UDT",
_ => panic!("Unsupported contract type {:?}", contract),
};
let type_desc = match env_type {
Expand Down Expand Up @@ -238,6 +237,7 @@ impl ContractsContext {
DepType::DepGroup,
vec![Contract::FundingLock, Contract::CommitmentLock],
),
(DepType::Code, DepType::Code, vec![Contract::SimpleUDT]),
] {
for contract in contracts {
let program_code_hash = get_hash_from_environment_variable(
Expand Down
Loading

0 comments on commit cc3b808

Please sign in to comment.