@bsv/sdk 1.6.26 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/cjs/package.json +1 -1
  2. package/dist/cjs/src/identity/IdentityClient.js +22 -6
  3. package/dist/cjs/src/identity/IdentityClient.js.map +1 -1
  4. package/dist/cjs/src/storage/StorageDownloader.js +24 -10
  5. package/dist/cjs/src/storage/StorageDownloader.js.map +1 -1
  6. package/dist/cjs/src/storage/StorageUploader.js +5 -4
  7. package/dist/cjs/src/storage/StorageUploader.js.map +1 -1
  8. package/dist/cjs/src/storage/StorageUtils.js +11 -3
  9. package/dist/cjs/src/storage/StorageUtils.js.map +1 -1
  10. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  11. package/dist/esm/src/identity/IdentityClient.js +22 -6
  12. package/dist/esm/src/identity/IdentityClient.js.map +1 -1
  13. package/dist/esm/src/storage/StorageDownloader.js +24 -10
  14. package/dist/esm/src/storage/StorageDownloader.js.map +1 -1
  15. package/dist/esm/src/storage/StorageUploader.js +5 -4
  16. package/dist/esm/src/storage/StorageUploader.js.map +1 -1
  17. package/dist/esm/src/storage/StorageUtils.js +11 -3
  18. package/dist/esm/src/storage/StorageUtils.js.map +1 -1
  19. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  20. package/dist/types/src/identity/IdentityClient.d.ts +4 -2
  21. package/dist/types/src/identity/IdentityClient.d.ts.map +1 -1
  22. package/dist/types/src/storage/StorageDownloader.d.ts +1 -1
  23. package/dist/types/src/storage/StorageDownloader.d.ts.map +1 -1
  24. package/dist/types/src/storage/StorageUploader.d.ts +1 -1
  25. package/dist/types/src/storage/StorageUploader.d.ts.map +1 -1
  26. package/dist/types/src/storage/StorageUtils.d.ts +3 -2
  27. package/dist/types/src/storage/StorageUtils.d.ts.map +1 -1
  28. package/dist/types/tsconfig.types.tsbuildinfo +1 -1
  29. package/dist/umd/bundle.js +2 -2
  30. package/dist/umd/bundle.js.map +1 -1
  31. package/docs/reference/identity.md +8 -4
  32. package/docs/reference/storage.md +12 -5
  33. package/docs/tutorials/uhrp-storage.md +6 -6
  34. package/package.json +1 -1
  35. package/src/identity/IdentityClient.ts +32 -6
  36. package/src/identity/__tests/IdentityClient.test.ts +172 -45
  37. package/src/storage/StorageDownloader.ts +28 -12
  38. package/src/storage/StorageUploader.ts +6 -5
  39. package/src/storage/StorageUtils.ts +12 -4
  40. package/src/storage/__tests/StorageDownloader.test.ts +34 -2
  41. package/src/storage/__tests/StorageUploader.test.ts +20 -0
