pybitmessage.api module

This is not what you run to start the Bitmessage API. Instead, enable the API and optionally enable daemon mode then run the PyBitmessage.

The PyBitmessage API is provided either as XML-RPC or JSON-RPC like in bitcoin. It’s selected according to ‘apivariant’ setting in config file.

Special value apivariant=legacy is to mimic the old pre 0.6.3 behaviour when any results are returned as strings of json.

All config settings related to API:
apienabled = true if ‘false’ the singleAPI wont start
apiinterface = 127.0.0.1 this is the recommended default
apiport = 8442 the API listens apiinterface:apiport if apiport is not used, random in range (32767, 65535) otherwice
apivariant = xml current default for backward compatibility, ‘json’ is recommended
apiusername = username set the username
apipassword = password and the password
apinotifypath = not really the API setting, this sets a path for the executable to be ran when certain internal event happens

To use the API concider such simple example:

import jsonrpclib

from pybitmessage import bmconfigparser, helper_startup

helper_startup.loadConfig()  # find and load local config file
conf = bmconfigparser.BMConfigParser()
api_uri = "http://%s:%s@127.0.0.1:8442/" % (
    conf.safeGet('bitmessagesettings', 'apiusername'),
    conf.safeGet('bitmessagesettings', 'apipassword')
)
api = jsonrpclib.ServerProxy(api_uri)
print(api.clientStatus())

For further examples please reference tests.test_api.

class ErrorCodes[source]

Bases: type

Metaclass for APIError documenting error codes.

exception APIError(faultCode, faultString, **extra)[source]

Bases: xmlrpclib.Fault

APIError exception class

Possible error values
Error Number Message
0000 Invalid command parameters number
0001 The specified passphrase is blank.
0002 The address version number currently must be 3, 4, or 0 (which means auto-select).
0003 The stream number must be 1 (or 0 which means auto-select). Others aren’t supported.
0004 Why would you ask me to generate 0 addresses for you?
0005 You have (accidentally?) specified too many addresses to make. Maximum 999. This check only exists to prevent mischief; if you really want to create more addresses than this, contact the Bitmessage developers and we can modify the check or you can do it yourself by searching the source code for this message.
0006 The encoding type must be 2 or 3.
0007 Could not decode address
0008 Checksum failed for address
0009 Invalid characters in address
0010 Address version number too high (or zero)
0011 The address version number currently must be 2, 3 or 4. Others aren’t supported. Check the address.
0012 The stream number must be 1. Others aren’t supported. Check the address.
0013 Could not find this address in your keys.dat file.
0014 Your fromAddress is disabled. Cannot send.
0015 Invalid ackData object size.
0016 You are already subscribed to that address.
0017 Label is not valid UTF-8 data.
0018 Chan name does not match address.
0019 The length of hash should be 32 bytes (encoded in hex thus 64 characters).
0020 Invalid method:
0021 Unexpected API Failure
0022 Decode error
0023 Bool expected in eighteenByteRipe
0024 Chan address is already present.
0025 Specified address is not a chan address. Use deleteAddress API call instead.
0026 Malformed varint in address:
0027 Message is too long.
class singleAPI(name=None)[source]

Bases: pybitmessage.network.threads.StoppableThread

API thread

name = 'singleAPI'
stopThread()

Stop the thread

run()

The instance of SimpleXMLRPCServer.SimpleXMLRPCServer or jsonrpclib.SimpleJSONRPCServer is created and started here with BMRPCDispatcher dispatcher.

class CommandHandler[source]

Bases: type

The metaclass for BMRPCDispatcher which fills _handlers dict by methods decorated with @command

class command(*aliases)[source]

Bases: object

Decorator for API command method

class BMXMLRPCRequestHandler(request, client_address, server)[source]

Bases: SimpleXMLRPCServer.SimpleXMLRPCRequestHandler

The main API handler

do_POST()

Handles the HTTP POST request.

Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server’s _dispatch method for handling.

Note

this method is the same as in SimpleXMLRPCServer.SimpleXMLRPCRequestHandler, just hacked to handle cookies

