Skip to content

Commit c380bec

Browse files
committed
Add verify credentials tutorial for Javascript
1 parent 3adc598 commit c380bec

File tree

7 files changed

+573
-2
lines changed

7 files changed

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

docs/tutorials/javascript/build-apps/credential-issuing-service.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,8 +357,7 @@ Using this service as a base, you can extend the service with more features, suc
357357
Alternatively, you can use credentials to for various purposes, such as:
358358

359359
- Define a [Permissioned Domain](/docs/concepts/tokens/decentralized-exchange/permissioned-domains) that uses your credentials to grant access to features on the XRP Ledger.
360-
<!-- TODO: Uncomment once tutorial is ready. -->
361-
<!-- - [Verify credentials](../compliance/verify-credential.md) manually to grant access to services that exist off-ledger. -->
360+
- [Verify credentials](../compliance/verify-credential.md) manually to grant access to services that exist off-ledger.
362361

363362
## See Also
364363

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
metadata:
3+
indexPage: true
4+
seo:
5+
description: Transact with confidence using the XRP Ledger's suite of compliance features for following government regulations and security practices.
6+
---
7+
# Transact with Confidence Using Compliance Features
8+
9+
The XRP Ledger has a rich suite of features designed to help financial institutions of all sizes engage with DeFi technology while complying with government regulations domestically and internationally.
10+
11+
See the following tutorials for examples of how to put these features to work:
12+
13+
{% child-pages /%}

0 commit comments

Comments
 (0)