Fix many bugs in the crypto and the wire protocol