Skip to content

Commit d727f77

Browse files
committed
Merge #7946: Reduce cs_main locks during ConnectTip/SyncWithWallets
b3b3c2a Reduce cs_main locks during ConnectTip/SyncWithWallets (Jonas Schnelli)
2 parents 3859072 + b3b3c2a commit d727f77

File tree

7 files changed

+49
-54
lines changed

7 files changed

+49
-54
lines changed

src/main.cpp

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1541,7 +1541,7 @@ bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const C
15411541
}
15421542
}
15431543

1544-
SyncWithWallets(tx, NULL, NULL);
1544+
SyncWithWallets(tx, NULL);
15451545

15461546
return true;
15471547
}
@@ -2770,7 +2770,7 @@ bool static DisconnectTip(CValidationState& state, const CChainParams& chainpara
27702770
// Let wallets know transactions went from 1-confirmed to
27712771
// 0-confirmed or conflicted:
27722772
BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2773-
SyncWithWallets(tx, pindexDelete->pprev, NULL);
2773+
SyncWithWallets(tx, pindexDelete->pprev);
27742774
}
27752775
return true;
27762776
}
@@ -2785,7 +2785,7 @@ static int64_t nTimePostConnect = 0;
27852785
* Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
27862786
* corresponding to pindexNew, to bypass loading it again from disk.
27872787
*/
2788-
bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const CBlock* pblock)
2788+
bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const CBlock* pblock, std::list<CTransaction> &txConflicted, std::vector<std::tuple<CTransaction,CBlockIndex*,int> > &txChanged)
27892789
{
27902790
assert(pindexNew->pprev == chainActive.Tip());
27912791
// Read block from disk.
@@ -2821,20 +2821,13 @@ bool static ConnectTip(CValidationState& state, const CChainParams& chainparams,
28212821
return false;
28222822
int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
28232823
LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2824-
// Remove conflicting transactions from the mempool.
2825-
list<CTransaction> txConflicted;
2824+
// Remove conflicting transactions from the mempool.;
28262825
mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
28272826
// Update chainActive & related variables.
28282827
UpdateTip(pindexNew, chainparams);
2829-
// Tell wallet about transactions that went from mempool
2830-
// to conflicted:
2831-
BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2832-
SyncWithWallets(tx, pindexNew, NULL);
2833-
}
2834-
// ... and about transactions that got confirmed:
2835-
BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2836-
SyncWithWallets(tx, pindexNew, pblock);
2837-
}
2828+
2829+
for(unsigned int i=0; i < pblock->vtx.size(); i++)
2830+
txChanged.push_back(std::make_tuple(pblock->vtx[i], pindexNew, i));
28382831

28392832
int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
28402833
LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
@@ -2916,7 +2909,7 @@ static void PruneBlockIndexCandidates() {
29162909
* Try to make some progress towards making pindexMostWork the active block.
29172910
* pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
29182911
*/
2919-
static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const CBlock* pblock, bool& fInvalidFound)
2912+
static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const CBlock* pblock, bool& fInvalidFound, std::list<CTransaction>& txConflicted, std::vector<std::tuple<CTransaction,CBlockIndex*,int> >& txChanged)
29202913
{
29212914
AssertLockHeld(cs_main);
29222915
const CBlockIndex *pindexOldTip = chainActive.Tip();
@@ -2949,7 +2942,7 @@ static bool ActivateBestChainStep(CValidationState& state, const CChainParams& c
29492942

29502943
// Connect new blocks.
29512944
BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2952-
if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2945+
if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL, txConflicted, txChanged)) {
29532946
if (state.IsInvalid()) {
29542947
// The block violates a consensus rule.
29552948
if (!state.CorruptionPossible())
@@ -3024,6 +3017,8 @@ bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams,
30243017
break;
30253018

30263019
const CBlockIndex *pindexFork;
3020+
std::list<CTransaction> txConflicted;
3021+
std::vector<std::tuple<CTransaction,CBlockIndex*,int> > txChanged;
30273022
bool fInitialDownload;
30283023
int nNewHeight;
30293024
{
@@ -3038,7 +3033,7 @@ bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams,
30383033
return true;
30393034

30403035
bool fInvalidFound = false;
3041-
if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL, fInvalidFound))
3036+
if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL, fInvalidFound, txConflicted, txChanged))
30423037
return false;
30433038

