-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathbitswap.ts
More file actions
80 lines (65 loc) · 2.51 KB
/
bitswap.ts
File metadata and controls
80 lines (65 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { createBitswap } from 'ipfs-bitswap'
import type { BlockAnnounceOptions, BlockBroker, BlockRetrievalOptions } from '@helia/interface/blocks'
import type { Libp2p, Startable } from '@libp2p/interface'
import type { Blockstore } from 'interface-blockstore'
import type { Bitswap, BitswapNotifyProgressEvents, BitswapOptions, BitswapWantBlockProgressEvents } from 'ipfs-bitswap'
import type { CID } from 'multiformats/cid'
import type { MultihashHasher } from 'multiformats/hashes/interface'
interface BitswapComponents {
libp2p: Libp2p
blockstore: Blockstore
hashers: Record<string, MultihashHasher>
}
export interface BitswapInit extends BitswapOptions {
}
class BitswapBlockBroker implements BlockBroker<BitswapWantBlockProgressEvents, BitswapNotifyProgressEvents>, Startable {
private readonly bitswap: Bitswap
private started: boolean
constructor (components: BitswapComponents, init: BitswapInit = {}) {
const { libp2p, blockstore, hashers } = components
this.bitswap = createBitswap(libp2p, blockstore, {
hashLoader: {
getHasher: async (codecOrName: string | number): Promise<MultihashHasher<number>> => {
let hasher: MultihashHasher | undefined
if (typeof codecOrName === 'string') {
hasher = Object.values(hashers).find(hasher => {
return hasher.name === codecOrName
})
} else {
hasher = hashers[codecOrName]
}
if (hasher != null) {
return hasher
}
throw new Error(`Could not load hasher for code/name "${codecOrName}"`)
}
},
...init
})
this.started = false
}
isStarted (): boolean {
return this.started
}
async start (): Promise<void> {
await this.bitswap.start()
this.started = true
}
async stop (): Promise<void> {
await this.bitswap.stop()
this.started = false
}
async announce (cid: CID, block: Uint8Array, options?: BlockAnnounceOptions<BitswapNotifyProgressEvents>): Promise<void> {
this.bitswap.notify(cid, block, options)
}
async retrieve (cid: CID, options: BlockRetrievalOptions<BitswapWantBlockProgressEvents> = {}): Promise<Uint8Array> {
return this.bitswap.want(cid, options)
}
}
/**
* A helper factory for users who want to override Helia `blockBrokers` but
* still want to use the default `BitswapBlockBroker`.
*/
export function bitswap (init: BitswapInit = {}): (components: BitswapComponents) => BlockBroker {
return (components) => new BitswapBlockBroker(components, init)
}