Skip to content

Commit

Permalink
[PROTO-1813] Add geo to purchases (#8424)
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondjacobson authored May 14, 2024
1 parent 33157c6 commit f9c7705
Show file tree
Hide file tree
Showing 5 changed files with 208 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,10 @@ const readConfig = (): Config => {
solana_relay_server_host: str({ default: '0.0.0.0' }),
solana_relay_server_port: num({ default: 6002 }),
audius_delegate_private_key: str({ default: '' }),
audius_ipdata_api_key: str({ default: '' })
audius_ipdata_api_key: str({
// Throwaway test key
default: '01b633611c0b57babd56a6fdf7400b21340956e1840da6dd788f9c37'
})
})
const solanaFeePayerWalletsParsed = env.audius_solana_fee_payer_wallets
let solanaFeePayerWallets: Keypair[] = []
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { PaymentRouterProgram } from '@audius/spl'
import {
Keypair,
PublicKey,
TransactionInstruction,
TransactionMessage,
} from '@solana/web3.js'
import { config } from '../../config'
import { describe, it } from 'vitest'
import { attachLocationData, isPaymentTransaction } from './attachLocationData'
import assert from 'assert'

const PAYMENT_ROUTER_PROGRAM_ID = new PublicKey(config.paymentRouterProgramId)
const MEMO_V2_PROGRAM_ID = new PublicKey(
'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'
)

const getRandomPublicKey = () => Keypair.generate().publicKey

describe('isPaymentTransaction', () => {
it('returns true when instructions are a payment', async () => {
const [pda, bump] = PublicKey.findProgramAddressSync(
[new TextEncoder().encode('payment_router')],
new PublicKey(PAYMENT_ROUTER_PROGRAM_ID)
)
const instructions = [
await PaymentRouterProgram.createRouteInstruction({
sender: getRandomPublicKey(),
senderOwner: pda,
paymentRouterPdaBump: bump,
recipients: [getRandomPublicKey()],
amounts: [BigInt(100)],
totalAmount: BigInt(100),
programId: PAYMENT_ROUTER_PROGRAM_ID
})
]
const isPayment = await isPaymentTransaction(instructions)
assert.strictEqual(isPayment, true)
})

it('returns false whe instructions are a recovery', async () => {
const [pda, bump] = PublicKey.findProgramAddressSync(
[new TextEncoder().encode('payment_router')],
new PublicKey(PAYMENT_ROUTER_PROGRAM_ID)
)
const instructions = [
await PaymentRouterProgram.createRouteInstruction({
sender: getRandomPublicKey(),
senderOwner: pda,
paymentRouterPdaBump: bump,
recipients: [getRandomPublicKey()],
amounts: [BigInt(100)],
totalAmount: BigInt(100),
programId: PAYMENT_ROUTER_PROGRAM_ID
}),
new TransactionInstruction({
keys: [{ pubkey: getRandomPublicKey(), isSigner: true, isWritable: true }],
data: Buffer.from('Recover Withdrawal'),
programId: MEMO_V2_PROGRAM_ID
})
]
const isPayment = await isPaymentTransaction(instructions)
assert.strictEqual(isPayment, false)
})
})

