Key encoding refactor Includes code cherry-picked from the following upstream PRs: - bitcoin/bitcoin#11372 - Only the first three commits (the fourth commit depends on #2390) Part of #3058.