Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor adaptation of VerifyCidTransform implementation #3178

Merged
merged 1 commit into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fast-moons-marry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@atproto/common": patch
---

Minor adaptation of VerifyCidTransform
50 changes: 24 additions & 26 deletions packages/common/src/ipld.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import crypto from 'crypto'
import { Transform, TransformCallback } from 'stream'
import { createHash } from 'node:crypto'
import { Transform } from 'node:stream'
import { check, schema } from '@atproto/common-web'
import { CID } from 'multiformats/cid'
import * as Block from 'multiformats/block'
Expand Down Expand Up @@ -63,34 +63,32 @@ export const sha256RawToCid = (hash: Uint8Array): CID => {
}

export class VerifyCidTransform extends Transform {
hasher = crypto.createHash('sha256')
constructor(public cid: CID) {
super()
}

_transform(chunk: Uint8Array, _enc: BufferEncoding, cb: TransformCallback) {
this.hasher.update(chunk)
cb(null, chunk)
}

_flush(cb: TransformCallback) {
try {
const cid = sha256RawToCid(this.hasher.digest())
if (this.cid.equals(cid)) {
return cb()
} else {
return cb(new VerifyCidError(this.cid, cid))
}
} catch (_err) {
const err =
_err instanceof Error
? _err
: new Error('Unexpected error', { cause: _err })
return cb(err)
}
const hasher = createHash('sha256')
super({
transform(chunk, encoding, callback) {
hasher.update(chunk)
callback(null, chunk)
},
flush(callback) {
try {
const actual = sha256RawToCid(hasher.digest())
if (actual.equals(cid)) {
return callback()
} else {
return callback(new VerifyCidError(cid, actual))
}
} catch (err) {
return callback(asError(err))
}
},
})
}
}

const asError = (err: unknown): Error =>
err instanceof Error ? err : new Error('Unexpected error', { cause: err })

export class VerifyCidError extends Error {
constructor(
public expected: CID,
Expand Down
Loading