XRP 백서

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 28쪽 중 27쪽

all this method to request a credential from the service. This method parses the request body as JSON and validates it. If this succeeds, it uses the data to fill out a CredentialCreate transaction. Finally, it checks the transaction's result to decide which HTTP response code to use: // POST /credential - Method for users to request a credential from the service ------------------- app. post ( "/credential" , async ( req , res ) => { try { // validateCredentialRequest() throws if the request is not validly formatted const credRequest = validateCredentialRequest (req.body); /** * As a credential issuer, you typically need to verify some information * about someone before you issue them a credential. For this example, * the user passes relevant information in a documents field of the API request. * The documents are kept confidential, off-chain. * * verifyDocuments() throws if the provided documents don't pass inspection */ verifyDocuments (req.body); const credXrpl = credentialToXrpl (credRequest); const tx = { TransactionType: "CredentialCreate" , Account: wallet.address, Subject: credXrpl.subject, CredentialType: credXrpl.credential, URI: credXrpl.uri, Expiration: credXrpl.expiration, }; const ccResponse = await client. submitAndWait (tx, { autofill: true , wallet }); if (ccResponse.result.meta.TransactionResult === "tecDUPLICATE" ) { throw new XRPLTxError (ccResponse, 409 ); } else if (ccResponse.result.meta.TransactionResult !== "tesSUCCESS" ) { throw new XRPLTxError (ccResponse); } return res. status ( 201 ). json (ccResponse.result); } catch (err) { return handleAppError (res, err); } }); The next API method is GET /admin/credential , which looks up credentials issued by the service. It uses the lookUpCredentials(...) method defined in look_up_credentials.js to get a list of credentials. Then it calls the serializeCredential(...) and parseCredentialFromXrpl(...) functions, imported from credential.js , to transform each ledger entry from the XRP Ledger format to the simplified representation the microservice uses. // GET /admin/credential - Method for admins to look up all credentials issued ------------------- app. get ( "/admin/credential" , async ( req , res ) => { try { // ?accepted=yes|no|both query parameter - the default is "both" const query = Object. fromEntries ( Object. entries (req.query). map (([ k , v ]) => [k. toLowerCase (), v]) ); const filterAccepted = (query.accepted || "both" ). toLowerCase (); const credentials = await lookUpCredentials (client, wallet.address, "" , filterAccepted); const result = credentials. map (( entry ) => credentialFromXrpl (entry)); return res. status ( 200 ). json ({ credentials: result }); } catch (err) { return handleAppError (res, err); } }); The final API method, DELETE /admin/credential , deletes a Credential from the ledger, revoking it. This again uses functions from credential.js to validate user inputs and translate them into XRPL format where necessary. After that, it attempts to look up the Credential in the ledger and returns an error if it doesn't exist. This way, the issuer doesn't have to pay the cost of sending a transaction that would fail. Finally, the method checks the transaction result and sets the HTTP response code accordingly. // DELETE /admin/credential - Method for admins to revoke an issued credential ---------------------------- app. delete ( "/admin/credential" , async ( req , res ) => { let delRequest; try { delRequest = validateCredentialRequest (req.body); const { credential } = credentialToXrpl (delRequest); // To save on transaction fees, check if the credential exists on ledger before attempting to delete it. // If the credential is not found, a RippledError (`entryNotFound`) is thrown. await client. request ({ command: "ledger_entry" , credential: { subject: delRequest.subject, issuer: wallet.address, credential_type: credential, }, ledger_index: "validated" , }); const tx = { TransactionType: "CredentialDelete" , Account: wallet.address, Subject: delRequest.subject, CredentialType: credential, }; const cdResponse = await client. submitAndWait (tx, { autofill: true , wallet }); if (cdResponse.result.meta.TransactionResult === "tecNO_ENTRY" ) { // Usually this won't happen since we just checked for the credential, // but it's possible it got deleted since then. throw new XRPLTxError (cdResponse, 404 ); } else if (cdResponse.result.meta.TransactionResult !== "tesSUCCESS" ) { throw new XRPLTxError (cdResponse); } return res. status ( 200 ). json (cdResponse.result); } catch (err) { if (err.data?.error === "entryNotFound" ) { return res. status ( 404 ). json ({ error: err.data.error, error_message: `Credential doesn't exist for subject '${ delRequest . subject }' and credential type '${ delRequest . credential }'` , }); } else { return handleAppError (res, err); } } }); The port for the microservice is set to either an environment variable called PORT or to 3000 , and the application listens for connections at the assigned port: const PORT = process.env. PORT || 3000 ; app. listen ( PORT , () => { console. log ( `🔐 Credential issuer service running on port: ${ PORT }` ); }); } Finally, the code runs the main() function: // Start the server -------------------------------------------------------------- main (). catch (( err ) => { console. error ( "❌ Fatal startup error:" , err); process. exit ( 1 ); }); look_up_credentials.js This file implements lookup of Credentials. Both the issuer code and the subject code use this function to look up their own credentials. This code performs pagination using markers to get all the results from the ledger. It also filters results based on the issuer/subject account, so that lookup by issuer, for example, doesn't include credentials that someone else issued to the issuer account. Finally, it can optionally check the accepted status of the Credentials and only include ones that are or aren't accepted. import { ValueError } from "./errors.js" ; const lsfAccepted = 0x00010000 ; /** * Looks up Credentials issued by/to a specified XRPL account, optionally * filtering by accepted status. Handles pagination. */ export async function lookUpCredentials ( client , issuer , subject , accepted = "both" ) { const account = issuer || subject; // Use whichever is specified, issuer if both if ( ! account) { throw new ValueError ( "Must specify issuer or subject" ); } accepted = accepted. toLowerCase (); if ( ! [ "yes" , "no" , "both" ]. includes (accepted)) { throw new ValueError ( "accepted must be 'yes', 'no', or 'both'" ); } const credentials = []; let request = { command: "account_objects" , account, type: "credential" , ledger_index: "validated" , }; // Fetch first page let response = await client. request (request); while ( true ) { for ( const obj of response.result.account_objects) { if (issuer && obj.Issuer !== issuer) continue ; if (subject && obj.Subject !== subject) continue ; const credAccepted = Boolean (obj.Flags & lsfAccepted); if (accepted === "yes" && ! credAccepted) continue ; if (accepted === "no" && credAccepted) continue ; credentials. push (obj); } if ( ! response.result.marker) break ; /** * If there is a marker, request the next page using the convenience function "requestNextPage()". * See https://js.xrpl.org/classes/Client.html#requestnextpage to learn more. **/ response = await client. requestNextPage (request, response.result); } return credentials; } credential.js This file defines a set of helper functions that validate credential related input, verify request data, and convert between the issuer microservice's simplified Credential format and the XRP Ledger object representation. It throws typed errors on invalid input. The file starts with importing dependencies, grouped into external packages and local files: import { isoTimeToRippleTime, rippleTimeToISOTime, isValidClassicAddress, } from "xrpl" ; import { stringToHex, hexToString } from "@xrplf/isomorphic/dist/utils/index.js" ; import { ValueError } from "./errors.js" ; It then defines regular expression constants that are used further on in the code to validate the credential and uri: // Regex constants const CREDENTIAL_REGEX = / ^ [A-Za-z0-9_.-] {1,128}$ / ; const URI_REGEX = / ^ [A-Za-z0-9\-._~:/?# \[\] @!$&'()*+,;=%] {1,256}$ / ; The function validateCredentialRequest(...) checks that the user input meets various requirements. It also parses the user-provided timestamp from a string to a native Javascript Date object if necessary. /** * Validate credential request. * This function performs parameter validation. Validated fields: * - subject (required): the subject of the credential, as a classic address * - credential (required): the credential type, in human-readable (ASCII) chars * - uri (optional): URI of the credential in human-readable (ASCII) chars * - expiration (optional): time when the credential expires (displayed as an ISO 8601 format string in JSON) */ export function validateCredentialRequest ({ subject , credential , uri , expiration }) { // Validate subject if ( typeof subject !== "string" ) { throw new ValueError ( "Must provide a string 'subject' field" ); } if ( ! isValidClassicAddress (subject)) { throw new ValueError ( `subject not valid address: '${ subject }'` ); } // Validate credential if ( typeof credential !== "string" ) { throw new ValueError ( "Must provide a string 'credential' field" ); } if ( ! CREDENTIAL_REGEX . test (credential)) { /** * Checks if the specified credential type is one that this service issues. * XRPL credential types can be any binary data; this service issues * any credential that can be encoded from the following ASCII chars: * alphanumeric characters, underscore, period, and dash. (min length 1, max 128) * * You might want to further limit the credential types, depending on your * use case; for example, you might only issue one specific credential type. */ throw new ValueError ( `credential not allowed: '${ credential }'.` ); } /* (Optional) Checks if the specified URI is acceptable for this service. XRPL Credentials' URI values can be any binary data; this service adds any user-requested URI to a Credential as long as the URI can be encoded from the characters usually allowed in URIs, namely the following ASCII chars: alphanumeric characters (upper and lower case) the following symbols: -._~:/?#[]@!$&'()*+,;=% (minimum length 1 and max length 256 chars) You might want to instead define your own URI and attach it to the Credential regardless of user input, or you might want to verify that the URI points to a valid Verifiable Credential document that matches the user. */ if (uri !== undefined ) { if ( typeof uri !== "string" || ! URI_REGEX . test (uri)) { throw new ValueError ( `URI isn't valid: ${ uri }` ); } } // Validate and parse expiration let parsedExpiration; if (expiration !== undefined ) { if ( typeof expiration !== "string" ) { throw new ValueError ( `Unsupported expiration format: ${ typeof expiration }` ); } parsedExpiration = new Date (expiration); if ( isNaN (parsedExpiration. getTime ())) { throw new ValueError ( `Invalid expiration date: ${ expiration }` ); } } return { subject, credential, uri, expiration: parsedExpiration, }; } The credentialFromXrpl(...) function converts an XRPL ledger entry into a usable credential object (for example, converting the credential field from hexadecimal to a native string). The API methods that read data from the XRP Ledger use this function so that their output is formatted the same way as user input in the other API methods. // Convert an XRPL ledger entry into a usable credential object export function credentialFromXrpl ( entry ) { const { Subject , CredentialType , URI , Expiration , Flags } = entry; return { subject: Subject, credential: hexToString (CredentialType), uri: URI ? hexToString ( URI ) : undefined , expiration: Expiration ? rippleTimeToISOTime (Expiration) : undefined , accepted: Boolean (Flags & 0x00010000 ), // lsfAccepted }; } The credentialToXrpl(...) function returns an object which is formatted for submitting to the XRP Ledger: // Convert to an object in a format closer to the XRP Ledger representation export function credentialToXrpl ( cred ) { // Credential type and URI are hexadecimal; // Expiration, if present, is in seconds since the Ripple Epoch. return { subject: cred.subject, credential: stringToHex (cred.credential), uri: cred.uri ? stringToHex (cred.uri) : undefined , expiration: cred.expiration ? isoTimeToRippleTime (cred.expiration) : undefined , }; } Finally, the verifyDocuments(...) function checks for an additional field, documents . For a realistic credential issuer, you might require the user to provide specific documents in the request body, like a photo of their government-issued ID or a cryptographically signed message from another business, which your code would check. For this tutorial, the check is only a placeholder: export function verifyDocuments ({ documents }) { /** * This is where you would check the user's documents to see if you * should issue the requested Credential to them. * Depending on the type of credentials your service needs, you might * need to implement different types of checks here. */ if ( typeof documents !== "object" || Object. keys (documents). length === 0 ) { throw new ValueError ( "you must provide a non-empty 'documents' field" ); } // As a placeholder, this example checks that the documents field // contains a string field named "reason" containing the word "please". const reason = documents.reason; if ( typeof reason !== "string" ) { throw new ValueError ( "documents must contain a 'reason' string" ); } if ( ! reason. toLowerCase (). includes ( "please" )) { throw new ValueError ( "reason must include 'please'" ); } } errors.js This file defines custom error classes used by the credential issuer service to provide consistent error handling and help distinguish between different kinds of failures: export class ValueError extends Error { constructor ( message ) { super (message); this .name = "ValueError" ; this .status = 400 ; this .type = "badRequest" ; } } export class XRPLTxError extends Error { constructor ( xrplResponse , status = 400 ) { super ( "XRPL transaction failed" ); this .name = "XRPLTxError" ; this .status = status; this .body = xrplResponse.result; } } Next Steps Using this service as a base, you can extend the service with more features, such as: Security/authentication to protect API methods from unauthorized use. Actually checking user documents to decide if you should issue a credential. Alternatively, you can use credentials to for various purposes, such as: Define a Permissioned Domain that uses your credentials to grant access to features on the XRP Ledger. Verify credentials manually to grant access to services that exist off-ledger. See Also Python: Build a Credential Issuing Service ## /docs/tutorials/javascript/compliance/create-permissioned-domains Manage Permissioned Domains Copy This tutorial shows how to create a permissioned domain , which can be used to grant access to specific other features like Permissioned DEXes and Single Asset Vaults . It also shows how to modify a domain to update its set of accepted credentials and how to delete a permissioned domain. Requires the PermissionedDomains amendment . Loading... Goals By following this tutorial, you should learn how to: Create a permissioned domain. Modify or delete a permissioned domain. Prerequisites To complete this tutorial, you should: Have a basic understanding of the XRP Ledger, including what permissioned domains and credentials are. Have an XRP Ledger client library , such as xrpl.js , installed. Tip This tutorial doesn't cover issuing and accepting credentials, which aren't necessary for creating and managing a permissioned domain. Valid credentials are necessary for actually using something that's gated by a permissioned domain. For examples of issuing and accepting credentials, see: Manage Credentials Build a Credential Issuing Service in JavaScript or in Python Source Code You can find the complete source code for this tutorial's examples in the code samples section of this website's repository . Steps 1. Install dependencies JavaScript Python From the code sample folder, use npm to install dependencies: npm i 2. Connect and get account(s) To get started, import the client library and instantiate an API client. You also need an issuer address and credential type for the credential that will grant access to your domain. The credentials themselves don't have to be issued yet; you can do that separately before or after setting up the domain, or you can rely on credentials issued by a third party. JavaScript Python import xrpl from 'xrpl' import { stringToHex } from '@xrplf/isomorphic/dist/utils/index.js' import fs from 'fs' // Get issuer wallet and define constants ------------------------------------- const client = new xrpl. Client ( 'wss://s.altnet.rippletest.net:51233' ) await client. connect () console. log ( 'Getting a new account from the faucet.' ) const { wallet } = await client. fundWallet () console. log ( `Account funded: Address: ${ wallet . address } Seed: ${ wallet . seed } ` ) const issuerAddress = wallet.address // Can also use a third-party issuer const credentialType = stringToHex ( "my-credential" ) 3. Send PermissionedDomainSet transaction To create a permissioned domain, send a PermissionedDomainSet transaction omitting the DomainID field. In the AcceptedCredentials field, specify the credentials that grant access to the domain. JavaScript Python // Create a domain ------------------------------------------------------------ const pDomainSet = { TransactionType: "PermissionedDomainSet" , Account: wallet.address, AcceptedCredentials: [ { Credential: { Issuer: issuerAddress, CredentialType: credentialType } } ] } console. log ( 'Submitting transaction' , JSON . stringify (pDomainSet, null , 2 )) const response = await client. submitAndWait (pDomainSet, { wallet, autofill: true }) console. log (response) const resultCode = response.result.meta.TransactionResult if (resultCode !== 'tesSUCCESS' ) { console. error ( `PermissionedDomainSet failed with code ${ resultCode }` ) client. disconnect () process. exit ( 2 ) } console. log ( 'Successfully created permissioned domain.' ) 4. Find the Domain ID To identify the permissioned domain later, you need its Domain ID. It is possible to calculate this using the Permissioned Domain ID format , but it is often easier to find it in the metadata of the transaction that created the domain. Look through the transaction metadata for a CreatedNode of type PermissionedDomain . The LedgerIndex field of that entry is the Domain ID. JavaScript Python // Find Domain ID in metadata ------------------------------------------------- let domainID for ( const modifiedNode of response.result.meta.AffectedNodes) { if (modifiedNode.CreatedNode?.LedgerEntryType
프로젝트로 돌아가기