-
Notifications
You must be signed in to change notification settings - Fork 579
/
verifier.ts
431 lines (369 loc) · 14.2 KB
/
verifier.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import { BufferSet } from 'buffer-map'
import { Blockchain } from '../blockchain'
import { Spend } from '../primitives'
import { Block } from '../primitives/block'
import { BlockHash, BlockHeader } from '../primitives/blockheader'
import { Target } from '../primitives/target'
import { SerializedTransaction, Transaction } from '../primitives/transaction'
import { IDatabaseTransaction } from '../storage'
import { Strategy } from '../strategy'
import { VerifyTransactionOptions } from '../workerPool/tasks/verifyTransaction'
import { ALLOWED_BLOCK_FUTURE_SECONDS, GENESIS_BLOCK_SEQUENCE } from './consensus'
export class Verifier {
strategy: Strategy
chain: Blockchain
/**
* Used to disable verifying the target on the Verifier for testing purposes
*/
enableVerifyTarget = true
constructor(chain: Blockchain) {
this.strategy = chain.strategy
this.chain = chain
}
/**
* Verify that the block is internally consistent:
* * All transaction proofs are valid
* * Header is valid
* * Miner's fee is transaction list fees + miner's reward
*/
async verifyBlock(
block: Block,
options: { verifyTarget?: boolean } = { verifyTarget: true },
): Promise<VerificationResult> {
// Verify the block header
const blockHeaderValid = this.verifyBlockHeader(block.header, options)
if (!blockHeaderValid.valid) {
return blockHeaderValid
}
// Verify the transactions
const verificationResults = await Promise.all(
block.transactions.map((t) => this.verifyTransaction(t, { verifyFees: false })),
)
const invalidResult = verificationResults.find((f) => !f.valid)
if (invalidResult !== undefined) {
return invalidResult
}
// Sum the totalTransactionFees and minersFee
let totalTransactionFees = BigInt(0)
let minersFee = BigInt(0)
const transactionFees = await Promise.all(block.transactions.map((t) => t.fee()))
for (let i = 0; i < transactionFees.length; i++) {
const fee = transactionFees[i]
// Miner's fee should be only the first transaction
if ((i === 0 && fee > 0) || (i !== 0 && fee < 0)) {
return { valid: false, reason: VerificationResultReason.INVALID_MINERS_FEE }
}
if (fee > 0) {
totalTransactionFees += fee
}
if (fee < 0) {
minersFee += fee
}
}
// minersFee should match the block header
if (block.header.minersFee !== minersFee) {
return { valid: false, reason: VerificationResultReason.INVALID_MINERS_FEE }
}
// minersFee should be (negative) miningReward + totalTransactionFees
const miningReward = block.header.strategy.miningReward(block.header.sequence)
if (minersFee !== BigInt(-1) * (BigInt(miningReward) + totalTransactionFees)) {
return { valid: false, reason: VerificationResultReason.INVALID_MINERS_FEE }
}
return { valid: true }
}
/**
* Verify that this block header is internally consistent. Does not verify
* the trees or its relationship to other blocks on the chain, and does not
* verify the transactions in the block.
*
* Specifically, it verifies that:
* * miners fee contains only one output note and no spends
* * miners fee is a valid transaction
* * the block hash meets the target hash on the block
* * the timestamp is not in future by our local clock time
*/
verifyBlockHeader(
blockHeader: BlockHeader,
options: { verifyTarget?: boolean } = { verifyTarget: true },
): VerificationResult {
if (blockHeader.graffiti.byteLength !== 32) {
return { valid: false, reason: VerificationResultReason.GRAFFITI }
}
if (this.enableVerifyTarget && options.verifyTarget && !blockHeader.verifyTarget()) {
return { valid: false, reason: VerificationResultReason.HASH_NOT_MEET_TARGET }
}
if (blockHeader.timestamp.getTime() > Date.now() + ALLOWED_BLOCK_FUTURE_SECONDS * 1000) {
return { valid: false, reason: VerificationResultReason.TOO_FAR_IN_FUTURE }
}
return { valid: true }
}
/**
* Verify that a new transaction received over the network has valid proofs
* before forwarding it to the network.
*
* @params payload an unknown message payload that peerNetwork has received from the network.
*
* @returns deserialized transaction to be processed by the main handler.
*/
verifyNewTransaction(serializedTransaction: SerializedTransaction): Transaction {
const transaction = this.strategy.transactionSerde.deserialize(serializedTransaction)
try {
// Transaction is lazily deserialized, so we use takeReference()
// to force deserialization errors here
transaction.takeReference()
} catch {
throw new Error('Transaction cannot deserialize')
} finally {
transaction.returnReference()
}
return transaction
}
async verifyTransaction(
transaction: Transaction,
options?: VerifyTransactionOptions,
): Promise<VerificationResult> {
if (this.isExpiredSequence(transaction.expirationSequence())) {
return {
valid: false,
reason: VerificationResultReason.TRANSACTION_EXPIRED,
}
}
try {
return transaction.verify(options)
} catch {
return { valid: false, reason: VerificationResultReason.VERIFY_TRANSACTION }
}
}
async verifyTransactionSpends(
transaction: Transaction,
tx?: IDatabaseTransaction,
): Promise<VerificationResult> {
return this.chain.db.withTransaction(tx, async (tx) => {
for (const spend of transaction.spends()) {
const reason = await this.verifySpend(spend, tx)
if (reason) {
return { valid: false, reason }
}
}
return { valid: true }
})
}
async verifyTransactionAdd(
transaction: Transaction,
tx?: IDatabaseTransaction,
): Promise<VerificationResult> {
let validity = await this.verifyTransactionSpends(transaction, tx)
if (!validity.valid) {
return validity
}
validity = await transaction.verify()
return validity
}
isExpiredSequence(expirationSequence: number, headSequence?: number): boolean {
headSequence = headSequence ?? this.chain.head.sequence
return expirationSequence !== 0 && expirationSequence <= headSequence
}
/**
* Verify that the header of this block is consistent with the one before it.
*
* Specifically, it checks:
* - The number of notes added is equal to the difference between
* commitment sizes
* - The number of nullifiers added is equal to the difference between
* commitment sizes
* - The timestamp of the block is within a threshold of not being before
* the previous block
* - The block sequence has incremented by one
*/
isValidAgainstPrevious(current: Block, previousHeader: BlockHeader): VerificationResult {
const { notes, nullifiers } = current.counts()
if (current.header.noteCommitment.size !== previousHeader.noteCommitment.size + notes) {
return { valid: false, reason: VerificationResultReason.NOTE_COMMITMENT_SIZE }
}
if (
current.header.nullifierCommitment.size !==
previousHeader.nullifierCommitment.size + nullifiers
) {
return { valid: false, reason: VerificationResultReason.NULLIFIER_COMMITMENT_SIZE }
}
if (
current.header.timestamp.getTime() <
previousHeader.timestamp.getTime() - ALLOWED_BLOCK_FUTURE_SECONDS * 1000
) {
return { valid: false, reason: VerificationResultReason.BLOCK_TOO_OLD }
}
if (current.header.sequence !== previousHeader.sequence + 1) {
return { valid: false, reason: VerificationResultReason.SEQUENCE_OUT_OF_ORDER }
}
if (!this.isValidTarget(current.header, previousHeader)) {
return { valid: false, reason: VerificationResultReason.INVALID_TARGET }
}
return { valid: true }
}
/**
* Verify that the target of this block is correct aginst the block before it.
*/
protected isValidTarget(header: BlockHeader, previous: BlockHeader): boolean {
if (!this.enableVerifyTarget) {
return true
}
const expectedTarget = Target.calculateTarget(
header.timestamp,
previous.timestamp,
previous.target,
)
return header.target.targetValue === expectedTarget.targetValue
}
// TODO: Rename to verifyBlock but merge verifyBlock into this
async verifyBlockAdd(block: Block, prev: BlockHeader | null): Promise<VerificationResult> {
if (block.header.sequence === GENESIS_BLOCK_SEQUENCE) {
return { valid: true }
}
if (!prev) {
return { valid: false, reason: VerificationResultReason.INVALID_PREV_HASH }
}
if (!block.header.previousBlockHash.equals(prev.hash)) {
return { valid: false, reason: VerificationResultReason.INVALID_PREV_HASH }
}
return block.withTransactionReferences(async () => {
let verification = this.isValidAgainstPrevious(block, prev)
if (!verification.valid) {
return verification
}
verification = await this.verifyBlock(block)
if (!verification.valid) {
return verification
}
return { valid: true }
})
}
/**
* Loop over all spends in the block and check that:
* - The nullifier has not previously been spent
* - the note being spent really existed in the tree at the time it was spent
*/
async hasValidSpends(block: Block, tx?: IDatabaseTransaction): Promise<VerificationResult> {
return this.chain.db.withTransaction(tx, async (tx) => {
const spendsInThisBlock = Array.from(block.spends())
const processedSpends = new BufferSet()
for (const [_, spend] of spendsInThisBlock.entries()) {
if (processedSpends.has(spend.nullifier)) {
return { valid: false, reason: VerificationResultReason.DOUBLE_SPEND }
}
const verificationError = await this.verifySpend(spend, tx)
if (verificationError) {
return { valid: false, reason: verificationError }
}
processedSpends.add(spend.nullifier)
}
return { valid: true }
})
}
/**
* Verify that the given spend was not in the nullifiers tree when it was the given size,
* and that the root of the notes tree is the one that is actually associated with the
* spend's spend root.
*
* @param spend the spend to be verified
* @param size the size of the nullifiers tree at which the spend must not exist
* @param tx optional transaction context within which to check the spends.
* TODO as its expensive, this would be a good place for a cache/map of verified Spends
*/
async verifySpend(
spend: Spend,
tx?: IDatabaseTransaction,
): Promise<VerificationResultReason | undefined> {
if (await this.chain.nullifiers.contains(spend.nullifier, tx)) {
return VerificationResultReason.DOUBLE_SPEND
}
try {
const realSpendRoot = await this.chain.notes.pastRoot(spend.size, tx)
if (!this.strategy.noteHasher.hashSerde().equals(spend.commitment, realSpendRoot)) {
return VerificationResultReason.INVALID_SPEND
}
} catch {
return VerificationResultReason.ERROR
}
}
/**
* Determine whether our trees match the commitment in the provided block.
*
* Matching means that the root hash of the tree when the tree is the size
* specified in the commitment is the same as the commitment,
* for both notes and nullifiers trees. Also verifies the spends, which have
* commitments as well.
*/
async verifyConnectedBlock(
block: Block,
tx?: IDatabaseTransaction,
): Promise<VerificationResult> {
return this.chain.db.withTransaction(tx, async (tx) => {
const header = block.header
const noteSize = header.noteCommitment.size
const nullifierSize = header.nullifierCommitment.size
const actualNoteSize = await this.chain.notes.size(tx)
const actualNullifierSize = await this.chain.nullifiers.size(tx)
if (noteSize > actualNoteSize) {
return { valid: false, reason: VerificationResultReason.NOTE_COMMITMENT_SIZE }
}
if (nullifierSize > actualNullifierSize) {
return { valid: false, reason: VerificationResultReason.NULLIFIER_COMMITMENT_SIZE }
}
const pastNoteRoot = await this.chain.notes.pastRoot(noteSize, tx)
if (
!this.strategy.noteHasher
.hashSerde()
.equals(pastNoteRoot, header.noteCommitment.commitment)
) {
return { valid: false, reason: VerificationResultReason.NOTE_COMMITMENT }
}
const pastNullifierRoot = await this.chain.nullifiers.pastRoot(nullifierSize, tx)
if (
!this.strategy.nullifierHasher
.hashSerde()
.equals(pastNullifierRoot, header.nullifierCommitment.commitment)
) {
return { valid: false, reason: VerificationResultReason.NULLIFIER_COMMITMENT }
}
const spendVerification = await this.hasValidSpends(block, tx)
if (!spendVerification.valid) {
return spendVerification
}
return { valid: true }
})
}
}
export enum VerificationResultReason {
BLOCK_TOO_OLD = 'Block timestamp is in past',
DOUBLE_SPEND = 'Double spend',
DUPLICATE = 'duplicate',
ERROR = 'error',
GRAFFITI = 'Graffiti field is not 32 bytes in length',
HASH_NOT_MEET_TARGET = 'hash does not meet target',
INVALID_MINERS_FEE = "Miner's fee is incorrect",
INVALID_PREV_HASH = 'invalid previous hash',
INVALID_SPEND = 'Invalid spend',
INVALID_TARGET = 'Invalid target',
INVALID_TRANSACTION_PROOF = 'invalid transaction proof',
NOTE_COMMITMENT = 'note_commitment',
NOTE_COMMITMENT_SIZE = 'Note commitment sizes do not match',
NULLIFIER_COMMITMENT = 'nullifier_commitment',
NULLIFIER_COMMITMENT_SIZE = 'Nullifier commitment sizes do not match',
ORPHAN = 'Block is an orphan',
SEQUENCE_OUT_OF_ORDER = 'Block sequence is out of order',
TOO_FAR_IN_FUTURE = 'timestamp is in future',
TRANSACTION_EXPIRED = 'Transaction expired',
VERIFY_TRANSACTION = 'verify_transaction',
}
/**
* Indicate whether some entity is valid, and if not, provide a reason and
* hash.
*/
export interface VerificationResult {
valid: boolean
reason?: VerificationResultReason
hash?: BlockHash
}