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

pink: mq egress & discover ink instantiated contracts #538

Merged
merged 16 commits into from
Oct 27, 2021
Merged
Show file tree
Hide file tree
Changes from 15 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
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ exclude = [
"ring",
"native-nostd-hasher",
"standalone/pruntime",
"crates/pink/examples/mqproxy",
]

members = [
Expand All @@ -30,6 +31,7 @@ members = [
"crates/phala-async-executor",
"crates/phala-allocator",
"crates/pink",
"crates/pink/pink-extension",
"pallets/phala",
"pallets/phala/mq-runtime-api",
"pallets/bridge",
Expand Down
6 changes: 3 additions & 3 deletions crates/phactory/src/contracts/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ impl contracts::NativeContract for Assets {
self.assets.insert(id, accounts);
self.next_id += 1;

Ok(())
Ok(Default::default())
} else {
Err(TransactionError::SymbolExist)
}
Expand All @@ -144,7 +144,7 @@ impl contracts::NativeContract for Assets {
self.metadata.remove(&id);
self.assets.remove(&id);

Ok(())
Ok(Default::default())
} else {
Err(TransactionError::NotAssetOwner)
}
Expand Down Expand Up @@ -203,7 +203,7 @@ impl contracts::NativeContract for Assets {
info!(" pushed history (dest)");
}

Ok(())
Ok(Default::default())
} else {
Err(TransactionError::InsufficientBalance)
}
Expand Down
6 changes: 3 additions & 3 deletions crates/phactory/src/contracts/balances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ impl contracts::NativeContract for Balances {
info!(" src: {:>20} -> {:>20}", src0, src0 - value);
info!(" dest: {:>20} -> {:>20}", dest0, dest0 + value);

Ok(())
Ok(Default::default())
} else {
Err(TransactionError::InsufficientBalance)
}
Expand Down Expand Up @@ -127,7 +127,7 @@ impl contracts::NativeContract for Balances {
amount: value,
};
context.mq().push_message(&data);
Ok(())
Ok(Default::default())
} else {
Err(TransactionError::InsufficientBalance)
}
Expand All @@ -152,7 +152,7 @@ impl contracts::NativeContract for Balances {
info!(" value: {:>20} -> {:>20}", 0, amount);
}
self.total_issuance += amount;
Ok(())
Ok(Default::default())
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions crates/phactory/src/contracts/btc_lottery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ impl BtcLottery {
};
round_utxo.insert(btc_address, utxo);
}
Ok(())
Ok(Default::default())
}
LotteryUserCommand::SetAdmin { new_admin } => {
// TODO: listen to some specific privileged account instead of ALICE
Expand All @@ -452,7 +452,7 @@ impl BtcLottery {
if self.admin == sender {
self.admin = new_admin;
}
Ok(())
Ok(Default::default())
} else {
Err(TransactionError::InvalidAccount)
}
Expand Down Expand Up @@ -483,6 +483,6 @@ impl BtcLottery {
btc_address,
} => Self::open_lottery(self, context.mq(), round_id, token_id, btc_address),
}
Ok(())
Ok(Default::default())
}
}
4 changes: 2 additions & 2 deletions crates/phactory/src/contracts/data_plaza.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ impl contracts::NativeContract for DataPlaza {
seller: address_hex,
details,
});
Ok(())
Ok(Default::default())
}
Command::OpenOrder(details) => {
self.orders.push(Order {
Expand All @@ -294,7 +294,7 @@ impl contracts::NativeContract for DataPlaza {
result_path: String::new(),
},
});
Ok(())
Ok(Default::default())
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/phactory/src/contracts/geolocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ impl contracts::NativeContract for Geolocation {
);
};

