The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
//! Calling the `tinywallet` module.
//!
//! The host half of `ai.tinyhumans.tinywallet.Wallet`. Two ways to get a signed
//! transaction, and which one a chain uses is a property of that chain.
//!
//! # The confidential flow — preferred, and what BTC, EVM and Tron use
//!
//! [`sign_transaction_in_module`] sends the recovery phrase itself, once, and
//! the module derives, encodes, signs and assembles. No private key is ever
//! reassembled in this process.
//!
//! ```text
//! host ==SignTransaction{phrase, path, fields}==> module (confidential)
//! host <=={raw transaction, txid}================ module
//! ```
//!
//! The phrase only goes to a recipient tinybus has attested, and
//! [`attested_proxy`] additionally insists the attested digest is one
//! `registry.rs` pinned — see there for why both checks are worth having.
//!
//! # The split flow — still here, still correct for some hosts
//!
//! [`sign_transaction`] keeps the key in this process: the module returns
//! digests, this process signs them, the module reassembles.
//!
//! ```text
//! host --BuildUnsigned{fields, public key}--> module
//! host <--[digests to sign]------------------- module
//! host (signs locally, with a key the module never sees)
//! host --AttachSignature{fields, signatures}-> module
//! host <--{raw transaction, txid}------------- module
//! ```
//!
//! It is not deprecated. It is the only option for a backend reached across a
//! transport, where the bus cannot say what is on the other end, and it is what
//! Solana still uses here — Solana hand-builds SPL messages that
//! `TransactionSpec::Solana` does not model, so there is nothing to send.
//!
//! # What the confidential flow does and does not buy
//!
//! A loaded module shares this address space and could read the phrase out of
//! process memory whichever flow is used, so neither is a hard isolation
//! boundary and neither is claimed as one.
//!
//! What changes is that this binary no longer performs derivation or signing at
//! all — the key exists only inside the module, for the duration of one call,
//! rather than being assembled here and held across two round trips. The bus
//! also refuses to carry the phrase to anything that is not an allowlisted,
//! hash-verified module, which the split flow could not express.
//!
//! # The fields are sent twice in the split flow, deliberately
//!
//! `AttachSignature` re-sends everything `BuildUnsigned` was given rather than a
//! handle to something the module remembered. That is what lets the module hold
//! no state between the calls — no store, no bound on it, no expiry for a host
//! that never comes back. Building is deterministic, so the module rebuilds the
//! transaction the digests were computed over. The confidential flow needs none
//! of this: it is one call.
//!
//! # Two signing schemes, and the difference matters
//!
//! A `Secp256k1Prehash` payload is **already hashed** and must be signed with a
//! prehash entry point; hashing it again produces a valid signature over the
//! wrong thing. An `Ed25519` payload is the whole message and must **not** be
//! pre-hashed, because ed25519 hashes internally. The module tags every payload
//! with which it is, and [`sign_payload`] dispatches on the tag rather than on
//! the chain — so a chain that changes scheme cannot silently sign wrongly.
use serde::de::DeserializeOwned;
use serde::Serialize;
use tinywallet_bus::names::methods;
use tinywallet_bus::wire::{
DeriveMnemonicSeedRequest, DeriveMnemonicSeedResponse, DerivedAccount,
EncodeErc20TransferRequest, EncodeErc20TransferResponse, ExportRequest, ExportedKey,
GenerateMnemonicRequest, GenerateMnemonicResponse, Scheme, SecretMaterial, SignMessageRequest,
SignRequest, Signature, SignedTransaction, TransactionSpec,
};
use zeroize::Zeroize;
use super::{ops, registry};
use crate::config::Config;
/// Registry id of the module these calls go to.
const MODULE_ID: &str = "tinywallet";
/// Why a wallet call did not produce a signed transaction.
///
/// Three variants because the wallet tools map them onto three different
/// user-facing outcomes: something the caller can correct, something it cannot,
/// and a capability that is not present on this host at all.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WalletCallError {
/// The module is not loaded and cannot be: unsupported host, downloads off,
/// disabled in config, or a load that already failed in this process.
Unavailable(String),
/// The request was rejected. The caller can act on this.
InvalidInput(String),
/// Building, signing, or assembly failed.
Failed(String),
}
impl std::fmt::Display for WalletCallError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unavailable(message) | Self::InvalidInput(message) | Self::Failed(message) => {
f.write_str(message)
}
}
}
}
/// Derive, build, sign and assemble entirely inside the module.
///
/// The counterpart to [`sign_transaction`], and the one to prefer: the phrase
/// crosses the bus once and no key material is ever reassembled here.
///
/// # Errors
///
/// [`WalletCallError`]. `Unavailable` if the module is not an attested
/// recipient — see [`attested_proxy`], which refuses to send the phrase at all
/// in that case.
pub async fn sign_transaction_in_module(
config: &Config,
transaction: &TransactionSpec,
secret: &SecretMaterial,
) -> Result<SignedTransaction, WalletCallError> {
let proxy = attested_proxy(config).await?;
log::debug!(
"[modules:wallet] sign_transaction chain={:?} module={MODULE_ID} (confidential)",
transaction.chain()
);
proxy
.call_confidential(
methods::SIGN_TRANSACTION,
(SignRequest {
secret: secret.clone(),
transaction: transaction.clone(),
},),
)
.await
.map_err(|error| classify(&error))
}
/// Ask the module for an address and public key.
///
/// # Errors
///
/// [`WalletCallError`].
pub async fn derive_account(
config: &Config,
secret: &SecretMaterial,
) -> Result<DerivedAccount, WalletCallError> {
log::debug!(
"[modules:wallet] derive_account chain={:?} module={MODULE_ID} (confidential)",
secret.chain
);
let mut request = secret.clone();
let result = call_confidential(config, methods::DERIVE_ACCOUNT, &request).await;
request.mnemonic.zeroize();
result
}
/// Generate a recovery phrase inside the attested TinyWallet module.
///
/// # Errors
///
/// [`WalletCallError`]. The phrase is returned to the host for encryption and
/// custody, but generation and BIP-39 vocabulary remain module-owned.
pub async fn generate_mnemonic(
config: &Config,
word_count: u8,
) -> Result<GenerateMnemonicResponse, WalletCallError> {
call_confidential(
config,
methods::GENERATE_MNEMONIC,
&GenerateMnemonicRequest { word_count },
)
.await
}
/// Derive a standard BIP-39 seed inside the attested module.
///
/// The caller uses the seed only for OpenHuman's generic storage-key KDF.
///
/// # Errors
///
/// [`WalletCallError`]. Invalid or unsupported phrases are classified as
/// [`WalletCallError::InvalidInput`].
pub async fn derive_mnemonic_seed(
config: &Config,
mnemonic: String,
) -> Result<DeriveMnemonicSeedResponse, WalletCallError> {
let mut request = DeriveMnemonicSeedRequest { mnemonic };
let result = call_confidential(config, methods::DERIVE_MNEMONIC_SEED, &request).await;
request.mnemonic.zeroize();
result
}
/// Encode ERC-20 transfer calldata with the module-owned ABI implementation.
///
/// # Errors
///
/// Returns [`WalletCallError`] if the module is unavailable or rejects the
/// recipient or base-unit amount.
pub async fn encode_erc20_transfer(
config: &Config,
to_address: &str,
amount_raw: &str,
) -> Result<String, WalletCallError> {
let response: EncodeErc20TransferResponse = call(
config,
methods::ENCODE_ERC20_TRANSFER,
&EncodeErc20TransferRequest {
to_address: to_address.to_owned(),
amount_raw: amount_raw.to_owned(),
},
)
.await?;
Ok(response.calldata)
}
/// Sign opaque bytes with the key derived from `secret`.
///
/// Blind: the module cannot check what the bytes mean, so
/// [`sign_transaction_in_module`] is the right call wherever the request can be
/// expressed as a `TransactionSpec`. This exists for the two encodings the wire
/// contract does not model — Solana SPL transfers and x402 payments — where the
/// alternative is not a verified signature but deriving the key in this process
/// and signing here, which is what these callers used to do.
///
/// # Errors
///
/// [`WalletCallError`].
pub async fn sign_message(
config: &Config,
secret: &SecretMaterial,
message: &[u8],
scheme: Scheme,
) -> Result<Signature, WalletCallError> {
let proxy = attested_proxy(config).await?;
log::debug!(
"[modules:wallet] sign_message chain={:?} bytes={} module={MODULE_ID} (confidential)",
secret.chain,
message.len()
);
proxy
.call_confidential(
methods::SIGN_MESSAGE,
(SignMessageRequest {
secret: secret.clone(),
message_hex: hex(message),
scheme,
},),
)
.await
.map_err(|error| classify(&error))
}
/// Ask the module for the raw derived key.
///
/// A compatibility call for downstream hosts that must drive a signer locally.
/// OpenHuman's own wallet paths sign inside the module.
///
/// # Errors
///
/// [`WalletCallError`].
pub async fn export_key(
config: &Config,
secret: &SecretMaterial,
) -> Result<ExportedKey, WalletCallError> {
let proxy = attested_proxy(config).await?;
log::debug!(
"[modules:wallet] export_key chain={:?} module={MODULE_ID} (confidential)",
secret.chain
);
proxy
.call_confidential(
methods::EXPORT_KEY,
(ExportRequest {
secret: secret.clone(),
},),
)
.await
.map_err(|error| classify(&error))
}
/// Call a typed Wallet, Web3, or x402 member with one request argument.
/// Business rules stay in the module; the host only transports the request.
pub async fn call<Request, Reply>(
config: &Config,
member: &str,
request: Request,
) -> Result<Reply, WalletCallError>
where
Request: Serialize + Send,
Reply: DeserializeOwned,
{
let (runtime, record) = ready(config).await?;
proxy(runtime, record)?
.call::<Reply>(member, (request,))
.await
.map_err(|error| classify(&error))
}
/// Call a Wallet member carrying secret material over TinyBus's confidential
/// transport. The loaded module must be attested and match this build's pin.
pub async fn call_confidential<Request, Reply>(
config: &Config,
member: &str,
request: &Request,
) -> Result<Reply, WalletCallError>
where
Request: Serialize + Send,
Reply: DeserializeOwned,
{
attested_proxy(config)
.await?
.call_confidential::<Reply>(member, (request,))
.await
.map_err(|error| classify(&error))
}
/// A proxy that has proved it is the artifact this build pinned.
///
/// # Why check here when the broker already refuses
///
/// The broker will not route a confidential call to an unattested recipient, so
/// omitting this would still be safe against the case it covers. Two reasons to
/// check anyway.
///
/// The first is the error. A broker refusal arrives after the request has been
/// serialized, which means a frame containing the recovery phrase was built and
/// handed to the bus before anything said no. Checking first means the phrase is
/// never put into a buffer on a call that was always going to fail.
///
/// The second is that this compares the digest against **this build's own
/// table**, which the broker cannot do — it only knows the host vouched for
/// something. Here we can insist it vouched for one of the artifacts
/// `registry.rs` names. That closes the gap where a host is somehow induced to
/// attest a different artifact for this bus name.
///
/// Both are belt-and-braces over a check that already exists. That is the right
/// posture for the one code path that hands over a recovery phrase.
async fn attested_proxy(config: &Config) -> Result<tinybus::Proxy, WalletCallError> {
let (runtime, record) = ready(config).await?;
let proxy = proxy(runtime, record)?;
let attestation = proxy
.attestation()
.await
.map_err(|error| WalletCallError::Failed(error.to_string()))?
.ok_or_else(|| {
WalletCallError::Unavailable(
"the wallet module is loaded but not an attested recipient, so it cannot be sent \
key material. This host is running a build whose module loader does not record \
an attestation for pinned releases; upgrade it rather than working around this."
.to_string(),
)
})?;
if attestation.name.as_str() != record.bus_name {
return Err(WalletCallError::Failed(format!(
"the wallet module's attestation names '{}' rather than '{}'",
attestation.name.as_str(),
record.bus_name
)));
}
if !digest_is_pinned(record, &attestation.sha256) {
return Err(WalletCallError::Failed(
"the loaded wallet module is not one of the artifacts this build pinned, so it will \
not be sent key material"
.to_string(),
));
}
Ok(proxy)
}
// Embedded library checksums verified from all 17 archives in the
// registry-pinned TinyWallet v0.27.0 release. Each library is trusted only
// while its archive checksum remains pinned in the supplied ModuleRecord.
const PINNED_WALLET_LIBRARIES: &[(&str, &str)] = &[
// archlinux-arm64
(
"739b73d4fe246b108d3d8c15b96e358219e3357554663054bde9b4cfcc1e1547",
"a57bf683224966ff71a833f7bc81d0aa11f55e82eb5a31797f4fe2877d63d3fe",
),
// archlinux-x86_64
(
"30ad7f2de3d10d584d677412cd1fa6fc124083fb28ad5c58fcdb63a8c3d88f79",
"021bd0b713368717ec1a480a2919c8414ac2f2fa94adf816e5e5ff1208a5bbe0",
),
// fedora-43-arm64
(
"e2a185ff78c0f636a1ccbc7a5d6d91e23121394fa5d64683058f33e24b414771",
"241d314a7afaa46d49944eb12daed96194d9b9c8fb21377b16c92bae3dcd72e5",
),
// fedora-43-x86_64
(
"28f03bfde6eb63dde25e0f6fafaf2ce25e453afdf56a5c9a3277d47bf2fe5400",
"e7f9ac37f2e0c1253725b340b35863c14e1953ef64f94c5d0d9fd26ed1f17faa",
),
// fedora-44-arm64
(
"574cf3773f405e282c3d42f4fb8ba8e3037e7abcd06ee63c719a134c100f9748",
"f3aea9878c4bba896febf0faadc23e7068076240a866c34386577e1ade210ba1",
),
// fedora-44-x86_64
(
"af05c0582364306a0bf885df059bea601044cfd40c40c7a14af043499053dc71",
"debb137f4883a5c9e77436ba8e47b2dcc66be4d7c924dc1b2562ebf885058a9e",
),
// macos-15-arm64
(
"554375d3e45eb9332454323937c7923e34a75934a99b2185bff35503b7abeec5",
"6f8fa586950899ead7d05720d74fce0f16677db97d631a261ee99697df8f09e5",
),
// macos-15-x86_64
(
"ad4a098b29dedd350bd60bf4d0194fa89cc2f79bff47447f7d52b440f702730a",
"f587e4bdfa9b3fd97fd2d4cb0f37524c8f5addd4e481d063fabc56a750944559",
),
// macos-26-arm64
(
"762c4fa1a283df5d499610314a6d35b002663e00f4b57105d56047a5d0cb83a8",
"7aca21d586818af307a88b7d21b6c6d89153abc3e8a9c1af0ec8c715464a51bb",
),
// macos-26-x86_64
(
"5973882752b659ac5ef9906fcc418e55796e3cc1375b3be141e16a624bc666c1",
"dcdae547da8c68207ec12ef6b8348ea98de757247b66182eba55a61c45914686",
),
// ubuntu-22.04-arm64
(
"927227ee8d8a23a12966ccb2de972fcab07e80fb6527dad840170e4ffd64f087",
"37adb1ac3667f08b745bc9ac747313fc16ef377d6b206a27accd11f5d6afa702",
),
// ubuntu-22.04-x86_64
(
"a031e81172452657a506cd769a41f8702c06d80a75b72ebf6dc9a0f4a8317c25",
"76172a4d1b444990090265ecbbc01b0afa756f88f647c20d0e9cf5391b2da8e9",
),
// ubuntu-24.04-arm64
(
"6e055459e513707e58b4d07c836a3659a453c3753ee8c632e858930c150b66f4",
"eaa566008f1fc5d05d0200ff34719f6cce5c751976e13b21ca33bd87c4c50238",
),
// ubuntu-24.04-x86_64
(
"cab0be708a52e8713df7cc57dc13717e3899ce3c8ec57819741b37dc463ccfc7",
"8fee5f20bd58505eb2a291e565d9c83928f4418d5c114413baf55613e0120baf",
),
// windows-11-arm64
(
"9e458762f740e166b9b028336b6faed3762dfb71bf46eb57c71ad7e3ec2dc9d3",
"ae2e72565b94598e1f3b472400782c84d8a64c9ca008e8fa7349e4058c5dfa57",
),
// windows-2022-x86_64
(
"ff389c8951c0721b31bb8eb4a71e86424f053923eab10464c8ee68bbb1ec25a1",
"bcbc74930538e6047744a9dd5c84334acb14f1285238479c89dfdd3fc42517e6",
),
// windows-2025-x86_64
(
"b01f58d66e73f73b510bf755fb89d1fa77a5caad00033405511ce12b84086632",
"0ec201f01d218327d336d70614ebcf7775c872fb51dacdf9fadae542109fe40c",
),
];
fn digest_is_pinned(record: &super::ModuleRecord, sha256: &str) -> bool {
record.assets.iter().any(|asset| {
asset.sha256.eq_ignore_ascii_case(sha256)
|| PINNED_WALLET_LIBRARIES.iter().any(|(archive, library)| {
asset.sha256.eq_ignore_ascii_case(archive) && library.eq_ignore_ascii_case(sha256)
})
})
}
/// Load the wallet module if it is not already serving.
///
/// Callers do not have to invoke this — the signing calls do — but a caller
/// that wraps its work in a deadline should, *outside* that deadline. A first
/// use may download and verify an artifact, and charging that against a
/// transaction timeout means the first transfer a user ever makes is the one
/// that fails.
///
/// # Errors
///
/// [`WalletCallError::Unavailable`].
pub async fn ensure_ready(config: &Config) -> Result<(), WalletCallError> {
ops::ensure_loaded(config, MODULE_ID)
.await
.map_err(WalletCallError::Unavailable)
}
/// Ensure the module is serving and hand back what a call needs.
async fn ready(
config: &Config,
) -> Result<
(
&'static tinybus::module::ModuleRuntime,
&'static super::ModuleRecord,
),
WalletCallError,
> {
ops::ensure_loaded(config, MODULE_ID)
.await
.map_err(WalletCallError::Unavailable)?;
let record = registry::find(MODULE_ID)
.ok_or_else(|| WalletCallError::Unavailable(format!("unknown module '{MODULE_ID}'")))?;
let runtime = super::runtime::runtime()
.await
.map_err(|_| WalletCallError::Unavailable("the module bus is not running".to_string()))?;
Ok((runtime, record))
}
/// A proxy for the module's object.
fn proxy(
runtime: &'static tinybus::module::ModuleRuntime,
record: &super::ModuleRecord,
) -> Result<tinybus::Proxy, WalletCallError> {
runtime
.proxy(record.bus_name, record.object_path)
.map_err(|error| WalletCallError::Failed(error.to_string()))
}
/// Map a bus failure onto the shape a caller can act on.
///
/// The wire name is the contract; the message is for a human. An unrecognised
/// name is `Failed` rather than `InvalidInput`, because telling a caller its
/// input was wrong when it was not points at the wrong fix.
fn classify(error: &tinybus::Error) -> WalletCallError {
let message = error.to_string();
match error.wire_name() {
"ai.tinyhumans.tinywallet.Error.InvalidInput" => WalletCallError::InvalidInput(message),
"ai.tinyhumans.tinywallet.Error.UnsupportedChain" => WalletCallError::Unavailable(message),
// The module is loaded but not answering: refused, faulted, or gone.
name if name.contains("ModuleUnavailable") => WalletCallError::Unavailable(message),
_ => WalletCallError::Failed(message),
}
}
/// Lowercase hex, unprefixed — the form every field in the wire contract uses.
fn hex(bytes: &[u8]) -> String {
bytes.iter().fold(String::new(), |mut out, byte| {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
out
})
}
#[cfg(test)]
#[path = "wallet_tests.rs"]
mod tests;