Fix peer disconnect handling
Improve peer_id allocation code to use (almost) constant time