@@ -725,28 +725,36 @@ class CDiskBlockIndex : public CBlockIndex
725
725
/* * An in-memory indexed chain of blocks. */
726
726
class CChain {
727
727
private:
728
- std::vector<CBlockIndex*> vChain;
728
+ mutable CCriticalSection cs_vchain;
729
+ std::vector<CBlockIndex*> vChain GUARDED_BY (cs_vchain);
729
730
730
731
public:
731
732
/* * Returns the index entry for the genesis block of this chain, or nullptr if none. */
732
733
CBlockIndex *Genesis () const {
734
+ LOCK (cs_vchain);
733
735
return vChain.size () > 0 ? vChain[0 ] : nullptr ;
734
736
}
735
737
736
738
/* * Returns the index entry for the tip of this chain, or nullptr if none. */
737
739
CBlockIndex *Tip () const {
740
+ LOCK (cs_vchain);
738
741
return vChain.size () > 0 ? vChain[vChain.size () - 1 ] : nullptr ;
739
742
}
740
743
741
744
/* * Returns the index entry at a particular height in this chain, or nullptr if no such height exists. */
742
745
CBlockIndex *operator [](int nHeight) const {
746
+ LOCK (cs_vchain);
743
747
if (nHeight < 0 || nHeight >= (int )vChain.size ())
744
748
return nullptr ;
745
749
return vChain[nHeight];
746
750
}
747
751
748
752
/* * Compare two chains efficiently. */
749
753
friend bool operator ==(const CChain &a, const CChain &b) {
754
+ // Maintain consistent lock order.
755
+ if (&b < &a) return b == a;
756
+
757
+ LOCK2 (a.cs_vchain , b.cs_vchain );
750
758
return a.vChain .size () == b.vChain .size () &&
751
759
a.vChain [a.vChain .size () - 1 ] == b.vChain [b.vChain .size () - 1 ];
752
760
}
@@ -758,6 +766,7 @@ class CChain {
758
766
759
767
/* * Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip. */
760
768
CBlockIndex *Next (const CBlockIndex *pindex) const {
769
+ LOCK (cs_vchain);
761
770
if (Contains (pindex))
762
771
return (*this )[pindex->nHeight + 1 ];
763
772
else
@@ -766,6 +775,7 @@ class CChain {
766
775
767
776
/* * Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
768
777
int Height () const {
778
+ LOCK (cs_vchain);
769
779
return vChain.size () - 1 ;
770
780
}
771
781
0 commit comments