Skip to content

Commit

Permalink
enable tss auth on spl whitelisting
Browse files Browse the repository at this point in the history
  • Loading branch information
skosito committed Oct 30, 2024
1 parent 6367073 commit bf7fb1a
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 14 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.anchor/
/target
**/.DS_Store
node_modules
88 changes: 83 additions & 5 deletions programs/protocol-contracts-solana/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,47 @@ pub mod gateway {
Ok(())
}

// whitelisting SPL tokens
pub fn whitelist_spl_mint(_ctx: Context<Whitelist>) -> Result<()> {
pub fn whitelist_spl_mint(
ctx: Context<Whitelist>,
signature: [u8; 64],
recovery_id: u8,
message_hash: [u8; 32],
nonce: u64
) -> Result<()> {
let pda = &mut ctx.accounts.pda;

validate_signature_or_authority(
pda,
&ctx.accounts.authority,
signature,
recovery_id,
message_hash,
nonce,
"whitelist_spl_mint"
)?;

Ok(())
}

pub fn unwhitelist_spl_mint(
ctx: Context<Unwhitelist>,
signature: [u8; 64],
recovery_id: u8,
message_hash: [u8; 32],
nonce: u64
) -> Result<()> {
let pda = &mut ctx.accounts.pda;

validate_signature_or_authority(
pda,
&ctx.accounts.authority,
signature,
recovery_id,
message_hash,
nonce,
"unwhitelist_spl_mint"
)?;

pub fn unwhitelist_spl_mint(_ctx: Context<Unwhitelist>) -> Result<()> {
Ok(())
}

Expand Down Expand Up @@ -393,6 +428,49 @@ fn recover_eth_address(
Ok(eth_address)
}

fn validate_signature_or_authority(
pda: &mut Account<Pda>,
authority: &Signer,
signature: [u8; 64],
recovery_id: u8,
message_hash: [u8; 32],
nonce: u64,
purpose: &str,
) -> Result<()> {
// signature provided, recover and verify that tss is the signer
if signature != [0u8; 64] {
if nonce != pda.nonce {
msg!("mismatch nonce");
return err!(Errors::NonceMismatch);
}

let mut concatenated_buffer = Vec::new();
concatenated_buffer.extend_from_slice(purpose.as_bytes());
concatenated_buffer.extend_from_slice(&pda.chain_id.to_be_bytes());
concatenated_buffer.extend_from_slice(&nonce.to_be_bytes());
require!(
message_hash == hash(&concatenated_buffer[..]).to_bytes(),
Errors::MessageHashMismatch
);

let address = recover_eth_address(&message_hash, recovery_id, &signature)?;
if address != pda.tss_address {
msg!("ECDSA signature error");
return err!(Errors::TSSAuthenticationFailed);
}

pda.nonce += 1;
} else {
// no signature provided, fallback to authority check
require!(
authority.key() == pda.authority,
Errors::SignerIsNotAuthority
);
}

Ok(())
}

#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(mut)]
Expand Down Expand Up @@ -513,7 +591,7 @@ pub struct Whitelist<'info> {
pub whitelist_entry: Account<'info, WhitelistEntry>,
pub whitelist_candidate: Account<'info, Mint>,

#[account(mut, seeds = [b"meta"], bump, has_one = authority)]
#[account(mut, seeds = [b"meta"], bump)]
pub pda: Account<'info, Pda>,
#[account(mut)]
pub authority: Signer<'info>,
Expand All @@ -535,7 +613,7 @@ pub struct Unwhitelist<'info> {
pub whitelist_entry: Account<'info, WhitelistEntry>,
pub whitelist_candidate: Account<'info, Mint>,

#[account(mut, seeds = [b"meta"], bump, has_one = authority)]
#[account(mut, seeds = [b"meta"], bump)]
pub pda: Account<'info, Pda>,
#[account(mut)]
pub authority: Signer<'info>,
Expand Down
74 changes: 65 additions & 9 deletions tests/protocol-contracts-solana.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ describe("some tests", () => {
})

it("whitelist USDC spl token", async () => {
await gatewayProgram.methods.whitelistSplMint().accounts({
await gatewayProgram.methods.whitelistSplMint([], 0, [], new anchor.BN(0)).accounts({
whitelistCandidate: mint.publicKey,
}).signers([]).rpc();

Expand All @@ -199,15 +199,14 @@ describe("some tests", () => {
seeds,
gatewayProgram.programId,
);
let entry = await gatewayProgram.account.whitelistEntry.fetch(entryAddress)

try {
seeds = [Buffer.from("whitelist", "utf-8"), mint_fake.publicKey.toBuffer()];
[entryAddress] = anchor.web3.PublicKey.findProgramAddressSync(
seeds,
gatewayProgram.programId,
);
entry = await gatewayProgram.account.whitelistEntry.fetch(entryAddress);
await gatewayProgram.account.whitelistEntry.fetch(entryAddress);
} catch(err) {
expect(err.message).to.include("Account does not exist or has no data");
}
Expand Down Expand Up @@ -289,7 +288,6 @@ describe("some tests", () => {
// expect(account2.amount).to.be.eq(1_000_000n);

const pdaAccountData = await gatewayProgram.account.pda.fetch(pdaAccount);
const hexAddr = bufferToHex(Buffer.from(pdaAccountData.tssAddress));
const amount = new anchor.BN(500_000);
const nonce = pdaAccountData.nonce;
await withdrawSplToken(mint, usdcDecimals, amount, nonce, pda_ata, wallet_ata, wallet.publicKey, keyPair, gatewayProgram);
Expand Down Expand Up @@ -414,7 +412,7 @@ describe("some tests", () => {
})

it("unwhitelist SPL token and deposit should fail", async () => {
await gatewayProgram.methods.unwhitelistSplMint().accounts({
await gatewayProgram.methods.unwhitelistSplMint([], 0, [], new anchor.BN(0)).accounts({
whitelistCandidate: mint.publicKey,
}).rpc();

Expand All @@ -427,12 +425,73 @@ describe("some tests", () => {
});

it("re-whitelist SPL token and deposit should succeed", async () => {
await gatewayProgram.methods.whitelistSplMint().accounts({
await gatewayProgram.methods.whitelistSplMint([], 0, [], new anchor.BN(0)).accounts({
whitelistCandidate: mint.publicKey,
}).rpc();
await depositSplTokens(gatewayProgram, conn, wallet, mint, address);
});

it("unwhitelist SPL token using tss signature and deposit should fail", async () => {
const pdaAccountData = await gatewayProgram.account.pda.fetch(pdaAccount);
const nonce = pdaAccountData.nonce;

const buffer = Buffer.concat([
Buffer.from("unwhitelist_spl_mint","utf-8"),
chain_id_bn.toArrayLike(Buffer, 'be', 8),
nonce.toArrayLike(Buffer, 'be', 8),
]);
const message_hash = keccak256(buffer);
const signature = keyPair.sign(message_hash, 'hex');
const { r, s, recoveryParam } = signature;
const signatureBuffer = Buffer.concat([
r.toArrayLike(Buffer, 'be', 32),
s.toArrayLike(Buffer, 'be', 32),
]);

await gatewayProgram.methods.unwhitelistSplMint(
Array.from(signatureBuffer),
Number(recoveryParam),
Array.from(message_hash),
nonce,
).accounts({
whitelistCandidate: mint.publicKey,
}).rpc();

try {
await depositSplTokens(gatewayProgram, conn, wallet, mint, address)
} catch (err) {
expect(err).to.be.instanceof(anchor.AnchorError);
expect(err.message).to.include("AccountNotInitialized");
}
});

it("re-whitelist SPL token using tss signature and deposit should succeed", async () => {
const pdaAccountData = await gatewayProgram.account.pda.fetch(pdaAccount);
const nonce = pdaAccountData.nonce;

const buffer = Buffer.concat([
Buffer.from("whitelist_spl_mint","utf-8"),
chain_id_bn.toArrayLike(Buffer, 'be', 8),
nonce.toArrayLike(Buffer, 'be', 8),
]);
const message_hash = keccak256(buffer);
const signature = keyPair.sign(message_hash, 'hex');
const { r, s, recoveryParam } = signature;
const signatureBuffer = Buffer.concat([
r.toArrayLike(Buffer, 'be', 32),
s.toArrayLike(Buffer, 'be', 32),
]);

await gatewayProgram.methods.whitelistSplMint(
Array.from(signatureBuffer),
Number(recoveryParam),
Array.from(message_hash),
nonce,
).accounts({
whitelistCandidate: mint.publicKey,
}).rpc();
await depositSplTokens(gatewayProgram, conn, wallet, mint, address);
});

it("update TSS address", async () => {
const newTss = new Uint8Array(20);
Expand Down Expand Up @@ -470,9 +529,6 @@ describe("some tests", () => {
}
});




const newAuthority = anchor.web3.Keypair.generate();
it("update authority", async () => {
await gatewayProgram.methods.updateAuthority(newAuthority.publicKey).accounts({
Expand Down

0 comments on commit bf7fb1a

Please sign in to comment.