1 2
import * as IlpPacket from 'ilp-packet'
2 2
import { create as createLogger } from '../common/log'
3 2
const log = createLogger('max-packet-amount-middleware')
4 2
import BigNumber from 'bignumber.js'
5 2
const { AmountTooLargeError } = IlpPacket.Errors
6
import { Middleware, MiddlewareCallback, MiddlewareServices, Pipelines } from '../types/middleware'
7
import { AccountInfo } from '../types/accounts'
8

9 2
export default class MaxPacketAmountMiddleware implements Middleware {
10
  private getInfo: (accountId: string) => AccountInfo
11

12
  constructor (opts: {}, { getInfo }: MiddlewareServices) {
13 2
    this.getInfo = getInfo
14
  }
15

16
  async applyToPipelines (pipelines: Pipelines, accountId: string) {
17 2
    const accountInfo = this.getInfo(accountId)
18

19 2
    if (!accountInfo) {
20 0
      throw new Error('account info unavailable. accountId=' + accountId)
21
    }
22

23 2
    if (accountInfo.maxPacketAmount) {
24 2
      const maxPacketAmount = accountInfo.maxPacketAmount
25 2
      pipelines.incomingData.insertLast({
26
        name: 'maxPacketAmount',
27
        method: async (data: Buffer, next: MiddlewareCallback<Buffer, Buffer>) => {
28 2
          if (data[0] === IlpPacket.Type.TYPE_ILP_PREPARE) {
29 2
            const parsedPacket = IlpPacket.deserializeIlpPrepare(data)
30

31 2
            const amount = new BigNumber(parsedPacket.amount)
32 2
            if (amount.gt(maxPacketAmount)) {
33 2
              log.debug('rejecting packet for exceeding max amount. accountId=%s maxAmount=%s actualAmount=%s', accountId, maxPacketAmount, parsedPacket.amount)
34 2
              throw new AmountTooLargeError(`packet size too large. maxAmount=${maxPacketAmount} actualAmount=${parsedPacket.amount}`, {
35
                receivedAmount: parsedPacket.amount,
36
                maximumAmount: maxPacketAmount
37
              })
38
            }
39
          }
40

41 2
          return next(data)
42
        }
43
      })
44
    }
45

46
  }
47
}

Read our documentation on viewing source code .

Loading