Skip to content

Commit

Permalink
Merge branch 'abk/run-810-make-canisterid-new-infallable' into 'master'
Browse files Browse the repository at this point in the history
RUN-810: Switch `CanisterId::new` to infallable `CanisterId::unchecked_from_principal`

`CanisterId::new` returns a `Result` type, but the value is always `Ok`
so it would be better to not return a `Result`. 

See merge request dfinity-lab/public/ic!15456
  • Loading branch information
adambratschikaye committed Oct 26, 2023
2 parents c5b72c8 + 33b4bbb commit f3216c1
Show file tree
Hide file tree
Showing 60 changed files with 205 additions and 277 deletions.
24 changes: 18 additions & 6 deletions rs/canonical_state/src/encoding/old_types.rs
Expand Up @@ -117,8 +117,12 @@ impl TryFrom<RequestV13> for ic_types::messages::Request {
.try_into()?;

Ok(Self {
receiver: ic_types::CanisterId::new(request.receiver.as_slice().try_into()?)?,
sender: ic_types::CanisterId::new(request.sender.as_slice().try_into()?)?,
receiver: ic_types::CanisterId::unchecked_from_principal(
request.receiver.as_slice().try_into()?,
),
sender: ic_types::CanisterId::unchecked_from_principal(
request.sender.as_slice().try_into()?,
),
sender_reply_callback: request.sender_reply_callback.into(),
payment,
method_name: request.method_name,
Expand Down Expand Up @@ -167,8 +171,12 @@ impl TryFrom<RequestV3> for ic_types::messages::Request {

fn try_from(request: RequestV3) -> Result<Self, Self::Error> {
Ok(Self {
receiver: ic_types::CanisterId::new(request.receiver.as_slice().try_into()?)?,
sender: ic_types::CanisterId::new(request.sender.as_slice().try_into()?)?,
receiver: ic_types::CanisterId::unchecked_from_principal(
request.receiver.as_slice().try_into()?,
),
sender: ic_types::CanisterId::unchecked_from_principal(
request.sender.as_slice().try_into()?,
),
sender_reply_callback: request.sender_reply_callback.into(),
payment: request.payment.cycles.try_into()?,
method_name: request.method_name,
Expand Down Expand Up @@ -214,8 +222,12 @@ impl TryFrom<ResponseV3> for ic_types::messages::Response {

fn try_from(response: ResponseV3) -> Result<Self, Self::Error> {
Ok(Self {
originator: ic_types::CanisterId::new(response.originator.as_slice().try_into()?)?,
respondent: ic_types::CanisterId::new(response.respondent.as_slice().try_into()?)?,
originator: ic_types::CanisterId::unchecked_from_principal(
response.originator.as_slice().try_into()?,
),
respondent: ic_types::CanisterId::unchecked_from_principal(
response.respondent.as_slice().try_into()?,
),
originator_reply_callback: response.originator_reply_callback.into(),
refund: response.refund.cycles.try_into()?,
response_payload: response.response_payload.try_into()?,
Expand Down
16 changes: 12 additions & 4 deletions rs/canonical_state/src/encoding/types.rs
Expand Up @@ -321,8 +321,12 @@ impl TryFrom<Request> for ic_types::messages::Request {
.try_into()?;

Ok(Self {
receiver: ic_types::CanisterId::new(request.receiver.as_slice().try_into()?)?,
sender: ic_types::CanisterId::new(request.sender.as_slice().try_into()?)?,
receiver: ic_types::CanisterId::unchecked_from_principal(
request.receiver.as_slice().try_into()?,
),
sender: ic_types::CanisterId::unchecked_from_principal(
request.sender.as_slice().try_into()?,
),
sender_reply_callback: request.sender_reply_callback.into(),
payment,
method_name: request.method_name,
Expand Down Expand Up @@ -362,8 +366,12 @@ impl TryFrom<Response> for ic_types::messages::Response {
.try_into()?;

Ok(Self {
originator: ic_types::CanisterId::new(response.originator.as_slice().try_into()?)?,
respondent: ic_types::CanisterId::new(response.respondent.as_slice().try_into()?)?,
originator: ic_types::CanisterId::unchecked_from_principal(
response.originator.as_slice().try_into()?,
),
respondent: ic_types::CanisterId::unchecked_from_principal(
response.respondent.as_slice().try_into()?,
),
originator_reply_callback: response.originator_reply_callback.into(),
refund,
response_payload: response.response_payload.try_into()?,
Expand Down
2 changes: 1 addition & 1 deletion rs/canonical_state/src/lazy_tree_conversion.rs
Expand Up @@ -164,7 +164,7 @@ impl LabelLike for CanisterId {
}

fn from_label(label: &[u8]) -> Option<Self> {
PrincipalId::from_label(label).map(|principal| Self::new(principal).unwrap())
PrincipalId::from_label(label).map(|principal| Self::unchecked_from_principal(principal))
}
}

Expand Down
8 changes: 1 addition & 7 deletions rs/drun/src/message.rs
Expand Up @@ -195,13 +195,7 @@ fn parse_message(s: &str, nonce: u64) -> Result<Message, String> {
fn parse_canister_id(canister_id: &str) -> Result<CanisterId, String> {
use std::str::FromStr;
match PrincipalId::from_str(canister_id) {
Ok(id) => match CanisterId::new(id) {
Ok(id) => Ok(id),
Err(err) => Err(format!(
"Failed to convert {} to canister id with {}",
canister_id, err
)),
},
Ok(id) => Ok(CanisterId::unchecked_from_principal(id)),
Err(err) => Err(format!(
"Failed to convert {} to principal id with {}",
canister_id, err
Expand Down
5 changes: 3 additions & 2 deletions rs/execution_environment/src/bitcoin.rs
Expand Up @@ -120,8 +120,9 @@ mod tests {

#[test]
fn clears_state_of_former_bitcoin_canisters() {
let bitcoin_canister_id =
CanisterId::new(PrincipalId::from_str("rwlgt-iiaaa-aaaaa-aaaaa-cai").unwrap()).unwrap();
let bitcoin_canister_id = CanisterId::unchecked_from_principal(
PrincipalId::from_str("rwlgt-iiaaa-aaaaa-aaaaa-cai").unwrap(),
);

let mut test = ExecutionTestBuilder::new()
// Set the bitcoin canister to be the ID of the canister about to be created.
Expand Down
9 changes: 2 additions & 7 deletions rs/execution_environment/src/canister_manager.rs
Expand Up @@ -265,12 +265,7 @@ impl TryFrom<(CanisterChangeOrigin, InstallCodeArgsV2)> for InstallCodeContext {

fn try_from(input: (CanisterChangeOrigin, InstallCodeArgsV2)) -> Result<Self, Self::Error> {
let (origin, args) = input;
let canister_id = CanisterId::new(args.canister_id).map_err(|err| {
InstallCodeContextError::InvalidCanisterId(format!(
"Converting canister id {} failed with {}",
args.canister_id, err
))
})?;
let canister_id = CanisterId::unchecked_from_principal(args.canister_id);
let compute_allocation = match args.compute_allocation {
Some(ca) => Some(ComputeAllocation::try_from(ca.0.to_u64().ok_or_else(
|| {
Expand Down Expand Up @@ -1247,7 +1242,7 @@ impl CanisterManager {
state: &mut ReplicatedState,
specified_id: PrincipalId,
) -> Result<CanisterId, CanisterManagerError> {
let new_canister_id = CanisterId::new(specified_id).unwrap();
let new_canister_id = CanisterId::unchecked_from_principal(specified_id);

if state.canister_states.get(&new_canister_id).is_some() {
return Err(CanisterManagerError::CanisterAlreadyExists(new_canister_id));
Expand Down
6 changes: 0 additions & 6 deletions rs/execution_environment/src/execution_environment.rs
Expand Up @@ -1955,12 +1955,6 @@ impl ExecutionEnvironment {
// TODO EXC-1060: get the right public key.
_key_id: &EcdsaKeyId,
) -> Result<ECDSAPublicKeyResponse, UserError> {
let _ = CanisterId::new(principal_id).map_err(|err| {
UserError::new(
ErrorCode::CanisterContractViolation,
format!("Not a canister id: {}", err),
)
})?;
let path = ExtendedDerivationPath {
caller: principal_id,
derivation_path,
Expand Down
11 changes: 1 addition & 10 deletions rs/http_endpoints/public/src/call.rs
Expand Up @@ -179,16 +179,7 @@ impl Service<Request<Bytes>> for CallService {
}
};

let effective_canister_id = match CanisterId::new(effective_principal_id) {
Ok(canister_id) => canister_id,
Err(_) => {
let res = make_plaintext_response(
StatusCode::BAD_REQUEST,
format!("Invalid canister id: {}", effective_principal_id),
);
return Box::pin(async move { Ok(res) });
}
};
let effective_canister_id = CanisterId::unchecked_from_principal(effective_principal_id);

// Reject requests where `canister_id` != `effective_canister_id` for non mgmt canister calls.
// This needs to be enforced because boundary nodes block access based on the `effective_canister_id`
Expand Down
11 changes: 1 addition & 10 deletions rs/http_endpoints/public/src/query.rs
Expand Up @@ -146,16 +146,7 @@ impl Service<Request<Bytes>> for QueryService {
}
};

let effective_canister_id = match CanisterId::new(effective_principal_id) {
Ok(canister_id) => canister_id,
Err(_) => {
let res = make_plaintext_response(
StatusCode::BAD_REQUEST,
format!("Invalid canister id: {}", effective_principal_id),
);
return Box::pin(async move { Ok(res) });
}
};
let effective_canister_id = CanisterId::unchecked_from_principal(effective_principal_id);

// Reject requests where `canister_id` != `effective_canister_id`. In comparison to update
// requests we don't need to check for the mgmt canister since all mgmt canister calls are updated calls.
Expand Down
5 changes: 1 addition & 4 deletions rs/http_endpoints/public/src/read_state/canister.rs
Expand Up @@ -260,10 +260,7 @@ fn verify_paths(
verify_principal_ids(&principal_id, &effective_principal_id)?;
can_read_canister_metadata(
user,
&CanisterId::new(principal_id).map_err(|_| HttpError {
status: StatusCode::BAD_REQUEST,
message: format!("Invalid canister id {}.", principal_id),
})?,
&CanisterId::unchecked_from_principal(principal_id),
&name,
state,
)?
Expand Down
4 changes: 3 additions & 1 deletion rs/ingress_manager/benches/build_payload.rs
Expand Up @@ -199,7 +199,9 @@ fn build_payload(criterion: &mut Criterion) {
// canister ids iterator
let mut rng = rand::thread_rng();
let canisters: Vec<CanisterId> = (0..(size / 10))
.map(|_| CanisterId::new(PrincipalId::new_user_test_id(rng.next_u64())).unwrap())
.map(|_| {
CanisterId::unchecked_from_principal(PrincipalId::new_user_test_id(rng.next_u64()))
})
.collect();

run_test(
Expand Down
13 changes: 6 additions & 7 deletions rs/nns/cmc/src/main.rs
Expand Up @@ -329,7 +329,7 @@ fn set_authorized_subnetwork_list(who: Option<PrincipalId>, subnets: Vec<SubnetI
with_state_mut(|state| {
let governance_canister_id = state.governance_canister_id;

if CanisterId::new(caller()) != Ok(governance_canister_id) {
if CanisterId::unchecked_from_principal(caller()) != governance_canister_id {
panic!("Only the governance canister can set authorized subnetwork lists.");
}

Expand Down Expand Up @@ -384,7 +384,7 @@ fn update_subnet_type_() {
fn update_subnet_type(args: UpdateSubnetTypeArgs) -> UpdateSubnetTypeResult {
let governance_canister_id = with_state(|state| state.governance_canister_id);

if CanisterId::new(caller()) != Ok(governance_canister_id) {
if CanisterId::unchecked_from_principal(caller()) != governance_canister_id {
panic!("Only the governance canister can update the available subnet types.");
}

Expand Down Expand Up @@ -456,7 +456,7 @@ fn change_subnet_type_assignment(
) -> ChangeSubnetTypeAssignmentResult {
let governance_canister_id = with_state(|state| state.governance_canister_id);

if CanisterId::new(caller()) != Ok(governance_canister_id) {
if CanisterId::unchecked_from_principal(caller()) != governance_canister_id {
panic!(
"Only the governance canister can change the assignment of subnets to subnet types."
);
Expand Down Expand Up @@ -1316,7 +1316,7 @@ async fn transaction_notification(tn: TransactionNotification) -> Result<CyclesR

let ledger_canister_id = with_state(|state| state.ledger_canister_id);

if CanisterId::new(caller) != Ok(ledger_canister_id) {
if CanisterId::unchecked_from_principal(caller) != ledger_canister_id {
return Err(format!(
"This canister can only be notified by the ledger canister ({}), not by {}.",
ledger_canister_id, caller
Expand Down Expand Up @@ -2047,10 +2047,9 @@ mod tests {
}
blocks_notified.insert(
60,
NotificationStatus::NotifiedCreateCanister(Ok(CanisterId::new(
NotificationStatus::NotifiedCreateCanister(Ok(CanisterId::unchecked_from_principal(
PrincipalId::new_user_test_id(4),
)
.unwrap())),
))),
);
state.blocks_notified = Some(blocks_notified);

Expand Down
3 changes: 1 addition & 2 deletions rs/nns/handlers/root/impl/src/lib.rs
Expand Up @@ -134,8 +134,7 @@ fn principal_name(principal_id: PrincipalId) -> String {
};
}

CanisterId::new(principal_id)
.ok()
Some(CanisterId::unchecked_from_principal(principal_id))
.and_then(|canister_id| CANISTER_ID_TO_NAME.get(&canister_id))
.map(|name| format!("{}_canister", name))
.unwrap_or_else(|| principal_id.to_string())
Expand Down
13 changes: 7 additions & 6 deletions rs/nns/sns-wasm/src/pb/mod.rs
Expand Up @@ -133,24 +133,24 @@ impl Display for SnsVersion {
impl SnsCanisterIds {
/// Get Root CanisterId
pub fn root(&self) -> CanisterId {
CanisterId::new(self.root.unwrap()).unwrap()
CanisterId::unchecked_from_principal(self.root.unwrap())
}
/// Get Governance CanisterId
pub fn governance(&self) -> CanisterId {
CanisterId::new(self.governance.unwrap()).unwrap()
CanisterId::unchecked_from_principal(self.governance.unwrap())
}
/// Get Ledger CanisterId
pub fn ledger(&self) -> CanisterId {
CanisterId::new(self.ledger.unwrap()).unwrap()
CanisterId::unchecked_from_principal(self.ledger.unwrap())
}
/// Get Swap CanisterId
pub fn swap(&self) -> CanisterId {
CanisterId::new(self.swap.unwrap()).unwrap()
CanisterId::unchecked_from_principal(self.swap.unwrap())
}

/// Get Index CanisterId
pub fn index(&self) -> CanisterId {
CanisterId::new(self.index.unwrap()).unwrap()
CanisterId::unchecked_from_principal(self.index.unwrap())
}
}

Expand Down Expand Up @@ -312,7 +312,8 @@ impl SnsCanisterIds {
]
.into_iter()
.flat_map(|(label, principal_id)| {
principal_id.map(|principal_id| (label, CanisterId::new(principal_id).unwrap()))
principal_id
.map(|principal_id| (label, CanisterId::unchecked_from_principal(principal_id)))
})
.collect()
}
Expand Down

0 comments on commit f3216c1

Please sign in to comment.