Move code from script to wallet

Continues #4754
Nit: Needless extra diff (and below)