Skip to content

Commit 3a20c92

Browse files
fix: Consolidate utility functions and improve code clarity
- Moved base58Encode and encodeVarint functions to utils.ts for better organization and reuse. - Updated imports in create.ts and resolve.ts to reflect the new utility function locations. - Changed variable declarations in resolveNumAlgo2 for consistency and clarity.
1 parent d372d63 commit 3a20c92

File tree

3 files changed

+66
-63
lines changed

3 files changed

+66
-63
lines changed

src/lib/create.ts

Lines changed: 1 addition & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Numalgo2Prefixes, VARIANT_4_PREFIX, JSON_MULTICODEC_PREFIX, SHA256_MULTIHASH_PREFIX, SHA256_HASH_LENGTH, MULTIBASE_BASE58BTC_PREFIX } from "./constants.js";
22
import type { IDIDDocumentServiceDescriptor, IDIDDocumentVerificationMethod } from "./interfaces.js"
3-
import { encodeService } from "./utils.js";
3+
import { base58Encode, encodeService, encodeVarint } from "./utils.js";
44
import { validateAuthentication, validateEncryption } from "./validators.js";
55
import { createHash } from 'crypto';
66

@@ -123,35 +123,3 @@ export const createNumAlgo4 = async (
123123
// Step 3: Construct the DID
124124
return `did:peer:${VARIANT_4_PREFIX}${hashString}:${encodedDocument}`;
125125
}
126-
127-
// Helper function to encode varint
128-
function encodeVarint(value: number): Uint8Array {
129-
const bytes: number[] = [];
130-
while (value >= 0x80) {
131-
bytes.push((value & 0xFF) | 0x80);
132-
value >>>= 7;
133-
}
134-
bytes.push(value & 0xFF);
135-
return new Uint8Array(bytes);
136-
}
137-
138-
// Helper function for base58 encoding
139-
function base58Encode(bytes: Uint8Array): string {
140-
const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
141-
let num = BigInt('0x' + Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join(''));
142-
143-
if (num === 0n) return alphabet[0];
144-
145-
let result = '';
146-
while (num > 0n) {
147-
result = alphabet[Number(num % 58n)] + result;
148-
num = num / 58n;
149-
}
150-
151-
// Add leading zeros
152-
for (let i = 0; i < bytes.length && bytes[i] === 0; i++) {
153-
result = alphabet[0] + result;
154-
}
155-
156-
return result;
157-
}

src/lib/resolve.ts

Lines changed: 6 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Numalgo2Prefixes, VARIANT_4_PREFIX, JSON_MULTICODEC_PREFIX, SHA256_MULTIHASH_PREFIX, SHA256_HASH_LENGTH, MULTIBASE_BASE58BTC_PREFIX } from "./constants.js";
22
import type { IDIDDocument, IDIDDocumentServiceDescriptor, IDIDDocumentVerificationMethod, IDIDRepository } from "./interfaces.js";
3-
import { assert, createDIDDocument, decodeService, isPeerDID } from "./utils.js";
3+
import { assert, base58Encode, createDIDDocument, decodeService, isPeerDID } from "./utils.js";
44
import { createHash } from 'crypto';
55

