Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,9 @@ export const BCH_TX_EXPLORER_URL = 'https://blockchair.com/bitcoin-cash/transact
export const MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME = 2
export const MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME = 20
export const CHRONIK_INITIALIZATION_DELAY = 2000
// Longest a mempool tx handler waits at startup for its addresses' `syncing` flag
// to clear. The flag can be left set by a sync that died, so never wait forever.
export const CHRONIK_SYNCING_WAIT_TIMEOUT_MS = 120000
export const MEMPOOL_PROCESS_DELAY = 100
export const CONFIRMED_TX_PROCESS_DELAY = 100

Expand Down
34 changes: 33 additions & 1 deletion services/chronikService.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BlockInfo, ChronikClient, ConnectionStrategy, ScriptUtxo, Tx, WsConfig, WsEndpoint, WsMsgClient, WsSubScriptClient } from 'chronik-client'
import { encodeCashAddress, decodeCashAddress } from 'ecashaddrjs'
import { AddressWithTransaction, BlockchainInfo, TransactionDetails, ProcessedMessages, SubbedAddressesLog, SyncAndSubscriptionReturn, SubscriptionReturn, SimpleBlockInfo } from 'types/chronikTypes'
import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index'
import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, CHRONIK_SYNCING_WAIT_TIMEOUT_MS, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index'
import { productionAddresses } from 'prisma-local/seeds/addresses'
import prisma from 'prisma-local/clientInstance'
import {
Expand Down Expand Up @@ -906,15 +906,34 @@ export class ChronikBlockchainClient {
return result
}

// At startup, lets a running sync of the tx's addresses finish before the
// mempool handler persists it. Both paths tolerate the other inserting first
// (upsert / createMany skipDuplicates), so this is only an ordering nicety and
// must never block for good: a sync that died leaves `syncing` set, and with
// MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME handlers stuck here all mempool
// processing would stall. Stop waiting once initialization ends or on timeout.
public async waitForSyncing (txId: string, addressStringArray: string[]): Promise<void> {
if (!this.initializing) return
console.log(`${this.CHRONIK_MSG_PREFIX}: Waiting unblocking addresses for ${txId}`)
const deadline = Date.now() + CHRONIK_SYNCING_WAIT_TIMEOUT_MS
while (true) {
const addresses = await fetchAddressesArray(addressStringArray)
if (addresses.every(a => !a.syncing)) {
console.log(`${this.CHRONIK_MSG_PREFIX}: Finished unblocking addresses for ${txId}`)
return
}
if (!this.initializing) {
console.log(`${this.CHRONIK_MSG_PREFIX}: Initialization finished, no longer waiting on addresses for ${txId}`)
return
}
if (Date.now() >= deadline) {
const stillSyncing = addresses.filter(a => a.syncing).map(a => a.address)
console.warn(
`${this.CHRONIK_MSG_PREFIX}: Gave up waiting after ${CHRONIK_SYNCING_WAIT_TIMEOUT_MS / 1000}s ` +
`for addresses still marked syncing for ${txId}: ${stillSyncing.join(', ')}`
)
return
}
await new Promise(resolve => setTimeout(resolve, CHRONIK_INITIALIZATION_DELAY))
}
}
Expand Down Expand Up @@ -1357,6 +1376,9 @@ export class ChronikBlockchainClient {
console.log(`${this.CHRONIK_MSG_PREFIX} Syncing ${addresses.length} addresses...`)
console.time(`${this.CHRONIK_MSG_PREFIX} syncAddresses`)
await setSyncingBatch(addresses.map(a => a.address), true)
// Addresses whose `syncing` flag this run has cleared; the rest are cleared in
// the finally below so a failed sync doesn't leave them flagged indefinitely.
const releasedAddresses = new Set<string>()

const perAddrCount = new Map<string, number>()
addresses.forEach(a => perAddrCount.set(a.id, 0))
Expand Down Expand Up @@ -1387,6 +1409,7 @@ export class ChronikBlockchainClient {
if (batch.phase === 'addresses-synced') {
// marcador de slice => desmarca syncing
await setSyncingBatch(batch.addressesSynced, false)
batch.addressesSynced.forEach(a => releasedAddresses.add(a))
progress?.addressesDone(this.networkSlug, batch.addressesSynced.length)
continue
}
Expand Down Expand Up @@ -1455,6 +1478,15 @@ export class ChronikBlockchainClient {
failedAddressesWithErrors[a.address] = err.stack ?? String(err)
}
})
} finally {
const unreleased = addresses.map(a => a.address).filter(a => !releasedAddresses.has(a))
if (unreleased.length > 0) {
try {
await setSyncingBatch(unreleased, false)
} catch (err: any) {
console.error(`${this.CHRONIK_MSG_PREFIX}: Failed to clear syncing flag for ${unreleased.length} addresses: ${err.message as string}`)
}
}
}

