From: Chris Duncan Date: Wed, 16 Jul 2025 04:06:22 +0000 (-0700) Subject: Add signing method to Account class and simplify Block sign method accordingly. X-Git-Tag: v0.10.5~57^2~1 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=7caedad3a310ba27a39d010aa61beb6cb4078d69;p=libnemo.git Add signing method to Account class and simplify Block sign method accordingly. --- diff --git a/src/lib/account.ts b/src/lib/account.ts index 23cf0b7..f85699d 100644 --- a/src/lib/account.ts +++ b/src/lib/account.ts @@ -6,6 +6,7 @@ import { ACCOUNT_KEY_BYTE_LENGTH, ACCOUNT_KEY_HEX_LENGTH, ALPHABET, PREFIX, PREF import { base32, bytes, hex, utf8 } from './convert' import { Rpc } from './rpc' import { NanoNaClWorker, SafeWorker } from '#workers' +import { ChangeBlock, ReceiveBlock, SendBlock } from './block' /** * Represents a single Nano address and the associated public key. To include the @@ -216,6 +217,29 @@ export class Account { this.#weight = BigInt(weight) } + /** + * Signs a block using the private key of the account. + * + * @param {(ChangeBlock|ReceiveBlock|SendBlock)} block - + */ + async sign (block: ChangeBlock | ReceiveBlock | SendBlock): Promise { + if (this.isLocked || this.#prv.buffer.detached) { + throw new Error('Failed to sign block with locked Account') + } + try { + const headers = { + method: 'detached' + } + const data = { + privateKey: new Uint8Array(this.#prv).buffer, + msg: hex.toBytes(block.hash).buffer + } + return await NanoNaClWorker.add(headers, data) + } catch (err) { + throw new Error(`Failed to sign block`, { cause: err }) + } + } + /** * Unlocks the account using the same password as used prior to lock it. * diff --git a/src/lib/block.ts b/src/lib/block.ts index 12bc6c8..025eb80 100644 --- a/src/lib/block.ts +++ b/src/lib/block.ts @@ -16,7 +16,7 @@ import { NanoNaClWorker } from '#workers' */ abstract class Block { account: Account - type: string = 'state' + type: 'state' = 'state' abstract subtype: 'send' | 'receive' | 'change' abstract previous: string abstract representative: Account @@ -139,20 +139,11 @@ abstract class Block { } this.signature = result.signature } else { - const key = input ?? this.account.privateKey - if (key == null) { - throw new Error('No valid key found to sign block') - } - const account = await Account.fromPrivateKey(key) try { - const headers = { - method: 'detached' - } - const data = { - privateKey: hex.toBytes(account.privateKey).buffer, - msg: hex.toBytes(this.hash).buffer - } - this.signature = await NanoNaClWorker.add(headers, data) + const account = (typeof input === 'string') + ? await Account.fromPrivateKey(input) + : this.account + this.signature = await account.sign(this) } catch (err) { throw new Error(`Failed to sign block`, { cause: err }) }