Bitzuma

An Introduction to the Electrum Python Console

By Rich Apodaca | Updated

Electrum is a popular wallet that can be used by beginners and experts alike. One of Electrum’s most powerful features is the Console. This article shows how to use the Console, and documents its built-in functions. Beginning Electrum users may want to first read A Beginner’s Guide to the Electrum Bitcoin Wallet and/or consider pre-ordering the upcoming book Electrum for Bitcoin Beginners.

Open the Console

The console is hidden by default. To show it, chose View>Show Console. Then click on the Console button near the top of Electrum’s main window.

Electrum Console

About the Console

The console provides you with an interactive Python shell configured with Electrum’s libraries. This allows you build scripts to automate various activities you might perform routinely.

One common reason to use the Console is reporting. For example, you may want to export certain views of your Electrum activity into reporting tools such as accounting software. The console allows you to perform this kind of automation and a lot more.

Entering Commands

Enter commands into the console by typing them after the >> prompt and then pressing enter. For example, a good way to begin your exploration would be to issue the help command:

help()

You should see a list of available commands. These commands (built-in functions) are enumerated and documented at the end of this post.

You may want to enter a code block into the Console. This can be done, but Python’s rules for significant whitespace must be followed.

For example, imagine we want to iterate over the addresses controlling unspent outputs. We can do that as follows:

>> for unspent in listunspent():
...  print(unspent.get('address'))
...
...

The first gives us the usual >> prompt. The second line prompt is three dots ..., after which we enter two spaces followed by the print statement. The last two lines are blank, causing the preceding code to be executed as a unit.

Running Stored Scripts

As you begin using the Console for more sophisticated tasks, re-entering scripts will become tedious. A better option is to store scripts in a file, which can then be re-run from the Console:

exec(open('/path/to/script/test.py').read())

For example, you could create a file that adds a new custom function that lists all UTXOs by outpoint. Save this code as a function called outpoints contained in the file outpoints.py. After loading the code with the exec command, you’ll be able to list your unspent outputs by outpoint:

exec(open('/pat/to/script/outpoints.py').read())
outpoints()

Although it may be obvious, your stored scripts can themselves import other scripts that use Electrum. In this way, you can build up complex workflows modularly.

For more scripting ideas and examples, see the scripting tutorial.

Built-in Functions

Electrum supports a wide range of built-in functions. Many of them merely provide a command-line interface for things that can be done through the GUI. Others make it possible to do things that are otherwise impossible.

The following is a list of built-in functions supported by the Console with example usage. For details, see the Electrum source.

addrequest

addrequest(amount, label)

Create a payment request for amount (in BTC) with label, using the first unused address of the wallet. The address will be considered as used after this operation. If no payment is received, the address will be considered as unused if the payment request is deleted from the wallet.

addtransaction

addtransaction(tx)

Adds transaction tx (serialized hex format) to the wallet history. tx must have at least one input controlled by the wallet. It’s not clear why this function would ever be necessary.

broadcast

broadcast(tx)

Broadcast transaction tx (serialized hex format) to the network.

check_seed

check_seed(seed, opt_entropy, opt_language)

Check that seed (a string) was generated with given opt_entropy (optional) and opt_language (optional).

clearrequests

clearrequests()

Removes all payment requests. Does not detach labels that may have been attached to addresses by previous requests.

commands

commands()

Prints a list of available commands.

createmultisig

createmultisig(threshold, pubkeys)

Creates a multisignature P2SH address with threshold and pubkeys (an array). For example, this creates representing a 1-of-2 multisignature address:

createmultisig(1, ["045a5713f24ba168d9c9d797ce5b9d7867fb936b7ea632cc1da08a6c4ba08aef8f7427e7ee1cf297212b58898657e3426dc9902d9ffc53e41787f8029804d49a87", "048fff4af0894075a46f3abf0b7b51f469e686ede3de2bc70a0bf7767f394362dad564c91ed8808d51aba4238b60b7979c6d805d1e55226d5b8935bdda2e4a47bd", "0405b4f342460aa8512e28a70393dc98117ebb56b10bb38968f986199ff9c5904bf834ba9fd0b323128127baa0e800b2bb12df4672cace22ac48cf6fa742ed2d19"])

and returns an object representing the result:

{
    "address": "2NBjFEvBWi7pNcJaLhSh58yD17oKVYHqWJ7",
    "redeemScript": "5141045a5713f24ba168d9c9d797ce5b9d7867fb936b7ea632cc1da08a6c4ba08aef8f7427e7ee1cf297212b58898657e3426dc9902d9ffc53e41787f8029804d49a8741048fff4af0894075a46f3abf0b7b51f469e686ede3de2bc70a0bf7767f394362dad564c91ed8808d51aba4238b60b7979c6d805d1e55226d5b8935bdda2e4a47bd410405b4f342460aa8512e28a70393dc98117ebb56b10bb38968f986199ff9c5904bf834ba9fd0b323128127baa0e800b2bb12df4672cace22ac48cf6fa742ed2d1953ae"
}

