From 7caedad3a310ba27a39d010aa61beb6cb4078d69 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Tue, 15 Jul 2025 21:06:22 -0700 Subject: [PATCH] Add signing method to Account class and simplify Block sign method accordingly. --- src/lib/account.ts | 24 ++++++++++++++++++++++++ src/lib/block.ts | 19 +++++-------------- 2 files changed, 29 insertions(+), 14 deletions(-) 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 }) } -- 2.47.3