"Maximum call stack size exceeded" error bug fixed

-The "Maximum call stack size exceeded" error is now handled internally by the block sync script in a way which will capture the error and re-launch the sync using a larger stack size and have the sync resume from where it left off. If the re-launch still doesn't have enough memory it will continue re-launching with more and more memory until the sync can finish without errors and then it will return to sync with a lower memory footprint for future syncs
-Added a new option for sync.elastic_stack_size which is used to determine how much memory should be used to increase the stack size for the block sync after encountering the "Maximum call stack size exceeded" error
-Fixed an issue with the block sync when using more than 1 thread that could sometimes cause the flattened txes value in the coinstats database to be written incorrectly (Use `npm run reindex-txcount` to fix this issue without needing to reindex the entire database)
-Updated the benchmark script so that it can also benefit from being able to capture the "Maximum call stack size exceeded" error even though the timing will be off so it outputs a new warning in that scenario which instructs to run the benchmark again with a higher stack size to properly capture the benchmark time
-Removed the "Maximum call stack size exceeded" error notes from the "Known Issues" section of the README
This commit is contained in:
Joe Uhren
2025-01-09 20:00:37 -07:00
parent 454fb0a7d7
commit 0b0ef817f1
7 changed files with 614 additions and 328 deletions
-24
View File
@@ -936,30 +936,6 @@ The benchmark script can be started with the following command:
### Known Issues
**exceeding stack size**
```
RangeError: Maximum call stack size exceeded
```
Nodes default stack size may be too small to index addresses with many tx's. If you experience the above error while running sync.js the stack size needs to be increased.
To determine the default setting run:
```
node --v8-options | grep -B0 -A1 stack-size
```
To run a sync with a larger stack size launch with:
```
node --stack-size=[SIZE] scripts/sync.js index update
```
Where [SIZE] is an integer higher than the default.
*note: SIZE will depend on which blockchain you are using, you may need to play around a bit to find an optimal setting*
**Error: bind EACCES ...**
This error can appear when you try to run the explorer on a port number lower than 1024. There are a couple solutions to this problem which are explained in more detail in the [Run Express Webserver on Port 80](#run-express-webserver-on-port-80) section.
+199 -30
View File
@@ -6,6 +6,7 @@ const lib = require('./explorer');
const settings = require('../lib/settings');
const async = require('async');
let stopSync = false;
let stackSizeErrorId = null;
function check_delete_tx(tx, block_height, tx_count, timeout, cb) {
// check if the tx object exists and does not match the current block height
@@ -116,12 +117,38 @@ function update_address(hash, blockheight, txid, amount, type, cb) {
});
}
function finalize_update_tx_db(coin, check_only, end, txes, cb) {
let statUpdateObject = {};
// check what stats data should be updated
if (stopSync || stackSizeErrorId || check_only == 2) {
// only update txes when fixing invalid and missing blocks or when a "normal" sync was stopped prematurely
statUpdateObject.txes = txes;
} else {
// update last and txes values for "normal" sync that finishes without being stopped prematurely
statUpdateObject = {
txes: txes,
last: end
};
}
// update local stats
Stats.updateOne({coin: coin}, statUpdateObject).then(() => {
return cb();
}).catch((err) => {
console.log(err);
return cb();
});
}
module.exports = {
save_tx: function(txid, blockheight, block, cb) {
lib.get_rawtransaction(txid, function(tx) {
if (tx && tx != `${settings.localization.ex_error}: ${settings.localization.check_console}`) {
lib.prepare_vin(tx, function(vin, tx_type_vin) {
lib.prepare_vout(tx.vout, txid, vin, ((!settings.blockchain_specific.zksnarks.enabled || typeof tx.vjoinsplit === 'undefined' || tx.vjoinsplit == null) ? [] : tx.vjoinsplit), function(vout, nvin, tx_type_vout) {
// check if vout is null which indicates an error
if (vout != null) {
lib.syncLoop(nvin.length, function (loop) {
const i = loop.iteration();
@@ -194,6 +221,15 @@ module.exports = {
});
});
});
} else {
// create a custom error that will be specifically checked for later (NOTE: tx_type_vout contains the error code in this special case)
const customError = new Error(tx_type_vout);
customError.code = tx_type_vout;
// return the custom error
return cb(customError, false);
}
});
});
} else
@@ -214,6 +250,9 @@ module.exports = {
if (parallel_tasks < 1)
parallel_tasks = 1;
let finished_tasks = 0;
let processed_last_block = false;
for (i = start; i < (end + 1); i++)
blocks_to_scan.push(i);
@@ -242,6 +281,12 @@ module.exports = {
});
async.eachLimit(blocks_to_scan, parallel_tasks, function(block_height, next_block) {
// check if this is the last block to process
if (block_height == end) {
// ensure the process knows not to wait for more threads to stop after this
processed_last_block = true;
}
// add the current block height to a queue and wait for it to be next in queue before starting to sync the block
block_queue.push(
{
@@ -283,14 +328,21 @@ module.exports = {
if (blockhash) {
lib.get_block(blockhash, function(block) {
if (block) {
let tx_counter = 0;
// loop through all txes in this block
async.eachLimit(block.tx, parallel_tasks, function(txid, next_tx) {
// increment tx counter
tx_counter++;
Tx.findOne({txid: txid}).then((tx) => {
if (tx && check_only != 2) {
setTimeout(function() {
tx = null;
tx_counter--;
// check if the script is stopping
if (stopSync && check_only != 2) {
if ((stopSync && check_only != 2) || stackSizeErrorId) {
// stop the loop
next_tx({});
} else
@@ -307,10 +359,14 @@ module.exports = {
// save the transaction to local database
module.exports.save_tx(txid, block_height, block, function(err, tx_has_vout) {
if (err) {
// check the error code
if (err.code == 'StackSizeError') {
// ensure the process halts after stopping all sync threads
stackSizeErrorId = txid;
} else if (err.code === 11000) {
// output a nicer error msg for the 11000 error code "duplicate key error collection" which can happen in some blockchains with non-standard txids being reused
if (err.code === 11000)
console.log(`${settings.localization.ex_warning}: ${block_height}: ${txid} already exists`);
else
} else
console.log(err);
}
else
@@ -321,9 +377,10 @@ module.exports = {
setTimeout(function() {
tx = null;
tx_counter--;
// check if the script is stopping
if (stopSync && check_only != 2) {
if ((stopSync && check_only != 2) || stackSizeErrorId) {
// stop the loop
next_tx({});
} else
@@ -334,9 +391,10 @@ module.exports = {
// skip adding the current tx
setTimeout(function() {
tx = null;
tx_counter--;
// check if the script is stopping
if (stopSync && check_only != 2) {
if ((stopSync && check_only != 2) || stackSizeErrorId) {
// stop the loop
next_tx({});
} else
@@ -350,9 +408,10 @@ module.exports = {
setTimeout(function() {
tx = null;
tx_counter--;
// check if the script is stopping
if (stopSync && check_only != 2) {
if ((stopSync && check_only != 2) || stackSizeErrorId) {
// stop the loop
next_tx({});
} else
@@ -360,7 +419,21 @@ module.exports = {
}, timeout);
});
}, function() {
setTimeout(function() {
// set the retry limit to a value that will be reached in ~10 seconds based on the
// timeout value which should be more than enough time for all threads to finish
// processing their last tx in case of error or cancel/kill script
const retryLimit = (10000 / timeout);
let retryAttempts = 0;
// wait for all threads to finish before continuing
const handle = setInterval(() => {
// check if all threads have properly finished or else the retry limit has been reached
// NOTE: the retry limit should never need to be used but is put in place to prevent an
// infinite loop just in case something goes very wrong
if (tx_counter === 0 || retryAttempts >= retryLimit) {
// stop waiting for all threads to finish
clearInterval(handle);
blockhash = null;
block = null;
@@ -368,11 +441,19 @@ module.exports = {
block_numbers[slotIndex] = 0;
// check if the script is stopping
if (stopSync && check_only != 2) {
if ((stopSync && check_only != 2) || stackSizeErrorId) {
// stop the loop
finished_tasks++;
next_block({});
} else
} else {
// check if the last block is finished or in process and increment the finished counter
if (processed_last_block)
finished_tasks++;
// proceed to next block
next_block();
}
}
}, timeout);
});
} else {
@@ -383,11 +464,18 @@ module.exports = {
block_numbers[slotIndex] = 0;
// check if the script is stopping
if (stopSync && check_only != 2) {
if ((stopSync && check_only != 2) || stackSizeErrorId) {
// stop the loop
finished_tasks++;
next_block({});
} else
} else {
// check if the last block is finished or in process and increment the finished counter
if (processed_last_block)
finished_tasks++;
// proceed to next block
next_block();
}
}, timeout);
}
});
@@ -397,11 +485,18 @@ module.exports = {
block_numbers[slotIndex] = 0;
// check if the script is stopping
if (stopSync && check_only != 2) {
if ((stopSync && check_only != 2) || stackSizeErrorId) {
// stop the loop
finished_tasks++;
next_block({});
} else
} else {
// check if the last block is finished or in process and increment the finished counter
if (processed_last_block)
finished_tasks++;
// proceed to next block
next_block();
}
}, timeout);
}
});
@@ -410,27 +505,37 @@ module.exports = {
() => {}
);
}, function() {
var statUpdateObject = {};
// set the retry limit to a value that will be reached in ~10 seconds based on the
// timeout value which should be more than enough time for all threads to finish
// processing their last tx in case of error or cancel/kill script
const retryLimit = (10000 / timeout);
let retryAttempts = 0;
// check what stats data should be updated
if (stopSync || check_only == 2) {
// only update txes when fixing invalid and missing blocks or when a "normal" sync was stopped prematurely
statUpdateObject.txes = txes;
// wait for all threads to finish before continuing
const handle = setInterval(() => {
// check if all threads have properly finished or else the retry limit has been reached
// NOTE: the retry limit should never need to be used but is put in place to prevent an
// infinite loop just in case something goes very wrong
if (finished_tasks === parallel_tasks || retryAttempts >= retryLimit) {
// stop waiting for all threads to finish
clearInterval(handle);
// finish the update
finalize_update_tx_db(coin, check_only, end, txes, function() {
// check if the script should continue or respawn a new process
if (!stackSizeErrorId) {
// continue to end of process
return cb(txes);
} else {
// update last and txes values for "normal" sync that finishes without being stopped prematurely
statUpdateObject = {
txes: txes,
last: end
};
// reload the sync process
module.exports.respawnSync();
}
// update local stats
Stats.updateOne({coin: coin}, statUpdateObject).then(() => {
return cb(txes);
}).catch((err) => {
console.log(err);
return cb(txes);
});
} else {
// still waiting for threads to finish so increment the retry counter
retryAttempts++;
}
}, timeout);
});
},
@@ -664,5 +769,69 @@ module.exports = {
getStopSync: function() {
return stopSync;
},
setStackSizeErrorId: function(value) {
stackSizeErrorId = value;
},
getStackSizeErrorId: function() {
return stackSizeErrorId;
},
respawnSync: function() {
let extraArgument = '';
// check if this is the benchmark script which must be handled slightly differently than a normal sync
if (process.argv[1].endsWith('benchmark.js')) {
// add the extra argument for benchmark syncing
extraArgument = '1';
}
const stackSizeArg = process.execArgv.find(arg => arg.startsWith('--stack-size='));
let stackSize = 4096;
// check if the script was called with a stack size argument
if (stackSizeArg) {
// set the default stack size to the value that is currently being used
stackSize = parseInt(stackSizeArg.split('=')[1]);
}
// increase stack size by the elastic amount
stackSize += settings.sync.elastic_stack_size;
// show an error msg
console.log(`${settings.localization.ex_error}: Maximum call stack size exceeded while processing txid ${stackSizeErrorId}`);
console.log(`Restarting sync process with increased stack size of ${stackSize}. ${settings.localization.please_wait}..`);
// filter out any existing --stack-size from execArgv
const execArgvWithoutStackSize = process.execArgv.filter(arg => !arg.startsWith('--stack-size='));
// populate child process arguments
const args = [
...execArgvWithoutStackSize,
`--stack-size=${stackSize}`,
...process.argv.slice(1) // includes the path to the sync script and any user args
];
// add the extra argument to resume the benchmark sync and skip the unlock step
if (extraArgument != '')
args.push(extraArgument);
else {
// remove lock
lib.remove_lock(process.argv[2] == null || process.argv[2] == '' ? 'index' : process.argv[2]);
}
const { spawn } = require('child_process');
// reload the sync process
const child = spawn(process.execPath, args, {
stdio: 'inherit'
});
// when the child process ends, exit this parent process with the same code
child.on('exit', code => {
process.exit(code ?? 1);
});
}
};
+11
View File
@@ -1117,6 +1117,7 @@ module.exports = {
var arr_vin = vin;
var tx_type = null;
try {
module.exports.syncLoop(vout.length, function (loop) {
var i = loop.iteration();
// make sure vout has an address
@@ -1296,6 +1297,16 @@ module.exports = {
} else
return cb(arr_vout, arr_vin, tx_type);
});
} catch(err) {
// check if a "Maximum call stack size exceeded" error occurred
if (err instanceof RangeError && /Maximum call stack size exceeded/i.test(err.message)) {
// return invalid results with error msg
return cb(null, null, 'StackSizeError');
} else {
// any other error should be output normally
throw err;
}
}
},
get_input_addresses: function(input, vout, cb) {
+5 -1
View File
@@ -1411,7 +1411,11 @@ exports.sync = {
// HEAVY: retrieved from getsupply rpc cmd (The "blockchain_specific.heavycoin.enabled" setting must be set to true and the "blockchain_specific.heavycoin.api_cmds.getsupply" setting must be set up correctly for this option to work properly)
// BALANCES : get the supply by running a query on the addresses collection and summing up all positive balances (potentially a long running query for blockchains with tons of addresses)
// TXOUTSET : retrieved from gettxoutsetinfo rpc cmd
"supply": "GETINFO"
"supply": "GETINFO",
// elastic_stack_size: If a "RangeError: Maximum call stack size exceeded" error occurs during a block sync (which can happen when dealing with large transactions with many addresses), the sync script will automatically be reloaded using a larger stack size value which increases memory usage based on this value.
// NOTE: If the first reload of the sync script still doesn't have enough memory to handle processing of a large transaction, the sync is smart enough to continue increasing the stack size by this value again and again until it finishes processing all blocks and then returns back to the default amount of memory for future blocks.
// It is recommended to leave this value alone unless you know what you are doing.
"elastic_stack_size": 4096
};
// captcha: a collection of settings that pertain to the captcha security used by different elements of the explorer
+94 -7
View File
@@ -1,18 +1,25 @@
const mongoose = require('mongoose');
const Address = require('../models/address');
const Tx = require('../models/tx');
const blkSync = require('../lib/block_sync');
const settings = require('../lib/settings');
const resumeSync = process.argv[2] == '1';
let dbString = `mongodb://${settings.benchmark.address}:${settings.benchmark.port}/admin`
// prevent stopping of the sync script to be able to gracefully shut down
process.on('SIGINT', () => {
if (!blkSync.getStackSizeErrorId())
console.log(`${settings.localization.stopping_sync_process}.. ${settings.localization.please_wait}..`);
blkSync.setStopSync(true);
});
// prevent killing of the sync script to be able to gracefully shut down
process.on('SIGTERM', () => {
if (!blkSync.getStackSizeErrorId())
console.log(`${settings.localization.stopping_sync_process}.. ${settings.localization.please_wait}..`);
blkSync.setStopSync(true);
});
@@ -89,6 +96,74 @@ function check_create_user(cb) {
return cb();
}
function initialize_data_startup(cb) {
console.log(`${settings.localization.initializing_database}.. ${settings.localization.please_wait}..`);
const db = require('../lib/database');
// check if stats collection is initialized
db.check_stats(settings.coin.name, function(stats_exists) {
let skip = true;
// determine if stats collection already exists
if (stats_exists == false) {
console.log(`${settings.localization.creating_initial_entry.replace('{1}', 'stats')}.. ${settings.localization.please_wait}..`);
skip = false;
}
// initialize the stats collection
db.create_stats(settings.coin.name, skip, function() {
// get the stats object from the database
db.get_stats(settings.coin.name, function(stats) {
// finished initializing startup data
console.log('Database initialization complete');
return cb(stats);
});
});
});
}
function delete_txes(cb) {
// check if the benchmark sync is being resumed
if (resumeSync) {
// do not delete the list of txes for a resume sync
return cb();
} else {
// delete all previous transaction records from the benchmark database
Tx.deleteMany({}).then(() => {
return cb();
});
}
}
function delete_addresses(cb) {
// check if the benchmark sync is being resumed
if (resumeSync) {
// do not delete the list of addresses for a resume sync
return cb();
} else {
// delete all previous address records from the benchmark database
Address.deleteMany({}).then(() => {
return cb();
});
}
}
function delete_stats(cb) {
// check if the benchmark sync is being resumed
if (resumeSync) {
// do not delete the database stats for a resume sync
return cb();
} else {
const Stats = require('../models/stats');
// delete all previous stat records from the benchmark database
Stats.deleteMany({}).then(() => {
return cb();
});
}
}
console.log(`${settings.localization.script_launched}: ${process.pid}`);
mongoose.set('strictQuery', true);
@@ -104,19 +179,22 @@ check_create_user(function() {
// connect to the benchmark database
mongoose.connect(dbString).then(() => {
const Tx = require('../models/tx');
// delete all previous transaction records from the benchmark database
Tx.deleteMany({}).then(() => {
const Address = require('../models/address');
delete_txes(function() {
// delete all previous address records from the benchmark database
Address.deleteMany({}).then(() => {
delete_addresses(function() {
// delete all previous stat records from the benchmark database
delete_stats(function() {
// initialize the benchmark database
initialize_data_startup(function(stats) {
// get the last synced block index value
const last = (stats.last ? stats.last : 0);
// get starting timestamp
const s_timer = new Date().getTime();
// start the block sync
blkSync.update_tx_db(settings.coin.name, 1, settings.benchmark.block_to_sync, 0, settings.sync.update_timeout, false, function() {
blkSync.update_tx_db(settings.coin.name, last, settings.benchmark.block_to_sync, stats.txes, settings.sync.update_timeout, false, function() {
// get ending timestamp
const e_timer = new Date().getTime();
@@ -134,12 +212,21 @@ check_create_user(function() {
address_count: acount,
seconds: (e_timer - s_timer) / 1000,
});
// check if the sync needed to be resumed
if (resumeSync) {
// output a warning msg
console.log(`\n${settings.localization.ex_warning}: The sync ran out of memory during processing and therefore the run time was affected. It is recommended to re-run the benchmark again using a larger stack size such as 25000 or higher with the cmd "node --stack-size=25000 scripts/benchmark.js" to help ensure an accurate benchmark time.`);
}
exit(0);
});
});
});
});
});
});
});
}).catch((err) => {
console.log('Error: Unable to connect to database: %s', dbString);
exit(999);
+37 -2
View File
@@ -18,14 +18,18 @@ var stopSync = false;
// prevent stopping of the sync script to be able to gracefully shut down
process.on('SIGINT', () => {
if (!blkSync.getStackSizeErrorId())
console.log(`${settings.localization.stopping_sync_process}.. ${settings.localization.please_wait}..`);
blkSync.setStopSync(true);
stopSync = true;
});
// prevent killing of the sync script to be able to gracefully shut down
process.on('SIGTERM', () => {
if (!blkSync.getStackSizeErrorId())
console.log(`${settings.localization.stopping_sync_process}.. ${settings.localization.please_wait}..`);
blkSync.setStopSync(true);
stopSync = true;
});
@@ -202,6 +206,12 @@ function update_orphans(orphan_index, orphan_current, last_blockindex, timeout,
tx_count = updated_tx_count2;
setTimeout(function() {
// check if there was a memory error
if (blkSync.getStackSizeErrorId() != null) {
// stop the loop
tx_loop.break(true);
}
// move to the next tx record
tx_loop.next();
}, timeout);
@@ -209,6 +219,12 @@ function update_orphans(orphan_index, orphan_current, last_blockindex, timeout,
});
}, function() {
setTimeout(function() {
// check if there was a memory error
if (blkSync.getStackSizeErrorId() != null) {
// stop the loop
block_loop.break(true);
}
// move to the next block record
block_loop.next();
}, timeout);
@@ -216,6 +232,8 @@ function update_orphans(orphan_index, orphan_current, last_blockindex, timeout,
});
});
}, function() {
// check if there was a memory error
if (!blkSync.getStackSizeErrorId()) {
// get the most recent stats
Stats.findOne({coin: settings.coin.name}).then((stats) => {
// add missing txes for the current block
@@ -259,6 +277,12 @@ function update_orphans(orphan_index, orphan_current, last_blockindex, timeout,
next(null);
}, timeout);
});
} else {
setTimeout(function() {
// stop the loop
next('StackSizeError');
}, timeout);
}
});
});
} else {
@@ -283,11 +307,17 @@ function update_orphans(orphan_index, orphan_current, last_blockindex, timeout,
function(err) {
// check if there is a msg to display
if (err != '' && err != 'stop') {
// check if this is the StackSizeError error
if (err == 'StackSizeError') {
// reload the sync process
blkSync.respawnSync();
} else {
// display the msg
console.log(err);
// stop fixing orphaned block data
return cb();
}
} else {
// check if the script is stopping
if (!stopSync)
@@ -514,9 +544,14 @@ function check_add_tx(txid, blockhash, tx_count, cb) {
// save the tx to the local database
blkSync.save_tx(txid, block.height, block, function(save_tx_err, tx_has_vout) {
// check if there were any save errors
if (save_tx_err)
if (save_tx_err) {
// check the error code
if (save_tx_err.code == 'StackSizeError') {
// ensure the process halts after stopping all sync threads
blkSync.setStackSizeErrorId(txid);
} else
console.log(save_tx_err);
else
} else
console.log('%s: %s', block.height, txid);
// check if the tx was saved correctly
+5 -1
View File
@@ -1498,7 +1498,11 @@
// HEAVY: retrieved from getsupply rpc cmd (The "blockchain_specific.heavycoin.enabled" setting must be set to true and the "blockchain_specific.heavycoin.api_cmds.getsupply" setting must be set up correctly for this option to work properly)
// BALANCES : get the supply by running a query on the addresses collection and summing up all positive balances (potentially a long running query for blockchains with tons of addresses)
// TXOUTSET : retrieved from gettxoutsetinfo rpc cmd
"supply": "GETINFO"
"supply": "GETINFO",
// elastic_stack_size: If a "RangeError: Maximum call stack size exceeded" error occurs during a block sync (which can happen when dealing with large transactions with many addresses), the sync script will automatically be reloaded using a larger stack size value which increases memory usage based on this value.
// NOTE: If the first reload of the sync script still doesn't have enough memory to handle processing of a large transaction, the sync is smart enough to continue increasing the stack size by this value again and again until it finishes processing all blocks and then returns back to the default amount of memory for future blocks.
// It is recommended to leave this value alone unless you know what you are doing.
"elastic_stack_size": 4096
},
// captcha: a collection of settings that pertain to the captcha security used by different elements of the explorer