Find the last common ancestor two blocks have. * Both pa and pb must be non-nullptr. */
| 152 | /** Find the last common ancestor two blocks have. |
| 153 | * Both pa and pb must be non-nullptr. */ |
| 154 | const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) { |
| 155 | // First rewind to the last common height (the forking point cannot be past one of the two). |
| 156 | if (pa->nHeight > pb->nHeight) { |
| 157 | pa = pa->GetAncestor(pb->nHeight); |
| 158 | } else if (pb->nHeight > pa->nHeight) { |
| 159 | pb = pb->GetAncestor(pa->nHeight); |
| 160 | } |
| 161 | while (pa != pb) { |
| 162 | // Jump back until pa and pb have a common "skip" ancestor. |
| 163 | while (pa->pskip != pb->pskip) { |
| 164 | // This logic relies on the property that equal-height blocks have equal-height skip |
| 165 | // pointers. |
| 166 | Assume(pa->nHeight == pb->nHeight); |
| 167 | Assume(pa->pskip->nHeight == pb->pskip->nHeight); |
| 168 | pa = pa->pskip; |
| 169 | pb = pb->pskip; |
| 170 | } |
| 171 | // At this point, pa and pb are different, but have equal pskip. The forking point lies in |
| 172 | // between pa/pb on the one end, and pa->pskip/pb->pskip on the other end. |
| 173 | pa = pa->pprev; |
| 174 | pb = pb->pprev; |
| 175 | } |
| 176 | return pa; |
| 177 | } |