Move code from script to wallet

Continues #4754
+1, but I wouldn't object to doing that later.