|
| 1 | +import { Type, TypeBoxTypeProvider } from '@fastify/type-provider-typebox'; |
| 2 | +import Fastify, { |
| 3 | + FastifyInstance, |
| 4 | + FastifyPluginCallback, |
| 5 | + FastifyReply, |
| 6 | + FastifyRequest, |
| 7 | +} from 'fastify'; |
| 8 | +import { Server } from 'http'; |
| 9 | +import { request } from 'undici'; |
| 10 | +import { logger, PINO_CONFIG } from './util/logger'; |
| 11 | +import { timeout } from './util/helpers'; |
| 12 | +import { Payload, PayloadSchema } from './schemas'; |
| 13 | +import { Predicate, ThenThat } from './schemas/predicate'; |
| 14 | + |
| 15 | +export type OnEventCallback = (uuid: string, payload: Payload) => Promise<void>; |
| 16 | + |
| 17 | +type ServerOptions = { |
| 18 | + server: { |
| 19 | + host: string; |
| 20 | + port: number; |
| 21 | + auth_token: string; |
| 22 | + external_hostname: string; |
| 23 | + }; |
| 24 | + chainhook_node: { |
| 25 | + hostname: string; |
| 26 | + port: number; |
| 27 | + }; |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * Starts the chainhook event server. |
| 32 | + * @returns Fastify instance |
| 33 | + */ |
| 34 | +export async function startServer( |
| 35 | + opts: ServerOptions, |
| 36 | + predicates: [Predicate], |
| 37 | + callback: OnEventCallback |
| 38 | +) { |
| 39 | + const base_path = `http://${opts.chainhook_node.hostname}:${opts.chainhook_node.port}`; |
| 40 | + |
| 41 | + async function waitForNode(this: FastifyInstance) { |
| 42 | + logger.info(`EventServer connecting to chainhook node...`); |
| 43 | + while (true) { |
| 44 | + try { |
| 45 | + await request(`${base_path}/ping`, { method: 'GET', throwOnError: true }); |
| 46 | + break; |
| 47 | + } catch (error) { |
| 48 | + logger.error(error, 'Chainhook node not available, retrying...'); |
| 49 | + await timeout(1000); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + async function registerPredicates(this: FastifyInstance) { |
| 55 | + logger.info(predicates, `EventServer registering predicates on ${base_path}...`); |
| 56 | + for (const predicate of predicates) { |
| 57 | + const thenThat: ThenThat = { |
| 58 | + http_post: { |
| 59 | + url: `http://${opts.server.external_hostname}/chainhook/${predicate.uuid}`, |
| 60 | + authorization_header: `Bearer ${opts.server.auth_token}`, |
| 61 | + }, |
| 62 | + }; |
| 63 | + try { |
| 64 | + const body = predicate; |
| 65 | + if ('mainnet' in body.networks) body.networks.mainnet.then_that = thenThat; |
| 66 | + if ('testnet' in body.networks) body.networks.testnet.then_that = thenThat; |
| 67 | + await request(`${base_path}/v1/chainhooks`, { |
| 68 | + method: 'POST', |
| 69 | + body: JSON.stringify(body), |
| 70 | + headers: { 'content-type': 'application/json' }, |
| 71 | + throwOnError: true, |
| 72 | + }); |
| 73 | + logger.info(`EventServer registered '${predicate.name}' predicate (${predicate.uuid})`); |
| 74 | + } catch (error) { |
| 75 | + logger.error(error, `EventServer unable to register predicate`); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + async function removePredicates(this: FastifyInstance) { |
| 81 | + logger.info(`EventServer closing predicates...`); |
| 82 | + for (const predicate of predicates) { |
| 83 | + try { |
| 84 | + await request(`${base_path}/v1/chainhooks/${predicate.chain}/${predicate.uuid}`, { |
| 85 | + method: 'DELETE', |
| 86 | + headers: { 'content-type': 'application/json' }, |
| 87 | + throwOnError: true, |
| 88 | + }); |
| 89 | + logger.info(`EventServer removed '${predicate.name}' predicate (${predicate.uuid})`); |
| 90 | + } catch (error) { |
| 91 | + logger.error(error, `EventServer unable to deregister predicate`); |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + async function isEventAuthorized(request: FastifyRequest, reply: FastifyReply) { |
| 97 | + const authHeader = request.headers.authorization; |
| 98 | + if (authHeader && authHeader === `Bearer ${opts.server.auth_token}`) { |
| 99 | + return; |
| 100 | + } |
| 101 | + await reply.code(403).send(); |
| 102 | + } |
| 103 | + |
| 104 | + const EventServer: FastifyPluginCallback<Record<never, never>, Server, TypeBoxTypeProvider> = ( |
| 105 | + fastify, |
| 106 | + options, |
| 107 | + done |
| 108 | + ) => { |
| 109 | + fastify.addHook('preHandler', isEventAuthorized); |
| 110 | + fastify.post( |
| 111 | + '/chainhook/:uuid', |
| 112 | + { |
| 113 | + schema: { |
| 114 | + params: Type.Object({ |
| 115 | + uuid: Type.String({ format: 'uuid' }), |
| 116 | + }), |
| 117 | + body: PayloadSchema, |
| 118 | + }, |
| 119 | + }, |
| 120 | + async (request, reply) => { |
| 121 | + try { |
| 122 | + await callback(request.params.uuid, request.body); |
| 123 | + } catch (error) { |
| 124 | + logger.error(error, `EventServer error processing payload`); |
| 125 | + await reply.code(422).send(); |
| 126 | + } |
| 127 | + await reply.code(200).send(); |
| 128 | + } |
| 129 | + ); |
| 130 | + done(); |
| 131 | + }; |
| 132 | + |
| 133 | + const fastify = Fastify({ |
| 134 | + trustProxy: true, |
| 135 | + logger: PINO_CONFIG, |
| 136 | + pluginTimeout: 0, // Disable so ping can retry indefinitely |
| 137 | + bodyLimit: 41943040, // 40 MB |
| 138 | + }).withTypeProvider<TypeBoxTypeProvider>(); |
| 139 | + |
| 140 | + fastify.addHook('onReady', waitForNode); |
| 141 | + fastify.addHook('onReady', registerPredicates); |
| 142 | + fastify.addHook('onClose', removePredicates); |
| 143 | + await fastify.register(EventServer); |
| 144 | + |
| 145 | + await fastify.listen({ host: opts.server.host, port: opts.server.port }); |
| 146 | + return fastify; |
| 147 | +} |
0 commit comments