describe('attachLocationData', () => {
it('attaches a properly formatted geo instruction', async () => {
const payerKey = getRandomPublicKey()
const recentBlockhash = '5D1qXoiJqhYYJTyVCWijs9zX9n2AoZbcbLviHHZ1U14L'
const [pda, bump] = PublicKey.findProgramAddressSync(
[new TextEncoder().encode('payment_router')],
new PublicKey(PAYMENT_ROUTER_PROGRAM_ID)
)
const instructions = [
await PaymentRouterProgram.createRouteInstruction({
sender: getRandomPublicKey(),
senderOwner: pda,
paymentRouterPdaBump: bump,
recipients: [getRandomPublicKey()],
amounts: [BigInt(100)],
totalAmount: BigInt(100),
programId: PAYMENT_ROUTER_PROGRAM_ID
}),
new TransactionInstruction({
keys: [{ pubkey: getRandomPublicKey(), isSigner: true, isWritable: true }],
data: Buffer.from('Some random memo'),
programId: MEMO_V2_PROGRAM_ID
})
]
const message = new TransactionMessage({
payerKey,
recentBlockhash,
instructions
})
const updatedMessage = attachLocationData({
transactionMessage: message,
location: {city: 'Nashville', region: 'TN', country: 'United States'}
})
assert.strictEqual(updatedMessage.instructions.length, 3)

assert.strictEqual(updatedMessage.instructions[0], instructions[0])
assert.strictEqual(updatedMessage.instructions[1], instructions[1])

assert.strictEqual(
updatedMessage.instructions[2].data.toString(),
'geo:{"city":"Nashville","region":"TN","country":"United States"}'
)
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import {
PublicKey,
TransactionInstruction,
TransactionMessage
} from '@solana/web3.js'
import { config } from '../../config'
import { LocationData } from '../../utils/ipData'

const MEMO_PROGRAM_ID = 'Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo'
const MEMO_V2_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'
const PAYMENT_ROUTER_PROGRAM_ID = config.paymentRouterProgramId

const RECOVERY_MEMO_STRING = "Recover Withdrawal"
const GEO_MEMO_STRING = "geo"

/**
* Determines whether or not the provided instructions are from a payment transaction
* @param instructions the instructions to check
* @returns boolean
*/
export const isPaymentTransaction = (
instructions: TransactionInstruction[]
) => {
let usesPaymentRouter = false
let isRecovery = false
for (let i = 0; i < instructions.length; i++) {
const instruction = instructions[i]
switch (instruction.programId.toBase58()) {
case PAYMENT_ROUTER_PROGRAM_ID:
usesPaymentRouter = true
break
case MEMO_PROGRAM_ID:
case MEMO_V2_PROGRAM_ID: {
const memo = instruction.data.toString()
if (memo === RECOVERY_MEMO_STRING) {
isRecovery = true
}
break
}
default:
break
}
}
return usesPaymentRouter && !isRecovery
}

/**
* Attaches location data to a TransactionMessage
*/
export const attachLocationData = (
{ transactionMessage, location }:
{
transactionMessage: TransactionMessage,
location: LocationData
}
): TransactionMessage => {
const memoInstruction = new TransactionInstruction({
keys: [{ pubkey: transactionMessage.payerKey, isSigner: true, isWritable: true }],
data: Buffer.from(`${GEO_MEMO_STRING}:${JSON.stringify(location)}`, 'utf-8'),
programId: new PublicKey(MEMO_V2_PROGRAM_ID)
})
const updatedInstructions = [...transactionMessage.instructions, memoInstruction]
const msg = new TransactionMessage({
payerKey: transactionMessage.payerKey,
recentBlockhash: transactionMessage.recentBlockhash,
instructions: updatedInstructions
})
return msg
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ import { assertRelayAllowedInstructions } from './assertRelayAllowedInstructions
import { cacheTransaction, getCachedDiscoveryNodes } from '../../redis'
import fetch from 'cross-fetch'
import { Logger } from 'pino'
import base58 from 'bs58'
import bs58 from 'bs58'
import { personalSign } from 'eth-sig-util'
import type { RelayRequestBody } from '@audius/sdk'
import { getRequestIpData } from '../../utils/ipData'
import { attachLocationData, isPaymentTransaction } from './attachLocationData'

const RETRY_DELAY_MS = 2 * 1000
const RETRY_TIMEOUT_MS = 60 * 1000
Expand Down Expand Up @@ -205,7 +207,8 @@ export const relay = async (
const strategy =
confirmationOptions?.strategy ?? (await connection.getLatestBlockhash())
const decoded = Buffer.from(encodedTransaction, 'base64')
const transaction = VersionedTransaction.deserialize(decoded)
let transaction = VersionedTransaction.deserialize(decoded)

const decompiled = TransactionMessage.decompile(transaction.message)
const feePayerKey = transaction.message.getAccountKeys().get(0)
const feePayerKeyPair = getFeePayerKeyPair(feePayerKey)
Expand All @@ -219,8 +222,20 @@ export const relay = async (
feePayer: feePayerKey.toBase58()
})

if (isPaymentTransaction(decompiled.instructions)) {
const location = await getRequestIpData(res.locals.logger, req)
if (location) {
transaction = new VersionedTransaction(
attachLocationData({
transactionMessage: decompiled,
location
}).compileToV0Message()
)
}
}

transaction.sign([feePayerKeyPair])
const signature = base58.encode(transaction.signatures[0])
const signature = bs58.encode(transaction.signatures[0])

const logger = res.locals.logger.child({ signature })
logger.info(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import { getClientIp } from "request-ip"
import { config } from "../config"
import { logger } from "../logger"

export type LocationData = { city: string, region: string, country: string } | {}
export type LocationData = { city: string, region: string, country: string } | null

// gets ip data from api.ipdata.co, returns an empty object {} if api key not configured or an error occurs
export const getIpData = async (logger: Logger, ip: string): Promise<LocationData> => {
const ipdataApiKey = config.ipdataApiKey
if (ipdataApiKey === null) {
logger.warn({}, "ip data requested but api key not configured")
return {}
return null
}
const url = `https://api.ipdata.co/${ip}?api-key=${config.ipdataApiKey}`
const url = `https://api.ipdata.co/${ip}?api-key=${ipdataApiKey}`
try {
const response = await axios.get(url)
.then(({ data: { city, region, country_name } }: { data: { city: string, region: string, country_name: string } }) => {
Expand All @@ -23,25 +23,25 @@ export const getIpData = async (logger: Logger, ip: string): Promise<LocationDat
return response
} catch (e: unknown) {
logger.error({ error: e }, "error requesting ip data")
return {}
return null
}
}

// gets ip data from api.ipdata.co, returns an empty object {} if api key not configured or an error occurs
export const getRequestIpData = async (logger: Logger, req: Request): Promise<LocationData> => {
export const getRequestIpData = async (logger: Logger, req: Request<unknown>): Promise<LocationData> => {
try {
const ip = getIP(req)
return getIpData(logger, ip)
} catch (e) {
logger.error({ e }, "error requesting ip data")
return {}
return null
}
}

// Utility to gather the IP from an incoming express request.
// Prioritizes 'X-Forwarded-For' if it exists. Otherwise returns the request objects ip.
// Throws if neither can be found.
export const getIP = (req: Request): string => {
export const getIP = (req: Request<unknown>): string => {
const clientIP = getClientIp(req)
// https://github.com/pbojinov/request-ip?tab=readme-ov-file#how-it-works
if (clientIP === null) {
Expand Down

0 comments on commit f9c7705

Please sign in to comment.