66
export const resolve = async (did: string, repository?: IDIDRepository): Promise<IDIDDocument> => {
@@ -35,11 +35,11 @@ export const resolveNumAlgo1 = async (did: string): Promise<IDIDDocument> => {
3535
}
3636

3737
export const resolveNumAlgo2 = async (did: string): Promise<IDIDDocument> => {
38-
let authKeys: IDIDDocumentVerificationMethod[] = [];
39-
let encKeys: IDIDDocumentVerificationMethod[] = [];
40-
let services: IDIDDocumentServiceDescriptor[] = [];
41-
let keys = did.split('.')
42-
let serviceMetadata = {index: 0};
38+
const authKeys: IDIDDocumentVerificationMethod[] = [];
39+
const encKeys: IDIDDocumentVerificationMethod[] = [];
40+
const services: IDIDDocumentServiceDescriptor[] = [];
41+
const keys = did.split('.')
42+
const serviceMetadata = {index: 0};
4343
let keyIndex = 1;
4444
delete keys[0];
4545
keys.forEach(k => {
@@ -258,24 +258,3 @@ function decodeVarint(bytes: Uint8Array): { value: number; bytes: Uint8Array } {
258258
bytes: bytes.slice(index)
259259
};
260260
}
261-
262-
// Helper function for base58 encoding (reused from create.ts)
263-
function base58Encode(bytes: Uint8Array): string {
264-
const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
265-
let num = BigInt('0x' + Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join(''));
266-
267-
if (num === 0n) return alphabet[0];
268-
269-
let result = '';
270-
while (num > 0n) {
271-
result = alphabet[Number(num % 58n)] + result;
272-
num = num / 58n;
273-
}
274-
275-
// Add leading zeros
276-
for (let i = 0; i < bytes.length && bytes[i] === 0; i++) {
277-
result = alphabet[0] + result;
278-
}
279-
280-
return result;
281-
}

src/lib/utils.ts

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { Numalgo2Prefixes, ServiceReplacements } from "./constants.js";
33
import type { IDIDDocumentServiceDescriptor, IDIDDocumentVerificationMethod } from "./interfaces.js";
44

55
export const assert = (exp: boolean, message: string) => {
6-
if(!Boolean(exp)) throw new Error(message || 'unknown assertion error');
6+
if(!exp) throw new Error(message || 'unknown assertion error');
77
}
88

99
export const base64 = {
@@ -92,7 +92,7 @@ export const decodeService = (did: string, service: string, metadata: Record<str
9292
export const isPeerDID = (did: string) => {
9393
// Updated regex to support variant 4 long form DIDs
9494
// Original patterns for variants 0, 1, 2
95-
const variant012Pattern = '^did:peer:(([01](z)([1-9a-km-zA-HJ-NP-Z]*))|(2((\.[AEVID](z)([1-9a-km-zA-HJ-NP-Z]*))+(\.(S)[0-9a-zA-Z=]*)*)))$';
95+
const variant012Pattern = '^did:peer:(([01](z)([1-9a-km-zA-HJ-NP-Z]*))|(2((.[AEVID](z)([1-9a-km-zA-HJ-NP-Z]*))+(.(S)[0-9a-zA-Z=]*)*)))$';
9696

9797
// Variant 4 pattern - can be short form (did:peer:4z...) or long form (did:peer:4z...:z...)
9898
const variant4Pattern = '^did:peer:4z[1-9a-km-zA-HJ-NP-Z]*(:[a-zA-Z0-9]+)*$';
@@ -120,7 +120,7 @@ export const createDIDDocument = (
120120
controller: k.controller,
121121
publicKeyMultibase: k.publicKeyMultibase
122122
}))
123-
let doc: any = {
123+
const doc: any = {
124124
"id": did,
125125
assertionMethod: auth,
126126
authentication: auth,
@@ -141,3 +141,59 @@ export const createDIDDocument = (
141141
}
142142
return {"@context": contexts, ...doc};
143143
}
144+
145+
// Helper function to encode varint
146+
export const encodeVarint = (value: number): Uint8Array => {
147+
const bytes: number[] = [];
148+
while (value >= 0x80) {
149+
bytes.push((value & 0xFF) | 0x80);
150+
value >>>= 7;
151+
}
152+
bytes.push(value & 0xFF);
153+
return new Uint8Array(bytes);
154+
}
155+
156+
// Helper to decode unsigned varints (LEB128)
157+
export const decodeVarint = (
158+
bytes: Uint8Array
159+
): { value: number; bytes: Uint8Array } => {
160+
let value = 0;
161+
let shift = 0;
162+
let index = 0;
163+
164+
while (index < bytes.length) {
165+
const byte = bytes[index++];
166+
value |= (byte & 0x7F) << shift;
167+
shift += 7;
168+
169+
// If the continuation bit is not set, we're done
170+
if ((byte & 0x80) === 0) {
171+
break;
172+
}
173+
}
174+
175+
return {
176+
value,
177+
bytes: bytes.slice(index)
178+
};
179+
};
180+
181+
export const base58Encode = (bytes: Uint8Array): string => {
182+
const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
183+
let num = BigInt('0x' + Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join(''));
184+
185+
if (num === 0n) return alphabet[0];
186+
187+
let result = '';
188+
while (num > 0n) {
189+
result = alphabet[Number(num % 58n)] + result;
190+
num = num / 58n;
191+
}
192+
193+
// Add leading zeros
194+
for (let i = 0; i < bytes.length && bytes[i] === 0; i++) {
195+
result = alphabet[0] + result;
196+
}
197+
198+
return result;
199+
}

0 commit comments

Comments
 (0)