APIAuthenticateClient()

Predicate to check for valid API credentials in the request header

class BMRPCDispatcher[source]

Bases: object

This class is used to dispatch API commands

HandleDecodeAddress(address)

Commands: decodeAddress

Decode given address and return dict with status, addressVersion, streamNumber and ripe keys

HandleListAddresses()

Commands: listAddresses, listAddresses2

Returns dict with a list of all used addresses with their properties in the addresses key.

HandleListAddressBookEntries(label=None)

Commands: listAddressBookEntries, legacy:listAddressbook

Returns dict with a list of all address book entries (address and label) in the addresses key.

HandleAddAddressBookEntry(address, label)

Commands: addAddressBookEntry, legacy:addAddressbook

Add an entry to address book. label must be base64 encoded.

HandleDeleteAddressBookEntry(address)

Commands: deleteAddressBookEntry, legacy:deleteAddressbook

Delete an entry from address book.

HandleCreateRandomAddress(label, eighteenByteRipe=False, totalDifficulty=0, smallMessageDifficulty=0)

Commands: createRandomAddress

Create one address using the random number generator.

Parameters:
  • label (str) – base64 encoded label for the address
  • eighteenByteRipe (bool) – is telling Bitmessage whether to generate an address with an 18 byte RIPE hash (as opposed to a 19 byte hash).
HandleCreateDeterministicAddresses(passphrase, numberOfAddresses=1, addressVersionNumber=0, streamNumber=0, eighteenByteRipe=False, totalDifficulty=0, smallMessageDifficulty=0)

Commands: createDeterministicAddresses

Create many addresses deterministically using the passphrase.

Parameters:
  • passphrase (str) – base64 encoded passphrase
  • numberOfAddresses (int) – number of addresses to create, up to 999

addressVersionNumber and streamNumber may be set to 0 which will tell Bitmessage to use the most up-to-date address version and the most available stream.

HandleGetDeterministicAddress(passphrase, addressVersionNumber, streamNumber)

Commands: getDeterministicAddress

Similar to createDeterministicAddresses except that the one address that is returned will not be added to the Bitmessage user interface or the keys.dat file.

HandleCreateChan(passphrase)

Commands: createChan

Creates a new chan. passphrase must be base64 encoded. Returns the corresponding Bitmessage address.

HandleJoinChan(passphrase, suppliedAddress)

Commands: joinChan

Join a chan. passphrase must be base64 encoded. Returns ‘success’.

HandleLeaveChan(address)

Commands: leaveChan

Leave a chan. Returns ‘success’.

Note

at this time, the address is still shown in the UI until a restart.

HandleDeleteAddress(address)

Commands: deleteAddress

Permanently delete the address from keys.dat file. Returns ‘success’.

HandleGetAllInboxMessages()

Commands: getAllInboxMessages

Returns a dict with all inbox messages in the inboxMessages key. The message is a dict with such keys: msgid, toAddress, fromAddress, subject, message, encodingType, receivedTime, read. msgid is hex encoded string. subject and message are base64 encoded.

HandleGetAllInboxMessageIds()

Commands: getAllInboxMessageIds, getAllInboxMessageIDs

The same as getAllInboxMessages but returns only msgid*s, result key - *inboxMessageIds.

HandleGetInboxMessageById(hid, readStatus=None)

Commands: getInboxMessageById, getInboxMessageByID

Returns a dict with list containing single message in the result key inboxMessage. May also return None if message was not found.

Parameters:
  • hid (str) – hex encoded msgid
  • readStatus (bool) – sets the message’s read status if present
HandleGetAllSentMessages()

Commands: getAllSentMessages

The same as getAllInboxMessages but for sent, result key - sentMessages. Message dict keys are: msgid, toAddress, fromAddress, subject, message, encodingType, lastActionTime, status, ackData. ackData is also a hex encoded string.

HandleGetAllSentMessageIds()

Commands: getAllSentMessageIds, getAllSentMessageIDs

The same as getAllInboxMessageIds but for sent, result key - sentMessageIds.

HandleInboxMessagesByReceiver(toAddress)