@@ -130,8 +130,8 @@ IdentityClient lets you discover who others are, and let the world know who you
130
130
  export class IdentityClient {
131
131
  constructor(wallet?: WalletInterface, private readonly options = DEFAULT_IDENTITY_CLIENT_OPTIONS, private readonly originator?: OriginatorDomainNameStringUnder250Bytes)
132
132
  async publiclyRevealAttributes(certificate: WalletCertificate, fieldsToReveal: CertificateFieldNameUnder50Bytes[]): Promise<BroadcastResponse | BroadcastFailure>
133
- async resolveByIdentityKey(args: DiscoverByIdentityKeyArgs): Promise<DisplayableIdentity[]>
134
- async resolveByAttributes(args: DiscoverByAttributesArgs): Promise<DisplayableIdentity[]>
133
+ async resolveByIdentityKey(args: DiscoverByIdentityKeyArgs, overrideWithContacts = true): Promise<DisplayableIdentity[]>
134
+ async resolveByAttributes(args: DiscoverByAttributesArgs, overrideWithContacts = true): Promise<DisplayableIdentity[]>
135
135
  public async getContacts(identityKey?: PubKeyHex, forceRefresh = false): Promise<Contact[]>
136
136
  public async saveContact(contact: DisplayableIdentity, metadata?: Record<string, any>): Promise<void>
137
137
  public async removeContact(identityKey: PubKeyHex): Promise<void>
@@ -228,7 +228,7 @@ Argument Details
228
228
  Resolves displayable identity certificates by specific identity attributes, issued by a trusted entity.
229
229
 
230
230
  ```ts
231
- async resolveByAttributes(args: DiscoverByAttributesArgs): Promise<DisplayableIdentity[]>
231
+ async resolveByAttributes(args: DiscoverByAttributesArgs, overrideWithContacts = true): Promise<DisplayableIdentity[]>
232
232
  ```
233
233
  See also: [DiscoverByAttributesArgs](./wallet.md#interface-discoverbyattributesargs), [DisplayableIdentity](./identity.md#interface-displayableidentity)
234
234
 
@@ -240,13 +240,15 @@ Argument Details
240
240
 
241
241
  + **args**
242
242
  + Attributes and optional parameters used to discover certificates.
243
+ + **overrideWithContacts**
244
+ + Whether to override the results with personal contacts if available.
243
245
 
244
246
  #### Method resolveByIdentityKey
245
247
 
246
248
  Resolves displayable identity certificates, issued to a given identity key by a trusted certifier.
247
249
 
248
250
  ```ts
249
- async resolveByIdentityKey(args: DiscoverByIdentityKeyArgs): Promise<DisplayableIdentity[]>
251
+ async resolveByIdentityKey(args: DiscoverByIdentityKeyArgs, overrideWithContacts = true): Promise<DisplayableIdentity[]>
250
252
  ```
251
253
  See also: [DiscoverByIdentityKeyArgs](./wallet.md#interface-discoverbyidentitykeyargs), [DisplayableIdentity](./identity.md#interface-displayableidentity)
252
254
 
@@ -258,6 +260,8 @@ Argument Details
258
260
 
259
261
  + **args**
260
262
  + Arguments for requesting the discovery based on the identity key.
263
+ + **overrideWithContacts**
264
+ + Whether to override the results with personal contacts if available.
261
265
 
262
266
  #### Method saveContact
263
267
 
@@ -22,7 +22,7 @@ Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](
22
22
 
23
23
  ```ts
24
24
  export interface DownloadResult {
25
- data: number[];
25
+ data: Uint8Array;
26
26
  mimeType: string | null;
27
27
  }
28
28
  ```
@@ -85,7 +85,7 @@ Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](
85
85
 
86
86
  ```ts
87
87
  export interface UploadableFile {
88
- data: number[];
88
+ data: Uint8Array | number[];
89
89
  type: string;
90
90
  }
91
91
  ```
@@ -341,13 +341,20 @@ Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](
341
341
  ### Variable: getURLForFile
342
342
 
343
343
  ```ts
344
- getURLForFile = (file: number[]): string => {
345
- const hash = sha256(file);
344
+ getURLForFile = (file: Uint8Array | number[]): string => {
345
+ const data = file instanceof Uint8Array ? file : Uint8Array.from(file);
346
+ const hasher = new Hash.SHA256();
347
+ const chunkSize = 1024 * 1024;
348
+ for (let i = 0; i < data.length; i += chunkSize) {
349
+ const chunk = data.subarray(i, i + chunkSize);
350
+ hasher.update(Array.from(chunk));
351
+ }
352
+ const hash = hasher.digest();
346
353
  return getURLForHash(hash);
347
354
  }
348
355
  ```
349
356
 
350
- See also: [getURLForHash](./storage.md#variable-geturlforhash), [sha256](./primitives.md#variable-sha256)
357
+ See also: [SHA256](./primitives.md#class-sha256), [getURLForHash](./storage.md#variable-geturlforhash)
351
358
 
352
359
  Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Enums](#enums), [Variables](#variables)
353
360
 
@@ -71,7 +71,7 @@ async function basicFileUpload() {
71
71
  // Create sample file
72
72
  const fileData = new TextEncoder().encode('Hello, UHRP storage!')
73
73
  const file = {
74
- data: Array.from(fileData),
74
+ data: fileData,
75
75
  type: 'text/plain'
76
76
  }
77
77
 
@@ -116,7 +116,7 @@ async function basicFileDownload(uhrpUrl: string) {
116
116
 
117
117
  // Convert to string if text file
118
118
  if (result.mimeType?.startsWith('text/')) {
119
- const content = new TextDecoder().decode(new Uint8Array(result.data))
119
+ const content = new TextDecoder().decode(result.data)
120
120
  console.log('Content:', content)
121
121
  }
122
122
 
@@ -172,7 +172,7 @@ class UHRPFileManager {
172
172
  tags: string[] = []
173
173
  ): Promise<FileMetadata> {
174
174
  const file = {
175
- data: Array.from(fileData),
175
+ data: fileData,
176
176
  type: mimeType
177
177
  }
178
178
 
@@ -217,7 +217,7 @@ class UHRPFileManager {
217
217
  console.log('File downloaded:', uhrpUrl)
218
218
 
219
219
  return {
220
- data: new Uint8Array(result.data),
220
+ data: result.data,
221
221
  metadata
222
222
  }
223
223
  } catch (error) {
@@ -371,7 +371,7 @@ class BatchFileOperations {
371
371
  const results = await Promise.allSettled(
372
372
  files.map(async (file) => {
373
373
  const fileObj = {
374
- data: Array.from(file.data),
374
+ data: file.data,
375
375
  type: file.type
376
376
  }
377
377
 
@@ -422,7 +422,7 @@ class BatchFileOperations {
422
422
  return {
423
423
  success: true,
424
424
  url,
425
- data: new Uint8Array(result.value.data)
425
+ data: result.value.data
426
426
  }
427
427
  } else {
428
428
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/sdk",
3
- "version": "1.6.26",
3
+ "version": "1.7.1",
4
4
  "type": "module",
5
5
  "description": "BSV Blockchain Software Development Kit",
6
6
  "main": "dist/cjs/mod.js",
@@ -116,11 +116,21 @@ export class IdentityClient {
116
116
  * Resolves displayable identity certificates, issued to a given identity key by a trusted certifier.
117
117
  *
118
118
  * @param {DiscoverByIdentityKeyArgs} args - Arguments for requesting the discovery based on the identity key.
119
+ * @param {boolean} [overrideWithContacts=true] - Whether to override the results with personal contacts if available.
119
120
  * @returns {Promise<DisplayableIdentity[]>} The promise resolves to displayable identities.
120
121
  */
121
122
  async resolveByIdentityKey (
122
- args: DiscoverByIdentityKeyArgs
123
+ args: DiscoverByIdentityKeyArgs,
124
+ overrideWithContacts = true
123
125
  ): Promise<DisplayableIdentity[]> {
126
+ if (overrideWithContacts) {
127
+ // Override results with personal contacts if available
128
+ const contacts = await this.contactsManager.getContacts(args.identityKey)
129
+ if (contacts.length > 0) {
130
+ return contacts
131
+ }
132
+ }
133
+
124
134
  const { certificates } = await this.wallet.discoverByIdentityKey(args, this.originator)
125
135
  return certificates.map(cert => {
126
136
  return IdentityClient.parseIdentity(cert)
@@ -131,15 +141,31 @@ export class IdentityClient {
131
141
  * Resolves displayable identity certificates by specific identity attributes, issued by a trusted entity.
132
142
  *
133
143
  * @param {DiscoverByAttributesArgs} args - Attributes and optional parameters used to discover certificates.
144
+ * @param {boolean} [overrideWithContacts=true] - Whether to override the results with personal contacts if available.
134
145
  * @returns {Promise<DisplayableIdentity[]>} The promise resolves to displayable identities.
135
146
  */
136
147
  async resolveByAttributes (
137
- args: DiscoverByAttributesArgs
148
+ args: DiscoverByAttributesArgs,
149
+ overrideWithContacts = true
138
150
  ): Promise<DisplayableIdentity[]> {
139
- const { certificates } = await this.wallet.discoverByAttributes(args, this.originator)
140
- return certificates.map(cert => {
141
- return IdentityClient.parseIdentity(cert)
142
- })
151
+ // Run both queries in parallel for better performance
152
+ const [contacts, certificatesResult] = await Promise.all([
153
+ overrideWithContacts ? this.contactsManager.getContacts() : Promise.resolve([]),
154
+ this.wallet.discoverByAttributes(args, this.originator)
155
+ ])
156
+
157
+ // Fast lookup by identityKey
158
+ const contactByKey = new Map<PubKeyHex, Contact>(
159
+ contacts.map(contact => [contact.identityKey, contact] as const)
160
+ )
161
+
162
+ // Guard if certificates might be absent
163
+ const certs = certificatesResult?.certificates ?? []
164
+
165
+ // Parse certificates and substitute with contacts where available
166
+ return certs.map(cert =>
167
+ contactByKey.get(cert.subject) ?? IdentityClient.parseIdentity(cert)
168
+ )
143
169
  }
144
170
 
145
171
  /**
@@ -226,6 +226,43 @@ describe('IdentityClient', () => {
226
226
  badgeClickURL: 'https://socialcert.net'
227
227
  })
228
228
  })
229
+
230
+ it('should prioritize contacts over discovered identities for same identity key', async () => {
231
+ const contact = {
232
+ name: 'Alice Smith (Personal Contact)',
233
+ identityKey: 'alice-identity-key',
234
+ avatarURL: 'alice-avatar.png',
235
+ abbreviatedKey: 'alice-i...',
236
+ badgeIconURL: '',
237
+ badgeLabel: '',
238
+ badgeClickURL: ''
239
+ }
240
+
241
+ const discoveredCertificate = {
242
+ type: KNOWN_IDENTITY_TYPES.xCert,
243
+ subject: 'alice-identity-key',
244
+ decryptedFields: {
245
+ userName: 'Alice Public',
246
+ profilePhoto: 'public-photo.png'
247
+ },
248
+ certifierInfo: {
249
+ name: 'CertifierX',
250
+ iconUrl: 'certifier-icon.png'
251
+ }
252
+ }
253
+
254
+ // Mock ContactsManager to return contact for the specific identity key
255
+ const mockContactsManager = identityClient['contactsManager']
256
+ mockContactsManager.getContacts = jest.fn().mockResolvedValue([contact])
257
+ walletMock.discoverByIdentityKey = jest.fn().mockResolvedValue({ certificates: [discoveredCertificate] })
258
+
259
+ const identities = await identityClient.resolveByIdentityKey({ identityKey: 'alice-identity-key' })
260
+
261
+ expect(identities).toHaveLength(1)
262
+ expect(identities[0].name).toBe('Alice Smith (Personal Contact)') // Contact should be returned, not discovered identity
263
+ // Wallet method should not be called when contact is found
264
+ expect(walletMock.discoverByIdentityKey).not.toHaveBeenCalled()
265
+ })
229
266
  })
230
267
 
231
268
  it('should throw if createAction returns no tx', async () => {
@@ -256,34 +293,124 @@ describe('IdentityClient', () => {
256
293
  })
257
294
 
258
295
  describe('resolveByAttributes', () => {
259
- it('should return parsed identities from discovered certificates', async () => {
296
+ beforeEach(() => {
297
+ // Mock both getContacts and discoverByAttributes
298
+ walletMock.discoverByAttributes = jest.fn().mockResolvedValue({ certificates: [] })
299
+ identityClient.getContacts = jest.fn().mockResolvedValue([])
300
+ })
301
+
302
+ it('should return parsed identities from discovered certificates only', async () => {
260
303
  const dummyCertificate = {
261
304
  type: KNOWN_IDENTITY_TYPES.emailCert,
262
- subject: 'emailSubject1234',
305
+ subject: 'alice-identity-key',
263
306
  decryptedFields: {
264
- email: 'alice@example.com',
265
- profilePhoto: 'ignored' // not used for email type
307
+ identityKey: 'alice-identity-key',
308
+ email: 'alice@example.com'
266
309
  },
267
310
  certifierInfo: {
268
- name: 'EmailCertifier',
269
- iconUrl: 'emailIconUrl'
311
+ name: 'Email Certifier',
312
+ iconUrl: 'certifier-icon.png',
313
+ publicKey: 'certifier-public-key',
314
+ website: 'https://certifier.example.com'
270
315
  }
271
316
  }
272
- // Mock discoverByAttributes to return a certificate list.
317
+
273
318
  walletMock.discoverByAttributes = jest.fn().mockResolvedValue({ certificates: [dummyCertificate] })
274
319
 
275
320
  const identities = await identityClient.resolveByAttributes({ attributes: { email: 'alice@example.com' } })
276
- expect(walletMock.discoverByAttributes).toHaveBeenCalledWith({ attributes: { email: 'alice@example.com' } }, undefined)
277
321
  expect(identities).toHaveLength(1)
278
- expect(identities[0]).toEqual({
279
- name: 'alice@example.com',
280
- avatarURL: 'XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu',
281
- abbreviatedKey: 'emailSubje...',
282
- identityKey: 'emailSubject1234',
283
- badgeLabel: 'Email certified by EmailCertifier',
284
- badgeIconURL: 'emailIconUrl',
285
- badgeClickURL: 'https://socialcert.net'
286
- })
322
+ expect(identities[0].name).toBe('alice@example.com')
323
+ })
324
+
325
+ it('should prioritize contacts over discovered identities for same identity key', async () => {
326
+ const contact = {
327
+ name: 'Alice Smith (Personal)',
328
+ identityKey: 'alice-identity-key',
329
+ avatarURL: 'alice-avatar.png',
330
+ abbreviatedKey: 'alice-i...',
331
+ badgeIconURL: '',
332
+ badgeLabel: '',
333
+ badgeClickURL: ''
334
+ }
335
+
336
+ const discoveredCertificate = {
337
+ type: KNOWN_IDENTITY_TYPES.emailCert,
338
+ subject: 'alice-identity-key',
339
+ decryptedFields: {
340
+ email: 'alice@example.com'
341
+ },
342
+ certifierInfo: {
343
+ name: 'Email Certifier',
344
+ iconUrl: 'certifier-icon.png',
345
+ publicKey: 'certifier-public-key',
346
+ website: 'https://certifier.example.com'
347
+ }
348
+ }
349
+
350
+ // Mock the ContactsManager's getContacts method instead of the IdentityClient method
351
+ const mockContactsManager = identityClient['contactsManager']
352
+ mockContactsManager.getContacts = jest.fn().mockResolvedValue([contact])
353
+ walletMock.discoverByAttributes = jest.fn().mockResolvedValue({ certificates: [discoveredCertificate] })
354
+
355
+ const identities = await identityClient.resolveByAttributes({ attributes: { name: 'Alice' } })
356
+
357
+ expect(identities).toHaveLength(1)
358
+ expect(identities[0].name).toBe('Alice Smith (Personal)') // Contact should be returned, not discovered identity
359
+ })
360
+
361
+ it('should return empty array for empty search terms', async () => {
362
+ const contacts = [
363
+ {
364
+ name: 'Alice Smith',
365
+ identityKey: 'alice-key',
366
+ avatarURL: '', abbreviatedKey: 'alice-i...', badgeIconURL: '', badgeLabel: '', badgeClickURL: ''
367
+ }
368
+ ]
369
+
370
+ const mockContactsManager = identityClient['contactsManager']
371
+ mockContactsManager.getContacts = jest.fn().mockResolvedValue(contacts)
372
+
373
+ const identities = await identityClient.resolveByAttributes({ attributes: { name: '', email: ' ' } })
374
+
375
+ expect(identities).toHaveLength(0)
376
+ })
377
+
378
+ it('should return only discovered identities when overrideWithContacts is false', async () => {
379
+ const contacts = [
380
+ {
381
+ name: 'Alice Smith (Personal)',
382
+ identityKey: 'alice-key',
383
+ avatarURL: '', abbreviatedKey: 'alice-i...', badgeIconURL: '', badgeLabel: '', badgeClickURL: ''
384
+ }
385
+ ]
386
+
387
+ const discoveredCertificate = {
388
+ type: KNOWN_IDENTITY_TYPES.emailCert,
389
+ subject: 'alice-key', // Same key as contact but should not be filtered out
390
+ decryptedFields: {
391
+ email: 'alice@example.com'
392
+ },
393
+ certifierInfo: {
394
+ name: 'Email Certifier',
395
+ iconUrl: 'certifier-icon.png',
396
+ publicKey: 'certifier-public-key',
397
+ website: 'https://certifier.example.com'
398
+ }
399
+ }
400
+
401
+ const mockContactsManager = identityClient['contactsManager']
402
+ mockContactsManager.getContacts = jest.fn().mockResolvedValue(contacts)
403
+ walletMock.discoverByAttributes = jest.fn().mockResolvedValue({ certificates: [discoveredCertificate] })
404
+
405
+ // With overrideWithContacts = false, should ignore contacts entirely
406
+ const identities = await identityClient.resolveByAttributes(
407
+ { attributes: { name: 'Alice' } },
408
+ false
409
+ )
410
+
411
+ expect(identities).toHaveLength(1)
412
+ expect(identities[0].name).toBe('alice@example.com') // Should be discovered identity, not contact
413
+ expect(mockContactsManager.getContacts).not.toHaveBeenCalled() // Should not fetch contacts
287
414
  })
288
415
  })
289
416
 
@@ -434,14 +561,14 @@ describe('IdentityClient', () => {
434
561
  customInstructions: JSON.stringify({ keyID: 'existingKeyID' })
435
562
  }
436
563
 
437
- ; (walletMock.listOutputs as jest.Mock).mockResolvedValueOnce({
438
- outputs: [existingOutput],
439
- BEEF: [1, 2, 3]
440
- })
564
+ ; (walletMock.listOutputs as jest.Mock).mockResolvedValueOnce({
565
+ outputs: [existingOutput],
566
+ BEEF: [1, 2, 3]
567
+ })
441
568
 
442
- ; (walletMock.decrypt as jest.Mock).mockResolvedValue({
443
- plaintext: new TextEncoder().encode(JSON.stringify(mockContact))
444
- })
569
+ ; (walletMock.decrypt as jest.Mock).mockResolvedValue({
570
+ plaintext: new TextEncoder().encode(JSON.stringify(mockContact))
571
+ })
445
572
 
446
573
  const updatedContact = { ...mockContact, name: 'Alice Updated' }
447
574
  await identityClient.saveContact(updatedContact)
@@ -489,14 +616,14 @@ describe('IdentityClient', () => {
489
616
  customInstructions: JSON.stringify({ keyID: 'mockKeyID' })
490
617
  }
491
618
 
492
- ; (walletMock.listOutputs as jest.Mock).mockResolvedValue({
493
- outputs: [mockOutput],
494
- BEEF: [1, 2, 3]
495
- })
619
+ ; (walletMock.listOutputs as jest.Mock).mockResolvedValue({
620
+ outputs: [mockOutput],
621
+ BEEF: [1, 2, 3]
622
+ })
496
623
 
497
- ; (walletMock.decrypt as jest.Mock).mockResolvedValue({
498
- plaintext: new TextEncoder().encode(JSON.stringify(mockContact))
499
- })
624
+ ; (walletMock.decrypt as jest.Mock).mockResolvedValue({
625
+ plaintext: new TextEncoder().encode(JSON.stringify(mockContact))
626
+ })
500
627
 
501
628
  const result = await identityClient.getContacts()
502
629
 
@@ -523,11 +650,11 @@ describe('IdentityClient', () => {
523
650
  })
524
651
  await identityClient.saveContact(mockContact)
525
652
 
526
- // Mock empty result for force refresh
527
- ; (walletMock.listOutputs as jest.Mock).mockResolvedValue({
528
- outputs: [],
529
- BEEF: []
530
- })
653
+ // Mock empty result for force refresh
654
+ ; (walletMock.listOutputs as jest.Mock).mockResolvedValue({
655
+ outputs: [],
656
+ BEEF: []
657
+ })
531
658
 
532
659
  const result = await identityClient.getContacts(undefined, true)
533
660
 
@@ -542,7 +669,7 @@ describe('IdentityClient', () => {
542
669
  BEEF: []
543
670
  })
544
671
  await identityClient.saveContact(mockContact)
545
-
672
+
546
673
  const otherContact = { ...mockContact, identityKey: 'different-key', name: 'Bob' }
547
674
  await identityClient.saveContact(otherContact)
548
675
 
@@ -575,7 +702,7 @@ describe('IdentityClient', () => {
575
702
  BEEF: []
576
703
  })
577
704
  await identityClient.saveContact(mockContact)
578
-
705
+
579
706
  const otherContact = { ...mockContact, identityKey: 'other-key', name: 'Bob' }
580
707
  await identityClient.saveContact(otherContact)
581
708
 
@@ -585,14 +712,14 @@ describe('IdentityClient', () => {
585
712
  customInstructions: JSON.stringify({ keyID: 'mockKeyID' })
586
713
  }
587
714
 
588
- ; (walletMock.listOutputs as jest.Mock).mockResolvedValue({
589
- outputs: [mockOutput],
590
- BEEF: [1, 2, 3]
591
- })
715
+ ; (walletMock.listOutputs as jest.Mock).mockResolvedValue({
716
+ outputs: [mockOutput],
717
+ BEEF: [1, 2, 3]
718
+ })
592
719
 
593
- ; (walletMock.decrypt as jest.Mock).mockResolvedValue({
594
- plaintext: new TextEncoder().encode(JSON.stringify(mockContact))
595
- })
720
+ ; (walletMock.decrypt as jest.Mock).mockResolvedValue({
721
+ plaintext: new TextEncoder().encode(JSON.stringify(mockContact))
722
+ })
596
723
 
597
724
  await identityClient.removeContact(mockContact.identityKey)
598
725
 
@@ -9,7 +9,7 @@ export interface DownloaderConfig {
9
9
  }
10
10
 
11
11
  export interface DownloadResult {
12
- data: number[]
12
+ data: Uint8Array
13
13
  mimeType: string | null
14
14
  }
15
15
 
@@ -58,6 +58,7 @@ export class StorageDownloader {
58
58
  throw new Error('Invalid parameter UHRP url')
59
59
  }
60
60
  const hash = StorageUtils.getHashFromURL(uhrpUrl)
61
+ const expected = Utils.toHex(hash)
61
62
  const downloadURLs = await this.resolve(uhrpUrl)
62
63
 
63
64
  if (!Array.isArray(downloadURLs) || downloadURLs.length === 0) {
@@ -70,22 +71,37 @@ export class StorageDownloader {
70
71
  const result = await fetch(downloadURLs[i], { method: 'GET' })
71
72
 
72
73
  // If the request fails, continue to the next url
73
- if (!result.ok || result.status >= 400) {
74
+ if (!result.ok || result.status >= 400 || result.body == null) {
74
75
  continue
75
76
  }
76
- const body = await result.arrayBuffer()
77
-
78
- // The body is loaded into a number array
79
- const content: number[] = [...new Uint8Array(body)]
80
- const contentHash = Hash.sha256(content)
81
- for (let i = 0; i < contentHash.length; ++i) {
82
- if (contentHash[i] !== hash[i]) {
83
- throw new Error('Value of content does not match hash of the url given')
84
- }
77
+
78
+ const reader = result.body.getReader()
79
+ const hashStream = new Hash.SHA256()
80
+ const chunks: Uint8Array[] = []
81
+ let totalLength = 0
82
+
83
+ while (true) {
84
+ const { done, value } = await reader.read()
85
+ if (done) break
86
+ hashStream.update(Array.from(value))
87
+ chunks.push(value)
88
+ totalLength += value.length
89
+ }
90
+
91
+ const digest = Utils.toHex(hashStream.digest())
92
+ if (digest !== expected) {
93
+ throw new Error('Data integrity error: value of content does not match hash of the url given')
94
+ }
95
+
96
+ const data = new Uint8Array(totalLength)
97
+ let offset = 0
98
+ for (const chunk of chunks) {
99
+ data.set(chunk, offset)
100
+ offset += chunk.length
85
101
  }
86
102
 
87
103
  return {
88
- data: content,
104
+ data,
89
105
  mimeType: result.headers.get('Content-Type')
90
106
  }
91
107
  } catch (error) {
@@ -8,7 +8,7 @@ export interface UploaderConfig {
8
8
  }
9
9
 
10
10
  export interface UploadableFile {
11
- data: number[]
11
+ data: Uint8Array | number[]
12
12
  type: string
13
13
  }
14
14
 
@@ -108,7 +108,7 @@ export class StorageUploader {
108
108
  file: UploadableFile,
109
109
  requiredHeaders: Record<string, string>
110
110
  ): Promise<UploadFileResult> {
111
- const body = Uint8Array.from(file.data)
111
+ const body = file.data instanceof Uint8Array ? file.data : Uint8Array.from(file.data)
112
112
 
113
113
  const response = await fetch(uploadURL, {
114
114
  method: 'PUT',
@@ -122,7 +122,7 @@ export class StorageUploader {
122
122
  throw new Error(`File upload failed: HTTP ${response.status}`)
123
123
  }
124
124
 
125
- const uhrpURL = await StorageUtils.getURLForFile(file.data)
125
+ const uhrpURL = StorageUtils.getURLForFile(body)
126
126
  return {
127
127
  published: true,
128
128
  uhrpURL
@@ -148,10 +148,11 @@ export class StorageUploader {
148
148
  retentionPeriod: number
149
149
  }): Promise<UploadFileResult> {
150
150
  const { file, retentionPeriod } = params
151
- const fileSize = file.data.length
151
+ const data = file.data instanceof Uint8Array ? file.data : Uint8Array.from(file.data)
152
+ const fileSize = data.byteLength
152
153
 
153
154
  const { uploadURL, requiredHeaders } = await this.getUploadInfo(fileSize, retentionPeriod)
154
- return await this.uploadFile(uploadURL, file, requiredHeaders)
155
+ return await this.uploadFile(uploadURL, { data, type: file.type }, requiredHeaders)
155
156
  }
156
157
 
157
158
  /**
@@ -1,5 +1,5 @@
1
- import { sha256 } from '../primitives/Hash.js'
2
1
  import { toHex, fromBase58Check, toBase58Check, toArray } from '../primitives/utils.js'
2
+ import { Hash } from '../primitives/index.js'
3
3
 
4
4
  /**
5
5
  * Takes a UHRP URL and removes any prefixes.
@@ -26,11 +26,19 @@ export const getURLForHash = (hash: number[]): string => {
26
26
 
27
27
  /**
28
28
  * Generates a UHRP URL for a given file.
29
- * @param {number[] | string} file - File content as number array or string.
29
+ * Uses a streaming hash to avoid excessive memory usage with large files.
30
+ * @param {Uint8Array | number[]} file - File content as a typed array or number array.
30
31
  * @returns {string} - Base58Check encoded URL.
31
32
  */
32
- export const getURLForFile = (file: number[]): string => {
33
- const hash = sha256(file)
33
+ export const getURLForFile = (file: Uint8Array | number[]): string => {
34
+ const data = file instanceof Uint8Array ? file : Uint8Array.from(file)
35
+ const hasher = new Hash.SHA256()
36
+ const chunkSize = 1024 * 1024
37
+ for (let i = 0; i < data.length; i += chunkSize) {
38
+ const chunk = data.subarray(i, i + chunkSize)
39
+ hasher.update(Array.from(chunk))
40
+ }
41
+ const hash = hasher.digest()
34
42
  return getURLForHash(hash)
35
43
  }
36
44