Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Batch accounts when decrypting transaction notes #4727

Merged
merged 9 commits into from
Apr 22, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions ironfish/src/rpc/routes/wallet/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ export async function getTransactionNotes(
}

decryptNotesPayloads.push({
accountId: account.id,
dguenther marked this conversation as resolved.
Show resolved Hide resolved
serializedNote: note.serialize(),
incomingViewKey: account.incomingViewKey,
outgoingViewKey: account.outgoingViewKey,
Expand Down
93 changes: 63 additions & 30 deletions ironfish/src/wallet/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,16 +411,15 @@ export class Wallet {
async (a) => await this.isAccountUpToDate(a),
))

const decryptedNotesByAccountId = new Map<string, Array<DecryptedNote>>()

const batchSize = 20
const notePromises: Array<Promise<Array<DecryptedNote>>> = []
let decryptNotesPayloads = []
for (const account of accountsToCheck) {
const decryptedNotes = []
let decryptNotesPayloads = []
let currentNoteIndex = initialNoteIndex

for (const note of transaction.notes) {
decryptNotesPayloads.push({
accountId: account.id,
serializedNote: note.serialize(),
incomingViewKey: account.incomingViewKey,
outgoingViewKey: account.outgoingViewKey,
Expand All @@ -434,22 +433,22 @@ export class Wallet {
}

if (decryptNotesPayloads.length >= batchSize) {
const decryptedNotesBatch = await this.decryptNotesFromTransaction(
decryptNotesPayloads,
)
decryptedNotes.push(...decryptedNotesBatch)
notePromises.push(this.decryptNotesFromTransaction(decryptNotesPayloads))
decryptNotesPayloads = []
}
}
}

if (decryptNotesPayloads.length) {
const decryptedNotesBatch = await this.decryptNotesFromTransaction(decryptNotesPayloads)
decryptedNotes.push(...decryptedNotesBatch)
}
if (decryptNotesPayloads.length) {
notePromises.push(this.decryptNotesFromTransaction(decryptNotesPayloads))
}

if (decryptedNotes.length) {
decryptedNotesByAccountId.set(account.id, decryptedNotes)
}
const decryptedNotesByAccountId = new Map<string, Array<DecryptedNote>>()
const flatPromises = (await Promise.all(notePromises)).flat()
for (const decryptedNote of flatPromises) {
const accountNotes = decryptedNotesByAccountId.get(decryptedNote.accountId) ?? []
accountNotes.push(decryptedNote)
decryptedNotesByAccountId.set(decryptedNote.accountId, accountNotes)
}

return decryptedNotesByAccountId
Expand Down Expand Up @@ -484,9 +483,47 @@ export class Wallet {
}
})

for (const account of accounts) {
const shouldDecrypt = await this.shouldDecryptForAccount(blockHeader, account)
const shouldDecryptAccounts = (
await Promise.all(
accounts.map((a) =>
this.shouldDecryptForAccount(blockHeader, a).then(
(shouldDecrypt): [Account, boolean] => [a, shouldDecrypt],
),
),
)
)
.filter((v) => v[1])
.map((v) => v[0])
dguenther marked this conversation as resolved.
Show resolved Hide resolved

const shouldDecryptAccountIds = new Set(shouldDecryptAccounts.map((a) => a.id))

const decryptedTransactions = await Promise.all(
transactions.map(({ transaction, initialNoteIndex }) =>
this.decryptNotes(transaction, initialNoteIndex, false, shouldDecryptAccounts).then(
(r) => ({
result: r,
transaction,
}),
),
),
)

// account id -> transaction hash -> Array<DecryptedNote>
const decryptedNotesMap: Map<string, Map<string, Array<DecryptedNote>>> = new Map()
for (const { transaction, result } of decryptedTransactions) {
for (const [accountId, decryptedNotes] of result) {
if (!decryptedNotes.length) {
continue
}
dguenther marked this conversation as resolved.
Show resolved Hide resolved

const accountTxnsMap =
decryptedNotesMap.get(accountId) ?? new Map<string, Array<DecryptedNote>>()
accountTxnsMap.set(transaction.hash().toString('base64'), decryptedNotes)
dguenther marked this conversation as resolved.
Show resolved Hide resolved
decryptedNotesMap.set(accountId, accountTxnsMap)
}
}

for (const account of accounts) {
if (scan && scan.isAborted) {
scan.signalComplete()
this.scan = null
Expand All @@ -495,11 +532,16 @@ export class Wallet {

await this.walletDb.db.transaction(async (tx) => {
let assetBalanceDeltas = new AssetBalances()
const accountTxnsMap = decryptedNotesMap.get(account.id)
const txns = transactions.map((t) => ({
transaction: t.transaction,
decryptedNotes: accountTxnsMap?.get(t.transaction.hash().toString('base64')) ?? [],
}))

if (shouldDecrypt) {
if (shouldDecryptAccountIds.has(account.id)) {
assetBalanceDeltas = await this.connectBlockTransactions(
blockHeader,
transactions,
txns,
account,
scan,
tx,
Expand Down Expand Up @@ -556,27 +598,18 @@ export class Wallet {

private async connectBlockTransactions(
blockHeader: WalletBlockHeader,
transactions: WalletBlockTransaction[],
transactions: Array<{ transaction: Transaction; decryptedNotes: Array<DecryptedNote> }>,
account: Account,
scan?: ScanState,
tx?: IDatabaseTransaction,
): Promise<AssetBalances> {
const assetBalanceDeltas = new AssetBalances()

for (const { transaction, initialNoteIndex } of transactions) {
for (const { transaction, decryptedNotes } of transactions) {
if (scan && scan.isAborted) {
return assetBalanceDeltas
}

const decryptedNotesByAccountId = await this.decryptNotes(
transaction,
initialNoteIndex,
false,
[account],
)

const decryptedNotes = decryptedNotesByAccountId.get(account.id) ?? []

const transactionDeltas = await account.connectTransaction(
blockHeader,
transaction,
Expand Down
7 changes: 7 additions & 0 deletions ironfish/src/workerPool/tasks/decryptNotes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ describe('DecryptNotesRequest', () => {
const request = new DecryptNotesRequest(
[
{
accountId: 'accountId',
serializedNote: Buffer.alloc(ENCRYPTED_NOTE_LENGTH, 1),
incomingViewKey: Buffer.alloc(ACCOUNT_KEY_LENGTH, 1).toString('hex'),
outgoingViewKey: Buffer.alloc(ACCOUNT_KEY_LENGTH, 1).toString('hex'),
Expand All @@ -39,6 +40,7 @@ describe('DecryptNotesRequest', () => {

const request = new DecryptNotesRequest(
Array.from({ length }, () => ({
accountId: 'accountId',
serializedNote: Buffer.alloc(ENCRYPTED_NOTE_LENGTH, 1),
incomingViewKey: Buffer.alloc(ACCOUNT_KEY_LENGTH, 1).toString('hex'),
outgoingViewKey: Buffer.alloc(ACCOUNT_KEY_LENGTH, 1).toString('hex'),
Expand All @@ -59,6 +61,7 @@ describe('DecryptNotesResponse', () => {
const response = new DecryptNotesResponse(
[
{
accountId: 'accountId',
forSpender: false,
index: 1,
hash: Buffer.alloc(32, 1),
Expand All @@ -79,6 +82,7 @@ describe('DecryptNotesResponse', () => {

const request = new DecryptNotesResponse(
Array.from({ length }, () => ({
accountId: 'accountId',
forSpender: false,
index: 1,
hash: Buffer.alloc(32, 1),
Expand All @@ -105,6 +109,7 @@ describe('DecryptNotesTask', () => {
const index = 2
const request = new DecryptNotesRequest([
{
accountId: account.id,
serializedNote: transaction.getNote(0).serialize(),
incomingViewKey: account.incomingViewKey,
outgoingViewKey: account.outgoingViewKey,
Expand Down Expand Up @@ -142,6 +147,7 @@ describe('DecryptNotesTask', () => {
const index = 3
const requestSpender = new DecryptNotesRequest([
{
accountId: accountA.id,
serializedNote: transaction.getNote(0).serialize(),
incomingViewKey: accountA.incomingViewKey,
outgoingViewKey: accountA.outgoingViewKey,
Expand All @@ -166,6 +172,7 @@ describe('DecryptNotesTask', () => {

const requestNoSpender = new DecryptNotesRequest([
{
accountId: accountA.id,
serializedNote: transaction.getNote(0).serialize(),
incomingViewKey: accountA.incomingViewKey,
outgoingViewKey: accountA.outgoingViewKey,
Expand Down
13 changes: 13 additions & 0 deletions ironfish/src/workerPool/tasks/decryptNotes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { WorkerTask } from './workerTask'

export interface DecryptNoteOptions {
serializedNote: Buffer
accountId: string
incomingViewKey: string
outgoingViewKey: string
viewKey: string
Expand All @@ -19,6 +20,7 @@ export interface DecryptNoteOptions {
}

export interface DecryptedNote {
accountId: string
dguenther marked this conversation as resolved.
Show resolved Hide resolved
index: number | null
forSpender: boolean
hash: Buffer
Expand All @@ -42,6 +44,7 @@ export class DecryptNotesRequest extends WorkerMessage {
bw.writeU8(flags)

bw.writeBytes(payload.serializedNote)
bw.writeVarString(payload.accountId, 'utf8')
bw.writeBytes(Buffer.from(payload.incomingViewKey, 'hex'))
bw.writeBytes(Buffer.from(payload.outgoingViewKey, 'hex'))
bw.writeBytes(Buffer.from(payload.viewKey, 'hex'))
Expand All @@ -61,13 +64,15 @@ export class DecryptNotesRequest extends WorkerMessage {
const hasCurrentNoteIndex = flags & (1 << 0)
const decryptForSpender = Boolean(flags & (1 << 1))
const serializedNote = reader.readBytes(ENCRYPTED_NOTE_LENGTH)
const accountId = reader.readVarString('utf8')
const incomingViewKey = reader.readBytes(ACCOUNT_KEY_LENGTH).toString('hex')
const outgoingViewKey = reader.readBytes(ACCOUNT_KEY_LENGTH).toString('hex')
const viewKey = reader.readBytes(VIEW_KEY_LENGTH).toString('hex')
const currentNoteIndex = hasCurrentNoteIndex ? reader.readU32() : null

payloads.push({
serializedNote,
accountId,
incomingViewKey,
outgoingViewKey,
currentNoteIndex,
Expand All @@ -84,6 +89,7 @@ export class DecryptNotesRequest extends WorkerMessage {
for (const payload of this.payloads) {
size += 1
size += ENCRYPTED_NOTE_LENGTH
size += bufio.sizeVarString(payload.accountId, 'utf8')
size += ACCOUNT_KEY_LENGTH
size += ACCOUNT_KEY_LENGTH
size += VIEW_KEY_LENGTH
Expand Down Expand Up @@ -115,6 +121,7 @@ export class DecryptNotesResponse extends WorkerMessage {
flags |= Number(note.forSpender) << 2
bw.writeU8(flags)
bw.writeHash(note.hash)
bw.writeVarString(note.accountId, 'utf8')
bw.writeBytes(note.serializedNote)

if (note.index) {
Expand Down Expand Up @@ -144,6 +151,7 @@ export class DecryptNotesResponse extends WorkerMessage {
const hasNullifier = flags & (1 << 1)
const forSpender = Boolean(flags & (1 << 2))
const hash = reader.readHash()
const accountId = reader.readVarString('utf8')
const serializedNote = reader.readBytes(DECRYPTED_NOTE_LENGTH)

let index = null
Expand All @@ -157,6 +165,7 @@ export class DecryptNotesResponse extends WorkerMessage {
}

notes.push({
accountId,
forSpender,
index,
hash,
Expand All @@ -176,6 +185,7 @@ export class DecryptNotesResponse extends WorkerMessage {

if (note) {
size += 1 + 32 + DECRYPTED_NOTE_LENGTH
size += bufio.sizeVarString(note.accountId, 'utf8')

if (note.index) {
size += 4
Expand Down Expand Up @@ -205,6 +215,7 @@ export class DecryptNotesTask extends WorkerTask {
const decryptedNotes = []

for (const {
accountId,
serializedNote,
incomingViewKey,
outgoingViewKey,
Expand All @@ -218,6 +229,7 @@ export class DecryptNotesTask extends WorkerTask {
const receivedNote = note.decryptNoteForOwner(incomingViewKey)
if (receivedNote && receivedNote.value() !== 0n) {
decryptedNotes.push({
accountId,
index: currentNoteIndex,
forSpender: false,
hash: note.hash(),
Expand All @@ -235,6 +247,7 @@ export class DecryptNotesTask extends WorkerTask {
const spentNote = note.decryptNoteForSpender(outgoingViewKey)
if (spentNote && spentNote.value() !== 0n) {
decryptedNotes.push({
accountId,
index: currentNoteIndex,
forSpender: true,
hash: note.hash(),
Expand Down
1 change: 1 addition & 0 deletions ironfish/src/workerPool/tasks/workerMessages.test.perf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ describe('WorkerMessages', () => {
for (const transaction of transactions) {
for (const note of transaction.notes) {
payload.push({
accountId: account.id,
serializedNote: note.serialize(),
incomingViewKey: account.incomingViewKey,
outgoingViewKey: account.outgoingViewKey,
Expand Down