1 2
import { createHash } from 'crypto'
2 2
import { create as createLogger } from '../common/log'
3 2
const log = createLogger('validate-fulfillment-middleware')
4 2
import * as IlpPacket from 'ilp-packet'
5
import { Middleware, MiddlewareCallback, Pipelines } from '../types/middleware'
6 2
const { WrongConditionError } = IlpPacket.Errors
7

8 2
export default class ValidateFulfillmentMiddleware implements Middleware {
9
  async applyToPipelines (pipelines: Pipelines, accountId: string) {
10 2
    pipelines.outgoingData.insertLast({
11
      name: 'validateFulfillment',
12
      method: async (data: Buffer, next: MiddlewareCallback<Buffer, Buffer>) => {
13 2
        if (data[0] === IlpPacket.Type.TYPE_ILP_PREPARE) {
14 2
          const { executionCondition } = IlpPacket.deserializeIlpPrepare(data)
15

16 2
          const result = await next(data)
17

18 2
          if (result[0] === IlpPacket.Type.TYPE_ILP_FULFILL) {
19 2
            const { fulfillment } = IlpPacket.deserializeIlpFulfill(result)
20 2
            const calculatedCondition = createHash('sha256').update(fulfillment).digest()
21

22 2
            if (!calculatedCondition.equals(executionCondition)) {
23 2
              log.error('received incorrect fulfillment from account. accountId=%s fulfillment=%s calculatedCondition=%s executionCondition=%s', accountId, fulfillment.toString('base64'), calculatedCondition.toString('base64'), executionCondition.toString('base64'))
24 2
              throw new WrongConditionError('fulfillment did not match expected value.')
25
            }
26
          }
27

28 2
          return result
29
        }
30

31 0
        return next(data)
32
      }
33
    })
34
  }
35
}

Read our documentation on viewing source code .

Loading