Additionally for quicker resolution of what the valid last block header is I should cherry-pick PR#334 into segwit.
decorated_heads = sorted(((
self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
#self.items[h].peer_addr is None,
-self.items[h].should_punish_reason(previous_block, bits, self, known_txs)[0],
-self.items[h].time_seen,
), h) for h in self.verified.tails.get(best_tail, []))
best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
P2pool will choose a share to work on based on the work done as of the 5th-grandparent of the shares first, and punishment is only the 2nd priority in case of a tie (i.e. shares that both have the same 5th grandparent). So if, for example, there is a Segwit2x sharechain that has 1.5x the hashrate as a Bitcoin Cash sharechain, and if a p2pool node sees both, it will choose the Segwit2x chain even if the bitcoind is Bitcoin Cash. This means that there will not be two completely separate sharechains, and that sharechain forks will generally be "resolved" (albeit incorrectly) in 5 shares or less. All Bitcoin forks will fight over the same share chain. But wait, there's more just below that:
if best is not None:
best_share = self.items[best]
punish, punish_reason = best_share.should_punish_reason(previous_block, bits, self, known_txs)
if punish > 0:
print 'Punishing share for %r! Jumping from %s to %s!' % (punish_reason, format_hash(best), format_hash(best_share.previous_hash))
best = best_share.previous_hash
That's a second check for punishment. If the share chosen by the first block of code is getting punished, then p2pool will just use its parent. This would mean that our hypothetical Bitcoin Cash miner would be mining a share based on the Segwit2x chain, but he would use the second-to-last share in that chain. This would make his shares have a disproportionately high chance of being orphaned, but not a 100% chance. If he and other BCH miners mine two shares in quick succession, they stand a reasonable chance of being used by Segwit2x miners.
Malicious miners could improve their chances by using the minimum share difficulty instead of the default share difficulty to further increase the probability of mining multiple shares in quick succession. A Bitcoin Cash proponent with a significant minority of hashrate could use this mechanism to preferentially orphan many or most shares submitted by Segwit2x or SegwitNo2x miners. On one of my nodes right now, the default share difficulty is about 30x higher than the consensus-enforced minimum share difficulty, so this attack would actually be quite feasible and effective even with only around 1/30th of the total p2pool hashrate.
In other words, the block-stale detection is not a solution to the forking blockchain problem. It is relevant to p2pool's behavior in forking situations, but it's mostly a weirding factor, and can be exploited by malicious, selfish, or politically motivated entities.