Ok(())
Ok(Default::default())
}
}
}
Expand Down
92 changes: 68 additions & 24 deletions crates/phactory/src/contracts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ fn account_id_from_hex(s: &str) -> Result<AccountId> {

pub use support::*;
mod support {
use phala_crypto::ecdh::EcdhPublicKey;
use phala_mq::traits::MessageChannel;
use ::pink::runtime::ExecSideEffects;
use runtime::BlockNumber;

use super::pink::group::GroupKeeper;
use super::*;
use crate::types::BlockInfo;
Expand All @@ -42,13 +47,14 @@ mod support {

pub struct NativeContext<'a> {
pub block: &'a BlockInfo<'a>,
mq: &'a SignedMessageChannel,
#[allow(unused)] // TODO.kevin: remove this.
secret_mq: SecretMessageChannel<'a, SignedMessageChannel>,
pub mq: &'a SignedMessageChannel,
pub secret_mq: SecretMessageChannel<'a, SignedMessageChannel>,
pub contract_groups: &'a mut GroupKeeper,
}

pub struct QueryContext<'a> {
pub block_number: BlockNumber,
pub now_ms: u64,
pub contract_groups: &'a mut GroupKeeper,
}

Expand All @@ -66,7 +72,16 @@ mod support {
req: OpaqueQuery,
context: &mut QueryContext,
) -> Result<OpaqueReply, OpaqueError>;
fn process_messages(&mut self, env: &mut ExecuteEnv);
fn group_id(&self) -> Option<phala_mq::ContractGroupId>;
Copy link
Contributor

Choose a reason for hiding this comment

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

When does groupd_id return None?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

native contracts return None

fn process_next_message(&mut self, env: &mut ExecuteEnv) -> Option<TransactionResult>;
fn on_block_end(&mut self, env: &mut ExecuteEnv) -> TransactionResult;
fn push_message(&self, payload: Vec<u8>, topic: Vec<u8>);
fn push_osp_message(
&self,
payload: Vec<u8>,
topic: Vec<u8>,
remote_pubkey: Option<&EcdhPublicKey>,
);
}

pub trait NativeContract {
Expand All @@ -75,13 +90,16 @@ mod support {
type QResp: Encode + Debug;

fn id(&self) -> ContractId;
fn group_id(&self) -> Option<phala_mq::ContractGroupId> {
None
Copy link
Contributor

Choose a reason for hiding this comment

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

Is it possible to assign the native contract to a special group id to simplify the logic elsewhere?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Sounds good. But if we treat the native contract the same as pink, I think there will be more tricky things to be handle, such as state handling. It will be more error-prone.

}
fn handle_command(
&mut self,
_origin: MessageOrigin,
_cmd: Self::Cmd,
_context: &mut NativeContext,
) -> TransactionResult {
Ok(())
Ok(Default::default())
}
fn handle_query(
&mut self,
Expand Down Expand Up @@ -148,45 +166,71 @@ mod support {
self.contract.id()
}

fn group_id(&self) -> Option<phala_mq::ContractGroupId> {
self.contract.group_id()
}

fn handle_query(
&mut self,
origin: Option<&runtime::AccountId>,
req: OpaqueQuery,
context: &mut QueryContext,
) -> Result<OpaqueReply, OpaqueError> {
debug!(target: "contract", "Contract {:?} handling query", self.id());
let response = self
.contract
.handle_query(origin, deopaque_query(req)?, context);
Ok(response.encode())
}

fn process_messages(&mut self, env: &mut ExecuteEnv) {
fn process_next_message(&mut self, env: &mut ExecuteEnv) -> Option<TransactionResult> {
let secret_mq = SecretMessageChannel::new(&self.ecdh_key, &self.send_mq);
let mut context = NativeContext {
block: env.block,
mq: &self.send_mq,
secret_mq,
contract_groups: &mut env.contract_groups,
};
loop {
let ok = phala_mq::select! {
next_cmd = self.cmd_rcv_mq => match next_cmd {
Ok((_, cmd, origin)) => {
let status = self.contract.handle_command(origin, cmd, &mut context);
if let Err(err) = status {
log::error!("Contract {:?} handle command error: {:?}", self.id(), err);
}
}
Err(e) => {
error!("Read command failed [{}]: {:?}", self.id(), e);
}
},
};
if ok.is_none() {
break;
}

phala_mq::select! {
next_cmd = self.cmd_rcv_mq => match next_cmd {
Ok((_, cmd, origin)) => {
info!(target: "contract", "Contract {:?} handling command", self.id());
self.contract.handle_command(origin, cmd, &mut context)
}
Err(e) => {
Err(TransactionError::ChannelError)
}
},
}
self.contract.on_block_end(&mut context)
}

fn on_block_end(&mut self, env: &mut ExecuteEnv) -> TransactionResult {
let secret_mq = SecretMessageChannel::new(&self.ecdh_key, &self.send_mq);
let mut context = NativeContext {
block: env.block,
mq: &self.send_mq,
secret_mq,
contract_groups: &mut env.contract_groups,
};
self.contract.on_block_end(&mut context);
Ok(Default::default())
}

fn push_message(&self, payload: Vec<u8>, topic: Vec<u8>) {
self.send_mq.push_data(payload, topic)
}

fn push_osp_message(
&self,
payload: Vec<u8>,
topic: Vec<u8>,
remote_pubkey: Option<&EcdhPublicKey>,
) {
let secret_mq = SecretMessageChannel::new(&self.ecdh_key, &self.send_mq);
secret_mq
.bind_remote_key(remote_pubkey)
.push_data(payload, topic)
}
}
}
Loading