-
Notifications
You must be signed in to change notification settings - Fork 8
/
inclusion-proofs.ts
64 lines (58 loc) · 2.54 KB
/
inclusion-proofs.ts
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
import assert from 'assert'
import util from 'util'
import { Database } from './database.js'
import { OpLog } from './log.js'
export interface VerifyInclusionProofOpts {
database?: Database
oplog?: OpLog
}
export async function verifyInclusionProof (proof: object|BlockInclusionProof, opts?: VerifyInclusionProofOpts) {
const p: BlockInclusionProof = proof instanceof BlockInclusionProof ? proof : BlockInclusionProof.fromJSON(proof)
let oplog: OpLog|undefined
if (opts?.oplog && opts.oplog.pubkey.equals(p.logPubkey)) {
oplog = opts.oplog
} else if (opts?.database && opts.database.isOplogParticipant(p.logPubkey)) {
oplog = opts.database.getParticipant(p.logPubkey) as OpLog
} else {
throw new Error('TODO: fetch oplog from network')
}
await oplog.verifyBlockInclusionProof(p)
}
export class BlockInclusionProof {
constructor (public logPubkey: Buffer, public blockSeq: number, public rootHashAtBlock: Buffer, public rootHashSignature: Buffer) {
}
[util.inspect.custom] (depth: number, opts: {indentationLvl: number, stylize: Function}) {
let indent = ''
if (opts.indentationLvl) {
while (indent.length < opts.indentationLvl) indent += ' '
}
return this.constructor.name + '(\n' +
indent + ' logPubkey: ' + opts.stylize(this.logPubkey.toString('hex'), 'string') + '\n' +
indent + ' blockSeq: ' + opts.stylize(this.blockSeq, 'number') + '\n' +
indent + ' rootHashAtBlock: ' + opts.stylize(this.rootHashAtBlock.toString('hex'), 'string') + '\n' +
indent + ' rootHashSignature: ' + opts.stylize(this.rootHashSignature.toString('hex'), 'string') + '\n' +
indent + ')'
}
toJSON () {
return {
vitraBlockInclusionProof: 1,
logPubkey: this.logPubkey.toString('hex'),
blockSeq: this.blockSeq,
rootHashAtBlock: this.rootHashAtBlock.toString('hex'),
rootHashSignature: this.rootHashSignature.toString('hex')
}
}
static fromJSON (obj: any): BlockInclusionProof {
assert(obj.vitraBlockInclusionProof >= 1, 'Invalid schema version')
assert(typeof obj.logPubkey === 'string' && obj.logPubkey.length === 64, 'Invalid logPubkey')
assert(typeof obj.blockSeq === 'number', 'Invalid blockSeq')
assert(typeof obj.rootHashAtBlock === 'string', 'Invalid rootHashAtBlock')
assert(typeof obj.rootHashSignature === 'string', 'Invalid rootHashSignature')
return new BlockInclusionProof(
Buffer.from(obj.logPubkey, 'hex'),
obj.blockSeq,
Buffer.from(obj.rootHashAtBlock, 'hex'),
Buffer.from(obj.rootHashSignature, 'hex')
)
}
}