Commands: getInboxMessagesByReceiver, legacy:getInboxMessagesByAddress

The same as getAllInboxMessages but returns only messages for toAddress.

HandleGetSentMessageById(hid)

Commands: getSentMessageById, getSentMessageByID

Similiar to getInboxMessageById but doesn’t change message’s read status (sent messages have no such field). Result key is sentMessage

HandleGetSentMessagesByAddress(fromAddress)

Commands: getSentMessagesByAddress, getSentMessagesBySender

The same as getAllSentMessages but returns only messages from fromAddress.

HandleGetSentMessagesByAckData(ackData)

Commands: getSentMessageByAckData

Similiar to getSentMessageById but searches by ackdata (also hex encoded).

HandleTrashMessage(msgid)

Commands: trashMessage

Trash message by msgid (encoded in hex). Returns a simple message saying that the message was trashed assuming it ever even existed. Prior existence is not checked.

HandleTrashInboxMessage(msgid)

Commands: trashInboxMessage

Trash inbox message by msgid (encoded in hex).

HandleTrashSentMessage(msgid)

Commands: trashSentMessage

Trash sent message by msgid (encoded in hex).

HandleSendMessage(toAddress, fromAddress, subject, message, encodingType=2, TTL=345600)

Commands: sendMessage

Send the message and return ackdata (hex encoded string). subject and message must be encoded in base64 which may optionally include line breaks. TTL is specified in seconds; values outside the bounds of 3600 to 2419200 will be moved to be within those bounds. TTL defaults to 4 days.

HandleSendBroadcast(fromAddress, subject, message, encodingType=2, TTL=345600)

Commands: sendBroadcast

Send the broadcast message. Similiar to sendMessage.

HandleGetStatus(ackdata)

Commands: getStatus

Get the status of sent message by its ackdata (hex encoded). Returns one of these strings: notfound, msgqueued, broadcastqueued, broadcastsent, doingpubkeypow, awaitingpubkey, doingmsgpow, forcepow, msgsent, msgsentnoackexpected or ackreceived.

HandleAddSubscription(address, label='')

Commands: addSubscription

Subscribe to the address. label must be base64 encoded.

HandleDeleteSubscription(address)

Commands: deleteSubscription

Unsubscribe from the address. The program does not check whether you were subscribed in the first place.

ListSubscriptions()

Commands: listSubscriptions

Returns dict with a list of all subscriptions in the subscriptions key.

HandleDisseminatePreEncryptedMsg(encryptedPayload, requiredAverageProofOfWorkNonceTrialsPerByte, requiredPayloadLengthExtraBytes)

Commands: disseminatePreEncryptedMsg

Handle a request to disseminate an encrypted message

HandleTrashSentMessageByAckDAta(ackdata)

Commands: trashSentMessageByAckData

Trash a sent message by ackdata (hex encoded)

HandleDissimatePubKey(payload)

Commands: disseminatePubkey

Handle a request to disseminate a public key

HandleGetMessageDataByDestinationHash(requestedHash)

Commands: getMessageDataByDestinationHash, getMessageDataByDestinationTag

Handle a request to get message data by destination hash

HandleClientStatus()

Commands: clientStatus

Returns the bitmessage status as dict with keys networkConnections, numberOfMessagesProcessed, numberOfBroadcastsProcessed, numberOfPubkeysProcessed, pendingDownload, networkStatus, softwareName, softwareVersion. networkStatus will be one of these strings: “notConnected”, “connectedButHaveNotReceivedIncomingConnections”, or “connectedAndReceivingIncomingConnections”.

HandleHelloWorld(a, b)

Commands: helloWorld

Test two string params

HandleAdd(a, b)

Commands: add

Test two numeric params

HandleStatusBar(message)

Commands: statusBar

Update GUI statusbar message

HandleDeleteAndVacuum()

Commands: deleteAndVacuum

Cleanup trashes and vacuum messages database

HandleShutdown()

Commands: shutdown

Shutdown the bitmessage. Returns ‘done’.

config = <pybitmessage.bmconfigparser.BMConfigParser instance>