progress?.addressesFailed(this.networkSlug, failedAddressesWithErrors)
Expand Down
111 changes: 110 additions & 1 deletion tests/unittests/chronikService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {
multiBlockchainClient
} from '../../services/chronikService'
import { Address, Prisma } from '@prisma/client'
import { fetchAddressesArray } from '../../services/addressService'
import { fetchAddressesArray, setSyncingBatch } from '../../services/addressService'
import { CHRONIK_SYNCING_WAIT_TIMEOUT_MS } from '../../constants/index'
import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses, connectTransactionsListToPrices, createManyTransactionsForSync, invalidateCachesForAddresses } from '../../services/transactionService'
import prisma from '../../prisma-local/clientInstance'
import { executeAddressTriggers } from '../../services/triggerService'
Expand Down Expand Up @@ -2027,3 +2028,111 @@ describe('changed addresses reported by the sync', () => {
await expect(multiBlockchainClient.syncMissedTransactions()).resolves.toBeUndefined()
})
})

describe('stale syncing flags', () => {
const ADDR = 'ecash:qqkv9wr69ry2p9l53lxp635va4h86wv435995w8p2h'

beforeEach(() => {
process.env.WS_AUTH_KEY = 'test-auth-key'
jest.spyOn(console, 'log').mockImplementation(() => {})
jest.spyOn(console, 'warn').mockImplementation(() => {})
jest.spyOn(console, 'error').mockImplementation(() => {})
;(fetchAddressesArray as jest.Mock).mockReset()
})

afterEach(() => {
jest.useRealTimers()
jest.restoreAllMocks()
})

describe('waitForSyncing', () => {
it('gives up after the timeout when an address stays marked syncing', async () => {
jest.useFakeTimers()
;(fetchAddressesArray as jest.Mock).mockResolvedValue([{ address: ADDR, syncing: true }])
const client = new ChronikBlockchainClient('ecash')
client.initializing = true

let done = false
const p = client.waitForSyncing('tx1', [ADDR]).then(() => { done = true })

await jest.advanceTimersByTimeAsync(CHRONIK_SYNCING_WAIT_TIMEOUT_MS - 5000)
expect(done).toBe(false)
await jest.advanceTimersByTimeAsync(10000)
await p
expect(done).toBe(true)
expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('Gave up waiting'))
})

it('stops waiting once the client finishes initializing', async () => {
jest.useFakeTimers()
;(fetchAddressesArray as jest.Mock).mockResolvedValue([{ address: ADDR, syncing: true }])
const client = new ChronikBlockchainClient('ecash')
client.initializing = true

let done = false
const p = client.waitForSyncing('tx1', [ADDR]).then(() => { done = true })
await jest.advanceTimersByTimeAsync(3000)
expect(done).toBe(false)

client.setInitialized()
await jest.advanceTimersByTimeAsync(3000)
await p
expect(done).toBe(true)
expect(console.warn).not.toHaveBeenCalled()
})

it('returns as soon as the addresses are no longer syncing', async () => {
;(fetchAddressesArray as jest.Mock).mockResolvedValue([{ address: ADDR, syncing: false }])
const client = new ChronikBlockchainClient('ecash')
client.initializing = true

await expect(client.waitForSyncing('tx1', [ADDR])).resolves.toBeUndefined()
expect(fetchAddressesArray).toHaveBeenCalledTimes(1)
})

it('does not wait at all when not initializing', async () => {
const client = new ChronikBlockchainClient('ecash')
client.setInitialized()

await client.waitForSyncing('tx1', [ADDR])
expect(fetchAddressesArray).not.toHaveBeenCalled()
})
})

describe('syncAddresses', () => {
const a1 = { id: 'addr-1', address: 'ecash:addr-1', networkId: 1 } as any
const a2 = { id: 'addr-2', address: 'ecash:addr-2', networkId: 1 } as any

beforeEach(() => {
jest.spyOn(prisma.address, 'findMany').mockResolvedValue([] as any)
;(setSyncingBatch as jest.Mock).mockReset().mockResolvedValue(undefined)
})

it('clears the syncing flag of addresses the sync never finished when it fails', async () => {
const client = new ChronikBlockchainClient('ecash')
jest.spyOn(client as any, 'fetchLatestTxsForAddresses').mockImplementation(async function * () {
yield { phase: 'addresses-synced', chronikTxs: [], addressesSynced: ['ecash:addr-1'] }
throw new Error('chronik down')
})

await client.syncAddresses([a1, a2])

expect(setSyncingBatch).toHaveBeenNthCalledWith(1, ['ecash:addr-1', 'ecash:addr-2'], true)
expect(setSyncingBatch).toHaveBeenNthCalledWith(2, ['ecash:addr-1'], false)
expect(setSyncingBatch).toHaveBeenNthCalledWith(3, ['ecash:addr-2'], false)
expect(setSyncingBatch).toHaveBeenCalledTimes(3)
})

it('does not clear flags again when every address finished', async () => {
const client = new ChronikBlockchainClient('ecash')
jest.spyOn(client as any, 'fetchLatestTxsForAddresses').mockImplementation(async function * () {
yield { phase: 'addresses-synced', chronikTxs: [], addressesSynced: ['ecash:addr-1', 'ecash:addr-2'] }
})

await client.syncAddresses([a1, a2])

expect(setSyncingBatch).toHaveBeenCalledTimes(2)
expect(setSyncingBatch).toHaveBeenLastCalledWith(['ecash:addr-1', 'ecash:addr-2'], false)
})
})
})
Loading