createnewaddress

createnewaddress()

Creates a new receiving address. The new address will be displayed with a red background to indicate that it falls outside of the gap limit.

decrypt

decrypt(pubkey, message)

Decrypts message encrypted with pubkey.

deserialize

deserialize(tx)

Deserializes tx (serialized hex).

For example, the command:

deserialize('020000000108b6f4cb5bb5397f2c962da7ad33e290db64764729d7fc34d41356143196cc49010000006b4830450221009649f90ddad006174204b6bb89f6c2dc67d0d2e4049cf7b7dfe70342b974eed8022068170631d583ed1bdbc1722571424557fcf3ef35da9220247636ac024c93728c012103a6a686c05a514b7a736db316b889015677579159e08e2e23a86cc07fb36d5cb2feffffff02a9e8ac200c0000001976a9146008fa55826f3ff4e20e50c2f4d0e62f369362a988ac1ab05d0b0000000017a9142ac95b52808ccf97949e1ee36012dc84b014f6d98755cd1300')

returns:

{
  "inputs": [
    {
      "address": "moQzkW7ZSHF7AdeM576BnsesLaLLvxZJXd",
      "num_sig": 1,
      "prevout_hash": "49cc9631145613d434fcd729477664db90e233ada72d962c7f39b55bcbf4b608",
      "prevout_n": 1,
      "pubkeys": [
        "03a6a686c05a514b7a736db316b889015677579159e08e2e23a86cc07fb36d5cb2"
      ],
      "scriptSig": "4830450221009649f90ddad006174204b6bb89f6c2dc67d0d2e4049cf7b7dfe70342b974eed8022068170631d583ed1bdbc1722571424557fcf3ef35da9220247636ac024c93728c012103a6a686c05a514b7a736db316b889015677579159e08e2e23a86cc07fb36d5cb2",
      "sequence": 4294967294,
      "signatures": [
        "30450221009649f90ddad006174204b6bb89f6c2dc67d0d2e4049cf7b7dfe70342b974eed8022068170631d583ed1bdbc1722571424557fcf3ef35da9220247636ac024c93728c01"
      ],
      "type": "p2pkh",
      "x_pubkeys": [
        "03a6a686c05a514b7a736db316b889015677579159e08e2e23a86cc07fb36d5cb2"
      ]
    }
  ],
  "lockTime": 1297749,
  "outputs": [
    {
      "address": "mpGjvGCdfRh8BU5DCpMN6PnsrSofsYg7Pw",
      "prevout_n": 0,
      "scriptPubKey": "76a9146008fa55826f3ff4e20e50c2f4d0e62f369362a988ac",
      "type": 0,
      "value": 52087810217
    },
    {
      "address": "2Mw9TarLpYsQmn5YySTGHccyussCDxFU5fT",
      "prevout_n": 1,
      "scriptPubKey": "a9142ac95b52808ccf97949e1ee36012dc84b014f6d987",
      "type": 0,
      "value": 190689306
    }
  ],
  "version": 2
}

dumpprivkeys

No longer functional. Use listaddresses with getprivatekeys instead.

encrypt

encrypt(pubkey, message)

Encrypts message with pubkey.

freeze

freeze(address)

Freezes the outputs controlled by address.

getaddressbalance

getaddressbalance(address)

Returns the balance of address. This is a walletless server query. Results are not checked by SPV.

getaddresshistory

getaddresshistory(address)

Return the transaction history address. This is a walletless server query, Results are not checked by SPV.

For example, the query:

getaddresshistory('moQzkW7ZSHF7AdeM576BnsesLaLLvxZJXd')

returns the result:

[
  {
    "height": 1297755,
    "tx_hash": "49cc9631145613d434fcd729477664db90e233ada72d962c7f39b55bcbf4b608"
  },
  {
    "height": 1297757,
    "tx_hash": "ed1350d20674d9a9596d66be869bba2da135ac24111a11205c0255221b6e95b6"
  }
]

getaddressunspent

