Skip to content

Commit

Permalink
remove swift messages from swift (#1386)
Browse files Browse the repository at this point in the history
* remove swift messages from swift

* revert Anchor.toml changes

* add slot sanity check
  • Loading branch information
NourAlharithi authored Dec 16, 2024
1 parent 28090f7 commit 70f3da2
Show file tree
Hide file tree
Showing 13 changed files with 93 additions and 508 deletions.
2 changes: 1 addition & 1 deletion programs/drift/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ pub enum ErrorCode {
SigVerificationFailed,
#[msg("Market index mismatched b/w taker and maker swift order params")]
MismatchedSwiftOrderParamsMarketIndex,
#[msg("Swift only available for market/oracle perp orders")]
#[msg("Invalid swift order param")]
InvalidSwiftOrderParam,
#[msg("Place and take order success condition failed")]
PlaceAndTakeOrderSuccessConditionFailed,
Expand Down
51 changes: 20 additions & 31 deletions programs/drift/src/instructions/keeper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ use crate::state::fulfillment_params::serum::SerumFulfillmentParams;
use crate::state::high_leverage_mode_config::HighLeverageModeConfig;
use crate::state::insurance_fund_stake::InsuranceFundStake;
use crate::state::oracle_map::OracleMap;
use crate::state::order_params::{
OrderParams, PlaceOrderOptions, SwiftOrderParamsMessage, SwiftServerMessage,
};
use crate::state::order_params::{OrderParams, PlaceOrderOptions, SwiftOrderParamsMessage};
use crate::state::paused_operations::PerpOperation;
use crate::state::perp_market::{ContractType, MarketStatus, PerpMarket};
use crate::state::perp_market_map::{
Expand Down Expand Up @@ -603,11 +601,8 @@ pub fn handle_update_user_open_orders_count<'info>(ctx: Context<UpdateUserIdle>)

pub fn handle_place_swift_taker_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceSwiftTakerOrder<'info>>,
swift_message_bytes: Vec<u8>,
swift_order_params_message_bytes: Vec<u8>,
) -> Result<()> {
let swift_message: SwiftServerMessage =
SwiftServerMessage::deserialize(&mut &swift_message_bytes[..]).unwrap();
let taker_order_params_message: SwiftOrderParamsMessage =
SwiftOrderParamsMessage::deserialize(&mut &swift_order_params_message_bytes[..]).unwrap();

Expand All @@ -634,7 +629,6 @@ pub fn handle_place_swift_taker_order<'c: 'info, 'info>(
taker_key,
&mut taker,
&mut swift_taker,
swift_message,
taker_order_params_message,
&ctx.accounts.ix_sysvar.to_account_info(),
&perp_market_map,
Expand All @@ -649,7 +643,6 @@ pub fn place_swift_taker_order<'c: 'info, 'info>(
taker_key: Pubkey,
taker: &mut RefMut<User>,
swift_account: &mut SwiftUserOrdersZeroCopyMut,
swift_message: SwiftServerMessage,
taker_order_params_message: SwiftOrderParamsMessage,
ix_sysvar: &AccountInfo<'info>,
perp_market_map: &PerpMarketMap,
Expand All @@ -665,20 +658,12 @@ pub fn place_swift_taker_order<'c: 'info, 'info>(
// Authenticate the swift param message
let ix_idx = load_current_index_checked(ix_sysvar)?;
validate!(
ix_idx > 1,
ix_idx > 0,
ErrorCode::InvalidVerificationIxIndex,
"instruction index must be greater than 1 for two sig verifies"
"instruction index must be greater than 0 for one sig verifies"
)?;

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

// Verify data from second verify ix
// Verify data from verify ix
let digest_hex = digest_struct_hex!(taker_order_params_message);
let ix: Instruction = load_instruction_at_checked(ix_idx as usize - 1, ix_sysvar)?;
verify_ed25519_msg(
Expand All @@ -687,12 +672,7 @@ pub fn place_swift_taker_order<'c: 'info, 'info>(
arrayref::array_ref!(digest_hex, 0, 64),
)?;

// Verify that sig from swift server corresponds to order message
if swift_message.swift_order_signature != extract_ed25519_ix_signature(&ix.data)? {
msg!("Swift order signature does not match the order signature");
return Err(ErrorCode::SigVerificationFailed.into());
}

let signature = extract_ed25519_ix_signature(&ix.data)?;
let clock = &Clock::get()?;

// First order must be a taker order
Expand All @@ -715,7 +695,14 @@ pub fn place_swift_taker_order<'c: 'info, 'info>(
}

// Set max slot for the order early so we set correct swift order id
let order_slot = swift_message.slot;
let order_slot = taker_order_params_message.slot;
if order_slot < clock.slot - 500 {
msg!(
"Swift order slot {} is too old: must be within 500 slots of current slot",
order_slot
);
return Err(print_error!(ErrorCode::InvalidSwiftOrderParam)().into());
}
let market_index = matching_taker_order_params.market_index;
let max_slot = order_slot.safe_add(
matching_taker_order_params
Expand All @@ -735,7 +722,11 @@ pub fn place_swift_taker_order<'c: 'info, 'info>(
}

// Dont place order if swift order already exists
let swift_order_id = SwiftOrderId::new(swift_message.uuid, max_slot, taker.next_order_id);
let swift_order_id = SwiftOrderId::new(
taker_order_params_message.uuid,
max_slot,
taker.next_order_id,
);
if swift_account.check_exists_and_prune_stale_swift_order_ids(swift_order_id, clock.slot) {
msg!("Swift order already exists for taker {}");
return Ok(());
Expand All @@ -757,10 +748,8 @@ pub fn place_swift_taker_order<'c: 'info, 'info>(
},
)?;

let order_params_hash = base64::encode(
solana_program::hash::hash(&swift_message.swift_order_signature.try_to_vec().unwrap())
.as_ref(),
);
let order_params_hash =
base64::encode(solana_program::hash::hash(&signature.try_to_vec().unwrap()).as_ref());

emit!(SwiftOrderRecord {
user: taker_key,
Expand Down
3 changes: 1 addition & 2 deletions programs/drift/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,9 @@ pub mod drift {

pub fn place_swift_taker_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceSwiftTakerOrder<'info>>,
swift_message_bytes: Vec<u8>,
swift_order_params_message_bytes: Vec<u8>,
) -> Result<()> {
handle_place_swift_taker_order(ctx, swift_message_bytes, swift_order_params_message_bytes)
handle_place_swift_taker_order(ctx, swift_order_params_message_bytes)
}

pub fn place_and_match_rfq_orders<'c: 'info, 'info>(
Expand Down
9 changes: 2 additions & 7 deletions programs/drift/src/state/order_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -706,17 +706,12 @@ impl OrderParams {
}
}

#[derive(AnchorSerialize, AnchorDeserialize, Clone, Eq, PartialEq, Debug)]
pub struct SwiftServerMessage {
pub uuid: [u8; 8],
pub swift_order_signature: [u8; 64],
pub slot: u64,
}

#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default, Eq, PartialEq, Debug)]
pub struct SwiftOrderParamsMessage {
pub swift_order_params: OrderParams,
pub sub_account_id: u16,
pub slot: u64,
pub uuid: [u8; 8],
pub take_profit_order_params: Option<SwiftTriggerOrderParams>,
pub stop_loss_order_params: Option<SwiftTriggerOrderParams>,
}
Expand Down
3 changes: 0 additions & 3 deletions sdk/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,6 @@ export type DriftEnv = 'devnet' | 'mainnet-beta';
export const DRIFT_PROGRAM_ID = 'dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH';
export const DRIFT_ORACLE_RECEIVER_ID =
'G6EoTTTgpkNBtVXo96EQp2m6uwwVh2Kt6YidjkmQqoha';
export const SWIFT_ID = 'SW1fThqrxLzVprnCMpiybiqYQfoNCdduC5uWsSUKChS';
export const ANCHOR_TEST_SWIFT_ID =
'DpaEdAPW3ZX67fnczT14AoX12Lx9VMkxvtT81nCHy3Nv';
export const PTYH_LAZER_PROGRAM_ID =
'pytd2yyk641x7ak7mkaasSJVXh6YYZnC7wTmtgAyxPt';
export const PYTH_LAZER_STORAGE_ACCOUNT_KEY = new PublicKey(
Expand Down
79 changes: 9 additions & 70 deletions sdk/src/driftClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ import {
StateAccount,
SwapReduceOnly,
SwiftOrderParamsMessage,
SwiftServerMessage,
TakerInfo,
TxParams,
UserAccount,
Expand Down Expand Up @@ -136,7 +135,6 @@ import {
DRIFT_ORACLE_RECEIVER_ID,
DEFAULT_CONFIRMATION_OPTS,
DRIFT_PROGRAM_ID,
SWIFT_ID,
DriftEnv,
PYTH_LAZER_STORAGE_ACCOUNT_KEY,
} from './config';
Expand Down Expand Up @@ -202,7 +200,6 @@ export class DriftClient {
connection: Connection;
wallet: IWallet;
public program: Program;
public swiftID: PublicKey;
provider: AnchorProvider;
opts?: ConfirmOptions;
users = new Map<string, User>();
Expand Down Expand Up @@ -270,7 +267,6 @@ export class DriftClient {
config.programID ?? new PublicKey(DRIFT_PROGRAM_ID),
this.provider
);
this.swiftID = config.swiftID ?? new PublicKey(SWIFT_ID);

this.authority = config.authority ?? this.wallet.publicKey;
this.activeSubAccountId = config.activeSubAccountId ?? 0;
Expand Down Expand Up @@ -5847,29 +5843,6 @@ export class DriftClient {
);
}

public encodeSwiftServerMessage(message: SwiftServerMessage): Buffer {
return this.program.coder.types.encode('SwiftServerMessage', message);
}

public decodeSwiftServerMessage(encodedMessage: Buffer): SwiftServerMessage {
const decodedSwiftMessage = this.program.coder.types.decode(
'SwiftServerMessage',
encodedMessage
);
return {
uuid: decodedSwiftMessage.uuid,
slot: decodedSwiftMessage.slot,
swiftOrderSignature: decodedSwiftMessage.swiftSignature,
};
}

public signSwiftServerMessage(message: SwiftServerMessage): Buffer {
const swiftServerMessage = Uint8Array.from(
digest(this.encodeSwiftServerMessage(message))
);
return this.signMessage(swiftServerMessage);
}

public signSwiftOrderParamsMessage(
orderParamsMessage: SwiftOrderParamsMessage
): Buffer {
Expand Down Expand Up @@ -5906,8 +5879,6 @@ export class DriftClient {
}

public async placeSwiftTakerOrder(
swiftServerMessage: Buffer,
swiftSignature: Buffer,
swiftOrderParamsMessage: Buffer,
swiftOrderParamsSignature: Buffer,
marketIndex: number,
Expand All @@ -5919,8 +5890,6 @@ export class DriftClient {
txParams?: TxParams
): Promise<TransactionSignature> {
const ixs = await this.getPlaceSwiftTakerPerpOrderIxs(
swiftServerMessage,
swiftSignature,
swiftOrderParamsMessage,
swiftOrderParamsSignature,
marketIndex,
Expand All @@ -5935,8 +5904,6 @@ export class DriftClient {
}

public async getPlaceSwiftTakerPerpOrderIxs(
encodedSwiftServerMessage: Buffer,
swiftSignature: Buffer,
encodedSwiftOrderParamsMessage: Buffer,
swiftOrderParamsSignature: Buffer,
marketIndex: number,
Expand All @@ -5957,13 +5924,6 @@ export class DriftClient {
readablePerpMarketIndex: marketIndex,
});

const swiftServerSignatureIx =
Ed25519Program.createInstructionWithPublicKey({
publicKey: new PublicKey(this.swiftID).toBytes(),
signature: Uint8Array.from(swiftSignature),
message: Uint8Array.from(digest(encodedSwiftServerMessage)),
});

const authorityToUse = authority || takerInfo.takerUserAccount.authority;
const swiftOrderParamsSignatureIx =
Ed25519Program.createInstructionWithPublicKey({
Expand All @@ -5976,7 +5936,6 @@ export class DriftClient {

const placeTakerSwiftPerpOrderIx =
await this.program.instruction.placeSwiftTakerOrder(
encodedSwiftServerMessage,
encodedSwiftOrderParamsMessage,
{
accounts: {
Expand All @@ -5994,16 +5953,10 @@ export class DriftClient {
}
);

return [
swiftServerSignatureIx,
swiftOrderParamsSignatureIx,
placeTakerSwiftPerpOrderIx,
];
return [swiftOrderParamsSignatureIx, placeTakerSwiftPerpOrderIx];
}

public async placeAndMakeSwiftPerpOrder(
encodedSwiftMessage: Buffer,
swiftSignature: Buffer,
encodedSwiftOrderParamsMessage: Buffer,
swiftOrderParamsSignature: Buffer,
swiftOrderUuid: Uint8Array,
Expand All @@ -6018,8 +5971,6 @@ export class DriftClient {
subAccountId?: number
): Promise<TransactionSignature> {
const ixs = await this.getPlaceAndMakeSwiftPerpOrderIxs(
encodedSwiftMessage,
swiftSignature,
encodedSwiftOrderParamsMessage,
swiftOrderParamsSignature,
swiftOrderUuid,
Expand All @@ -6039,8 +5990,6 @@ export class DriftClient {
}

public async getPlaceAndMakeSwiftPerpOrderIxs(
encodedSwiftMessage: Buffer,
swiftSignature: Buffer,
encodedSwiftOrderParamsMessage: Buffer,
swiftOrderParamsSignature: Buffer,
swiftOrderUuid: Uint8Array,
Expand All @@ -6053,18 +6002,13 @@ export class DriftClient {
referrerInfo?: ReferrerInfo,
subAccountId?: number
): Promise<TransactionInstruction[]> {
const [
swiftServerSignatureIx,
swiftOrderSignatureIx,
placeTakerSwiftPerpOrderIx,
] = await this.getPlaceSwiftTakerPerpOrderIxs(
encodedSwiftMessage,
swiftSignature,
encodedSwiftOrderParamsMessage,
swiftOrderParamsSignature,
orderParams.marketIndex,
takerInfo
);
const [swiftOrderSignatureIx, placeTakerSwiftPerpOrderIx] =
await this.getPlaceSwiftTakerPerpOrderIxs(
encodedSwiftOrderParamsMessage,
swiftOrderParamsSignature,
orderParams.marketIndex,
takerInfo
);

orderParams = getOrderParams(orderParams, { marketType: MarketType.PERP });
const userStatsPublicKey = this.getUserStatsAccountPublicKey();
Expand Down Expand Up @@ -6113,12 +6057,7 @@ export class DriftClient {
}
);

return [
swiftServerSignatureIx,
swiftOrderSignatureIx,
placeTakerSwiftPerpOrderIx,
placeAndMakeIx,
];
return [swiftOrderSignatureIx, placeTakerSwiftPerpOrderIx, placeAndMakeIx];
}

public encodeRFQMakerOrderParams(message: RFQMakerOrderParams): Buffer {
Expand Down
1 change: 0 additions & 1 deletion sdk/src/driftClientConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export type DriftClientConfig = {
wallet: IWallet;
env?: DriftEnv;
programID?: PublicKey;
swiftID?: PublicKey;
accountSubscription?: DriftClientSubscriptionConfig;
opts?: ConfirmOptions;
txSender?: TxSender;
Expand Down
Loading

0 comments on commit 70f3da2

Please sign in to comment.