TrustVC is a comprehensive wrapper library designed to simplify the signing and verification processes for TrustVC W3C Verifiable Credentials (VC) and OpenAttestation Verifiable Documents (VD), adhering to the W3C VC Data Model v1.1 (W3C Standard). It ensures compatibility and interoperability for Verifiable Credentials while supporting OpenAttestation Verifiable Documents (VD) v6.9.5. TrustVC seamlessly integrates functionalities for handling W3C Verifiable Credentials and OpenAttestation Verifiable Documents, leveraging existing TradeTrust libraries and smart contracts for Token Registry (V4 and V5). Additionally, it includes essential utility functions for strings, networks, and chains, making it a versatile tool for developers working with decentralized identity and verifiable data solutions.
npm install
npm run build
npm run test
This module provides utility functions for wrapping OpenAttestation documents of version 2 (v2) and version 3 (v3). These functions validate the document version and apply the appropriate wrapping logic using the OpenAttestation library. Note that wrapping is not required for W3C-compliant documents, as they follow a different format and standard.
Wraps a single OpenAttestation document asynchronously, supporting both v2 and v3 documents.
document: OpenAttestationDocument The OpenAttestation document to be wrapped.
Promise A promise that resolves to the wrapped document.
Error If the document version is unsupported or if an error occurs during wrapping.
import { wrapOADocument } from '@trustvc/trustvc';
const document = {
/* OpenAttestation document (v2 or v3) */
};
const wrappedDocument = await wrapOADocument(document);
console.log(wrappedDocument);
Wraps multiple OpenAttestation documents asynchronously, supporting both v2 and v3 documents.
documents: OpenAttestationDocument[] An array of OpenAttestation documents to be wrapped.
Promise<WrappedDocument[]> A promise that resolves to the array of wrapped documents.
Error If the documents include unsupported versions or if an error occurs during wrapping.
import { wrapOADocuments } from '@trustvc/trustvc';
const documents = [
{
/* doc1 */
},
{
/* doc2 */
},
];
const wrappedDocuments = await wrapOADocuments(documents);
console.log(wrappedDocuments);
The TrustVC Signing feature simplifies the signing process for OA documents and W3C-compliant verifiable credentials using BBS+ signatures. This feature allows you to easily sign W3C Verifiable Credentials (VCs) and ensure they comply with the latest standards.
The signing functionality is split into two methods:
- signOA: Designed specifically for signing OpenAttestation documents.
- signW3C: Tailored for signing W3C-compliant verifiable credentials.
import { wrapOA, signOA } from '@trustvc/trustvc';
const rawDocument = {
'@context': [
'https://www.w3.org/ns/credentials/v2',
'https://schemata.openattestation.com/com/openattestation/4.0/context.json',
],
type: ['VerifiableCredential', 'OpenAttestationCredential'],
credentialSubject: {
id: '0x1234567890123456789012345678901234567890',
name: 'John Doe',
country: 'SG',
},
issuer: {
id: 'did:ethr:0xB26B4941941C51a4885E5B7D3A1B861E54405f90',
type: 'OpenAttestationIssuer',
name: 'Government Technology Agency of Singapore (GovTech)',
identityProof: { identityProofType: 'DNS-DID', identifier: 'example.openattestation.com' },
},
};
const wrappedDocument = await wrapOA(rawDocument);
const signedWrappedDocument = await signOA(wrappedDocument, {
public: 'did:ethr:0xB26B4941941C51a4885E5B7D3A1B861E54405f90#controller',
private: '<privateKey>',
});
import { signW3C, VerificationType } from '@trustvc/trustvc';
const rawDocument = {
'@context': [
'https://www.w3.org/2018/credentials/v1',
'https://w3c-ccg.github.io/citizenship-vocab/contexts/citizenship-v1.jsonld',
'https://w3id.org/security/bbs/v1',
'https://w3id.org/vc/status-list/2021/v1',
],
credentialStatus: {
id: 'https://trustvc.github.io/did/credentials/statuslist/1#1',
type: 'StatusList2021Entry',
statusPurpose: 'revocation',
statusListIndex: '10',
statusListCredential: 'https://trustvc.github.io/did/credentials/statuslist/1',
},
credentialSubject: {
name: 'TrustVC',
birthDate: '2024-04-01T12:19:52Z',
type: ['PermanentResident', 'Person'],
},
expirationDate: '2029-12-03T12:19:52Z',
issuer: 'did:web:trustvc.github.io:did:1',
type: ['VerifiableCredential'],
issuanceDate: '2024-04-01T12:19:52Z',
};
const signingResult = await signW3C(rawDocument, {
id: 'did:web:trustvc.github.io:did:1#keys-1',
controller: 'did:web:trustvc.github.io:did:1',
type: VerificationType.Bls12381G2Key2020,
publicKeyBase58:
'oRfEeWFresvhRtXCkihZbxyoi2JER7gHTJ5psXhHsdCoU1MttRMi3Yp9b9fpjmKh7bMgfWKLESiK2YovRd8KGzJsGuamoAXfqDDVhckxuc9nmsJ84skCSTijKeU4pfAcxeJ',
privateKeyBase58: '<privateKeyBase58>',
});
TrustVC simplifies the verification process with a single function that supports both W3C Verifiable Credentials (VCs) and OpenAttestation Verifiable Documents (VDs). Whether you're working with W3C standards or OpenAttestation standards, TrustVC handles the verification seamlessly.
import { verifyDocument } from '@trustvc/trustvc';
const signedDocument = {
'@context': [
'https://www.w3.org/2018/credentials/v1',
'https://w3c-ccg.github.io/citizenship-vocab/contexts/citizenship-v1.jsonld',
'https://w3id.org/security/bbs/v1',
'https://w3id.org/vc/status-list/2021/v1',
],
credentialStatus: {
id: 'https://trustvc.github.io/did/credentials/statuslist/1#1',
type: 'StatusList2021Entry',
statusPurpose: 'revocation',
statusListIndex: '10',
statusListCredential: 'https://trustvc.github.io/did/credentials/statuslist/1',
},
credentialSubject: {
name: 'TrustVC',
birthDate: '2024-04-01T12:19:52Z',
type: ['PermanentResident', 'Person'],
},
expirationDate: '2029-12-03T12:19:52Z',
issuer: 'did:web:trustvc.github.io:did:1',
type: ['VerifiableCredential'],
issuanceDate: '2024-04-01T12:19:52Z',
proof: {
type: 'BbsBlsSignature2020',
created: '2024-10-14T04:11:49Z',
proofPurpose: 'assertionMethod',
proofValue:
'l79dlFQMowalep+WCFqgCvpVBcCAr0GDEFUV6S7gRVY/TQ+sp/wcwaT61PaD19rJYUHlKfzccE4m7waZyoLEkBLFiK2g54Q2i+CdtYBgDdkUDsoULSBMcH1MwGHwdjfXpldFNFrHFx/IAvLVniyeMQ==',
verificationMethod: 'did:web:trustvc.github.io:did:1#keys-1',
},
};
const resultFragments = await verifyDocument(signedDocument);
The
encrypt
function encrypts plaintext messages using the ChaCha20 encryption algorithm, ensuring the security and integrity of the input data. It supports custom keys and nonces, returning the encrypted message in hexadecimal format.
function encrypt(message: string, key: string, nonce?: string): string;
The encrypt
function is a utility for encrypting text messages using ChaCha20, a stream cipher known for its speed and security. This function ensures that the key meets the 32-byte requirement and that a valid 12-byte nonce is either supplied or generated.
The output is a hexadecimal string representing the encrypted data.
-
message
(string): The plaintext message to encrypt. -
key
(string): The encryption key, which will be transformed into a 32-byte key. -
nonce
(string, optional): A 12-byte nonce for encryption. If omitted, a new nonce will be generated automatically.
-
string
: The encrypted message encoded in hexadecimal format.
- Runtime errors: Issues during key transformation, nonce generation, or encryption.
import { encrypt } from '@trustvc/trustvc';
const message = 'Hello, ChaCha20!';
const key = 'my-secret-key';
const encryptedMessage = encrypt(message, key);
console.log(`Encrypted Message: ${encryptedMessage}`);
import { encrypt } from '@trustvc/trustvc';
const message = 'Secure this message.';
const key = 'another-secret-key';
const nonce = '123456789012'; // Custom 12-byte nonce
const encryptedMessage = encrypt(message, key, nonce);
console.log(`Encrypted Message with Nonce: ${encryptedMessage}`);
The function uses the following utilities:
-
stringToUint8Array
: Converts strings toUint8Array
. -
generate32ByteKey
: Ensures the key is exactly 32 bytes. -
generate12ByteNonce
: Produces a valid 12-byte nonce if none is provided.
It also relies on the ts-chacha20
library for encryption operations.
- The encrypted message is returned as a hexadecimal string.
- Always ensure the key and nonce are securely stored and not reused.
- ChaCha20 requires a unique nonce for each encryption to maintain security.
- Hexadecimal encoding is used by default for simplicity and readability.
The
decrypt
function decrypts messages encrypted with the ChaCha20 algorithm. It converts the input from a hexadecimal format back into plaintext using the provided key and nonce.
function decrypt(encryptedMessage: string, key: string, nonce?: string): string;
The decrypt
function is a utility for decrypting hexadecimal-encoded messages that were encrypted using the ChaCha20 stream cipher. It ensures the key meets the 32-byte requirement and validates or generates a 12-byte nonce if not supplied.
The function returns the original plaintext message in UTF-8 format.
-
encryptedMessage
(string): The encrypted message, in hexadecimal format. -
key
(string): The decryption key, which will be transformed into a 32-byte key. Defaults toDEFAULT_KEY
if an empty key is provided. -
nonce
(string, optional): A 12-byte nonce used during encryption. If omitted, one will be generated.
-
string
: The decrypted plaintext message in UTF-8 format.
The function throws an error if:
- The key is invalid or transformation fails.
- The decryption process encounters unexpected issues.
import { decrypt } from '@trustvc/trustvc';
const encryptedMessage = 'e8b7c7e9...';
const key = 'my-secret-key';
const decryptedMessage = decrypt(encryptedMessage, key);
console.log(`Decrypted Message: ${decryptedMessage}`);
import { decrypt } from '@trustvc/trustvc';
const encryptedMessage = 'f3a7e9b2...';
const key = 'another-secret-key';
const nonce = '123456789012'; // Custom 12-byte nonce
const decryptedMessage = decrypt(encryptedMessage, key, nonce);
console.log(`Decrypted Message with Nonce: ${decryptedMessage}`);
The function uses the following utilities:
-
stringToUint8Array
: Converts strings toUint8Array
. -
generate32ByteKey
: Ensures the key is exactly 32 bytes. -
generate12ByteNonce
: Produces a valid 12-byte nonce if none is provided.
It also relies on the ts-chacha20
library for decryption operations.
- The function accepts the encrypted message in hexadecimal format and returns the decrypted message in UTF-8 format.
- Always use the same key and nonce pair that were used during encryption for successful decryption.
- If a custom nonce is not provided, the function will generate a new one, which may not match the original encryption nonce and will result in decryption failure.
- The default key,
DEFAULT_KEY
, should only be used for fallback scenarios and not in production environments. - Suggestion: If available, consider using the value of the key Id inside the document as the encryption key. This can simplify key management and enhance the security of your encryption process.
The Electronic Bill of Lading (eBL) is a digital document that can be used to prove the ownership of goods. It is a standardized document that is accepted by all major shipping lines and customs authorities. The Token Registry repository contains both the smart contract (v4 and v5) code for token registry (in
/contracts
) as well as the node package for using this library (in/src
). The TrustVC library not only simplifies signing and verification but also imports and integrates existing TradeTrust libraries and smart contracts for token registry (V4 and V5), making it a versatile tool for decentralized identity and trust solutions.
To use the package, you will need to provide your own Web3 provider or signer (if you are writing to the blockchain). This package exposes the Typechain(Ethers) bindings for the contracts.
The
TradeTrustToken
is a Soulbound Token (SBT) tied to the Title Escrow. The SBT implementation is loosely based on OpenZeppelin's implementation of the ERC721 standard. An SBT is used in this case because the token, while can be transferred to the registry, is largely restricted to its designated Title Escrow contracts. See issue #108 for more details.
import { v4Contracts } from '@trustvc/trustvc';
const v4connectedRegistry = v4Contracts.TradeTrustToken__factory.connect(
tokenRegistryAddress,
signer,
);
await v4connectedRegistry.mint(beneficiaryAddress, holderAddress, tokenId);
await v4connectedRegistry.restore(tokenId);
await v4connectedRegistry.burn(tokenId);
For more information on Token Registry and Title Escrow contracts version v4, please visit the readme of TradeTrust Token Registry V4.
Token Registry v5 is the newest version. It allows you to manage token-based credentials and ownership transfers through smart contracts. The Tradetrust Token Registry now supports encrypted remarks for enhanced security when executing contract functions. This guide explains how to use the updated title-escrow command with encrypted remarks and highlights the changes introduced in this version. A new rejection function feature has been introduced, allowing a new holder or owner of a document to reject the transfer of the document. This provides an additional layer of control and flexibility for holders and owners to refuse ownership or custodianship if required.
[!IMPORTANT] This new version uses:
- Ethers v6
- OpenZeppelin v5
- Contracts are upgraded to v 0.8.20
- Runs on Compiler v 0.8.22
The
remark
field is optional and can be left empty by providing an empty string"0x"
. Please note that any value in theremark
field is limited to 120 characters, and encryption is recommended.
In Token Registry v5, the way you connect to a registry hasn’t changed much, but it's important to ensure you're using the updated contract and factory from Token Registry v5.
In TrustVC, you will use the token-registry-v5 module to access the Token Registry v5 contracts.
import { v5Contracts } from '@trustvc/trustvc';
const connectedRegistry = v5Contracts.TradeTrustToken__factory.connect(
tokenRegistryAddress,
signer,
);
In Token Registry v5, there is a slight change when you mint tokens. You will now need to pass remarks
as an optional argument. If no remarks are provided, ensure you pass 0x
to avoid errors.
await connectedRegistry.mint(beneficiaryAddress, holderAddress, tokenId, remarks);
If no remarks are passed, the method expects '0x' as the value for remarks:
await connectedRegistry.mint(beneficiaryAddress, holderAddress, tokenId, '0x');
The restore method remains mostly the same, but you'll now also have the option to include remarks.
await connectedRegistry.restore(tokenId, remarks);
If no remarks are passed, use '0x':
await connectedRegistry.restore(tokenId, '0x');
You can burn or accept a document in Token Registry v5 by passing remarks as an optional argument.
await connectedRegistry.burn(tokenId, remarks);
If no remarks are passed, use '0x':
await connectedRegistry.burn(tokenId, '0x');
When connecting to Title Escrow, the process is similar. You will use the updated contract from Token Registry v5 or TrustVC depending on your installation choice.
[!IMPORTANT] A new
remark
field has been introduced for all contract operations.The
remark
field is optional and can be left empty by providing an empty string"0x"
. Please note that any value in theremark
field is limited to 120 characters, and encryption is recommended.
import { v5Contracts } from '@trustvc/trustvc';
const connectedEscrow = v5Contracts.TitleEscrow__factory.connect(
existingTitleEscrowAddress,
signer,
);
In Token Registry v4, the method to return the title to the issuer was surrender(). With Token Registry v5, this has been updated to returnToIssuer().
await connectedEscrow.returnToIssuer(remarks);
If no remarks are provided, you must pass '0x' as the argument:
await connectedEscrow.returnToIssuer('0x');
Token Registry v5 introduces additional methods for rejecting transfers, if necessary, for wrongful transactions:
[!IMPORTANT] Rejection must occur as the very next action after being appointed as
beneficiary
and/orholder
. If any transactions occur by the new appointee, it will be considered as an implicit acceptance of appointment.There are separate methods to reject a
beneficiary
(rejectTransferBeneficiary
) and aholder
(rejectTransferHolder
). However, if you are both, you must userejectTransferOwners
, as the other two methods will not work in this case.
Reject Transfer of Ownership:
Prevents a transfer of ownership to an incorrect or unauthorized party.
function rejectTransferOwner(bytes calldata _remark) external;
Reject Transfer of Holding:
Prevents a transfer of holding to an incorrect or unauthorized party.
function rejectTransferHolder(bytes calldata _remark) external;
Reject Both Roles (Ownership & Holding):
Prevents both ownership and holding transfers, effectively rejecting the entire transfer process.
function rejectTransferOwners(bytes calldata _remark) external;
For more information on Token Registry and Title Escrow contracts version v5, please visit the readme of TradeTrust Token Registry V5