|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +import { Command } from "commander"; |
| 4 | +import { Client, rippleTimeToISOTime, convertStringToHex } from "xrpl"; |
| 5 | +import winston from "winston"; |
| 6 | + |
| 7 | +// Set up logging -------------------------------------------------------------- |
| 8 | +// Use WARNING by default in case verify_credential is called from elsewhere. |
| 9 | +const logger = winston.createLogger({ |
| 10 | + level: "warn", |
| 11 | + transports: [new winston.transports.Console()], |
| 12 | + format: winston.format.simple(), |
| 13 | +}); |
| 14 | + |
| 15 | +// Define an error to throw when XRPL lookup fails unexpectedly |
| 16 | +class XRPLLookupError extends Error { |
| 17 | + constructor(error) { |
| 18 | + super("XRPL look up error"); |
| 19 | + this.name = "XRPLLookupError"; |
| 20 | + this.body = error; |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +const CREDENTIAL_REGEX = /^[0-9A-F]{2,128}$/; |
| 25 | +// See https://xrpl.org/docs/references/protocol/ledger-data/ledger-entry-types/credential#credential-flags |
| 26 | +// to learn more about the lsfAccepted flag. |
| 27 | +const LSF_ACCEPTED = 0x00010000; |
| 28 | + |
| 29 | +async function verifyCredential(client, issuer, subject, credentialType, binary=false) { |
| 30 | + /** |
| 31 | + * Check whether an XRPL account holds a specified credential, |
| 32 | + * as of the most recently validated ledger. |
| 33 | + * Parameters: |
| 34 | + * client - Client for interacting with rippled servers. |
| 35 | + * issuer - Address of the credential issuer, in base58. |
| 36 | + * subject - Address of the credential holder/subject, in base58. |
| 37 | + * credentialType - Credential type to check for as a string, |
| 38 | + * which will be encoded as UTF-8 (1-128 characters long). |
| 39 | + * binary - Specifies that the credential type is provided in hexadecimal format. |
| 40 | + * You must provide the credential_type as input. |
| 41 | + * Returns True if the account holds the specified, valid credential. |
| 42 | + * Returns False if the credential is missing, expired, or not accepted. |
| 43 | + */ |
| 44 | + |
| 45 | + // Encode credentialType as uppercase hex, if needed |
| 46 | + let credentialTypeHex = ""; |
| 47 | + if (binary) { |
| 48 | + credentialTypeHex = credentialType.toUpperCase(); |
| 49 | + } else { |
| 50 | + credentialTypeHex = convertStringToHex(credentialType).toUpperCase(); |
| 51 | + logger.info(`Encoded credential_type as hex: ${credentialTypeHex}`); |
| 52 | + } |
| 53 | + |
| 54 | + if (credentialTypeHex.length % 2 !== 0 || !CREDENTIAL_REGEX.test(credentialTypeHex)) { |
| 55 | + // Hexadecimal is always 2 chars per byte, so an odd length is invalid. |
| 56 | + throw new Error("Credential type must be 128 characters as hexadecimal."); |
| 57 | + } |
| 58 | + |
| 59 | + // Perform XRPL lookup of Credential ledger entry -------------------------- |
| 60 | + const ledgerEntryRequest = { |
| 61 | + command: "ledger_entry", |
| 62 | + credential: { |
| 63 | + subject: subject, |
| 64 | + issuer: issuer, |
| 65 | + credential_type: credentialTypeHex, |
| 66 | + }, |
| 67 | + ledger_index: "validated", |
| 68 | + }; |
| 69 | + logger.info("Looking up credential..."); |
| 70 | + logger.info(JSON.stringify(ledgerEntryRequest, null, 2)); |
| 71 | + |
| 72 | + let xrplResponse; |
| 73 | + try { |
| 74 | + xrplResponse = await client.request(ledgerEntryRequest); |
| 75 | + } catch (err) { |
| 76 | + if (err.data?.error === "entryNotFound") { |
| 77 | + logger.info("Credential was not found"); |
| 78 | + return false; |
| 79 | + } else { |
| 80 | + // Other errors, for example invalidly specified addresses. |
| 81 | + throw new XRPLLookupError(err?.data || err); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + const credential = xrplResponse.result.node; |
| 86 | + logger.info("Found credential:"); |
| 87 | + logger.info(JSON.stringify(credential, null, 2)); |
| 88 | + |
| 89 | + // Check if the credential has been accepted --------------------------- |
| 90 | + if (!(credential.Flags & LSF_ACCEPTED)) { |
| 91 | + logger.info("Credential is not accepted."); |
| 92 | + return false |
| 93 | + } |
| 94 | + |
| 95 | + // Confirm that the credential is not expired ------------------------------ |
| 96 | + if (credential.Expiration) { |
| 97 | + const expirationTime = rippleTimeToISOTime(credential.Expiration); |
| 98 | + logger.info(`Credential has expiration: ${expirationTime}`); |
| 99 | + logger.info("Looking up validated ledger to check for expiration."); |
| 100 | + |
| 101 | + let ledgerResponse; |
| 102 | + try { |
| 103 | + ledgerResponse = await client.request({ |
| 104 | + command: "ledger", |
| 105 | + ledger_index: "validated", |
| 106 | + }); |
| 107 | + } catch (err) { |
| 108 | + throw new XRPLLookupError(err?.data || err); |
| 109 | + } |
| 110 | + |
| 111 | + const closeTime = rippleTimeToISOTime(ledgerResponse.result.ledger.close_time); |
| 112 | + logger.info(`Most recent validated ledger is: ${closeTime}`); |
| 113 | + |
| 114 | + if (new Date(closeTime) > new Date(expirationTime)) { |
| 115 | + logger.info("Credential is expired."); |
| 116 | + return false; |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + // Credential has passed all checks --------------------------------------- |
| 121 | + logger.info("Credential is valid."); |
| 122 | + return true; |
| 123 | +} |
| 124 | + |
| 125 | + |
| 126 | +// Commandline usage ----------------------------------------------------------- |
| 127 | +async function main() { |
| 128 | + // Websocket URLs of public servers |
| 129 | + const NETWORKS = { |
| 130 | + devnet: "wss://s.devnet.rippletest.net:51233", |
| 131 | + testnet: "wss://s.altnet.rippletest.net:51233", |
| 132 | + mainnet: "wss://xrplcluster.com/", |
| 133 | + }; |
| 134 | + |
| 135 | + |
| 136 | + // Parse arguments --------------------------------------------------------- |
| 137 | + let result = false |
| 138 | + const program = new Command(); |
| 139 | + program |
| 140 | + .name("verify-credential") |
| 141 | + .description("Verify an XRPL credential") |
| 142 | + .argument("[issuer]", "Credential issuer address as base58", "rEzikzbnH6FQJ2cCr4Bqmf6c3jyWLzkonS") |
| 143 | + .argument("[subject]", "Credential subject (holder) address as base58", "rsYhHbanGpnYe3M6bsaMeJT5jnLTfDEzoA") |
| 144 | + .argument("[credential_type]", "Credential type as string.", "my_credential") |
| 145 | + .option("-b, --binary", "Use binary (hexadecimal) for credential_type") |
| 146 | + .option( |
| 147 | + `-n, --network <network> {${Object.keys(NETWORKS)}}`, |
| 148 | + "Use the specified network for lookup", |
| 149 | + (value) => { |
| 150 | + if (!Object.keys(NETWORKS).includes(value)) { |
| 151 | + throw new Error(`Must be one of: ${Object.keys(NETWORKS)}`); |
| 152 | + } |
| 153 | + return value; |
| 154 | + }, |
| 155 | + "devnet" |
| 156 | + ) |
| 157 | + .option("-q, --quiet", "Don't print log messages") |
| 158 | + // Call verify_credential with appropriate args ---------------------------- |
| 159 | + .action(async (issuer, subject, credentialType, options) => { |
| 160 | + const client = new Client(NETWORKS[options.network]); |
| 161 | + await client.connect(); |
| 162 | + |
| 163 | + // Use INFO level by default when called from the commandline. |
| 164 | + if (!options.quiet) { logger.level = "info" } |
| 165 | + |
| 166 | + // Commander.js automatically sets options.binary to a boolean: |
| 167 | + // - If you provide -b or --binary on the command line then options.binary = true |
| 168 | + // - If you do not provide it then options.binary = false |
| 169 | + result = await verifyCredential(client, issuer, subject, credentialType, options.binary); |
| 170 | + |
| 171 | + await client.disconnect(); |
| 172 | + }); |
| 173 | + await program.parseAsync(process.argv); |
| 174 | + |
| 175 | + // Return a nonzero exit code if credential verification failed ----------- |
| 176 | + if (!result) { |
| 177 | + process.exit(1); |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +main().catch((err) => { |
| 182 | + console.error("Fatal startup error:", err); |
| 183 | + process.exit(1); |
| 184 | +}); |
0 commit comments