getaddressunspent(address)
getaddressunspent('mggZWFFvr7UUyXAc4TeQhTzBSGfrGowU1b')
[
  {
    "height": 1297760,
    "tx_hash": "7ff68c5eaddcaee21ecbef714bdbf322a52eccb189b6ddff607b953c130bb46b",
    "tx_pos": 0,
    "value": 157961195
  },
  {
    "height": 1297760,
    "tx_hash": "26f8e3ed4c404f6400a14f6331d7859d877924fd95f90c1f4023bb329c96a1fc",
    "tx_pos": 0,
    "value": 168862247
  },
  {
    "height": 1297760,
    "tx_hash": "b5e6db2d771eeded9f015fd363d1d7c473a26b57bfd416081e9f12fe8f7403fe",
    "tx_pos": 0,
    "value": 51017054
  }
]

getalias

getalias(key)

Retrieves alias using key from your list of contacts.

getbalance

getbalance()

getconfig

getconfig(key)

Returns the value of configuration variable key.

For example, to find out if dynamic fees are set, use:

getconfig('dynamic_fees')

getfeerate

getfeerate()

Return current optimal fee rate per kilobyte, according to config settings (static/dynamic).

getmasterprivate

getmasterprivate()

Returns the master private key as a string beginning with “prv” (mainnet) or “tprv” (testnet).

getmerkle

getmerkle(txid, height)

Returns a Merkle proof for the transaction identified by txid at block height height.

For example:

getmerkle('6355ab17628634a29296c39096e753fd8af4c1cc7904e5099ae15c8d67c3c28f', 1297761)
{
  "block_height": 1297761,
  "merkle": [
    "29830f9db4458c119b161743ea9b704b93a42bd2b81f62f4d5c874f8c05dc2c3",
    "0adce0ea522fab1625b38d7f5ba8d0f3143d5c82342fd4f02de560445ee5011d",
    "060c88329089fc74b7f6534ef18e5c3f2aa89d8a8f934e4a5d052e23c958f126",
    "975a2c2547ed69de7ae19303e3a40dd01905e9d761aac7817b949f41b40c482f",
    "d85e5ee516b177958a5aed7a1b48a868719013119611cf697b55f54eef5e78e1",
    "a7034e75e3f8d76207b2fb063cba27470dd4c5c8ab07228530d9a6dea0a69893"
  ],
  "pos": 1
}

getmpk

getmpk()

Return the master private key as a string beginning with “xpriv” (mainnet) or “tpriv” (testnet).

getprivatekeys

getprivatekeys(address)

Returns the private key(s) associated with address as an array.

getrequest

getrequest(address)

Returns the payment request associated with address.

getseed

getseed()

Return the wallet’s mnemonic seed.

getservers

getservers()

Returns a set of servers. For example:

{
  "testnet1.bauerj.eu": {
    "pruning": "-",
    "s": "50002",
    "t": "50001",
    "version": "1.2"
  }
}

gettransaction

gettransaction(txid)

Returns a transaction represented by txid. For example:

gettransaction('6355ab17628634a29296c39096e753fd8af4c1cc7904e5099ae15c8d67c3c28f')

returns:

{
  "complete": true,
  "final": true,
  "hex": "0200000001a55bb0a05d2164427c4d0d7075b7551b743855e120d1f0a10d6ac5bd94e384fe000000006b483045022100df8beef2dcc84c693b544dd6048c83e73bedf0ab171f92e3c5a7579a2e3001b002207981b622a7182b37eb9b709fb6ae0c70eda26f18d618eac71095aeaedaaa937c0121021e27f8c06374d2d6a660d1be15ab93db9038d23d0fffc6a41b58f2f0f600a9c8feffffff02cb6879070000000017a914c695370cc29e494fa601cf61e7a8989284ddd74a87e16faf500b0000001976a914ca5b06c1e07cc188da922674a07bfd25adcbc6ca88ac60cd1300"
}

getunusedaddress

getunusedaddress()

Returns the first unused address of the wallet, or none if all addresses are used. An address is considered to be used if it has received a transaction, or if it is used in a payment request.

help

help()

Returns a list of available built-in functions.

history

history()

Example:

{
  "summary": {
    "end_balance": "0.09899776 BTC",
    "end_date": null,
    "expenditures": "0.00100224 BTC",
    "income": "0.1 BTC",
    "start_balance": "0. BTC",
    "start_date": null
  },
  "transactions": [
      {
        "balance": "0.1 BTC",
        "confirmations": 2964,
        "date": "2018-04-27 08:02",
        "height": 1294800,
        "label": "From faucet",
        "timestamp": 1524841353,
        "txid": "d39a91d18067dd0c03b9f1b0cbf0ed304f2289b17d55c389412ad99bcb4f1107",
        "value": "0.1 BTC"
      },
      {
        "balance": "0.09899776 BTC",
        "confirmations": 2954,
        "date": "2018-04-27 09:40",
        "height": 1294810,
        "label": "Faucet donation",
        "timestamp": 1524847244,
        "txid": "6d171797243500542e39246792df7c2153d7e0f07e1e94ccfbcb3912ccf324f6",
        "value": "-0.00100224 BTC"
      }
  ]
}

