|
| 1 | +import { Descriptor } from '@bitgo/wasm-miniscript'; |
| 2 | +import { EnvironmentName, Triple } from '@bitgo/sdk-core'; |
| 3 | +import * as utxolib from '@bitgo/utxo-lib'; |
| 4 | + |
| 5 | +import { DescriptorBuilder, parseDescriptor } from './builder'; |
| 6 | +import { NamedDescriptor } from './NamedDescriptor'; |
| 7 | +import { DescriptorMap, toDescriptorMap } from '../core/descriptor'; |
| 8 | + |
| 9 | +export type DescriptorValidationPolicy = { allowedTemplates: DescriptorBuilder['name'][] } | 'allowAll'; |
| 10 | + |
| 11 | +export type KeyTriple = Triple<utxolib.BIP32Interface>; |
| 12 | + |
| 13 | +function isDescriptorWithTemplate( |
| 14 | + d: Descriptor, |
| 15 | + name: DescriptorBuilder['name'], |
| 16 | + walletKeys: Triple<utxolib.BIP32Interface> |
| 17 | +): boolean { |
| 18 | + const parsed = parseDescriptor(d); |
| 19 | + if (parsed.name !== name) { |
| 20 | + return false; |
| 21 | + } |
| 22 | + if (parsed.keys.length !== walletKeys.length) { |
| 23 | + return false; |
| 24 | + } |
| 25 | + return parsed.keys.every((k, i) => k.toBase58() === walletKeys[i].toBase58()); |
| 26 | +} |
| 27 | + |
| 28 | +export function assertDescriptorPolicy( |
| 29 | + descriptor: Descriptor, |
| 30 | + policy: DescriptorValidationPolicy, |
| 31 | + walletKeys: Triple<utxolib.BIP32Interface> |
| 32 | +): void { |
| 33 | + if (policy === 'allowAll') { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + if ('allowedTemplates' in policy) { |
| 38 | + const allowed = policy.allowedTemplates; |
| 39 | + if (!allowed.some((t) => isDescriptorWithTemplate(descriptor, t, walletKeys))) { |
| 40 | + throw new Error(`Descriptor ${descriptor.toString()} does not match any allowed template`); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + throw new Error(`Unknown descriptor validation policy: ${policy}`); |
| 45 | +} |
| 46 | + |
| 47 | +export function toDescriptorMapValidate( |
| 48 | + descriptors: NamedDescriptor[], |
| 49 | + walletKeys: KeyTriple, |
| 50 | + policy: DescriptorValidationPolicy |
| 51 | +): DescriptorMap { |
| 52 | + const map = toDescriptorMap(descriptors); |
| 53 | + for (const descriptor of map.values()) { |
| 54 | + assertDescriptorPolicy(descriptor, policy, walletKeys); |
| 55 | + } |
| 56 | + return map; |
| 57 | +} |
| 58 | + |
| 59 | +export function getPolicyForEnv(env: EnvironmentName): DescriptorValidationPolicy { |
| 60 | + switch (env) { |
| 61 | + case 'adminProd': |
| 62 | + case 'prod': |
| 63 | + return { |
| 64 | + allowedTemplates: ['Wsh2Of3', 'ShWsh2Of3CltvDrop'], |
| 65 | + }; |
| 66 | + default: |
| 67 | + return 'allowAll'; |
| 68 | + } |
| 69 | +} |
0 commit comments