UNPKG

982 BJavaScriptView Raw
1'use strict'
2
3const errcode = require('err-code')
4const uint8ArrayToString = require('uint8arrays/to-string')
5
6/**
7 * @typedef {import('./record')} Record
8 */
9
10/**
11 * Checks a record and ensures it is still valid.
12 * It runs the needed validators.
13 * If verification fails the returned Promise will reject with the error.
14 *
15 * @param {import('libp2p-interfaces/src/types').DhtValidators} validators
16 * @param {Record} record
17 */
18const verifyRecord = (validators, record) => {
19 const key = record.key
20 const keyString = uint8ArrayToString(key)
21 const parts = keyString.split('/')
22
23 if (parts.length < 3) {
24 // No validator available
25 return
26 }
27
28 const validator = validators[parts[1].toString()]
29
30 if (!validator) {
31 const errMsg = 'Invalid record keytype'
32
33 throw errcode(new Error(errMsg), 'ERR_INVALID_RECORD_KEY_TYPE')
34 }
35
36 return validator.func(key, record.value)
37}
38
39module.exports = {
40 verifyRecord: verifyRecord,
41 validators: require('./validators')
42}