repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/api/fdroid.rs | src-ahqstore-types/src/api/fdroid.rs | rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false | |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/api/flatpak.rs | src-ahqstore-types/src/api/flatpak.rs | use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::{
AHQStoreApplication, AppRepo, DownloadUrl, InstallerFormat, InstallerOptions,
InstallerOptionsLinux,
};
use super::{SearchEntry, CLIENT};
pub static FH_BASE_URL: &'static str = "https://flathub.org/api/v2";
pub static SEARCH: &'static str = "https://flathub.org/api/v2/search?locale=en";
pub static APP: &'static str = "https://flathub.org/api/v2/appstream/{{id}}";
pub static SUMMARY_ARCHES: &'static str = "https://flathub.org/api/v2/summary/{{id}}";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlatpakApplication {
pub r#type: String,
pub description: String,
pub app_id: String,
pub name: String,
pub summary: String,
pub developer_name: String,
pub urls: Option<Urls>,
pub project_license: Option<String>,
pub icon: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Urls {
pub homepage: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Summary {
pub arches: Vec<String>,
}
async fn get_ft_app(id: &str) -> Option<FlatpakApplication> {
CLIENT
.get(APP.replace("{{id}}", &id))
.send()
.await
.ok()?
.json()
.await
.ok()
}
pub async fn get_app(id: &str) -> Option<AHQStoreApplication> {
let app_id = id.replacen("flatpak:", "", 1);
let app = get_ft_app(&app_id).await?;
let Summary { arches } = CLIENT
.get(SUMMARY_ARCHES.replace("{{id}}", &app_id))
.send()
.await
.ok()?
.json()
.await
.ok()?;
let mut linux: Option<InstallerOptionsLinux> = None;
#[allow(non_snake_case)]
let mut linuxArm64: Option<InstallerOptionsLinux> = None;
arches.into_iter().for_each(|s| {
if &s == "aarch64" {
linuxArm64 = InstallerOptionsLinux { assetId: 0 }.into();
} else if &s == "x86_64" {
linux = InstallerOptionsLinux { assetId: 0 }.into();
}
});
Some(AHQStoreApplication {
appDisplayName: app.name.clone(),
appId: format!("flatpak:{}", app.app_id),
appShortcutName: app.name,
authorId: format!("flathub"),
description: app.summary,
displayImages: vec![],
license_or_tos: app.project_license,
releaseTagName: format!("flathub"),
repo: AppRepo {
author: app.developer_name,
repo: "flathub".to_string(),
},
site: app.urls.map_or_else(|| None, |x| x.homepage),
version: format!("flatpak:latest"),
source: Some(format!("Flatpak")),
install: InstallerOptions {
android: None,
linuxArm7: None,
win32: None,
winarm: None,
linux,
linuxArm64,
},
downloadUrls: {
let mut map = HashMap::new();
map.insert(
0,
DownloadUrl {
asset: "url".to_string(),
installerType: InstallerFormat::LinuxFlathubFlatpak,
url: "flatpak".into(),
},
);
map
},
resources: None,
verified: false
})
}
pub async fn get_app_asset<T>(id: &str, _: T) -> Option<Vec<u8>> {
let id = id.replacen("flatpak:", "", 1);
let app = get_ft_app(&id).await?;
CLIENT
.get(app.icon)
.send()
.await
.ok()?
.bytes()
.await
.ok()?
.to_vec()
.into()
}
#[derive(Debug, Serialize, Deserialize)]
struct FlatpakSearchObject {
pub query: String,
pub filters: Vec<()>,
}
#[derive(Debug, Serialize, Deserialize)]
struct FlatpakSearchReturnObject {
pub hits: Vec<FlatpakReturnedApplication>,
}
#[derive(Debug, Serialize, Deserialize)]
struct FlatpakReturnedApplication {
pub name: String,
pub app_id: String,
}
pub async fn search(query: &str) -> Option<Vec<SearchEntry>> {
use serde_json::to_string;
let FlatpakSearchReturnObject { mut hits } = CLIENT
.post(SEARCH)
.body(
to_string(&FlatpakSearchObject {
query: query.to_string(),
filters: vec![],
})
.ok()?,
)
.send()
.await
.ok()?
.json::<FlatpakSearchReturnObject>()
.await
.ok()?;
hits.truncate(10);
Some(
hits
.into_iter()
.map(|x| SearchEntry {
id: format!("flatpak:{}", x.app_id),
name: x.name.clone(),
title: x.name,
})
.collect::<Vec<_>>(),
)
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/api/methods.rs | src-ahqstore-types/src/api/methods.rs | //! Collection of methods that can be used to fetch data from URL Declared AHQ Store Sources
//!
//! Currently URL Declared AHQ Store Parsable Repos Officially Used are
//! - AHQ Store Official Community Repository (AHQStore)
//! - Microsoft Winget Community Repository (WinGet)
use std::collections::HashMap;
#[cfg(feature = "js")]
use wasm_bindgen::prelude::wasm_bindgen;
use serde::{Deserialize, Serialize};
use crate::AHQStoreApplication;
use super::{ahqstore::AHQSTORE_COMMIT_URL, winget::WINGET_COMMIT_URL, RepoHomeData, CLIENT};
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))]
pub struct GHRepoCommit {
pub sha: String,
}
pub enum OfficialManifestSource {
AHQStore,
#[doc = "Third Party Manifest Repo Adapted for use"]
WinGet,
#[doc = "Third Party API Used"]
FlatHub,
#[doc = "Third Party API Used"]
FDroid,
}
pub type Store = OfficialManifestSource;
pub type GHRepoCommits = Vec<GHRepoCommit>;
pub async fn get_commit(store: OfficialManifestSource, token: Option<&String>) -> Option<String> {
let mut builder = CLIENT.get(match store {
OfficialManifestSource::AHQStore => AHQSTORE_COMMIT_URL,
OfficialManifestSource::WinGet => WINGET_COMMIT_URL,
_ => {
return None;
}
});
if let Some(val) = token {
builder = builder.bearer_auth(val);
}
let val = builder.send().await.ok()?;
let mut val = val.json::<GHRepoCommits>().await.ok()?;
let sha = val.remove(0).sha;
Some(sha)
}
pub async fn get_total_maps(total: &str, commit: &str) -> Option<usize> {
CLIENT
.get(total.replace("{COMMIT}", commit))
.send()
.await
.ok()?
.json()
.await
.ok()
}
pub async fn get_home(home: &str, commit: &str) -> Option<Vec<(String, Vec<String>)>> {
let home: RepoHomeData = CLIENT
.get(home.replace("{COMMIT}", commit))
.send()
.await
.ok()?
.json()
.await
.ok()?;
let mut resp_home = vec![];
for (title, data) in home {
let mut resp_data = vec![];
for item in data {
let id = item.get_id();
if let Some(id) = id {
resp_data.push(id);
}
}
resp_home.push((title, resp_data));
}
Some(resp_home)
}
pub async fn get_search(search: &str, commit: &str, id: &str) -> Option<Vec<super::SearchEntry>> {
let url = search.replace("{COMMIT}", commit).replace("{ID}", id);
CLIENT
.get(url)
.send()
.await
.ok()?
.json::<Vec<super::SearchEntry>>()
.await
.ok()
}
pub async fn get_full_map(total: &str, map: &str, commit: &str) -> Option<super::MapData> {
let total = get_total_maps(total, commit).await?;
let mut result = HashMap::new();
let mut i = 1;
while i <= total {
let map_result = get_map(map, commit, &i.to_string()).await?;
for (k, v) in map_result {
result.insert(k, v);
}
i += 1;
}
Some(result)
}
pub async fn get_full_search(
total: &str,
search: &str,
commit: &str,
) -> Option<Vec<super::SearchEntry>> {
let total = get_total_maps(total, commit).await?;
let mut result = vec![];
let mut i = 1;
while i <= total {
let mut search_result = get_search(search, commit, &i.to_string()).await?;
result.append(&mut search_result);
i += 1;
}
Some(result)
}
pub type RespMapData = super::MapData;
pub async fn get_map(map: &str, commit: &str, id: &str) -> Option<RespMapData> {
let val: super::MapData = CLIENT
.get(map.replace("{COMMIT}", commit).replace("{ID}", id))
.send()
.await
.ok()?
.json()
.await
.ok()?;
return Some(val);
}
pub async fn get_devs_apps(apps_dev: &str, commit: &str, id: &str) -> Option<Vec<String>> {
let data: String = CLIENT
.get(apps_dev.replace("{COMMIT}", commit).replace("{ID}", id))
.send()
.await
.ok()?
.text()
.await
.ok()?;
Some(
data
.split("\n")
.into_iter()
.filter(|x| x.trim() != "")
.map(|x| x.to_string())
.collect(),
)
}
pub async fn get_dev_data(dev_data: &str, commit: &str, id: &str) -> Option<super::DevData> {
CLIENT
.get(dev_data.replace("{COMMIT}", commit).replace("{ID}", id))
.send()
.await
.ok()?
.json()
.await
.ok()
}
pub async fn get_app_asset(
app_asset_url: &str,
commit: &str,
app_id: &str,
asset: &str,
) -> Option<Vec<u8>> {
let path = app_asset_url
.replace("{COMMIT}", commit)
.replace("{APP_ID}", app_id)
.replace("{ASSET}", asset);
let builder = CLIENT.get(&path).send().await.ok()?;
Some(builder.bytes().await.ok()?.to_vec())
}
pub async fn get_app(app_url: &str, commit: &str, app_id: &str) -> Option<AHQStoreApplication> {
let url = app_url
.replace("{COMMIT}", commit)
.replace("{APP_ID}", app_id);
let builder = CLIENT.get(url).send().await.ok()?;
builder.json().await.ok()
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/api/search.rs | src-ahqstore-types/src/api/search.rs | use super::{flatpak, get_all_commits, get_all_search, Commits, SearchEntry};
use anyhow::{Context, Result};
use fuse_rust::{Fuse, Fuseable};
use serde::Serialize;
use std::{
ptr::{addr_of, addr_of_mut},
sync::LazyLock,
time::{SystemTime, UNIX_EPOCH},
};
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
struct SCache {
e: Vec<SearchEntry>,
t: u64,
}
static mut SEARCH: Option<SCache> = None;
static FUSE: LazyLock<Fuse> = LazyLock::new(|| Fuse::default());
fn get_search_inner() -> Option<&'static Vec<SearchEntry>> {
let search = unsafe {
let addr = addr_of!(SEARCH);
let addr = &*addr;
let addr = addr.as_ref();
addr
};
let Some(x) = search else {
return None;
};
if x.t > now() {
return Some(&x.e);
}
return None;
}
#[derive(Debug)]
pub enum RespSearchEntry {
Static(&'static SearchEntry),
Owned(SearchEntry),
None,
}
impl Fuseable for RespSearchEntry {
fn lookup(&self, key: &str) -> Option<&str> {
match self {
RespSearchEntry::Owned(x) => x.lookup(key),
RespSearchEntry::Static(x) => x.lookup(key),
RespSearchEntry::None => None
}
}
fn properties(&self) -> Vec<fuse_rust::FuseProperty> {
match self {
RespSearchEntry::Owned(x) => x.properties(),
RespSearchEntry::Static(x) => x.properties(),
RespSearchEntry::None => vec![],
}
}
}
impl Serialize for RespSearchEntry {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer {
match self {
RespSearchEntry::Owned(x) => x.serialize(serializer),
RespSearchEntry::Static(x) => x.serialize(serializer),
RespSearchEntry::None => "".serialize(serializer)
}
}
}
pub async fn get_search(commit: Option<&Commits>, query: &str) -> Result<Vec<RespSearchEntry>> {
let search = get_search_inner();
let search = if search.is_none() {
let commit = if commit.is_none() {
&get_all_commits(None).await?
} else {
commit.unwrap()
};
let search = get_all_search(commit).await?;
let addr = unsafe { &mut *addr_of_mut!(SEARCH) };
*addr = Some(SCache {
e: search,
t: now() + 6 * 60,
});
get_search_inner().unwrap()
} else {
search.unwrap()
};
let mut res = vec![];
for val in FUSE.search_text_in_fuse_list(query, search) {
res.push(RespSearchEntry::Static(&search[val.index]));
}
#[cfg(any(feature = "all_platforms", target_os = "linux"))]
for val in flatpak::search(query).await.context("")? {
res.push(RespSearchEntry::Owned(val));
}
let mut final_res = vec![];
for val in FUSE.search_text_in_fuse_list(query, &res) {
let dummy = RespSearchEntry::None;
let resp = std::mem::replace(&mut res[val.index], dummy);
final_res.push(resp);
}
drop(res);
Ok(final_res)
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/api/mod.rs | src-ahqstore-types/src/api/mod.rs | #[cfg(feature = "js")]
use wasm_bindgen::prelude::wasm_bindgen;
#[cfg(feature = "js")]
use tsify::declare;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[cfg(feature = "search")]
use fuse_rust::{FuseProperty, Fuseable};
#[cfg(feature = "internet")]
pub mod internet;
#[cfg(feature = "internet")]
pub use internet::*;
#[cfg(feature = "internet")]
pub mod methods;
#[cfg(feature = "internet")]
pub mod ahqstore;
#[cfg(feature = "internet")]
pub mod winget;
#[cfg(feature = "internet")]
pub mod flatpak;
#[cfg(feature = "internet")]
pub mod fdroid;
#[cfg(all(feature = "internet", feature = "search"))]
pub mod search;
use reqwest::{Client, ClientBuilder};
use std::sync::LazyLock;
pub static CLIENT: LazyLock<Client> = LazyLock::new(|| {
ClientBuilder::new()
.user_agent("AHQ Store Types / Rust / AHQ Softwares")
.build()
.unwrap()
});
#[cfg_attr(feature = "js", declare)]
pub type MapData = HashMap<String, String>;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct HomeItem {
pub ahqstore: Option<String>,
pub winget: Option<String>,
pub flatpak: Option<String>,
pub fdroid: Option<String>,
}
impl HomeItem {
pub fn get_id(self) -> Option<String> {
if let Some(x) = self.ahqstore {
return Some(x);
}
#[cfg(target_os = "windows")]
return self.winget;
#[cfg(target_os = "linux")]
return self.flatpak;
#[cfg(target_os = "android")]
return self.fdroid;
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "android")))]
return None;
}
}
pub type RepoHomeData = Vec<(String, Vec<HomeItem>)>;
pub type HomeData = Vec<(String, Vec<String>)>;
#[derive(Serialize, Deserialize, Debug)]
#[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))]
pub struct SearchEntry {
pub name: String,
pub title: String,
pub id: String,
}
#[cfg(feature = "search")]
impl Fuseable for SearchEntry {
fn properties(&self) -> Vec<FuseProperty> {
vec![
FuseProperty {
value: "id".into(),
weight: 0.34,
},
FuseProperty {
value: "title".into(),
weight: 0.33,
},
FuseProperty {
value: "name".into(),
weight: 0.33,
},
]
}
fn lookup(&self, key: &str) -> Option<&str> {
match key {
"name" => Some(&self.name),
"title" => Some(&self.title),
"id" => Some(&self.id),
_ => None,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))]
pub struct DevData {
pub name: String,
pub id: String,
pub github: String,
pub avatar_url: String,
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/api/internet.rs | src-ahqstore-types/src/api/internet.rs | //! Unified API for all officially declared AHQ Store Parsable Repos
//!
//! Currently URL Declared AHQ Store Parsable Repos Officially Used are
//! - 🛍️ AHQ Store Official Community Repository (AHQStore)
//! - 🪟 Microsoft Winget Community Repository (WinGet)
//! - 🫓 Flathub Community Repository (FlatHub)
//! - 📱 FDroid Android Community Repository (FDroid)
use crate::AHQStoreApplication;
use super::{
ahqstore::{
AHQSTORE_APPS_DEV, AHQSTORE_APP_ASSET_URL, AHQSTORE_APP_URL, AHQSTORE_DEV_DATA, AHQSTORE_HOME,
AHQSTORE_MAP, AHQSTORE_SEARCH, AHQSTORE_TOTAL,
},
flatpak,
methods::{self, OfficialManifestSource, Store},
winget::{
WINGET_APPS_DEV, WINGET_APP_ASSET_URL, WINGET_APP_URL, WINGET_MAP, WINGET_SEARCH, WINGET_TOTAL,
},
SearchEntry,
};
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Commits {
pub ahqstore: String,
pub winget: String,
}
pub async fn get_all_commits(token: Option<String>) -> Result<Commits> {
let ahqstore = methods::get_commit(Store::AHQStore, token.as_ref())
.await
.context("http")?;
let winget = methods::get_commit(Store::WinGet, token.as_ref())
.await
.context("http")?;
Ok(Commits { ahqstore, winget })
}
pub async fn get_total_maps_by_source(
source: OfficialManifestSource,
commit: &str,
) -> Result<usize> {
let total = match source {
OfficialManifestSource::AHQStore => &*AHQSTORE_TOTAL,
OfficialManifestSource::WinGet => &*WINGET_TOTAL,
_ => {
return Err(anyhow!("source not supported"));
}
};
methods::get_total_maps(total, commit).await.context("")
}
pub async fn get_home(ahqstore_repo_commit: &str) -> Result<Vec<(String, Vec<String>)>> {
let home = &*AHQSTORE_HOME;
methods::get_home(home, ahqstore_repo_commit)
.await
.context("")
}
pub async fn get_search_by_source(
source: OfficialManifestSource,
commit: &str,
id: &str,
) -> Result<Vec<super::SearchEntry>> {
let search = match source {
OfficialManifestSource::AHQStore => &*AHQSTORE_SEARCH,
OfficialManifestSource::WinGet => &*WINGET_SEARCH,
_ => {
return Err(anyhow!(""));
}
};
methods::get_search(search, commit, id).await.context("")
}
pub async fn get_all_maps_by_source(
source: OfficialManifestSource,
commit: &str,
) -> Result<super::MapData> {
let (total, map) = match source {
OfficialManifestSource::AHQStore => (&*AHQSTORE_TOTAL, &*AHQSTORE_MAP),
OfficialManifestSource::WinGet => (&*WINGET_TOTAL, &*WINGET_MAP),
_ => {
return Err(anyhow!("source not supported"));
}
};
let (total, map) = (total.as_str(), map.as_str());
methods::get_full_map(total, map, commit).await.context("")
}
pub async fn get_all_search(commit: &Commits) -> Result<Vec<SearchEntry>> {
let total = &*AHQSTORE_TOTAL;
let search = &*AHQSTORE_SEARCH;
#[allow(unused_mut)]
let mut result: Vec<SearchEntry> = methods::get_full_search(total, search, &commit.ahqstore)
.await
.context("")?;
#[cfg(any(feature = "all_platforms", windows))]
{
let total = &*WINGET_TOTAL;
let search = &*WINGET_SEARCH;
result.append(
&mut methods::get_full_search(total, search, &commit.winget)
.await
.context("")?,
);
}
Ok(result)
}
pub type RespMapData = super::MapData;
pub async fn get_map_by_source(
source: OfficialManifestSource,
commit: &str,
id: &str,
) -> Result<RespMapData> {
let map = match source {
OfficialManifestSource::AHQStore => &*AHQSTORE_MAP,
OfficialManifestSource::WinGet => &*WINGET_MAP,
_ => {
return Err(anyhow!("source not supported"));
}
};
methods::get_map(map, commit, id).await.context("")
}
pub async fn get_devs_apps(
commit: &Commits,
dev_id: &str,
) -> Result<Vec<String>> {
match dev_id {
"flatpak" | "fdroid" => {
// Not worth it to make the api (yer)
return Ok(vec![]);
}
_ => {}
};
let (commit, apps_dev) = if dev_id.starts_with("winget_") {
(&commit.winget, &*WINGET_APPS_DEV)
} else {
(&commit.ahqstore, &*AHQSTORE_APPS_DEV)
};
methods::get_devs_apps(apps_dev, commit, dev_id)
.await
.context("")
}
pub async fn get_dev_data(
commit: &Commits,
id: &str,
) -> Result<super::DevData> {
let dev_data = match id {
"winget" => {
return Ok(super::DevData {
name: "WinGet".into(),
id: "winget".into(),
github: "https://github.com/microsoft/winget-pkgs".into(),
avatar_url: "https://github.com/microsoft/winget-cli/blob/master/.github/images/WindowsPackageManager_Assets/ICO/PNG/_64.png?raw=true".into(),
});
}
"flathub" => {
return Ok(super::DevData {
name: "FlatHub".into(),
id: "flathub".into(),
github: "https://github.com/flathub".into(),
avatar_url: "https://avatars.githubusercontent.com/u/27268838?s=200&v=4".into(),
});
}
"fdroid" => {
return Ok(super::DevData {
name: "F-Droid".into(),
id: "fdroid".into(),
avatar_url: "https://avatars.githubusercontent.com/u/8239603?s=200&v=4".into(),
github: "https://github.com/f-droid".into(),
})
}
_ => &*AHQSTORE_DEV_DATA,
};
methods::get_dev_data(dev_data, &commit.ahqstore, id)
.await
.context("")
}
pub async fn get_app_asset(commit: &Commits, app_id: &str, asset: &str) -> Option<Vec<u8>> {
if app_id.starts_with("flathub:") {
return flatpak::get_app_asset(app_id, asset).await;
}
let (commit, app_asset_url) = if app_id.starts_with("winget_app_") {
(&commit.winget, &*WINGET_APP_ASSET_URL)
} else {
(&commit.ahqstore, &*AHQSTORE_APP_ASSET_URL)
};
methods::get_app_asset(app_asset_url, commit, app_id, asset).await
}
pub async fn get_app(commit: &Commits, app_id: &str) -> Result<AHQStoreApplication> {
if app_id.starts_with("flathub:") {
return flatpak::get_app(app_id).await.context("");
}
let (commit, app_url) = if app_id.starts_with("winget_app_") {
(&commit.winget, &*WINGET_APP_URL)
} else {
(&commit.ahqstore, &*AHQSTORE_APP_URL)
};
methods::get_app(app_url, commit, app_id).await.context("")
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/api/winget.rs | src-ahqstore-types/src/api/winget.rs | //! Declared URLS for:
//! AHQ Store WinGet Repo Parsable Urls (microsoft/winget-pkgs mirror)
//!
//! Repository Mirror : <https://github.com/ahqstore/ahqstore-winget-pkgs>
//! Thanks to winget-pkgs@microsoft for providing the data
use std::sync::LazyLock;
pub static WINGET_COMMIT_URL: &'static str =
"https://api.github.com/repos/ahqstore/ahqstore-winget-pkgs/commits";
pub static WINGET_BASE_URL: &'static str =
"https://rawcdn.githack.com/ahqstore/ahqstore-winget-pkgs/{COMMIT}";
pub static WINGET_APP_URL: LazyLock<String> =
LazyLock::new(|| format!("{WINGET_BASE_URL}/db/apps/{{APP_ID}}.json"));
pub static WINGET_APP_ASSET_URL: LazyLock<String> =
LazyLock::new(|| format!("{WINGET_BASE_URL}/db/res/{{APP_ID}}/{{ASSET}}"));
pub static WINGET_TOTAL: LazyLock<String> = LazyLock::new(|| format!("{WINGET_BASE_URL}/db/total"));
pub static WINGET_SEARCH: LazyLock<String> =
LazyLock::new(|| format!("{WINGET_BASE_URL}/db/search/{{ID}}.json"));
pub static WINGET_MAP: LazyLock<String> =
LazyLock::new(|| format!("{WINGET_BASE_URL}/db/map/{{ID}}.json"));
pub static WINGET_APPS_DEV: LazyLock<String> =
LazyLock::new(|| format!("{WINGET_BASE_URL}/db/dev/{{ID}}"));
pub static WINGET_DEV_DATA: LazyLock<String> =
LazyLock::new(|| format!("{WINGET_BASE_URL}/users/{{ID}}.json"));
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/api/ahqstore.rs | src-ahqstore-types/src/api/ahqstore.rs | //! Declared URLS for:
//! AHQ Store Community Repository Parsable Urls (ahqstore/apps)
//!
//! Repository Mirror : <https://github.com/ahqstore/apps>
use std::sync::LazyLock;
pub static AHQSTORE_COMMIT_URL: &'static str = "https://api.github.com/repos/ahqstore/apps/commits";
pub static AHQSTORE_BASE_URL: &'static str = "https://rawcdn.githack.com/ahqstore/apps/{COMMIT}";
pub static AHQSTORE_APP_URL: LazyLock<String> =
LazyLock::new(|| format!("{AHQSTORE_BASE_URL}/db/apps/{{APP_ID}}.json"));
pub static AHQSTORE_APP_ASSET_URL: LazyLock<String> =
LazyLock::new(|| format!("{AHQSTORE_BASE_URL}/db/res/{{APP_ID}}/{{ASSET}}"));
pub static AHQSTORE_TOTAL: LazyLock<String> =
LazyLock::new(|| format!("{AHQSTORE_BASE_URL}/db/total"));
pub static AHQSTORE_HOME: LazyLock<String> =
LazyLock::new(|| format!("{AHQSTORE_BASE_URL}/db/home.json"));
pub static AHQSTORE_SEARCH: LazyLock<String> =
LazyLock::new(|| format!("{AHQSTORE_BASE_URL}/db/search/{{ID}}.json"));
pub static AHQSTORE_MAP: LazyLock<String> =
LazyLock::new(|| format!("{AHQSTORE_BASE_URL}/db/map/{{ID}}.json"));
pub static AHQSTORE_APPS_DEV: LazyLock<String> =
LazyLock::new(|| format!("{AHQSTORE_BASE_URL}/db/dev/{{ID}}"));
pub static AHQSTORE_DEV_DATA: LazyLock<String> =
LazyLock::new(|| format!("{AHQSTORE_BASE_URL}/users/{{ID}}.json"));
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/data/mod.rs | src-ahqstore-types/src/data/mod.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct DeveloperUser {
/// The Name of the Developer
name: String,
/// A short description of the author[^1]
///
/// [^1]: Maximum 128 words
description: String,
/// The GitHub username of the user
gh_username: String,
/// The base64 version of the user's icon
icon_base64: Option<String>,
/// No user can be ahq_official except @ahqsoftwares
ahq_official: bool,
/// The public email of the user
email: String,
#[doc = "🔬 v2 Schema\n\n"]
support: AppSupport,
/// The list of apps published by the user
apps: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct AppSupport {
/// We recommend you set a discord server
pub discord: Option<String>,
/// Support Site
pub website: Option<String>,
/// GitHub page
pub github: Option<String>,
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/js_macros/src/lib.rs | src-ahqstore-types/js_macros/src/lib.rs | extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn;
#[proc_macro_derive(TsifyAsync)]
pub fn tsify_async_macro_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as a syntax tree
// that we can manipulate
let ast = syn::parse(input).unwrap();
// Build the trait implementation
impl_tsify_async_macro(&ast)
}
fn impl_tsify_async_macro(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;
let gen = quote! {
impl From<#name> for JsValue {
fn from(value: #name) -> Self {
serde_wasm_bindgen::to_value(&value).unwrap()
}
}
};
gen.into()
} | rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/build.rs | src-setup/build.rs | fn main() {
slint_build::compile("ui/index.slint").unwrap();
#[cfg(windows)]
{
let mut res = tauri_winres::WindowsResource::new();
res.set_icon("icon.ico");
res.compile().unwrap();
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/center.rs | src-setup/src/center.rs | // Thanks @prof79
//
// Code Snippet from:
//
// https://github.com/prof79/slint-center-window/blob/main/src/winit_helper.rs
use i_slint_backend_winit::winit::dpi::PhysicalPosition;
use i_slint_backend_winit::winit::monitor::MonitorHandle;
use i_slint_backend_winit::winit::window::Window;
use i_slint_backend_winit::WinitWindowAccessor;
pub fn hide(window: &slint::Window) {
if window.has_winit_window() {
window.with_winit_window(|window| {
window.set_visible(false);
});
}
}
pub fn center_window(window: &slint::Window) {
if window.has_winit_window() {
window.with_winit_window(|window: &Window| {
match window.current_monitor() {
Some(monitor) => set_centered(window, &monitor),
None => (),
};
None as Option<()>
});
}
}
fn set_centered(window: &Window, monitor: &MonitorHandle) {
let window_size = window.outer_size();
let monitor_size = monitor.size();
let monitor_position = monitor.position();
let mut monitor_window_position = PhysicalPosition { x: 0, y: 0 };
monitor_window_position.x = (monitor_position.x as f32 + (monitor_size.width as f32 * 0.5)
- (window_size.width as f32 * 0.5)) as i32;
monitor_window_position.y = (monitor_position.y as f32 + (monitor_size.height as f32 * 0.5)
- (window_size.height as f32 * 0.5)) as i32;
window.set_outer_position(monitor_window_position);
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/main.rs | src-setup/src/main.rs | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![allow(static_mut_refs, unused, dead_code)]
slint::include_modules!();
use slint::{run_event_loop, CloseRequestResponse, ComponentHandle, SharedString};
use std::{env::args, sync::Arc, thread, time::Duration};
mod center;
mod elevate;
mod install;
mod uninstall;
pub mod utils;
#[derive(Debug, Clone, Copy)]
pub enum InstallMode {
None,
Uninstall,
Install,
InstallPR,
}
fn main() -> Result<(), slint::PlatformError> {
let arg = args().collect::<Vec<_>>();
let update = if arg.len() > 1 {
if &arg[1] == "uninstall" {
InstallMode::Uninstall
} else if &arg[1] == "update" {
InstallMode::Install
} else {
InstallMode::InstallPR
}
} else {
InstallMode::None
};
elevate::relaunch_if_needed(&update);
let shall_we_update = !matches!(update, InstallMode::None);
let splash = Splash::new().unwrap();
center::center_window(splash.window());
splash.show();
let splash_hwnd = splash.as_weak();
let ui = AppWindow::new()?;
center::center_window(ui.window());
let ui_hwnd = ui.as_weak();
ui.window().hide();
std::thread::spawn(move || {
thread::sleep(Duration::from_secs(
if shall_we_update {
1
} else {
5
}
));
splash_hwnd.upgrade_in_event_loop(|s| {
center::hide(s.window());
});
ui_hwnd.upgrade_in_event_loop(|f| {
f.show();
});
});
if !matches!(update, InstallMode::None) && !matches!(update, InstallMode::Uninstall) {
ui.set_counter(0.0);
ui.set_msg(SharedString::from("Updating..."));
ui.set_preview(matches!(update, InstallMode::InstallPR));
install::start_install(ui.clone_strong(), update);
} else if matches!(update, InstallMode::Uninstall) {
ui.set_uninstall(true);
ui.set_counter(0.0);
ui.set_msg(SharedString::from("Uninstalling..."));
ui.set_preview(false);
uninstall::uninstall(ui.clone_strong());
}
ui.on_tos(|| {
let _ = open::that("https://ahqstore.github.io/tos");
});
ui.on_site(|| {
let _ = open::that("https://ahqstore.github.io");
});
ui.on_start_install({
let ui_handle = ui.as_weak();
move || {
let handle = ui_handle.unwrap();
handle.set_counter(0.0);
let install_mode = if handle.get_preview() {
InstallMode::InstallPR
} else {
InstallMode::Install
};
install::start_install(handle, install_mode);
}
});
ui.window().on_close_requested(move || {
splash.hide();
CloseRequestResponse::HideWindow
});
run_event_loop()
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/elevate.rs | src-setup/src/elevate.rs | #[cfg(windows)]
use std::{
env::current_exe,
process::{self, Command},
};
#[cfg(windows)]
use check_elevation::is_elevated;
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use crate::InstallMode;
#[cfg(windows)]
fn place_bin_in_temp() -> String {
let mut temp_file = std::env::temp_dir();
std::fs::create_dir_all(&temp_file).unwrap();
temp_file.push("uninstall.exe");
let exe = current_exe().unwrap();
let exe = exe.to_string_lossy();
let exe = exe.to_string();
std::fs::copy(&exe, &temp_file).unwrap();
temp_file.to_string_lossy().to_string()
}
#[cfg(not(windows))]
pub fn relaunch_if_needed(_: &InstallMode) {}
#[cfg(windows)]
pub fn relaunch_if_needed(update: &InstallMode) {
let exe = current_exe().unwrap();
let exe = exe.to_string_lossy();
let (wait, exe): (bool, String) =
if matches!(update, &InstallMode::Uninstall) && !exe.ends_with("uninstall.exe") {
(false, place_bin_in_temp())
} else {
(true, format!("{exe}"))
};
if !is_elevated().unwrap_or(false) {
let mut cmd = Command::new("powershell");
let cmd = cmd.creation_flags(0x08000000);
let cmd = cmd.args(["start-process", "-FilePath"]);
let cmd = cmd.arg(format!("\"{exe}\""));
if wait {
cmd.arg("-wait");
}
if matches!(update, &InstallMode::Install) {
cmd.arg("-args 'update'");
} else if matches!(update, &InstallMode::InstallPR) {
cmd.arg("-args 'update-pr'");
} else if matches!(update, &InstallMode::Uninstall) {
cmd.arg("-args 'uninstall'");
}
cmd.arg("-verb runas");
cmd.spawn().unwrap().wait().unwrap();
process::exit(0);
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/uninstall/mod.rs | src-setup/src/uninstall/mod.rs | use slint::SharedString;
use std::{
fs, mem,
process::{self, Command},
thread,
time::Duration,
};
#[cfg(windows)]
use super::install::regedit::rem_reg;
#[cfg(windows)]
use crate::{install::regedit, AppWindow};
#[cfg(windows)]
use std::os::windows::process::CommandExt;
#[cfg(windows)]
static mut WIN: Option<AppWindow> = None;
#[cfg(not(windows))]
pub fn uninstall<T>(_: T) {}
#[cfg(windows)]
pub fn uninstall(win: AppWindow) {
use crate::utils;
unsafe {
WIN = Some(win);
};
thread::spawn(move || {
let win = unsafe { mem::replace(&mut WIN, None).unwrap() };
win.set_msg(SharedString::from("Getting files ready..."));
thread::sleep(Duration::from_secs(3));
win.set_msg(SharedString::from("Uninstalling..."));
let id = fs::read_to_string(r"C:\Program Files\AHQ Store\unst").unwrap();
let success = Command::new("msiexec.exe")
.arg("/qb+")
.arg(format!("/x{}", &id))
.spawn()
.unwrap()
.wait()
.unwrap()
.success();
utils::kill_daemon();
fs::remove_dir_all(r"C:\Program Files\AHQ Store");
let rem = fs::remove_file(
r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\ahqstore_user_daemon.exe",
);
println!("Err {:?}", rem.err());
println!("Success: {success}");
regedit::rem_reg(&id);
win.set_msg("Uninstalled 🎉".into());
thread::sleep(Duration::from_secs(5));
process::exit(0);
});
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/utils/mod.rs | src-setup/src/utils/mod.rs | #[cfg(windows)]
use std::{os::windows::process::CommandExt, process::Command};
use dirs::home_dir;
use lazy_static::lazy_static;
#[cfg(windows)]
lazy_static! {
pub static ref ROOT_DIR: String = std::env::var("SystemDrive").unwrap();
pub static ref AHQSTORE_ROOT: String = format!(
"{}{}ProgramData{}AHQ Store Applications",
&*ROOT_DIR, &SEP, &SEP
);
}
#[cfg(unix)]
lazy_static! {
pub static ref ROOT_DIR: String = "/".into();
pub static ref AHQSTORE_ROOT: String = "/ahqstore".into();
}
#[cfg(windows)]
static SEP: &'static str = "\\";
#[cfg(unix)]
static SEP: &'static str = "/";
lazy_static! {
pub static ref PROGRAMS: String = format!("{}{}Programs", &*AHQSTORE_ROOT, &SEP,);
pub static ref UPDATERS: String = format!("{}{}Updaters", &*AHQSTORE_ROOT, &SEP);
pub static ref INSTALLERS: String = format!("{}{}Installers", &*AHQSTORE_ROOT, &SEP);
}
#[cfg(windows)]
pub fn get_daemon() -> &'static str {
r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\ahqstore_user_daemon.exe"
}
#[cfg(windows)]
pub fn kill_daemon() {
let _ = Command::new("taskkill.exe")
.arg("/F")
.arg("/IM")
.arg("ahqstore_user_daemon.exe")
.creation_flags(0x08000000)
.spawn()
.unwrap()
.wait()
.unwrap();
}
#[cfg(windows)]
pub fn run_daemon(path: &str) {
let _ = Command::new("powershell.exe")
.args(["start-process", "-FilePath"])
.arg(format!("\"{}\"", &path))
.creation_flags(0x08000000)
.spawn()
.unwrap()
.wait()
.unwrap();
}
pub fn get_install() -> String {
let mut path = home_dir().unwrap();
#[cfg(windows)]
path.push("ahqstore.msi");
#[cfg(not(windows))]
path.push("ahqstore.deb");
path.to_str().unwrap().to_string()
}
#[cfg(not(windows))]
pub fn get_temp_service_dir() -> String {
let mut path = home_dir().unwrap();
path.push("ahqstore_service");
path.to_str().unwrap().to_string()
}
pub fn get_service_dir() -> String {
use std::fs;
#[cfg(windows)]
{
use std::{os::windows::process::CommandExt, process::Command};
Command::new("sc.exe")
.creation_flags(0x08000000)
.args(["stop", "AHQ Store Service"])
.spawn()
.unwrap()
.wait()
.unwrap();
Command::new("sc.exe")
.creation_flags(0x08000000)
.args(["delete", "AHQ Store Service"])
.spawn()
.unwrap()
.wait()
.unwrap();
}
let _ = fs::create_dir_all(&*AHQSTORE_ROOT);
let _ = fs::create_dir_all(&*PROGRAMS);
let _ = fs::create_dir_all(&*UPDATERS);
let _ = fs::create_dir_all(&*INSTALLERS);
#[cfg(windows)]
return format!("{}\\ahqstore_service.exe", &*AHQSTORE_ROOT);
#[cfg(unix)]
return format!("{}/ahqstore_service", &*AHQSTORE_ROOT);
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/install/regedit.rs | src-setup/src/install/regedit.rs | use winreg::enums::*;
use winreg::RegKey;
#[cfg(windows)]
pub fn create_association() -> Option<()> {
let root = RegKey::predef(HKEY_CLASSES_ROOT);
let (key, _) = root.create_subkey("ahqstore").ok()?;
key.set_value("", &"AHQ Store").ok()?;
let (icon, _) = key.create_subkey("DefaultIcon").ok()?;
icon
.set_value("", &r"C:\Program Files\AHQ Store\ahq-store-app.exe,0")
.ok()?;
let (shell, _) = key.create_subkey("shell").ok()?;
let (shell, _) = shell.create_subkey("open").ok()?;
let (shell, _) = shell.create_subkey("command").ok()?;
shell
.set_value(
"",
&r#""C:\Program Files\AHQ Store\ahq-store-app.exe" protocol %1"#,
)
.ok()?;
Some(())
}
#[cfg(windows)]
pub fn custom_uninstall() -> Option<()> {
use std::fs;
let root = RegKey::predef(HKEY_LOCAL_MACHINE);
let key = root.open_subkey("SOFTWARE").ok()?;
let key = key.open_subkey("Microsoft").ok()?;
let key = key.open_subkey("Windows").ok()?;
let key = key.open_subkey("CurrentVersion").ok()?;
let key = key
.open_subkey_with_flags("Uninstall", KEY_ALL_ACCESS)
.ok()?;
let mut uninstall_str = String::default();
let unst = r#""C:\Program Files\AHQ Store\uninstall.exe" uninstall"#;
key.enum_keys().for_each(|x| {
if let Ok(x) = x {
let debug_data = &x;
if let Ok(key) = key.open_subkey_with_flags(&x, KEY_ALL_ACCESS) {
let name = key.get_value::<String, &str>("DisplayName");
let uninstall = key.get_value::<String, &str>("UninstallString");
if let (Ok(x), Ok(y)) = (name, uninstall) {
if &x == "AHQ Store" {
println!("id {debug_data} Name {x}");
key
.set_value(
"DisplayIcon",
&r"C:\Program Files\AHQ Store\ahq-store-app.exe,0",
)
.unwrap();
key.set_value("WindowsInstaller", &0u32).unwrap();
key.set_value("UninstallString", &unst).unwrap();
if &y != unst {
uninstall_str = y;
} else {
uninstall_str = format!("{}", debug_data);
}
}
}
}
}
});
let uninstall_str = uninstall_str.to_lowercase();
let uninstall_str = uninstall_str.replace("msiexec.exe /x", "");
fs::write(r"C:\Program Files\AHQ Store\unst", uninstall_str).ok()
}
pub fn rem_reg(path: &str) -> Option<()> {
let root = RegKey::predef(HKEY_LOCAL_MACHINE);
let key = root.open_subkey("SOFTWARE").ok()?;
let key = key.open_subkey("Microsoft").ok()?;
let key = key.open_subkey("Windows").ok()?;
let key = key.open_subkey("CurrentVersion").ok()?;
let key = key
.open_subkey_with_flags("Uninstall", KEY_ALL_ACCESS)
.ok()?;
/// DANGER: NO NOT REMOVE
/// IF PATH == "", IT"LL BREAK THE SYSTEM
if path != "" && path.len() > 10 {
key.delete_subkey_all(path.to_uppercase()).ok()
} else {
None
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/install/msi.rs | src-setup/src/install/msi.rs | use std::os::windows::process::CommandExt;
use std::process::Command;
pub fn install_msi(path: &str) {
Command::new("powershell")
.args([
"start-process",
"-FilePath",
&format!("\"{}\"", &path),
"-Wait",
"-ArgumentList",
"/quiet, /passive, /norestart",
])
.creation_flags(0x08000000)
.spawn()
.unwrap()
.wait()
.unwrap();
}
pub fn install_service(path: &str) {
Command::new("sc.exe")
.creation_flags(0x08000000)
.args([
"create",
"AHQ Store Service",
"start=",
"auto",
"binpath=",
path,
])
.spawn()
.unwrap()
.wait()
.unwrap();
Command::new("sc.exe")
.creation_flags(0x08000000)
.args(["start", "AHQ Store Service"])
.spawn()
.unwrap()
.wait()
.unwrap();
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/install/download.rs | src-setup/src/install/download.rs | use std::{fs, io::Write};
use reqwest::Client;
pub async fn download<T: FnMut(f32)>(client: &mut Client, url: &str, path: &str, mut call: T) {
let _ = fs::remove_file(&path);
println!("Path: {}", &path);
let mut response = client.get(url).send().await.unwrap();
let mut c = 0;
let t = (response.content_length().unwrap_or(10000)) as u64;
let mut file = vec![];
let mut last = 0u64;
while let Some(chunk) = response.chunk().await.unwrap() {
c += chunk.len();
if last != (c as u64 * 100) / t {
last = (c as u64 * 100) / t;
call(last as f32 / 100.0);
}
file.write_all(&chunk.to_vec()).unwrap();
}
fs::write(path, file).unwrap();
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/install/fetch.rs | src-setup/src/install/fetch.rs | use crate::InstallMode;
use reqwest::{Client, ClientBuilder};
use serde::{Deserialize, Serialize};
use std::env::consts::ARCH;
#[derive(Serialize, Deserialize)]
struct Release {
pub prerelease: bool,
pub tag_name: String,
pub assets: Vec<Asset>,
}
#[derive(Serialize, Deserialize)]
struct Asset {
pub name: String,
pub browser_download_url: String,
}
#[derive(Default, Debug)]
pub struct ReleaseData {
pub msi: String,
pub service: String,
pub linux_daemon: String,
pub deb: String,
pub windows_user_runner: String,
}
macro_rules! arch {
($x:expr, $y:expr) => {
(ARCH == "x86_64" && $x) || (ARCH == "aarch64" && $y)
};
}
pub async fn fetch(install: &InstallMode) -> (Client, ReleaseData) {
let client: Client = ClientBuilder::new()
.user_agent("AHQ Store / Installer")
.build()
.unwrap();
let pre = matches!(install, &InstallMode::InstallPR);
let url = if pre {
"https://api.github.com/repos/ahqsoftwares/tauri-ahq-store/releases"
} else {
"https://api.github.com/repos/ahqsoftwares/tauri-ahq-store/releases/latest"
};
let release = {
if pre {
let release = client
.get(url)
.send()
.await
.unwrap()
.json::<Vec<Release>>()
.await
.unwrap();
release.into_iter().find(|x| x.prerelease).unwrap()
} else {
client
.get(url)
.send()
.await
.unwrap()
.json::<Release>()
.await
.unwrap()
}
};
let mut data = ReleaseData::default();
release.assets.into_iter().for_each(|x| {
if arch!(
x.name.ends_with("x64_en-US.msi"),
x.name.ends_with("arm64_en-US.msi")
) {
data.msi = x.browser_download_url;
} else if arch!(
x.name.ends_with("amd64.deb"),
x.name.ends_with("unsupported.deb")
) {
data.deb = x.browser_download_url;
} else if arch!(
&x.name == "ahqstore_service_amd64.exe",
&x.name == "ahqstore_service_arm64.exe"
) {
data.service = x.browser_download_url;
} else if arch!(
&x.name == "ahqstore_service_amd64",
&x.name == "unsupported_ahqstore_service_arm64"
) {
data.linux_daemon = x.browser_download_url;
} else if arch!(
&x.name == "ahqstore_user_daemon_amd64.exe",
&x.name == "ahqstore_user_daemon_arm64.exe"
) {
data.windows_user_runner = x.browser_download_url;
}
});
(client, data)
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/install/mod.rs | src-setup/src/install/mod.rs | #[cfg(unix)]
use notify_rust::Notification;
use slint::SharedString;
use std::{fs, thread, time::Duration};
use self::fetch::fetch;
use self::fetch::ReleaseData;
use crate::{utils::get_install, AppWindow, InstallMode};
use reqwest::Client;
mod download;
mod fetch;
#[cfg(not(windows))]
mod deb;
#[cfg(windows)]
mod msi;
#[cfg(windows)]
pub mod regedit;
use download::download;
static mut WIN: Option<AppWindow> = None;
pub fn start_install(win: AppWindow, install: InstallMode) {
unsafe { WIN = Some(win) };
thread::spawn(move || {
let win = unsafe { std::mem::replace(&mut WIN, None).unwrap() };
win.set_msg(SharedString::from("Getting files ready..."));
thread::sleep(Duration::from_secs(3));
let mut runtime = tokio::runtime::Builder::new_current_thread();
let runtime = runtime.enable_all().build().unwrap();
runtime.block_on(async {
let (mut client, files) = fetch(&install).await;
println!("{:?}", &files);
plt_install(&win, &mut client, &files).await;
});
});
}
#[cfg(not(windows))]
async fn plt_install(win: &AppWindow, client: &mut Client, files: &ReleaseData) {
use std::process;
use crate::{
install::deb::{exit, get_sudo, install_daemon, install_deb},
utils::{get_service_dir, get_temp_service_dir},
};
if &files.deb == "" {
Notification::new()
.summary("Uh Oh!")
.body("We were unable to find the linux build files, try toggling the Pre-Release Option")
.show()
.unwrap();
win.set_counter(-1.0);
win.set_msg("Install".into());
return;
}
win.set_msg("Downloading...".into());
let installer = get_install();
let temp_service = get_temp_service_dir();
let _ = fs::remove_file(&installer);
download(client, &files.deb, &installer, |perc| {
win.set_counter(perc);
})
.await;
thread::sleep(Duration::from_secs(1));
win.set_counter(0.0);
thread::sleep(Duration::from_secs(3));
download(client, &files.linux_daemon, &temp_service, |perc| {
win.set_counter(perc);
})
.await;
thread::sleep(Duration::from_secs(2));
win.set_indet(true);
win.set_msg("Installing...".into());
let mut sudo = get_sudo();
install_deb(&mut sudo, &installer);
install_daemon(&mut sudo, temp_service);
exit(sudo);
thread::sleep(Duration::from_secs(1));
let _ = fs::remove_file(&installer);
win.set_msg("Installed 🎉".into());
win.set_indet(false);
thread::sleep(Duration::from_secs(5));
process::exit(0);
}
#[cfg(windows)]
async fn plt_install(win: &AppWindow, client: &mut Client, files: &ReleaseData) {
use std::{env::current_exe, process};
use crate::{
install::msi::{install_msi, install_service},
utils::{get_daemon, get_service_dir, kill_daemon, run_daemon},
};
win.set_msg("Downloading...".into());
let installer = get_install();
let service = get_service_dir();
let daemon = get_daemon();
let _ = fs::remove_file(&installer);
download(client, &files.msi, &installer, |perc| {
win.set_counter(perc);
})
.await;
thread::sleep(Duration::from_secs(1));
win.set_counter(0.0);
thread::sleep(Duration::from_secs(3));
download(client, &files.service, &service, |perc| {
win.set_counter(perc);
})
.await;
win.set_counter(1.0);
thread::sleep(Duration::from_millis(100));
win.set_counter(0.0);
thread::sleep(Duration::from_millis(100));
kill_daemon();
if &files.windows_user_runner != "" {
download(client, &files.windows_user_runner, daemon, |perc| {
win.set_counter(perc);
})
.await;
win.set_counter(1.0);
thread::sleep(Duration::from_millis(100));
}
win.set_indet(true);
win.set_msg("Installing...".into());
regedit::create_association();
thread::sleep(Duration::from_secs(2));
install_msi(&installer);
run_daemon(daemon);
regedit::custom_uninstall();
thread::sleep(Duration::from_secs(3));
install_service(&service);
thread::sleep(Duration::from_secs(1));
let _ = fs::remove_file(&installer);
let _ = fs::write(
r"C:\Program Files\AHQ Store\uninstall.exe",
fs::read(current_exe().unwrap()).unwrap(),
);
win.set_msg("Installed 🎉".into());
win.set_indet(false);
thread::sleep(Duration::from_secs(5));
process::exit(0);
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-setup/src/install/deb.rs | src-setup/src/install/deb.rs | use crate::utils::get_service_dir;
use std::{
io::Write,
process::{Child, Command, Stdio},
};
pub fn get_sudo() -> Child {
println!("Running pxexec");
let child = Command::new("pkexec")
.args(["sudo", "-i"])
.stdin(Stdio::piped())
.spawn()
.unwrap();
child
}
pub fn install_deb(child: &mut Child, path: &str) {
let stdin = child.stdin.as_mut();
let stdin = stdin.unwrap();
let data = format!("sudo apt install {:?}\n", &path);
let _ = stdin.write_all(data.as_bytes());
let _ = stdin.flush();
}
pub fn install_daemon(child: &mut Child, service: String) {
let stdin = child.stdin.as_mut();
let stdin = stdin.unwrap();
let perma_service = get_service_dir();
let data = format!(
"cp {} {}\nrm {}\nchmod -R u+rwx /ahqstore\n",
&service, &perma_service, &service
);
let _ = stdin.write_all(data.as_bytes());
let file = format!(
r"[Unit]
Description=AHQ Store Service
[Service]
User=root
WorkingDirectory=/ahqstore
ExecStart=/ahqstore/service
Restart=always
[Install]
WantedBy=multi-user.target"
);
let data = format!("echo {file:?} > /etc/systemd/system/ahqstore.service\nsystemctl daemon-reload\nsystemctl enable ahqstore.service\nsystemctl start ahqstore.service\n");
let _ = stdin.write_all(data.as_bytes());
}
pub fn exit(mut child: Child) {
let stdin = child.stdin.as_mut();
let stdin = stdin.unwrap();
let _ = stdin.write_all(b"exit\n");
let _ = stdin.flush();
let _ = child.wait();
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/build.rs | src-tauri/build.rs | fn main() {
tauri_build::build()
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/structs.rs | src-tauri/src/structs.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PayloadReq {
pub module: String,
pub data: Option<String>,
pub ref_id: u64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ToSendResp {
pub method: Option<String>,
pub status: Option<String>,
pub payload: Option<String>,
pub ref_id: String,
pub reason: Option<String>,
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/rpc.rs | src-tauri/src/rpc.rs | use discord_rich_presence::{
activity::{Activity, Assets, Button},
DiscordIpc, DiscordIpcClient,
};
use std::thread::spawn;
use std::time::Duration;
static CLIENT_ID: &str = "897736309806882827";
pub fn init_presence(window: &tauri::WebviewWindow) {
let window = window.clone();
let _ = spawn(move || {
if let Ok(mut rpc) = DiscordIpcClient::new(CLIENT_ID) {
loop {
if let Ok(_) = rpc.connect() {
break;
}
std::thread::sleep(Duration::from_secs(1));
}
let version = env!("CARGO_PKG_VERSION");
#[cfg(not(debug_assertions))]
let deatils = format!("v{}", &version);
#[cfg(debug_assertions)]
let deatils = format!("v{}-next-internal", &version);
loop {
let title = window
.title()
.unwrap_or("Home - AHQ Store".into())
.replace(" - AHQ Store", " Page")
.replace("AHQ Store", "Loading Screen");
let title = format!("Viewing {}", &title);
let activity = Activity::new()
.state(&title)
.details(&deatils)
.assets(
Assets::new()
.large_image("icon")
.large_text("AHQ Store")
.small_image("dev")
.small_text("ahqsoftwares"),
)
.buttons(vec![Button::new("Download", "https://ahqstore.github.io")]);
if let Err(_) = rpc.set_activity(activity) {
let _ = rpc.reconnect();
}
std::thread::sleep(Duration::from_secs(5));
}
} else {
println!("Fail...");
}
});
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/main.rs | src-tauri/src/main.rs | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![allow(static_mut_refs)]
pub mod rpc;
#[macro_use]
pub mod encryption;
pub mod structs;
mod app;
fn main() {
app::main();
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/app/download.rs | src-tauri/src/app/download.rs | use crate::app::utils::CLIENT;
use std::{
fs::{create_dir_all, File},
io::Write,
};
pub fn download(url: &str, path: &str, file: &str, logger: fn(u64, u64) -> ()) -> u8 {
let datas = create_dir_all(path);
match datas {
Err(_daras) => {
#[cfg(debug_assertions)]
println!("{}", _daras.to_string())
}
Ok(()) => {
#[cfg(debug_assertions)]
println!("Created Dir for files")
}
};
(|| {
let mut file = File::create(format!("{}/{}", &path, &file)).ok()?;
let bytes = CLIENT.get(url).send().ok()?.bytes().ok()?;
let total = bytes.len() as u64;
let mut written = 0 as u64;
for byte in bytes.chunks(20000) {
written += byte.len() as u64;
file.write(byte).ok()?;
logger(written, total);
}
file.flush().ok()
})()
.map_or_else(|| 1, |_| 0)
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/app/utils.rs | src-tauri/src/app/utils.rs | use std::process::{Command, Stdio};
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use lazy_static::lazy_static;
use reqwest::{
blocking::{Client, ClientBuilder},
header::{HeaderMap, HeaderValue},
};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct GhRelease {
pub prerelease: bool,
pub assets: Vec<GHAsset>,
}
#[derive(Serialize, Deserialize)]
struct GHAsset {
pub name: String,
pub browser_download_url: String,
}
lazy_static! {
pub static ref CLIENT: Client = {
let mut map = HeaderMap::new();
map.insert(
"User-Agent",
HeaderValue::from_str("AHQ Store/Service Installer").unwrap(),
);
ClientBuilder::new().default_headers(map).build().unwrap()
};
}
pub fn get_service_url(pr: bool) -> String {
let mut get = CLIENT
.get("https://api.github.com/repos/ahqsoftwares/tauri-ahq-store/releases")
.send()
.unwrap()
.json::<Vec<GhRelease>>()
.unwrap();
let get = if pr {
get.swap_remove(0)
} else {
get.into_iter().find(|x| x.prerelease == false).unwrap()
};
for asset in get.assets {
if (cfg!(unix) && &asset.name == "ahqstore_setup_amd64_linux")
|| (cfg!(windows) && &asset.name == "ahqstore_setup_win32_amd64.exe")
{
return asset.browser_download_url;
}
}
panic!("Asset not found");
}
#[tauri::command(async)]
pub fn is_an_admin() -> bool {
get_whoami().map_or_else(|| false, |x| get_localgroup(&x).unwrap_or(false))
}
#[cfg(unix)]
fn get_whoami() -> Option<String> {
let mut whoami = None;
let command = Command::new("whomai").stdout(Stdio::piped()).spawn();
if let Ok(child) = command {
if let Ok(status) = child.wait_with_output() {
let output = String::from_utf8_lossy(&status.stdout);
whoami = Some(output.trim().into());
}
}
whoami
}
#[cfg(windows)]
fn get_whoami() -> Option<String> {
let mut whoami = None;
let command = Command::new("powershell")
.args(["whoami"])
.creation_flags(0x08000000)
.stdout(Stdio::piped())
.spawn();
if let Ok(child) = command {
if let Ok(status) = child.wait_with_output() {
let output = String::from_utf8_lossy(&status.stdout);
let new_whoami = output.split("\\").collect::<Vec<&str>>()[1]
.trim()
.to_string();
whoami = Some(new_whoami);
}
}
whoami
}
#[cfg(unix)]
fn get_localgroup(user: &String) -> Option<bool> {
return None;
}
#[cfg(windows)]
fn get_localgroup(user: &String) -> Option<bool> {
let command = Command::new("powershell")
.arg("$AdminGroupName = (Get-WmiObject -Class Win32_Group -Filter 'LocalAccount = True AND SID = \"S-1-5-32-544\"').Name;")
.arg("net localgroup $AdminGroupName")
.creation_flags(0x08000000)
.stdout(Stdio::piped())
.spawn()
.ok()?
.wait_with_output()
.ok()?
.stdout;
let command = String::from_utf8_lossy(&command);
let users = command
.split("-------------------------------------------------------------------------------")
.collect::<Vec<&str>>()[1]
.trim()
.trim()
.split("\n");
let mut users = users.collect::<Vec<_>>();
users.pop();
let users = users
.into_iter()
.map(|x| x.trim().to_lowercase())
.filter(|x| x == user)
.collect::<Vec<String>>();
Some(users.len() > 0 && users.len() <= 1)
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/app/mod.rs | src-tauri/src/app/mod.rs | #![allow(unused)]
#![allow(non_upper_case_globals)]
pub mod download;
pub mod extract;
#[macro_use]
pub mod utils;
mod ws;
use crate::rpc;
use ahqstore_types::search::RespSearchEntry;
use tauri::{Emitter, Listener};
use tauri::menu::IconMenuItemBuilder;
use tauri::tray::{TrayIconBuilder, TrayIconEvent, MouseButton};
use tauri::window::{ProgressBarState, ProgressBarStatus};
use tauri::{AppHandle, Runtime, WebviewWindowBuilder};
use tauri::{
ipc::Response,
image::Image,
menu::{Menu, MenuBuilder, MenuEvent, MenuId, MenuItem},
Manager, RunEvent,
};
//modules
use crate::encryption::{decrypt, encrypt, to_hash_uid};
//crates
#[cfg(windows)]
use windows::Win32::{
Foundation::BOOL,
Graphics::Dwm::{
DwmEnableBlurBehindWindow, DwmSetWindowAttribute, DWMWINDOWATTRIBUTE, DWM_BLURBEHIND,
},
};
use std::panic::catch_unwind;
use std::path::PathBuf;
use std::process;
use std::time::{Duration, SystemTime};
#[cfg(unix)]
use whatadistro::identify;
//std
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::{
fs,
fmt::Display,
process::Command,
process::Stdio,
sync::{Arc, Mutex},
thread,
};
//link Launcher
use open as open_2;
use utils::{get_service_url, is_an_admin};
use ahqstore_types::{
internet, search, AHQStoreApplication, Commits, DevData
};
use serde::{Serialize, Deserialize};
use anyhow::Context;
#[derive(Debug, Serialize, Deserialize)]
pub enum AHQError {
JustAnError
}
impl Display for AHQError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AHQError::JustAnError => write!(f, "JustAnError"),
}
}
}
impl std::error::Error for AHQError {}
impl From<anyhow::Error> for AHQError {
fn from(_: anyhow::Error) -> Self {
AHQError::JustAnError
}
}
macro_rules! platform_impl {
($x:expr, $y:expr) => {{
#[cfg(windows)]
return { $x };
#[cfg(unix)]
return { $y };
}};
}
#[derive(Debug, Clone)]
struct AppData {
pub name: String,
pub data: String,
}
static mut WINDOW: Option<tauri::WebviewWindow<tauri::Wry>> = None;
static mut UPDATER_FILE: Option<String> = None;
lazy_static::lazy_static! {
static ref ready: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));
static ref queue: Arc<Mutex<Vec<AppData>>> = Arc::new(Mutex::new(Vec::<AppData>::new()));
}
pub fn main() {
let context = tauri::generate_context!();
let app = tauri::Builder::default()
.setup(|app| {
println!(
"Webview v{}",
tauri::webview_version().unwrap_or("UNKNOWN".to_string())
);
let args = std::env::args();
let buf = std::env::current_exe().unwrap().to_owned();
let exec = buf.to_str().unwrap().to_owned();
let window = app.get_webview_window("main").unwrap();
let listener = window.clone();
let ready_clone = ready.clone();
let queue_clone = queue.clone();
let mut updater_path = app.path().app_data_dir().unwrap();
let _ = fs::create_dir_all(&updater_path);
updater_path.push("update.txt");
unsafe {
UPDATER_FILE = Some(updater_path.to_str().unwrap().to_string());
fs::remove_dir_all(format!("{}\\astore", sys_handler())).unwrap_or(());
let window = app.get_webview_window("main").unwrap();
WINDOW = Some(window.clone());
ws::init(&window, || {
#[cfg(debug_assertions)]
println!("Reinstall of AHQ Store is required...");
tauri::async_runtime::spawn(async {
update_inner(true).await;
});
});
}
tauri::async_runtime::block_on(async {
update_inner(false).await;
});
#[cfg(windows)]
{
thread::sleep(Duration::from_secs(1));
let hwnd = window.hwnd().unwrap();
unsafe {
//2: Mica, 3: Acrylic, 4: Mica Alt
let attr = 2;
let _ = DwmSetWindowAttribute(
hwnd,
DWMWINDOWATTRIBUTE(38),
&attr as *const _ as _,
std::mem::size_of_val(&attr) as u32,
);
}
}
{
let window = window.clone();
listener.listen("ready", move |_| {
#[cfg(debug_assertions)]
println!("ready");
*ready_clone.lock().unwrap() = true;
for item in queue_clone.lock().unwrap().iter() {
window.emit(item.name.as_str(), item.data.clone()).unwrap();
}
let lock = queue_clone.lock();
if lock.is_ok() {
*lock.unwrap() = Vec::<AppData>::new();
}
});
}
{
let window = window.clone();
listener.listen("activate", move |_| {
window.show().unwrap();
});
}
if std::env::args().last().unwrap().as_str() != exec.clone().as_str() {
let args = args.last().unwrap_or(String::from(""));
#[cfg(debug_assertions)]
println!("Started with {}", args);
if *ready.clone().lock().unwrap() {
window.emit("launch_app", args.clone()).unwrap();
} else {
queue.clone().lock().unwrap().push(AppData {
data: args.clone(),
name: String::from("launch_app"),
});
}
}
Ok(())
})
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_single_instance::init(|app, args, _| {
if let Some(main) = app.get_webview_window("main") {
let _ = main.show();
let _ = main.set_focus();
if args.len() == 3 {
if *ready.clone().lock().unwrap() {
main.emit("launch_app", args[2].clone()).unwrap();
} else {
queue.clone().lock().unwrap().push(AppData {
data: args[2].clone(),
name: String::from("launch_app"),
});
}
}
}
}))
.invoke_handler(tauri::generate_handler![
get_windows,
sys_handler,
encrypt,
decrypt,
dsc_rpc,
to_hash_uid,
open,
set_progress,
is_an_admin,
is_development,
check_install_update,
show_code,
rem_code,
hash_username,
get_linux_distro,
set_commit,
get_all_search,
get_home,
get_app,
get_dev_data,
get_app_asset,
get_devs_apps,
get_arch,
set_scale
])
.menu(|handle| Menu::new(handle))
.build(context)
.unwrap();
TrayIconBuilder::with_id("main")
.tooltip("AHQ Store is running")
.icon(Image::from_bytes(include_bytes!("../../icons/icon.png")).unwrap())
.menu_on_left_click(false)
.menu(
&MenuBuilder::new(&app)
.id("tray-menu")
.item(
&IconMenuItemBuilder::new("&AHQ Store")
.enabled(false)
.icon(Image::from_bytes(include_bytes!("../../icons/icon.png")).unwrap())
.build(&app)
.unwrap(),
)
.separator()
.item(&MenuItem::with_id(&app, "open", "Open App", true, None::<String>).unwrap())
.item(
&MenuItem::with_id(&app, "update", "Check for Updates", true, None::<String>).unwrap(),
)
.separator()
.item(&MenuItem::with_id(&app, "quit", "Quit", true, None::<String>).unwrap())
.build()
.unwrap(),
)
.on_tray_icon_event(|app, event| match event {
TrayIconEvent::Click { button, .. } => match button {
MouseButton::Left => {
let _ = app.app_handle().get_webview_window("main").unwrap().show();
}
_ => {}
}
_ => {}
})
.on_menu_event(|app, ev| {
let MenuEvent { id: MenuId(id) } = ev;
match id.as_str() {
"open" => {
let window = app.get_webview_window("main").unwrap();
window.show().unwrap();
}
"update" => {
tauri::async_runtime::spawn(async {
check_install_update().await;
});
}
"quit" => {
process::exit(0);
}
_ => {}
}
})
.build(&app)
.unwrap();
app.run(move |app, event| match event {
RunEvent::ExitRequested { api, .. } => {
api.prevent_exit();
}
RunEvent::WindowEvent { event, label, .. } => match event {
tauri::WindowEvent::CloseRequested { api, .. } => {
api.prevent_close();
if let Some(win) = app.get_webview_window(&label) {
let _ = win.hide();
}
}
_ => {}
},
_ => {}
});
}
static mut COMMIT: Option<Commits> = None;
#[tauri::command(async)]
async fn set_scale(window: tauri::WebviewWindow, scale: f64) {
let _ = window.set_zoom(scale);
}
#[tauri::command(async)]
async fn set_commit(commit: Commits) {
unsafe {
COMMIT = Some(commit);
}
}
#[tauri::command(async)]
async fn get_all_search(query: &str) -> Result<Vec<RespSearchEntry>, AHQError> {
Ok(search::get_search(unsafe { COMMIT.as_ref() }, query).await?)
}
#[tauri::command(async)]
async fn get_home() -> Result<Vec<(String, Vec<String>)>, AHQError> {
Ok(internet::get_home(unsafe { &COMMIT.as_ref().unwrap().ahqstore }).await?)
}
#[tauri::command(async)]
async fn get_app(app: &str) -> Result<AHQStoreApplication, AHQError> {
Ok(internet::get_app(unsafe { COMMIT.as_ref().unwrap() }, app).await?)
}
#[tauri::command(async)]
async fn get_app_asset(app: &str, asset: &str) -> Result<Response, AHQError> {
let bytes = internet::get_app_asset(unsafe { COMMIT.as_ref().unwrap() }, app, asset).await.context("")?;
Ok(Response::new(bytes))
}
#[tauri::command(async)]
async fn get_dev_data(dev: &str) -> Result<DevData, AHQError> {
Ok(internet::get_dev_data(unsafe { COMMIT.as_ref().unwrap() }, dev).await?)
}
#[tauri::command(async)]
async fn get_devs_apps(dev: &str) -> Result<Vec<String>, AHQError> {
Ok(internet::get_devs_apps(unsafe { COMMIT.as_ref().unwrap() }, dev).await?)
}
#[tauri::command(async)]
fn hash_username(username: String) -> String {
ahqstore_gh_hash::compute(username.as_str())
}
#[tauri::command(async)]
fn dsc_rpc(window: tauri::WebviewWindow<tauri::Wry>,) {
rpc::init_presence(&window);
}
#[tauri::command(async)]
fn show_code<R: Runtime>(app: AppHandle<R>, code: String) {
WebviewWindowBuilder::new(&app, "code", tauri::WebviewUrl::App(PathBuf::from(&format!("/{code}"))))
.skip_taskbar(true)
.title("Login to GitHub")
.inner_size(400.0, 150.0)
.max_inner_size(400.0, 150.0)
.min_inner_size(400.0, 150.0)
.decorations(false)
.always_on_top(true)
.fullscreen(false)
.content_protected(true)
.maximizable(false)
.minimizable(false)
.closable(true)
.focused(true)
.build();
}
#[tauri::command(async)]
fn rem_code<R: Runtime>(app: tauri::AppHandle<R>) {
app.get_webview_window("code")
.unwrap()
.destroy()
.unwrap()
}
#[tauri::command(async)]
fn is_development() -> bool {
cfg!(debug_assertions) || env!("CARGO_PKG_VERSION").contains("-alpha")
}
#[cfg(unix)]
pub fn chmod(typ: &str, regex: &str) -> Option<bool> {
use std::process::Command;
Command::new("chmod")
.args([typ, regex])
.spawn()
.ok()?
.wait()
.ok()?
.success()
.into()
}
#[tauri::command(async)]
fn open(url: String) -> Option<()> {
match open_2::that(url) {
Ok(_) => Some(()),
_ => None,
}
}
#[tauri::command]
async fn check_install_update() {
update_inner(false).await;
}
async fn now() -> u64 {
use std::time::UNIX_EPOCH;
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
async fn update_inner(must: bool) {
use updater::*;
let now = now().await;
if !must {
if let Some(x) = unsafe { UPDATER_FILE.as_ref() } {
if let Ok(mut x) = fs::read(x) {
let mut bytes = [0; 8];
x.truncate(8);
if x.len() == 8 {
for (i, d) in x.iter().enumerate() {
bytes[i] = *d;
}
let should = u64::from_be_bytes(bytes) + (/*1 day*/ 60 * 60 * 24);
if now < should {
return;
}
}
}
}
}
let (avail, release) = is_update_available(
if must {
""
} else { env!("CARGO_PKG_VERSION") },
env!("CARGO_PKG_VERSION").contains("-alpha"),
)
.await;
if avail {
if let Some(release) = release {
unsafe {
let _ = WINDOW.clone().unwrap().emit("update", "installing");
}
let _ = fs::write(unsafe { UPDATER_FILE.as_ref().unwrap() }, now.to_be_bytes());
tokio::time::sleep(Duration::from_secs(4)).await;
update(release).await;
process::exit(0);
}
}
}
#[tauri::command(async)]
fn sys_handler() -> String {
#[cfg(windows)]
return std::env::var("SYSTEMROOT")
.unwrap()
.to_uppercase()
.as_str()
.replace("\\WINDOWS", "")
.replace("\\Windows", "");
#[cfg(unix)]
return "/".into();
}
#[tauri::command(async)]
fn set_progress(
window: tauri::WebviewWindow<tauri::Wry>,
state: i32,
c: Option<u64>,
t: Option<u64>,
) {
let progress = match (c, t) {
(Some(c), Some(t)) => Some((c * 100) / t),
_ => None,
};
let _ = window.set_progress_bar(ProgressBarState {
progress,
status: Some(match state {
1 => ProgressBarStatus::Indeterminate,
2 => ProgressBarStatus::Normal,
4 => ProgressBarStatus::Error,
8 => ProgressBarStatus::Paused,
_ => ProgressBarStatus::None,
}),
});
}
#[tauri::command(async)]
fn get_linux_distro() -> Option<String> {
#[cfg(windows)]
return None;
#[cfg(unix)]
return Some(identify()?.name().into());
}
#[tauri::command(async)]
fn get_windows() -> &'static str {
#[cfg(unix)]
return "linux";
#[cfg(windows)]
return {
if is_windows_11() {
"11"
} else {
"10"
}
};
}
#[tauri::command(async)]
fn get_arch() -> &'static str {
std::env::consts::ARCH
}
#[cfg(windows)]
fn is_windows_11() -> bool {
let version = Command::new("cmd")
.creation_flags(0x08000000)
.args(["/c", "ver"])
.stdout(Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap()
.stdout;
let string = String::from_utf8(version).unwrap();
let splitted = string
.replace("\n", "")
.replace("Microsoft Windows [", "")
.replace("]", "");
let version: Vec<&str> = splitted.split(".").collect();
let version: usize = version[2].parse().unwrap_or(0);
version >= 22000
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/app/ws.rs | src-tauri/src/app/ws.rs | use async_recursion::async_recursion;
#[cfg(windows)]
use tokio::net::windows::named_pipe::{ClientOptions, PipeMode};
#[cfg(unix)]
use tokio::net::UnixStream;
use tokio::sync::Mutex;
use serde_json::from_str;
use std::sync::Arc;
use std::thread;
use std::{ffi::OsStr, io::ErrorKind, thread::spawn, time::Duration};
use tauri::{Emitter, Listener};
use tauri::Manager;
static mut CONNECTION: Option<WsConnection> = None;
static mut WINDOW: Option<tauri::WebviewWindow> = None;
static mut LAST_CMD: Option<String> = None;
#[allow(unused)]
struct WsConnection {
to_send: Arc<Mutex<Vec<String>>>,
}
unsafe impl Send for WsConnection {}
unsafe impl Sync for WsConnection {}
impl WsConnection {
pub fn new() -> Self {
unsafe {
LAST_CMD = Some("".into());
}
Self {
to_send: Arc::new(Mutex::new(vec![])),
}
}
pub fn send_ws(&mut self, value: &str) {
unsafe {
if let Some(x) = LAST_CMD.as_mut() {
if &x != &value {
let to_send = self.to_send.clone();
if let Ok(mut send) = to_send.try_lock() {
LAST_CMD = Some(value.into());
send.push(value.into());
} else {
thread::sleep(std::time::Duration::from_millis(1));
self.send_ws(value);
};
}
}
}
}
#[async_recursion]
pub async unsafe fn start(&mut self, reinstall_astore: fn(), tries: u8) {
#[cfg(windows)]
let path = OsStr::new(r"\\.\pipe\ahqstore-service-api-v3");
let reinstall = || async {
tokio::time::sleep(Duration::from_millis(5)).await;
if tries > 20 {
reinstall_astore();
false
} else {
true
}
};
#[cfg(windows)]
let ipc_gen_0x68 = ClientOptions::new().pipe_mode(PipeMode::Message).open(path);
#[cfg(unix)]
let ipc_gen_0x68 = UnixStream::connect("/ahqstore/socket")
.await;
match ipc_gen_0x68 {
Ok(ipc) => {
let mut len: [u8; 8] = [0; 8];
loop {
// Reading Pending Messages
match ipc.try_read(&mut len) {
Ok(0) => {}
Ok(8) => {
let size = usize::from_be_bytes(len);
let mut data: Vec<u8> = vec![];
let mut bit = [0u8];
let mut iter = 0i64;
loop {
iter += 1;
if iter == i64::MAX {
reinstall_astore();
}
if data.len() == size {
break;
}
match ipc.try_read(&mut bit) {
Ok(_) => {
data.push(bit[0]);
}
Err(e) => match e.kind() {
ErrorKind::WouldBlock => {}
e => {
println!("Byte: {e:?}");
if &format!("{e:?}") != "Uncategorized" {
break;
}
}
},
}
}
if data.len() == usize::from_be_bytes(len) {
let stri = String::from_utf8_lossy(&data);
let stri = stri.to_string();
if let Some(win) = WINDOW.as_mut() {
win.emit("ws_resp", &[stri]).unwrap_or(());
}
} else {
println!("Packet Rejected!");
}
}
Ok(t) => {
println!("huh {t}");
break;
}
Err(e) => match e.kind() {
ErrorKind::WouldBlock => {}
e => {
println!("Len: {e:?}");
break;
}
},
}
//Sending Messages
if let Ok(ref mut x) = self.to_send.try_lock() {
if x.len() > 0 {
let msg = x.remove(0);
let len = msg.len().to_be_bytes();
let mut data = vec![];
for byte in len {
data.push(byte);
}
for byte in msg.as_bytes() {
data.push(*byte);
}
if let Err(_) = ipc.try_write(&data) {
println!("{data:?} resulted in error");
}
}
}
#[cfg(windows)]
tokio::time::sleep(Duration::from_nanos(1)).await;
#[cfg(not(windows))]
tokio::time::sleep(Duration::from_nanos(100)).await;
}
drop(ipc);
if reinstall().await {
self.start(reinstall_astore, tries + 1).await;
}
}
e => {
println!("{tries}: {e:?}");
if reinstall().await {
self.start(reinstall_astore, tries + 1).await;
}
}
}
}
}
pub unsafe fn init<'a>(window: &tauri::WebviewWindow, reinstall_astore: fn()) {
let window: tauri::WebviewWindow = window.clone();
spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.worker_threads(5)
.enable_all()
.build()
.unwrap();
rt.block_on(async move {
WINDOW = Some(window);
let connection = WsConnection::new();
CONNECTION = Some(connection);
if let Some(win) = WINDOW.as_mut() {
win.listen("ws_send", |ev| {
let x = ev.payload();
if let Ok(x) = from_str::<String>(x) {
CONNECTION.as_mut().unwrap().send_ws(&x);
}
});
}
let ras = reinstall_astore.clone();
unsafe { CONNECTION.as_mut().unwrap().start(ras, 0).await };
});
});
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/app/extract.rs | src-tauri/src/app/extract.rs | use std::{env::current_exe, ffi::OsStr};
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::process::Command;
pub fn run_admin<T: AsRef<OsStr>>(path: T) {
#[cfg(windows)]
{
let mut child = Command::new("powershell");
let exe = current_exe().unwrap();
child
.creation_flags(0x08000000)
.arg("start-process")
.arg(path)
.args(["-verb", "runas"])
.arg("-wait; start-process")
.arg(exe);
let _ = child.spawn().unwrap();
}
#[cfg(unix)]
{
Command::new("nohup").arg(path).spawn().unwrap();
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/encryption/mod.rs | src-tauri/src/encryption/mod.rs | mod cache;
use cache::*;
use bcrypt::{hash_with_salt, Version, DEFAULT_COST};
use chacha20poly1305::{
aead::{generic_array::GenericArray, Aead, KeyInit},
ChaCha20Poly1305,
};
use lazy_static::lazy_static;
lazy_static! {
static ref CRYPTER: ChaCha20Poly1305 = {
let key = GenericArray::from_slice(
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/encrypt")).as_bytes(),
);
ChaCha20Poly1305::new(&key)
};
}
static SALT: [u8; 16] = [
0x14, 0x4b, 0x3d, 0x69, 0x1a, 0x7b, 0x4e, 0xcf, 0x39, 0xcf, 0x73, 0x5c, 0x7f, 0xa7, 0xa7, 0x9c,
];
use serde_json::to_string;
#[tauri::command(async)]
pub fn to_hash_uid(id: String) -> Option<String> {
Some(
hash_with_salt(&id, DEFAULT_COST, SALT)
.ok()?
.format_for_version(Version::TwoB)
.replace(".", "0")
.replace("/", "1")
.replace("$", "2"),
)
}
#[tauri::command(async)]
pub fn encrypt(payload: String) -> Option<Vec<u8>> {
let nonce = GenericArray::from_slice(b"SSSSSSSSSSSS");
if let Some(x) = get_encrypted(payload.clone()) {
return Some(x);
} else {
let data = CRYPTER.encrypt(nonce, payload.as_bytes());
if let Ok(data) = &data {
set_encrypted(payload, data.clone());
}
return data.ok();
}
}
#[tauri::command(async)]
pub fn decrypt(encrypted: Vec<u8>) -> Option<String> {
let nonce = GenericArray::from_slice(b"SSSSSSSSSSSS");
let en_txt = to_string(&encrypted).ok()?;
if let Some(x) = get_decrypted(en_txt.clone()) {
return Some(x);
}
let decrypted = CRYPTER.decrypt(nonce, &*encrypted).ok()?;
let string = String::from_utf8(decrypted);
if let Err(x) = string {
println!("{:#?}", x);
return None;
} else {
let string = string.unwrap();
set_decrypted(en_txt, string.clone());
return Some(string);
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-tauri/src/encryption/cache.rs | src-tauri/src/encryption/cache.rs | use std::collections::HashMap;
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
struct CacheEntry {
pub data: String,
pub last_accessed: u64,
}
struct CacheEntryVec {
pub data: Vec<u8>,
pub last_accessed: u64,
}
static mut PURGING: bool = false;
static mut ENCRYPTED: Option<HashMap<String, CacheEntryVec>> = None;
static mut DECRYPTED: Option<HashMap<String, CacheEntry>> = None;
pub fn get_encrypted(key: String) -> Option<Vec<u8>> {
let purging = unsafe { PURGING };
if purging {
return None;
}
let encrypted = unsafe { ENCRYPTED.as_ref() };
if let Some(encrypted) = encrypted {
let resp = encrypted.get(&key).map(|e| e.data.clone());
if let &Some(_) = &resp {
unsafe { update_time(key, false) };
}
return resp;
} else {
unsafe {
init();
}
}
None
}
pub fn set_encrypted(key: String, data: Vec<u8>) {
let purging = unsafe { PURGING };
if purging {
return;
}
let encrypted = unsafe { ENCRYPTED.as_mut() };
if let None = encrypted {
unsafe {
init();
}
}
encrypted.unwrap().insert(
key,
CacheEntryVec {
data,
last_accessed: now(),
},
);
}
pub fn get_decrypted(key: String) -> Option<String> {
let purging = unsafe { PURGING };
if purging {
return None;
}
let decrypted = unsafe { DECRYPTED.as_ref() };
if let Some(decrypted) = decrypted {
let resp = decrypted.get(&key).map(|e| e.data.clone());
if let &Some(_) = &resp {
unsafe { update_time(key, true) };
}
return resp;
} else {
unsafe {
init();
}
}
None
}
pub fn set_decrypted(key: String, data: String) {
let purging = unsafe { PURGING };
if purging {
return;
}
let decrypted = unsafe { DECRYPTED.as_mut() };
if let None = decrypted {
unsafe {
init();
}
}
decrypted.unwrap().insert(
key,
CacheEntry {
data,
last_accessed: now(),
},
);
}
unsafe fn update_time(key: String, decrypted: bool) {
if decrypted {
let data = DECRYPTED.as_mut().unwrap();
if let Some(x) = data.get_mut(&key) {
x.last_accessed = now();
}
} else {
let data = ENCRYPTED.as_mut().unwrap();
if let Some(x) = data.get_mut(&key) {
x.last_accessed = now();
}
}
}
unsafe fn init() {
ENCRYPTED = Some(HashMap::new());
DECRYPTED = Some(HashMap::new());
thread::spawn(|| loop {
PURGING = true;
let rn = now();
let encrypted = ENCRYPTED.as_ref().unwrap();
let encrypted_mut = ENCRYPTED.as_mut().unwrap();
encrypted.iter().for_each(|x| {
let should_delete = rn - x.1.last_accessed > 5 * 60;
if should_delete {
encrypted_mut.remove(x.0);
}
});
let decrypted = DECRYPTED.as_ref().unwrap();
let decrypted_mut = DECRYPTED.as_mut().unwrap();
decrypted.iter().for_each(|x| {
let should_delete = rn - x.1.last_accessed > 5 * 60;
if should_delete {
decrypted_mut.remove(x.0);
}
});
PURGING = false;
thread::sleep(Duration::from_secs(120));
});
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/authentication.rs | src-service/src/authentication.rs | use crate::utils::*;
use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, Users};
#[cfg(windows)]
pub fn is_current_logged_in_user(pid: usize) -> bool {
use windows::{
core::PWSTR,
Win32::System::RemoteDesktop::{
WTSGetActiveConsoleSessionId, WTSQuerySessionInformationW, WTSUserName,
WTS_CURRENT_SERVER_HANDLE,
},
};
let mut system = System::new();
let mut users = Users::new();
users.refresh();
system.refresh_processes_specifics(
ProcessesToUpdate::Some(&[Pid::from(pid)]),
true,
ProcessRefreshKind::everything(),
);
(|| unsafe {
let process = system.process(Pid::from(pid))?;
let user = users.get_user_by_id(process.user_id()?)?.name();
let sessionid = WTSGetActiveConsoleSessionId();
let mut user_name: PWSTR = PWSTR::null();
let mut user_name_len: u32 = 0;
WTSQuerySessionInformationW(
WTS_CURRENT_SERVER_HANDLE,
sessionid,
WTSUserName,
&mut user_name as *mut _ as _,
&mut user_name_len as *mut _,
)
.unwrap();
let user_name = user_name.to_string().unwrap();
if user == user_name {
return Some(true);
}
Some(false)
})()
.unwrap_or(false)
}
pub fn authenticate_process(pid: usize, time: bool) -> (bool, bool, String) {
#[cfg(all(not(debug_assertions), windows))]
let exe = [format!(
r"{}\Program Files\AHQ Store\ahq-store-app.exe",
get_main_drive()
)];
#[cfg(all(not(debug_assertions), unix))]
let exe = [
format!("/bin/ahq-store-app"),
format!("/usr/bin/ahq-store-app"),
];
#[cfg(debug_assertions)]
let exe: [String; 0] = [];
let mut system = System::new();
let mut users = Users::new();
users.refresh();
system.refresh_processes_specifics(
ProcessesToUpdate::Some(&[Pid::from(pid)]),
true,
ProcessRefreshKind::everything(),
);
let process = system.process(Pid::from(pid));
if let Some(process) = process {
let (admin, user) = (|| {
let user = users.get_user_by_id(process.user_id()?)?;
let groups = user.groups();
let user = user.name().to_string();
#[cfg(windows)]
let admin = "Administrators";
#[cfg(unix)]
let admin = "sudo";
return Some(
(groups.iter().find(|x| x.name() == admin).is_some(), user)
);
})()
.unwrap_or((false, "".into()));
let Some(ex) = process.exe() else {
return (false, false, "".into());
};
let exe_path = ex.to_string_lossy();
let exe_path = exe_path.to_string();
#[cfg(feature = "no_auth")]
return (true, admin, user);
let running_for_secs = now() - process.start_time();
if exe.contains(&exe_path) {
if time && running_for_secs > 20 {
return (false, admin, user);
}
return (true, admin, user);
}
}
(false, false, "".into())
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/main.rs | src-service/src/main.rs | #![allow(static_mut_refs)]
#![feature(async_closure)]
#[cfg(windows)]
use std::time::Duration;
#[cfg(windows)]
use std::sync::{Arc, Mutex};
#[cfg(windows)]
use windows_service::{
define_windows_service,
service::*,
service_control_handler::{self, ServiceControlHandlerResult, ServiceStatusHandle},
service_dispatcher, Result as SResult,
};
use ipc::launch;
#[allow(unused)]
use utils::{delete_log, write_log, write_service};
use self::handlers::init;
pub mod authentication;
mod encryption;
mod ipc;
mod utils;
pub mod handlers;
// #[cfg(unix)]
// type SResult<T> = Result<T, ()>;
#[cfg(unix)]
#[tokio::main]
pub async fn main() {
start().await;
}
async fn start() {
delete_log();
write_log("WIN NT: Selecting PORT");
write_log("WIN NT: STARTING");
init();
launch().await;
}
#[cfg(windows)]
define_windows_service!(ffi_service_main, service_runner);
#[cfg(windows)]
pub fn main() -> SResult<()> {
#[cfg(windows)]
#[cfg(not(feature = "no_service"))]
service_dispatcher::start("AHQ Store Service", ffi_service_main)?;
#[cfg(any(all(feature = "no_service", windows), target_os = "linux"))]
service_runner("");
Ok(())
}
#[cfg(windows)]
fn service_runner<T>(_: T) {
#[cfg(debug_assertions)]
use encryption::encrypt2;
#[cfg(all(windows, not(feature = "no_service")))]
{
let handler: Arc<Mutex<Option<ServiceStatusHandle>>> = Arc::new(Mutex::new(None));
let status_handle = handler.clone();
let event_handler = move |control_event| -> ServiceControlHandlerResult {
match control_event {
ServiceControl::Stop => {
write_service(-1);
// Handle stop event and return control back to the system.
status_handle
.lock()
.unwrap()
.unwrap()
.set_service_status(ServiceStatus {
service_type: ServiceType::OWN_PROCESS,
current_state: ServiceState::Stopped,
controls_accepted: ServiceControlAccept::STOP,
exit_code: ServiceExitCode::Win32(0),
checkpoint: 0,
wait_hint: Duration::default(),
process_id: Some(std::process::id()),
})
.unwrap();
ServiceControlHandlerResult::NoError
}
// All services must accept Interrogate even if it's a no-op.
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
_ => ServiceControlHandlerResult::NotImplemented,
}
};
let handle_clone = handler.clone();
// Register system service event handler
let status_handle = service_control_handler::register("AHQ Store Service", event_handler)
.expect("This should work");
match handle_clone.lock() {
Ok(mut handle) => {
*handle = Some(status_handle.clone());
}
_ => {}
}
status_handle
.set_service_status(ServiceStatus {
service_type: ServiceType::OWN_PROCESS,
current_state: ServiceState::Running,
controls_accepted: ServiceControlAccept::STOP,
exit_code: ServiceExitCode::Win32(0),
checkpoint: 0,
wait_hint: Duration::default(),
process_id: Some(std::process::id()),
})
.unwrap();
}
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap()
.block_on(async {
#[cfg(debug_assertions)]
{
let vect = encrypt2("%Qzn835y37z%%^&*&^%&^%^&%^".into()).unwrap();
println!("{:?}", vect);
}
start().await;
});
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/encryption/mod.rs | src-service/src/encryption/mod.rs | mod cache;
use lazy_static::lazy_static;
use chacha20poly1305::{
aead::{generic_array::GenericArray, Aead, KeyInit},
ChaCha20Poly1305,
};
use serde_json::from_str;
use cache::*;
lazy_static! {
static ref CRYPTER: ChaCha20Poly1305 = {
let key = GenericArray::from_slice(include!("../encrypt").as_bytes());
ChaCha20Poly1305::new(&key)
};
static ref CRYPTER2: ChaCha20Poly1305 = {
let key = GenericArray::from_slice(include!("../encrypt_2").as_bytes());
ChaCha20Poly1305::new(&key)
};
}
pub fn encrypt_vec(data: String) -> Option<Vec<u8>> {
let nonce = GenericArray::from_slice(b"SSSSSSSSSSSS");
if let Ok(dat) = CRYPTER.encrypt(nonce, data.as_bytes()) {
return Some(dat);
}
None
}
pub fn encrypt2(data: String) -> Option<Vec<u8>> {
let nonce = GenericArray::from_slice(b"SSSSSSSSSSSS");
CRYPTER2.encrypt(nonce, data.as_bytes()).ok()
}
pub fn _decrypt(data: String) -> Option<String> {
let nonce = GenericArray::from_slice(b"SSSSSSSSSSSS");
if let Some(x) = get_decrypted(data.clone()) {
return Some(x);
} else if let Ok(x) = from_str::<Vec<u8>>(&data) {
if let Ok(dat) = CRYPTER.decrypt(nonce, x.as_slice()) {
if let Ok(dat) = String::from_utf8(dat) {
set_decrypted(data, dat.clone());
return Some(dat);
}
}
}
None
}
pub fn decrypt2(data: Vec<u8>) -> Option<String> {
let nonce = GenericArray::from_slice(b"SSSSSSSSSSSS");
if let Ok(dat) = CRYPTER2.decrypt(nonce, data.as_slice()) {
return String::from_utf8(dat).ok();
}
None
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/encryption/cache.rs | src-service/src/encryption/cache.rs | #![allow(dead_code)]
use std::collections::HashMap;
use std::thread;
use std::time::Duration;
use crate::utils::now;
struct CacheEntry {
pub data: String,
pub last_accessed: u64,
}
static mut PURGING: bool = false;
static mut ENCRYPTED: Option<HashMap<String, CacheEntry>> = None;
static mut DECRYPTED: Option<HashMap<String, CacheEntry>> = None;
pub fn get_encrypted(key: String) -> Option<String> {
let purging = unsafe { PURGING };
if purging {
return None;
}
let encrypted = unsafe { ENCRYPTED.as_ref() };
if let Some(encrypted) = encrypted {
let resp = encrypted.get(&key).map(|e| e.data.clone());
if let &Some(_) = &resp {
unsafe { update_time(key, false) };
}
return resp;
} else {
unsafe {
init();
}
}
None
}
pub fn set_encrypted(key: String, data: String) {
let purging = unsafe { PURGING };
if purging {
return;
}
let encrypted = unsafe { ENCRYPTED.as_mut() };
if let None = encrypted {
unsafe {
init();
}
}
encrypted.unwrap().insert(
key,
CacheEntry {
data,
last_accessed: now(),
},
);
}
pub fn get_decrypted(key: String) -> Option<String> {
let purging = unsafe { PURGING };
if purging {
return None;
}
let decrypted = unsafe { DECRYPTED.as_ref() };
if let Some(decrypted) = decrypted {
let resp = decrypted.get(&key).map(|e| e.data.clone());
if let &Some(_) = &resp {
unsafe { update_time(key, true) };
}
return resp;
} else {
unsafe {
init();
}
}
None
}
pub fn set_decrypted(key: String, data: String) {
let purging = unsafe { PURGING };
if purging {
return;
}
let decrypted = unsafe { DECRYPTED.as_mut() };
if let None = decrypted {
unsafe {
init();
}
}
decrypted.unwrap().insert(
key,
CacheEntry {
data,
last_accessed: now(),
},
);
}
unsafe fn update_time(key: String, decrypted: bool) {
let encrypted = if decrypted {
DECRYPTED.as_mut().unwrap()
} else {
ENCRYPTED.as_mut().unwrap()
};
if let Some(x) = encrypted.get_mut(&key) {
x.last_accessed = now();
}
}
unsafe fn init() {
ENCRYPTED = Some(HashMap::new());
DECRYPTED = Some(HashMap::new());
thread::spawn(|| loop {
PURGING = true;
let rn = now();
let encrypted = ENCRYPTED.as_ref().unwrap();
let encrypted_mut = ENCRYPTED.as_mut().unwrap();
encrypted.iter().for_each(|x| {
let should_delete = rn - x.1.last_accessed > 5 * 60;
if should_delete {
encrypted_mut.remove(x.0);
}
});
let decrypted = DECRYPTED.as_ref().unwrap();
let decrypted_mut = DECRYPTED.as_mut().unwrap();
decrypted.iter().for_each(|x| {
let should_delete = rn - x.1.last_accessed > 5 * 60;
if should_delete {
decrypted_mut.remove(x.0);
}
});
PURGING = false;
thread::sleep(Duration::from_secs(120));
});
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/ipc/win32.rs | src-service/src/ipc/win32.rs | use std::{
ffi::{c_void, OsStr}, io::ErrorKind, os::windows::io::AsRawHandle, ptr, time::Duration
};
use tokio::net::windows::named_pipe::{PipeMode, ServerOptions};
use windows::Win32::{
Foundation::HANDLE,
Security::{
InitializeSecurityDescriptor, SetSecurityDescriptorDacl, PSECURITY_DESCRIPTOR,
SECURITY_ATTRIBUTES, SECURITY_DESCRIPTOR,
},
System::Pipes::GetNamedPipeClientProcessId,
System::SystemServices::SECURITY_DESCRIPTOR_REVISION,
};
use crate::{
authentication::*,
handlers::{get_prefs, handle_msg, GET_INSTALL_DAEMON},
utils::{get_iprocess, set_iprocess, set_perms, structs::{rem_current_user, set_current_user}, write_log, ws_send},
};
use ahqstore_types::{Command, Prefs};
pub async fn launch() {
write_log("Starting");
let _ = GET_INSTALL_DAEMON.send(Command::GetSha(0));
let mut obj = SECURITY_DESCRIPTOR::default();
// make it have full rights over the named pipe
unsafe {
InitializeSecurityDescriptor(
PSECURITY_DESCRIPTOR(&mut obj as *mut _ as *mut c_void),
SECURITY_DESCRIPTOR_REVISION,
)
.unwrap();
SetSecurityDescriptorDacl(
PSECURITY_DESCRIPTOR(&mut obj as *mut _ as *mut c_void),
true,
Some(ptr::null()),
false,
)
.unwrap();
}
let mut attr = SECURITY_ATTRIBUTES::default();
attr.lpSecurityDescriptor = &mut obj as *mut _ as *mut c_void;
let pipe = unsafe {
ServerOptions::new()
.first_pipe_instance(true)
.reject_remote_clients(true)
.pipe_mode(PipeMode::Message)
.create_with_security_attributes_raw(
OsStr::new(r"\\.\pipe\ahqstore-service-api-v3"),
&mut attr as *mut _ as *mut c_void,
)
.unwrap()
};
set_iprocess(pipe);
write_log("Started");
let mut pipe = get_iprocess().unwrap();
loop {
write_log("Loop");
rem_current_user();
if let Ok(()) = pipe.connect().await {
println!("Connected");
let handle = pipe.as_raw_handle();
let mut process_id = 0u32;
unsafe {
let handle = HANDLE(handle);
let _ = GetNamedPipeClientProcessId(handle, &mut process_id as *mut _);
}
let (auth, admin, user) = authenticate_process(process_id as usize, true);
if !auth {
println!("Unauthenticated");
let _ = pipe.disconnect();
} else {
set_current_user(user);
set_perms((|| {
if admin {
return (true, true, true);
}
let Prefs {
launch_app,
install_apps,
..
} = get_prefs();
(admin, launch_app, install_apps)
})());
let mut ext: u8 = 0;
'a: loop {
let mut val: [u8; 8] = [0u8; 8];
//let mut buf: Box<[u8]>;
ext += 1;
if ext >= 200 {
ext = 0;
let (auth, _, _) = authenticate_process(process_id as usize, false);
if !auth {
let _ = pipe.disconnect();
break 'a;
}
if !is_current_logged_in_user(process_id as usize) {
ws_send(&mut pipe, b"kill()").await;
let _ = pipe.disconnect();
break 'a;
}
}
match pipe.try_read(&mut val) {
Ok(0) => {}
Ok(_) => {
let total = usize::from_be_bytes(val);
let mut buf: Vec<u8> = Vec::new();
let mut byte = [0u8];
for _ in 0..total {
match pipe.try_read(&mut byte) {
Ok(_) => {
buf.push(byte[0]);
}
Err(e) => match e.kind() {
ErrorKind::WouldBlock => {}
e => {
let err = format!("{e:?}");
write_log(&err);
if &err != "Uncategorized" {
let _ = pipe.disconnect();
break 'a;
}
}
},
}
}
handle_msg(admin, String::from_utf8_lossy(&buf).to_string());
}
Err(e) => match e.kind() {
ErrorKind::WouldBlock => {}
e => {
let err = format!("{e:?}");
println!("{}", &err);
write_log(&err);
if &err != "Uncategorized" {
let _ = pipe.disconnect();
break 'a;
}
}
},
}
tokio::time::sleep(Duration::from_nanos(10)).await;
}
}
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/ipc/linux.rs | src-service/src/ipc/linux.rs | use std::time::Duration;
use std::{fs, io::ErrorKind};
use tokio::{io::AsyncWriteExt, net::UnixListener};
use crate::{
authentication::authenticate_process,
handlers::{get_prefs, handle_msg, GET_INSTALL_DAEMON},
utils::structs::{rem_current_user, set_current_user},
utils::{chmod, get_iprocess, set_iprocess, set_perms, write_log},
};
use ahqstore_types::{Command, Prefs};
pub async fn launch() {
let _ = GET_INSTALL_DAEMON.send(Command::GetSha(0));
println!("STARTING UP");
[
"/ahqstore",
"/ahqstore/Installers",
"/ahqstore/Programs",
"/ahqstore/Updaters",
]
.iter()
.for_each(|x| {
let _ = fs::create_dir_all(x);
});
chmod("655", "/ahqstore/").unwrap();
let _ = fs::remove_file("/ahqstore/socket");
let socket = UnixListener::bind("/ahqstore/socket").unwrap();
chmod("777", "/ahqstore/socket").unwrap();
loop {
rem_current_user();
if let Ok((stream, _)) = socket.accept().await {
println!("Got Stream");
set_iprocess(stream);
let pipe = get_iprocess().unwrap();
let Ok(cred) = pipe.peer_cred() else {
println!("Err 0x1");
let _ = pipe.shutdown().await;
continue;
};
let Some(pid) = cred.pid() else {
println!("Err 0x2");
let _ = pipe.shutdown().await;
continue;
};
if pid <= 0 {
println!("Err 0x3");
let _ = pipe.shutdown().await;
continue;
}
let (auth, sudoer, user) = authenticate_process(pid as usize, true);
if !auth {
println!("FAILED CHECK");
let _ = pipe.shutdown().await;
println!("DISCONNECT");
continue;
}
set_current_user(user);
set_perms((|| {
if sudoer {
return (true, true, true);
}
let Prefs {
launch_app,
install_apps,
..
} = get_prefs();
(sudoer, launch_app, install_apps)
})());
let mut ext: u8 = 0;
'a: loop {
ext += 1;
if ext > 20 {
ext = 0;
if !authenticate_process(pid as usize, false).0 {
let _ = pipe.shutdown().await;
println!("DISCONNECT");
break 'a;
}
}
let mut val: [u8; 8] = [0u8; 8];
match pipe.try_read(&mut val) {
Ok(0) => {}
Ok(_) => {
let total = usize::from_be_bytes(val);
let mut buf: Vec<u8> = Vec::new();
let mut byte = [0u8];
println!("total: {total}");
for _ in 0..total {
match pipe.try_read(&mut byte) {
Ok(_) => {
buf.push(byte[0]);
}
Err(e) => match e.kind() {
ErrorKind::WouldBlock => {}
e => {
let err = format!("{e:?}");
write_log(&err);
if &err != "Uncategorized" {
let _ = pipe.shutdown().await;
break 'a;
}
}
},
}
}
let msg = String::from_utf8_lossy(&buf).to_string();
println!("Handling MSG");
println!("{msg:?}");
handle_msg(sudoer, msg);
}
Err(e) => match e.kind() {
ErrorKind::WouldBlock => {}
e => {
let err = format!("{e:?}");
println!("{}", &err);
write_log(&err);
if &err != "Uncategorized" {
let _ = pipe.shutdown().await;
break 'a;
}
}
},
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
} else {
println!("socket.accept failed...");
}
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/ipc/mod.rs | src-service/src/ipc/mod.rs | #[cfg(windows)]
mod win32;
#[cfg(windows)]
pub use win32::launch;
#[cfg(unix)]
mod linux;
#[cfg(unix)]
pub use linux::launch;
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/utils/db.rs | src-service/src/utils/db.rs | #[cfg(windows)]
use tokio::net::windows::named_pipe::NamedPipeServer;
#[cfg(unix)]
use tokio::net::UnixStream;
#[cfg(windows)]
pub type ServiceIpc = NamedPipeServer;
#[cfg(unix)]
pub type ServiceIpc = UnixStream;
static mut IPC: Option<ServiceIpc> = None;
static mut PREFS: (bool, bool, bool) = (false, false, false);
pub fn set_iprocess(ipc: ServiceIpc) {
unsafe {
IPC = Some(ipc);
}
}
pub fn get_iprocess() -> Option<&'static mut ServiceIpc> {
unsafe { IPC.as_mut() }
}
pub fn set_perms(perms: (bool, bool, bool)) {
unsafe { PREFS = perms }
}
pub fn get_perms() -> (bool, bool, bool) {
unsafe { PREFS }
}
pub async fn ws_send(ipc: &mut &'static mut ServiceIpc, val: &[u8]) {
let len = val.len().to_be_bytes();
let mut data = len.to_vec();
for byte in val {
data.push(*byte);
}
let _ = ipc.try_write(&data);
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/utils/log_file.rs | src-service/src/utils/log_file.rs | use std::{fmt::Display, fs};
use crate::encryption;
#[allow(unused)]
use super::{get_main_drive, now};
fn get_service_file() -> String {
#[cfg(windows)]
return format!(
"{}\\ProgramData\\AHQ Store Applications\\service.encrypted.txt",
&get_main_drive()
);
#[cfg(unix)]
return format!("/ahqstore/service.encrypted.txt");
}
fn get_log_file() -> String {
#[cfg(windows)]
return format!(
"{}\\ProgramData\\AHQ Store Applications\\server.log.txt",
&get_main_drive()
);
#[cfg(unix)]
return format!("/ahqstore/server.log.txt");
}
fn get_old_log_file() -> String {
#[cfg(windows)]
return format!(
"{}\\ProgramData\\AHQ Store Applications\\server.old.log.txt",
&get_main_drive()
);
#[cfg(unix)]
return format!("/ahqstore/server.old.log.txt");
}
pub fn write_service<T>(status: T) -> Option<()>
where
T: ToString,
{
let file = get_service_file();
let data = encryption::encrypt_vec(status.to_string())?;
fs::write(file, data).ok()
}
pub fn write_log<T>(status: T) -> Option<()>
where
T: Display,
{
let file_path = get_log_file();
let mut file =
fs::read_to_string(&file_path).unwrap_or("----------- SERVER LOG -----------".into());
file.push_str(&format!("\n{}: {}", now(), status));
fs::write(file_path, file).ok()
}
pub fn delete_log() -> Option<()> {
let file_path = get_log_file();
let old_file_path = get_old_log_file();
write_service("STOPPED");
fs::copy(&file_path, &old_file_path).ok();
fs::remove_file(file_path).ok()
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/utils/structs.rs | src-service/src/utils/structs.rs | pub use ahqstore_types::*;
static mut CURRENT_USER: Option<String> = None;
pub fn set_current_user(user: String) {
unsafe {
CURRENT_USER = Some(user);
}
}
pub fn rem_current_user() {
unsafe {
CURRENT_USER = None;
}
}
pub fn get_current_user() -> Option<&'static str> {
unsafe { CURRENT_USER.as_ref().map(|x| x.as_str()) }
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/utils/mod.rs | src-service/src/utils/mod.rs | #![allow(unused)]
use std::time::{SystemTime, UNIX_EPOCH};
mod db;
mod log_file;
use ahqstore_types::AHQStoreApplication;
pub use db::*;
pub use log_file::*;
pub mod structs;
pub fn get_program_folder(app_id: &str) -> String {
#[cfg(windows)]
return format!(
"{}\\ProgramData\\AHQ Store Applications\\Programs\\{}",
&get_main_drive(),
&app_id
);
#[cfg(unix)]
return format!("/ahqstore/Programs/{}", &app_id);
}
pub fn get_programs() -> String {
#[cfg(windows)]
return format!(
"{}\\ProgramData\\AHQ Store Applications\\Programs",
&get_main_drive()
);
#[cfg(unix)]
return format!("/ahqstore/Programs");
}
pub fn get_installer_file(app: &AHQStoreApplication) -> String {
#[cfg(windows)]
return format!(
"{}\\ProgramData\\AHQ Store Applications\\Installers\\{}{}",
&get_main_drive(),
&app.appId,
&app.get_win_extension().unwrap_or(".unknown")
);
#[cfg(unix)]
return format!(
"/ahqstore/Installers/{}{}",
&app.appId,
&app.get_linux_extension().unwrap_or(".unknown")
);
}
pub fn get_custom_file(app: &AHQStoreApplication, extension: &str) -> String {
#[cfg(windows)]
return format!(
"{}\\ProgramData\\AHQ Store Applications\\Installers\\{}.{}",
&get_main_drive(),
&app.appId,
&extension
);
#[cfg(unix)]
return format!("/ahqstore/Installers/{}.{}", &app.appId, &extension);
}
pub fn get_file_on_root(file: &str) -> String {
#[cfg(windows)]
return format!(
"{}\\ProgramData\\AHQ Store Applications\\{}",
&get_main_drive(),
&file
);
#[cfg(unix)]
return format!("/ahqstore/{file}");
}
pub fn get_target_lnk(name: &str) -> String {
#[cfg(windows)]
return format!(
"{}\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\AHQ Store\\{}.lnk",
&get_main_drive(),
&name
);
#[cfg(unix)]
return format!("/usr/share/applications/{}.desktop", &name);
}
pub fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
pub fn get_main_drive() -> String {
std::env::var("SystemDrive")
.unwrap_or("C:".into())
.to_string()
}
#[cfg(unix)]
pub fn chmod(typ: &str, regex: &str) -> Option<bool> {
use std::process::Command;
Command::new("chmod")
.args([typ, regex])
.spawn()
.ok()?
.wait()
.ok()?
.success()
.into()
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/mod.rs | src-service/src/handlers/mod.rs | #![allow(unused)]
use ahqstore_types::UpdateStatusReport;
use lazy_static::lazy_static;
use std::sync::mpsc::Sender;
#[allow(unused)]
use tokio::{io::AsyncWriteExt, spawn};
use crate::{
utils::{
get_iprocess, get_perms,
structs::{get_current_user, Command, ErrorType, Reason, Response},
},
write_log,
};
use self::daemon::{lib_msg, UPDATE_STATUS_REPORT};
use self::service::*;
mod daemon;
mod service;
pub use service::get_prefs;
pub use self::service::init;
lazy_static! {
pub static ref GET_INSTALL_DAEMON: Sender<Command> = daemon::get_install_daemon();
}
use super::utils::ws_send;
pub fn handle_msg(admin: bool, data: String) {
let (admin, launch, install) = get_perms();
spawn(async move {
if let Some(mut ws) = get_iprocess() {
if let Some(x) = Command::try_from(&data) {
match (admin, launch, install, x) {
(_, _, _, Command::GetSha(ref_id)) => unsafe {
let val = if let Some(x) = COMMIT_ID.as_ref() {
Response::as_msg(Response::SHAId(ref_id, x.clone()))
} else {
Response::as_msg(Response::Error(ErrorType::GetSHAFailed(ref_id)))
};
ws_send(&mut ws, &val).await;
send_term(ref_id).await;
},
(_, _, _, Command::GetApp(ref_id, app_id)) => {
let _ = GET_INSTALL_DAEMON.send(Command::GetApp(ref_id, app_id));
}
(_, true, true, Command::InstallApp(ref_id, app_id)) => {
let _ = GET_INSTALL_DAEMON.send(Command::InstallApp(ref_id, app_id));
}
(_, true, true, Command::UninstallApp(ref_id, app_id)) => {
let msg = Response::as_msg(Response::Acknowledged(ref_id));
ws_send(&mut ws, &msg).await;
let _ = GET_INSTALL_DAEMON.send(Command::UninstallApp(ref_id, app_id));
send_term(ref_id).await;
}
(_, _, _, Command::ListApps(ref_id)) => {
#[allow(unused)]
if let Some(mut x) = list_apps() {
let user = get_current_user().unwrap_or("");
#[cfg(windows)]
if let Some(mut a) = list_user_apps(Some(user.into())) {
let (_, mut data) = a.remove(0);
drop(a);
x.extend(data);
}
let val = Response::as_msg(Response::ListApps(ref_id, x));
ws_send(&mut ws, &val).await;
}
send_term(ref_id).await;
}
(_, _, _, Command::GetPrefs(ref_id)) => {
let val = Response::as_msg(Response::Prefs(ref_id, get_prefs()));
ws_send(&mut ws, &val).await;
send_term(ref_id).await;
}
(true, _, _, Command::SetPrefs(ref_id, prefs)) => {
let val = if let Some(_) = set_prefs(prefs) {
Response::as_msg(Response::PrefsSet(ref_id))
} else {
Response::as_msg(Response::Error(ErrorType::PrefsError(ref_id)))
};
ws_send(&mut ws, &val).await;
send_term(ref_id).await;
}
(_, true, _, Command::RunUpdate(ref_id)) => {
let _ = GET_INSTALL_DAEMON.send(Command::RunUpdate(ref_id));
}
(_, true, _, Command::UpdateStatus(ref_id)) => {
let _ = ws_send(
&mut ws,
&Response::as_msg(Response::UpdateStatus(ref_id, unsafe {
UPDATE_STATUS_REPORT
.as_ref()
.unwrap_or(&UpdateStatusReport::Checking)
.clone()
})),
)
.await;
send_term(ref_id).await;
}
(_, true, _, Command::GetLibrary(ref_id)) => {
ws_send(&mut ws, &lib_msg()).await;
send_term(ref_id).await;
}
(_, true, true, Command::AddPkg(ref_id, _pkg)) => {
send_term(ref_id).await;
}
_ => {
let x = Response::as_msg(Response::Error(ErrorType::PrefsError(255)));
ws_send(&mut ws, &x).await;
}
}
} else {
let x = Response::as_msg(Response::Disconnect(Reason::UnknownData(0)));
ws_send(&mut ws, &x).await;
#[cfg(windows)]
let _ = ws.disconnect();
#[cfg(unix)]
let _ = ws.shutdown().await;
}
} else {
write_log("STOPPING: Critical Error!");
panic!("Critical Error!");
}
});
}
pub async fn send_term(ref_id: u64) {
if let Some(mut ws) = get_iprocess() {
let x = Response::as_msg(Response::TerminateBlock(ref_id));
ws_send(&mut ws, &x).await;
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/http.rs | src-service/src/handlers/service/http.rs | use ahqstore_types::{
internet::{get_all_commits as t_get_commit, get_app as t_get_app},
AppStatus, Commit, Commits, Library,
};
use lazy_static::lazy_static;
use reqwest::{Client, ClientBuilder, Request, StatusCode};
use serde_json::from_str;
use std::{
fs::{self, File},
io::Write,
};
use crate::utils::get_program_folder;
#[allow(unused)]
use crate::{
handlers::daemon::lib_msg,
utils::{
get_file_on_root, get_installer_file, get_iprocess,
structs::{AHQStoreApplication, AppId, ErrorType, RefId, Response},
ws_send,
},
};
use std::time::Duration;
#[cfg(debug_assertions)]
use crate::utils::write_log;
#[cfg(windows)]
use super::unzip;
pub static mut COMMIT_ID: Option<Commits> = None;
lazy_static! {
static ref DOWNLOADER: Client = ClientBuilder::new()
.user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36")
.build()
.unwrap();
static ref NODE21: &'static str = "https://nodejs.org/dist/v21.4.0/node-v21.4.0-win-x64.zip";
static ref NODE20: &'static str = "https://nodejs.org/dist/v20.10.0/node-v20.10.0-win-x64.zip";
}
pub fn init() {
tokio::spawn(async {
get_commit().await;
});
}
pub async fn get_commit() -> u8 {
if let Some(x) = t_get_commit(None).await.ok() {
unsafe {
COMMIT_ID = Some(x);
}
0
} else {
1
}
}
pub async fn download_app(
val: &mut Library,
) -> Option<(AHQStoreApplication, File, reqwest::Response)> {
let app_id = &val.app_id;
let app_id = app_id.to_string();
let app_id = get_app(0, app_id).await;
match app_id {
Response::AppData(_, _, data) => {
let file = get_installer_file(&data);
val.app = Some(data.clone());
val.status = AppStatus::Downloading;
#[cfg(windows)]
let mut resp = DOWNLOADER
.get(&data.get_win32_download()?.url)
.send()
.await
.ok()?;
#[cfg(unix)]
let mut resp = DOWNLOADER
.get(&data.get_linux_download()?.url)
.send()
.await
.ok()?;
#[cfg(debug_assertions)]
write_log("Response Successful");
let _ = fs::remove_file(&file);
let mut file = File::create(&file).ok()?;
#[cfg(debug_assertions)]
write_log("File Successful");
let total = resp.content_length().unwrap_or(0);
val.max = total as u64;
let mut current = 0u64;
let mut last = 0.0f64;
Some((data, file, resp))
}
_ => {
return None;
}
}
}
pub async fn get_app_local(ref_id: RefId, app_id: AppId) -> Response {
let folder = get_program_folder(&app_id);
let Ok(x) = fs::read_to_string(format!("{}/app.json", &folder)) else {
return Response::Error(ErrorType::GetAppFailed(ref_id, app_id));
};
let Ok(x) = from_str(&x) else {
return Response::Error(ErrorType::GetAppFailed(ref_id, app_id));
};
Response::AppData(ref_id, app_id, x)
}
pub async fn get_app(ref_id: RefId, app_id: AppId) -> Response {
let app = t_get_app(unsafe { COMMIT_ID.as_ref().unwrap() }, &app_id).await;
if let Ok(x) = app {
return Response::AppData(ref_id, app_id, x);
}
Response::Error(ErrorType::GetAppFailed(ref_id, app_id))
}
#[cfg(windows)]
async fn write_download(file: &mut File, url: &str) -> Option<()> {
let mut download = DOWNLOADER.get(url).send().await.ok()?;
while let Some(chunk) = download.chunk().await.ok()? {
file.write(&chunk).ok()?;
}
file.flush().ok()
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/mod.rs | src-service/src/handlers/service/mod.rs | use std::{process::Child, thread::JoinHandle};
use tokio::task::JoinHandle as TokioJoinHandle;
mod http;
mod prefs;
pub enum UninstallResult {
Thread(JoinHandle<bool>),
Sync(Option<String>),
}
pub enum InstallResult {
Thread(TokioJoinHandle<Option<()>>),
Child(Child),
}
pub use http::*;
pub use prefs::*;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use windows::*;
#[cfg(unix)]
mod linux;
#[cfg(unix)]
pub use linux::*;
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/prefs.rs | src-service/src/handlers/service/prefs.rs | use std::fs;
use crate::{
encryption::{decrypt2, encrypt2},
utils::get_main_drive,
};
use ahqstore_types::Prefs;
use lazy_static::lazy_static;
lazy_static! {
static ref PREFS: String = format!(
"{}\\ProgramData\\AHQ Store Applications\\perfs.encryped",
get_main_drive()
);
}
pub fn get_prefs() -> Prefs {
get_prefs_inner().unwrap_or(Prefs::default())
}
fn get_prefs_inner() -> Option<Prefs> {
Prefs::str_to(&decrypt2(Prefs::get(&PREFS)?)?)
}
pub fn set_prefs(values: Prefs) -> Option<()> {
let data = values.convert()?;
let encrypted = encrypt2(data)?;
fs::write(PREFS.as_str(), encrypted).ok()
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/linux/mod.rs | src-service/src/handlers/service/linux/mod.rs | use std::{fs, process::Command};
use ahqstore_types::InstallerFormat;
use super::{InstallResult, UninstallResult};
use crate::utils::{
chmod, get_installer_file, get_program_folder, get_programs, get_target_lnk,
structs::{AHQStoreApplication, AppData},
};
pub mod av;
pub async fn install_app<T>(app: &AHQStoreApplication, _update: bool, _: &T) -> Option<InstallResult> {
let file = get_installer_file(app);
let Some(linux) = app.get_linux_download() else {
return None;
};
match linux.installerType {
InstallerFormat::LinuxAppImage => {
deploy_appimg(&file, app);
Some(InstallResult::Child(
Command::new("bash").arg("true").spawn().ok()?,
))
}
_ => None,
}
}
pub fn deploy_appimg(file: &str, app: &AHQStoreApplication) -> Option<()> {
let install_folder = get_program_folder(&app.appId);
let version_file = format!("{}/ahqStoreVersion", &install_folder);
let new_file = format!("{}/app.AppImage", &install_folder);
let _ = fs::remove_dir_all(&install_folder);
fs::create_dir_all(&install_folder).ok()?;
fs::copy(&file, &new_file).ok()?;
fs::remove_file(&file).ok()?;
fs::write(version_file, &app.version).ok()?;
let link = get_target_lnk(&app.appShortcutName.replace(" ", ""));
let contents = format!(
r"[Desktop Entry]
Terminal=false
Type=Application
Name={}
Exec={}
Icon={}",
&app.appShortcutName, &new_file, &new_file
);
fs::write(&link, contents).ok()?;
if !(chmod("a+rx", &link)? && chmod("a+rx", &new_file)?) {
return None;
};
None
}
pub fn uninstall_app(app: &AHQStoreApplication) -> UninstallResult {
let link = get_target_lnk(&app.appShortcutName);
let program = get_program_folder(&app.appId);
let app = app.appId.clone();
UninstallResult::Thread(std::thread::spawn(move || {
let _ = fs::remove_file(&link);
let Ok(_) = fs::remove_dir_all(&program) else {
return false;
};
// Successful
true
}))
}
pub fn list_apps() -> Option<Vec<AppData>> {
let folder = get_programs();
let dirs = fs::read_dir(&folder).ok()?;
let mut vec = vec![];
for dir in dirs {
let dir = dir.ok()?.file_name();
let dir = dir.to_str().unwrap_or("unknown");
let version = fs::read_to_string(format!(
"{}/{}",
&get_program_folder(&dir),
"ahqStoreVersion"
))
.unwrap_or("unknown".into());
vec.push((dir.to_owned(), version));
}
Some(vec)
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/linux/av/update.rs | src-service/src/handlers/service/linux/av/update.rs | pub async fn update_win_defender() -> Option<()> {
Some(())
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/linux/av/mod.rs | src-service/src/handlers/service/linux/av/mod.rs | pub mod scan;
pub mod update;
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/linux/av/scan.rs | src-service/src/handlers/service/linux/av/scan.rs | use std::thread::JoinHandle;
pub type Malicious = bool;
pub fn scan_threaded<T>(_p: &T) -> JoinHandle<Option<Malicious>> {
std::thread::spawn(|| Some(false))
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/mod.rs | src-service/src/handlers/service/windows/mod.rs | pub mod av;
mod exe;
mod msi;
use ahqstore_types::{InstallerFormat, WindowsInstallScope};
use mslnk::ShellLink;
use serde_json::to_string_pretty;
use std::{
fs,
io::Error,
os::windows::process::CommandExt,
process::{Child, Command},
thread::{self, sleep},
time::Duration,
};
use tokio::spawn;
use user::{get_user_program_folder, get_user_programs, install_user_zip};
use crate::utils::{
get_installer_file, get_program_folder, get_programs, get_target_lnk,
structs::{get_current_user, AHQStoreApplication, AppData},
};
use super::{InstallResult, UninstallResult};
pub use exe::pipe;
mod user;
pub fn run(path: &str, args: &[&str]) -> Result<Child, Error> {
Command::new(path)
.creation_flags(0x08000000)
.args(args)
.spawn()
}
pub fn unzip(path: &str, dest: &str) -> Result<Child, Error> {
Command::new("powershell")
.creation_flags(0x08000000)
.args([
"-Command",
&format!("Expand-Archive -Path '{path}' -DestinationPath '{dest}' -Force"),
])
.spawn()
}
pub async fn install_app(
app: &AHQStoreApplication,
update: bool,
user: &str,
) -> Option<InstallResult> {
let file = get_installer_file(app);
let win32 = app.get_win_download()?;
let opt = app.get_win_options()?.scope.as_ref();
let scope = opt.unwrap_or(&WindowsInstallScope::Machine);
match win32.installerType {
InstallerFormat::WindowsZip => match scope {
&WindowsInstallScope::Machine => load_zip(&file, app),
&WindowsInstallScope::User => install_user_zip(&file, app, user),
},
InstallerFormat::WindowsInstallerMsi => install_msi(&file, app),
InstallerFormat::WindowsInstallerExe => {
exe::install(
&file,
app,
update,
matches!(scope, &WindowsInstallScope::User),
user,
)
.await
}
_ => None,
}
}
pub fn install_msi(msi: &str, app: &AHQStoreApplication) -> Option<InstallResult> {
let install_folder = get_program_folder(&app.appId);
fs::create_dir_all(&install_folder).ok()?;
let to_exec_msi = format!("{}\\installer.msi", &install_folder);
fs::copy(&msi, &to_exec_msi).ok()?;
fs::write(
format!("{}\\app.json", &install_folder),
to_string_pretty(&app).ok()?,
)
.ok()?;
fs::write(
format!("{}\\ahqStoreVersion", &install_folder),
&app.version,
)
.ok()?;
fs::remove_file(&msi).ok()?;
Some(InstallResult::Child(
run("msiexec", &["/norestart", "/qn", "/i", &to_exec_msi]).ok()?,
))
}
pub fn load_zip(zip: &str, app: &AHQStoreApplication) -> Option<InstallResult> {
let install_folder = get_program_folder(&app.appId);
let version_file = format!("{}\\ahqStoreVersion", install_folder);
let cmd = unzip(&zip, &install_folder);
let zip = zip.to_string();
let app = app.clone();
Some(InstallResult::Thread(spawn(async move {
use tokio::fs;
let _ = fs::remove_dir_all(&install_folder).await;
fs::create_dir_all(&install_folder).await.ok()?;
sleep(Duration::from_millis(200));
println!("Unzipped");
let cleanup = |err| {
let _ = fs::remove_file(&zip);
if err {
let _ = fs::remove_dir_all(&install_folder);
} else {
if let Some(val) = app.get_win_options() {
if let Some(exec) = &val.exec {
if let Ok(link) = ShellLink::new(format!("{}\\{}", &install_folder, &exec)) {
let _ = link.create_lnk(get_target_lnk(&app.appShortcutName));
}
}
}
}
};
let val = (|| async {
let mut child = cmd.ok()?;
let status = child.wait().ok()?;
if !status.success() {
return None;
}
let _ = fs::write(&version_file, &app.version).await.ok()?;
let _ = fs::write(
format!("{}\\app.json", &install_folder),
to_string_pretty(&app).ok()?,
)
.await
.ok()?;
Some(())
})()
.await;
cleanup(val.is_none());
val
})))
}
pub fn uninstall_app(app: &AHQStoreApplication) -> UninstallResult {
let link = get_target_lnk(&app.appShortcutName);
let program = get_program_folder(&app.appId);
if msi::is_msi(&app.appId) {
UninstallResult::Thread(msi::uninstall_msi(app.appId.clone()))
} else {
UninstallResult::Thread(thread::spawn(move || {
let _ = fs::remove_file(&link);
if !fs::remove_dir_all(&program).is_ok() {
return false;
}
// Successful
true
}))
}
}
pub fn list_apps() -> Option<Vec<AppData>> {
let folder = get_programs();
let dirs = fs::read_dir(&folder).ok()?;
let mut vec = vec![];
for dir in dirs {
let dir = dir.ok()?.file_name();
let dir = dir.to_str().unwrap_or("unknown");
let version = fs::read_to_string(format!(
"{}\\{}",
&get_program_folder(&dir),
"ahqStoreVersion"
))
.unwrap_or("unknown".into());
if version == "unknown" {
let _ = fs::remove_dir_all(get_program_folder(&dir));
} else if version != "custom" {
if msi::is_msi(dir) {
if msi::exists(dir).unwrap_or(false) {
vec.push((dir.to_owned(), version));
}
} else {
vec.push((dir.to_owned(), version));
}
}
}
Some(vec)
}
pub fn list_user_apps(user: Option<String>) -> Option<Vec<(String, Vec<AppData>)>> {
let Some(user) = user else {
let mut result: Vec<(String, Vec<AppData>)> = vec![];
for x in fs::read_dir("C:\\Users").ok()? {
let x = x.ok()?;
let file = x.file_name().into_string().ok()?;
if let Some(mut data) = list_user_apps(Some(file)) {
result.push(data.remove(0));
}
}
return Some(result);
};
let folder = get_user_programs(&user);
let dirs = fs::read_dir(&folder).ok()?;
let mut vec = vec![];
for dir in dirs {
let dir = dir.ok()?.file_name();
let dir = dir.to_str().unwrap_or("unknown");
let version = fs::read_to_string(format!(
"{}\\{}",
&get_user_program_folder(&dir, &user),
"ahqStoreVersion"
))
.unwrap_or("unknown".into());
if version == "unknown" {
let _ = fs::remove_dir_all(get_user_program_folder(&dir, &user));
} else if version != "custom" {
if msi::is_msi(dir) {
if msi::exists(dir).unwrap_or(false) {
vec.push((dir.to_owned(), version));
}
} else {
vec.push((dir.to_owned(), version));
}
}
}
Some(vec![(user, vec)])
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/user/mod.rs | src-service/src/handlers/service/windows/user/mod.rs | mod zip;
pub use zip::*;
use crate::utils::get_main_drive;
pub(super) fn get_user_program_folder(app_id: &str, user: &str) -> String {
format!(
"{}\\Users\\{}\\AHQ Store Applications\\Programs\\{}",
&get_main_drive(),
user,
app_id,
)
}
pub(super) fn get_user_programs(user: &str) -> String {
format!(
"{}\\Users\\{}\\AHQ Store Applications\\Programs\\",
&get_main_drive(),
user,
)
} | rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/user/zip.rs | src-service/src/handlers/service/windows/user/zip.rs | use ahqstore_types::AHQStoreApplication;
use crate::handlers::InstallResult;
pub fn install_user_zip(zip: &str, app: &AHQStoreApplication, user: &str) -> Option<InstallResult> {
None
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/msi/mod.rs | src-service/src/handlers/service/windows/msi/mod.rs | use msi::{open, Select};
use winreg::{enums::HKEY_LOCAL_MACHINE, RegKey};
use std::{
fs::{self, File},
thread::{self, JoinHandle},
};
use crate::utils::get_program_folder;
use super::run;
fn msi_from_id(app_id: &str) -> String {
let dir = get_program_folder(app_id);
format!("{dir}/installer.msi")
}
pub fn is_msi(app_id: &str) -> bool {
fs::metadata(msi_from_id(app_id)).is_ok()
}
fn get_product_code(msi: &mut msi::Package<File>) -> Option<String> {
let mut property = msi.select_rows(Select::table("Property")).ok()?;
property.find(|x| &x[0].as_str() == &Some("ProductCode"))?[1]
.as_str()
.map_or_else(|| None, |x| Some(x.into()))
}
pub fn exists(app_id: &str) -> Option<bool> {
let msi = msi_from_id(app_id);
let mut msi = open(msi).ok()?;
let product_code = get_product_code(&mut msi)?;
let reg = RegKey::predef(HKEY_LOCAL_MACHINE);
reg
.open_subkey(&format!(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{}",
&product_code
))
.ok()?;
Some(true)
}
pub fn uninstall_msi(app_id: String) -> JoinHandle<bool> {
thread::spawn(move || {
let program = get_program_folder(&app_id);
let msi = msi_from_id(&app_id);
if exists(&app_id).unwrap_or(false) {
let succ = (|| -> Option<bool> {
Some(
run("msiexec", &["/passive", "/qn", "/x", &msi])
.ok()?
.wait()
.ok()?
.success(),
)
})()
.unwrap_or(false);
return match succ {
true => {
let Some(_) = fs::remove_dir_all(&program).ok() else {
return false;
};
true
}
_ => false,
};
}
false
})
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/exe/mod.rs | src-service/src/handlers/service/windows/exe/mod.rs | use std::fs;
use ahqstore_types::{AHQStoreApplication, RefId, Response};
use daemon::get_handles;
use pipe::{get_exe_process_handle, CONNECTED};
use serde_json::{json, to_string_pretty};
use tokio::{spawn, sync::oneshot, task::JoinHandle};
use crate::{
handlers::InstallResult,
utils::{get_custom_file, get_program_folder, now, ws_send},
};
static mut COUNTER: RefId = 0;
mod daemon;
pub mod pipe;
pub async fn install(
path: &str,
app: &AHQStoreApplication,
update: bool,
_user: bool,
_username: &str,
) -> Option<InstallResult> {
if unsafe { !CONNECTED } {
return None;
}
unsafe {
COUNTER += 1;
};
let icon_path = get_custom_file(app, "png");
let icon = app.get_resource(0).await?;
fs::write(&icon_path, icon);
let count = unsafe { COUNTER };
let mut resp = vec![0];
if update {
resp.push(1);
} else {
resp.push(0);
}
let windows_options = app.get_win_options()?;
let args = windows_options
.installerArgs
.as_ref()
.map_or_else(|| vec![], |x| x.iter().map(|x| x.as_str()).collect());
let data = serde_json::to_string(&json!({
"display": app.appDisplayName,
"id": app.appId,
"icon": &icon_path,
"path": &path,
"count": count,
"args": args
}))
.ok()?;
resp.append(&mut data.into_bytes());
ws_send(&mut get_exe_process_handle()?, &resp).await;
let install_folder = get_program_folder(&app.appId);
let to_exec = format!("{}\\installer.exe", &install_folder);
let path = path.to_string();
let app_str = to_string_pretty(app).ok()?;
let ver = app.version.clone();
Some(InstallResult::Thread(spawn(async move {
let (tx, rx) = oneshot::channel::<bool>();
get_handles().insert(
count,
(
now(),
Box::new(move |success| {
let res: Option<()> = (move || {
fs::create_dir_all(&install_folder).ok()?;
fs::copy(&path, to_exec).ok()?;
fs::write(format!("{}\\app.json", &install_folder), app_str).ok()?;
fs::write(format!("{}\\ahqStoreVersion", &install_folder), ver).ok()?;
fs::remove_file(path).ok()?;
fs::remove_file(icon_path).ok()?;
Some(())
})();
tx.send(success && res.is_some()).ok();
}),
),
);
rx.await.ok().and_then(|x| if x { Some(()) } else { None })
})))
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/exe/pipe.rs | src-service/src/handlers/service/windows/exe/pipe.rs | use std::future::Future;
use std::io::ErrorKind;
use std::os::windows::io::AsRawHandle;
use std::time::Duration;
use std::{ffi::c_void, ptr};
use tokio::net::windows::named_pipe::{NamedPipeServer, PipeMode, ServerOptions};
use windows::Win32::{
Foundation::HANDLE,
Security::{
InitializeSecurityDescriptor, SetSecurityDescriptorDacl, PSECURITY_DESCRIPTOR,
SECURITY_ATTRIBUTES, SECURITY_DESCRIPTOR,
},
System::{Pipes::GetNamedPipeClientProcessId, SystemServices::SECURITY_DESCRIPTOR_REVISION},
};
use crate::authentication::is_current_logged_in_user;
use crate::encryption::decrypt2;
use crate::handlers::service::windows::exe::daemon::get_exe_tx;
use crate::utils::write_log;
use super::daemon::start_exe_daemon;
pub static mut EXE_DAEMON_PROCESS: Option<NamedPipeServer> = None;
pub static mut CONNECTED: bool = false;
pub fn get_exe_process_handle() -> Option<&'static mut NamedPipeServer> {
unsafe { EXE_DAEMON_PROCESS.as_mut() }
}
pub fn launch() -> impl Future<Output = ()> {
println!("[EXE]: Hosting EXE Service handler");
write_log("[EXE]: Hosting EXE Service handler");
let mut obj = SECURITY_DESCRIPTOR::default();
// make it have full rights over the named pipe
unsafe {
InitializeSecurityDescriptor(
PSECURITY_DESCRIPTOR(&mut obj as *mut _ as *mut c_void),
SECURITY_DESCRIPTOR_REVISION,
)
.unwrap();
SetSecurityDescriptorDacl(
PSECURITY_DESCRIPTOR(&mut obj as *mut _ as *mut c_void),
true,
Some(ptr::null()),
false,
)
.unwrap();
}
let mut attr = SECURITY_ATTRIBUTES::default();
attr.lpSecurityDescriptor = &mut obj as *mut _ as *mut c_void;
let pipe = unsafe {
ServerOptions::new()
.first_pipe_instance(true)
.reject_remote_clients(true)
.pipe_mode(PipeMode::Message)
.create_with_security_attributes_raw(
r"\\.\pipe\ahqstore-service-exe-v3",
&mut attr as *mut _ as *mut c_void,
)
.unwrap()
};
unsafe {
EXE_DAEMON_PROCESS = pipe.into();
}
let pipe = get_exe_process_handle().unwrap();
async move {
start_exe_daemon().await;
loop {
println!("[EXE]: Loop");
if let Ok(()) = pipe.connect().await {
unsafe { CONNECTED = true };
println!("[EXE]: Connected");
let handle = pipe.as_raw_handle();
let mut process_id = 0u32;
unsafe {
let handle = HANDLE(handle);
let _ = GetNamedPipeClientProcessId(handle, &mut process_id as *mut _);
}
if !is_current_logged_in_user(process_id as usize) {
let _ = pipe.disconnect();
continue;
}
let mut authenticated = false;
// Wait for 1 min 30 seconds to connect
// 1 minute 30 seconds
'auth: for _ in 0..=9_000 {
match read_msg(pipe).await {
ReadResponse::Data(msg) => {
if "%Qzn835y37z%%^&*&^%&^%^&%^" == &decrypt2(msg).unwrap_or_default() {
println!("[EXE]: Authenticated");
authenticated = true;
}
break 'auth;
}
ReadResponse::Disconnect => {
println!("[EXE]: SIG Disconnect");
break 'auth;
}
_ => {}
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
if !authenticated {
println!("[EXE]: Disconnect, authenticated = {authenticated}");
let _ = pipe.disconnect();
continue;
}
let mut count: u8 = 0;
'a: loop {
count += 1;
if count >= 30 {
if !is_current_logged_in_user(process_id as usize) {
let _ = pipe.disconnect();
break 'a;
}
count = 0;
}
match read_msg(pipe).await {
ReadResponse::Data(msg) => {
get_exe_tx().send(msg.into()).await;
}
ReadResponse::Disconnect => {
let _ = pipe.disconnect();
break 'a;
}
_ => {}
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
unsafe {
CONNECTED = false;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
pub enum ReadResponse {
None,
Data(Vec<u8>),
Disconnect,
}
pub async fn read_msg(pipe: &mut NamedPipeServer) -> ReadResponse {
let mut val = [0u8; 8];
match pipe.try_read(&mut val) {
Ok(0) => {
return ReadResponse::None;
}
Ok(_) => {
println!("[EXE]: Reading bytes");
let total = usize::from_be_bytes(val);
let mut buf: Vec<u8> = Vec::new();
let mut byte = [0u8];
println!("Total {total}");
for _ in 0..total {
match pipe.try_read(&mut byte) {
Ok(_) => {
buf.push(byte[0]);
}
Err(e) => match e.kind() {
ErrorKind::WouldBlock => {
return ReadResponse::None;
}
ErrorKind::BrokenPipe => {
println!("[EXE]: Broken Pipe");
return ReadResponse::Disconnect;
}
e => {
let err = format!("{e:?}");
if &err != "Uncategorized" {
let _ = pipe.disconnect();
return ReadResponse::Disconnect;
}
return ReadResponse::None;
}
},
}
}
return ReadResponse::Data(buf);
}
Err(e) => match e.kind() {
ErrorKind::BrokenPipe => {
println!("[EXE]: Broken Pipe");
return ReadResponse::Disconnect;
}
ErrorKind::WouldBlock => ReadResponse::None,
e => {
let err = format!("[EXE]: {e:?}");
println!("{}", &err);
write_log(&err);
if &err != "Uncategorized" {
let _ = pipe.disconnect();
return ReadResponse::Disconnect;
}
ReadResponse::None
}
},
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/exe/daemon.rs | src-service/src/handlers/service/windows/exe/daemon.rs | use std::{collections::HashMap, time::Duration};
use tokio::{
spawn,
sync::mpsc::{channel, Sender},
time::sleep,
};
use crate::utils::{now, ws_send};
use super::pipe::get_exe_process_handle;
static mut TX: Option<Sender<Vec<u8>>> = None;
static mut HANDLES: Option<HashMap<u64, (u64, Box<dyn FnOnce(bool) -> ()>)>> = None;
pub fn get_exe_tx() -> &'static Sender<Vec<u8>> {
unsafe { TX.as_ref().unwrap() }
}
pub fn get_handles() -> &'static mut HashMap<u64, (u64, Box<dyn FnOnce(bool) -> ()>)> {
unsafe { HANDLES.as_mut().unwrap() }
}
pub async fn start_exe_daemon() {
let (tx, mut rx) = channel::<Vec<u8>>(10240);
unsafe {
TX = Some(tx);
HANDLES = Some(HashMap::new());
}
tokio::spawn(async move {
let mut count: u16 = 0;
loop {
count += 1;
// Check after 3k loops (~5 mins)
if count >= 3000 {
count = 0;
let handles = get_handles();
let mut to_remove = vec![];
handles.values().for_each(|(t, _)| {
if now() > *t {
to_remove.push(*t);
}
});
for entry in to_remove {
let mut ws_val = vec![1];
ws_val.append(&mut entry.to_be_bytes().to_vec());
spawn(async move {
ws_send(&mut get_exe_process_handle()?, &ws_val).await;
Some(())
});
let (id, c) = handles.remove(&entry).unwrap();
c(false);
}
}
if let Some(mut x) = rx.try_recv().ok() {
println!("Resp {x:?}");
let data: Vec<u8> = x.drain(1..).collect();
if data.len() == 8 {
let data: [u8; 8] = data[0..8].try_into().unwrap();
let data = u64::from_be_bytes(data);
let successful = x.pop().unwrap() == 0;
println!("Got data... successful: {}, entry {}", successful, data);
if let Some((_, x)) = get_handles().remove(&data) {
println!("Got entry");
x(successful);
}
}
}
sleep(Duration::from_millis(100)).await;
}
});
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/av/update.rs | src-service/src/handlers/service/windows/av/update.rs | use tokio::process::Command;
use super::DEFENDER_CMD;
pub async fn update_win_defender() -> Option<()> {
if !Command::new(DEFENDER_CMD)
.args(["-SignatureUpdate"])
.spawn()
.ok()?
.wait()
.await
.ok()?
.success()
{
return None;
}
Some(())
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/av/mod.rs | src-service/src/handlers/service/windows/av/mod.rs | pub static DEFENDER_CMD: &'static str = "C:\\Program Files\\Windows Defender\\MpCmdRun";
pub mod scan;
pub mod update;
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/service/windows/av/scan.rs | src-service/src/handlers/service/windows/av/scan.rs | use std::{
process::{Command, Stdio},
thread::{self, JoinHandle},
};
use super::DEFENDER_CMD;
pub type Malicious = bool;
pub fn scan_threaded(path: &str) -> JoinHandle<Option<Malicious>> {
let child = Command::new(DEFENDER_CMD)
.args(["-Scan", "-ScanType", "3", "-File"])
.arg(path)
.stdout(Stdio::piped())
.spawn();
let okay = format!("Scanning {} found no threats", &path);
thread::spawn(move || {
let out = child.ok()?.wait_with_output().ok()?.stdout;
let out = String::from_utf8_lossy(&out);
if out.contains(&okay) {
return Some(false);
}
Some(true)
})
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/daemon/dwn.rs | src-service/src/handlers/daemon/dwn.rs | use std::{io::Write, mem::replace};
use ahqstore_types::{AppStatus, Library};
use crate::{
handlers::{av, install_app, InstallResult},
utils::get_installer_file,
};
use super::{DaemonData, DaemonState, Step};
pub async fn handle(resp: &mut Library, state: &mut DaemonState, imp: &mut bool) {
let data = state.data.as_mut().unwrap();
if let DaemonData::Dwn(x) = data {
match x.ext_bytes.chunk().await {
Ok(Some(chunk)) => {
let len = chunk.len() as f64;
let prog = len * 100.0 / resp.max as f64;
resp.progress += prog;
let _ = x.file.write_all(&chunk);
}
Ok(None) => {
println!("100 %");
let _ = x.file.flush();
let _ = x.file.sync_all();
//Drop the File
let mut data = replace(&mut state.data, None);
let mut data = data.expect("Impossible to be null");
let DaemonData::Dwn(x) = data else {
panic!("Impossible panic");
};
resp.status = AppStatus::AVScanning;
let inst = get_installer_file(&x.app);
state.data = Some(DaemonData::AVScan(x.app, av::scan::scan_threaded(&inst)));
state.step = Step::AVScanning;
*imp = true;
}
_ => {}
}
}
}
pub async fn av_scan(resp: &mut Library, state: &mut DaemonState, imp: &mut bool) {
let data = state.data.as_mut().unwrap();
if let DaemonData::AVScan(app, x) = data {
if x.is_finished() {
*imp = true;
let mut data = replace(&mut state.data, None);
let data = data.expect("Impossible to be null");
let DaemonData::AVScan(app, x) = data else {
panic!("Impossible panic");
};
let av_flagged = x.join().expect("This cannot panic as the Thread cannot");
if !av_flagged.unwrap_or(true) {
resp.status = AppStatus::Installing;
if let Some(x) = install_app(&app, resp.is_update, &resp.user).await {
state.step = Step::Installing;
state.data = Some(DaemonData::Inst(x));
} else {
state.step = Step::Done;
resp.status = AppStatus::NotSuccessful;
}
} else {
state.step = Step::Done;
resp.status = AppStatus::AVFlagged;
}
}
}
}
pub async fn handle_inst(resp: &mut Library, state: &mut DaemonState, imp: &mut bool) {
let data = state.data.as_mut().unwrap();
let handle_exit = |imp: &mut bool, success: bool, resp: &mut Library, state: &mut DaemonState| {
*imp = true;
if !success {
resp.status = AppStatus::NotSuccessful;
} else {
resp.status = AppStatus::InstallSuccessful;
}
state.step = Step::Done;
};
if let DaemonData::Inst(x) = data {
match x {
InstallResult::Child(x) => {
match x.try_wait() {
Ok(Some(s)) => handle_exit(imp, s.success(), resp, state),
// Let's actually block
Ok(None) => match x.wait() {
Ok(s) => handle_exit(imp, s.success(), resp, state),
_ => handle_exit(imp, false, resp, state),
},
_ => handle_exit(imp, false, resp, state),
}
}
InstallResult::Thread(x) => {
if x.is_finished() {
let res = x.await.unwrap();
handle_exit(
imp,
match res {
Some(()) => true,
_ => false,
},
resp,
state,
)
}
}
}
}
}
pub async fn handle_u_inst(resp: &mut Library, state: &mut DaemonState, imp: &mut bool) {
let data = state.data.as_mut().unwrap();
let handle_exit = |success: bool, resp: &mut Library, state: &mut DaemonState| {
if !success {
resp.status = AppStatus::NotSuccessful;
} else {
resp.status = AppStatus::UninstallSuccessful;
}
state.step = Step::Done;
};
if let DaemonData::Unst(x) = data {
if x.is_finished() {
*imp = true;
let x = replace(x, std::thread::spawn(|| false));
let x = x.join();
handle_exit(
match x {
Ok(s) => s,
_ => false,
},
resp,
state,
)
}
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/daemon/mod.rs | src-service/src/handlers/daemon/mod.rs | mod dwn;
mod recv;
use recv::recv;
use ahqstore_types::{
AHQStoreApplication, AppStatus, Command, Library, Response, ToDo, UpdateStatusReport,
};
use reqwest::Request;
use std::{
default,
fs::File,
future::{Future, IntoFuture},
mem::replace,
process::Child,
sync::mpsc::{channel, Receiver, Sender},
thread::JoinHandle,
time::{Duration, SystemTime},
};
use tokio::{
spawn,
time::{sleep, Sleep},
};
use crate::utils::{get_iprocess, structs::get_current_user, ws_send};
#[cfg(windows)]
use crate::handlers::pipe;
use super::{
av::{self, scan::Malicious},
get_app, get_commit, get_prefs, list_apps,
service::{download_app, install_app, UninstallResult},
uninstall_app, InstallResult,
};
#[cfg(windows)]
use super::list_user_apps;
pub static mut UPDATE_STATUS_REPORT: Option<UpdateStatusReport> = None;
pub static mut LIBRARY: Option<Vec<Library>> = None;
fn time() -> u64 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs()
}
fn time_millis() -> u128 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_millis()
}
pub fn lib_msg() -> Vec<u8> {
Response::as_msg(Response::Library(0, unsafe {
LIBRARY
.as_ref()
.unwrap()
.clone()
.into_iter()
.map(|mut x| {
x.app = None;
x
})
.collect()
}))
}
pub static BETWEEN: fn() -> Sleep = || sleep(Duration::from_millis(20));
pub fn get_install_daemon() -> Sender<Command> {
let (tx, rx) = channel();
spawn(async move {
run_daemon(rx).await;
});
tx
}
#[derive(Default, Debug)]
pub enum Step {
StartDownload,
Downloading,
AVScanning,
Installing,
StartUninstall,
Uninstalling,
Done,
#[default]
None,
}
pub enum DaemonData {
Dwn(DownloadData),
AVScan(AHQStoreApplication, JoinHandle<Option<Malicious>>),
Inst(InstallResult),
Unst(JoinHandle<bool>),
None,
}
#[derive(Debug)]
pub struct DownloadData {
pub current: u64,
pub total: u64,
pub file: File,
pub ext_bytes: reqwest::Response,
pub app: AHQStoreApplication,
}
#[derive(Default)]
pub struct DaemonState {
pub step: Step,
pub data: Option<DaemonData>,
pub entry: usize,
}
async fn run_daemon(mut rx: Receiver<Command>) {
println!("Daemon Running");
#[cfg(windows)]
tokio::spawn(async {
pipe::launch().await;
});
tokio::spawn(async {
av::update::update_win_defender().await;
});
let mut state = DaemonState::default();
unsafe {
UPDATE_STATUS_REPORT = Some(UpdateStatusReport::Disabled);
LIBRARY = Some(vec![]);
}
let should_autorun = get_prefs().auto_update_apps;
if should_autorun {
unsafe {
UPDATE_STATUS_REPORT = Some(UpdateStatusReport::UpToDate);
}
}
let mut secs = time() - 800;
let mut last_has_updated = false;
let run_update = || check_update();
let pending = unsafe { LIBRARY.as_mut().unwrap() };
let mut run_update_now = false;
let mut lib_sent = time_millis();
loop {
// Get data loop
let Some(mut ws) = get_iprocess() else {
continue;
};
if recv::recv(&mut rx, pending, &mut run_update_now).await {
ws_send(&mut ws, &lib_msg()).await;
}
if (should_autorun && time() > secs) || run_update_now {
run_update_now = false;
secs = time() + 600;
if 0 == get_commit().await {
run_update().await;
}
}
let mut state_change = false;
if let Step::None = state.step {
if pending.len() > 0 {
let data = pending.get(0).unwrap();
state = DaemonState {
step: match data.to {
ToDo::Install => Step::StartDownload,
ToDo::Uninstall => Step::StartUninstall,
},
data: None,
entry: 0,
};
state_change = true;
}
} else if let Step::Done = state.step {
if pending.len() > 0 {
pending.remove(0);
}
state.step = Step::None;
} else if let Step::StartDownload = state.step {
let entry = pending.get_mut(state.entry).unwrap();
if let Some((app, file, resp)) = download_app(entry).await {
let len = resp.content_length().unwrap_or(0);
entry.max = len;
entry.status = AppStatus::Downloading;
state.step = Step::Downloading;
state.data = Some(DaemonData::Dwn(DownloadData {
app,
file,
ext_bytes: resp,
total: len,
current: 0,
}));
} else {
state.step = Step::Done;
entry.status = AppStatus::NotSuccessful;
}
state_change = true;
} else if let Step::Downloading = state.step {
let resp = pending.get_mut(state.entry).unwrap();
dwn::handle(resp, &mut state, &mut state_change).await;
} else if let Step::AVScanning = state.step {
let resp = pending.get_mut(state.entry).unwrap();
dwn::av_scan(resp, &mut state, &mut state_change).await;
} else if let Step::StartUninstall = state.step {
let resp = pending.get_mut(state.entry).unwrap();
if let Some(x) = &resp.app {
let res = uninstall_app(&x);
match res {
// No implementors
UninstallResult::Sync(x) => {
state.step = Step::Done;
match x {
Some(_) => resp.status = AppStatus::UninstallSuccessful,
_ => resp.status = AppStatus::NotSuccessful,
}
}
// Only Implemented
UninstallResult::Thread(x) => {
resp.status = AppStatus::Uninstalling;
state.step = Step::Uninstalling;
state.data = Some(DaemonData::Unst(x));
}
}
state_change = true;
}
} else if let Step::Installing = state.step {
let resp = pending.get_mut(state.entry).unwrap();
dwn::handle_inst(resp, &mut state, &mut state_change).await;
} else if let Step::Uninstalling = state.step {
let resp = pending.get_mut(state.entry).unwrap();
dwn::handle_u_inst(resp, &mut state, &mut state_change).await;
}
if time_millis() - lib_sent >= 1500 || state_change {
ws_send(&mut ws, &lib_msg()).await;
lib_sent = time_millis();
}
let mut has_updated = false;
unsafe {
match UPDATE_STATUS_REPORT.as_ref().unwrap() {
UpdateStatusReport::UpToDate => {}
_ => {
if has_updated != last_has_updated {
last_has_updated = has_updated;
UPDATE_STATUS_REPORT = Some(UpdateStatusReport::UpToDate);
let _ = ws_send(
&mut ws,
&Response::as_msg(Response::UpdateStatus(0, UpdateStatusReport::UpToDate)),
)
.await;
}
}
}
}
match state.step {
Step::Downloading => {}
_ => BETWEEN().await,
};
}
}
pub async fn check_update() -> Option<bool> {
let mut to_update = vec![];
let Some(mut ws) = get_iprocess() else {
return None;
};
unsafe {
UPDATE_STATUS_REPORT = Some(UpdateStatusReport::Checking);
let _ = ws_send(
&mut ws,
&Response::as_msg(Response::UpdateStatus(0, UpdateStatusReport::Checking)),
)
.await;
}
let mut manage = async |x: Vec<(String, String)>, user: String| {
for (id, ver) in x {
if &ver == "custom" {
continue;
}
let app = get_app(0, id).await;
match app {
Response::AppData(_, id, app) => {
use ahqstore_types::{InstallerFormat, WindowsInstallScope};
// Skip if the user is not the currently logged in user
// Because WindowsInstallerExe cannot install if the user is not logged in
if let (Some(x), Some(y)) = (app.get_win_download(), app.get_win_options()) {
let scope = y.scope.as_ref().unwrap_or(&WindowsInstallScope::Machine);
if matches!(&x.installerType, &InstallerFormat::WindowsInstallerExe)
&& matches!(scope, &WindowsInstallScope::User)
{
if get_current_user().unwrap_or("") != &user {
continue;
}
}
}
if &ver == &app.version {
continue;
}
to_update.push((id, app, user.clone()));
}
_ => {}
}
}
};
if let Some(x) = list_apps() {
manage(x, "machine".into()).await;
}
#[cfg(windows)]
if let Some(x) = list_user_apps(None) {
for (user, apps) in x {
manage(apps, user).await;
}
}
let library = unsafe { LIBRARY.as_mut().unwrap() };
if to_update.is_empty() {
unsafe {
UPDATE_STATUS_REPORT = Some(UpdateStatusReport::UpToDate);
}
let _ = ws_send(
&mut ws,
&Response::as_msg(Response::UpdateStatus(0, UpdateStatusReport::UpToDate)),
)
.await;
return Some(false);
}
to_update.into_iter().for_each(|(id, app, user)| {
library.push(Library {
app_id: id.clone(),
is_update: true,
progress: 0.0,
status: AppStatus::Pending,
to: ToDo::Uninstall,
max: 0,
app: Some(app.clone()),
user: user.clone(),
});
library.push(Library {
app_id: id,
is_update: true,
progress: 0.0,
status: AppStatus::Pending,
to: ToDo::Install,
app: Some(app),
max: 0,
user,
});
});
unsafe {
UPDATE_STATUS_REPORT = Some(UpdateStatusReport::Updating);
let _ = ws_send(
&mut ws,
&Response::as_msg(Response::UpdateStatus(0, UpdateStatusReport::Updating)),
)
.await;
return Some(false);
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-service/src/handlers/daemon/recv.rs | src-service/src/handlers/daemon/recv.rs | use ahqstore_types::{AppStatus, Command, Library, Response, ToDo};
use std::sync::mpsc::Receiver;
use crate::{
handlers::{get_app, get_app_local},
utils::{structs::get_current_user, ws_send, ServiceIpc},
};
use super::{lib_msg, BETWEEN};
pub async fn recv(
rx: &mut Receiver<Command>,
pending: &mut Vec<Library>,
run_update_now: &mut bool,
) -> bool {
let mut found = false;
'r: loop {
if let Ok(data) = rx.try_recv() {
match data {
Command::InstallApp(_, app_id) => {
pending.push(Library {
app_id,
is_update: false,
status: AppStatus::Pending,
to: ToDo::Install,
progress: 0.0,
max: 0,
app: None,
// It is important to clone here so that it can be processed correctly even if the user changes
user: get_current_user()
.expect("Impossible to be null")
.to_string(),
});
}
Command::UninstallApp(ref_id, app_id) => {
if let Response::AppData(_, app_id, app) = get_app_local(ref_id, app_id).await {
pending.push(Library {
app_id,
is_update: false,
app: Some(app),
progress: 0.0,
max: 0,
status: AppStatus::Pending,
to: ToDo::Uninstall,
// It is important to clone here so that it can be processed correctly even if the user changes
user: get_current_user()
.expect("Impossible to be null")
.to_string(),
});
}
}
Command::RunUpdate(_) => {
*run_update_now = true;
}
_ => {}
}
found = true;
} else {
break 'r;
}
BETWEEN().await;
}
found
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-exe-installer/build.rs | src-exe-installer/build.rs | fn main() -> std::io::Result<()> {
if cfg!(target_os = "windows") {
let mut res = tauri_winres::WindowsResource::new();
res
.set_icon("icon.ico")
.set("InternalName", "ahqstore_user_daemon.exe")
.set("OriginalFilename", "ahqstore_user_daemon.exe")
.set("ProductName", "AHQ Store User Side Daemon")
.set(
"FileDescription",
"AHQ Store EXE Application Installer Daemon",
)
.set("LegalCopyright", "©️ AHQ Store 2024");
return res.compile();
}
Ok(())
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-exe-installer/src/main.rs | src-exe-installer/src/main.rs | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![allow(static_mut_refs)]
use daemon::PIPE;
use serde::{Deserialize, Serialize};
use std::{sync::LazyLock, time::Duration};
use tokio::{net::windows::named_pipe::NamedPipeClient, time::sleep};
use win32_notif::ToastsNotifier;
use chacha20poly1305::{
aead::{generic_array::GenericArray, Aead, KeyInit},
ChaCha20Poly1305,
};
pub(crate) static NOTIFIER: LazyLock<ToastsNotifier> =
LazyLock::new(|| ToastsNotifier::new("com.ahqstore.app").unwrap());
mod daemon;
pub(crate) static KEY_PASS: LazyLock<Vec<u8>> = LazyLock::new(|| {
let key = GenericArray::from_slice(include!("./encrypt_2").as_bytes());
let key = ChaCha20Poly1305::new(&key);
let nonce = GenericArray::from_slice(b"SSSSSSSSSSSS");
let to_encrypt = "%Qzn835y37z%%^&*&^%&^%^&%^";
key.encrypt(nonce, to_encrypt.as_bytes()).unwrap()
});
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct QuickApplicationData {
pub display: String,
pub id: String,
pub icon: String,
pub path: String,
pub count: u64,
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
loop {
unsafe {
PIPE = None;
}
daemon::run().await;
sleep(Duration::from_secs(1)).await;
}
}
pub async fn ws_send(ipc: &mut NamedPipeClient, val: &[u8]) {
let len = val.len().to_be_bytes();
let mut data = len.to_vec();
for byte in val {
data.push(*byte);
}
let _ = ipc.try_write(&data);
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-exe-installer/src/daemon/notification.rs | src-exe-installer/src/daemon/notification.rs | use std::{collections::HashMap, thread};
use win32_notif::{
notification::{
actions::{
action::{ActivationType, HintButtonStyle},
ActionButton,
},
header::{Header, HeaderActivationType},
visual::{progress::ProgressValue, Image, Placement, Progress, Text},
Scenario,
},
Notification, NotificationActivatedEventHandler, NotificationBuilder,
};
use crate::{ws_send, NOTIFIER};
use super::{run, QuickApplicationData, PIPE};
pub static mut NOTIF_MAP: Option<HashMap<u64, (QuickApplicationData, Notification<'static>)>> =
None;
pub(crate) fn get_notif_map(
) -> &'static mut HashMap<u64, (QuickApplicationData, Notification<'static>)> {
unsafe {
if NOTIF_MAP.is_none() {
NOTIF_MAP = Some(HashMap::new());
}
NOTIF_MAP.as_mut().unwrap()
}
}
pub fn send_update_notif(
id: u64,
icon_path: &str,
app_name: &str,
) -> Option<Notification<'static>> {
let Ok(x) = NotificationBuilder::new()
.header(Header::new(
"update",
"Update Application",
"update",
Some(HeaderActivationType::Foreground),
))
.set_use_button_style(true)
.set_scenario(Scenario::Urgent)
.visual(Text::create(
1,
&format!("Would you like to update {}?", app_name),
))
.visual(Image::new(
3,
format!("file:///{}", &icon_path),
None,
false,
Placement::AppLogoOverride,
true,
))
.action(
ActionButton::create("Yes")
.set_activation_type(ActivationType::Foreground)
.set_id("yes")
.set_button_style(HintButtonStyle::Success),
)
.action(
ActionButton::create("No")
.set_activation_type(ActivationType::Foreground)
.set_id("no"),
)
.on_activated(NotificationActivatedEventHandler::new(move |_, args| {
if let Some(args) = args {
let map = get_notif_map();
let Some((app, _x)) = map.remove(&id) else {
return Ok(());
};
// yes
if &args.button_id.unwrap_or_default() == "yes" {
send_update_notif(app.count, &app.icon, &app.display);
thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(async move {
let success = run::run(&app.path).await;
let mut resp = app.count.to_be_bytes().to_vec();
resp.push(if success { 0 } else { 1 });
if let Some(x) = unsafe { PIPE.as_mut() } {
ws_send(x, &resp).await;
}
})
});
}
// no
else {
thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(async move {
let success = run::run(&app.path).await;
let mut resp = app.count.to_be_bytes().to_vec();
resp.push(if success { 0 } else { 1 });
if let Some(x) = unsafe { PIPE.as_mut() } {
println!("Responded");
ws_send(x, &resp).await;
}
})
});
}
}
Ok(())
}))
.build(0, &NOTIFIER, &format!("{id}"), "update")
else {
return None;
};
x.show().ok()?;
Some(x)
}
pub fn send_installing(app: &QuickApplicationData, update: bool) {
let Ok(x) = NotificationBuilder::new()
.header(Header::new(
"update",
"Update Application",
"update",
Some(HeaderActivationType::Foreground),
))
.set_use_button_style(true)
.set_scenario(Scenario::Urgent)
.visual(Text::create(
1,
&(if !update {
format!("Installing {}", &app.display)
} else {
format!("Updating {}", &app.display)
}),
))
.visual(Image::new(
3,
format!("file:///{}", &app.icon),
None,
false,
Placement::AppLogoOverride,
true,
))
.visual(Progress::create(
if update {
"Updating..."
} else {
"Installing..."
},
ProgressValue::Indeterminate,
))
.build(0, &NOTIFIER, &format!("install_{}", app.id), "install")
else {
return;
};
let _ = x.show().ok();
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-exe-installer/src/daemon/mod.rs | src-exe-installer/src/daemon/mod.rs | use std::{io::ErrorKind, time::Duration};
use notification::{get_notif_map, send_installing, send_update_notif};
use tokio::{
net::windows::named_pipe::{ClientOptions, NamedPipeClient},
time::sleep,
};
use crate::{ws_send, QuickApplicationData};
mod notification;
pub(super) mod run;
pub static mut PIPE: Option<NamedPipeClient> = None;
pub async fn run() -> Option<()> {
let pipe = ClientOptions::new()
.open(r"\\.\pipe\ahqstore-service-exe-v3")
.ok()?;
unsafe {
PIPE = Some(pipe);
}
let pipe = unsafe { PIPE.as_mut().unwrap() };
sleep(Duration::from_millis(100)).await;
let _ = ws_send(
pipe,
&crate::KEY_PASS,
)
.await;
loop {
match read_msg(pipe).await {
ReadResponse::Data(mut data) => {
// data[0] == 1 means that remove the entry
if &data[0] == &1 {
let data = data.drain(1..=8).collect::<Vec<u8>>();
let data: [u8; 8] = data[0..].try_into().ok()?;
let _entry = u64::from_be_bytes(data);
} else {
let string_data = data.drain(2..).collect::<Vec<u8>>();
let _ = (|| async {
let update = data.remove(1) == 1;
let data = String::from_utf8(string_data).ok()?;
let data = serde_json::from_str::<QuickApplicationData>(&data).ok()?;
if update {
let notif = send_update_notif(data.count, &data.icon, &data.display)?;
let _ = get_notif_map().insert(data.count, (data, notif));
} else {
send_installing(&data, false);
let success = run::run(&data.path).await;
let mut resp = vec![];
resp.push(if success { 0 } else { 1 });
resp.append(&mut data.count.to_be_bytes().to_vec());
drop(data);
let _ = ws_send(pipe, &resp).await;
}
Some(())
})()
.await;
}
}
ReadResponse::Disconnect => {
println!("Breaking");
break;
}
ReadResponse::None => {}
}
sleep(Duration::from_nanos(100)).await;
}
println!("Broken");
return Some(());
}
pub enum ReadResponse {
None,
Data(Vec<u8>),
Disconnect,
}
pub async fn read_msg(pipe: &mut NamedPipeClient) -> ReadResponse {
let mut val = [0u8; 8];
match pipe.try_read(&mut val) {
Ok(0) => {
return ReadResponse::None;
}
Ok(_) => {
let total = usize::from_be_bytes(val);
let mut buf: Vec<u8> = Vec::new();
let mut byte = [0u8];
loop {
if buf.len() >= total {
break;
}
match pipe.try_read(&mut byte) {
Ok(_) => {
buf.push(byte[0]);
}
Err(e) => match e.kind() {
ErrorKind::BrokenPipe => {
return ReadResponse::Disconnect;
}
_ => {}
},
}
}
ReadResponse::Data(buf)
}
Err(e) => {
match e.kind() {
ErrorKind::WouldBlock => ReadResponse::None,
_ => ReadResponse::None,
}
},
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-exe-installer/src/daemon/run.rs | src-exe-installer/src/daemon/run.rs | use tokio::process::Command;
async fn run_inner(path: &str) -> Option<bool> {
let success = Command::new(path)
.spawn()
.ok()?
.wait()
.await
.ok()?
.success();
Some(success)
}
pub async fn run(path: &str) -> bool {
run_inner(path).await.unwrap_or(false)
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-updater/src/lib.rs | src-updater/src/lib.rs | mod check;
mod platform;
pub use check::*;
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-updater/src/check.rs | src-updater/src/check.rs | use std::env::consts::{ARCH, OS};
use serde::{Deserialize, Serialize};
use crate::platform::{platform_update, CLIENT};
#[derive(Debug, Serialize, Deserialize)]
pub struct Asset {
pub browser_download_url: String,
pub name: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Release {
pub tag_name: String,
pub prerelease: bool,
pub assets: Vec<Asset>,
}
pub fn gen_asset_name() -> String {
let mut installer = String::from("ahqstore_setup");
if OS == "linux" {
if ARCH == "x86_64" {
installer.push_str("_linux_amd64");
} else if ARCH == "aarch64" {
installer.push_str("_linux_arm64");
}
} else if OS == "windows" {
if ARCH == "x86_64" {
installer.push_str("_win32_amd64.exe");
} else if ARCH == "aarch64" {
installer.push_str("_win32_arm64.exe");
}
}
installer
}
pub async fn is_update_available(version: &str, pr_in: bool) -> (bool, Option<Release>) {
if let Ok(resp) = CLIENT
.get("https://api.github.com/repos/ahqsoftwares/tauri-ahq-store/releases")
.send()
.await
{
println!("Available");
if let Ok(resp) = resp.json::<Vec<Release>>().await {
if let Some(release) = resp.into_iter().find(|x| x.prerelease == pr_in) {
println!("Found a release\ncurr = {}, there = {}", version, release.tag_name);
let setup = gen_asset_name();
let setup = release.assets.iter().find(|x| &&x.name == &&setup);
if &release.tag_name != version && setup.is_some() {
return (true, Some(release));
}
}
}
}
(false, None)
}
pub async fn update(release: Release) {
let setup = gen_asset_name();
let setup = release.assets.iter().find(|x| &&x.name == &&setup).unwrap();
platform_update(&release, setup).await;
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-updater/src/platform/mod.rs | src-updater/src/platform/mod.rs | use std::{fs::File, io::Write};
use lazy_static::lazy_static;
use reqwest::{Client, ClientBuilder};
lazy_static! {
pub static ref CLIENT: Client = ClientBuilder::new()
.user_agent("AHQ Store / Updater")
.build()
.unwrap();
}
pub async fn download(url: &str, path: &str) -> Option<()> {
println!("{}", &path);
let mut file = File::create(path).ok()?;
let res = CLIENT.get(url).send().await.ok()?.bytes().await.ok()?;
file.write_all(&res).ok()?;
file.flush().ok()?;
drop(res);
drop(file);
Some(())
}
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use windows::*;
#[cfg(unix)]
mod linux;
#[cfg(unix)]
pub use linux::*;
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-updater/src/platform/linux/mod.rs | src-updater/src/platform/linux/mod.rs | use std::{
fs::*,
process::{self, Command},
};
use super::download;
use crate::{Asset, Release};
use dirs::home_dir;
pub async fn platform_update(raw: &Release, asset: &Asset) {
let mut local = home_dir().unwrap();
let _ = create_dir_all(&local);
local.push("ahqstore_updater");
let file = local.to_str().unwrap_or("/updater");
let _ = remove_file(&file);
if let Some(()) = download(&asset.browser_download_url, file).await {
Command::new("chmod")
.arg("a+rwx")
.arg(file)
.spawn()
.unwrap()
.wait()
.unwrap();
let mut cmd = Command::new("nohup");
cmd.arg(file);
if raw.prerelease {
cmd.arg("updatepr");
} else {
cmd.arg("update");
}
cmd.spawn().unwrap();
} else {
process::exit(-5);
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
ahqsoftwares/tauri-ahq-store | https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-updater/src/platform/windows/mod.rs | src-updater/src/platform/windows/mod.rs | use std::{
fs::{create_dir_all, remove_file},
process::Command,
};
use crate::{Asset, Release};
use dirs::cache_dir;
use super::download;
pub async fn platform_update(raw: &Release, asset: &Asset) {
let mut local = cache_dir().unwrap();
local.push("Temp");
let _ = create_dir_all(&local);
local.push("ahqstore_updater.exe");
let file = local.to_str().unwrap_or("C:\\updater.exe");
let _ = remove_file(&file);
if let Some(()) = download(&asset.browser_download_url, file).await {
let mut cmd = Command::new("powershell");
cmd.arg("Start-Process");
cmd.arg(file);
if raw.prerelease {
cmd.arg("updatepr");
} else {
cmd.arg("update");
}
cmd.spawn().unwrap();
}
}
| rust | MIT | 93abe09a40592f177b8aeba6ab105ebe97fc50cc | 2026-01-04T20:16:47.735892Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/icx/src/main.rs | icx/src/main.rs | use anyhow::{bail, Context, Result};
use candid::{
types::value::IDLValue,
types::{Function, Type, TypeInner},
CandidType, Decode, Deserialize, IDLArgs, TypeEnv,
};
use candid_parser::{check_prog, parse_idl_args, parse_idl_value, IDLProg};
use clap::{crate_authors, crate_version, Parser, ValueEnum};
use ic_agent::{
agent::{
self,
agent_error::HttpErrorPayload,
signed::{SignedQuery, SignedRequestStatus, SignedUpdate},
CallResponse,
},
export::Principal,
identity::BasicIdentity,
Agent, AgentError, Identity,
};
use ic_ed25519::PrivateKey;
use ic_utils::interfaces::management_canister::{
builders::{CanisterSettings, InstallCodeArgs},
MgmtMethod,
};
use std::{
collections::VecDeque, convert::TryFrom, io::BufRead, path::PathBuf, str::FromStr,
time::Duration,
};
const DEFAULT_IC_GATEWAY: &str = "https://ic0.app";
#[derive(Parser)]
#[clap(
version = crate_version!(),
author = crate_authors!(),
propagate_version(true),
)]
struct Opts {
/// The URL of the replica.
#[clap(default_value = "http://localhost:8000/")]
replica: String,
/// An optional PEM file to read the identity from. If none is passed,
/// a random identity will be created.
#[clap(long)]
pem: Option<PathBuf>,
/// An optional field to set the expiry time on requests. Can be a human
/// readable time (like `100s`) or a number of seconds.
#[clap(long)]
ttl: Option<humantime::Duration>,
#[clap(subcommand)]
subcommand: SubCommand,
}
#[derive(Parser)]
enum SubCommand {
/// Sends an update call to the replica.
Update(CallOpts),
/// Send a query call to the replica.
Query(CallOpts),
/// Checks the `status` endpoints of the replica.
Status,
/// Send a serialized request, taking from STDIN.
Send,
/// Transform Principal from hex to new text.
PrincipalConvert(PrincipalConvertOpts),
}
/// A subcommand for controlling testing
#[derive(Parser)]
struct CallOpts {
/// The Canister ID to call.
canister_id: Principal,
/// Output the serialization of a message to STDOUT.
#[arg(long)]
serialize: bool,
/// Path to a candid file to analyze the argument. Otherwise candid will parse the
/// argument without type hint.
#[arg(long)]
candid: Option<PathBuf>,
method_name: String,
/// The type of output (hex or IDL).
#[arg(long, value_enum, default_value_t = ArgType::Idl)]
arg: ArgType,
/// The type of output (hex or IDL).
#[arg(long, value_enum, default_value_t = ArgType::Idl)]
output: ArgType,
/// Argument to send, in Candid textual format.
arg_value: Option<String>,
}
#[derive(ValueEnum, Clone)]
enum ArgType {
Idl,
Raw,
}
impl std::str::FromStr for ArgType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"idl" => Ok(ArgType::Idl),
"raw" => Ok(ArgType::Raw),
other => Err(format!("invalid argument type: {other}")),
}
}
}
#[derive(Parser)]
struct PrincipalConvertOpts {
/// Convert from hexadecimal to the new group-based Principal text.
#[clap(long)]
from_hex: Option<String>,
/// Convert from the new group-based Principal text to hexadecimal.
#[clap(long)]
to_hex: Option<String>,
}
/// Parse IDL file into `TypeEnv`. This is a best effort function: it will succeed if
/// the IDL file can be parsed and type checked in Rust parser, and has an
/// actor in the IDL file. If anything fails, it returns None.
pub fn get_candid_type(
idl_path: &std::path::Path,
method_name: &str,
) -> Result<Option<(TypeEnv, Function)>> {
let (env, ty) = check_candid_file(idl_path)
.with_context(|| format!("Failed when checking candid file: {}", idl_path.display()))?;
match ty {
None => Ok(None),
Some(actor) => {
let method = env
.get_method(&actor, method_name)
.with_context(|| format!("Failed to get method: {method_name}"))?
.clone();
Ok(Some((env, method)))
}
}
}
pub fn check_candid_file(idl_path: &std::path::Path) -> Result<(TypeEnv, Option<Type>)> {
let idl_file = std::fs::read_to_string(idl_path)
.with_context(|| format!("Failed to read Candid file: {}", idl_path.to_string_lossy()))?;
let ast = idl_file
.parse::<IDLProg>()
.with_context(|| format!("Failed to parse the Candid file: {}", idl_path.display()))?;
let mut env = TypeEnv::new();
let actor = check_prog(&mut env, &ast).with_context(|| {
format!(
"Failed to type check the Candid file: {}",
idl_path.display()
)
})?;
Ok((env, actor))
}
fn blob_from_arguments(
arguments: Option<&str>,
arg_type: &ArgType,
method_type: &Option<(TypeEnv, Function)>,
) -> Result<Vec<u8>> {
let mut buffer = Vec::new();
let arguments = if arguments == Some("-") {
use std::io::Read;
std::io::stdin().read_to_end(&mut buffer).unwrap();
std::str::from_utf8(&buffer).ok()
} else {
arguments
};
match arg_type {
ArgType::Raw => {
let bytes = hex::decode(arguments.unwrap_or(""))
.context("Argument is not a valid hex string")?;
Ok(bytes)
}
ArgType::Idl => {
let arguments = arguments.unwrap_or("()");
let args = parse_idl_args(arguments);
let typed_args = match method_type {
None => args
.context("Failed to parse arguments with no method type info")?
.to_bytes(),
Some((env, func)) => {
let first_char = arguments.chars().next();
let is_candid_format = first_char == Some('(');
// If parsing fails and method expects a single value, try parsing as IDLValue.
// If it still fails, and method expects a text type, send arguments as text.
let args = args.or_else(|e| {
if func.args.len() == 1 && !is_candid_format {
let is_quote = first_char == Some('"');
if &TypeInner::Text == func.args[0].as_ref() && !is_quote {
Ok(IDLValue::Text(arguments.to_string()))
} else {
parse_idl_value(arguments)
}
.map(|v| IDLArgs::new(&[v]))
} else {
Err(e)
}
});
args.context("Failed to parse arguments with method type info")?
.to_bytes_with_types(env, &func.args)
}
}
.context("Failed to serialize Candid values")?;
Ok(typed_args)
}
}
}
fn print_idl_blob(
blob: &[u8],
output_type: &ArgType,
method_type: &Option<(TypeEnv, Function)>,
) -> Result<()> {
let hex_string = hex::encode(blob);
match output_type {
ArgType::Raw => {
println!("{hex_string}");
}
ArgType::Idl => {
let result = match method_type {
None => IDLArgs::from_bytes(blob),
Some((env, func)) => IDLArgs::from_bytes_with_types(blob, env, &func.rets),
};
println!(
"{}",
result.with_context(|| format!("Failed to deserialize blob 0x{hex_string}"))?
);
}
}
Ok(())
}
async fn fetch_root_key_from_non_ic(agent: &Agent, replica: &str) -> Result<()> {
let normalized_replica = replica.strip_suffix('/').unwrap_or(replica);
if normalized_replica != DEFAULT_IC_GATEWAY {
agent
.fetch_root_key()
.await
.context("Failed to fetch root key from replica")?;
}
Ok(())
}
pub fn get_effective_canister_id(
is_management_canister: bool,
method_name: &str,
arg_value: &[u8],
canister_id: Principal,
) -> Result<Option<Principal>> {
if is_management_canister {
let method_name = MgmtMethod::from_str(method_name).with_context(|| {
format!("Attempted to call an unsupported management canister method: {method_name}")
})?;
match method_name {
MgmtMethod::CreateCanister | MgmtMethod::RawRand => bail!(
"{} can only be called via an inter-canister call.",
method_name.as_ref()
),
MgmtMethod::InstallCode => {
let install_args = Decode!(arg_value, InstallCodeArgs)
.context("Argument is not valid for CanisterInstall")?;
Ok(Some(install_args.canister_id))
}
MgmtMethod::StartCanister
| MgmtMethod::StopCanister
| MgmtMethod::CanisterStatus
| MgmtMethod::DeleteCanister
| MgmtMethod::DepositCycles
| MgmtMethod::UninstallCode
| MgmtMethod::ProvisionalTopUpCanister
| MgmtMethod::UploadChunk
| MgmtMethod::ClearChunkStore
| MgmtMethod::StoredChunks
| MgmtMethod::FetchCanisterLogs
| MgmtMethod::TakeCanisterSnapshot
| MgmtMethod::ListCanisterSnapshots
| MgmtMethod::DeleteCanisterSnapshot
| MgmtMethod::LoadCanisterSnapshot
| MgmtMethod::ReadCanisterSnapshotMetadata
| MgmtMethod::ReadCanisterSnapshotData
| MgmtMethod::UploadCanisterSnapshotMetadata
| MgmtMethod::UploadCanisterSnapshotData => {
#[derive(CandidType, Deserialize)]
struct In {
canister_id: Principal,
}
let in_args =
Decode!(arg_value, In).context("Argument is not a valid Principal")?;
Ok(Some(in_args.canister_id))
}
MgmtMethod::ProvisionalCreateCanisterWithCycles => Ok(None),
MgmtMethod::UpdateSettings => {
#[derive(CandidType, Deserialize)]
struct In {
canister_id: Principal,
settings: CanisterSettings,
}
let in_args =
Decode!(arg_value, In).context("Argument is not valid for UpdateSettings")?;
Ok(Some(in_args.canister_id))
}
MgmtMethod::InstallChunkedCode => {
#[derive(CandidType, Deserialize)]
struct In {
target_canister: Principal,
}
let in_args = Decode!(arg_value, In)
.context("Argument is not valid for InstallChunkedCode")?;
Ok(Some(in_args.target_canister))
}
MgmtMethod::BitcoinGetBalance
| MgmtMethod::BitcoinGetUtxos
| MgmtMethod::BitcoinSendTransaction
| MgmtMethod::BitcoinGetCurrentFeePercentiles
| MgmtMethod::BitcoinGetBlockHeaders
| MgmtMethod::EcdsaPublicKey
| MgmtMethod::SignWithEcdsa
| MgmtMethod::NodeMetricsHistory
| MgmtMethod::CanisterInfo => {
bail!("Management canister method {method_name} can only be run from canisters");
}
}
} else {
Ok(Some(canister_id))
}
}
fn create_identity(maybe_pem: Option<PathBuf>) -> impl Identity {
if let Some(pem_path) = maybe_pem {
BasicIdentity::from_pem_file(pem_path).expect("Could not read the key pair.")
} else {
let private_key = PrivateKey::generate();
BasicIdentity::from_raw_key(&private_key.serialize_raw())
}
}
#[tokio::main]
async fn main() -> Result<()> {
let opts: Opts = Opts::parse();
let agent = Agent::builder()
.with_url(&opts.replica)
.with_boxed_identity(Box::new(create_identity(opts.pem)))
.build()
.context("Failed to build the Agent")?;
let default_effective_canister_id =
pocket_ic::nonblocking::get_default_effective_canister_id(opts.replica.clone())
.await
.unwrap_or(Principal::management_canister());
// You can handle information about subcommands by requesting their matches by name
// (as below), requesting just the name used, or both at the same time
match &opts.subcommand {
SubCommand::Update(t) | SubCommand::Query(t) => {
let maybe_candid_path = t.candid.as_ref();
let expire_after: Option<std::time::Duration> = opts.ttl.map(Into::into);
let method_type = match maybe_candid_path {
None => None,
Some(path) => get_candid_type(path, &t.method_name)
.context("Failed to get method type from candid file")?,
};
let arg = blob_from_arguments(t.arg_value.as_deref(), &t.arg, &method_type)
.context("Invalid arguments")?;
let is_management_canister = t.canister_id == Principal::management_canister();
let effective_canister_id = get_effective_canister_id(
is_management_canister,
&t.method_name,
&arg,
t.canister_id,
)
.context("Failed to get effective_canister_id for this call")?
.unwrap_or(default_effective_canister_id);
if t.serialize {
match &opts.subcommand {
SubCommand::Update(_) => {
// For local emulator, we need to fetch the root key for updates.
// So on an air-gapped machine, we can only generate message for the IC main net
// which agent hard-coded its root key
fetch_root_key_from_non_ic(&agent, &opts.replica).await?;
let mut builder = agent.update(&t.canister_id, &t.method_name);
if let Some(d) = expire_after {
builder = builder.expire_after(d);
}
let signed_update = builder
.with_arg(arg)
.with_effective_canister_id(effective_canister_id)
.sign()
.context("Failed to sign the update call")?;
let serialized = serde_json::to_string(&signed_update).unwrap();
println!("{serialized}");
let signed_request_status = agent
.sign_request_status(effective_canister_id, signed_update.request_id)
.context(
"Failed to sign the request_status call accompany with the update",
)?;
let serialized = serde_json::to_string(&signed_request_status).unwrap();
println!("{serialized}");
}
&SubCommand::Query(_) => {
fetch_root_key_from_non_ic(&agent, &opts.replica).await?;
let mut builder = agent.query(&t.canister_id, &t.method_name);
if let Some(d) = expire_after {
builder = builder.expire_after(d);
}
let signed_query = builder
.with_arg(arg)
.with_effective_canister_id(effective_canister_id)
.sign()
.context("Failed to sign the query call")?;
let serialized = serde_json::to_string(&signed_query).unwrap();
println!("{serialized}");
}
_ => unreachable!(),
}
} else {
let result = match &opts.subcommand {
SubCommand::Update(_) => {
// We need to fetch the root key for updates.
fetch_root_key_from_non_ic(&agent, &opts.replica).await?;
let mut builder = agent.update(&t.canister_id, &t.method_name);
if let Some(d) = expire_after {
builder = builder.expire_after(d);
}
let printer = async {
loop {
eprint!(".");
tokio::time::sleep(Duration::from_secs(1)).await;
}
};
let result = builder
.with_arg(arg)
.with_effective_canister_id(effective_canister_id)
.call_and_wait();
let result = tokio::select!(
Ok(unreachable) = tokio::spawn(printer) => unreachable,
res = tokio::time::timeout(Duration::from_secs(5 * 60), result) => res,
);
eprintln!();
result.unwrap_or(Err(AgentError::TimeoutWaitingForResponse()))
}
SubCommand::Query(_) => {
fetch_root_key_from_non_ic(&agent, &opts.replica).await?;
let mut builder = agent.query(&t.canister_id, &t.method_name);
if let Some(d) = expire_after {
builder = builder.expire_after(d);
}
builder
.with_arg(arg)
.with_effective_canister_id(effective_canister_id)
.call()
.await
}
_ => unreachable!(),
};
match result {
Ok(blob) => {
print_idl_blob(&blob, &t.output, &method_type)
.context("Failed to print result blob")?;
}
Err(AgentError::TransportError(_)) => return Ok(()),
Err(AgentError::HttpError(HttpErrorPayload {
status,
content_type,
content,
})) => {
let mut error_message =
format!("Server returned an HTTP Error:\n Code: {status}\n");
match content_type.as_deref() {
None => error_message
.push_str(&format!(" Content: {}\n", hex::encode(content))),
Some("text/plain; charset=UTF-8" | "text/plain") => {
error_message.push_str(" ContentType: text/plain\n");
error_message.push_str(&format!(
" Content: {}\n",
String::from_utf8_lossy(&content)
));
}
Some(x) => {
error_message.push_str(&format!(" ContentType: {x}\n"));
error_message.push_str(&format!(
" Content: {}\n",
hex::encode(&content)
));
}
}
bail!(error_message);
}
Err(s) => Err(s).context("Got an error when make the canister call")?,
}
}
}
SubCommand::Status => {
let status = agent
.status()
.await
.context("Failed to get network status")?;
println!("{status:#}");
}
SubCommand::PrincipalConvert(t) => {
if let Some(hex) = &t.from_hex {
let p = Principal::try_from(hex::decode(hex).expect("Could not decode hex: {}"))
.expect("Could not transform into a Principal: {}");
eprintln!("Principal: {p}");
} else if let Some(txt) = &t.to_hex {
let p = Principal::from_text(txt.as_str())
.expect("Could not transform into a Principal: {}");
eprintln!("Hexadecimal: {}", hex::encode(p.as_slice()));
}
}
SubCommand::Send => {
let input: VecDeque<String> = std::io::stdin()
.lock()
.lines()
.collect::<Result<VecDeque<String>, std::io::Error>>()
.context("Failed to read from stdin")?;
let mut buffer = String::new();
for line in input {
buffer.push_str(&line);
}
println!("{buffer}");
if let Ok(signed_update) = serde_json::from_str::<SignedUpdate>(&buffer) {
fetch_root_key_from_non_ic(&agent, &opts.replica).await?;
let call_response = agent
.update_signed(
signed_update.effective_canister_id,
signed_update.signed_update,
)
.await
.context("Got an AgentError when send the signed update call")?;
match call_response {
CallResponse::Response(blob) => {
print_idl_blob(&blob, &ArgType::Idl, &None)
.context("Failed to print update result")?;
}
CallResponse::Poll(request_id) => {
eprintln!("RequestID: 0x{}", String::from(request_id));
}
};
} else if let Ok(signed_query) = serde_json::from_str::<SignedQuery>(&buffer) {
let blob = agent
.query_signed(
signed_query.effective_canister_id,
signed_query.signed_query,
)
.await
.context("Got an error when send the signed query call")?;
print_idl_blob(&blob, &ArgType::Idl, &None)
.context("Failed to print query result")?;
} else if let Ok(signed_request_status) =
serde_json::from_str::<SignedRequestStatus>(&buffer)
{
fetch_root_key_from_non_ic(&agent, &opts.replica).await?;
let (response, _) = agent
.request_status_signed(
&signed_request_status.request_id,
signed_request_status.effective_canister_id,
signed_request_status.signed_request_status,
)
.await
.context("Got an error when send the signed request_status call")?;
match response {
agent::RequestStatusResponse::Replied(response) => {
print_idl_blob(&response.arg, &ArgType::Idl, &None)
.context("Failed to print request_status result")?;
}
agent::RequestStatusResponse::Rejected(replica_error) => {
bail!(
r#"The Replica returned an error. reject code: {:?}, reject message: "{}", error code: {}"#,
replica_error.reject_code,
replica_error.reject_message,
replica_error.error_code.unwrap_or_default()
);
}
_ => bail!("Can't get valid status of the request.",),
}
} else {
bail!("Invalid input.");
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use crate::Opts;
use clap::CommandFactory;
#[test]
fn valid_command() {
Opts::command().debug_assert();
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-transport-types/src/lib.rs | ic-transport-types/src/lib.rs | //! Types related to the [HTTP transport](https://internetcomputer.org/docs/current/references/ic-interface-spec#http-interface)
//! for the [Internet Computer](https://internetcomputer.org). Primarily used through [`ic-agent`](https://docs.rs/ic-agent).
#![warn(missing_docs, missing_debug_implementations)]
#![deny(elided_lifetimes_in_paths)]
use std::borrow::Cow;
use candid::Principal;
use ic_certification::Label;
pub use request_id::{to_request_id, RequestId, RequestIdError};
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use thiserror::Error;
mod request_id;
pub mod signed;
/// The authentication envelope, containing the contents and their signature. This struct can be passed to `Agent`'s
/// `*_signed` methods via [`encode_bytes`](Envelope::encode_bytes).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct Envelope<'a> {
/// The data that is signed by the caller.
pub content: Cow<'a, EnvelopeContent>,
/// The public key of the self-signing principal this request is from.
#[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]
pub sender_pubkey: Option<Vec<u8>>,
/// A cryptographic signature authorizing the request. Not necessarily made by `sender_pubkey`; when delegations are involved,
/// `sender_sig` is the tail of the delegation chain, and `sender_pubkey` is the head.
#[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]
pub sender_sig: Option<Vec<u8>>,
/// The chain of delegations connecting `sender_pubkey` to `sender_sig`, and in that order.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sender_delegation: Option<Vec<SignedDelegation>>,
}
impl Envelope<'_> {
/// Convert the authentication envelope to the format expected by the IC HTTP interface. The result can be passed to `Agent`'s `*_signed` methods.
pub fn encode_bytes(&self) -> Vec<u8> {
let mut serializer = serde_cbor::Serializer::new(Vec::new());
serializer.self_describe().unwrap();
self.serialize(&mut serializer)
.expect("infallible Envelope::serialize");
serializer.into_inner()
}
}
/// The content of an IC ingress message, not including any signature information.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "request_type", rename_all = "snake_case")]
pub enum EnvelopeContent {
/// A replicated call to a canister method, whether update or query.
Call {
/// A random series of bytes to uniquely identify this message.
#[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]
nonce: Option<Vec<u8>>,
/// A nanosecond timestamp after which this request is no longer valid.
ingress_expiry: u64,
/// The principal that is sending this request.
sender: Principal,
/// The ID of the canister to be called.
canister_id: Principal,
/// The name of the canister method to be called.
method_name: String,
/// The argument to pass to the canister method.
#[serde(with = "serde_bytes")]
arg: Vec<u8>,
},
/// A request for information from the [IC state tree](https://internetcomputer.org/docs/current/references/ic-interface-spec#state-tree).
ReadState {
/// A nanosecond timestamp after which this request is no longer valid.
ingress_expiry: u64,
/// The principal that is sending this request.
sender: Principal,
/// A list of paths within the state tree to fetch.
paths: Vec<Vec<Label>>,
},
/// An unreplicated call to a canister query method.
Query {
/// A nanosecond timestamp after which this request is no longer valid.
ingress_expiry: u64,
/// The principal that is sending this request.
sender: Principal,
/// The ID of the canister to be called.
canister_id: Principal,
/// The name of the canister method to be called.
method_name: String,
/// The argument to pass to the canister method.
#[serde(with = "serde_bytes")]
arg: Vec<u8>,
/// A random series of bytes to uniquely identify this message.
#[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]
nonce: Option<Vec<u8>>,
},
}
impl EnvelopeContent {
/// Returns the `ingress_expiry` field common to all variants.
pub fn ingress_expiry(&self) -> u64 {
let (Self::Call { ingress_expiry, .. }
| Self::Query { ingress_expiry, .. }
| Self::ReadState { ingress_expiry, .. }) = self;
*ingress_expiry
}
/// Returns the `sender` field common to all variants.
pub fn sender(&self) -> &Principal {
let (Self::Call { sender, .. }
| Self::Query { sender, .. }
| Self::ReadState { sender, .. }) = self;
sender
}
/// Converts the envelope content to a request ID.
///
/// Equivalent to calling [`to_request_id`], but infallible.
pub fn to_request_id(&self) -> RequestId {
to_request_id(self)
.expect("to_request_id::<EnvelopeContent> should always succeed but did not")
}
}
/// The response from a request to the `read_state` endpoint.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ReadStateResponse {
/// A [certificate](https://internetcomputer.org/docs/current/references/ic-interface-spec#certificate), containing
/// part of the system state tree as well as a signature to verify its authenticity.
/// Use the [`ic-certification`](https://docs.rs/ic-certification) crate to process it.
#[serde(with = "serde_bytes")]
pub certificate: Vec<u8>,
}
/// The parsed response from a request to the v3 `call` endpoint. A request to the `call` endpoint.
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum TransportCallResponse {
/// The IC responded with a certified response.
Replied {
/// The CBOR serialized certificate for the call response.
#[serde(with = "serde_bytes")]
certificate: Vec<u8>,
},
/// The replica responded with a non replicated rejection.
NonReplicatedRejection(RejectResponse),
/// The replica timed out the sync request, but forwarded the ingress message
/// to the canister. The request id should be used to poll for the response
/// The status of the request must be polled.
Accepted,
}
/// The response from a request to the `call` endpoint.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum CallResponse<Out> {
/// The call completed, and the response is available.
Response(Out),
/// The replica timed out the update call, and the request id should be used to poll for the response
/// using the `Agent::wait` method.
Poll(RequestId),
}
impl<Out> CallResponse<Out> {
/// Maps the inner value, if this is `Response`.
#[inline]
pub fn map<Out2>(self, f: impl FnOnce(Out) -> Out2) -> CallResponse<Out2> {
match self {
Self::Poll(p) => CallResponse::Poll(p),
Self::Response(r) => CallResponse::Response(f(r)),
}
}
}
impl<T, E> CallResponse<Result<T, E>> {
/// Extracts an inner `Result`, if this is `Response`.
#[inline]
pub fn transpose(self) -> Result<CallResponse<T>, E> {
match self {
Self::Poll(p) => Ok(CallResponse::Poll(p)),
Self::Response(r) => r.map(CallResponse::Response),
}
}
}
impl<T> CallResponse<Option<T>> {
/// Extracts an inner `Option`, if this is `Response`.
#[inline]
pub fn transpose(self) -> Option<CallResponse<T>> {
match self {
Self::Poll(p) => Some(CallResponse::Poll(p)),
Self::Response(r) => r.map(CallResponse::Response),
}
}
}
impl<T> CallResponse<(T,)> {
/// Extracts the inner value of a 1-tuple, if this is `Response`.
#[inline]
pub fn detuple(self) -> CallResponse<T> {
match self {
Self::Poll(p) => CallResponse::Poll(p),
Self::Response(r) => CallResponse::Response(r.0),
}
}
}
/// Possible responses to a query call.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum QueryResponse {
/// The request was successfully replied to.
Replied {
/// The reply from the canister.
reply: ReplyResponse,
/// The list of node signatures.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
signatures: Vec<NodeSignature>,
},
/// The request was rejected.
Rejected {
/// The rejection from the canister.
#[serde(flatten)]
reject: RejectResponse,
/// The list of node signatures.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
signatures: Vec<NodeSignature>,
},
}
impl QueryResponse {
/// Returns the signable form of the query response, as described in
/// [the spec](https://internetcomputer.org/docs/current/references/ic-interface-spec#http-query).
/// This is what is signed in the `signatures` fields.
pub fn signable(&self, request_id: RequestId, timestamp: u64) -> Vec<u8> {
#[derive(Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
enum QueryResponseSignable<'a> {
Replied {
reply: &'a ReplyResponse, // polyfill until hash_of_map is figured out
request_id: RequestId,
timestamp: u64,
},
Rejected {
reject_code: RejectCode,
reject_message: &'a String,
#[serde(default)]
error_code: Option<&'a String>,
request_id: RequestId,
timestamp: u64,
},
}
let response = match self {
Self::Replied { reply, .. } => QueryResponseSignable::Replied {
reply,
request_id,
timestamp,
},
Self::Rejected { reject, .. } => QueryResponseSignable::Rejected {
error_code: reject.error_code.as_ref(),
reject_code: reject.reject_code,
reject_message: &reject.reject_message,
request_id,
timestamp,
},
};
let mut signable = Vec::with_capacity(44);
signable.extend_from_slice(b"\x0Bic-response");
signable.extend_from_slice(to_request_id(&response).unwrap().as_slice());
signable
}
/// Helper function to get the signatures field present in both variants.
pub fn signatures(&self) -> &[NodeSignature] {
let (Self::Rejected { signatures, .. } | Self::Replied { signatures, .. }) = self;
signatures
}
}
/// An IC execution error received from the replica.
#[derive(Debug, Clone, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
pub struct RejectResponse {
/// The [reject code](https://internetcomputer.org/docs/current/references/ic-interface-spec#reject-codes) returned by the replica.
pub reject_code: RejectCode,
/// The rejection message.
pub reject_message: String,
/// The optional [error code](https://internetcomputer.org/docs/current/references/ic-interface-spec#error-codes) returned by the replica.
#[serde(default)]
pub error_code: Option<String>,
}
/// See the [interface spec](https://internetcomputer.org/docs/current/references/ic-interface-spec#reject-codes).
#[derive(
Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr, Ord, PartialOrd,
)]
#[repr(u8)]
pub enum RejectCode {
/// Fatal system error, retry unlikely to be useful
SysFatal = 1,
/// Transient system error, retry might be possible.
SysTransient = 2,
/// Invalid destination (e.g. canister/account does not exist)
DestinationInvalid = 3,
/// Explicit reject by the canister.
CanisterReject = 4,
/// Canister error (e.g., trap, no response)
CanisterError = 5,
}
impl TryFrom<u64> for RejectCode {
type Error = InvalidRejectCodeError;
fn try_from(value: u64) -> Result<Self, InvalidRejectCodeError> {
match value {
1 => Ok(RejectCode::SysFatal),
2 => Ok(RejectCode::SysTransient),
3 => Ok(RejectCode::DestinationInvalid),
4 => Ok(RejectCode::CanisterReject),
5 => Ok(RejectCode::CanisterError),
_ => Err(InvalidRejectCodeError(value)),
}
}
}
/// Error returned from `RejectCode::try_from`.
#[derive(Debug, Error)]
#[error("Invalid reject code {0}")]
pub struct InvalidRejectCodeError(pub u64);
/// The response of `/api/v3/canister/<effective_canister_id>/read_state` with `request_status` request type.
///
/// See [the HTTP interface specification](https://internetcomputer.org/docs/current/references/ic-interface-spec#http-call-overview) for more details.
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)]
pub enum RequestStatusResponse {
/// The status of the request is unknown.
Unknown,
/// The request has been received, and will probably get processed.
Received,
/// The request is currently being processed.
Processing,
/// The request has been successfully replied to.
Replied(ReplyResponse),
/// The request has been rejected.
Rejected(RejectResponse),
/// The call has been completed, and it has been long enough that the reply/reject data has been purged, but the call has not expired yet.
Done,
}
/// A successful reply to a canister call.
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct ReplyResponse {
/// The reply message, likely Candid-encoded.
#[serde(with = "serde_bytes")]
pub arg: Vec<u8>,
}
/// A delegation from one key to another.
///
/// If key A signs a delegation containing key B, then key B may be used to
/// authenticate as key A's corresponding principal(s).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Delegation {
/// The delegated-to key.
#[serde(with = "serde_bytes")]
pub pubkey: Vec<u8>,
/// A nanosecond timestamp after which this delegation is no longer valid.
pub expiration: u64,
/// If present, this delegation only applies to requests sent to one of these canisters.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub targets: Option<Vec<Principal>>,
}
const IC_REQUEST_DELEGATION_DOMAIN_SEPARATOR: &[u8] = b"\x1Aic-request-auth-delegation";
impl Delegation {
/// Returns the signable form of the delegation, by running it through [`to_request_id`]
/// and prepending `\x1Aic-request-auth-delegation` to the result.
pub fn signable(&self) -> Vec<u8> {
let hash = to_request_id(self).unwrap();
let mut bytes = Vec::with_capacity(59);
bytes.extend_from_slice(IC_REQUEST_DELEGATION_DOMAIN_SEPARATOR);
bytes.extend_from_slice(hash.as_slice());
bytes
}
}
/// A [`Delegation`] that has been signed by an [`Identity`](https://docs.rs/ic-agent/latest/ic_agent/trait.Identity.html).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SignedDelegation {
/// The signed delegation.
pub delegation: Delegation,
/// The signature for the delegation.
#[serde(with = "serde_bytes")]
pub signature: Vec<u8>,
}
/// A response signature from an individual node.
#[derive(Debug, Clone, Serialize, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
pub struct NodeSignature {
/// The timestamp that the signature was created at.
pub timestamp: u64,
/// The signature.
#[serde(with = "serde_bytes")]
pub signature: Vec<u8>,
/// The ID of the node.
pub identity: Principal,
}
/// A list of subnet metrics.
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct SubnetMetrics {
/// The number of canisters on this subnet.
pub num_canisters: u64,
/// The total size of the state in bytes taken by canisters on this subnet since this subnet was created.
pub canister_state_bytes: u64,
/// The total number of cycles consumed by all current and deleted canisters on this subnet.
#[serde(with = "map_u128")]
pub consumed_cycles_total: u128,
/// The total number of transactions processed on this subnet since this subnet was created.
pub update_transactions_total: u64,
}
mod map_u128 {
use serde::{
de::{Error, IgnoredAny, MapAccess, Visitor},
ser::SerializeMap,
Deserializer, Serializer,
};
use std::fmt;
pub fn serialize<S: Serializer>(val: &u128, s: S) -> Result<S::Ok, S::Error> {
let low = *val & u64::MAX as u128;
let high = *val >> 64;
let mut map = s.serialize_map(Some(2))?;
map.serialize_entry(&0, &low)?;
map.serialize_entry(&1, &(high != 0).then_some(high))?;
map.end()
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<u128, D::Error> {
d.deserialize_map(MapU128Visitor)
}
struct MapU128Visitor;
impl<'de> Visitor<'de> for MapU128Visitor {
type Value = u128;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a map of low and high")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let (_, low): (IgnoredAny, u64) = map
.next_entry()?
.ok_or_else(|| A::Error::missing_field("0"))?;
let opt: Option<(IgnoredAny, Option<u64>)> = map.next_entry()?;
let high = opt.and_then(|x| x.1).unwrap_or(0);
Ok(((high as u128) << 64) | low as u128)
}
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-transport-types/src/request_id.rs | ic-transport-types/src/request_id.rs | //! This module deals with computing Request IDs based on the content of a
//! message.
//!
//! A request ID is a SHA256 hash of the request's body. See
//! [Representation-independent Hashing of Structured Data](https://internetcomputer.org/docs/current/references/ic-interface-spec#hash-of-map)
//! from the IC spec for the method of calculation.
use error::RequestIdFromStringError;
use serde::{
de::{self, Error as _, Visitor},
ser::{
SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
SerializeTupleStruct, SerializeTupleVariant,
},
Deserialize, Deserializer, Serialize, Serializer,
};
use sha2::{Digest, Sha256};
use std::{
fmt::{self, Display, Formatter},
io::Write,
ops::Deref,
str::FromStr,
};
mod error;
#[doc(inline)]
pub use error::RequestIdError;
const IC_REQUEST_DOMAIN_SEPARATOR: &[u8; 11] = b"\x0Aic-request";
/// Type alias for a sha256 result (ie. a u256).
type Sha256Hash = [u8; 32];
/// Derive the request ID from a serializable data structure. This does not include the `ic-request` domain prefix.
///
/// See [Representation-independent Hashing of Structured Data](https://internetcomputer.org/docs/current/references/ic-interface-spec#hash-of-map)
/// from the IC spec for the method of calculation.
///
/// # Serialization
///
/// This section is only relevant if you're using this function to hash your own types.
///
/// * Per the spec, neither of bools, floats, or nulls are supported.
/// * Enum variants are serialized identically to `serde_json`.
/// * `Option::None` fields are omitted entirely.
/// * Byte strings are serialized *differently* to arrays of bytes -
/// use of `serde_bytes` is required for correctness.
pub fn to_request_id<'a, V>(value: &V) -> Result<RequestId, RequestIdError>
where
V: 'a + Serialize,
{
value
.serialize(RequestIdSerializer)
.transpose()
.unwrap_or(Err(RequestIdError::EmptySerializer))
.map(RequestId)
}
/// A Request ID.
#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct RequestId(Sha256Hash);
impl RequestId {
/// Creates a new `RequestId` from a SHA-256 hash.
pub fn new(from: &[u8; 32]) -> RequestId {
RequestId(*from)
}
/// Returns the signable form of the request ID, by prepending `"\x0Aic-request"` to it,
/// for use in [`Identity::sign`](https://docs.rs/ic-agent/latest/ic_agent/trait.Identity.html#tymethod.sign).
pub fn signable(&self) -> Vec<u8> {
let mut signable = Vec::with_capacity(43);
signable.extend_from_slice(IC_REQUEST_DOMAIN_SEPARATOR);
signable.extend_from_slice(&self.0);
signable
}
}
impl Deref for RequestId {
type Target = [u8; 32];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl FromStr for RequestId {
type Err = RequestIdFromStringError;
fn from_str(from: &str) -> Result<Self, Self::Err> {
let mut blob: [u8; 32] = [0; 32];
let vec = hex::decode(from).map_err(RequestIdFromStringError::FromHexError)?;
if vec.len() != 32 {
return Err(RequestIdFromStringError::InvalidSize(vec.len()));
}
blob.copy_from_slice(vec.as_slice());
Ok(RequestId::new(&blob))
}
}
impl From<RequestId> for String {
fn from(id: RequestId) -> String {
hex::encode(id.0)
}
}
impl Display for RequestId {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
hex::encode(self.0).fmt(f)
}
}
// Request ID hashing in all contexts is implemented as a serde Serializer to eliminate any special-casing.
struct RequestIdSerializer;
impl Serializer for RequestIdSerializer {
// Serde conveniently allows us to have each serialization operation return a value.
// Since this serializer is a hash function, this eliminates any need for a state-machine.
type Ok = Option<Sha256Hash>;
type Error = RequestIdError;
// We support neither floats nor bools nor nulls.
fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
Err(RequestIdError::UnsupportedTypeBool)
}
fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
Err(RequestIdError::UnsupportedTypeF32)
}
fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
Err(RequestIdError::UnsupportedTypeF64)
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
Err(RequestIdError::UnsupportedTypeUnit)
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
Err(RequestIdError::UnsupportedTypeUnitStruct)
}
// Ints are serialized using signed LEB128 encoding.
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
let mut arr = [0u8; 10];
let n = leb128::write::signed(&mut &mut arr[..], v).unwrap();
Ok(Some(Sha256::digest(&arr[..n]).into()))
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
// Uints are serialized using unsigned LEB128 encoding.
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
let mut arr = [0u8; 10];
let n = leb128::write::unsigned(&mut &mut arr[..], v).unwrap();
Ok(Some(Sha256::digest(&arr[..n]).into()))
}
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(v as u64)
}
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(v as u64)
}
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(v as u64)
}
// Bytes are serialized as-is.
fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
Ok(Some(Sha256::digest(v).into()))
}
// Strings are serialized as UTF-8 bytes.
fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
self.serialize_bytes(v.as_bytes())
}
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
let mut utf8 = [0u8; 4];
let str = v.encode_utf8(&mut utf8);
self.serialize_bytes(str.as_bytes())
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
self.serialize_str(variant)
}
// Newtypes, including Option::Some, are transparent.
fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> {
value.serialize(self)
}
fn serialize_newtype_struct<T: Serialize + ?Sized>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error> {
value.serialize(self)
}
// Fields containing None are omitted from the containing struct or array.
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
// Arrays, tuples, and tuple structs are treated identically.
type SerializeSeq = SeqSerializer;
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
self.serialize_tuple(len.unwrap_or(8))
}
type SerializeTuple = SeqSerializer;
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
Ok(SeqSerializer {
elems: Vec::with_capacity(len),
})
}
type SerializeTupleStruct = SeqSerializer;
fn serialize_tuple_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
self.serialize_tuple(len)
}
// Maps and structs are treated identically.
type SerializeMap = StructSerializer;
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
self.serialize_struct("", len.unwrap_or(8))
}
type SerializeStruct = StructSerializer;
fn serialize_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
Ok(StructSerializer {
fields: Vec::with_capacity(len),
field_name: <_>::default(),
})
}
// We apply serde_json's handling of complex variants. That is,
// the body is placed within a struct with one field, named the same thing as the variant.
fn serialize_newtype_variant<T: Serialize + ?Sized>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error> {
let mut s = self.serialize_struct(name, 1)?;
SerializeStruct::serialize_field(&mut s, variant, value)?;
SerializeStruct::end(s)
}
type SerializeTupleVariant = TupleVariantSerializer;
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
Ok(TupleVariantSerializer {
name: variant,
seq_ser: SeqSerializer {
elems: Vec::with_capacity(len),
},
})
}
type SerializeStructVariant = StructVariantSerializer;
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
Ok(StructVariantSerializer {
name: variant,
struct_ser: StructSerializer {
fields: Vec::with_capacity(len),
field_name: <_>::default(),
},
})
}
// We opt into the binary encoding for Principal and other such types.
fn is_human_readable(&self) -> bool {
false
}
// Optimized version of serialize_str for types that serialize by rendering themselves to strings.
fn collect_str<T: Display + ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> {
let mut hasher = Sha256::new();
write!(hasher, "{value}").map_err(|e| RequestIdError::CustomSerdeError(format!("{e}")))?;
Ok(Some(hasher.finalize().into()))
}
}
struct StructSerializer {
fields: Vec<(Sha256Hash, Sha256Hash)>,
field_name: Sha256Hash,
}
// Structs are hashed by hashing each key-value pair, sorting them, concatenating them, and hashing the result.
impl SerializeStruct for StructSerializer {
type Ok = Option<Sha256Hash>;
type Error = RequestIdError;
fn serialize_field<T: Serialize + ?Sized>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), Self::Error> {
if let Some(hash) = value.serialize(RequestIdSerializer)? {
self.fields
.push((Sha256::digest(key.as_bytes()).into(), hash));
}
Ok(())
}
fn end(mut self) -> Result<Self::Ok, Self::Error> {
self.fields.sort_unstable();
let mut hasher = Sha256::new();
for (key, value) in self.fields {
hasher.update(key);
hasher.update(value);
}
Ok(Some(hasher.finalize().into()))
}
}
impl SerializeMap for StructSerializer {
type Ok = Option<Sha256Hash>;
type Error = RequestIdError;
// This implementation naïvely assumes serialize_key is called before serialize_value, with no checks.
// SerializeMap's documentation states that such a case is 'allowed to panic or produce bogus results.'
fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> {
match key.serialize(RequestIdSerializer)? {
Some(hash) => {
self.field_name = hash;
Ok(())
}
None => Err(RequestIdError::KeyWasNone),
}
}
fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> {
if let Some(hash) = value.serialize(RequestIdSerializer)? {
self.fields.push((self.field_name, hash));
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
SerializeStruct::end(self)
}
}
struct SeqSerializer {
elems: Vec<Sha256Hash>,
}
// Sequences are hashed by hashing each element, concatenating the hashes, and hashing the result.
impl SerializeSeq for SeqSerializer {
type Ok = Option<Sha256Hash>;
type Error = RequestIdError;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> {
if let Some(hash) = value.serialize(RequestIdSerializer)? {
self.elems.push(hash);
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
let mut hasher = Sha256::new();
for elem in self.elems {
hasher.update(elem);
}
Ok(Some(hasher.finalize().into()))
}
}
impl SerializeTuple for SeqSerializer {
type Ok = Option<Sha256Hash>;
type Error = RequestIdError;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> {
SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
SerializeSeq::end(self)
}
}
impl SerializeTupleStruct for SeqSerializer {
type Ok = Option<Sha256Hash>;
type Error = RequestIdError;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> {
SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
SerializeSeq::end(self)
}
}
struct StructVariantSerializer {
name: &'static str,
struct_ser: StructSerializer,
}
// Struct variants are serialized like structs, but then placed within another struct
// under a key corresponding to the variant name.
impl SerializeStructVariant for StructVariantSerializer {
type Ok = Option<Sha256Hash>;
type Error = RequestIdError;
fn serialize_field<T: Serialize + ?Sized>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), Self::Error> {
SerializeStruct::serialize_field(&mut self.struct_ser, key, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
let Some(inner_struct_hash) = SerializeStruct::end(self.struct_ser)? else {
return Ok(None);
};
let outer_struct = StructSerializer {
field_name: <_>::default(),
fields: vec![(Sha256::digest(self.name).into(), inner_struct_hash)],
};
SerializeStruct::end(outer_struct)
}
}
struct TupleVariantSerializer {
name: &'static str,
seq_ser: SeqSerializer,
}
// Tuple variants are serialized like tuples, but then placed within another struct
// under a key corresponding to the variant name.
impl SerializeTupleVariant for TupleVariantSerializer {
type Ok = Option<Sha256Hash>;
type Error = RequestIdError;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> {
SerializeSeq::serialize_element(&mut self.seq_ser, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
let Some(inner_seq_hash) = SerializeSeq::end(self.seq_ser)? else {
return Ok(None);
};
let outer_struct = StructSerializer {
field_name: <_>::default(),
fields: vec![(Sha256::digest(self.name).into(), inner_seq_hash)],
};
SerializeStruct::end(outer_struct)
}
}
// can't use serde_bytes on by-value arrays
// these impls are effectively #[serde(with = "serde_bytes")]
impl Serialize for RequestId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
let mut text = [0u8; 64];
hex::encode_to_slice(self.0, &mut text).unwrap();
serializer.serialize_str(std::str::from_utf8(&text).unwrap())
} else {
serializer.serialize_bytes(&self.0)
}
}
}
impl<'de> Deserialize<'de> for RequestId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
if deserializer.is_human_readable() {
deserializer.deserialize_str(RequestIdVisitor)
} else {
deserializer.deserialize_bytes(RequestIdVisitor)
}
}
}
struct RequestIdVisitor;
impl<'de> Visitor<'de> for RequestIdVisitor {
type Value = RequestId;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a sha256 hash")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(RequestId::new(v.try_into().map_err(|_| {
E::custom(format_args!("must be 32 bytes long, was {}", v.len()))
})?))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: de::SeqAccess<'de>,
{
let mut arr = Sha256Hash::default();
for (i, byte) in arr.iter_mut().enumerate() {
*byte = seq.next_element()?.ok_or(A::Error::custom(format_args!(
"must be 32 bytes long, was {}",
i - 1
)))?;
}
if seq.next_element::<u8>()?.is_some() {
Err(A::Error::custom("must be 32 bytes long, was more"))
} else {
Ok(RequestId(arr))
}
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
if v.len() != 64 {
return Err(E::custom(format_args!(
"must be 32 bytes long, was {}",
v.len() / 2
)));
}
let mut arr = Sha256Hash::default();
hex::decode_to_slice(v, &mut arr).map_err(E::custom)?;
Ok(RequestId(arr))
}
}
#[cfg(test)]
mod tests {
use super::*;
use candid::Principal;
use std::{collections::HashMap, convert::TryFrom};
/// The actual example used in the public spec in the Request ID section.
#[test]
fn public_spec_example_old() {
#[derive(Serialize)]
struct PublicSpecExampleStruct {
request_type: &'static str,
canister_id: Principal,
method_name: &'static str,
#[serde(with = "serde_bytes")]
arg: &'static [u8],
sender: Option<Principal>,
ingress_expiry: Option<u64>,
}
// The current example
let current = PublicSpecExampleStruct {
request_type: "call",
sender: Some(Principal::anonymous()),
ingress_expiry: Some(1_685_570_400_000_000_000),
canister_id: Principal::from_slice(b"\x00\x00\x00\x00\x00\x00\x04\xD2"),
method_name: "hello",
arg: b"DIDL\x00\xFD*",
};
// Hash taken from the example on the public spec.
let request_id = to_request_id(¤t).unwrap();
assert_eq!(
hex::encode(request_id.0),
"1d1091364d6bb8a6c16b203ee75467d59ead468f523eb058880ae8ec80e2b101"
);
// A previous example
let old = PublicSpecExampleStruct {
request_type: "call",
canister_id: Principal::from_slice(b"\x00\x00\x00\x00\x00\x00\x04\xD2"), // 1234 in u64
method_name: "hello",
arg: b"DIDL\x00\xFD*",
ingress_expiry: None,
sender: None,
};
let request_id = to_request_id(&old).unwrap();
assert_eq!(
hex::encode(request_id.0),
"8781291c347db32a9d8c10eb62b710fce5a93be676474c42babc74c51858f94b"
);
}
/// The same example as above, except we use the `ApiClient` enum newtypes.
#[test]
fn public_spec_example_api_client() {
#[derive(Serialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "request_type")]
enum PublicSpec {
Call {
canister_id: Principal,
method_name: String,
#[serde(with = "serde_bytes")]
arg: Option<Vec<u8>>,
sender: Option<Principal>,
ingress_expiry: Option<u64>,
},
}
let current = PublicSpec::Call {
sender: Some(Principal::anonymous()),
ingress_expiry: Some(1_685_570_400_000_000_000),
canister_id: Principal::from_slice(b"\x00\x00\x00\x00\x00\x00\x04\xD2"),
method_name: "hello".to_owned(),
arg: Some(b"DIDL\x00\xFD*".to_vec()),
};
// Hash taken from the example on the public spec.
let request_id = to_request_id(¤t).unwrap();
assert_eq!(
hex::encode(request_id.0),
"1d1091364d6bb8a6c16b203ee75467d59ead468f523eb058880ae8ec80e2b101"
);
let old = PublicSpec::Call {
canister_id: Principal::from_slice(b"\x00\x00\x00\x00\x00\x00\x04\xD2"), // 1234 in u64
method_name: "hello".to_owned(),
arg: Some(b"DIDL\x00\xFD*".to_vec()),
ingress_expiry: None,
sender: None,
};
let request_id = to_request_id(&old).unwrap();
assert_eq!(
hex::encode(request_id.0),
"8781291c347db32a9d8c10eb62b710fce5a93be676474c42babc74c51858f94b"
);
}
/// A simple example with nested arrays and blobs
#[test]
#[allow(clippy::string_lit_as_bytes)]
fn array_example() {
#[derive(Serialize)]
struct NestedArraysExample {
sender: Principal,
paths: Vec<Vec<serde_bytes::ByteBuf>>,
}
let data = NestedArraysExample {
sender: Principal::try_from(&vec![0, 0, 0, 0, 0, 0, 0x04, 0xD2]).unwrap(), // 1234 in u64
paths: vec![
vec![],
vec![serde_bytes::ByteBuf::from("".as_bytes())],
vec![
serde_bytes::ByteBuf::from("hello".as_bytes()),
serde_bytes::ByteBuf::from("world".as_bytes()),
],
],
};
let request_id = to_request_id(&data).unwrap();
assert_eq!(
hex::encode(request_id.0),
"97d6f297aea699aec85d3377c7643ea66db810aba5c4372fbc2082c999f452dc"
);
/* The above was generated using ic-ref as follows:
~/dfinity/ic-ref/impl $ cabal repl ic-ref
Build profile: -w ghc-8.8.4 -O1
…
*Main> :set -XOverloadedStrings
*Main> :m + IC.HTTP.RequestId IC.HTTP.GenR
*Main IC.HTTP.RequestId IC.HTTP.GenR> import qualified Data.HashMap.Lazy as HM
*Main IC.HTTP.RequestId IC.HTTP.GenR HM> let input = GRec (HM.fromList [("sender", GBlob "\0\0\0\0\0\0\x04\xD2"), ("paths", GList [ GList [], GList [GBlob ""], GList [GBlob "hello", GBlob "world"]])])
*Main IC.HTTP.RequestId IC.HTTP.GenR HM> putStrLn $ IC.Types.prettyBlob (requestId input )
0x97d6f297aea699aec85d3377c7643ea66db810aba5c4372fbc2082c999f452dc
*/
}
/// A simple example with just an empty array
#[test]
fn array_example_empty_array() {
#[derive(Serialize)]
struct NestedArraysExample {
paths: Vec<Vec<serde_bytes::ByteBuf>>,
}
let data = NestedArraysExample { paths: vec![] };
let request_id = to_request_id(&data).unwrap();
assert_eq!(
hex::encode(request_id.0),
"99daa8c80a61e87ac1fdf9dd49e39963bfe4dafb2a45095ebf4cad72d916d5be"
);
/* The above was generated using ic-ref as follows:
~/dfinity/ic-ref/impl $ cabal repl ic-ref
Build profile: -w ghc-8.8.4 -O1
…
*Main> :set -XOverloadedStrings
*Main> :m + IC.HTTP.RequestId IC.HTTP.GenR
*Main IC.HTTP.RequestId IC.HTTP.GenR> import qualified Data.HashMap as HM
*Main IC.HTTP.RequestId IC.HTTP.GenR HM> let input = GRec (HM.fromList [("paths", GList [])])
*Main IC.HTTP.RequestId IC.HTTP.GenR HM> putStrLn $ IC.Types.prettyBlob (requestId input )
0x99daa8c80a61e87ac1fdf9dd49e39963bfe4dafb2a45095ebf4cad72d916d5be
*/
}
/// A simple example with an array that holds an empty array
#[test]
fn array_example_array_with_empty_array() {
#[derive(Serialize)]
struct NestedArraysExample {
paths: Vec<Vec<serde_bytes::ByteBuf>>,
}
let data = NestedArraysExample {
paths: vec![vec![]],
};
let request_id = to_request_id(&data).unwrap();
assert_eq!(
hex::encode(request_id.0),
"ea01a9c3d3830db108e0a87995ea0d4183dc9c6e51324e9818fced5c57aa64f5"
);
/* The above was generated using ic-ref as follows:
~/dfinity/ic-ref/impl $ cabal repl ic-ref
Build profile: -w ghc-8.8.4 -O1
…
*Main> :set -XOverloadedStrings
*Main> :m + IC.HTTP.RequestId IC.HTTP.GenR
*Main IC.HTTP.RequestId IC.HTTP.GenR> import qualified Data.HashMap.Lazy as HM
*Main IC.HTTP.RequestId IC.HTTP.GenR HM> let input = GRec (HM.fromList [("paths", GList [ GList [] ])])
*Main IC.HTTP.RequestId IC.HTTP.GenR HM> putStrLn $ IC.Types.prettyBlob (requestId input )
0xea01a9c3d3830db108e0a87995ea0d4183dc9c6e51324e9818fced5c57aa64f5
*/
}
#[test]
fn nested_map() {
#[derive(Serialize)]
struct Outer {
foo: Inner,
#[serde(with = "serde_bytes")]
bar: &'static [u8],
}
#[derive(Serialize)]
struct Inner {
baz: &'static str,
quux: u64,
}
let outer = Outer {
foo: Inner {
baz: "hello",
quux: 3,
},
bar: b"world",
};
assert_eq!(
hex::encode(to_request_id(&outer).unwrap().0),
"3d447339cc0c2b894ee215c8141770bf4b86c72b6c37d9873213a786ec7f9f31"
);
}
#[test]
fn structural_equivalence_collections() {
#[derive(Serialize)]
struct Maplike {
foo: i32,
}
let hashed_struct = to_request_id(&Maplike { foo: 73 }).unwrap();
assert_eq!(
hashed_struct,
to_request_id(&HashMap::from([("foo", 73_i32)])).unwrap(),
"map hashed identically to struct"
);
assert_eq!(
hex::encode(&hashed_struct[..]),
"7b3d327026e6bb5b4c13b898a6ca8fff6fd6838f44f6c27d9adf34542add75a0"
);
#[derive(Serialize)]
struct Seqlike(u8, u8, u8);
let hashed_array = to_request_id(&[1, 2, 3]).unwrap();
assert_eq!(
hashed_array,
to_request_id(&Seqlike(1, 2, 3)).unwrap(),
"tuple struct hashed identically to array"
);
assert_eq!(
hashed_array,
to_request_id(&(1, 2, 3)).unwrap(),
"tuple hashed identically to array"
);
assert_eq!(
hex::encode(&hashed_array[..]),
"2628a7cbda257cd0dc45779e43080e0a93037468fe270faae515f7c7941069e3"
);
}
#[test]
fn structural_equivalence_option() {
#[derive(Serialize)]
struct WithOpt {
x: u64,
y: Option<&'static str>,
}
#[derive(Serialize)]
struct WithoutOptSome {
x: u64,
y: &'static str,
}
#[derive(Serialize)]
struct WithoutOptNone {
x: u64,
}
let without_some = to_request_id(&WithoutOptSome { x: 3, y: "hello" }).unwrap();
assert_eq!(
without_some,
to_request_id(&WithOpt {
x: 3,
y: Some("hello")
})
.unwrap(),
"Option::Some(x) hashed identically to x"
);
assert_eq!(
hex::encode(&without_some[..]),
"f9532efd31fe55f5013d84fa4e1585b9a52e6cf82842adabe22fd3ac359c4143"
);
let without_none = to_request_id(&WithoutOptNone { x: 7_000_000 }).unwrap();
assert_eq!(
without_none,
to_request_id(&WithOpt {
x: 7_000_000,
y: None
})
.unwrap(),
"Option::None field deleted from struct"
);
assert_eq!(
hex::encode(&without_none[..]),
"fe4c9222ee2bffbc3ff7f25510d5b258adfa38a16740050a112ccc98eb886de5"
);
}
#[test]
fn structural_equivalence_variant() {
#[derive(Serialize)]
#[serde(rename_all = "snake_case")]
enum Complex {
Newtype(u64),
Tuple(&'static str, [u64; 2]),
Struct {
#[serde(with = "serde_bytes")]
field: &'static [u8],
},
}
#[derive(Serialize)]
struct NewtypeWrapper {
newtype: u64,
}
#[derive(Serialize)]
struct TupleWrapper {
tuple: (&'static str, [u64; 2]),
}
#[derive(Serialize)]
struct Inner {
#[serde(with = "serde_bytes")]
field: &'static [u8],
}
#[derive(Serialize)]
struct StructWrapper {
r#struct: Inner,
}
let newtype = to_request_id(&NewtypeWrapper { newtype: 673 }).unwrap();
assert_eq!(
newtype,
to_request_id(&Complex::Newtype(673)).unwrap(),
"newtype variant serialized as field"
);
assert_eq!(
hex::encode(&newtype[..]),
"87371cb37e4a28512e898a691ccbd8cd33efb902a5ac9ecf3a73e5e97f9c23f8"
);
let tuple = to_request_id(&TupleWrapper {
tuple: ("four", [5, 6]),
})
.unwrap();
assert_eq!(
tuple,
to_request_id(&Complex::Tuple("four", [5, 6])).unwrap(),
"tuple variant serialized as field"
);
assert_eq!(
hex::encode(&tuple[..]),
"729d2b57c442203f83b347ec644c8b38277076b5a9ebb3c2873ac64ddd793304"
);
let r#struct = to_request_id(&StructWrapper {
r#struct: Inner {
field: b"\x0Aic-request",
},
})
.unwrap();
assert_eq!(
r#struct,
to_request_id(&Complex::Struct {
field: b"\x0Aic-request"
})
.unwrap(),
"struct variant serialized as field"
);
assert_eq!(
hex::encode(&r#struct[..]),
"c2b325a8f7633df8054e9bd538ac8d26dc85cba4ad542cdbfca7109e1a60cf0c"
);
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-transport-types/src/signed.rs | ic-transport-types/src/signed.rs | //! Types representing signed messages.
use crate::request_id::RequestId;
use candid::Principal;
use serde::{Deserialize, Serialize};
/// A signed query request message. Produced by
/// [`QueryBuilder::sign`](https://docs.rs/ic-agent/latest/ic_agent/agent/struct.QueryBuilder.html#method.sign).
///
/// To submit this request, pass the `signed_query` field to [`Agent::query_signed`](https://docs.rs/ic-agent/latest/ic_agent/struct.Agent.html#method.query_signed).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SignedQuery {
/// The Unix timestamp that the request will expire at.
pub ingress_expiry: u64,
/// The principal ID of the caller.
pub sender: Principal,
/// The principal ID of the canister being called.
pub canister_id: Principal,
/// The name of the canister method being called.
pub method_name: String,
/// The argument blob to be passed to the method.
#[serde(with = "serde_bytes")]
pub arg: Vec<u8>,
/// The [effective canister ID](https://internetcomputer.org/docs/current/references/ic-interface-spec#http-effective-canister-id) of the destination.
pub effective_canister_id: Principal,
/// The CBOR-encoded [authentication envelope](https://internetcomputer.org/docs/current/references/ic-interface-spec#authentication) for the request.
/// This field can be passed to [`Agent::query_signed`](https://docs.rs/ic-agent/latest/ic_agent/struct.Agent.html#method.query_signed).
#[serde(with = "serde_bytes")]
pub signed_query: Vec<u8>,
/// A nonce to uniquely identify this query call.
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(with = "serde_bytes")]
pub nonce: Option<Vec<u8>>,
}
/// A signed update request message. Produced by
/// [`UpdateBuilder::sign`](https://docs.rs/ic-agent/latest/ic_agent/agent/struct.UpdateBuilder.html#method.sign).
///
/// To submit this request, pass the `signed_update` field to [`Agent::update_signed`](https://docs.rs/ic-agent/latest/ic_agent/struct.Agent.html#method.update_signed).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SignedUpdate {
/// A nonce to uniquely identify this update call.
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(with = "serde_bytes")]
pub nonce: Option<Vec<u8>>,
/// The Unix timestamp that the request will expire at.
pub ingress_expiry: u64,
/// The principal ID of the caller.
pub sender: Principal,
/// The principal ID of the canister being called.
pub canister_id: Principal,
/// The name of the canister method being called.
pub method_name: String,
/// The argument blob to be passed to the method.
#[serde(with = "serde_bytes")]
pub arg: Vec<u8>,
/// The [effective canister ID](https://internetcomputer.org/docs/current/references/ic-interface-spec#http-effective-canister-id) of the destination.
pub effective_canister_id: Principal,
#[serde(with = "serde_bytes")]
/// The CBOR-encoded [authentication envelope](https://internetcomputer.org/docs/current/references/ic-interface-spec#authentication) for the request.
/// This field can be passed to [`Agent::update_signed`](https://docs.rs/ic-agent/latest/ic_agent/struct.Agent.html#method.update_signed).
pub signed_update: Vec<u8>,
/// The request ID.
pub request_id: RequestId,
}
/// A signed request-status request message. Produced by
/// [`Agent::sign_request_status`](https://docs.rs/ic-agent/latest/ic_agent/agent/struct.Agent.html#method.sign_request_status).
///
/// To submit this request, pass the `signed_request_status` field to [`Agent::request_status_signed`](https://docs.rs/ic-agent/latest/ic_agent/struct.Agent.html#method.request_status_signed).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SignedRequestStatus {
/// The Unix timestamp that the request will expire at.
pub ingress_expiry: u64,
/// The principal ID of the caller.
pub sender: Principal,
/// The [effective canister ID](https://internetcomputer.org/docs/current/references/ic-interface-spec#http-effective-canister-id) of the destination.
pub effective_canister_id: Principal,
/// The request ID.
pub request_id: RequestId,
/// The CBOR-encoded [authentication envelope](https://internetcomputer.org/docs/current/references/ic-interface-spec#authentication) for the request.
/// This field can be passed to [`Agent::request_status_signed`](https://docs.rs/ic-agent/latest/ic_agent/struct.Agent.html#method.request_status_signed).
#[serde(with = "serde_bytes")]
pub signed_request_status: Vec<u8>,
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
#[test]
fn test_query_serde() {
let query = SignedQuery {
ingress_expiry: 1,
sender: Principal::management_canister(),
canister_id: Principal::management_canister(),
method_name: "greet".to_string(),
arg: vec![0, 1],
effective_canister_id: Principal::management_canister(),
signed_query: vec![0, 1, 2, 3],
nonce: None,
};
let serialized = serde_json::to_string(&query).unwrap();
let deserialized = serde_json::from_str::<SignedQuery>(&serialized);
assert!(deserialized.is_ok());
}
#[test]
fn test_update_serde() {
let update = SignedUpdate {
nonce: None,
ingress_expiry: 1,
sender: Principal::management_canister(),
canister_id: Principal::management_canister(),
method_name: "greet".to_string(),
arg: vec![0, 1],
effective_canister_id: Principal::management_canister(),
signed_update: vec![0, 1, 2, 3],
request_id: RequestId::new(&[0; 32]),
};
let serialized = serde_json::to_string(&update).unwrap();
let deserialized = serde_json::from_str::<SignedUpdate>(&serialized);
assert!(deserialized.is_ok());
}
#[test]
fn test_request_status_serde() {
let request_status = SignedRequestStatus {
ingress_expiry: 1,
sender: Principal::management_canister(),
effective_canister_id: Principal::management_canister(),
request_id: RequestId::new(&[0; 32]),
signed_request_status: vec![0, 1, 2, 3],
};
let serialized = serde_json::to_string(&request_status).unwrap();
let deserialized = serde_json::from_str::<SignedRequestStatus>(&serialized);
assert!(deserialized.is_ok());
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-transport-types/src/request_id/error.rs | ic-transport-types/src/request_id/error.rs | //! Error type for the `RequestId` calculation.
use thiserror::Error;
/// Errors from reading a `RequestId` from a string. This is not the same as
/// deserialization.
#[derive(Error, Debug)]
pub enum RequestIdFromStringError {
/// The string was not of a valid length.
#[error("Invalid string size: {0}. Must be even.")]
InvalidSize(usize),
/// The string was not in a valid hexadecimal format.
#[error("Error while decoding hex: {0}")]
FromHexError(hex::FromHexError),
}
/// An error during the calculation of the `RequestId`.
///
/// Since we use serde for serializing a data type into a hash, this has to support traits that
/// serde expects, such as Display
#[derive(Error, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub enum RequestIdError {
/// An unknown error occurred inside `serde`.
#[error("A custom error happened inside Serde: {0}")]
CustomSerdeError(String),
/// The serializer was not given any data.
#[error("Need to provide data to serialize")]
EmptySerializer,
/// A map was serialized with a key of `None`.
#[error("Struct serializer received a key of None")]
KeyWasNone,
/// The serializer received a `bool`, which it does not support.
#[error("Unsupported type: Bool")]
UnsupportedTypeBool,
/// The serializer received a `f32`, which it does not support.
#[error("Unsupported type: f32")]
UnsupportedTypeF32,
/// The serializer received a `f64`, which it does not support.
#[error("Unsupported type: f64")]
UnsupportedTypeF64,
/// The serializer received a `()`, which it does not support.
#[error("Unsupported type: ()")]
UnsupportedTypeUnit,
// Variants and complex types.
/// The serializer received an enum unit variant, which it does not support.
#[error("Unsupported type: unit struct")]
UnsupportedTypeUnitStruct,
}
impl serde::ser::Error for RequestIdError {
fn custom<T>(msg: T) -> Self
where
T: std::fmt::Display,
{
RequestIdError::CustomSerdeError(msg.to_string())
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/lib.rs | ic-agent/src/lib.rs | //! The `ic-agent` is a simple-to-use library that enables you to
//! build applications and interact with the [Internet Computer](https://internetcomputer.org)
//! in Rust. It serves as a Rust-based low-level backend for the
//! DFINITY Canister Software Development Kit (SDK) and the command-line execution environment
//! [`dfx`](https://internetcomputer.org/docs/current/developer-docs/setup/install).
//!
//! ## Overview
//! The `ic-agent` is a Rust crate that can connect directly to the Internet
//! Computer through the Internet Computer protocol (ICP).
//! The key software components of the ICP are broadly referred to as the
//! [replica](https://internetcomputer.org/docs/current/concepts/nodes-subnets).
//!
//! The agent is designed to be compatible with multiple versions of the
//! replica API, and to expose both low-level APIs for communicating with
//! Internet Computer protocol components like the replica and to provide
//! higher-level APIs for communicating with software applications deployed
//! as [canisters](https://internetcomputer.org/docs/current/concepts/canisters-code).
//!
//! ## Example
//! The following example illustrates how to use the Agent interface to send
//! a call to an Internet Computer's Ledger Canister to check the total ICP tokens supply.
//!
//! ```rust
//!use anyhow::{Context, Result};
//!use candid::{Decode, Nat};
//!use ic_agent::{export::Principal, Agent};
//!use url::Url;
//!
//!pub async fn create_agent(url: Url, use_mainnet: bool) -> Result<Agent> {
//! let agent = Agent::builder().with_url(url).build()?;
//! if !use_mainnet {
//! agent.fetch_root_key().await?;
//! }
//! Ok(agent)
//!}
//!
//!#[tokio::main]
//!async fn main() -> Result<()> {
//! // IC HTTP Gateway URL
//! let url = Url::parse("https://ic0.app").unwrap();
//! let agent = create_agent(url, true).await?;
//!
//! // ICP Ledger Canister ID
//! let canister_id = Principal::from_text("ryjl3-tyaaa-aaaaa-aaaba-cai")?;
//!
//! // Method: icrc1_total_supply (takes no arguments, returns nat)
//! let method_name = "icrc1_total_supply";
//!
//! // Encode empty Candid arguments
//! let args = candid::encode_args(())?;
//!
//! // Dispatch query call
//! let response = agent
//! .query(&canister_id, method_name)
//! .with_arg(args)
//! .call()
//! .await
//! .context("Failed to query icrc1_total_supply method.")?;
//!
//! // Decode the response as nat
//! let total_supply_nat =
//! Decode!(&response, Nat).context("Failed to decode total supply as nat.")?;
//!
//! println!("Total ICP Supply: {} ICP", total_supply_nat);
//!
//! Ok(())
//!}
//! ```
//! For more information about the Agent interface used in this example, see the
//! [Agent] documentation.
//!
//! ## References
//! For an introduction to the Internet Computer and the DFINITY Canister SDK,
//! see the following resources:
//!
//! - [How the IC Works](https://internetcomputer.org/docs/current/concepts/)
//! - [DFINITY Canister SDK](https://internetcomputer.org/docs/current/references/cli-reference/)
//!
//! The Internet Computer protocol and interface specifications are not
//! publicly available yet. When these specifications are made public and
//! generally available, additional details about the versions supported will
//! be available here.
#![warn(
missing_docs,
rustdoc::broken_intra_doc_links,
rustdoc::private_intra_doc_links
)]
#![cfg_attr(not(target_family = "wasm"), warn(clippy::future_not_send))]
#![cfg_attr(docsrs, feature(doc_cfg))]
#[macro_use]
mod util;
pub mod agent;
pub mod export;
pub mod identity;
use agent::response_authentication::LookupPath;
#[doc(inline)]
pub use agent::{agent_error, agent_error::AgentError, Agent, NonceFactory, NonceGenerator};
#[doc(inline)]
pub use ic_transport_types::{to_request_id, RequestId, RequestIdError, TransportCallResponse};
#[doc(inline)]
pub use identity::{Identity, Signature};
// Re-export from ic_certification for backward compatibility.
pub use ic_certification::{hash_tree, Certificate};
/// Looks up a value in the certificate's tree at the specified hash.
///
/// Returns the value if it was found; otherwise, errors with `LookupPathAbsent`, `LookupPathUnknown`, or `LookupPathError`.
pub fn lookup_value<P: LookupPath, Storage: AsRef<[u8]>>(
tree: &ic_certification::certificate::Certificate<Storage>,
path: P,
) -> Result<&[u8], AgentError> {
agent::response_authentication::lookup_value(&tree.tree, path)
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/util.rs | ic-agent/src/util.rs | #![allow(dead_code)]
use std::future::Future;
use std::time::Duration;
pub async fn sleep(d: Duration) {
#[cfg(not(all(target_family = "wasm", feature = "wasm-bindgen")))]
tokio::time::sleep(d).await;
#[cfg(all(target_family = "wasm", feature = "wasm-bindgen"))]
wasm_bindgen_futures::JsFuture::from(js_sys::Promise::new(&mut |rs, rj| {
use wasm_bindgen::{JsCast, UnwrapThrowExt};
let global = js_sys::global();
let res = if let Some(window) = global.dyn_ref::<web_sys::Window>() {
window.set_timeout_with_callback_and_timeout_and_arguments_0(&rs, d.as_millis() as _)
} else if let Some(worker) = global.dyn_ref::<web_sys::WorkerGlobalScope>() {
worker.set_timeout_with_callback_and_timeout_and_arguments_0(&rs, d.as_millis() as _)
} else {
panic!("global window or worker unavailable");
};
if let Err(e) = res {
rj.call1(&rj, &e).unwrap_throw();
}
}))
.await
.expect("unable to setTimeout");
#[cfg(all(target_family = "wasm", not(feature = "wasm-bindgen")))]
const _: () =
{ panic!("Using ic-agent from WASM requires enabling the `wasm-bindgen` feature") };
}
#[cfg(all(target_family = "wasm", feature = "wasm-bindgen"))]
pub fn spawn(f: impl Future<Output = ()> + 'static) {
wasm_bindgen_futures::spawn_local(f);
}
#[cfg(not(all(target_family = "wasm", feature = "wasm-bindgen")))]
pub fn spawn(f: impl Future<Output = ()> + Send + 'static) {
tokio::spawn(f);
}
macro_rules! log {
($name:ident, $($t:tt)*) => { #[cfg(feature = "tracing")] { tracing::$name!($($t)*) } };
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/export.rs | ic-agent/src/export.rs | //! A module to re-export types that are visible through the ic-agent API.
#[doc(inline)]
pub use candid::types::principal::{Principal, PrincipalError};
pub use reqwest;
pub use serde_bytes;
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/identity/prime256v1.rs | ic-agent/src/identity/prime256v1.rs | use crate::{agent::EnvelopeContent, export::Principal, Identity, Signature};
#[cfg(feature = "pem")]
use crate::identity::error::PemError;
use p256::{
ecdsa::{self, signature::Signer, SigningKey, VerifyingKey},
pkcs8::{Document, EncodePublicKey},
SecretKey,
};
#[cfg(feature = "pem")]
use std::path::Path;
use super::Delegation;
/// A cryptographic identity based on the Prime256v1 elliptic curve.
///
/// The caller will be represented via [`Principal::self_authenticating`], which contains the SHA-224 hash of the public key.
#[derive(Clone, Debug)]
pub struct Prime256v1Identity {
private_key: SigningKey,
_public_key: VerifyingKey,
der_encoded_public_key: Document,
}
impl Prime256v1Identity {
/// Creates an identity from a PEM file. Shorthand for calling `from_pem` with `std::fs::read`.
#[cfg(feature = "pem")]
pub fn from_pem_file<P: AsRef<Path>>(file_path: P) -> Result<Self, PemError> {
Self::from_pem(std::fs::read(file_path)?)
}
/// Creates an identity from a PEM certificate.
#[cfg(feature = "pem")]
pub fn from_pem<B: AsRef<[u8]>>(pem_contents: B) -> Result<Self, PemError> {
use sec1::{pem::PemLabel, EcPrivateKey};
const EC_PARAMETERS: &str = "EC PARAMETERS";
const PRIME256V1: &[u8] = b"\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07";
let contents = pem_contents.as_ref();
for pem in pem::parse_many(contents)? {
if pem.tag() == EC_PARAMETERS && pem.contents() != PRIME256V1 {
return Err(PemError::UnsupportedKeyCurve(
"prime256v1".to_string(),
pem.contents().to_vec(),
));
}
if pem.tag() != EcPrivateKey::PEM_LABEL {
continue;
}
let private_key =
SecretKey::from_sec1_der(pem.contents()).map_err(|_| pkcs8::Error::KeyMalformed)?;
return Ok(Self::from_private_key(private_key));
}
Err(pem::PemError::MissingData.into())
}
/// Creates an identity from a private key.
pub fn from_private_key(private_key: SecretKey) -> Self {
let public_key = private_key.public_key();
let der_encoded_public_key = public_key
.to_public_key_der()
.expect("Cannot DER encode prime256v1 public key.");
Self {
private_key: private_key.into(),
_public_key: public_key.into(),
der_encoded_public_key,
}
}
}
impl Identity for Prime256v1Identity {
fn sender(&self) -> Result<Principal, String> {
Ok(Principal::self_authenticating(
self.der_encoded_public_key.as_ref(),
))
}
fn public_key(&self) -> Option<Vec<u8>> {
Some(self.der_encoded_public_key.as_ref().to_vec())
}
fn sign(&self, content: &EnvelopeContent) -> Result<Signature, String> {
self.sign_arbitrary(&content.to_request_id().signable())
}
fn sign_delegation(&self, content: &Delegation) -> Result<Signature, String> {
self.sign_arbitrary(&content.signable())
}
fn sign_arbitrary(&self, content: &[u8]) -> Result<Signature, String> {
let ecdsa_sig: ecdsa::Signature = self
.private_key
.try_sign(content)
.map_err(|err| format!("Cannot create prime256v1 signature: {err}"))?;
let r = ecdsa_sig.r().as_ref().to_bytes();
let s = ecdsa_sig.s().as_ref().to_bytes();
let mut bytes = [0u8; 64];
if r.len() > 32 || s.len() > 32 {
return Err("Cannot create prime256v1 signature: malformed signature.".to_string());
}
bytes[(32 - r.len())..32].clone_from_slice(&r);
bytes[32 + (32 - s.len())..].clone_from_slice(&s);
let signature = Some(bytes.to_vec());
let public_key = self.public_key();
Ok(Signature {
public_key,
signature,
delegations: None,
})
}
}
#[cfg(feature = "pem")]
#[cfg(test)]
mod test {
use super::*;
use candid::Encode;
use p256::{
ecdsa::{signature::Verifier, Signature},
elliptic_curve::PrimeField,
FieldBytes, Scalar,
};
// WRONG_CURVE_IDENTITY_FILE is generated from the following command:
// > openssl ecparam -name secp160r2 -genkey
// it uses the secp160r2 curve instead of prime256v1 and should
// therefore be rejected by Prime256v1Identity when loading an identity
const WRONG_CURVE_IDENTITY_FILE: &str = "\
-----BEGIN EC PARAMETERS-----
BgUrgQQAHg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MFACAQEEFI9cF6zXxMKhtjn1gBD7AHPbzehfoAcGBSuBBAAeoSwDKgAEh5NXszgR
oGSXVWaGxcQhQWlFG4pbnOG+93xXzfRD7eKWOdmun2bKxQ==
-----END EC PRIVATE KEY-----
";
// WRONG_CURVE_IDENTITY_FILE_NO_PARAMS is generated from the following command:
// > openssl ecparam -name secp160r2 -genkey -noout
// it uses the secp160r2 curve instead of prime256v1 and should
// therefore be rejected by Prime256v1Identity when loading an identity
const WRONG_CURVE_IDENTITY_FILE_NO_PARAMS: &str = "\
-----BEGIN EC PRIVATE KEY-----
MFACAQEEFI9cF6zXxMKhtjn1gBD7AHPbzehfoAcGBSuBBAAeoSwDKgAEh5NXszgR
oGSXVWaGxcQhQWlFG4pbnOG+93xXzfRD7eKWOdmun2bKxQ==
-----END EC PRIVATE KEY-----
";
// IDENTITY_FILE was generated from the the following commands:
// > openssl ecparam -name prime256v1 -genkey -noout -out identity.pem
// > cat identity.pem
const IDENTITY_FILE: &str = "\
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIL1ybmbwx+uKYsscOZcv71MmKhrNqfPP0ke1unET5AY4oAoGCCqGSM49
AwEHoUQDQgAEUbbZV4NerZTPWfbQ749/GNLu8TaH8BUS/I7/+ipsu+MPywfnBFIZ
Sks4xGbA/ZbazsrMl4v446U5UIVxCGGaKw==
-----END EC PRIVATE KEY-----
";
// DER_ENCODED_PUBLIC_KEY was generated from the the following commands:
// > openssl ec -in identity.pem -pubout -outform DER -out public.der
// > hexdump -ve '1/1 "%.2x"' public.der
const DER_ENCODED_PUBLIC_KEY: &str = "3059301306072a8648ce3d020106082a8648ce3d0301070342000451b6d957835ead94cf59f6d0ef8f7f18d2eef13687f01512fc8efffa2a6cbbe30fcb07e70452194a4b38c466c0fd96dacecacc978bf8e3a53950857108619a2b";
#[test]
#[should_panic(expected = "UnsupportedKeyCurve")]
fn test_prime256v1_reject_wrong_curve() {
Prime256v1Identity::from_pem(WRONG_CURVE_IDENTITY_FILE.as_bytes()).unwrap();
}
#[test]
#[should_panic(expected = "KeyMalformed")]
fn test_prime256v1_reject_wrong_curve_no_id() {
Prime256v1Identity::from_pem(WRONG_CURVE_IDENTITY_FILE_NO_PARAMS.as_bytes()).unwrap();
}
#[test]
fn test_prime256v1_public_key() {
// Create a prime256v1 identity from a PEM file.
let identity = Prime256v1Identity::from_pem(IDENTITY_FILE.as_bytes())
.expect("Cannot create prime256v1 identity from PEM file.");
// Assert the DER-encoded prime256v1 public key matches what we would expect.
assert!(DER_ENCODED_PUBLIC_KEY == hex::encode(identity.der_encoded_public_key));
}
#[test]
fn test_prime256v1_signature() {
// Create a prime256v1 identity from a PEM file.
let identity = Prime256v1Identity::from_pem(IDENTITY_FILE.as_bytes())
.expect("Cannot create prime256v1 identity from PEM file.");
// Create a prime256v1 signature for a hello-world canister.
let message = EnvelopeContent::Call {
nonce: None,
ingress_expiry: 0,
sender: identity.sender().unwrap(),
canister_id: "bkyz2-fmaaa-aaaaa-qaaaq-cai".parse().unwrap(),
method_name: "greet".to_string(),
arg: Encode!(&"world").unwrap(),
};
let signature = identity
.sign(&message)
.expect("Cannot create prime256v1 signature.")
.signature
.expect("Cannot find prime256v1 signature bytes.");
// Import the prime256v1 signature.
let r: Scalar = Option::from(Scalar::from_repr(*FieldBytes::from_slice(
&signature[0..32],
)))
.expect("Cannot extract r component from prime256v1 signature bytes.");
let s: Scalar = Option::from(Scalar::from_repr(*FieldBytes::from_slice(&signature[32..])))
.expect("Cannot extract s component from prime256v1 signature bytes.");
let ecdsa_sig = Signature::from_scalars(r, s)
.expect("Cannot create prime256v1 signature from r and s components.");
// Assert the prime256v1 signature is valid.
identity
._public_key
.verify(&message.to_request_id().signable(), &ecdsa_sig)
.expect("Cannot verify prime256v1 signature.");
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/identity/delegated.rs | ic-agent/src/identity/delegated.rs | use candid::Principal;
use der::{Decode, SliceReader};
use ecdsa::signature::Verifier;
use k256::Secp256k1;
use p256::NistP256;
use pkcs8::{spki::SubjectPublicKeyInfoRef, AssociatedOid, ObjectIdentifier};
use sec1::{EcParameters, EncodedPoint};
use crate::{agent::EnvelopeContent, Signature};
use super::{error::DelegationError, Delegation, Identity, SignedDelegation};
/// An identity that has been delegated the authority to authenticate as a different principal.
pub struct DelegatedIdentity {
to: Box<dyn Identity>,
chain: Vec<SignedDelegation>,
from_key: Vec<u8>,
}
impl DelegatedIdentity {
/// Creates a delegated identity that signs using `to`, for the principal corresponding to the public key `from_key`.
///
/// `chain` must be a list of delegations connecting `from_key` to `to.public_key()`, and in that order;
/// otherwise, this function will return an error.
pub fn new(
from_key: Vec<u8>,
to: Box<dyn Identity>,
chain: Vec<SignedDelegation>,
) -> Result<Self, DelegationError> {
let mut last_verified = &from_key;
for delegation in &chain {
let spki = SubjectPublicKeyInfoRef::decode(
&mut SliceReader::new(&last_verified[..]).map_err(|_| DelegationError::Parse)?,
)
.map_err(|_| DelegationError::Parse)?;
if spki.algorithm.oid == elliptic_curve::ALGORITHM_OID {
let Some(params) = spki.algorithm.parameters else {
return Err(DelegationError::UnknownAlgorithm);
};
let params = params
.decode_as::<EcParameters>()
.map_err(|_| DelegationError::Parse)?;
let curve = params
.named_curve()
.ok_or(DelegationError::UnknownAlgorithm)?;
if curve == Secp256k1::OID {
let pt = EncodedPoint::from_bytes(spki.subject_public_key.raw_bytes())
.map_err(|_| DelegationError::Parse)?;
let vk = k256::ecdsa::VerifyingKey::from_encoded_point(&pt)
.map_err(|_| DelegationError::Parse)?;
let sig = k256::ecdsa::Signature::try_from(&delegation.signature[..])
.map_err(|_| DelegationError::Parse)?;
vk.verify(&delegation.delegation.signable(), &sig)
.map_err(|_| DelegationError::BrokenChain {
from: last_verified.clone(),
to: Some(delegation.delegation.clone()),
})?;
} else if curve == NistP256::OID {
let pt = EncodedPoint::from_bytes(spki.subject_public_key.raw_bytes())
.map_err(|_| DelegationError::Parse)?;
let vk = p256::ecdsa::VerifyingKey::from_encoded_point(&pt)
.map_err(|_| DelegationError::Parse)?;
let sig = p256::ecdsa::Signature::try_from(&delegation.signature[..])
.map_err(|_| DelegationError::Parse)?;
vk.verify(&delegation.delegation.signable(), &sig)
.map_err(|_| DelegationError::BrokenChain {
from: last_verified.clone(),
to: Some(delegation.delegation.clone()),
})?;
} else {
return Err(DelegationError::UnknownAlgorithm);
}
} else if spki.algorithm.oid == ObjectIdentifier::new_unwrap("1.3.101.112") {
let vk =
ic_ed25519::PublicKey::deserialize_raw(spki.subject_public_key.raw_bytes())
.map_err(|_| DelegationError::Parse)?;
vk.verify_signature(&delegation.delegation.signable(), &delegation.signature[..])
.map_err(|_| DelegationError::BrokenChain {
from: last_verified.clone(),
to: Some(delegation.delegation.clone()),
})?;
} else {
return Err(DelegationError::UnknownAlgorithm);
}
last_verified = &delegation.delegation.pubkey;
}
let delegated_principal = Principal::self_authenticating(last_verified);
if delegated_principal != to.sender().map_err(DelegationError::IdentityError)? {
return Err(DelegationError::BrokenChain {
from: last_verified.clone(),
to: None,
});
}
Ok(Self::new_unchecked(from_key, to, chain))
}
/// Creates a delegated identity that signs using `to`, for the principal corresponding to the public key `from_key`.
///
/// `chain` must be a list of delegations connecting `from_key` to `to.public_key()`, and in that order;
/// otherwise, the replica will reject this delegation when used as an identity.
pub fn new_unchecked(
from_key: Vec<u8>,
to: Box<dyn Identity>,
chain: Vec<SignedDelegation>,
) -> Self {
Self {
to,
chain,
from_key,
}
}
fn chain_signature(&self, mut sig: Signature) -> Signature {
sig.public_key = self.public_key();
sig.delegations
.get_or_insert(vec![])
.extend(self.chain.iter().cloned());
sig
}
}
impl Identity for DelegatedIdentity {
fn sender(&self) -> Result<Principal, String> {
Ok(Principal::self_authenticating(&self.from_key))
}
fn public_key(&self) -> Option<Vec<u8>> {
Some(self.from_key.clone())
}
fn sign(&self, content: &EnvelopeContent) -> Result<Signature, String> {
self.to.sign(content).map(|sig| self.chain_signature(sig))
}
fn sign_delegation(&self, content: &Delegation) -> Result<Signature, String> {
self.to
.sign_delegation(content)
.map(|sig| self.chain_signature(sig))
}
fn sign_arbitrary(&self, content: &[u8]) -> Result<Signature, String> {
self.to
.sign_arbitrary(content)
.map(|sig| self.chain_signature(sig))
}
fn delegation_chain(&self) -> Vec<SignedDelegation> {
let mut chain = self.to.delegation_chain();
chain.extend(self.chain.iter().cloned());
chain
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/identity/anonymous.rs | ic-agent/src/identity/anonymous.rs | use crate::{agent::EnvelopeContent, export::Principal, identity::Identity, Signature};
/// The anonymous identity.
///
/// The caller will be represented as [`Principal::anonymous`], or `2vxsx-fae`.
#[derive(Debug, Copy, Clone)]
pub struct AnonymousIdentity;
impl Identity for AnonymousIdentity {
fn sender(&self) -> Result<Principal, String> {
Ok(Principal::anonymous())
}
fn public_key(&self) -> Option<Vec<u8>> {
None
}
fn sign(&self, _: &EnvelopeContent) -> Result<Signature, String> {
Ok(Signature {
signature: None,
public_key: None,
delegations: None,
})
}
fn sign_arbitrary(&self, _: &[u8]) -> Result<Signature, String> {
Ok(Signature {
public_key: None,
signature: None,
delegations: None,
})
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/identity/error.rs | ic-agent/src/identity/error.rs | use ic_transport_types::Delegation;
use thiserror::Error;
/// An error happened while reading a PEM file.
#[cfg(feature = "pem")]
#[derive(Error, Debug)]
pub enum PemError {
/// An error occurred with disk I/O.
#[error(transparent)]
Io(#[from] std::io::Error),
/// An unsupported curve was detected
#[error("Only {0} curve is supported: {1:?}")]
UnsupportedKeyCurve(String, Vec<u8>),
/// An error occurred while reading the file in PEM format.
#[cfg(feature = "pem")]
#[error("An error occurred while reading the file: {0}")]
PemError(#[from] pem::PemError),
/// An error occurred while reading the file in DER format.
#[cfg(feature = "pem")]
#[error("An error occurred while reading the file: {0}")]
DerError(#[from] der::Error),
/// The private key is invalid.
#[error("Invalid private key: {0}")]
InvalidPrivateKey(String),
/// The key was rejected by k256.
#[error("A key was rejected by k256: {0}")]
ErrorStack(#[from] k256::pkcs8::Error),
}
/// An error occurred constructing a [`DelegatedIdentity`](super::delegated::DelegatedIdentity).
#[derive(Error, Debug)]
pub enum DelegationError {
/// Parsing error in delegation bytes.
#[error("A delegation could not be parsed")]
Parse,
/// A key in the chain did not match the signature of the next chain link.
#[error("A link was missing in the delegation chain")]
BrokenChain {
/// The key that should have matched the next delegation
from: Vec<u8>,
/// The delegation that didn't match, or `None` if the `Identity` didn't match
to: Option<Delegation>,
},
/// A key with an unknown algorithm was used. The IC supports Ed25519, secp256k1, and prime256v1, and in ECDSA the curve must be specified.
#[error("The delegation chain contained a key with an unknown algorithm")]
UnknownAlgorithm,
/// One of `Identity`'s functions returned an error.
#[error("A delegated-to identity encountered an error: {0}")]
IdentityError(String),
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/identity/mod.rs | ic-agent/src/identity/mod.rs | //! Types and traits dealing with identity across the Internet Computer.
use std::sync::Arc;
use crate::{agent::EnvelopeContent, export::Principal};
pub(crate) mod anonymous;
pub(crate) mod basic;
pub(crate) mod delegated;
pub(crate) mod error;
pub(crate) mod prime256v1;
pub(crate) mod secp256k1;
#[doc(inline)]
pub use anonymous::AnonymousIdentity;
#[doc(inline)]
pub use basic::BasicIdentity;
#[doc(inline)]
pub use delegated::DelegatedIdentity;
#[doc(inline)]
pub use error::DelegationError;
#[doc(inline)]
pub use ic_transport_types::{Delegation, SignedDelegation};
#[doc(inline)]
pub use prime256v1::Prime256v1Identity;
#[doc(inline)]
pub use secp256k1::Secp256k1Identity;
#[cfg(feature = "pem")]
#[doc(inline)]
pub use error::PemError;
/// A cryptographic signature, signed by an [Identity].
#[derive(Clone, Debug)]
pub struct Signature {
/// This is the DER-encoded public key.
pub public_key: Option<Vec<u8>>,
/// The signature bytes.
pub signature: Option<Vec<u8>>,
/// A list of delegations connecting `public_key` to the key that signed `signature`, and in that order.
pub delegations: Option<Vec<SignedDelegation>>,
}
/// An `Identity` produces [`Signatures`](Signature) for requests or delegations. It knows or
/// represents the [`Principal`] of the sender.
///
/// [`Agents`](crate::Agent) are assigned a single `Identity` object, but there can be multiple
/// identities used.
pub trait Identity: Send + Sync {
/// Returns a sender, ie. the Principal ID that is used to sign a request.
///
/// Only one sender can be used per request.
fn sender(&self) -> Result<Principal, String>;
/// Produce the public key commonly returned in [`Signature`].
///
/// Should only return `None` if `sign` would do the same.
fn public_key(&self) -> Option<Vec<u8>>;
/// Sign a request ID derived from a content map.
///
/// Implementors should call `content.to_request_id().signable()` for the actual bytes that need to be signed.
fn sign(&self, content: &EnvelopeContent) -> Result<Signature, String>;
/// Sign a delegation to let another key be used to authenticate [`sender`](Identity::sender).
///
/// Not all `Identity` implementations support this operation, though all `ic-agent` implementations other than `AnonymousIdentity` do.
///
/// Implementors should call `content.signable()` for the actual bytes that need to be signed.
fn sign_delegation(&self, content: &Delegation) -> Result<Signature, String> {
let _ = content; // silence unused warning
Err(String::from("unsupported"))
}
/// Sign arbitrary bytes.
///
/// Not all `Identity` implementations support this operation, though all `ic-agent` implementations do.
fn sign_arbitrary(&self, content: &[u8]) -> Result<Signature, String> {
let _ = content; // silence unused warning
Err(String::from("unsupported"))
}
/// A list of signed delegations connecting [`sender`](Identity::sender)
/// to [`public_key`](Identity::public_key), and in that order.
fn delegation_chain(&self) -> Vec<SignedDelegation> {
vec![]
}
}
macro_rules! delegating_impl {
($implementor:ty, $name:ident => $self_expr:expr) => {
impl Identity for $implementor {
fn sender(&$name) -> Result<Principal, String> {
$self_expr.sender()
}
fn public_key(&$name) -> Option<Vec<u8>> {
$self_expr.public_key()
}
fn sign(&$name, content: &EnvelopeContent) -> Result<Signature, String> {
$self_expr.sign(content)
}
fn sign_delegation(&$name, content: &Delegation) -> Result<Signature, String> {
$self_expr.sign_delegation(content)
}
fn sign_arbitrary(&$name, content: &[u8]) -> Result<Signature, String> {
$self_expr.sign_arbitrary(content)
}
fn delegation_chain(&$name) -> Vec<SignedDelegation> {
$self_expr.delegation_chain()
}
}
};
}
delegating_impl!(Box<dyn Identity>, self => **self);
delegating_impl!(Arc<dyn Identity>, self => **self);
delegating_impl!(&dyn Identity, self => *self);
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/identity/secp256k1.rs | ic-agent/src/identity/secp256k1.rs | use crate::{agent::EnvelopeContent, export::Principal, Identity, Signature};
#[cfg(feature = "pem")]
use crate::identity::error::PemError;
use k256::{
ecdsa::{self, signature::Signer, SigningKey, VerifyingKey},
pkcs8::{Document, EncodePublicKey},
SecretKey,
};
#[cfg(feature = "pem")]
use std::path::Path;
use super::Delegation;
/// A cryptographic identity based on the Secp256k1 elliptic curve.
///
/// The caller will be represented via [`Principal::self_authenticating`], which contains the SHA-224 hash of the public key.
#[derive(Clone, Debug)]
pub struct Secp256k1Identity {
private_key: SigningKey,
_public_key: VerifyingKey,
der_encoded_public_key: Document,
}
impl Secp256k1Identity {
/// Creates an identity from a PEM file. Shorthand for calling `from_pem` with `std::fs::read`.
#[cfg(feature = "pem")]
pub fn from_pem_file<P: AsRef<Path>>(file_path: P) -> Result<Self, PemError> {
Self::from_pem(std::fs::read(file_path)?)
}
/// Creates an identity from a PEM certificate.
#[cfg(feature = "pem")]
pub fn from_pem<B: AsRef<[u8]>>(pem_contents: B) -> Result<Self, PemError> {
use sec1::{pem::PemLabel, EcPrivateKey};
const EC_PARAMETERS: &str = "EC PARAMETERS";
const SECP256K1: &[u8] = b"\x06\x05\x2b\x81\x04\x00\x0a";
let contents = pem_contents.as_ref();
for pem in pem::parse_many(contents)? {
if pem.tag() == EC_PARAMETERS && pem.contents() != SECP256K1 {
return Err(PemError::UnsupportedKeyCurve(
"secp256k1".to_string(),
pem.contents().to_vec(),
));
}
if pem.tag() != EcPrivateKey::PEM_LABEL {
continue;
}
let private_key =
SecretKey::from_sec1_der(pem.contents()).map_err(|_| pkcs8::Error::KeyMalformed)?;
return Ok(Self::from_private_key(private_key));
}
Err(pem::PemError::MissingData.into())
}
/// Creates an identity from a private key.
pub fn from_private_key(private_key: SecretKey) -> Self {
let public_key = private_key.public_key();
let der_encoded_public_key = public_key
.to_public_key_der()
.expect("Cannot DER encode secp256k1 public key.");
Self {
private_key: private_key.into(),
_public_key: public_key.into(),
der_encoded_public_key,
}
}
}
impl Identity for Secp256k1Identity {
fn sender(&self) -> Result<Principal, String> {
Ok(Principal::self_authenticating(
self.der_encoded_public_key.as_ref(),
))
}
fn public_key(&self) -> Option<Vec<u8>> {
Some(self.der_encoded_public_key.as_ref().to_vec())
}
fn sign(&self, content: &EnvelopeContent) -> Result<Signature, String> {
self.sign_arbitrary(&content.to_request_id().signable())
}
fn sign_delegation(&self, content: &Delegation) -> Result<Signature, String> {
self.sign_arbitrary(&content.signable())
}
fn sign_arbitrary(&self, content: &[u8]) -> Result<Signature, String> {
let ecdsa_sig: ecdsa::Signature = self
.private_key
.try_sign(content)
.map_err(|err| format!("Cannot create secp256k1 signature: {err}"))?;
let r = ecdsa_sig.r().as_ref().to_bytes();
let s = ecdsa_sig.s().as_ref().to_bytes();
let mut bytes = [0u8; 64];
if r.len() > 32 || s.len() > 32 {
return Err("Cannot create secp256k1 signature: malformed signature.".to_string());
}
bytes[(32 - r.len())..32].clone_from_slice(&r);
bytes[32 + (32 - s.len())..].clone_from_slice(&s);
let signature = Some(bytes.to_vec());
let public_key = self.public_key();
Ok(Signature {
public_key,
signature,
delegations: None,
})
}
}
#[cfg(feature = "pem")]
#[cfg(test)]
mod test {
use super::*;
use candid::Encode;
use k256::{
ecdsa::{signature::Verifier, Signature},
elliptic_curve::PrimeField,
FieldBytes, Scalar,
};
// WRONG_CURVE_IDENTITY_FILE is generated from the following command:
// > openssl ecparam -name secp160r2 -genkey
// it uses hte secp160r2 curve instead of secp256k1 and should
// therefore be rejected by Secp256k1Identity when loading an identity
const WRONG_CURVE_IDENTITY_FILE: &str = "-----BEGIN EC PARAMETERS-----
BgUrgQQAHg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MFACAQEEFI9cF6zXxMKhtjn1gBD7AHPbzehfoAcGBSuBBAAeoSwDKgAEh5NXszgR
oGSXVWaGxcQhQWlFG4pbnOG+93xXzfRD7eKWOdmun2bKxQ==
-----END EC PRIVATE KEY-----
";
// WRONG_CURVE_IDENTITY_FILE_NO_PARAMS is generated from the following command:
// > openssl ecparam -name secp160r2 -genkey -noout
// it uses hte secp160r2 curve instead of secp256k1 and should
// therefore be rejected by Secp256k1Identity when loading an identity
const WRONG_CURVE_IDENTITY_FILE_NO_PARAMS: &str = "-----BEGIN EC PRIVATE KEY-----
MFACAQEEFI9cF6zXxMKhtjn1gBD7AHPbzehfoAcGBSuBBAAeoSwDKgAEh5NXszgR
oGSXVWaGxcQhQWlFG4pbnOG+93xXzfRD7eKWOdmun2bKxQ==
-----END EC PRIVATE KEY-----
";
// IDENTITY_FILE was generated from the the following commands:
// > openssl ecparam -name secp256k1 -genkey -noout -out identity.pem
// > cat identity.pem
const IDENTITY_FILE: &str = "-----BEGIN EC PARAMETERS-----
BgUrgQQACg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIAgy7nZEcVHkQ4Z1Kdqby8SwyAiyKDQmtbEHTIM+WNeBoAcGBSuBBAAK
oUQDQgAEgO87rJ1ozzdMvJyZQ+GABDqUxGLvgnAnTlcInV3NuhuPv4O3VGzMGzeB
N3d26cRxD99TPtm8uo2OuzKhSiq6EQ==
-----END EC PRIVATE KEY-----
";
// DER_ENCODED_PUBLIC_KEY was generated from the the following commands:
// > openssl ec -in identity.pem -pubout -outform DER -out public.der
// > hexdump -ve '1/1 "%.2x"' public.der
const DER_ENCODED_PUBLIC_KEY: &str = "3056301006072a8648ce3d020106052b8104000a0342000480ef3bac9d68cf374cbc9c9943e180043a94c462ef8270274e57089d5dcdba1b8fbf83b7546ccc1b3781377776e9c4710fdf533ed9bcba8d8ebb32a14a2aba11";
#[test]
#[should_panic(expected = "UnsupportedKeyCurve")]
fn test_secp256k1_reject_wrong_curve() {
Secp256k1Identity::from_pem(WRONG_CURVE_IDENTITY_FILE.as_bytes()).unwrap();
}
#[test]
#[should_panic(expected = "KeyMalformed")]
fn test_secp256k1_reject_wrong_curve_no_id() {
Secp256k1Identity::from_pem(WRONG_CURVE_IDENTITY_FILE_NO_PARAMS.as_bytes()).unwrap();
}
#[test]
fn test_secp256k1_public_key() {
// Create a secp256k1 identity from a PEM file.
let identity = Secp256k1Identity::from_pem(IDENTITY_FILE.as_bytes())
.expect("Cannot create secp256k1 identity from PEM file.");
// Assert the DER-encoded secp256k1 public key matches what we would expect.
assert!(DER_ENCODED_PUBLIC_KEY == hex::encode(identity.der_encoded_public_key));
}
#[test]
fn test_secp256k1_signature() {
// Create a secp256k1 identity from a PEM file.
let identity = Secp256k1Identity::from_pem(IDENTITY_FILE.as_bytes())
.expect("Cannot create secp256k1 identity from PEM file.");
// Create a secp256k1 signature for a hello-world canister.
let message = EnvelopeContent::Call {
nonce: None,
ingress_expiry: 0,
sender: identity.sender().unwrap(),
canister_id: "bkyz2-fmaaa-aaaaa-qaaaq-cai".parse().unwrap(),
method_name: "greet".to_string(),
arg: Encode!(&"world").unwrap(),
};
let signature = identity
.sign(&message)
.expect("Cannot create secp256k1 signature.")
.signature
.expect("Cannot find secp256k1 signature bytes.");
// Import the secp256k1 signature into OpenSSL.
let r: Scalar = Option::from(Scalar::from_repr(*FieldBytes::from_slice(
&signature[0..32],
)))
.expect("Cannot extract r component from secp256k1 signature bytes.");
let s: Scalar = Option::from(Scalar::from_repr(*FieldBytes::from_slice(&signature[32..])))
.expect("Cannot extract s component from secp256k1 signature bytes.");
let ecdsa_sig = Signature::from_scalars(r, s)
.expect("Cannot create secp256k1 signature from r and s components.");
// Assert the secp256k1 signature is valid.
identity
._public_key
.verify(&message.to_request_id().signable(), &ecdsa_sig)
.expect("Cannot verify secp256k1 signature.");
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/identity/basic.rs | ic-agent/src/identity/basic.rs | use crate::{agent::EnvelopeContent, export::Principal, Identity, Signature};
#[cfg(feature = "pem")]
use crate::identity::error::PemError;
use ic_ed25519::PrivateKey;
use std::fmt;
use super::Delegation;
/// A cryptographic identity which signs using an Ed25519 key pair.
///
/// The caller will be represented via [`Principal::self_authenticating`], which contains the SHA-224 hash of the public key.
pub struct BasicIdentity {
private_key: KeyCompat,
der_encoded_public_key: Vec<u8>,
}
impl fmt::Debug for BasicIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BasicIdentity")
.field("der_encoded_public_key", &self.der_encoded_public_key)
.finish_non_exhaustive()
}
}
impl BasicIdentity {
/// Create a `BasicIdentity` from reading a PEM file at the path.
#[cfg(feature = "pem")]
pub fn from_pem_file<P: AsRef<std::path::Path>>(file_path: P) -> Result<Self, PemError> {
Self::from_pem(std::fs::read(file_path)?)
}
/// Create a `BasicIdentity` from reading a PEM File from a Reader.
#[cfg(feature = "pem")]
pub fn from_pem<B: AsRef<[u8]>>(pem_contents: B) -> Result<Self, PemError> {
use der::{asn1::OctetString, Decode, ErrorKind, SliceReader, Tag, TagNumber};
use pkcs8::PrivateKeyInfo;
let bytes = pem_contents.as_ref();
let pem = pem::parse(bytes)?;
let pki_res = PrivateKeyInfo::decode(&mut SliceReader::new(pem.contents())?);
let mut truncated;
let pki = match pki_res {
Ok(pki) => pki,
Err(e) => {
if e.kind()
== (ErrorKind::Noncanonical {
tag: Tag::ContextSpecific {
constructed: true,
number: TagNumber::new(1),
},
})
{
// Very old versions of dfx generated nonconforming containers. They can only be imported if the extra data is removed.
truncated = pem.into_contents();
if truncated[48..52] != *b"\xA1\x23\x03\x21" {
return Err(e.into());
}
// hatchet surgery
truncated.truncate(48);
truncated[1] = 46;
truncated[4] = 0;
PrivateKeyInfo::decode(&mut SliceReader::new(&truncated)?).map_err(|_| e)?
} else {
return Err(e.into());
}
}
};
let decoded_key = OctetString::from_der(pki.private_key)?; // ed25519 uses an octet string within another octet string
let key_len = decoded_key.as_bytes().len();
if key_len != 32 {
Err(PemError::InvalidPrivateKey(format!(
"Ed25519 expects a 32 octets private key, but got {key_len} octets",
)))
} else {
let raw_key: [u8; 32] = decoded_key.as_bytes().try_into().unwrap();
Ok(Self::from_raw_key(&raw_key))
}
}
/// Create a `BasicIdentity` from a raw 32-byte private key as described in RFC 8032 5.1.5.
pub fn from_raw_key(key: &[u8; 32]) -> Self {
let private_key = PrivateKey::deserialize_raw_32(key);
let public_key = private_key.public_key();
let der_encoded_public_key = public_key.serialize_rfc8410_der();
Self {
private_key: KeyCompat::Standard(private_key),
der_encoded_public_key,
}
}
/// Create a `BasicIdentity` from a `SigningKey` from `ed25519-consensus`.
///
/// # Note
///
/// This constructor is kept for backwards compatibility.
/// The signing won't use `ed25519-consensus` anymore.
#[deprecated(since = "0.41.0", note = "use BasicIdentity::from_raw_key instead")]
pub fn from_signing_key(key: ed25519_consensus::SigningKey) -> Self {
let raw_key = key.to_bytes();
Self::from_raw_key(&raw_key)
}
/// Create a `BasicIdentity` from an `Ed25519KeyPair` from `ring`.
#[cfg(feature = "ring")]
pub fn from_key_pair(key_pair: ring::signature::Ed25519KeyPair) -> Self {
use ic_ed25519::PublicKey;
use ring::signature::KeyPair;
let raw_public_key = key_pair.public_key().as_ref().to_vec();
// Unwrap safe: we trust that the public key is valid, as it comes from a valid key pair.
let public_key = PublicKey::deserialize_raw(&raw_public_key).unwrap();
let der_encoded_public_key = public_key.serialize_rfc8410_der();
Self {
private_key: KeyCompat::Ring(key_pair),
der_encoded_public_key,
}
}
}
enum KeyCompat {
/// ic_ed25519::PrivateKey
Standard(PrivateKey),
#[cfg(feature = "ring")]
Ring(ring::signature::Ed25519KeyPair),
}
impl KeyCompat {
fn sign(&self, payload: &[u8]) -> Vec<u8> {
match self {
Self::Standard(k) => k.sign_message(payload).to_vec(),
#[cfg(feature = "ring")]
Self::Ring(k) => k.sign(payload).as_ref().to_vec(),
}
}
}
impl Identity for BasicIdentity {
fn sender(&self) -> Result<Principal, String> {
Ok(Principal::self_authenticating(&self.der_encoded_public_key))
}
fn public_key(&self) -> Option<Vec<u8>> {
Some(self.der_encoded_public_key.clone())
}
fn sign(&self, content: &EnvelopeContent) -> Result<Signature, String> {
self.sign_arbitrary(&content.to_request_id().signable())
}
fn sign_delegation(&self, content: &Delegation) -> Result<Signature, String> {
self.sign_arbitrary(&content.signable())
}
fn sign_arbitrary(&self, content: &[u8]) -> Result<Signature, String> {
let signature = self.private_key.sign(content);
Ok(Signature {
signature: Some(signature),
public_key: self.public_key(),
delegations: None,
})
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/agent_test.rs | ic-agent/src/agent/agent_test.rs | use self::mock::{
assert_mock, assert_single_mock, assert_single_mock_count, mock, mock_additional,
};
use crate::{agent::Status, export::Principal, Agent, AgentError, Certificate};
use candid::{Encode, Nat};
use futures_util::FutureExt;
use ic_certification::{Delegation, Label};
use ic_transport_types::{
NodeSignature, QueryResponse, RejectCode, RejectResponse, ReplyResponse, TransportCallResponse,
};
use std::{collections::BTreeMap, str::FromStr, sync::Arc, time::Duration};
#[cfg(all(target_family = "wasm", feature = "wasm-bindgen"))]
use wasm_bindgen_test::wasm_bindgen_test;
use crate::agent::route_provider::{RoundRobinRouteProvider, RouteProvider};
#[cfg(all(target_family = "wasm", feature = "wasm-bindgen"))]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
fn make_agent(url: &str) -> Agent {
let builder = Agent::builder().with_url(url);
builder.with_verify_query_signatures(false).build().unwrap()
}
fn make_agent_with_route_provider(
route_provider: Arc<dyn RouteProvider>,
tcp_retries: usize,
) -> Agent {
Agent::builder()
.with_arc_route_provider(route_provider)
.with_max_tcp_error_retries(tcp_retries)
.with_verify_query_signatures(false)
.build()
.unwrap()
}
fn make_untimed_agent(url: &str) -> Agent {
Agent::builder()
.with_url(url)
.with_verify_query_signatures(false)
.with_ingress_expiry(Duration::from_secs(u32::MAX.into()))
.build()
.unwrap()
}
fn make_certifying_agent(url: &str) -> Agent {
Agent::builder()
.with_url(url)
.with_ingress_expiry(Duration::from_secs(u32::MAX.into()))
.build()
.unwrap()
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn query() -> Result<(), AgentError> {
let blob = Vec::from("Hello World");
let response = QueryResponse::Replied {
reply: ReplyResponse { arg: blob.clone() },
signatures: vec![],
};
let (query_mock, url) = mock(
"POST",
"/api/v3/canister/aaaaa-aa/query",
200,
serde_cbor::to_vec(&response)?,
Some("application/cbor"),
)
.await;
let agent = make_agent(&url);
let result = agent
.query_raw(
Principal::management_canister(),
Principal::management_canister(),
"main".to_string(),
vec![],
None,
false,
None,
)
.await;
assert_mock(query_mock).await;
assert_eq!(result?, blob);
Ok(())
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn query_error() -> Result<(), AgentError> {
let (query_mock, url) =
mock("POST", "/api/v3/canister/aaaaa-aa/query", 500, vec![], None).await;
let agent = make_agent(&url);
let result = agent
.query_raw(
Principal::management_canister(),
Principal::management_canister(),
"greet".to_string(),
vec![],
None,
false,
None,
)
.await;
assert_mock(query_mock).await;
assert!(result.is_err());
Ok(())
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn query_rejected() -> Result<(), AgentError> {
let response: QueryResponse = QueryResponse::Rejected {
reject: RejectResponse {
reject_code: RejectCode::DestinationInvalid,
reject_message: "Rejected Message".to_string(),
error_code: Some("Error code".to_string()),
},
signatures: vec![],
};
let (query_mock, url) = mock(
"POST",
"/api/v3/canister/aaaaa-aa/query",
200,
serde_cbor::to_vec(&response)?,
Some("application/cbor"),
)
.await;
let agent = make_agent(&url);
let result = agent
.query_raw(
Principal::management_canister(),
Principal::management_canister(),
"greet".to_string(),
vec![],
None,
false,
None,
)
.await;
assert_mock(query_mock).await;
match result {
Err(AgentError::UncertifiedReject {
reject: replica_error,
..
}) => {
assert_eq!(replica_error.reject_code, RejectCode::DestinationInvalid);
assert_eq!(replica_error.reject_message, "Rejected Message");
assert_eq!(replica_error.error_code, Some("Error code".to_string()));
}
result => unreachable!("{:?}", result),
}
Ok(())
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn call_error() -> Result<(), AgentError> {
let (call_mock, url) = mock("POST", "/api/v4/canister/aaaaa-aa/call", 500, vec![], None).await;
let agent = make_agent(&url);
let result = agent
.update(&Principal::management_canister(), "greet")
.with_arg([])
.call()
.await;
assert_mock(call_mock).await;
assert!(result.is_err());
Ok(())
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn call_rejected() -> Result<(), AgentError> {
let reject_response = RejectResponse {
reject_code: RejectCode::SysTransient,
reject_message: "Test reject message".to_string(),
error_code: Some("Test error code".to_string()),
};
let reject_body = TransportCallResponse::NonReplicatedRejection(reject_response.clone());
let body = serde_cbor::to_vec(&reject_body).unwrap();
let (call_mock, url) = mock(
"POST",
"/api/v4/canister/aaaaa-aa/call",
200,
body,
Some("application/cbor"),
)
.await;
let agent = make_agent(&url);
let result = agent
.update(&Principal::management_canister(), "greet")
.with_arg([])
.call()
.await;
assert_mock(call_mock).await;
assert!(
matches!(result, Err(AgentError::UncertifiedReject { reject, .. }) if reject == reject_response)
);
Ok(())
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn call_rejected_without_error_code() -> Result<(), AgentError> {
let non_replicated_reject = RejectResponse {
reject_code: RejectCode::SysTransient,
reject_message: "Test reject message".to_string(),
error_code: None,
};
let reject_body = TransportCallResponse::NonReplicatedRejection(non_replicated_reject.clone());
let canister_id_str = "aaaaa-aa";
let body = serde_cbor::to_vec(&reject_body).unwrap();
let (call_mock, url) = mock(
"POST",
format!("/api/v4/canister/{canister_id_str}/call").as_str(),
200,
body,
Some("application/cbor"),
)
.await;
let agent = make_agent(&url);
let result = agent
.update(&Principal::from_str(canister_id_str).unwrap(), "greet")
.with_arg([])
.call()
.await;
assert_mock(call_mock).await;
assert!(
matches!(result, Err(AgentError::UncertifiedReject { reject, .. }) if reject == non_replicated_reject)
);
Ok(())
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn status() -> Result<(), AgentError> {
let map = BTreeMap::new();
let response = serde_cbor::Value::Map(map);
let (read_mock, url) = mock(
"GET",
"/api/v2/status",
200,
serde_cbor::to_vec(&response)?,
Some("application/cbor"),
)
.await;
let agent = make_agent(&url);
let result = agent.status().await;
assert_mock(read_mock).await;
assert!(matches!(result, Ok(Status { .. })));
Ok(())
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn status_okay() -> Result<(), AgentError> {
let map = BTreeMap::new();
let response = serde_cbor::Value::Map(map);
let (read_mock, url) = mock(
"GET",
"/api/v2/status",
200,
serde_cbor::to_vec(&response)?,
Some("application/cbor"),
)
.await;
let agent = make_agent(&url);
let result = agent.status().await;
assert_mock(read_mock).await;
assert!(result.is_ok());
Ok(())
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
async fn reqwest_client_status_okay_when_request_retried() -> Result<(), AgentError> {
let map = BTreeMap::new();
let response = serde_cbor::Value::Map(map);
let (read_mock, url) = mock(
"GET",
"/api/v2/status",
200,
serde_cbor::to_vec(&response)?,
Some("application/cbor"),
)
.await;
// Without retry request should fail.
let non_working_url = "http://127.0.0.1:4444";
let tcp_retries = 0;
let route_provider = RoundRobinRouteProvider::new(vec![non_working_url, &url]).unwrap();
let agent = make_agent_with_route_provider(Arc::new(route_provider), tcp_retries);
let result = agent.status().await;
assert!(result.is_err());
// With retry request should succeed.
let tcp_retries = 1;
let route_provider = RoundRobinRouteProvider::new(vec![non_working_url, &url]).unwrap();
let agent = make_agent_with_route_provider(Arc::new(route_provider), tcp_retries);
let result = agent.status().await;
assert_mock(read_mock).await;
assert!(result.is_ok());
Ok(())
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
// test that the agent (re)tries to reach the server.
// We spawn an agent that waits 400ms between requests, and times out after 600ms. The agent is
// expected to hit the server at ~ 0ms and ~ 400 ms, and then shut down at 600ms, so we check that
// the server got two requests.
async fn status_error() -> Result<(), AgentError> {
// This mock is never asserted as we don't know (nor do we need to know) how many times
// it is called.
let (_read_mock, url) = mock("GET", "/api/v2/status", 500, vec![], None).await;
let agent = make_agent(&url);
let result = agent.status().await;
assert!(result.is_err());
Ok(())
}
const REQ_WITH_DELEGATED_CERT_PATH: [&str; 1] = ["time"];
const REQ_WITH_DELEGATED_CERT_CANISTER: &str = "ivg37-qiaaa-aaaab-aaaga-cai";
// This file is a mainnet POST response body to /api/v3/canister/ivg37-.../read_state with path /time
const REQ_WITH_DELEGATED_CERT_RESPONSE: &[u8] = include_bytes!("agent_test/ivg37_time.bin");
// this is the same response as REQ_WITH_DELEGATED_CERT_RESPONSE, but with a manually pruned /canister_ranges.
// Run the ref-tests bin prune-ranges to generate it.
const PRUNED_RANGES: &[u8] = include_bytes!("agent_test/ivg37_time_pruned_ranges.bin");
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
// asserts that a delegated certificate with correct /subnet/<subnetid>/canister_ranges
// passes the certificate verification
async fn check_subnet_range_with_valid_range() {
let (_read_mock, url) = mock(
"POST",
"/api/v3/canister/ivg37-qiaaa-aaaab-aaaga-cai/read_state",
200,
REQ_WITH_DELEGATED_CERT_RESPONSE.into(),
Some("application/cbor"),
)
.await;
let agent = make_untimed_agent(&url);
let _result = agent
.read_state_raw(
vec![REQ_WITH_DELEGATED_CERT_PATH
.into_iter()
.map(Label::from)
.collect()],
Principal::from_text(REQ_WITH_DELEGATED_CERT_CANISTER).unwrap(),
)
.await
.expect("read state failed");
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
// asserts that a delegated certificate with /subnet/<subnetid>/canister_ranges that don't include
// the canister gets rejected by the cert verification because the subnet is not authorized to
// respond to requests for this canister. We do this by using a correct response but serving it
// for the wrong canister, which a malicious node might do.
async fn check_subnet_range_with_unauthorized_range() {
let wrong_canister = Principal::from_text("ryjl3-tyaaa-aaaaa-aaaba-cai").unwrap();
let (_read_mock, url) = mock(
"POST",
"/api/v3/canister/ryjl3-tyaaa-aaaaa-aaaba-cai/read_state",
200,
REQ_WITH_DELEGATED_CERT_RESPONSE.into(),
Some("application/cbor"),
)
.await;
let agent = make_untimed_agent(&url);
let result = agent
.read_state_raw(
vec![REQ_WITH_DELEGATED_CERT_PATH
.into_iter()
.map(Label::from)
.collect()],
wrong_canister,
)
.await;
assert_eq!(result, Err(AgentError::CertificateNotAuthorized()));
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
// asserts that a delegated certificate with pruned/removed /subnet/<subnetid>/canister_ranges
// gets rejected by the cert verification. We do this by using a correct response that has
// the leaf manually pruned
async fn check_subnet_range_with_pruned_range() {
let canister = Principal::from_text("ivg37-qiaaa-aaaab-aaaga-cai").unwrap();
let (_read_mock, url) = mock(
"POST",
"/api/v3/canister/ivg37-qiaaa-aaaab-aaaga-cai/read_state",
200,
PRUNED_RANGES.into(),
Some("application/cbor"),
)
.await;
let agent = make_untimed_agent(&url);
let result = agent
.read_state_raw(
vec![REQ_WITH_DELEGATED_CERT_PATH
.into_iter()
.map(Label::from)
.collect()],
canister,
)
.await;
assert!(result.is_err());
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn wrong_subnet_query_certificate() {
// these responses are for canister 224od-giaaa-aaaao-ae5vq-cai
let wrong_canister = Principal::from_text("rdmx6-jaaaa-aaaaa-aaadq-cai").unwrap();
let (mut read_mock, url) = mock(
"POST",
&format!("/api/v3/canister/{wrong_canister}/read_state"),
200,
SUBNET_224OD.into(),
Some("application/cbor"),
)
.await;
let blob = Encode!(&Nat::from(12u8)).unwrap();
let response = QueryResponse::Replied {
reply: ReplyResponse { arg: blob.clone() },
signatures: vec![NodeSignature {
timestamp: 1_697_831_349_698_624_964,
signature: hex::decode("4bb6ba316623395d56d8e2834ece39d2c81d47e76a9fd122e1457963be6a83a5589e2c98c7b4d8b3c6c7b11c74b8ce9dcb345b5d1bd91706a643f33c7b509b0b").unwrap(),
identity: "oo4np-rrvnz-5vram-kglex-enhkp-uew6q-vdf6z-whj4x-v44jd-tebaw-nqe".parse().unwrap()
}],
};
mock_additional(
&mut read_mock,
"POST",
&format!("/api/v3/canister/{wrong_canister}/query"),
200,
serde_cbor::to_vec(&response).unwrap(),
Some("application/cbor"),
)
.await;
let agent = make_certifying_agent(&url);
let result = agent.query(&wrong_canister, "getVersion").call().await;
assert!(matches!(
dbg!(result.unwrap_err()),
AgentError::CertificateNotAuthorized()
));
assert_single_mock(
"POST",
&format!("/api/v3/canister/{wrong_canister}/read_state"),
&read_mock,
)
.await;
}
// This file is a mainnet POST response body to /api/v3/canister/224od-.../read_state with path /subnet
const SUBNET_224OD: &[u8] = include_bytes!("agent_test/224od_subnet.bin");
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn no_cert() {
let canister = Principal::from_text("224od-giaaa-aaaao-ae5vq-cai").unwrap();
let (mut read_mock, url) = mock(
"POST",
"/api/v3/canister/224od-giaaa-aaaao-ae5vq-cai/read_state",
200,
SUBNET_224OD.into(),
Some("application/cbor"),
)
.await;
let blob = Encode!(&Nat::from(12u8)).unwrap();
let response = QueryResponse::Replied {
reply: ReplyResponse { arg: blob.clone() },
signatures: vec![],
};
mock_additional(
&mut read_mock,
"POST",
"/api/v3/canister/224od-giaaa-aaaao-ae5vq-cai/query",
200,
serde_cbor::to_vec(&response).unwrap(),
Some("application/cbor"),
)
.await;
let agent = make_certifying_agent(&url);
let result = agent.query(&canister, "getVersion").call().await;
assert!(matches!(result.unwrap_err(), AgentError::MissingSignature));
assert_mock(read_mock).await;
}
// This file is a mainnet POST response body to /api/v3/subnet/uzr34-.../read_state with paths /canister_ranges/hex(uzr34-...) and /subnet/hex(uzr34-...)
const NODE_KEYS_UZR34: &[u8] = include_bytes!("agent_test/uzr34_node_keys.bin");
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn too_many_delegations() {
// Use the certificate as its own delegation, and repeat the process the specified number of times
fn self_delegate_cert(subnet_id: &[u8], cert: &Certificate, depth: u32) -> Certificate {
let mut current = cert.clone();
for _ in 0..depth {
current = Certificate {
tree: current.tree.clone(),
signature: current.signature.clone(),
delegation: Some(Delegation {
subnet_id: subnet_id.to_vec(),
certificate: serde_cbor::to_vec(¤t).unwrap(),
}),
}
}
current
}
let subnet_id =
Principal::from_text("uzr34-akd3s-xrdag-3ql62-ocgoh-ld2ao-tamcv-54e7j-krwgb-2gm4z-oqe")
.unwrap();
let (_read_mock, url) = mock(
"POST",
format!("/api/v3/subnet/{subnet_id}/read_state").as_str(),
200,
NODE_KEYS_UZR34.into(),
Some("application/cbor"),
)
.await;
let path_label = Label::from_bytes("subnet".as_bytes());
let agent = make_untimed_agent(&url);
let cert = agent
.read_subnet_state_raw(vec![vec![path_label]], subnet_id)
.await
.expect("read state failed");
let new_cert = self_delegate_cert(subnet_id.as_slice(), &cert, 1);
assert!(matches!(
agent.verify_for_subnet(&new_cert, subnet_id).unwrap_err(),
AgentError::CertificateHasTooManyDelegations
));
}
#[cfg_attr(not(target_family = "wasm"), tokio::test)]
#[cfg_attr(target_family = "wasm", wasm_bindgen_test)]
async fn retry_ratelimit() {
let (mut mock, url) = mock(
"POST",
"/api/v3/canister/ryjl3-tyaaa-aaaaa-aaaba-cai/query",
429,
vec![],
Some("text/plain"),
)
.await;
let agent = make_agent(&url);
futures_util::select! {
_ = agent.query(&"ryjl3-tyaaa-aaaaa-aaaba-cai".parse().unwrap(), "greet").call().fuse() => panic!("did not retry 429"),
_ = crate::util::sleep(Duration::from_millis(500)).fuse() => {},
};
assert_single_mock_count(
"POST",
"/api/v3/canister/ryjl3-tyaaa-aaaaa-aaaba-cai/query",
2,
&mut mock,
)
.await;
}
#[cfg(not(target_family = "wasm"))]
mod mock {
use std::collections::HashMap;
use mockito::{Mock, Server, ServerGuard};
pub async fn mock(
method: &str,
path: &str,
status_code: u16,
body: Vec<u8>,
content_type: Option<&str>,
) -> ((ServerGuard, HashMap<String, Mock>), String) {
let mut server = Server::new_async().await;
let mut mock = server
.mock(method, path)
.with_status(status_code as _)
.with_body(body);
if let Some(content_type) = content_type {
mock = mock.with_header("Content-Type", content_type);
}
let mock = mock.create_async().await;
let url = server.url();
(
(server, HashMap::from([(format!("{method} {path}"), mock)])),
url,
)
}
pub async fn mock_additional(
orig: &mut (ServerGuard, HashMap<String, Mock>),
method: &str,
path: &str,
status_code: u16,
body: Vec<u8>,
content_type: Option<&str>,
) {
let mut mock = orig
.0
.mock(method, path)
.with_status(status_code as _)
.with_body(body);
if let Some(content_type) = content_type {
mock = mock.with_header("Content-Type", content_type);
}
orig.1
.insert(format!("{method} {path}"), mock.create_async().await);
}
pub async fn assert_mock((_, mocks): (ServerGuard, HashMap<String, Mock>)) {
for mock in mocks.values() {
mock.assert_async().await;
}
}
pub async fn assert_single_mock(
method: &str,
path: &str,
(_, mocks): &(ServerGuard, HashMap<String, Mock>),
) {
mocks[&format!("{method} {path}")].assert_async().await;
}
pub async fn assert_single_mock_count(
method: &str,
path: &str,
n: usize,
(_, mocks): &mut (ServerGuard, HashMap<String, Mock>),
) {
let k = format!("{method} {path}");
let mut mock = mocks.remove(&k).unwrap();
mock = mock.expect_at_least(n);
mock.assert_async().await;
mocks.insert(k, mock);
}
}
#[cfg(all(target_family = "wasm", feature = "wasm-bindgen"))]
mod mock {
use js_sys::*;
use reqwest::Client;
use serde::Serialize;
use std::collections::HashMap;
use wasm_bindgen::{prelude::*, JsCast};
use wasm_bindgen_futures::JsFuture;
use web_sys::*;
#[wasm_bindgen(module = "/http_mock_service_worker.js")]
extern "C" {}
#[derive(Debug, Serialize)]
struct MockConfig {
pub kind: String,
pub method: String,
pub path: String,
pub status_code: u16,
pub headers: Option<HashMap<String, String>>,
pub body: Vec<u8>,
}
pub async fn mock(
method: &str,
path: &str,
status_code: u16,
body: Vec<u8>,
content_type: Option<&str>,
) -> (String, String) {
let swc = window().unwrap().navigator().service_worker();
let registration: ServiceWorkerRegistration =
JsFuture::from(swc.register("/http_mock_service_worker.js"))
.await
.unwrap()
.unchecked_into();
JsFuture::from(swc.ready().unwrap()).await.unwrap();
let sw = registration.active().unwrap();
let mut nonce = [0; 16];
getrandom::getrandom(&mut nonce).unwrap();
let nonce = hex::encode(nonce);
let config = MockConfig {
kind: "config".into(),
method: method.into(),
path: path.into(),
status_code,
body,
headers: content_type.map(|c| HashMap::from([("Content-Type".into(), c.into())])),
};
if sw.state() == ServiceWorkerState::Activating {
JsFuture::from(Promise::new(&mut |rs, _| sw.set_onstatechange(Some(&rs))))
.await
.unwrap();
}
Client::new()
.post(&format!("http://mock_configure/{nonce}"))
.json(&config)
.send()
.await
.unwrap()
.error_for_status()
.unwrap();
(nonce.clone(), format!("http://mock_{}/", nonce))
}
pub async fn mock_additional(
orig: &mut String,
method: &str,
path: &str,
status_code: u16,
body: Vec<u8>,
content_type: Option<&str>,
) {
let config = MockConfig {
kind: "config".into(),
method: method.into(),
path: path.into(),
status_code,
body,
headers: content_type.map(|c| HashMap::from([("Content-Type".into(), c.into())])),
};
Client::new()
.post(&format!("http://mock_configure/{orig}"))
.json(&config)
.send()
.await
.unwrap()
.error_for_status()
.unwrap();
}
async fn get_hits(nonce: &str) -> HashMap<String, i64> {
Client::new()
.get(&format!("http://mock_assert/{}", nonce))
.send()
.await
.unwrap()
.error_for_status()
.unwrap()
.json()
.await
.unwrap()
}
pub async fn assert_mock(nonce: String) {
let hits = get_hits(&nonce).await;
assert!(hits.values().all(|x| *x > 0));
}
pub async fn assert_single_mock(method: &str, path: &str, nonce: &String) {
let hits = get_hits(nonce).await;
assert!(hits[&format!("{method} {path}")] > 0);
}
pub async fn assert_single_mock_count(method: &str, path: &str, n: usize, nonce: &mut String) {
let hits = get_hits(&*nonce).await;
assert!(hits[&format!("{method} {path}")] >= n as i64);
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/subnet.rs | ic-agent/src/agent/subnet.rs | //! Information about IC subnets.
//!
//! Fetch subnet information via [`Agent::fetch_subnet_by_id`](crate::Agent::fetch_subnet_by_id) or
//! [`Agent::get_subnet_by_canister`](crate::Agent::get_subnet_by_canister).
use std::{collections::HashMap, ops::RangeInclusive};
use candid::Principal;
use rangemap::RangeInclusiveSet;
use crate::agent::PrincipalStep;
/// Information about a subnet, including its public key, member nodes, and assigned canister ranges.
///
/// Range information may be incomplete depending on how the subnet was fetched. The lack of a canister ID
/// within assigned ranges should not be treated immediately as an authorization failure without fetching
/// fresh data with [`Agent::fetch_subnet_by_canister`](crate::Agent::fetch_subnet_by_canister).
#[derive(Clone)]
pub struct Subnet {
pub(crate) id: Principal,
// This key is just fetched for completeness. Do not actually use this value as it is not authoritative in case of a rogue subnet.
// If a future agent needs to know the subnet key then it should fetch /subnet from the *root* subnet.
pub(crate) key: Vec<u8>,
pub(crate) node_keys: HashMap<Principal, Vec<u8>>,
pub(crate) canister_ranges: RangeInclusiveSet<Principal, PrincipalStep>,
}
impl Subnet {
/// Checks whether the given canister ID is contained within the subnet's assigned canister ranges.
pub fn contains_canister(&self, canister_id: &Principal) -> bool {
self.canister_ranges.contains(canister_id)
}
/// Returns an iterator over the known canister ID ranges assigned to this subnet.
pub fn iter_canister_ranges(&self) -> CanisterRangesIter<'_> {
CanisterRangesIter {
inner: self.canister_ranges.iter(),
}
}
/// Returns the self-reported public key of the subnet.
///
/// Note that this key is not authoritative if the subnet is rogue.
pub fn self_reported_key(&self) -> &[u8] {
&self.key
}
/// Checks whether the given node ID is a member of this subnet.
pub fn contains_node(&self, node_id: &Principal) -> bool {
self.node_keys.contains_key(node_id)
}
/// Returns the public key of the given node ID, if it is a member of this subnet.
pub fn get_node_key(&self, node_id: &Principal) -> Option<&[u8]> {
self.node_keys.get(node_id).map(|k| &k[..])
}
/// Returns an iterator over the nodes in this subnet.
pub fn iter_nodes(&self) -> SubnetNodeIter<'_> {
SubnetNodeIter {
inner: self.node_keys.keys(),
}
}
/// Returns an iterator over the node IDs and their corresponding public keys in this subnet.
pub fn iter_node_keys(&self) -> SubnetKeysIter<'_> {
SubnetKeysIter {
inner: self.node_keys.iter(),
}
}
/// Returns the subnet's ID.
pub fn id(&self) -> Principal {
self.id
}
}
/// Iterator over the canister ID ranges assigned to a subnet.
pub struct CanisterRangesIter<'a> {
inner: rangemap::inclusive_set::Iter<'a, Principal>,
}
impl Iterator for CanisterRangesIter<'_> {
type Item = RangeInclusive<Principal>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().cloned()
}
}
/// Iterator over the node IDs in a subnet.
pub struct SubnetNodeIter<'a> {
inner: std::collections::hash_map::Keys<'a, Principal, Vec<u8>>,
}
impl<'a> Iterator for SubnetNodeIter<'a> {
type Item = Principal;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().copied()
}
}
/// Iterator over the node IDs and their corresponding public keys in a subnet.
pub struct SubnetKeysIter<'a> {
inner: std::collections::hash_map::Iter<'a, Principal, Vec<u8>>,
}
impl<'a> Iterator for SubnetKeysIter<'a> {
type Item = (Principal, &'a [u8]);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(k, v)| (*k, &v[..]))
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/builder.rs | ic-agent/src/agent/builder.rs | use crate::{
agent::{agent_config::AgentConfig, Agent},
AgentError, Identity, NonceFactory, NonceGenerator,
};
use std::sync::Arc;
use super::{route_provider::RouteProvider, HttpService};
/// A builder for an [`Agent`].
#[derive(Default)]
pub struct AgentBuilder {
config: AgentConfig,
}
impl AgentBuilder {
/// Create an instance of [Agent] with the information from this builder.
pub fn build(self) -> Result<Agent, AgentError> {
Agent::new(self.config)
}
/// Set the dynamic transport layer for the [`Agent`], performing continuous discovery of the API boundary nodes
/// and routing traffic via them based on latency. Cannot be set together with `with_route_provider`.
///
/// See [`DynamicRouteProvider`](super::route_provider::DynamicRouteProvider) if more customization is needed such as polling intervals.
pub fn with_background_dynamic_routing(mut self) -> Self {
assert!(
self.config.route_provider.is_none(),
"with_background_dynamic_routing cannot be called with with_route_provider"
);
self.config.background_dynamic_routing = true;
self
}
/// Set the URL of the [`Agent`]. Either this or `with_route_provider` must be called (but not both).
pub fn with_url<S: Into<String>>(mut self, url: S) -> Self {
assert!(
self.config.route_provider.is_none(),
"with_url cannot be called with with_route_provider"
);
self.config.url = Some(url.into().parse().unwrap());
self
}
/// Add a `NonceFactory` to this Agent. By default, no nonce is produced.
pub fn with_nonce_factory(self, nonce_factory: NonceFactory) -> AgentBuilder {
self.with_nonce_generator(nonce_factory)
}
/// Same as [`Self::with_nonce_factory`], but for any `NonceGenerator` type
pub fn with_nonce_generator<N: 'static + NonceGenerator>(
self,
nonce_factory: N,
) -> AgentBuilder {
self.with_arc_nonce_generator(Arc::new(nonce_factory))
}
/// Same as [`Self::with_nonce_generator`], but reuses an existing `Arc`.
pub fn with_arc_nonce_generator(
mut self,
nonce_factory: Arc<dyn NonceGenerator>,
) -> AgentBuilder {
self.config.nonce_factory = Arc::new(nonce_factory);
self
}
/// Add an identity provider for signing messages. This is required.
pub fn with_identity<I>(self, identity: I) -> Self
where
I: 'static + Identity,
{
self.with_arc_identity(Arc::new(identity))
}
/// Same as [`Self::with_identity`], but reuses an existing box
pub fn with_boxed_identity(self, identity: Box<dyn Identity>) -> Self {
self.with_arc_identity(Arc::from(identity))
}
/// Same as [`Self::with_identity`], but reuses an existing `Arc`
pub fn with_arc_identity(mut self, identity: Arc<dyn Identity>) -> Self {
self.config.identity = identity;
self
}
/// Provides a _default_ ingress expiry. This is the delta that will be applied
/// at the time an update or query is made. The default expiry cannot be a
/// fixed system time. This is also used when checking certificate timestamps.
///
/// The timestamp corresponding to this duration may be rounded in order to reduce
/// cache misses. The current implementation rounds to the nearest minute if the
/// expiry is more than a minute, but this is not guaranteed.
pub fn with_ingress_expiry(mut self, ingress_expiry: std::time::Duration) -> Self {
self.config.ingress_expiry = ingress_expiry;
self
}
/// Allows disabling query signature verification. Query signatures improve resilience but require
/// a separate read-state call to fetch node keys.
pub fn with_verify_query_signatures(mut self, verify_query_signatures: bool) -> Self {
self.config.verify_query_signatures = verify_query_signatures;
self
}
/// Sets the maximum number of requests that the agent will make concurrently. The replica is configured
/// to only permit 50 concurrent requests per client. Set this value lower if you have multiple agents,
/// to avoid the slowdown of retrying any 429 errors.
pub fn with_max_concurrent_requests(mut self, max_concurrent_requests: usize) -> Self {
self.config.max_concurrent_requests = max_concurrent_requests;
self
}
/// Add a `RouteProvider` to this agent, to provide the URLs of boundary nodes.
pub fn with_route_provider(self, provider: impl RouteProvider + 'static) -> Self {
self.with_arc_route_provider(Arc::new(provider))
}
/// Same as [`Self::with_route_provider`], but reuses an existing `Arc`.
pub fn with_arc_route_provider(mut self, provider: Arc<dyn RouteProvider>) -> Self {
assert!(
!self.config.background_dynamic_routing,
"with_background_dynamic_routing cannot be called with with_route_provider"
);
assert!(
self.config.url.is_none(),
"with_url cannot be called with with_route_provider"
);
self.config.route_provider = Some(provider);
self
}
/// Provide a pre-configured HTTP client to use. Use this to set e.g. HTTP timeouts or proxy configuration.
pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
assert!(
self.config.http_service.is_none(),
"with_arc_http_middleware cannot be called with with_http_client"
);
self.config.client = Some(client);
self
}
/// Provide a custom `reqwest`-compatible HTTP service, e.g. to add per-request headers for custom boundary nodes.
/// Most users will not need this and should use `with_http_client`. Cannot be called with `with_http_client`.
///
/// The trait is automatically implemented for any `tower::Service` impl matching the one `reqwest::Client` uses,
/// including `reqwest-middleware`. This is a low-level interface, and direct implementations must provide all automatic retry logic.
pub fn with_arc_http_middleware(mut self, service: Arc<dyn HttpService>) -> Self {
assert!(
self.config.client.is_none(),
"with_arc_http_middleware cannot be called with with_http_client"
);
self.config.http_service = Some(service);
self
}
/// Retry up to the specified number of times upon encountering underlying TCP errors.
pub fn with_max_tcp_error_retries(mut self, retries: usize) -> Self {
self.config.max_tcp_error_retries = retries;
self
}
/// Don't accept HTTP bodies any larger than `max_size` bytes.
pub fn with_max_response_body_size(mut self, max_size: usize) -> Self {
self.config.max_response_body_size = Some(max_size);
self
}
/// Set the maximum time to wait for a response from the replica.
pub fn with_max_polling_time(mut self, max_polling_time: std::time::Duration) -> Self {
self.config.max_polling_time = max_polling_time;
self
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/nonce.rs | ic-agent/src/agent/nonce.rs | use rand::{rngs::OsRng, Rng};
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc, Mutex,
};
/// A Factory for nonce blobs.
#[derive(Clone)]
pub struct NonceFactory {
inner: Arc<dyn NonceGenerator>,
}
impl NonceFactory {
/// Creates a nonce factory from an iterator over blobs. The iterator is not assumed to be fused.
pub fn from_iterator(iter: Box<dyn Iterator<Item = Vec<u8>> + Send>) -> Self {
Self {
inner: Arc::new(Iter::from(iter)),
}
}
/// Creates a nonce factory that generates random blobs using `getrandom`.
pub fn random() -> NonceFactory {
Self {
inner: Arc::new(RandomBlob {}),
}
}
/// Creates a nonce factory that returns None every time.
pub fn empty() -> NonceFactory {
Self {
inner: Arc::new(Empty),
}
}
/// Creates a nonce factory that generates incrementing blobs.
pub fn incrementing() -> NonceFactory {
Self {
inner: Arc::new(Incrementing::default()),
}
}
/// Generates a nonce, if one is available. Otherwise, returns None.
pub fn generate(&self) -> Option<Vec<u8>> {
NonceGenerator::generate(self)
}
}
impl NonceGenerator for NonceFactory {
fn generate(&self) -> Option<Vec<u8>> {
self.inner.generate()
}
}
/// An interface for generating nonces.
pub trait NonceGenerator: Send + Sync {
/// Generates a nonce, if one is available. Otherwise, returns None.
fn generate(&self) -> Option<Vec<u8>>;
}
#[expect(unused)]
pub(crate) struct Func<T>(pub T);
impl<T: Send + Sync + Fn() -> Option<Vec<u8>>> NonceGenerator for Func<T> {
fn generate(&self) -> Option<Vec<u8>> {
(self.0)()
}
}
pub(crate) struct Iter<T>(Mutex<T>);
impl<T: Send + Iterator<Item = Vec<u8>>> From<T> for Iter<T> {
fn from(val: T) -> Iter<T> {
Iter(Mutex::new(val))
}
}
impl<T: Send + Iterator<Item = Vec<u8>>> NonceGenerator for Iter<T> {
fn generate(&self) -> Option<Vec<u8>> {
self.0.lock().unwrap().next()
}
}
#[derive(Default)]
pub(crate) struct RandomBlob {}
impl NonceGenerator for RandomBlob {
fn generate(&self) -> Option<Vec<u8>> {
Some(OsRng.gen::<[u8; 16]>().to_vec())
}
}
#[derive(Default)]
pub(crate) struct Empty;
impl NonceGenerator for Empty {
fn generate(&self) -> Option<Vec<u8>> {
None
}
}
#[derive(Default)]
pub(crate) struct Incrementing {
next: AtomicU64,
}
impl From<u64> for Incrementing {
fn from(val: u64) -> Incrementing {
Incrementing {
next: AtomicU64::new(val),
}
}
}
impl NonceGenerator for Incrementing {
fn generate(&self) -> Option<Vec<u8>> {
let val = self.next.fetch_add(1, Ordering::Relaxed);
Some(val.to_le_bytes().to_vec())
}
}
impl<N: NonceGenerator + ?Sized> NonceGenerator for Box<N> {
fn generate(&self) -> Option<Vec<u8>> {
(**self).generate()
}
}
impl<N: NonceGenerator + ?Sized> NonceGenerator for Arc<N> {
fn generate(&self) -> Option<Vec<u8>> {
(**self).generate()
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/agent_error.rs | ic-agent/src/agent/agent_error.rs | //! Errors that can occur when using the replica agent.
use crate::{agent::status::Status, RequestIdError};
use candid::Principal;
use ic_certification::Label;
use ic_transport_types::{InvalidRejectCodeError, RejectResponse};
use leb128::read;
use std::time::Duration;
use std::{
fmt::{Debug, Display, Formatter},
str::Utf8Error,
};
use thiserror::Error;
/// An error that occurs on transport layer
#[derive(Error, Debug)]
pub enum TransportError {
/// Reqwest-related error
#[error("{0}")]
Reqwest(reqwest::Error),
#[error("{0}")]
/// Generic non-specific error
Generic(String),
}
/// An error that occurred when using the agent.
#[derive(Error, Debug)]
pub enum AgentError {
/// The replica URL was invalid.
#[error(r#"Invalid Replica URL: "{0}""#)]
InvalidReplicaUrl(String),
/// The request timed out.
#[error("The request timed out.")]
TimeoutWaitingForResponse(),
/// An error occurred when signing with the identity.
#[error("Identity had a signing error: {0}")]
SigningError(String),
/// The data fetched was invalid CBOR.
#[error("Invalid CBOR data, could not deserialize: {0}")]
InvalidCborData(#[from] serde_cbor::Error),
/// There was an error calculating a request ID.
#[error("Cannot calculate a RequestID: {0}")]
CannotCalculateRequestId(#[from] RequestIdError),
/// There was an error when de/serializing with Candid.
#[error("Candid returned an error: {0}")]
CandidError(Box<dyn Send + Sync + std::error::Error>),
/// There was an error parsing a URL.
#[error(r#"Cannot parse url: "{0}""#)]
UrlParseError(#[from] url::ParseError),
/// The HTTP method was invalid.
#[error(r#"Invalid method: "{0}""#)]
InvalidMethodError(#[from] http::method::InvalidMethod),
/// The principal string was not a valid principal.
#[error("Cannot parse Principal: {0}")]
PrincipalError(#[from] crate::export::PrincipalError),
/// The subnet rejected the message.
#[error("The replica returned a rejection error: reject code {:?}, reject message {}, error code {:?}", .reject.reject_code, .reject.reject_message, .reject.error_code)]
CertifiedReject {
/// The rejection returned by the replica.
reject: RejectResponse,
/// The operation that was rejected. Not always available.
operation: Option<Operation>,
},
/// The subnet may have rejected the message. This rejection cannot be verified as authentic.
#[error("The replica returned a rejection error: reject code {:?}, reject message {}, error code {:?}", .reject.reject_code, .reject.reject_message, .reject.error_code)]
UncertifiedReject {
/// The rejection returned by the boundary node.
reject: RejectResponse,
/// The operation that was rejected. Not always available.
operation: Option<Operation>,
},
/// The replica returned an HTTP error.
#[error("The replica returned an HTTP Error: {0}")]
HttpError(HttpErrorPayload),
/// The status endpoint returned an invalid status.
#[error("Status endpoint returned an invalid status.")]
InvalidReplicaStatus,
/// The call was marked done, but no reply was provided.
#[error("Call was marked as done but we never saw the reply. Request ID: {0}")]
RequestStatusDoneNoReply(String),
/// A string error occurred in an external tool.
#[error("A tool returned a string message error: {0}")]
MessageError(String),
/// There was an error reading a LEB128 value.
#[error("Error reading LEB128 value: {0}")]
Leb128ReadError(#[from] read::Error),
/// A string was invalid UTF-8.
#[error("Error in UTF-8 string: {0}")]
Utf8ReadError(#[from] Utf8Error),
/// The lookup path was absent in the certificate.
#[error("The lookup path ({0:?}) is absent in the certificate.")]
LookupPathAbsent(Vec<Label>),
/// The lookup path was unknown in the certificate.
#[error("The lookup path ({0:?}) is unknown in the certificate.")]
LookupPathUnknown(Vec<Label>),
/// The lookup path did not make sense for the certificate.
#[error("The lookup path ({0:?}) does not make sense for the certificate.")]
LookupPathError(Vec<Label>),
/// The request status at the requested path was invalid.
#[error("The request status ({1}) at path {0:?} is invalid.")]
InvalidRequestStatus(Vec<Label>, String),
/// The certificate verification for a `read_state` call failed.
#[error("Certificate verification failed.")]
CertificateVerificationFailed(),
/// The signature verification for a query call failed.
#[error("Query signature verification failed.")]
QuerySignatureVerificationFailed,
/// The certificate contained a delegation that does not include the `effective_canister_id` in the `canister_ranges` field.
#[error("Certificate is not authorized to respond to queries for this canister. While developing: Did you forget to set effective_canister_id?")]
CertificateNotAuthorized(),
/// The certificate was older than allowed by the `ingress_expiry`.
#[error("Certificate is stale (over {0:?}). Is the computer's clock synchronized?")]
CertificateOutdated(Duration),
/// The certificate contained more than one delegation.
#[error("The certificate contained more than one delegation")]
CertificateHasTooManyDelegations,
/// The query response did not contain any node signatures.
#[error("Query response did not contain any node signatures")]
MissingSignature,
/// The query response contained a malformed signature.
#[error("Query response contained a malformed signature")]
MalformedSignature,
/// The read-state response contained a malformed public key.
#[error("Read state response contained a malformed public key")]
MalformedPublicKey,
/// The query response contained more node signatures than the subnet has nodes.
#[error("Query response contained too many signatures ({had}, exceeding the subnet's total nodes: {needed})")]
TooManySignatures {
/// The number of provided signatures.
had: usize,
/// The number of nodes on the subnet.
needed: usize,
},
/// There was a length mismatch between the expected and actual length of the BLS DER-encoded public key.
#[error(
r#"BLS DER-encoded public key must be ${expected} bytes long, but is {actual} bytes long."#
)]
DerKeyLengthMismatch {
/// The expected length of the key.
expected: usize,
/// The actual length of the key.
actual: usize,
},
/// There was a mismatch between the expected and actual prefix of the BLS DER-encoded public key.
#[error("BLS DER-encoded public key is invalid. Expected the following prefix: ${expected:?}, but got ${actual:?}")]
DerPrefixMismatch {
/// The expected key prefix.
expected: Vec<u8>,
/// The actual key prefix.
actual: Vec<u8>,
},
/// The status response did not contain a root key.
#[error("The status response did not contain a root key. Status: {0}")]
NoRootKeyInStatus(Status),
/// The invocation to the wallet call forward method failed with an error.
#[error("The invocation to the wallet call forward method failed with the error: {0}")]
WalletCallFailed(String),
/// The wallet operation failed.
#[error("The wallet operation failed: {0}")]
WalletError(String),
/// The wallet canister must be upgraded. See [`dfx wallet upgrade`](https://internetcomputer.org/docs/current/references/cli-reference/dfx-wallet)
#[error("The wallet canister must be upgraded: {0}")]
WalletUpgradeRequired(String),
/// The response size exceeded the provided limit.
#[error("Response size exceeded limit.")]
ResponseSizeExceededLimit(),
/// An unknown error occurred during communication with the replica.
#[error("An error happened during communication with the replica: {0}")]
TransportError(TransportError),
/// There was a mismatch between the expected and actual CBOR data during inspection.
#[error("There is a mismatch between the CBOR encoded call and the arguments: field {field}, value in argument is {value_arg}, value in CBOR is {value_cbor}")]
CallDataMismatch {
/// The field that was mismatched.
field: String,
/// The value that was expected to be in the CBOR.
value_arg: String,
/// The value that was actually in the CBOR.
value_cbor: String,
},
/// The rejected call had an invalid reject code (valid range 1..5).
#[error(transparent)]
InvalidRejectCode(#[from] InvalidRejectCodeError),
/// Route provider failed to generate a url for some reason.
#[error("Route provider failed to generate url: {0}")]
RouteProviderError(String),
/// Invalid HTTP response.
#[error("Invalid HTTP response: {0}")]
InvalidHttpResponse(String),
}
impl PartialEq for AgentError {
fn eq(&self, other: &Self) -> bool {
// Verify the debug string is the same. Some of the subtypes of this error
// don't implement Eq or PartialEq, so we cannot rely on derive.
format!("{self:?}") == format!("{other:?}")
}
}
impl From<candid::Error> for AgentError {
fn from(e: candid::Error) -> AgentError {
AgentError::CandidError(e.into())
}
}
/// A HTTP error from the replica.
pub struct HttpErrorPayload {
/// The HTTP status code.
pub status: u16,
/// The MIME type of `content`.
pub content_type: Option<String>,
/// The body of the error.
pub content: Vec<u8>,
}
impl HttpErrorPayload {
fn fmt_human_readable(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
// No matter content_type is TEXT or not,
// always try to parse it as a String.
// When fail, print the raw byte array
f.write_fmt(format_args!(
"Http Error: status {}, content type {:?}, content: {}",
http::StatusCode::from_u16(self.status)
.map_or_else(|_| format!("{}", self.status), |code| format!("{code}")),
self.content_type.clone().unwrap_or_default(),
String::from_utf8(self.content.clone()).unwrap_or_else(|_| format!(
"(unable to decode content as UTF-8: {:?})",
self.content
))
))?;
Ok(())
}
}
impl Debug for HttpErrorPayload {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
self.fmt_human_readable(f)
}
}
impl Display for HttpErrorPayload {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
self.fmt_human_readable(f)
}
}
/// An operation that can result in a reject.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Operation {
/// A call to a canister method.
Call {
/// The canister whose method was called.
canister: Principal,
/// The name of the method.
method: String,
},
/// A read of the state tree, in the context of a canister. This will *not* be returned for request polling.
ReadState {
/// The requested paths within the state tree.
paths: Vec<Vec<String>>,
/// The canister the read request was made in the context of.
canister: Principal,
},
/// A read of the state tree, in the context of a subnet.
ReadSubnetState {
/// The requested paths within the state tree.
paths: Vec<Vec<String>>,
/// The subnet the read request was made in the context of.
subnet: Principal,
},
}
#[cfg(test)]
mod tests {
use super::HttpErrorPayload;
use crate::AgentError;
#[test]
fn content_type_none_valid_utf8() {
let payload = HttpErrorPayload {
status: 420,
content_type: None,
content: vec![104, 101, 108, 108, 111],
};
assert_eq!(
format!("{}", AgentError::HttpError(payload)),
r#"The replica returned an HTTP Error: Http Error: status 420 <unknown status code>, content type "", content: hello"#,
);
}
#[test]
fn content_type_none_invalid_utf8() {
let payload = HttpErrorPayload {
status: 420,
content_type: None,
content: vec![195, 40],
};
assert_eq!(
format!("{}", AgentError::HttpError(payload)),
r#"The replica returned an HTTP Error: Http Error: status 420 <unknown status code>, content type "", content: (unable to decode content as UTF-8: [195, 40])"#,
);
}
#[test]
fn formats_text_plain() {
let payload = HttpErrorPayload {
status: 420,
content_type: Some("text/plain".to_string()),
content: vec![104, 101, 108, 108, 111],
};
assert_eq!(
format!("{}", AgentError::HttpError(payload)),
r#"The replica returned an HTTP Error: Http Error: status 420 <unknown status code>, content type "text/plain", content: hello"#,
);
}
#[test]
fn formats_text_plain_charset_utf8() {
let payload = HttpErrorPayload {
status: 420,
content_type: Some("text/plain; charset=utf-8".to_string()),
content: vec![104, 101, 108, 108, 111],
};
assert_eq!(
format!("{}", AgentError::HttpError(payload)),
r#"The replica returned an HTTP Error: Http Error: status 420 <unknown status code>, content type "text/plain; charset=utf-8", content: hello"#,
);
}
#[test]
fn formats_text_html() {
let payload = HttpErrorPayload {
status: 420,
content_type: Some("text/html".to_string()),
content: vec![119, 111, 114, 108, 100],
};
assert_eq!(
format!("{}", AgentError::HttpError(payload)),
r#"The replica returned an HTTP Error: Http Error: status 420 <unknown status code>, content type "text/html", content: world"#,
);
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/status.rs | ic-agent/src/agent/status.rs | //! Types for interacting with the status endpoint of a replica. See [`Status`] for details.
use std::{collections::BTreeMap, fmt::Debug};
/// Value returned by the status endpoint of a replica. This is a loose mapping to CBOR values.
/// Because the agent should not return [`serde_cbor::Value`] directly across API boundaries,
/// we reimplement it as [`Value`] here.
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Hash)]
pub enum Value {
/// See [`Null`](serde_cbor::Value::Null).
Null,
/// See [`String`](serde_cbor::Value::Text).
String(String),
/// See [`Integer`](serde_cbor::Value::Integer).
Integer(i64),
/// See [`Bool`](serde_cbor::Value::Bool).
Bool(bool),
/// See [`Bytes`](serde_cbor::Value::Bytes).
Bytes(Vec<u8>),
/// See [`Vec`](serde_cbor::Value::Array).
Vec(Vec<Value>),
/// See [`Map`](serde_cbor::Value::Map).
Map(BTreeMap<String, Box<Value>>),
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::Null => f.write_str("null"),
Value::String(s) => f.write_fmt(format_args!(r#""{}""#, s.escape_debug())),
Value::Integer(i) => f.write_str(&i.to_string()),
Value::Bool(true) => f.write_str("true"),
Value::Bool(false) => f.write_str("false"),
Value::Bytes(b) => f.debug_list().entries(b).finish(),
Value::Vec(v) => f.debug_list().entries(v).finish(),
Value::Map(m) => f.debug_map().entries(m).finish(),
}
}
}
/// The structure returned by [`super::Agent::status`], containing the information returned
/// by the status endpoint of a replica.
#[derive(Debug, Ord, PartialOrd, PartialEq, Eq)]
pub struct Status {
/// Optional. The precise git revision of the Internet Computer Protocol implementation.
pub impl_version: Option<String>,
/// Optional. The health status of the replica. One hopes it's "healthy".
pub replica_health_status: Option<String>,
/// Optional. The root (public) key used to verify certificates.
pub root_key: Option<Vec<u8>>,
/// Contains any additional values that the replica gave as status.
pub values: BTreeMap<String, Box<Value>>,
}
impl std::fmt::Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("{\n")?;
let mut first = true;
for (key, value) in &self.values {
if first {
first = false;
} else {
f.write_str(",\n")?;
}
f.write_fmt(format_args!(r#" "{}": "#, key.escape_debug()))?;
std::fmt::Display::fmt(&value, f)?;
}
f.write_str("\n}")
}
}
fn cbor_value_to_value(value: &serde_cbor::Value) -> Result<Value, ()> {
match value {
serde_cbor::Value::Null => Ok(Value::Null),
serde_cbor::Value::Bool(b) => Ok(Value::Bool(*b)),
serde_cbor::Value::Integer(i) => Ok(Value::Integer(*i as i64)),
serde_cbor::Value::Bytes(b) => Ok(Value::Bytes(b.to_owned())),
serde_cbor::Value::Text(s) => Ok(Value::String(s.to_owned())),
serde_cbor::Value::Array(a) => Ok(Value::Vec(
a.iter()
.map(cbor_value_to_value)
.collect::<Result<Vec<Value>, ()>>()
.map_err(|_| ())?,
)),
serde_cbor::Value::Map(m) => {
let mut map = BTreeMap::new();
for (key, value) in m {
let k = match key {
serde_cbor::Value::Text(t) => t.to_owned(),
serde_cbor::Value::Integer(i) => i.to_string(),
_ => return Err(()),
};
let v = Box::new(cbor_value_to_value(value)?);
map.insert(k, v);
}
Ok(Value::Map(map))
}
serde_cbor::Value::Tag(_, v) => cbor_value_to_value(v.as_ref()),
_ => Err(()),
}
}
impl std::convert::TryFrom<&serde_cbor::Value> for Status {
type Error = ();
fn try_from(value: &serde_cbor::Value) -> Result<Self, ()> {
let v = cbor_value_to_value(value)?;
match v {
Value::Map(map) => {
let impl_version: Option<String> = map.get("impl_version").and_then(|v| {
if let Value::String(s) = v.as_ref() {
Some(s.to_owned())
} else {
None
}
});
let replica_health_status: Option<String> =
map.get("replica_health_status").and_then(|v| {
if let Value::String(s) = v.as_ref() {
Some(s.to_owned())
} else {
None
}
});
let root_key: Option<Vec<u8>> = map.get("root_key").and_then(|v| {
if let Value::Bytes(bytes) = v.as_ref() {
Some(bytes.to_owned())
} else {
None
}
});
Ok(Status {
impl_version,
replica_health_status,
root_key,
values: map,
})
}
_ => Err(()),
}
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/route_provider.rs | ic-agent/src/agent/route_provider.rs | //! A [`RouteProvider`] for dynamic generation of routing urls.
use arc_swap::ArcSwapOption;
use dynamic_routing::{
dynamic_route_provider::DynamicRouteProviderBuilder,
node::Node,
snapshot::{
latency_based_routing::LatencyRoutingSnapshot,
round_robin_routing::RoundRobinRoutingSnapshot,
},
};
use std::{
future::Future,
str::FromStr,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
time::Duration,
};
use url::Url;
use crate::agent::AgentError;
use super::HttpService;
#[cfg(not(feature = "_internal_dynamic-routing"))]
pub(crate) mod dynamic_routing;
#[cfg(feature = "_internal_dynamic-routing")]
pub mod dynamic_routing;
const IC0_DOMAIN: &str = "ic0.app";
const ICP0_DOMAIN: &str = "icp0.io";
const ICP_API_DOMAIN: &str = "icp-api.io";
const LOCALHOST_DOMAIN: &str = "localhost";
const IC0_SUB_DOMAIN: &str = ".ic0.app";
const ICP0_SUB_DOMAIN: &str = ".icp0.io";
const ICP_API_SUB_DOMAIN: &str = ".icp-api.io";
const LOCALHOST_SUB_DOMAIN: &str = ".localhost";
/// Statistical info about routing urls.
#[derive(Debug, PartialEq)]
pub struct RoutesStats {
/// Total number of existing routes (both healthy and unhealthy).
pub total: usize,
/// Number of currently healthy routes, or None if health status information is unavailable.
/// A healthy route is one that is available and ready to receive traffic.
/// The specific criteria for what constitutes a "healthy" route is implementation dependent.
pub healthy: Option<usize>,
}
impl RoutesStats {
/// Creates an new instance of [`RoutesStats`].
pub fn new(total: usize, healthy: Option<usize>) -> Self {
Self { total, healthy }
}
}
/// A [`RouteProvider`] for dynamic generation of routing urls.
pub trait RouteProvider: std::fmt::Debug + Send + Sync {
/// Generates the next routing URL based on the internal routing logic.
///
/// This method returns a single `Url` that can be used for routing.
/// The logic behind determining the next URL can vary depending on the implementation
fn route(&self) -> Result<Url, AgentError>;
/// Generates up to `n` different routing URLs in order of priority.
///
/// This method returns a vector of `Url` instances, each representing a routing
/// endpoint. The URLs are ordered by priority, with the most preferred route
/// appearing first. The returned vector can contain fewer than `n` URLs if
/// fewer are available.
fn n_ordered_routes(&self, n: usize) -> Result<Vec<Url>, AgentError>;
/// Returns statistics about the total number of existing routes and the number of healthy routes.
fn routes_stats(&self) -> RoutesStats;
}
/// A simple implementation of the [`RouteProvider`] which produces an even distribution of the urls from the input ones.
#[derive(Debug)]
pub struct RoundRobinRouteProvider {
routes: Vec<Url>,
current_idx: AtomicUsize,
}
impl RouteProvider for RoundRobinRouteProvider {
/// Generates a url for the given endpoint.
fn route(&self) -> Result<Url, AgentError> {
if self.routes.is_empty() {
return Err(AgentError::RouteProviderError(
"No routing urls provided".to_string(),
));
}
// This operation wraps around an overflow, i.e. after max is reached the value is reset back to 0.
let prev_idx = self.current_idx.fetch_add(1, Ordering::Relaxed);
Ok(self.routes[prev_idx % self.routes.len()].clone())
}
fn n_ordered_routes(&self, n: usize) -> Result<Vec<Url>, AgentError> {
if n == 0 {
return Ok(Vec::new());
}
if n >= self.routes.len() {
return Ok(self.routes.clone());
}
let idx = self.current_idx.fetch_add(n, Ordering::Relaxed) % self.routes.len();
let mut urls = Vec::with_capacity(n);
if self.routes.len() - idx >= n {
urls.extend_from_slice(&self.routes[idx..idx + n]);
} else {
urls.extend_from_slice(&self.routes[idx..]);
urls.extend_from_slice(&self.routes[..n - urls.len()]);
}
Ok(urls)
}
fn routes_stats(&self) -> RoutesStats {
RoutesStats::new(self.routes.len(), None)
}
}
impl RoundRobinRouteProvider {
/// Construct [`RoundRobinRouteProvider`] from a vector of urls.
pub fn new<T: AsRef<str>>(routes: Vec<T>) -> Result<Self, AgentError> {
let routes: Result<Vec<Url>, _> = routes
.into_iter()
.map(|url| {
Url::from_str(url.as_ref()).and_then(|mut url| {
// rewrite *.ic0.app to ic0.app
if let Some(domain) = url.domain() {
if domain.ends_with(IC0_SUB_DOMAIN) {
url.set_host(Some(IC0_DOMAIN))?;
} else if domain.ends_with(ICP0_SUB_DOMAIN) {
url.set_host(Some(ICP0_DOMAIN))?;
} else if domain.ends_with(ICP_API_SUB_DOMAIN) {
url.set_host(Some(ICP_API_DOMAIN))?;
} else if domain.ends_with(LOCALHOST_SUB_DOMAIN) {
url.set_host(Some(LOCALHOST_DOMAIN))?;
}
}
Ok(url)
})
})
.collect();
Ok(Self {
routes: routes?,
current_idx: AtomicUsize::new(0),
})
}
}
impl RouteProvider for Url {
fn route(&self) -> Result<Url, AgentError> {
Ok(self.clone())
}
fn n_ordered_routes(&self, _: usize) -> Result<Vec<Url>, AgentError> {
Ok(vec![self.route()?])
}
fn routes_stats(&self) -> RoutesStats {
RoutesStats::new(1, None)
}
}
/// A [`RouteProvider`] that will attempt to discover new boundary nodes and cycle through them, optionally prioritizing those with low latency.
#[derive(Debug)]
pub struct DynamicRouteProvider {
inner: Box<dyn RouteProvider>,
}
impl DynamicRouteProvider {
/// Create a new `DynamicRouter` from a list of seed domains and a routing strategy.
pub async fn run_in_background(
seed_domains: Vec<String>,
client: Arc<dyn HttpService>,
strategy: DynamicRoutingStrategy,
) -> Result<Self, AgentError> {
let seed_nodes: Result<Vec<_>, _> = seed_domains.into_iter().map(Node::new).collect();
let boxed = match strategy {
DynamicRoutingStrategy::ByLatency => Box::new(
DynamicRouteProviderBuilder::new(
LatencyRoutingSnapshot::new(),
seed_nodes?,
client,
)
.build()
.await,
) as Box<dyn RouteProvider>,
DynamicRoutingStrategy::RoundRobin => Box::new(
DynamicRouteProviderBuilder::new(
RoundRobinRoutingSnapshot::new(),
seed_nodes?,
client,
)
.build()
.await,
),
};
Ok(Self { inner: boxed })
}
/// Same as [`run_in_background`](Self::run_in_background), but with custom intervals for refreshing the routing list and health-checking nodes.
pub async fn run_in_background_with_intervals(
seed_domains: Vec<String>,
client: Arc<dyn HttpService>,
strategy: DynamicRoutingStrategy,
list_update_interval: Duration,
health_check_interval: Duration,
) -> Result<Self, AgentError> {
let seed_nodes: Result<Vec<_>, _> = seed_domains.into_iter().map(Node::new).collect();
let boxed = match strategy {
DynamicRoutingStrategy::ByLatency => Box::new(
DynamicRouteProviderBuilder::new(
LatencyRoutingSnapshot::new(),
seed_nodes?,
client,
)
.with_fetch_period(list_update_interval)
.with_check_period(health_check_interval)
.build()
.await,
) as Box<dyn RouteProvider>,
DynamicRoutingStrategy::RoundRobin => Box::new(
DynamicRouteProviderBuilder::new(
RoundRobinRoutingSnapshot::new(),
seed_nodes?,
client,
)
.with_fetch_period(list_update_interval)
.with_check_period(health_check_interval)
.build()
.await,
),
};
Ok(Self { inner: boxed })
}
}
impl RouteProvider for DynamicRouteProvider {
fn route(&self) -> Result<Url, AgentError> {
self.inner.route()
}
fn n_ordered_routes(&self, n: usize) -> Result<Vec<Url>, AgentError> {
self.inner.n_ordered_routes(n)
}
fn routes_stats(&self) -> RoutesStats {
self.inner.routes_stats()
}
}
/// Strategy for [`DynamicRouteProvider`]'s routing mechanism.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum DynamicRoutingStrategy {
/// Prefer nodes with low latency.
ByLatency,
/// Cycle through discovered nodes with no regard for latency.
RoundRobin,
}
#[derive(Debug)]
pub(crate) struct UrlUntilReady<R> {
url: Url,
router: ArcSwapOption<R>,
}
impl<R: RouteProvider + 'static> UrlUntilReady<R> {
pub(crate) fn new<
#[cfg(not(target_family = "wasm"))] F: Future<Output = R> + Send + 'static,
#[cfg(target_family = "wasm")] F: Future<Output = R> + 'static,
>(
url: Url,
fut: F,
) -> Arc<Self> {
let s = Arc::new(Self {
url,
router: ArcSwapOption::empty(),
});
let weak = Arc::downgrade(&s);
crate::util::spawn(async move {
let router = fut.await;
if let Some(outer) = weak.upgrade() {
outer.router.store(Some(Arc::new(router)))
}
});
s
}
}
impl<R: RouteProvider> RouteProvider for UrlUntilReady<R> {
fn n_ordered_routes(&self, n: usize) -> Result<Vec<Url>, AgentError> {
if let Some(r) = &*self.router.load() {
r.n_ordered_routes(n)
} else {
self.url.n_ordered_routes(n)
}
}
fn route(&self) -> Result<Url, AgentError> {
if let Some(r) = &*self.router.load() {
r.route()
} else {
self.url.route()
}
}
fn routes_stats(&self) -> RoutesStats {
RoutesStats::new(1, None)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_routes() {
let provider = RoundRobinRouteProvider::new::<&str>(vec![])
.expect("failed to create a route provider");
let result = provider.route().unwrap_err();
assert_eq!(
result,
AgentError::RouteProviderError("No routing urls provided".to_string())
);
}
#[test]
fn test_routes_rotation() {
let provider = RoundRobinRouteProvider::new(vec!["https://url1.com", "https://url2.com"])
.expect("failed to create a route provider");
let url_strings = ["https://url1.com", "https://url2.com", "https://url1.com"];
let expected_urls: Vec<Url> = url_strings
.iter()
.map(|url_str| Url::parse(url_str).expect("Invalid URL"))
.collect();
let urls: Vec<Url> = (0..3)
.map(|_| provider.route().expect("failed to get next url"))
.collect();
assert_eq!(expected_urls, urls);
}
#[test]
fn test_n_routes() {
// Test with an empty list of urls
let provider = RoundRobinRouteProvider::new(Vec::<&str>::new())
.expect("failed to create a route provider");
let urls_iter = provider.n_ordered_routes(1).expect("failed to get urls");
assert!(urls_iter.is_empty());
// Test with non-empty list of urls
let provider = RoundRobinRouteProvider::new(vec![
"https://url1.com",
"https://url2.com",
"https://url3.com",
"https://url4.com",
"https://url5.com",
])
.expect("failed to create a route provider");
// First call
let urls: Vec<_> = provider.n_ordered_routes(3).expect("failed to get urls");
let expected_urls: Vec<Url> = ["https://url1.com", "https://url2.com", "https://url3.com"]
.iter()
.map(|url_str| Url::parse(url_str).expect("invalid URL"))
.collect();
assert_eq!(urls, expected_urls);
// Second call
let urls: Vec<_> = provider.n_ordered_routes(3).expect("failed to get urls");
let expected_urls: Vec<Url> = ["https://url4.com", "https://url5.com", "https://url1.com"]
.iter()
.map(|url_str| Url::parse(url_str).expect("invalid URL"))
.collect();
assert_eq!(urls, expected_urls);
// Third call
let urls: Vec<_> = provider.n_ordered_routes(2).expect("failed to get urls");
let expected_urls: Vec<Url> = ["https://url2.com", "https://url3.com"]
.iter()
.map(|url_str| Url::parse(url_str).expect("invalid URL"))
.collect();
assert_eq!(urls, expected_urls);
// Fourth call
let urls: Vec<_> = provider.n_ordered_routes(5).expect("failed to get urls");
let expected_urls: Vec<Url> = [
"https://url1.com",
"https://url2.com",
"https://url3.com",
"https://url4.com",
"https://url5.com",
]
.iter()
.map(|url_str| Url::parse(url_str).expect("invalid URL"))
.collect();
assert_eq!(urls, expected_urls);
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/mod.rs | ic-agent/src/agent/mod.rs | //! The main Agent module. Contains the [Agent] type and all associated structures.
pub(crate) mod agent_config;
pub mod agent_error;
pub(crate) mod builder;
// delete this module after 0.40
#[doc(hidden)]
#[deprecated(since = "0.38.0", note = "use the AgentBuilder methods")]
pub mod http_transport;
pub(crate) mod nonce;
pub(crate) mod response_authentication;
pub mod route_provider;
pub mod status;
pub mod subnet;
pub use agent_config::AgentConfig;
pub use agent_error::AgentError;
use agent_error::{HttpErrorPayload, Operation};
use async_lock::Semaphore;
use async_trait::async_trait;
pub use builder::AgentBuilder;
use bytes::Bytes;
use cached::{Cached, TimedCache};
use http::{header::CONTENT_TYPE, HeaderMap, Method, StatusCode, Uri};
use ic_ed25519::{PublicKey, SignatureError};
#[doc(inline)]
pub use ic_transport_types::{
signed, CallResponse, Envelope, EnvelopeContent, RejectCode, RejectResponse, ReplyResponse,
RequestStatusResponse,
};
pub use nonce::{NonceFactory, NonceGenerator};
use rangemap::{RangeInclusiveMap, StepFns};
use reqwest::{Client, Request, Response};
use route_provider::{
dynamic_routing::{
dynamic_route_provider::DynamicRouteProviderBuilder, node::Node,
snapshot::latency_based_routing::LatencyRoutingSnapshot,
},
RouteProvider, UrlUntilReady,
};
pub use subnet::Subnet;
use time::OffsetDateTime;
use tower_service::Service;
#[cfg(test)]
mod agent_test;
use crate::{
agent::response_authentication::{
extract_der, lookup_canister_info, lookup_canister_metadata, lookup_canister_ranges,
lookup_incomplete_subnet, lookup_request_status, lookup_subnet_and_ranges,
lookup_subnet_canister_ranges, lookup_subnet_metrics, lookup_time, lookup_tree,
lookup_value,
},
agent_error::TransportError,
export::Principal,
identity::Identity,
to_request_id, RequestId,
};
use backoff::{backoff::Backoff, ExponentialBackoffBuilder};
use backoff::{exponential::ExponentialBackoff, SystemClock};
use ic_certification::{Certificate, Delegation, Label};
use ic_transport_types::{
signed::{SignedQuery, SignedRequestStatus, SignedUpdate},
QueryResponse, ReadStateResponse, SubnetMetrics, TransportCallResponse,
};
use serde::Serialize;
use status::Status;
use std::{
borrow::Cow,
convert::TryFrom,
fmt::{self, Debug},
future::{Future, IntoFuture},
pin::Pin,
str::FromStr,
sync::{Arc, Mutex, RwLock},
task::{Context, Poll},
time::Duration,
};
use crate::agent::response_authentication::lookup_api_boundary_nodes;
const IC_STATE_ROOT_DOMAIN_SEPARATOR: &[u8; 14] = b"\x0Dic-state-root";
const IC_ROOT_KEY: &[u8; 133] = b"\x30\x81\x82\x30\x1d\x06\x0d\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x01\x02\x01\x06\x0c\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x02\x01\x03\x61\x00\x81\x4c\x0e\x6e\xc7\x1f\xab\x58\x3b\x08\xbd\x81\x37\x3c\x25\x5c\x3c\x37\x1b\x2e\x84\x86\x3c\x98\xa4\xf1\xe0\x8b\x74\x23\x5d\x14\xfb\x5d\x9c\x0c\xd5\x46\xd9\x68\x5f\x91\x3a\x0c\x0b\x2c\xc5\x34\x15\x83\xbf\x4b\x43\x92\xe4\x67\xdb\x96\xd6\x5b\x9b\xb4\xcb\x71\x71\x12\xf8\x47\x2e\x0d\x5a\x4d\x14\x50\x5f\xfd\x74\x84\xb0\x12\x91\x09\x1c\x5f\x87\xb9\x88\x83\x46\x3f\x98\x09\x1a\x0b\xaa\xae";
#[cfg(not(target_family = "wasm"))]
type AgentFuture<'a, V> = Pin<Box<dyn Future<Output = Result<V, AgentError>> + Send + 'a>>;
#[cfg(target_family = "wasm")]
type AgentFuture<'a, V> = Pin<Box<dyn Future<Output = Result<V, AgentError>> + 'a>>;
/// A low level Agent to make calls to a Replica endpoint.
///
#[cfg_attr(unix, doc = " ```rust")] // pocket-ic
#[cfg_attr(not(unix), doc = " ```ignore")]
/// use ic_agent::{Agent, export::Principal};
/// use candid::{Encode, Decode, CandidType, Nat};
/// use serde::Deserialize;
///
/// #[derive(CandidType)]
/// struct Argument {
/// amount: Option<Nat>,
/// }
///
/// #[derive(CandidType, Deserialize)]
/// struct CreateCanisterResult {
/// canister_id: Principal,
/// }
///
/// # fn create_identity() -> impl ic_agent::Identity {
/// # // In real code, the raw key should be either read from a pem file or generated with randomness.
/// # ic_agent::identity::BasicIdentity::from_raw_key(&[0u8;32])
/// # }
/// #
/// async fn create_a_canister() -> Result<Principal, Box<dyn std::error::Error>> {
/// # Ok(ref_tests::utils::with_pic(async move |pic| {
/// # let url = ref_tests::utils::get_pic_url(&pic);
/// let agent = Agent::builder()
/// .with_url(url)
/// .with_identity(create_identity())
/// .build()?;
///
/// // Only do the following call when not contacting the IC main net (e.g. a local emulator).
/// // This is important as the main net public key is static and a rogue network could return
/// // a different key.
/// // If you know the root key ahead of time, you can use `agent.set_root_key(root_key);`.
/// agent.fetch_root_key().await?;
/// let management_canister_id = Principal::from_text("aaaaa-aa")?;
///
/// // Create a call to the management canister to create a new canister ID, and wait for a result.
/// // This API only works in local instances; mainnet instances must use the cycles ledger.
/// // See `dfx info default-effective-canister-id`.
/// # let effective_canister_id = ref_tests::utils::get_effective_canister_id(&pic).await;
/// let response = agent.update(&management_canister_id, "provisional_create_canister_with_cycles")
/// .with_effective_canister_id(effective_canister_id)
/// .with_arg(Encode!(&Argument { amount: None })?)
/// .await?;
///
/// let result = Decode!(response.as_slice(), CreateCanisterResult)?;
/// let canister_id: Principal = Principal::from_text(&result.canister_id.to_text())?;
/// Ok(canister_id)
/// # }).await)
/// }
///
/// # let mut runtime = tokio::runtime::Runtime::new().unwrap();
/// # runtime.block_on(async {
/// let canister_id = create_a_canister().await.unwrap();
/// eprintln!("{}", canister_id);
/// # });
/// ```
///
/// This agent does not understand Candid, and only acts on byte buffers.
///
/// Some methods return certificates. While there is a `verify_certificate` method, any certificate
/// you receive from a method has already been verified and you do not need to manually verify it.
#[derive(Clone)]
pub struct Agent {
nonce_factory: Arc<dyn NonceGenerator>,
identity: Arc<dyn Identity>,
ingress_expiry: Duration,
root_key: Arc<RwLock<Vec<u8>>>,
client: Arc<dyn HttpService>,
route_provider: Arc<dyn RouteProvider>,
subnet_key_cache: Arc<Mutex<SubnetCache>>,
concurrent_requests_semaphore: Arc<Semaphore>,
verify_query_signatures: bool,
max_response_body_size: Option<usize>,
max_polling_time: Duration,
#[allow(dead_code)]
max_tcp_error_retries: usize,
}
impl fmt::Debug for Agent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_struct("Agent")
.field("ingress_expiry", &self.ingress_expiry)
.finish_non_exhaustive()
}
}
impl Agent {
/// Create an instance of an [`AgentBuilder`] for building an [`Agent`]. This is simpler than
/// using the [`AgentConfig`] and [`Agent::new()`].
pub fn builder() -> builder::AgentBuilder {
Default::default()
}
/// Create an instance of an [`Agent`].
pub fn new(config: agent_config::AgentConfig) -> Result<Agent, AgentError> {
let client = config.http_service.unwrap_or_else(|| {
Arc::new(Retry429Logic {
client: config.client.unwrap_or_else(|| {
#[cfg(not(target_family = "wasm"))]
{
Client::builder()
.use_rustls_tls()
.timeout(Duration::from_secs(360))
.build()
.expect("Could not create HTTP client.")
}
#[cfg(all(target_family = "wasm", feature = "wasm-bindgen"))]
{
Client::new()
}
}),
})
});
Ok(Agent {
nonce_factory: config.nonce_factory,
identity: config.identity,
ingress_expiry: config.ingress_expiry,
root_key: Arc::new(RwLock::new(IC_ROOT_KEY.to_vec())),
client: client.clone(),
route_provider: if let Some(route_provider) = config.route_provider {
route_provider
} else if let Some(url) = config.url {
if config.background_dynamic_routing {
assert!(
url.scheme() == "https" && url.path() == "/" && url.port().is_none() && url.domain().is_some(),
"in dynamic routing mode, URL must be in the exact form https://domain with no path, port, IP, or non-HTTPS scheme"
);
let seeds = vec![Node::new(url.domain().unwrap()).unwrap()];
UrlUntilReady::new(url, async move {
DynamicRouteProviderBuilder::new(
LatencyRoutingSnapshot::new(),
seeds,
client,
)
.build()
.await
}) as Arc<dyn RouteProvider>
} else {
Arc::new(url)
}
} else {
panic!("either route_provider or url must be specified");
},
subnet_key_cache: Arc::new(Mutex::new(SubnetCache::new())),
verify_query_signatures: config.verify_query_signatures,
concurrent_requests_semaphore: Arc::new(Semaphore::new(config.max_concurrent_requests)),
max_response_body_size: config.max_response_body_size,
max_tcp_error_retries: config.max_tcp_error_retries,
max_polling_time: config.max_polling_time,
})
}
/// Set the identity provider for signing messages.
///
/// NOTE: if you change the identity while having update calls in
/// flight, you will not be able to [`Agent::request_status_raw`] the status of these
/// messages.
pub fn set_identity<I>(&mut self, identity: I)
where
I: 'static + Identity,
{
self.identity = Arc::new(identity);
}
/// Set the arc identity provider for signing messages.
///
/// NOTE: if you change the identity while having update calls in
/// flight, you will not be able to [`Agent::request_status_raw`] the status of these
/// messages.
pub fn set_arc_identity(&mut self, identity: Arc<dyn Identity>) {
self.identity = identity;
}
/// By default, the agent is configured to talk to the main Internet Computer, and verifies
/// responses using a hard-coded public key.
///
/// This function will instruct the agent to ask the endpoint for its public key, and use
/// that instead. This is required when talking to a local test instance, for example.
///
/// *Only use this when you are _not_ talking to the main Internet Computer, otherwise
/// you are prone to man-in-the-middle attacks! Do not call this function by default.*
pub async fn fetch_root_key(&self) -> Result<(), AgentError> {
if self.read_root_key()[..] != IC_ROOT_KEY[..] {
// already fetched the root key
return Ok(());
}
let status = self.status().await?;
let Some(root_key) = status.root_key else {
return Err(AgentError::NoRootKeyInStatus(status));
};
self.set_root_key(root_key);
Ok(())
}
/// By default, the agent is configured to talk to the main Internet Computer, and verifies
/// responses using a hard-coded public key.
///
/// Using this function you can set the root key to a known one if you know if beforehand.
pub fn set_root_key(&self, root_key: Vec<u8>) {
*self.root_key.write().unwrap() = root_key;
}
/// Return the root key currently in use.
pub fn read_root_key(&self) -> Vec<u8> {
self.root_key.read().unwrap().clone()
}
fn get_expiry_date(&self) -> u64 {
let expiry_raw = OffsetDateTime::now_utc() + self.ingress_expiry;
let mut rounded = expiry_raw.replace_nanosecond(0).unwrap();
if self.ingress_expiry.as_secs() > 90 {
rounded = rounded.replace_second(0).unwrap();
}
rounded.unix_timestamp_nanos().try_into().unwrap()
}
/// Return the principal of the identity.
pub fn get_principal(&self) -> Result<Principal, String> {
self.identity.sender()
}
async fn query_endpoint<A>(
&self,
effective_canister_id: Principal,
serialized_bytes: Vec<u8>,
) -> Result<A, AgentError>
where
A: serde::de::DeserializeOwned,
{
let _permit = self.concurrent_requests_semaphore.acquire().await;
let bytes = self
.execute(
Method::POST,
&format!("api/v3/canister/{}/query", effective_canister_id.to_text()),
Some(serialized_bytes),
)
.await?
.1;
serde_cbor::from_slice(&bytes).map_err(AgentError::InvalidCborData)
}
async fn read_state_endpoint<A>(
&self,
effective_canister_id: Principal,
serialized_bytes: Vec<u8>,
) -> Result<A, AgentError>
where
A: serde::de::DeserializeOwned,
{
let _permit = self.concurrent_requests_semaphore.acquire().await;
let endpoint = format!(
"api/v3/canister/{}/read_state",
effective_canister_id.to_text()
);
let bytes = self
.execute(Method::POST, &endpoint, Some(serialized_bytes))
.await?
.1;
serde_cbor::from_slice(&bytes).map_err(AgentError::InvalidCborData)
}
async fn read_subnet_state_endpoint<A>(
&self,
subnet_id: Principal,
serialized_bytes: Vec<u8>,
) -> Result<A, AgentError>
where
A: serde::de::DeserializeOwned,
{
let _permit = self.concurrent_requests_semaphore.acquire().await;
let endpoint = format!("api/v3/subnet/{}/read_state", subnet_id.to_text());
let bytes = self
.execute(Method::POST, &endpoint, Some(serialized_bytes))
.await?
.1;
serde_cbor::from_slice(&bytes).map_err(AgentError::InvalidCborData)
}
async fn call_endpoint(
&self,
effective_canister_id: Principal,
serialized_bytes: Vec<u8>,
) -> Result<TransportCallResponse, AgentError> {
let _permit = self.concurrent_requests_semaphore.acquire().await;
let endpoint = format!("api/v4/canister/{}/call", effective_canister_id.to_text());
let (status_code, response_body) = self
.execute(Method::POST, &endpoint, Some(serialized_bytes))
.await?;
if status_code == StatusCode::ACCEPTED {
return Ok(TransportCallResponse::Accepted);
}
serde_cbor::from_slice(&response_body).map_err(AgentError::InvalidCborData)
}
/// The simplest way to do a query call; sends a byte array and will return a byte vector.
/// The encoding is left as an exercise to the user.
#[allow(clippy::too_many_arguments)]
async fn query_raw(
&self,
canister_id: Principal,
effective_canister_id: Principal,
method_name: String,
arg: Vec<u8>,
ingress_expiry_datetime: Option<u64>,
use_nonce: bool,
explicit_verify_query_signatures: Option<bool>,
) -> Result<Vec<u8>, AgentError> {
let operation = Operation::Call {
canister: canister_id,
method: method_name.clone(),
};
let content = self.query_content(
canister_id,
method_name,
arg,
ingress_expiry_datetime,
use_nonce,
)?;
let serialized_bytes = sign_envelope(&content, self.identity.clone())?;
self.query_inner(
effective_canister_id,
serialized_bytes,
content.to_request_id(),
explicit_verify_query_signatures,
operation,
)
.await
}
/// Send the signed query to the network. Will return a byte vector.
/// The bytes will be checked if it is a valid query.
/// If you want to inspect the fields of the query call, use [`signed_query_inspect`] before calling this method.
pub async fn query_signed(
&self,
effective_canister_id: Principal,
signed_query: Vec<u8>,
) -> Result<Vec<u8>, AgentError> {
let envelope: Envelope =
serde_cbor::from_slice(&signed_query).map_err(AgentError::InvalidCborData)?;
let EnvelopeContent::Query {
canister_id,
method_name,
..
} = &*envelope.content
else {
return Err(AgentError::CallDataMismatch {
field: "request_type".to_string(),
value_arg: "query".to_string(),
value_cbor: if matches!(*envelope.content, EnvelopeContent::Call { .. }) {
"update"
} else {
"read_state"
}
.to_string(),
});
};
let operation = Operation::Call {
canister: *canister_id,
method: method_name.clone(),
};
self.query_inner(
effective_canister_id,
signed_query,
envelope.content.to_request_id(),
None,
operation,
)
.await
}
/// Helper function for performing both the query call and possibly a `read_state` to check the subnet node keys.
///
/// This should be used instead of `query_endpoint`. No validation is performed on `signed_query`.
async fn query_inner(
&self,
effective_canister_id: Principal,
signed_query: Vec<u8>,
request_id: RequestId,
explicit_verify_query_signatures: Option<bool>,
operation: Operation,
) -> Result<Vec<u8>, AgentError> {
let response = if explicit_verify_query_signatures.unwrap_or(self.verify_query_signatures) {
let (response, mut subnet) = futures_util::try_join!(
self.query_endpoint::<QueryResponse>(effective_canister_id, signed_query),
self.get_subnet_by_canister(&effective_canister_id)
)?;
if response.signatures().is_empty() {
return Err(AgentError::MissingSignature);
} else if response.signatures().len() > subnet.node_keys.len() {
return Err(AgentError::TooManySignatures {
had: response.signatures().len(),
needed: subnet.node_keys.len(),
});
}
for signature in response.signatures() {
if OffsetDateTime::now_utc()
- OffsetDateTime::from_unix_timestamp_nanos(signature.timestamp.into()).unwrap()
> self.ingress_expiry
{
return Err(AgentError::CertificateOutdated(self.ingress_expiry));
}
let signable = response.signable(request_id, signature.timestamp);
let node_key = if let Some(node_key) = subnet.node_keys.get(&signature.identity) {
node_key
} else {
subnet = self
.fetch_subnet_by_canister(&effective_canister_id)
.await?;
subnet
.node_keys
.get(&signature.identity)
.ok_or(AgentError::CertificateNotAuthorized())?
};
if node_key.len() != 44 {
return Err(AgentError::DerKeyLengthMismatch {
expected: 44,
actual: node_key.len(),
});
}
const DER_PREFIX: [u8; 12] = [48, 42, 48, 5, 6, 3, 43, 101, 112, 3, 33, 0];
if node_key[..12] != DER_PREFIX {
return Err(AgentError::DerPrefixMismatch {
expected: DER_PREFIX.to_vec(),
actual: node_key[..12].to_vec(),
});
}
let pubkey = PublicKey::deserialize_raw(&node_key[12..])
.map_err(|_| AgentError::MalformedPublicKey)?;
match pubkey.verify_signature(&signable, &signature.signature[..]) {
Ok(()) => (),
Err(SignatureError::InvalidSignature) => {
return Err(AgentError::QuerySignatureVerificationFailed)
}
Err(SignatureError::InvalidLength) => {
return Err(AgentError::MalformedSignature)
}
_ => unreachable!(),
}
}
response
} else {
self.query_endpoint::<QueryResponse>(effective_canister_id, signed_query)
.await?
};
match response {
QueryResponse::Replied { reply, .. } => Ok(reply.arg),
QueryResponse::Rejected { reject, .. } => Err(AgentError::UncertifiedReject {
reject,
operation: Some(operation),
}),
}
}
fn query_content(
&self,
canister_id: Principal,
method_name: String,
arg: Vec<u8>,
ingress_expiry_datetime: Option<u64>,
use_nonce: bool,
) -> Result<EnvelopeContent, AgentError> {
Ok(EnvelopeContent::Query {
sender: self.identity.sender().map_err(AgentError::SigningError)?,
canister_id,
method_name,
arg,
ingress_expiry: ingress_expiry_datetime.unwrap_or_else(|| self.get_expiry_date()),
nonce: use_nonce.then(|| self.nonce_factory.generate()).flatten(),
})
}
/// The simplest way to do an update call; sends a byte array and will return a response, [`CallResponse`], from the replica.
async fn update_raw(
&self,
canister_id: Principal,
effective_canister_id: Principal,
method_name: String,
arg: Vec<u8>,
ingress_expiry_datetime: Option<u64>,
) -> Result<CallResponse<(Vec<u8>, Certificate)>, AgentError> {
let nonce = self.nonce_factory.generate();
let content = self.update_content(
canister_id,
method_name.clone(),
arg,
ingress_expiry_datetime,
nonce,
)?;
let operation = Some(Operation::Call {
canister: canister_id,
method: method_name,
});
let request_id = to_request_id(&content)?;
let serialized_bytes = sign_envelope(&content, self.identity.clone())?;
let response_body = self
.call_endpoint(effective_canister_id, serialized_bytes)
.await?;
match response_body {
TransportCallResponse::Replied { certificate } => {
let certificate =
serde_cbor::from_slice(&certificate).map_err(AgentError::InvalidCborData)?;
self.verify(&certificate, effective_canister_id)?;
let status = lookup_request_status(&certificate, &request_id)?;
match status {
RequestStatusResponse::Replied(reply) => {
Ok(CallResponse::Response((reply.arg, certificate)))
}
RequestStatusResponse::Rejected(reject_response) => {
Err(AgentError::CertifiedReject {
reject: reject_response,
operation,
})?
}
_ => Ok(CallResponse::Poll(request_id)),
}
}
TransportCallResponse::Accepted => Ok(CallResponse::Poll(request_id)),
TransportCallResponse::NonReplicatedRejection(reject_response) => {
Err(AgentError::UncertifiedReject {
reject: reject_response,
operation,
})
}
}
}
/// Send the signed update to the network. Will return a [`CallResponse<Vec<u8>>`].
/// The bytes will be checked to verify that it is a valid update.
/// If you want to inspect the fields of the update, use [`signed_update_inspect`] before calling this method.
pub async fn update_signed(
&self,
effective_canister_id: Principal,
signed_update: Vec<u8>,
) -> Result<CallResponse<Vec<u8>>, AgentError> {
let envelope: Envelope =
serde_cbor::from_slice(&signed_update).map_err(AgentError::InvalidCborData)?;
let EnvelopeContent::Call {
canister_id,
method_name,
..
} = &*envelope.content
else {
return Err(AgentError::CallDataMismatch {
field: "request_type".to_string(),
value_arg: "update".to_string(),
value_cbor: if matches!(*envelope.content, EnvelopeContent::Query { .. }) {
"query"
} else {
"read_state"
}
.to_string(),
});
};
let operation = Some(Operation::Call {
canister: *canister_id,
method: method_name.clone(),
});
let request_id = to_request_id(&envelope.content)?;
let response_body = self
.call_endpoint(effective_canister_id, signed_update)
.await?;
match response_body {
TransportCallResponse::Replied { certificate } => {
let certificate =
serde_cbor::from_slice(&certificate).map_err(AgentError::InvalidCborData)?;
self.verify(&certificate, effective_canister_id)?;
let status = lookup_request_status(&certificate, &request_id)?;
match status {
RequestStatusResponse::Replied(reply) => Ok(CallResponse::Response(reply.arg)),
RequestStatusResponse::Rejected(reject_response) => {
Err(AgentError::CertifiedReject {
reject: reject_response,
operation,
})?
}
_ => Ok(CallResponse::Poll(request_id)),
}
}
TransportCallResponse::Accepted => Ok(CallResponse::Poll(request_id)),
TransportCallResponse::NonReplicatedRejection(reject_response) => {
Err(AgentError::UncertifiedReject {
reject: reject_response,
operation,
})
}
}
}
fn update_content(
&self,
canister_id: Principal,
method_name: String,
arg: Vec<u8>,
ingress_expiry_datetime: Option<u64>,
nonce: Option<Vec<u8>>,
) -> Result<EnvelopeContent, AgentError> {
Ok(EnvelopeContent::Call {
canister_id,
method_name,
arg,
nonce,
sender: self.identity.sender().map_err(AgentError::SigningError)?,
ingress_expiry: ingress_expiry_datetime.unwrap_or_else(|| self.get_expiry_date()),
})
}
fn get_retry_policy(&self) -> ExponentialBackoff<SystemClock> {
ExponentialBackoffBuilder::new()
.with_initial_interval(Duration::from_millis(500))
.with_max_interval(Duration::from_secs(1))
.with_multiplier(1.4)
.with_max_elapsed_time(Some(self.max_polling_time))
.build()
}
/// Wait for `request_status` to return a Replied response and return the arg.
pub async fn wait_signed(
&self,
request_id: &RequestId,
effective_canister_id: Principal,
signed_request_status: Vec<u8>,
) -> Result<(Vec<u8>, Certificate), AgentError> {
let mut retry_policy = self.get_retry_policy();
let mut request_accepted = false;
loop {
let (resp, cert) = self
.request_status_signed(
request_id,
effective_canister_id,
signed_request_status.clone(),
)
.await?;
match resp {
RequestStatusResponse::Unknown => {}
RequestStatusResponse::Received | RequestStatusResponse::Processing => {
if !request_accepted {
retry_policy.reset();
request_accepted = true;
}
}
RequestStatusResponse::Replied(ReplyResponse { arg, .. }) => {
return Ok((arg, cert))
}
RequestStatusResponse::Rejected(response) => {
return Err(AgentError::CertifiedReject {
reject: response,
operation: None,
})
}
RequestStatusResponse::Done => {
return Err(AgentError::RequestStatusDoneNoReply(String::from(
*request_id,
)))
}
};
match retry_policy.next_backoff() {
Some(duration) => crate::util::sleep(duration).await,
None => return Err(AgentError::TimeoutWaitingForResponse()),
}
}
}
/// Call `request_status` on the `RequestId` in a loop and return the response as a byte vector.
pub async fn wait(
&self,
request_id: &RequestId,
effective_canister_id: Principal,
) -> Result<(Vec<u8>, Certificate), AgentError> {
self.wait_inner(request_id, effective_canister_id, None)
.await
}
async fn wait_inner(
&self,
request_id: &RequestId,
effective_canister_id: Principal,
operation: Option<Operation>,
) -> Result<(Vec<u8>, Certificate), AgentError> {
let mut retry_policy = self.get_retry_policy();
let mut request_accepted = false;
loop {
let (resp, cert) = self
.request_status_raw(request_id, effective_canister_id)
.await?;
match resp {
RequestStatusResponse::Unknown => {}
RequestStatusResponse::Received | RequestStatusResponse::Processing => {
if !request_accepted {
// The system will return RequestStatusResponse::Unknown
// until the request is accepted
// and we generally cannot know how long that will take.
// State transitions between Received and Processing may be
// instantaneous. Therefore, once we know the request is accepted,
// we should restart the backoff so the request does not time out.
retry_policy.reset();
request_accepted = true;
}
}
RequestStatusResponse::Replied(ReplyResponse { arg, .. }) => {
return Ok((arg, cert))
}
RequestStatusResponse::Rejected(response) => {
return Err(AgentError::CertifiedReject {
reject: response,
operation,
})
}
RequestStatusResponse::Done => {
return Err(AgentError::RequestStatusDoneNoReply(String::from(
*request_id,
)))
}
};
match retry_policy.next_backoff() {
Some(duration) => crate::util::sleep(duration).await,
None => return Err(AgentError::TimeoutWaitingForResponse()),
}
}
}
/// Request the raw state tree directly, under an effective canister ID.
/// See [the protocol docs](https://internetcomputer.org/docs/current/references/ic-interface-spec#http-read-state) for more information.
pub async fn read_state_raw(
&self,
paths: Vec<Vec<Label>>,
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | true |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/agent_config.rs | ic-agent/src/agent/agent_config.rs | use reqwest::Client;
use url::Url;
use crate::{
agent::{NonceFactory, NonceGenerator},
identity::{anonymous::AnonymousIdentity, Identity},
};
use std::{sync::Arc, time::Duration};
use super::{route_provider::RouteProvider, HttpService};
/// A configuration for an agent.
#[non_exhaustive]
pub struct AgentConfig {
/// See [`with_nonce_factory`](super::AgentBuilder::with_nonce_factory).
pub nonce_factory: Arc<dyn NonceGenerator>,
/// See [`with_identity`](super::AgentBuilder::with_identity).
pub identity: Arc<dyn Identity>,
/// See [`with_ingress_expiry`](super::AgentBuilder::with_ingress_expiry).
pub ingress_expiry: Duration,
/// See [`with_http_client`](super::AgentBuilder::with_http_client).
pub client: Option<Client>,
/// See [`with_route_provider`](super::AgentBuilder::with_route_provider).
pub route_provider: Option<Arc<dyn RouteProvider>>,
/// See [`verify_query_signatures`](super::AgentBuilder::with_verify_query_signatures).
pub verify_query_signatures: bool,
/// See [`with_max_concurrent_requests`](super::AgentBuilder::with_max_concurrent_requests).
pub max_concurrent_requests: usize,
/// See [`with_max_response_body_size`](super::AgentBuilder::with_max_response_body_size).
pub max_response_body_size: Option<usize>,
/// See [`with_max_tcp_error_retries`](super::AgentBuilder::with_max_tcp_error_retries).
pub max_tcp_error_retries: usize,
/// See [`with_arc_http_middleware`](super::AgentBuilder::with_arc_http_middleware).
pub http_service: Option<Arc<dyn HttpService>>,
/// See [`with_max_polling_time`](super::AgentBuilder::with_max_polling_time).
pub max_polling_time: Duration,
/// See [`with_background_dynamic_routing`](super::AgentBuilder::with_background_dynamic_routing).
pub background_dynamic_routing: bool,
/// See [`with_url`](super::AgentBuilder::with_url).
pub url: Option<Url>,
}
impl Default for AgentConfig {
fn default() -> Self {
Self {
nonce_factory: Arc::new(NonceFactory::random()),
identity: Arc::new(AnonymousIdentity {}),
ingress_expiry: Duration::from_secs(3 * 60),
client: None,
http_service: None,
verify_query_signatures: true,
max_concurrent_requests: 50,
route_provider: None,
max_response_body_size: None,
max_tcp_error_retries: 0,
max_polling_time: Duration::from_secs(60 * 5),
background_dynamic_routing: false,
url: None,
}
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
dfinity/agent-rs | https://github.com/dfinity/agent-rs/blob/6fef5bfa96d2ed63b84afd173cc049e38cb5a210/ic-agent/src/agent/response_authentication.rs | ic-agent/src/agent/response_authentication.rs | use crate::agent::{
ApiBoundaryNode, PrincipalStep, RejectCode, RejectResponse, RequestStatusResponse,
};
use crate::{export::Principal, AgentError, RequestId};
use ic_certification::hash_tree::{HashTree, SubtreeLookupResult};
use ic_certification::{certificate::Certificate, hash_tree::Label, LookupResult};
use ic_transport_types::{ReplyResponse, SubnetMetrics};
use rangemap::RangeInclusiveSet;
use std::collections::{HashMap, HashSet};
use std::str::from_utf8;
use super::Subnet;
const DER_PREFIX: &[u8; 37] = b"\x30\x81\x82\x30\x1d\x06\x0d\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x01\x02\x01\x06\x0c\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x02\x01\x03\x61\x00";
const KEY_LENGTH: usize = 96;
pub fn extract_der(buf: Vec<u8>) -> Result<Vec<u8>, AgentError> {
let expected_length = DER_PREFIX.len() + KEY_LENGTH;
if buf.len() != expected_length {
return Err(AgentError::DerKeyLengthMismatch {
expected: expected_length,
actual: buf.len(),
});
}
let prefix = &buf[0..DER_PREFIX.len()];
if prefix[..] != DER_PREFIX[..] {
return Err(AgentError::DerPrefixMismatch {
expected: DER_PREFIX.to_vec(),
actual: prefix.to_vec(),
});
}
let key = &buf[DER_PREFIX.len()..];
Ok(key.to_vec())
}
pub(crate) fn lookup_time<Storage: AsRef<[u8]>>(
certificate: &Certificate<Storage>,
) -> Result<u64, AgentError> {
let mut time = lookup_value(&certificate.tree, ["time".as_bytes()])?;
Ok(leb128::read::unsigned(&mut time)?)
}
pub(crate) fn lookup_canister_info<Storage: AsRef<[u8]>>(
certificate: Certificate<Storage>,
canister_id: Principal,
path: &str,
) -> Result<Vec<u8>, AgentError> {
let path_canister = [
"canister".as_bytes(),
canister_id.as_slice(),
path.as_bytes(),
];
lookup_value(&certificate.tree, path_canister).map(<[u8]>::to_vec)
}
pub(crate) fn lookup_canister_metadata<Storage: AsRef<[u8]>>(
certificate: Certificate<Storage>,
canister_id: Principal,
path: &str,
) -> Result<Vec<u8>, AgentError> {
let path_canister = [
"canister".as_bytes(),
canister_id.as_slice(),
"metadata".as_bytes(),
path.as_bytes(),
];
lookup_value(&certificate.tree, path_canister).map(<[u8]>::to_vec)
}
pub(crate) fn lookup_subnet_metrics<Storage: AsRef<[u8]>>(
certificate: Certificate<Storage>,
subnet_id: Principal,
) -> Result<SubnetMetrics, AgentError> {
let path_stats = [b"subnet", subnet_id.as_slice(), b"metrics"];
let metrics = lookup_value(&certificate.tree, path_stats)?;
Ok(serde_cbor::from_slice(metrics)?)
}
pub(crate) fn lookup_subnet_canister_ranges<Storage: AsRef<[u8]>>(
certificate: &Certificate<Storage>,
subnet_id: Principal,
) -> Result<Vec<(Principal, Principal)>, AgentError> {
let path_ranges = [b"subnet", subnet_id.as_slice(), b"canister_ranges"];
let ranges = lookup_value(&certificate.tree, path_ranges)?;
Ok(serde_cbor::from_slice(ranges)?)
}
pub(crate) fn lookup_request_status<Storage: AsRef<[u8]>>(
certificate: &Certificate<Storage>,
request_id: &RequestId,
) -> Result<RequestStatusResponse, AgentError> {
use AgentError::*;
let path_status = [
"request_status".into(),
request_id.to_vec().into(),
"status".into(),
];
match certificate.tree.lookup_path(&path_status) {
LookupResult::Absent => Ok(RequestStatusResponse::Unknown),
LookupResult::Unknown => Err(LookupPathUnknown(path_status.to_vec())),
LookupResult::Found(status) => match from_utf8(status)? {
"done" => Ok(RequestStatusResponse::Done),
"processing" => Ok(RequestStatusResponse::Processing),
"received" => Ok(RequestStatusResponse::Received),
"rejected" => lookup_rejection(certificate, request_id),
"replied" => lookup_reply(certificate, request_id),
other => Err(InvalidRequestStatus(path_status.into(), other.to_string())),
},
LookupResult::Error => Err(LookupPathError(path_status.into())),
}
}
pub(crate) fn lookup_rejection<Storage: AsRef<[u8]>>(
certificate: &Certificate<Storage>,
request_id: &RequestId,
) -> Result<RequestStatusResponse, AgentError> {
let reject_code = lookup_reject_code(certificate, request_id)?;
let reject_message = lookup_reject_message(certificate, request_id)?;
let error_code = lookup_error_code(certificate, request_id)?;
Ok(RequestStatusResponse::Rejected(RejectResponse {
reject_code,
reject_message,
error_code,
}))
}
pub(crate) fn lookup_reject_code<Storage: AsRef<[u8]>>(
certificate: &Certificate<Storage>,
request_id: &RequestId,
) -> Result<RejectCode, AgentError> {
let path = [
"request_status".as_bytes(),
request_id.as_slice(),
"reject_code".as_bytes(),
];
let code = lookup_value(&certificate.tree, path)?;
let mut readable = code;
let code_digit = leb128::read::unsigned(&mut readable)?;
Ok(RejectCode::try_from(code_digit)?)
}
pub(crate) fn lookup_reject_message<Storage: AsRef<[u8]>>(
certificate: &Certificate<Storage>,
request_id: &RequestId,
) -> Result<String, AgentError> {
let path = [
"request_status".as_bytes(),
request_id.as_slice(),
"reject_message".as_bytes(),
];
let msg = lookup_value(&certificate.tree, path)?;
Ok(from_utf8(msg)?.to_string())
}
pub(crate) fn lookup_error_code<Storage: AsRef<[u8]>>(
certificate: &Certificate<Storage>,
request_id: &RequestId,
) -> Result<Option<String>, AgentError> {
let path = [
"request_status".as_bytes(),
request_id.as_slice(),
"error_code".as_bytes(),
];
let msg = lookup_value(&certificate.tree, path);
match msg {
Ok(val) => Ok(Some(from_utf8(val)?.to_string())),
Err(AgentError::LookupPathAbsent(_)) => Ok(None),
Err(e) => Err(e),
}
}
pub(crate) fn lookup_reply<Storage: AsRef<[u8]>>(
certificate: &Certificate<Storage>,
request_id: &RequestId,
) -> Result<RequestStatusResponse, AgentError> {
let path = [
"request_status".as_bytes(),
request_id.as_slice(),
"reply".as_bytes(),
];
let reply_data = lookup_value(&certificate.tree, path)?;
let arg = Vec::from(reply_data);
Ok(RequestStatusResponse::Replied(ReplyResponse { arg }))
}
/// The cert should contain both /subnet/<subnet_id> and /canister_ranges/<subnet_id>
pub(crate) fn lookup_subnet_and_ranges<Storage: AsRef<[u8]> + Clone>(
subnet_id: &Principal,
certificate: &Certificate<Storage>,
) -> Result<Subnet, AgentError> {
let mut subnet = lookup_incomplete_subnet(subnet_id, certificate)?;
let canister_ranges = lookup_canister_ranges(subnet_id, certificate)?;
subnet.canister_ranges = canister_ranges;
Ok(subnet)
}
/// This function will *not* populate `canister_ranges`. See [`lookup_canister_ranges`] or [`lookup_subnet_and_ranges`] for that.
pub(crate) fn lookup_incomplete_subnet<Storage: AsRef<[u8]> + Clone>(
subnet_id: &Principal,
certificate: &Certificate<Storage>,
) -> Result<Subnet, AgentError> {
let subnet_tree = lookup_tree(&certificate.tree, [b"subnet", subnet_id.as_slice()])?;
let key = lookup_value(&subnet_tree, [b"public_key".as_ref()])?.to_vec();
let node_keys_subtree = lookup_tree(&subnet_tree, [b"node".as_ref()])?;
let mut node_keys = HashMap::new();
for path in node_keys_subtree.list_paths() {
if path.len() < 2 {
// if it's absent, it's because this is the wrong subnet
return Err(AgentError::CertificateNotAuthorized());
}
if path[1].as_bytes() != b"public_key" {
continue;
}
if path.len() > 2 {
return Err(AgentError::LookupPathError(
path.into_iter()
.map(|label| label.as_bytes().to_vec().into())
.collect(),
));
}
let node_id = Principal::from_slice(path[0].as_bytes());
let node_key = lookup_value(&node_keys_subtree, [node_id.as_slice(), b"public_key"])?;
node_keys.insert(node_id, node_key.to_vec());
}
let subnet = Subnet {
id: *subnet_id,
canister_ranges: RangeInclusiveSet::new_with_step_fns(),
key,
node_keys,
};
Ok(subnet)
}
pub(crate) fn lookup_canister_ranges<Storage: AsRef<[u8]> + Clone>(
subnet_id: &Principal,
certificate: &Certificate<Storage>,
) -> Result<RangeInclusiveSet<Principal, PrincipalStep>, AgentError> {
match certificate
.tree
.lookup_path([b"subnet", subnet_id.as_slice(), b"canister_ranges"])
{
LookupResult::Found(_) => {
let ranges: Vec<(Principal, Principal)> =
lookup_subnet_canister_ranges(certificate, *subnet_id)?;
let mut canister_ranges = RangeInclusiveSet::new_with_step_fns();
for (low, high) in ranges {
canister_ranges.insert(low..=high);
}
Ok(canister_ranges)
}
_ => {
let canister_ranges_tree = lookup_tree(
&certificate.tree,
[b"canister_ranges", subnet_id.as_slice()],
)?;
let mut canister_ranges = RangeInclusiveSet::new_with_step_fns();
for shard in canister_ranges_tree.list_paths() {
let shard_ranges: Vec<(Principal, Principal)> =
serde_cbor::from_slice::<Vec<(Principal, Principal)>>(lookup_value(
&canister_ranges_tree,
[shard[0].as_bytes()],
)?)?;
for (low, high) in shard_ranges {
canister_ranges.insert(low..=high);
}
}
Ok(canister_ranges)
}
}
}
pub(crate) fn lookup_api_boundary_nodes<Storage: AsRef<[u8]> + Clone>(
certificate: Certificate<Storage>,
) -> Result<Vec<ApiBoundaryNode>, AgentError> {
// API boundary nodes paths in the state tree, as defined in the spec (https://internetcomputer.org/docs/current/references/ic-interface-spec#state-tree-api-bn).
let api_bn_path = "api_boundary_nodes".as_bytes();
let domain_path = "domain".as_bytes();
let ipv4_path = "ipv4_address".as_bytes();
let ipv6_path = "ipv6_address".as_bytes();
let api_bn_tree = lookup_tree(&certificate.tree, [api_bn_path])?;
let mut api_bns = Vec::<ApiBoundaryNode>::new();
let paths = api_bn_tree.list_paths();
let node_ids: HashSet<&[u8]> = paths.iter().map(|path| path[0].as_bytes()).collect();
for node_id in node_ids {
let domain =
String::from_utf8(lookup_value(&api_bn_tree, [node_id, domain_path])?.to_vec())
.map_err(|err| AgentError::Utf8ReadError(err.utf8_error()))?;
let ipv6_address =
String::from_utf8(lookup_value(&api_bn_tree, [node_id, ipv6_path])?.to_vec())
.map_err(|err| AgentError::Utf8ReadError(err.utf8_error()))?;
let ipv4_address = match lookup_value(&api_bn_tree, [node_id, ipv4_path]) {
Ok(ipv4) => Some(
String::from_utf8(ipv4.to_vec())
.map_err(|err| AgentError::Utf8ReadError(err.utf8_error()))?,
),
// By convention an absent path `/api_boundary_nodes/<node_id>/ipv4_address` in the state tree signifies that ipv4 is None.
Err(AgentError::LookupPathAbsent(_)) => None,
Err(err) => return Err(err),
};
let api_bn = ApiBoundaryNode {
domain,
ipv6_address,
ipv4_address,
};
api_bns.push(api_bn);
}
Ok(api_bns)
}
/// The path to [`lookup_value`]
pub trait LookupPath {
type Item: AsRef<[u8]>;
type Iter<'a>: Iterator<Item = &'a Self::Item>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_>;
fn into_vec(self) -> Vec<Label<Vec<u8>>>;
}
impl<'b, const N: usize> LookupPath for [&'b [u8]; N] {
type Item = &'b [u8];
type Iter<'a>
= std::slice::Iter<'a, &'b [u8]>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_> {
self.as_slice().iter()
}
fn into_vec(self) -> Vec<Label<Vec<u8>>> {
self.map(Label::from_bytes).into()
}
}
impl<'b, 'c> LookupPath for &'c [&'b [u8]] {
type Item = &'b [u8];
type Iter<'a>
= std::slice::Iter<'a, &'b [u8]>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_> {
<[_]>::iter(self)
}
fn into_vec(self) -> Vec<Label<Vec<u8>>> {
self.iter().map(|v| Label::from_bytes(v)).collect()
}
}
impl<'b> LookupPath for Vec<&'b [u8]> {
type Item = &'b [u8];
type Iter<'a>
= std::slice::Iter<'a, &'b [u8]>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_> {
<[_]>::iter(self.as_slice())
}
fn into_vec(self) -> Vec<Label<Vec<u8>>> {
self.into_iter().map(Label::from_bytes).collect()
}
}
impl<const N: usize> LookupPath for [Vec<u8>; N] {
type Item = Vec<u8>;
type Iter<'a>
= std::slice::Iter<'a, Vec<u8>>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_> {
self.as_slice().iter()
}
fn into_vec(self) -> Vec<Label<Vec<u8>>> {
self.map(Label::from).into()
}
}
impl<'c> LookupPath for &'c [Vec<u8>] {
type Item = Vec<u8>;
type Iter<'a>
= std::slice::Iter<'a, Vec<u8>>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_> {
<[_]>::iter(self)
}
fn into_vec(self) -> Vec<Label<Vec<u8>>> {
self.iter().map(|v| Label::from(v.clone())).collect()
}
}
impl LookupPath for Vec<Vec<u8>> {
type Item = Vec<u8>;
type Iter<'a>
= std::slice::Iter<'a, Vec<u8>>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_> {
<[_]>::iter(self.as_slice())
}
fn into_vec(self) -> Vec<Label<Vec<u8>>> {
self.into_iter().map(Label::from).collect()
}
}
impl<Storage: AsRef<[u8]> + Into<Vec<u8>>, const N: usize> LookupPath for [Label<Storage>; N] {
type Item = Label<Storage>;
type Iter<'a>
= std::slice::Iter<'a, Label<Storage>>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_> {
self.as_slice().iter()
}
fn into_vec(self) -> Vec<Label<Vec<u8>>> {
self.map(Label::from_label).into()
}
}
impl<'c, Storage: AsRef<[u8]> + Into<Vec<u8>>> LookupPath for &'c [Label<Storage>] {
type Item = Label<Storage>;
type Iter<'a>
= std::slice::Iter<'a, Label<Storage>>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_> {
<[_]>::iter(self)
}
fn into_vec(self) -> Vec<Label<Vec<u8>>> {
self.iter()
.map(|v| Label::from_bytes(v.as_bytes()))
.collect()
}
}
impl LookupPath for Vec<Label<Vec<u8>>> {
type Item = Label<Vec<u8>>;
type Iter<'a>
= std::slice::Iter<'a, Label<Vec<u8>>>
where
Self: 'a;
fn iter(&self) -> Self::Iter<'_> {
<[_]>::iter(self.as_slice())
}
fn into_vec(self) -> Vec<Label<Vec<u8>>> {
self
}
}
/// Looks up a value in the certificate's tree at the specified hash.
///
/// Returns the value if it was found; otherwise, errors with `LookupPathAbsent`, `LookupPathUnknown`, or `LookupPathError`.
pub fn lookup_value<P: LookupPath, Storage: AsRef<[u8]>>(
tree: &HashTree<Storage>,
path: P,
) -> Result<&[u8], AgentError> {
use AgentError::*;
match tree.lookup_path(path.iter()) {
LookupResult::Absent => Err(LookupPathAbsent(path.into_vec())),
LookupResult::Unknown => Err(LookupPathUnknown(path.into_vec())),
LookupResult::Found(value) => Ok(value),
LookupResult::Error => Err(LookupPathError(path.into_vec())),
}
}
/// Looks up a subtree in the certificate's tree at the specified hash.
///
/// Returns the value if it was found; otherwise, errors with `LookupPathAbsent` or `LookupPathUnknown`.
pub fn lookup_tree<P: LookupPath, Storage: AsRef<[u8]> + Clone>(
tree: &HashTree<Storage>,
path: P,
) -> Result<HashTree<Storage>, AgentError> {
use AgentError::*;
match tree.lookup_subtree(path.iter()) {
SubtreeLookupResult::Absent => Err(LookupPathAbsent(path.into_vec())),
SubtreeLookupResult::Unknown => Err(LookupPathUnknown(path.into_vec())),
SubtreeLookupResult::Found(value) => Ok(value),
}
}
| rust | Apache-2.0 | 6fef5bfa96d2ed63b84afd173cc049e38cb5a210 | 2026-01-04T20:16:51.650214Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.