Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Source Account Auth: Plumb account invoker through SDK #670

Merged
merged 16 commits into from
Sep 26, 2022
12 changes: 6 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 6 additions & 11 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,14 @@ soroban-sdk = { path = "soroban-sdk" }
soroban-auth = { path = "soroban-auth" }
soroban-spec = { path = "soroban-spec" }
soroban-sdk-macros = { path = "soroban-sdk-macros" }
soroban-env-common = { git = "https://github.com/stellar/rs-soroban-env", rev = "d43b297" }
soroban-env-guest = { git = "https://github.com/stellar/rs-soroban-env", rev = "d43b297" }
soroban-env-host = { git = "https://github.com/stellar/rs-soroban-env", rev = "d43b297" }
soroban-env-macros = { git = "https://github.com/stellar/rs-soroban-env", rev = "d43b297" }
soroban-native-sdk-macros = { git = "https://github.com/stellar/rs-soroban-env", rev = "d43b297" }
stellar-xdr = { git = "https://github.com/stellar/rs-stellar-xdr", rev = "c026149" }
soroban-env-common = { git = "https://github.com/stellar/rs-soroban-env", rev = "4a7f11bd" }
soroban-env-guest = { git = "https://github.com/stellar/rs-soroban-env", rev = "4a7f11bd" }
soroban-env-host = { git = "https://github.com/stellar/rs-soroban-env", rev = "4a7f11bd" }
soroban-env-macros = { git = "https://github.com/stellar/rs-soroban-env", rev = "4a7f11bd" }
soroban-native-sdk-macros = { git = "https://github.com/stellar/rs-soroban-env", rev = "4a7f11bd" }
stellar-xdr = { git = "https://github.com/stellar/rs-stellar-xdr", rev = "3c495a5a" }
wasmi = { package = "soroban-wasmi", git = "https://github.com/stellar/wasmi", rev = "a61b6df" }

# soroban-env-common = { path = "../rs-soroban-env/soroban-env-common" }
# soroban-env-guest = { path = "../rs-soroban-env/soroban-env-guest" }
# soroban-env-host = { path = "../rs-soroban-env/soroban-env-host" }
# soroban-env-macros = { path = "../rs-soroban-env/soroban-env-macros" }

[profile.dev]
overflow-checks = true
panic = "abort"
Expand Down
1 change: 1 addition & 0 deletions soroban-auth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ ed25519-dalek = { version = "1.0.1", optional = true }
rand = { version = "0.7.3", optional = true }