30443039
if (fInvalidFound) {
@@ -3053,6 +3048,17 @@ bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams,
30533048
// When we reach this point, we switched to a new tip (stored in pindexNewTip).
30543049

30553050
// Notifications/callbacks that can run without cs_main
3051+
3052+
// throw all transactions though the signal-interface
3053+
// while _not_ holding the cs_main lock
3054+
BOOST_FOREACH(const CTransaction &tx, txConflicted)
3055+
{
3056+
SyncWithWallets(tx, pindexNewTip);
3057+
}
3058+
// ... and about transactions that got confirmed:
3059+
for(unsigned int i = 0; i < txChanged.size(); i++)
3060+
SyncWithWallets(std::get<0>(txChanged[i]), std::get<1>(txChanged[i]), std::get<2>(txChanged[i]));
3061+
30563062
// Always notify the UI if a new block tip was connected
30573063
if (pindexFork != pindexNewTip) {
30583064
uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);

src/validationinterface.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,6 @@ void UnregisterAllValidationInterfaces() {
4848
g_signals.UpdatedBlockTip.disconnect_all_slots();
4949
}
5050

51-
void SyncWithWallets(const CTransaction &tx, const CBlockIndex *pindex, const CBlock *pblock) {
52-
g_signals.SyncTransaction(tx, pindex, pblock);
51+
void SyncWithWallets(const CTransaction &tx, const CBlockIndex *pindex, int posInBlock) {
52+
g_signals.SyncTransaction(tx, pindex, posInBlock);
5353
}

src/validationinterface.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,12 @@ void UnregisterValidationInterface(CValidationInterface* pwalletIn);
2828
/** Unregister all wallets from core */
2929
void UnregisterAllValidationInterfaces();
3030
/** Push an updated transaction to all registered wallets */
31-
void SyncWithWallets(const CTransaction& tx, const CBlockIndex *pindex, const CBlock* pblock = NULL);
31+
void SyncWithWallets(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock = -1);
3232

3333
class CValidationInterface {
3434
protected:
3535
virtual void UpdatedBlockTip(const CBlockIndex *pindex) {}
36-
virtual void SyncTransaction(const CTransaction &tx, const CBlockIndex *pindex, const CBlock *pblock) {}
36+
virtual void SyncTransaction(const CTransaction &tx, const CBlockIndex *pindex, int posInBlock) {}
3737
virtual void SetBestChain(const CBlockLocator &locator) {}
3838
virtual void UpdatedTransaction(const uint256 &hash) {}
3939
virtual void Inventory(const uint256 &hash) {}
@@ -50,7 +50,7 @@ struct CMainSignals {
5050
/** Notifies listeners of updated block chain tip */
5151
boost::signals2::signal<void (const CBlockIndex *)> UpdatedBlockTip;
5252
/** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */
53-
boost::signals2::signal<void (const CTransaction &, const CBlockIndex *pindex, const CBlock *)> SyncTransaction;
53+
boost::signals2::signal<void (const CTransaction &, const CBlockIndex *pindex, int posInBlock)> SyncTransaction;
5454
/** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */
5555
boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
5656
/** Notifies listeners of a new active block chain. */

src/wallet/wallet.cpp

Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -886,18 +886,18 @@ bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
886886
* pblock is optional, but should be provided if the transaction is known to be in a block.
887887
* If fUpdate is true, existing transactions will be updated.
888888
*/
889-
bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
889+
bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
890890
{
891891
{
892892
AssertLockHeld(cs_wallet);
893893

894-
if (pblock) {
894+
if (posInBlock != -1) {
895895
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
896896
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
897897
while (range.first != range.second) {
898898
if (range.first->second != tx.GetHash()) {
899-
LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pblock->GetHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
900-
MarkConflicted(pblock->GetHash(), range.first->second);
899+
LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pIndex->GetBlockHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
900+
MarkConflicted(pIndex->GetBlockHash(), range.first->second);
901901
}
902902
range.first++;
903903
}
@@ -911,8 +911,8 @@ bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pbl
911911
CWalletTx wtx(this,tx);
912912

913913
// Get merkle branch if transaction was found in a block
914-
if (pblock)
915-
wtx.SetMerkleBranch(*pblock);
914+
if (posInBlock != -1)
915+
wtx.SetMerkleBranch(pIndex, posInBlock);
916916

917917
return AddToWallet(wtx, false);
918918
}
@@ -1037,11 +1037,11 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
10371037
}
10381038
}
10391039

1040-
void CWallet::SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, const CBlock* pblock)
1040+
void CWallet::SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock)
10411041
{
10421042
LOCK2(cs_main, cs_wallet);
10431043

1044-
if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1044+
if (!AddToWalletIfInvolvingMe(tx, pindex, posInBlock, true))
10451045
return; // Not one of ours
10461046

10471047
// If a transaction changes 'conflicted' state, that changes the balance
@@ -1399,9 +1399,10 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
13991399

14001400
CBlock block;
14011401
ReadBlockFromDisk(block, pindex, Params().GetConsensus());
1402-
BOOST_FOREACH(CTransaction& tx, block.vtx)
1402+
int posInBlock;
1403+
for (posInBlock = 0; posInBlock < (int)block.vtx.size(); posInBlock++)
14031404
{
1404-
if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1405+
if (AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate))
14051406
ret++;
14061407
}
14071408
pindex = chainActive.Next(pindex);
@@ -3526,31 +3527,19 @@ CWalletKey::CWalletKey(int64_t nExpires)
35263527
nTimeExpires = nExpires;
35273528
}
35283529

3529-
int CMerkleTx::SetMerkleBranch(const CBlock& block)
3530+
int CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
35303531
{
35313532
AssertLockHeld(cs_main);
35323533
CBlock blockTmp;
35333534

35343535
// Update the tx's hashBlock
3535-
hashBlock = block.GetHash();
3536+
hashBlock = pindex->GetBlockHash();
35363537

3537-
// Locate the transaction
3538-
for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
3539-
if (block.vtx[nIndex] == *(CTransaction*)this)
3540-
break;
3541-
if (nIndex == (int)block.vtx.size())
3542-
{
3543-
nIndex = -1;
3544-
LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
3545-
return 0;
3546-
}
3538+
// set the position of the transaction in the block
3539+
nIndex = posInBlock;
35473540

35483541
// Is the tx in a block that's in the main chain
3549-
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3550-
if (mi == mapBlockIndex.end())
3551-
return 0;
3552-
const CBlockIndex* pindex = (*mi).second;
3553-
if (!pindex || !chainActive.Contains(pindex))
3542+
if (!chainActive.Contains(pindex))
35543543
return 0;
35553544

35563545
return chainActive.Height() - pindex->nHeight + 1;

src/wallet/wallet.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ class CMerkleTx : public CTransaction
200200
READWRITE(nIndex);
201201
}
202202

203-
int SetMerkleBranch(const CBlock& block);
203+
int SetMerkleBranch(const CBlockIndex* pIndex, int posInBlock);
204204

205205
/**
206206
* Return depth of transaction in blockchain:
@@ -731,8 +731,8 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface
731731
void MarkDirty();
732732
bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
733733
bool LoadToWallet(const CWalletTx& wtxIn);
734-
void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, const CBlock* pblock);
735-
bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
734+
void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock);
735+
bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
736736
int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
737737
void ReacceptWalletTransactions();
738738
void ResendWalletTransactions(int64_t nBestBlockTime);

src/zmq/zmqnotificationinterface.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ void CZMQNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindex)
141141
}
142142
}
143143

144-
void CZMQNotificationInterface::SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, const CBlock* pblock)
144+
void CZMQNotificationInterface::SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int posInBlock)
145145
{
146146
for (std::list<CZMQAbstractNotifier*>::iterator i = notifiers.begin(); i!=notifiers.end(); )
147147
{

src/zmq/zmqnotificationinterface.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class CZMQNotificationInterface : public CValidationInterface
2424
void Shutdown();
2525

2626
// CValidationInterface
27-
void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, const CBlock* pblock);
27+
void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock);
2828
void UpdatedBlockTip(const CBlockIndex *pindex);
2929

3030
private:

0 commit comments

Comments
 (0)