importprivkey

importprivkey(privkey)

Imports the private key represented by privkey (WIF or hex format).

is_synchronized

is_synchronized()

Returns wallet synchronization status.

ismine

ismine(address)

Returns true if the address belongs to the wallet, or false otherwise.

listaddresses

listaddresses(opt_receiving, opt_change, opt_show_labels, opt_frozen, opt_unused, opt_funded, opt_show_balance)

Returns a list of addresses controlled by the wallet, filtered by the optional opt_filter parameter.

listaddresses(True, False, True)

listcontacts

listcontacts()

Returns a list of contacts.

listrequests

listrequests()

Returns the open payment requests. For example:

[
  {
    "URI": "bitcoin:n1kPEgWKs5ouKkqF4Vo2ztejjcCesSCMTe?amount=0.1",
    "address": "n1kPEgWKs5ouKkqF4Vo2ztejjcCesSCMTe",
    "amount": 10000000,
    "amount (BTC)": "0.1",
    "exp": null,
    "id": "56a6cc639f",
    "memo": "Test",
    "status": "Pending",
    "time": 1526419221
  }
]

listunspent

listunspent()

Returns the list of unspent transaction outputs. For example:

[
  {
    "address": "mpB1GBsJi8i7m56Zgh3QtSTHBUSacZzed3",
    "coinbase": false,
    "height": 1294810,
    "prevout_hash": "6d171797243500542e39246792df7c2153d7e0f07e1e94ccfbcb3912ccf324f6",
    "prevout_n": 1,
    "value": "0.09899776"
  }
]

make_seed

make_seed()

Generates a new seed. Does not change your current seed.

notify

notify(address, url)

Watch address. On receiving address changes, send an http POST to url.

password

password(opt_old_password=None, opt_new_password=None)

Changes the wallet password.

payto

payto(address, amount, opt_fee, opt_from, opt_change, opt_nocheck, opt_unsigned, opt_rbf, opt_password, opt_locktime)

Create a transaction paying address in the amount amount (BTC, or ‘!’ to send wallet balance). Options include:

  • opt_fee the fee to use (in BTC), None by default
  • opt_from the funding address, None by default
  • opt_change the change address
  • opt_nocheck don’t verify aliases, False by default
  • opt_unsigned if True, no signature will be added, False by default
  • opt_rbf if True, RBF will be used, False by default
  • opt_password wallet password, None by default
  • opt_locktime lock time block number, None by default

paytomany

paytomany(outputs, opt_fee, opt_from, opt_change, opt_nocheck, opt_unsigned, opt_rbf, opt_password, opt_locktime)

Create a multi-output transaction using outputs to define payee addresses and amounts. outputs is an array in the format [address, amount]. Options include:

  • opt_fee the fee to use (in BTC), None by default
  • opt_from the funding address, None by default
  • opt_change the change address
  • opt_nocheck don’t verify aliases, False by default
  • opt_unsigned if True, no signature will be added, False by default
  • opt_rbf if True, RBF will be used, False by default
  • opt_password wallet password, None by default
  • opt_locktime lock time block number, None by default

rmrequest

rmrequest(address)

Deletes the payment request linked to address. Will not remove labels associated with address through the request.

searchcontacts

searchcontacts('Satoshi')

Returns a list of matching contacts based on query.

serialize

serialize(jsontx)

Create a transaction from jsontx. Inputs must have a redeemPubkey. Outputs must be a list of {'address':address, 'value':satoshi_amount}.

setconfig

setconfig(key, value)

Sets the configuration variable key to value. For example:

getconfig('dynamic_fees', False)

setlabel

setlabel(key, label)

Associates label with key, where key can be an address or transaction ID.

signmessage

signmessage(address, message, opt_password)

Signs message with the private key for address using optional wallet password opt_password.

signrequest

signrequest(address)

Signs a payment request associated with address using your Open Alias.

signtransaction

signtransaction(tx, opt_privkey)

Signs transaction tx (hex encoding). The wallet keys will be used unless a private key opt_privkey is provided.

sweep

sweep(privkey, address)

Sweeps the outputs controlled by privkey into address. Returns a transaction but does not broadcast it.

unfreeze

unfreeze(address)

Unfreezes address.

validateaddress

validateaddress(address)

Returns True if address is valid, or False otherwise.

verifymessage

verifymessage(address, signature, message)

Returns True if signature matches message for address or False otherwise.

version

version()

Returns the version of Electrum you’re currently running.