From: Chris Duncan Date: Wed, 9 Jul 2025 17:34:30 +0000 (-0700) Subject: Improve block validation. X-Git-Tag: v0.10.5~82 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=780ab63cfc8d8866affe9c2ac3834a5cb7ea6afe;p=libnemo.git Improve block validation. --- diff --git a/src/lib/block.ts b/src/lib/block.ts index 13a3e6d..3ab8c99 100644 --- a/src/lib/block.ts +++ b/src/lib/block.ts @@ -32,7 +32,7 @@ abstract class Block { if (this.constructor === Block) { throw new Error('Block is an abstract class and cannot be instantiated directly.') } - if (account.constructor === Account) { + if (account instanceof Account) { this.account = account } else if (typeof account === 'string') { this.account = Account.fromAddress(account) @@ -331,43 +331,45 @@ export class ChangeBlock extends Block { * * @param {Block} block - SendBlock, ReceiveBlock, or ChangeBlock to validate */ -function validate (block: Block): void { - if (block.account == null) { +function validate (block: unknown): asserts block is Block { + if (typeof block !== 'object') { + throw new TypeError('Invalid block') + } + const b = block as { [key: string]: unknown } + if (b.account == null) { throw new Error('Account missing') } - if (block.previous == null || block.previous === '') { + if (b.previous == null || b.previous === '') { throw new Error('Frontier missing') } - if (block.representative == null) { + if (b.representative == null) { throw new Error('Representative missing') } - if (block.balance == null) { + if (b.balance == null) { throw new Error('Balance missing') } - if (block.balance < 0) { + if (typeof b.balance !== 'number' && typeof b.balance !== 'bigint') { + throw new TypeError('Balance must be number or bigint') + } + if (b.balance < 0) { throw new Error('Negative balance') } - switch (block.constructor) { - case SendBlock: { - if (block.link == null || block.link === '') { - throw new Error('Recipient missing') - } - break + if (b instanceof SendBlock) { + if (b.link == null || b.link === '') { + throw new Error('Recipient missing') } - case ReceiveBlock: { - if (block.link == null) { - throw new Error('Origin send block hash missing') - } - break + } + if (b instanceof ReceiveBlock) { + if (b.link == null) { + throw new Error('Origin send block hash missing') } - case ChangeBlock: { - if (block.link == null) { - throw new Error('Change block link missing') - } - if (+block.link !== 0) { - throw new Error('Invalid change block link') - } - break + } + if (b instanceof ChangeBlock) { + if (b.link == null) { + throw new Error('Change block link missing') + } + if (+(b.link) !== 0) { + throw new Error('Invalid change block link') } } }