Skip to content
This repository has been archived by the owner on Jun 17, 2022. It is now read-only.

Commit

Permalink
test(channel): add channel challenge/resolve test
Browse files Browse the repository at this point in the history
  • Loading branch information
nanne007 committed Dec 31, 2019
1 parent 25ace7e commit fe6f2a7
Show file tree
Hide file tree
Showing 14 changed files with 179 additions and 96 deletions.
2 changes: 1 addition & 1 deletion libra
Submodule libra updated from d03782 to 075a71
108 changes: 54 additions & 54 deletions sgwallet/src/channel/channel.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::channel::{ApplyCoSignedTxn, ApplySoloTxn};
use crate::{
chain_watcher::{Interest, TransactionWithInfo},
chain_watcher::TransactionWithInfo,
channel::{
access_local, channel_event_stream::ChannelEventStream, AccessingResource, ApplyPendingTxn,
CancelPendingTxn, Channel, ChannelEvent, CollectProposalWithSigs, Execute, ForceTravel,
GetPendingTxn, GrantProposal,
access_local, channel_event_stream::ChannelEventStream, AccessingResource,
ApplyCoSignedTxn, ApplyPendingTxn, ApplySoloTxn, CancelPendingTxn, Channel, ChannelEvent,
CollectProposalWithSigs, Execute, ForceTravel, GetPendingTxn, GrantProposal,
},
channel_state_view::ChannelStateView,
utils::contract::{
challenge_channel_action, close_channel_action, parse_channel_event, resolve_channel_action,
},
wallet::{
execute_transaction, submit_transaction, txn_expiration, watch_transaction, GAS_UNIT_PRICE,
execute_transaction, submit_transaction, txn_expiration, GAS_UNIT_PRICE,
MAX_GAS_AMOUNT_OFFCHAIN, MAX_GAS_AMOUNT_ONCHAIN,
},
};
Expand All @@ -24,7 +23,7 @@ use coerce_rt::actor::{
message::{Handler, Message},
Actor, ActorRef,
};
use futures::{channel::oneshot, SinkExt, StreamExt};
use futures::{SinkExt, StreamExt};
use libra_crypto::{
ed25519::{Ed25519PublicKey, Ed25519Signature},
hash::CryptoHash,
Expand All @@ -45,8 +44,7 @@ use libra_types::{
transaction::{
ChannelTransactionPayload, ChannelTransactionPayloadBody, RawTransaction, ScriptAction,
SignedTransaction, Transaction, TransactionArgument, TransactionInfo,
TransactionListWithProof, TransactionOutput, TransactionPayload, TransactionWithProof,
Version,
TransactionListWithProof, TransactionOutput, TransactionPayload, Version,
},
vm_error::StatusCode,
write_set::WriteSet,
Expand Down Expand Up @@ -221,9 +219,16 @@ impl Handler<CollectProposalWithSigs> for Channel {

// if the output modifies user's channel state, permission need to be granted by user.
// it cannot be auto-signed.
let can_auto_signed = !output
.write_set()
.contains_channel_resource(&self.account_address);
let can_auto_signed = !is_participant_channel_resource_modified(
self.witness_data().write_set(),
output.write_set(),
&self.account_address,
);

debug!(
"{}/{} - auto sign({}) channel txn: {:?}",
&self.account_address, &self.channel_address, can_auto_signed, &payload_body,
);
if !verified_signatures.contains_key(&self.account_address) && can_auto_signed {
self.do_grant_proposal(proposal, output, verified_signatures)?;
} else {
Expand Down Expand Up @@ -475,7 +480,6 @@ impl Handler<ApplyCoSignedTxn> for Channel {
debug_assert!(self.channel_address == channel_txn_payload.channel_address());
debug_assert!(channel_txn_payload.is_authorized());

let channel_txn_proposer = channel_txn_payload.proposer();
let txn_channel_seq_number = channel_txn_payload.witness().channel_sequence_number();
let local_channel_seq_number = self.channel_sequence_number();
// compare the new txn's witness sequence number with local sequence_number
Expand All @@ -502,7 +506,7 @@ impl Handler<ApplyCoSignedTxn> for Channel {
unimplemented!()
}
}
AppliedChannelTxn::Offchain(s) => {
AppliedChannelTxn::Offchain(_s) => {
if raw_txn.sender() == self.account_address {
// FIXME: what happened, why I apply a offchain txn, while still travelled it.
unimplemented!()
Expand Down Expand Up @@ -547,7 +551,7 @@ impl Handler<ApplyCoSignedTxn> for Channel {
channel_resource.event_handle().count(),
10,
);
let mut myself = self.actor_ref(ctx).await;
let myself = self.actor_ref(ctx).await;
tokio::task::spawn(channel_event_loop(channel_event_stream, myself));
}
} else if channel_resource.closed() {
Expand Down Expand Up @@ -597,7 +601,6 @@ impl Handler<ApplySoloTxn> for Channel {
debug_assert!(self.channel_address == channel_txn_payload.channel_address());
debug_assert!(!channel_txn_payload.is_authorized());

let channel_txn_proposer = channel_txn_payload.proposer();
let txn_channel_seq_number = channel_txn_payload.witness().channel_sequence_number();
let local_channel_seq_number = self.channel_sequence_number();
// compare the new txn's witness sequence number with local sequence_number
Expand Down Expand Up @@ -629,7 +632,7 @@ impl Handler<ApplySoloTxn> for Channel {
}
}
}
AppliedChannelTxn::Offchain(s) => {
AppliedChannelTxn::Offchain(_s) => {
if self.account_address == raw_txn.sender() {
// FIXME: why whould I applied an offchain txn, while still submit a outdated solo txn to chain.
unimplemented!()
Expand Down Expand Up @@ -711,7 +714,7 @@ impl Handler<ChannelLockTimeout> for Channel {
async fn handle(
&mut self,
_message: ChannelLockTimeout,
ctx: &mut ActorHandlerContext,
_ctx: &mut ActorHandlerContext,
) -> <ChannelLockTimeout as Message>::Result {
let _ = self.solo_txn(close_channel_action(), None).await?;
Ok(())
Expand Down Expand Up @@ -740,12 +743,14 @@ async fn channel_event_loop<A>(
});
match result {
Err(e) => error!("get channel state change error, {}", e),
Ok(t) => {
if let Err(_e) = actor_ref.send(t).await {
error!("actor {:?} is gone, stop now", &actor_ref);
Ok(t) => match actor_ref.send(t).await {
Err(_) => {
info!("actor {:?} is gone, stop now", &actor_ref);
break;
}
}
Ok(Err(e)) => error!("fail to handle channel stage change event, {:?}", e),
Ok(Ok(_)) => {}
},
}
}
}
Expand Down Expand Up @@ -775,11 +780,7 @@ impl Handler<ChannelStageChange> for Channel {
self.account_address, self.channel_address, &message
);

let ChannelStageChange {
stage,
version,
event_number,
} = message;
let ChannelStageChange { version, .. } = message;

if version <= self.channel_state.version() {
info!(
Expand Down Expand Up @@ -829,9 +830,9 @@ impl Handler<ChannelStageChange> for Channel {
};

if is_authorized {
self.handle(ApplyCoSignedTxn { channel_txn }, _ctx).await;
let _ = self.handle(ApplyCoSignedTxn { channel_txn }, _ctx).await?;
} else {
self.handle(ApplySoloTxn { channel_txn }, _ctx).await;
let _ = self.handle(ApplySoloTxn { channel_txn }, _ctx).await?;
}
}

Expand Down Expand Up @@ -1538,29 +1539,28 @@ impl Channel {
}
}

pub fn channel_txn_interest(channel_address: AccountAddress) -> Interest {
Box::new(move |txn_info| match &txn_info.txn {
Transaction::UserTransaction(t) => match t.raw_txn().payload() {
TransactionPayload::Channel(cp) => cp.channel_address() == channel_address,
_ => false,
},
_ => false,
})
}

#[allow(dead_code)]
pub fn channel_txn_oneshot_interest(
channel_address: AccountAddress,
channel_sequence_number: u64,
) -> Interest {
Box::new(move |txn| match &txn.txn {
Transaction::UserTransaction(t) => match t.raw_txn().payload() {
TransactionPayload::Channel(cp) => {
cp.channel_address() == channel_address
&& cp.channel_sequence_number() == channel_sequence_number
}
_ => false,
},
_ => false,
})
fn is_participant_channel_resource_modified(
old_write_set: &WriteSet,
new_write_set: &WriteSet,
participant: &AccountAddress,
) -> bool {
let prev_write_set = old_write_set
.iter()
.map(|p| (&p.0, &p.1))
.collect::<BTreeMap<_, _>>();
for (ap, op) in new_write_set {
let contain_participant_data = ap
.data_path()
.and_then(|data_path| data_path.participant())
.filter(|account| account == participant)
.is_some();
let modified_in_this_epoch = !prev_write_set
.get(ap)
.filter(|old_op| **old_op == op)
.is_some();
if contain_participant_data && modified_in_this_epoch {
return true;
}
}
return false;
}
4 changes: 1 addition & 3 deletions sgwallet/src/channel/channel_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@ use coerce_rt::actor::ActorRef;
use libra_types::{
access_path::{AccessPath, DataPath},
account_address::AccountAddress,
language_storage::StructTag,
channel::{make_resource, LibraResource},
};

use libra_types::channel::{make_resource, LibraResource};
use serde::de::DeserializeOwned;
use sgtypes::pending_txn::PendingTransaction;
use std::collections::BTreeSet;
Expand Down
1 change: 1 addition & 0 deletions sgwallet/src/utils/actor_timer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0

#![allow(dead_code)]
use coerce_rt::actor::{
message::{Handler, Message},
Actor, ActorRef,
Expand Down
24 changes: 12 additions & 12 deletions sgwallet/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
use crate::{
chain_watcher::{ChainWatcher, ChainWatcherHandle, TransactionWithInfo},
channel::{
ApplyPendingTxn, CancelPendingTxn, Channel, ChannelEvent, ChannelHandle,
CollectProposalWithSigs, Execute, ForceTravel, GrantProposal,
ApplyCoSignedTxn, ApplyPendingTxn, ApplySoloTxn, CancelPendingTxn, Channel, ChannelEvent,
ChannelHandle, CollectProposalWithSigs, Execute, ForceTravel, GrantProposal,
},
scripts::*,
};
Expand All @@ -31,9 +31,9 @@ use libra_types::{
account_config::{coin_struct_tag, AccountResource},
byte_array::ByteArray,
channel::{
channel_mirror_struct_tag, channel_participant_struct_tag, channel_struct_tag,
make_resource, user_channels_struct_tag, ChannelMirrorResource,
ChannelParticipantAccountResource, ChannelResource, UserChannelsResource,
channel_mirror_struct_tag, channel_struct_tag, make_resource, user_channels_struct_tag,
ChannelMirrorResource, ChannelParticipantAccountResource, ChannelResource, LibraResource,
UserChannelsResource,
},
language_storage::StructTag,
transaction::{
Expand All @@ -60,11 +60,12 @@ use sgtypes::{
sg_error::SgError,
signed_channel_transaction::SignedChannelTransaction,
};
use std::collections::{BTreeSet, HashMap, HashSet};

use crate::channel::{ApplyCoSignedTxn, ApplySoloTxn};
use libra_types::channel::LibraResource;
use std::{path::Path, sync::Arc, time::Duration};
use std::{
collections::{BTreeSet, HashMap, HashSet},
path::Path,
sync::Arc,
time::Duration,
};
use tokio::runtime;
use vm_runtime::{MoveVM, VMExecutor};

Expand Down Expand Up @@ -254,8 +255,7 @@ impl Wallet {
}

pub async fn channel_handle(&self, participant: AccountAddress) -> Result<Arc<ChannelHandle>> {
let (channel_address, participants) =
generate_channel_address(participant, self.shared.account);
let (channel_address, _) = generate_channel_address(participant, self.shared.account);
let handle = self.get_channel(channel_address).await?;
Ok(handle)
}
Expand Down
7 changes: 3 additions & 4 deletions sgwallet/tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![allow(dead_code)]

use anyhow::Result;
use libra_crypto::{
Expand All @@ -10,9 +11,9 @@ use libra_crypto::{
use libra_tools::tempdir::TempPath;
use libra_types::{account_address::AccountAddress, transaction::TransactionArgument};
use rand::prelude::*;
use sgchain::star_chain_client::{ChainClient, MockChainClient};
use sgchain::star_chain_client::ChainClient;
use sgwallet::wallet::Wallet;
use std::{sync::Arc, time::Duration};
use std::sync::Arc;
use tokio::runtime::Runtime;
pub fn setup_wallet(
executor: tokio::runtime::Handle,
Expand Down Expand Up @@ -76,7 +77,6 @@ where
res
}

#[allow(dead_code)]
pub async fn send_payment(
sender_wallet: Arc<Wallet>,
receiver_wallet: Arc<Wallet>,
Expand All @@ -103,7 +103,6 @@ pub async fn send_payment(
Ok(sender_gas)
}

#[allow(dead_code)]
pub async fn receive_payment(
sender_wallet: Arc<Wallet>,
receiver_wallet: Arc<Wallet>,
Expand Down
3 changes: 2 additions & 1 deletion sgwallet/tests/mock_chain_test_helper.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![allow(dead_code)]

use sgchain::star_chain_client::{ChainClient, MockChainClient};
use std::{sync::Arc, time::Duration};
use std::sync::Arc;

pub fn run_with_mock_client<F, T>(mut f: F) -> T
where
Expand Down
2 changes: 2 additions & 0 deletions sgwallet/tests/rpc_chain_test_helper.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![allow(dead_code)]

use libra_logger::prelude::*;
use sgchain::star_chain_client::{ChainClient, StarChainClient};
use std::sync::Arc;
Expand Down
2 changes: 1 addition & 1 deletion sgwallet/tests/test_chain_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use libra_types::{
account_config::{account_struct_tag, AccountResource},
};
use mock_chain_test_helper::run_with_mock_client;
use sgchain::star_chain_client::{ChainClient, MockChainClient};
use sgchain::star_chain_client::ChainClient;
use sgwallet::{
chain_state_access::{AccessState, ChainStateAccessor},
chain_watcher::*,
Expand Down
Loading

0 comments on commit fe6f2a7

Please sign in to comment.