Note that my wallet file uses the old 1.x format. The script should work fine with newer wallet files but I'm not 100% sure . Either way you should definitely backup your wallet file first.
require_once('easybitcoin.php');
$bitcoin = new Bitcoin('user', 'pw', '127.0.0.1', '8332');
$file_output = array();
$address_labels = array();
$wallet_file_path = 'C:/Users/User/AppData/Roaming/Electrum/wallets/default_wallet'; // wallet file location
$file_input = json_decode(file_get_contents($wallet_file_path), true);
// pull address labels from file
foreach ($file_input['labels'] as $key => $label) {
if (strlen($key) < 64) {
$address_labels[$key] = $label;
}
}
// check each tx against address labels and create new tx label if needed
foreach ($file_input['transactions'] as $tx_hash => $transaction) {
if (array_key_exists($tx_hash, $file_input['txo'])) {
$tx_json = json_encode($bitcoin->decoderawtransaction($transaction));
foreach ($address_labels as $address => $label) {
if (strpos($tx_json, $address) !== false && !array_key_exists($tx_hash, $file_input['labels'])) {
$file_output['labels'][$tx_hash] = $label;
echo $tx_hash.' '.$label.PHP_EOL; // display each new label (optional)
}
}
}
}
// remove address labels and add new tx labels
$file_input['labels'] = array_diff($file_input['labels'], $address_labels);
$file_input['labels'] = array_merge($file_input['labels'], $file_output['labels']);
ksort($file_input['labels']);
// convert some arrays to objects, to comply with electrum wallet format
$file_input['accounts'] = (object) $file_input['accounts'];
$file_input['accounts_expanded'] = (object) $file_input['accounts_expanded'];
$file_input['pruned_txo'] = (object) $file_input['pruned_txo'];
$file_input['receive_requests2'] = (object) $file_input['receive_requests2'];
foreach ($file_input['txi'] as &$txi) {
$txi = (object) $txi;
}
foreach ($file_input['txo'] as &$txo) {
$txo = (object) $txo;
}
// encode wallet and write to file
$file_output = json_encode($file_input, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$file_output = str_replace("\n", "\r\n", $file_output); // convert line endings for windows
file_put_contents($wallet_file_path, $file_output);
?>