[dev_dependencies]
soroban-sdk = { version = "0.0.4", features = ["testutils"] }
ed25519-dalek = { version = "1.0.1" }
rand = { version = "0.7.3" }
2 changes: 1 addition & 1 deletion soroban-auth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ fn verify_account_signatures(env: &Env, auth: &AccountSignatures, name: Symbol,
/// invocations to be replayable if it is important they are not.**
pub fn verify(env: &Env, sig: &Signature, name: Symbol, args: impl IntoVal<Env, Vec<RawVal>>) {
match sig {
Signature::Contract => {
Signature::Invoker => {
env.get_invoking_contract();
}
Signature::Ed25519(e) => verify_ed25519_signature(env, &e, name, args.into_val(env)),
Expand Down
8 changes: 4 additions & 4 deletions soroban-auth/src/public_types.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use soroban_sdk::{contracttype, Bytes, BytesN, Env, RawVal, Symbol, Vec};
use soroban_sdk::{contracttype, Bytes, BytesN, Env, Invoker, RawVal, Symbol, Vec};

/// An Ed25519 signature contains a single signature for the
/// [`SignaturePayload`].
Expand Down Expand Up @@ -26,7 +26,7 @@ pub struct AccountSignatures {
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
#[contracttype(lib = "soroban_auth")]
pub enum Signature {
Contract,
Invoker,
Ed25519(Ed25519Signature),
Account(AccountSignatures),
}
Expand All @@ -35,7 +35,7 @@ impl Signature {
/// Returns the identifier that this signatures claims to authenticate.
pub fn identifier(&self, env: &Env) -> Identifier {
match self {
Signature::Contract => Identifier::Contract(env.get_invoking_contract()),
Signature::Invoker => Identifier::Invoker(env.invoker()),
Signature::Ed25519(e) => Identifier::Ed25519(e.public_key.clone()),
Signature::Account(a) => Identifier::Account(a.account_id.clone()),
}
Expand All @@ -53,7 +53,7 @@ impl Signature {
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
#[contracttype(lib = "soroban_auth")]
pub enum Identifier {
Contract(BytesN<32>),
Invoker(Invoker),
Ed25519(BytesN<32>),
Account(BytesN<32>),
}
Expand Down
10 changes: 5 additions & 5 deletions soroban-auth/tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ fn read_nonce(e: &Env, id: &Identifier) -> BigInt {
}

fn verify_and_consume_nonce(e: &Env, id: &Identifier, expected_nonce: &BigInt) {
// replay protection is not required for Contract authorization because
// replay protection is not required for invoker authorization because
// there's no cryptographic signature involved. All that's checked is the
// invoking contract, so this contract just expects 0.
if matches!(id, Identifier::Contract(_)) {
// invoker, so this contract just expects 0.
if matches!(id, Identifier::Invoker(_)) {
if BigInt::zero(&e) != expected_nonce {
panic!("nonce should be zero for Contract")
panic!("nonce should be zero for invoker")
}
return;
}
Expand Down Expand Up @@ -60,7 +60,7 @@ pub struct OuterTestContract;
impl OuterTestContract {
pub fn authorize(e: Env, contract_id: BytesN<32>) {
let client = TestContractClient::new(&e, contract_id);
client.verify_sig(&Signature::Contract, &BigInt::zero(&e));
client.verify_sig(&Signature::Invoker, &BigInt::zero(&e));
}
}

Expand Down
1 change: 1 addition & 0 deletions soroban-sdk-macros/src/map_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pub fn map_type(t: &Type) -> Result<ScSpecTypeDef, Error> {
"Status" => Ok(ScSpecTypeDef::Status),
"Bytes" => Ok(ScSpecTypeDef::Bytes),
"BigInt" => Ok(ScSpecTypeDef::BigInt),
"Invoker" => Ok(ScSpecTypeDef::Invoker),
s => Ok(ScSpecTypeDef::Udt(ScSpecTypeUdt {
name: s.try_into().map_err(|e| {
Error::new(
Expand Down
160 changes: 160 additions & 0 deletions soroban-sdk/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,169 @@ use core::{
use crate::{
env::internal::{Env as _, RawVal, RawValConvertible},
env::EnvObj,
xdr::ScObjectType,
Bytes, BytesN, ConversionError, Env, EnvVal, IntoVal, Object, TryFromVal, TryIntoVal,
};

/// Account ID is a Stellar account ID.
///
/// The ID is opaque and does not expose the identifier to the contract, but the
/// value is unique and can be used as a key in maps, or compared with other
/// account identifiers.
#[derive(Clone)]
pub struct AccountId(EnvObj);

impl Debug for AccountId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "AccountId(..)")?;
Ok(())
}
}

impl Eq for AccountId {}

impl PartialEq for AccountId {
fn eq(&self, other: &Self) -> bool {
self.partial_cmp(other) == Some(Ordering::Equal)
}
}

impl PartialOrd for AccountId {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(Ord::cmp(self, other))
}
}

impl Ord for AccountId {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.0.cmp(&other.0)
}
}

impl TryFromVal<Env, Object> for AccountId {
type Error = ConversionError;

fn try_from_val(env: &Env, val: Object) -> Result<Self, Self::Error> {
if val.is_obj_type(ScObjectType::AccountId) {
Ok(AccountId(val.in_env(env)))
} else {
Err(ConversionError {})
}
}
}

impl TryIntoVal<Env, AccountId> for Object {
type Error = <Account as TryFromVal<Env, Object>>::Error;

fn try_into_val(self, env: &Env) -> Result<AccountId, Self::Error> {
<_ as TryFromVal<_, Object>>::try_from_val(env, self)
}
}

impl TryFromVal<Env, RawVal> for AccountId {
type Error = <Account as TryFromVal<Env, Object>>::Error;

fn try_from_val(env: &Env, val: RawVal) -> Result<Self, Self::Error> {
<_ as TryFromVal<_, Object>>::try_from_val(env, val.try_into()?)
}
}

impl TryIntoVal<Env, AccountId> for RawVal {
type Error = <Account as TryFromVal<Env, Object>>::Error;

fn try_into_val(self, env: &Env) -> Result<AccountId, Self::Error> {
<_ as TryFromVal<_, RawVal>>::try_from_val(env, self)
}
}

impl IntoVal<Env, Object> for AccountId {
fn into_val(self, _env: &Env) -> Object {
self.to_object()
}
}

impl IntoVal<Env, Object> for &AccountId {
fn into_val(self, _env: &Env) -> Object {
self.to_object()
}
}

impl IntoVal<Env, RawVal> for AccountId {
fn into_val(self, _env: &Env) -> RawVal {
self.to_raw()
}
}

impl IntoVal<Env, RawVal> for &AccountId {
fn into_val(self, _env: &Env) -> RawVal {
self.to_raw()
}
}

#[cfg(not(target_family = "wasm"))]
use super::xdr::ScVal;

#[cfg(not(target_family = "wasm"))]
impl TryFrom<&AccountId> for ScVal {
type Error = ConversionError;
fn try_from(v: &AccountId) -> Result<Self, Self::Error> {
ScVal::try_from_val(&v.0.env, v.0.val.to_raw())
}
}

#[cfg(not(target_family = "wasm"))]
impl TryFrom<AccountId> for ScVal {
type Error = ConversionError;
fn try_from(v: AccountId) -> Result<Self, Self::Error> {
(&v).try_into()
}
}

#[cfg(not(target_family = "wasm"))]
impl TryFromVal<Env, ScVal> for AccountId {
type Error = ConversionError;
fn try_from_val(env: &Env, val: ScVal) -> Result<Self, Self::Error> {
<_ as TryFromVal<_, Object>>::try_from_val(
env,
val.try_into_val(env).map_err(|_| ConversionError)?,
)
}
}

#[cfg(not(target_family = "wasm"))]
impl TryIntoVal<Env, AccountId> for ScVal {
type Error = ConversionError;
fn try_into_val(self, env: &Env) -> Result<AccountId, Self::Error> {
AccountId::try_from_val(env, self)
}
}

impl AccountId {
pub(crate) unsafe fn unchecked_new(obj: EnvObj) -> Self {
Self(obj)
}

pub fn env(&self) -> &Env {
self.0.env()
}

pub fn as_raw(&self) -> &RawVal {
self.0.as_raw()
}

pub fn as_object(&self) -> &Object {
self.0.as_object()
}

pub fn to_raw(&self) -> RawVal {
self.0.to_raw()
}

pub fn to_object(&self) -> Object {
self.0.to_object()
}
}

/// Account references a Stellar account and provides access to information
/// about the account, such as its thresholds and signers.
#[derive(Clone)]
Copy link
Member Author

Choose a reason for hiding this comment

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

Note that the Account type, and its functions are still accessed via a BytesN<32>. That will be changed to use the new AccountId in stellar/rs-soroban-env#477.

Expand Down
5 changes: 5 additions & 0 deletions soroban-sdk/src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,11 @@ impl<const N: usize> TryIntoVal<Env, BytesN<N>> for ScVal {
}

impl<const N: usize> BytesN<N> {
#[inline(always)]
pub(crate) unsafe fn unchecked_new(obj: EnvObj) -> Self {
Self(Bytes::unchecked_new(obj))
}

pub fn env(&self) -> &Env {
self.0.env()
}
Expand Down
22 changes: 22 additions & 0 deletions soroban-sdk/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub use internal::ConversionError;
pub use internal::EnvBase;
pub use internal::FromVal;
pub use internal::IntoVal;
use internal::InvokerType;
pub use internal::Object;
pub use internal::RawVal;
pub use internal::RawValConvertible;
Expand All @@ -49,6 +50,8 @@ pub use internal::Val;
pub type EnvVal = internal::EnvVal<Env, RawVal>;
pub type EnvObj = internal::EnvVal<Env, Object>;

use crate::invoker::Invoker;
use crate::AccountId;
use crate::{
contract_data::ContractData, deploy::Deployer, events::Events, ledger::Ledger, logging::Logger,
Bytes, BytesN, Vec,
Expand Down Expand Up @@ -177,6 +180,21 @@ impl Env {
.unwrap()
}

/// Get the invoker of the current executing contract.
pub fn invoker(&self) -> Invoker {
let invoker_type: InvokerType = internal::Env::get_invoker_type(self)
.try_into()
.expect("unrecogniaed invoker type");
match invoker_type {
InvokerType::Account => Invoker::Account(unsafe {
AccountId::unchecked_new(internal::Env::get_invoking_account(self).in_env(self))
}),
InvokerType::Contract => Invoker::Contract(unsafe {
BytesN::unchecked_new(internal::Env::get_invoking_contract(self).in_env(self))
}),
}
}

/// Get the 32-byte hash identifier of the contract that invoked this
/// contract.
///
Expand Down Expand Up @@ -294,6 +312,10 @@ impl Env {
internal::budget::Budget::default(),
);

env_impl.set_source_account(xdr::AccountId(xdr::PublicKey::PublicKeyTypeEd25519(
xdr::Uint256([0; 32]),
)));

let l = internal::LedgerInfo {
protocol_version: 0,
sequence_number: 0,
Expand Down
Loading