@bsv/sdk 1.6.26 → 1.7.0

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 (32) hide show
  1. package/dist/cjs/package.json +1 -1
  2. package/dist/cjs/src/storage/StorageDownloader.js +24 -10
  3. package/dist/cjs/src/storage/StorageDownloader.js.map +1 -1
  4. package/dist/cjs/src/storage/StorageUploader.js +5 -4
  5. package/dist/cjs/src/storage/StorageUploader.js.map +1 -1
  6. package/dist/cjs/src/storage/StorageUtils.js +11 -3
  7. package/dist/cjs/src/storage/StorageUtils.js.map +1 -1
  8. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  9. package/dist/esm/src/storage/StorageDownloader.js +24 -10
  10. package/dist/esm/src/storage/StorageDownloader.js.map +1 -1
  11. package/dist/esm/src/storage/StorageUploader.js +5 -4
  12. package/dist/esm/src/storage/StorageUploader.js.map +1 -1
  13. package/dist/esm/src/storage/StorageUtils.js +11 -3
  14. package/dist/esm/src/storage/StorageUtils.js.map +1 -1
  15. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  16. package/dist/types/src/storage/StorageDownloader.d.ts +1 -1
  17. package/dist/types/src/storage/StorageDownloader.d.ts.map +1 -1
  18. package/dist/types/src/storage/StorageUploader.d.ts +1 -1
  19. package/dist/types/src/storage/StorageUploader.d.ts.map +1 -1
  20. package/dist/types/src/storage/StorageUtils.d.ts +3 -2
  21. package/dist/types/src/storage/StorageUtils.d.ts.map +1 -1
  22. package/dist/types/tsconfig.types.tsbuildinfo +1 -1
  23. package/dist/umd/bundle.js +2 -2
  24. package/dist/umd/bundle.js.map +1 -1
  25. package/docs/reference/storage.md +12 -5
  26. package/docs/tutorials/uhrp-storage.md +6 -6
  27. package/package.json +1 -1
  28. package/src/storage/StorageDownloader.ts +28 -12
  29. package/src/storage/StorageUploader.ts +6 -5
  30. package/src/storage/StorageUtils.ts +12 -4
  31. package/src/storage/__tests/StorageDownloader.test.ts +34 -2
  32. package/src/storage/__tests/StorageUploader.test.ts +20 -0
@@ -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: [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.0",
4
4
  "type": "module",
5
5
  "description": "BSV Blockchain Software Development Kit",
6
6
  "main": "dist/cjs/mod.js",
@@ -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
 
@@ -3,8 +3,9 @@ import { StorageUtils } from '../index.js'
3
3
  import { LookupResolver } from '../../overlay-tools/index.js'
4
4
  import Transaction from '../../transaction/Transaction.js'
5
5
  import PushDrop from '../../script/templates/PushDrop.js'
6
- import { Hash, PublicKey } from '../../primitives/index.js'
6
+ import { PublicKey } from '../../primitives/index.js'
7
7
  import { Utils } from '../../primitives/index.js'
8
+ import { ReadableStream } from 'stream/web'
8
9
 
9
10
  beforeEach(() => {
10
11
  jest.restoreAllMocks()
@@ -125,7 +126,7 @@ describe('StorageDownloader', () => {
125
126
  const result = await downloader.download('validUrl')
126
127
  expect(fetchSpy).toHaveBeenCalledTimes(2)
127
128
  expect(result).toEqual({
128
- data: new Array(32).fill(0),
129
+ data: new Uint8Array(32).fill(0),
129
130
  mimeType: 'application/test'
130
131
  })
131
132
  })
@@ -200,5 +201,36 @@ describe('StorageDownloader', () => {
200
201
  .resolves
201
202
  .toEqual(["", ""])
202
203
  })
204
+
205
+ it.skip('downloads and verifies large streamed content', async () => {
206
+ const size = 5 * 1024 * 1024
207
+ const data = new Uint8Array(size)
208
+ for (let i = 0; i < size; i++) data[i] = i % 256
209
+ const uhrpUrl = StorageUtils.getURLForFile(data)
210
+
211
+ jest.spyOn(downloader, 'resolve').mockResolvedValue(['http://large-file'])
212
+
213
+ const chunkSize = 64 * 1024
214
+ const stream = new ReadableStream<Uint8Array>({
215
+ start (controller) {
216
+ for (let offset = 0; offset < data.length; offset += chunkSize) {
217
+ controller.enqueue(data.subarray(offset, offset + chunkSize))
218
+ }
219
+ controller.close()
220
+ }
221
+ })
222
+
223
+ jest.spyOn(global, 'fetch').mockResolvedValue(
224
+ new Response(stream as any, {
225
+ status: 200,
226
+ headers: { 'Content-Type': 'application/octet-stream' }
227
+ })
228
+ )
229
+
230
+ const result = await downloader.download(uhrpUrl)
231
+ expect(result.mimeType).toBe('application/octet-stream')
232
+ expect(result.data.length).toBe(size)
233
+ expect(result.data).toEqual(data)
234
+ })
203
235
  })
204
236
  })
@@ -1,6 +1,7 @@
1
1
  import { StorageUploader } from '../StorageUploader.js'
2
2
  import * as StorageUtils from '../StorageUtils.js'
3
3
  import WalletClient from '../../wallet/WalletClient.js'
4
+ import { createHash } from 'crypto'
4
5
 
5
6
  /**
6
7
  * A helper for converting a string to a number[] of UTF-8 bytes
@@ -66,6 +67,25 @@ describe('StorageUploader Tests', () => {
66
67
  expect(firstFour).toHaveLength(8)
67
68
  })
68
69
 
70
+ it('should handle large file uploads efficiently', async () => {
71
+ const size = 5 * 1024 * 1024
72
+ const data = new Uint8Array(size)
73
+ for (let i = 0; i < size; i++) data[i] = i % 256
74
+
75
+ jest.spyOn(uploader as any, 'getUploadInfo').mockResolvedValue({
76
+ uploadURL: 'https://example-upload.com/put'
77
+ })
78
+
79
+ const result = await uploader.publishFile({
80
+ file: { data, type: 'application/octet-stream' },
81
+ retentionPeriod: 7
82
+ })
83
+
84
+ const expectedHash = createHash('sha256').update(data).digest()
85
+ const urlHash = StorageUtils.getHashFromURL(result.uhrpURL)
86
+ expect(Buffer.from(urlHash)).toEqual(expectedHash)
87
+ })
88
+
69
89
  it('should throw if the upload fails with HTTP 500', async () => {
70
90
  // Force the direct upload (global fetch) to fail
71
91
  globalFetchSpy.mockResolvedValueOnce(new Response(null, { status: 500 }))