Hunting for logic bugs in Monero
Florian Mathieu
, 5 min read, filed under security
- C++
- LMDB

Over the past decade, I’ve had the pleasure of developing software for quite a few open-source projects in the cryptocurrency space. Not so long ago, I realized that all this experience could also be useful for security analysis.
The applications and use cases in the cryptocurrency space are growing at a dazzling speed, but only at the surface. The core concepts underneath have evolved at a much more measured pace.
Many cryptocurrencies share a similar codebase; often they are outright clones of Bitcoin, Ethereum, Monero, etc. The experience you gain from working on one project easily carries over to another, because they share a lot of similarities and sometimes even the same code.
I decided to spend a few months reading codebases, hunting for bugs, and investigating whether those bugs had any real-world security impact. It turned out to be a fascinating journey: I found bugs in every project I investigated. Luckily, not all of them were a security risk.
This story is about a bug that had great potential for abuse but turned out to be harmless. I think it’s still an interesting read: it’s easy to understand what went wrong, and the methodology described below is generic enough to apply to your own research.
Methodology
I wanted to cover as many projects as possible in the time I had set aside, which left only a few days per project. The Monero codebase is simply too large to audit in that time, so I picked the corner that seemed most interesting: the Blockchain* classes and their functions. A bug there could allow double-spending and become my very own money printer.
The first thing to do is to truly understand the codebase, which, surprisingly, had more in common with Bitcoin’s than I expected. I compiled a list of the interesting classes and their functions and inspected them. Once I had a high-level overview of what the code is supposed to do and what assumptions it makes, I brainstormed potential attack vectors.
Blockchain: handles adding blocks at the highest level.
Blockchain::handle_block_to_main_chain(...): can I cheat the proof of work?Blockchain::check_tx_inputs(...): can I bypass any transaction input checks?Blockchain::pop_blocks(...): can I trigger the popping of legitimate blocks?
BlockchainDB: handles generic database logic.
BlockchainDB::add_block(...): can I add misbehaving blocks that double spend?BlockchainDB::pop_block(...): can I pop blocks containing my transaction?BlockchainDB::add_transaction(...): can I cause misbehavior when adding a transaction?BlockchainDB::remove_transaction(...): can I inadvertently remove a transaction?
BlockchainLMDB: handles LMDB-specific database logic.
BlockchainLMDB::add_spent_key(...): can I prevent the database from storing a spent key?BlockchainLMDB::remove_spent_key(...): can I somehow remove my spent key after it has been spent?
I picked this code because, in my experience, the complex cryptography code typically gets stringent security audits, while the transaction handling code around it does not. That code is just as important, though, and can contain bugs with the same impact as broken cryptography.
First signs of trouble
bool Blockchain::handle_block_to_main_chain(...)
{
...
// FIXME: the storage should not be responsible for validation.
// If it does any, it is merely a sanity check.
// Validation is the purview of the Blockchain class
// - TW
//
// ND: this is not needed, db->add_block() checks for duplicate k_images
// and fails accordingly.
// if (!check_for_double_spend(tx, keys))
// {
// LOG_PRINT_L0("Double spend detected in transaction (id: " << tx_id);
// bvc.m_verifivation_failed = true;
// break;
// }
...
}
Typically, you can find the code responsible for double-spend prevention by simply searching the codebase for “double spend”. That brought me to this comment, which explains that the double-spend check was disabled here because it already happens elsewhere.
It takes a bit of tracing through the codebase to see why you can’t double-spend, but I will save you the effort:
BlockchainDB::add_block(...)
-> BlockchainDB::add_transaction(...)
-> BlockchainLMDB::add_spent_key(...)
In the end, it’s BlockchainLMDB::add_spent_key(...) that catches a double-spend: when adding a spent key to the LMDB database, it checks that the key didn’t exist yet, and throws an exception if it did.
On further investigation, though, BlockchainDB::add_transaction(...) showed signs of some funky behavior, which I cover in the next section.
It’s worth noting that in Monero, unlike more transparent blockchains (Bitcoin, Ethereum, etc.), only the spender can truly know whether an input has been spent. Double-spend prevention works by giving each spent input a unique key, called the key image. Only the owner of an input can sign a transaction that spends it, and in doing so they also generate its key image. These key images are stored permanently and are what prevents double-spending.
If a transaction comes in and one of the inputs has a key image that is already recorded in the database, that transaction gets rejected as a double spend.
The misbehaving nested for-loops
The code below is a pattern I always look out for in audits: a for-loop that runs a bit of code and, when things don’t go as expected, follows up with another for-loop to undo everything.
void BlockchainDB::add_transaction(...)
{
...
for (const txin_v& tx_input : tx.vin)
{
if (tx_input.type() == typeid(txin_to_key))
{
add_spent_key(boost::get<txin_to_key>(tx_input).k_image);
}
else if (tx_input.type() == typeid(txin_gen))
{
/* nothing to do here */
miner_tx = true;
}
else
{
LOG_PRINT_L1("Unsupported input type, removing key images and aborting transaction addition");
for (const txin_v& tx_input : tx.vin)
{
if (tx_input.type() == typeid(txin_to_key))
{
remove_spent_key(boost::get<txin_to_key>(tx_input).k_image);
}
}
return;
}
}
...
In some cases it’s a perfectly fine pattern, but in this particular example, it’s a pipe bomb.
Note how the code loops over the inputs and calls add_spent_key until it hits an input type it can’t handle. It then removes the key images of all inputs, even those it may not have added to the database in the first place.
That raises the question: can processing transaction B remove a spent key that was added by an earlier transaction A? Long story short, no, but let’s figure out why together!
Trying to craft an exploit
The buggy path depends entirely on the input type. Only if I can get a transaction to this code with an input type it doesn’t recognize will it remove all the spent key images in that transaction, and only then could I pull off a double-spend.
So what input types are there? A quick search through the codebase (CTRL+F is your friend here) turns up:
txin_to_keytxin_gentxin_to_scripttxin_to_scripthash
Whoa! There are two other input types: txin_to_script and txin_to_scripthash. At first this looked very promising, and I can assure you I was very excited.
In theory, if I could construct a valid transaction containing a single input of type txin_to_script or txin_to_scripthash, every txin_to_key input after it would have its key image deleted, if it existed. That would erase the fact that those inputs were spent in another transaction, for anyone who processed the block.
The block would still be rejected because it contains an invalid transaction, but that doesn’t matter: my transaction only has to make it halfway to the database to remove the key images of my already spent inputs.
But the excitement was short-lived, because I hit a roadblock in Blockchain::check_tx_inputs(...):
bool Blockchain::check_tx_inputs(...) const
{
...
for (const auto& txin : tx.vin)
{
// make sure output being spent is of type txin_to_key, rather than
// e.g. txin_gen, which is only used for miner transactions
CHECK_AND_ASSERT_MES(txin.type() == typeid(txin_to_key), false, "wrong type id in tx input at Blockchain::check_tx_inputs");
const txin_to_key& in_to_key = boost::get<txin_to_key>(txin);
...
}
}
Every transaction input (except the miner input) must be of type txin_to_key. This check runs long before the buggy code, so there’s no way to exploit the bug.
The end
I hope you enjoyed this deep dive into how Monero processes blocks and protects against double-spends. Even though this bug didn’t turn out to be a security vulnerability, I reported it upstream and it was fixed.
Some key takeaways that I want to share:
- Even well-audited codebases can contain bugs.
- Focus on areas that are likely less audited.
- Get a decent understanding of the high-level workings, and write down questions as you go.
CTRL + FandF12(in VSCode) are your friends when looking to trace functions.- Stay curious, and spend time validating the assumptions that both you and the code make.
Questions or comments? Reply to the post on X.