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

Account Abstraction - Custom Validation Signature Scheme #229

Draft
wants to merge 12 commits into
base: main
Choose a base branch
from
8 changes: 8 additions & 0 deletions Scarb.lock
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ dependencies = [
"snforge_std",
]

[[package]]
name = "custom_signature_validation"
version = "0.1.0"

[[package]]
name = "custom_type_serde"
version = "0.1.0"
Expand Down Expand Up @@ -131,6 +135,10 @@ dependencies = [
"openzeppelin",
]

[[package]]
name = "simple_storage"
version = "0.1.0"

[[package]]
name = "simple_vault"
version = "0.1.0"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
target
14 changes: 14 additions & 0 deletions listings/advanced-concepts/custom_signature_validation/Scarb.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "custom_signature_validation"
version = "0.1.0"
edition = "2023_11"

# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html

[dependencies]
starknet.workspace = true

[scripts]
test.workspace = true

[[target.starknet-contract]]
julio4 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// ANCHOR: custom_signature_scheme
use starknet::secp256_trait::{
Secp256PointTrait, Signature as Secp256Signature, recover_public_key, is_signature_entry_valid
};
use starknet::secp256r1::Secp256r1Point;
use starknet::secp256k1::Secp256k1Point;
use starknet::{ EthAddress, eth_signature::is_eth_signature_valid };
use core::traits::TryInto;


const SECP256R1_SIGNER_TYPE: felt252 = 'Secp256r1 Signer';
const SECP256K1_SIGNER_TYPE: felt252 = 'Secp256k1 Signer';
const SECP_256_R1_HALF: u256 = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 / 2;
const SECP_256_K1_HALF: u256 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 / 2;



#[derive(Drop, Copy, PartialEq, Serde, Default)]
enum SignerType {
#[default]
Secp256r1,
Secp256k1,
}

#[derive(Drop, Copy, Serde)]
enum SignerSignature {
Secp256r1: (Secp256r1Signer, Secp256Signature),
Secp256k1: (Secp256k1Signer, Secp256Signature),
}

#[derive(Drop, Copy, Serde)]
enum Signer {
Secp256r1: Secp256r1Signer,
Secp256k1: Secp256k1Signer,
}

#[derive(Drop, Copy, Serde, PartialEq)]
struct Secp256r1Signer {
pubkey: NonZero<u256>
}

#[derive(Drop, Copy, PartialEq)]
struct Secp256k1Signer {
pubkey_hash: EthAddress
}


// To ensure the pubkey hash is not zero
impl Secp256k1SignerSerde of Serde<Secp256k1Signer> {
#[inline(always)]
fn serialize(self: @Secp256k1Signer, ref output: Array<felt252>) {
self.pubkey_hash.serialize(ref output);
}

#[inline(always)]
fn deserialize(ref serialized: Span<felt252>) -> Option<Secp256k1Signer> {
let pubkey_hash = Serde::<EthAddress>::deserialize(ref serialized)?;
assert(pubkey_hash.address != 0, 'zero pub key hash' );
Option::Some(Secp256k1Signer { pubkey_hash })
}
}

// To check if secp256k1 and secp256r1 signatures are valid
trait Secp256SignatureTrait {
fn is_valid_signature(self: SignerSignature, hash: felt252) -> bool;
fn signer(self: SignerSignature) -> Signer;
}

impl Secp256SignatureImpl of Secp256SignatureTrait {
#[inline(always)]
fn is_valid_signature(self: SignerSignature, hash: felt252) -> bool {
match self {
SignerSignature::Secp256r1((
signer, signature
)) => is_valid_secp256r1_signature(hash.into(), signer, signature),
SignerSignature::Secp256k1((
signer, signature
)) => is_valid_secp256k1_signature(hash.into(), signer.pubkey_hash.into(), signature),
}
}

#[inline(always)]
fn signer(self: SignerSignature) -> Signer {
match self {
SignerSignature::Secp256k1((signer, _)) => Signer::Secp256k1(signer),
SignerSignature::Secp256r1((signer, _)) => Signer::Secp256r1(signer),
}
}
}

// To validate secp256k1 signature
#[inline(always)]
fn is_valid_secp256k1_signature(hash: u256, pubkey_hash: EthAddress, signature: Secp256Signature) -> bool {
assert(signature.s <= SECP_256_K1_HALF, 'malleable signature');
is_eth_signature_valid(hash, signature, pubkey_hash).is_ok()
}

// To validate secp256r1 signature
#[inline(always)]
fn is_valid_secp256r1_signature(hash: u256, signer: Secp256r1Signer, signature: Secp256Signature) -> bool {
assert(is_signature_entry_valid::<Secp256r1Point>(signature.s), 'invalid s-value');
assert(is_signature_entry_valid::<Secp256r1Point>(signature.r), 'invalid r-value');
assert(signature.s <= SECP_256_R1_HALF, 'malleable signature');
let recovered_pubkey = recover_public_key::<Secp256r1Point>(hash, signature).expect('invalid sign format');
let (recovered_signer, _) = recovered_pubkey.get_coordinates().expect('invalid sig format');
recovered_signer == signer.pubkey.into()
}

