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

Swfit/hex taker #1337

Merged
merged 10 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Features

### Fixes

### Breaking

## [2.101.0] - 2024-11-15

### Features

- program: upgrade switchboard on demand oracles ([#1329](https://github.com/drift-labs/protocol-v2/pull/1329))

### Fixes
Expand Down
3 changes: 2 additions & 1 deletion Cargo.lock

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

3 changes: 2 additions & 1 deletion programs/drift/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "drift"
version = "2.100.0"
version = "2.101.0"
description = "Created with Anchor"
edition = "2018"

Expand All @@ -26,6 +26,7 @@ pythnet-sdk = { git = "https://github.com/drift-labs/pyth-crosschain", rev = "3e
pyth-solana-receiver-sdk = { git = "https://github.com/drift-labs/pyth-crosschain", rev = "3e8a24ecd0bcf22b787313e2020f4186bb22c729"}
bytemuck = { version = "1.4.0" }
borsh = "0.10.3"
hex = "0.4.3"
num-traits = "0.2"
uint = { version = "0.9.1", default-features = false }
num-derive = "0.3"
Expand Down
12 changes: 6 additions & 6 deletions programs/drift/src/instructions/keeper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ use crate::state::user::{
MarginMode, MarketType, OrderStatus, OrderTriggerCondition, OrderType, User, UserStats,
};
use crate::state::user_map::{load_user_map, load_user_maps, UserMap, UserStatsMap};
use crate::validation::sig_verification::{extract_ed25519_ix_signature, verify_ed25519_digest};
use crate::validation::sig_verification::{extract_ed25519_ix_signature, verify_ed25519_msg};
use crate::validation::user::validate_user_is_idle;
use crate::{
controller, digest_struct, load, math, print_error, OracleSource, GOV_SPOT_MARKET_INDEX,
MARGIN_PRECISION,
controller, digest_struct, digest_struct_hex, load, math, print_error, OracleSource,
GOV_SPOT_MARKET_INDEX, MARGIN_PRECISION,
};
use crate::{load_mut, QUOTE_PRECISION_U64};
use crate::{validate, QUOTE_PRECISION_I128};
Expand Down Expand Up @@ -589,18 +589,18 @@ pub fn place_swift_taker_order<'c: 'info, 'info>(

// Verify data from first verify ix
let ix: Instruction = load_instruction_at_checked(ix_idx as usize - 2, ix_sysvar)?;
verify_ed25519_digest(
verify_ed25519_msg(
&ix,
&swift_server::id().to_bytes(),
&digest_struct!(swift_message),
)?;

// Verify data from second verify ix
let ix: Instruction = load_instruction_at_checked(ix_idx as usize - 1, ix_sysvar)?;
verify_ed25519_digest(
verify_ed25519_msg(
&ix,
&taker.authority.to_bytes(),
&digest_struct!(&taker_order_params_message),
digest_struct_hex!(taker_order_params_message),
)?;

// Verify that sig from swift server corresponds to order message
Expand Down
9 changes: 9 additions & 0 deletions programs/drift/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,18 @@ macro_rules! safe_decrement {
}};
}

/// Calculate the sha256 digest of anchor encoded `struct`
#[macro_export]
macro_rules! digest_struct {
($struct:expr) => {
solana_program::hash::hash(&$struct.try_to_vec().unwrap()).to_bytes()
};
}

/// Calculate the hexified sha256 digest of anchor encoded `struct`
#[macro_export]
macro_rules! digest_struct_hex {
($struct:expr) => {
arrayref::array_ref!(hex::encode(digest_struct!($struct)).as_bytes(), 0, 64)
};
}
14 changes: 9 additions & 5 deletions programs/drift/src/validation/sig_verification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,19 @@ fn check_ed25519_data(data: &[u8], pubkey: &[u8], msg: &[u8], sig: &[u8]) -> Res
Ok(())
}

/// Check Ed25519Program instruction data verifies the given digest
/// Check Ed25519Program instruction data verifies the given msg
///
/// `ix` an Ed25519Program instruction [see](https://github.com/solana-labs/solana/blob/master/sdk/src/ed25519_instruction.rs))
///
/// `digest` expected digest signed by the offchain client i.e 'sha256(appMessage.serialize())'
/// `msg` expected msg signed by the offchain client e.g 'sha256(appMessage.serialize())' for a digest
///
/// `pubkey` expected pubkey of the signer
///
pub fn verify_ed25519_digest(ix: &Instruction, pubkey: &[u8; 32], digest: &[u8; 32]) -> Result<()> {
pub fn verify_ed25519_msg<const N: usize>(
ix: &Instruction,
pubkey: &[u8; 32],
msg: &[u8; N],
) -> Result<()> {
if ix.program_id != ED25519_ID || ix.accounts.len() != 0 {
msg!("Invalid Ix: program ID: {:?}", ix.program_id);
msg!("Invalid Ix: accounts: {:?}", ix.accounts.len());
Expand All @@ -100,7 +104,7 @@ pub fn verify_ed25519_digest(ix: &Instruction, pubkey: &[u8; 32], digest: &[u8;
msg!(
"Invalid Ix: data: {:?}, len: {:?}",
ix.data.len(),
16 + 64 + 32 + digest.len()
16 + 64 + 32 + N
);
return Err(ErrorCode::SigVerificationFailed.into());
}
Expand Down Expand Up @@ -137,7 +141,7 @@ pub fn verify_ed25519_digest(ix: &Instruction, pubkey: &[u8; 32], digest: &[u8;

// verify data is for digest and pubkey
let ix_msg_data = &ix_data[112..];
if ix_msg_data != digest || message_data_size != digest.len() as u16 {
if ix_msg_data != msg || message_data_size != N as u16 {
return Err(ErrorCode::SigVerificationFailed.into());
}

Expand Down
2 changes: 1 addition & 1 deletion sdk/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.101.0-beta.7
2.102.0-beta.2
2 changes: 1 addition & 1 deletion sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@drift-labs/sdk",
"version": "2.101.0-beta.7",
"version": "2.102.0-beta.2",
"main": "lib/node/index.js",
"types": "lib/node/index.d.ts",
"browser": "./lib/browser/index.js",
Expand Down
13 changes: 7 additions & 6 deletions sdk/src/adminClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3859,10 +3859,12 @@ export class AdminClient extends DriftClient {
}

public async initializePythPullOracle(
feedId: string
feedId: string,
isAdmin = false
): Promise<TransactionSignature> {
const initializePythPullOracleIx = await this.getInitializePythPullOracleIx(
feedId
feedId,
isAdmin
);
const tx = await this.buildTransaction(initializePythPullOracleIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
Expand All @@ -3871,16 +3873,15 @@ export class AdminClient extends DriftClient {
}

public async getInitializePythPullOracleIx(
feedId: string
feedId: string,
isAdmin = false
): Promise<TransactionInstruction> {
const feedIdBuffer = getFeedIdUint8Array(feedId);
return await this.program.instruction.initializePythPullOracle(
feedIdBuffer,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
admin: isAdmin ? this.getStateAccount().admin : this.wallet.publicKey,
state: await this.getStatePublicKey(),
systemProgram: SystemProgram.programId,
priceFeed: getPythPullOraclePublicKey(
Expand Down
2 changes: 1 addition & 1 deletion sdk/src/constants/perpMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1002,7 +1002,7 @@ export const MainnetPerpMarkets: PerpMarketConfig[] = [
symbol: 'PNUT-PERP',
baseAssetSymbol: 'PNUT',
marketIndex: 55,
oracle: new PublicKey('5RgXW13Kq1RgCLEsJhhchWt3W4R2XLJnd6KqgZk6dSY7'),
oracle: new PublicKey('5AcetMtdRHxkse2ny44NcRdsysnXu9deW7Yy5Y63qAHE'),
launchTs: 1731443152000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
Expand Down
11 changes: 11 additions & 0 deletions sdk/src/constants/spotMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,17 @@ export const MainnetSpotMarkets: SpotMarketConfig[] = [
pythFeedId:
'0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
},
{
symbol: 'USDS',
marketIndex: 28,
oracle: new PublicKey('7pT9mxKXyvfaZKeKy1oe2oV2K1RFtF7tPEJHUY3h2vVV'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('USDSwr9ApdHk5bvJKMjzff41FfuX8bSxdKcR81vTwcA'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
pythFeedId:
'0x77f0971af11cc8bac224917275c1bf55f2319ed5c654a1ca955c82fa2d297ea1',
},
];

export const SpotMarkets: { [key in DriftEnv]: SpotMarketConfig[] } = {
Expand Down
2 changes: 1 addition & 1 deletion sdk/src/idl/drift.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "2.100.0",
"version": "2.101.0",
"name": "drift",
"instructions": [
{
Expand Down