UNPKG

1.57 kBPlain TextView Raw
1import { createHash } from 'crypto'
2import { create as createLogger } from '../common/log'
3const log = createLogger('validate-fulfillment-middleware')
4import * as IlpPacket from 'ilp-packet'
5import { Middleware, MiddlewareCallback, Pipelines } from '../types/middleware'
6const { WrongConditionError } = IlpPacket.Errors
7
8export default class ValidateFulfillmentMiddleware implements Middleware {
9 async applyToPipelines (pipelines: Pipelines, accountId: string) {
10 pipelines.outgoingData.insertLast({
11 name: 'validateFulfillment',
12 method: async (data: Buffer, next: MiddlewareCallback<Buffer, Buffer>) => {
13 if (data[0] === IlpPacket.Type.TYPE_ILP_PREPARE) {
14 const { executionCondition } = IlpPacket.deserializeIlpPrepare(data)
15
16 const result = await next(data)
17
18 if (result[0] === IlpPacket.Type.TYPE_ILP_FULFILL) {
19 const { fulfillment } = IlpPacket.deserializeIlpFulfill(result)
20 const calculatedCondition = createHash('sha256').update(fulfillment).digest()
21
22 if (!calculatedCondition.equals(executionCondition)) {
23 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 throw new WrongConditionError('fulfillment did not match expected value.')
25 }
26 }
27
28 return result
29 }
30
31 return next(data)
32 }
33 })
34 }
35}