// impl to convert signer type into felt252 using into()
impl SignerTypeIntoFelt252 of Into<SignerType, felt252> {
#[inline(always)]
fn into(self: SignerType) -> felt252 {
match self {
SignerType::Secp256k1 => 1,
SignerType::Secp256r1 => 2,
}
}
}


// impl to convert u256 type into SignerType using try_into()
impl U256TryIntoSignerType of TryInto<u256, SignerType> {
#[inline(always)]
fn try_into(self: u256) -> Option<SignerType> {
if self == 1 {
Option::Some(SignerType::Secp256k1)
} else if self == 2 {
Option::Some(SignerType::Secp256r1)
} else {
Option::None
}
}
}

// ANCHOR_END: custom_signature_scheme
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mod custom_signature;
37 changes: 37 additions & 0 deletions src/advanced-concepts/custom_signature_validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Custom Signature Validation Scheme

Digital signatures are a fundamental aspect of modern cryptography, used to verify the authenticity and integrity of digital messages or transactions. They are based on public-key cryptography, where a pair of keys (a public key and a private key) are used to create and verify signatures.
Private keys are kept secret and secure by the owner, and are used to sign the message or transaction, while the public key can be used by anyone to verify the signature.
Copy link
Contributor

Choose a reason for hiding this comment

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

  • secured
  • to sign data such as messages or transactions
  • and can be verified by anyone with the public key


Account Abstraction is a native feature on Starknet, this makes it possible for anyone to implement custom signature schemes. The implication is that signature schemes on Starknet are not limited to just one, any standard signature scheme can be validated, for example Starknet signature, Secp256k1, Secp256r1, Eip191 etc are some of the custom signatures that can be validated on Starknet currently.
Copy link
Contributor

Choose a reason for hiding this comment

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

Little redundant, you can compact it like this:
Account Abstraction is a native feature on Starknet, this makes it possible for anyone to implement custom signature schemes and use it to validate transactions with the implementation of the signature validation logic.


### The Concepts of Accounts and Signers

i. **Account:** All accounts are smart contracts that can hold assets and execute transactions on Starknet, these account contracts however must implement some specific methods outlined in SNIP-6. For further reading: [Account contract](https://starknet-by-example.voyager.online/advanced-concepts/account_abstraction/account_contract.html).

ii. **Signers:** These are responsible for digitally signing transactions and provide the authorization needed to initiate transactions.
Digital signatures are cryptographic proofs that transactions are authorized by corresponding accounts.

### Signature validation on Starknet

On Starknet transactions are signed offchain, which means that the signature process happens outside the blockchain. The signed transaction is then submitted to Starknet network for verification and execution. Read more: [Starknet-js docs](https://www.starknetjs.com/docs/guides/signature/)

All Account contracts on Starknet must implement the SNIP-6 standard as mentioned earlier. The methods implemented in the SNIP-6 standard provide means to move offchain signatures onchain and execute them.

`is_valid_signature` returns true if the signature is valid, `__validate__` validates the signature and marks them as 'VALIDATED', while `__execute__` executes the validated transaction. Sample implementation of SNIP-6 standard: [Sample SNIP-6 Implementation](https://starknet-by-example.voyager.online/advanced-concepts/account_abstraction/account_contract.html#minimal-account-contract-executing-transactions)
Copy link
Contributor

Choose a reason for hiding this comment

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

Could you use relative path to account contract instead of absolute url


On Ethereum, only **one** signature scheme is used for signing messages and transactions, and also for signature authentications: the Elliptic Curve Digital Signature Algorithm (ECDSA). That means that no other signature algorithms can be validated on Ethereum, making it more secure but less flexible.
Copy link
Contributor

Choose a reason for hiding this comment

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

On Ethereum, only one signature scheme is used: ECDSA. It makes Ethereum more secure but also less flexible.

Custom signature validation employed on Starknet gives room for more flexibility, however, care must be taken to validate all signatures meticulously to ensure that:

a. the message has not been altered.
b. the signer owns the private key corresponding to the public key.

In summary, Starknet accounts are normal blockchain accounts that hold assets and initiate transactions onchain, while signers provide the authorization required to ensure that transactions originating from these accounts are secure and valid.

### Custom signature validation sample

The example below shows a sample implementation of `Secp256r1` and `Secp256k1` signature schemes:
Copy link
Contributor

Choose a reason for hiding this comment

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

As it can be a bit complex in one big block, try to break it in each steps of the implementation


julio4 marked this conversation as resolved.
Show resolved Hide resolved
```rust
{{#rustdoc_include ../../listings/advanced-concepts/custom_signature_validation/src/custom_signature.cairo:custom_signature_scheme}}
```