Move API code to api.py #609

Merged
Atheros1 merged 7 commits from master into master 2014-01-13 01:58:07 +01:00
2 changed files with 913 additions and 912 deletions
Showing only changes of commit 0b81e9b206 - Show all commits

View File

@ -1,911 +1,912 @@
# Copyright (c) 2012-2014 Jonathan Warren # Copyright (c) 2012-2014 Jonathan Warren
# Copyright (c) 2012-2014 The Bitmessage developers # Copyright (c) 2012-2014 The Bitmessage developers
comment= """ comment= """
This is not what you run to run the Bitmessage API. Instead, enable daemon mode This is not what you run to run the Bitmessage API. Instead, enable the API
( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py. ( https://bitmessage.org/wiki/API ) and optionally enable daemon mode
""" ( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py.
"""
if __name__ == "__main__":
print comment if __name__ == "__main__":
import sys print comment
sys.exit(0) import sys
sys.exit(0)
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import json from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import json
import shared
import time import shared
from addresses import decodeAddress,addBMIfNotPresent,decodeVarint,calculateInventoryHash import time
import helper_inbox from addresses import decodeAddress,addBMIfNotPresent,decodeVarint,calculateInventoryHash
import helper_sent import helper_inbox
import hashlib import helper_sent
import hashlib
from pyelliptic.openssl import OpenSSL
from struct import pack from pyelliptic.openssl import OpenSSL
from struct import pack
# Classes
from helper_sql import sqlQuery,sqlExecute,SqlBulkExecute # Classes
from debug import logger from helper_sql import sqlQuery,sqlExecute,SqlBulkExecute
from debug import logger
# Helper Functions
import proofofwork # Helper Functions
import proofofwork
str_chan = '[chan]'
str_chan = '[chan]'
class APIError(Exception):
def __init__(self, error_number, error_message): class APIError(Exception):
super(APIError, self).__init__() def __init__(self, error_number, error_message):
self.error_number = error_number super(APIError, self).__init__()
self.error_message = error_message self.error_number = error_number
def __str__(self): self.error_message = error_message
return "API Error %04i: %s" % (self.error_number, self.error_message) def __str__(self):
return "API Error %04i: %s" % (self.error_number, self.error_message)
# This is one of several classes that constitute the API
# This class was written by Vaibhav Bhatia. Modified by Jonathan Warren (Atheros). # This is one of several classes that constitute the API
# http://code.activestate.com/recipes/501148-xmlrpc-serverclient-which-does-cookie-handling-and/ # This class was written by Vaibhav Bhatia. Modified by Jonathan Warren (Atheros).
class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): # http://code.activestate.com/recipes/501148-xmlrpc-serverclient-which-does-cookie-handling-and/
class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
def do_POST(self):
# Handles the HTTP POST request. def do_POST(self):
# Attempts to interpret all HTTP POST requests as XML-RPC calls, # Handles the HTTP POST request.
# which are forwarded to the server's _dispatch method for handling. # 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 SimpleXMLRPCRequestHandler,
# just hacked to handle cookies # Note: this method is the same as in SimpleXMLRPCRequestHandler,
# just hacked to handle cookies
# Check that the path is legal
if not self.is_rpc_path_valid(): # Check that the path is legal
self.report_404() if not self.is_rpc_path_valid():
return self.report_404()
return
try:
# Get arguments by reading body of request. try:
# We read this in chunks to avoid straining # Get arguments by reading body of request.
# socket.read(); around the 10 or 15Mb mark, some platforms # We read this in chunks to avoid straining
# begin to have problems (bug #792570). # socket.read(); around the 10 or 15Mb mark, some platforms
max_chunk_size = 10 * 1024 * 1024 # begin to have problems (bug #792570).
size_remaining = int(self.headers["content-length"]) max_chunk_size = 10 * 1024 * 1024
L = [] size_remaining = int(self.headers["content-length"])
while size_remaining: L = []
chunk_size = min(size_remaining, max_chunk_size) while size_remaining:
L.append(self.rfile.read(chunk_size)) chunk_size = min(size_remaining, max_chunk_size)
size_remaining -= len(L[-1]) L.append(self.rfile.read(chunk_size))
data = ''.join(L) size_remaining -= len(L[-1])
data = ''.join(L)
# In previous versions of SimpleXMLRPCServer, _dispatch
# could be overridden in this class, instead of in # In previous versions of SimpleXMLRPCServer, _dispatch
# SimpleXMLRPCDispatcher. To maintain backwards compatibility, # could be overridden in this class, instead of in
# check to see if a subclass implements _dispatch and dispatch # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
# using that method if present. # check to see if a subclass implements _dispatch and dispatch
response = self.server._marshaled_dispatch( # using that method if present.
data, getattr(self, '_dispatch', None) response = self.server._marshaled_dispatch(
) data, getattr(self, '_dispatch', None)
except: # This should only happen if the module is buggy )
# internal error, report as HTTP server error except: # This should only happen if the module is buggy
self.send_response(500) # internal error, report as HTTP server error
self.end_headers() self.send_response(500)
else: self.end_headers()
# got a valid XML RPC response else:
self.send_response(200) # got a valid XML RPC response
self.send_header("Content-type", "text/xml") self.send_response(200)
self.send_header("Content-length", str(len(response))) self.send_header("Content-type", "text/xml")
self.send_header("Content-length", str(len(response)))
# HACK :start -> sends cookies here
if self.cookies: # HACK :start -> sends cookies here
for cookie in self.cookies: if self.cookies:
self.send_header('Set-Cookie', cookie.output(header='')) for cookie in self.cookies:
# HACK :end self.send_header('Set-Cookie', cookie.output(header=''))
# HACK :end
self.end_headers()
self.wfile.write(response) self.end_headers()
self.wfile.write(response)
# shut down the connection
self.wfile.flush() # shut down the connection
self.connection.shutdown(1) self.wfile.flush()
self.connection.shutdown(1)
def APIAuthenticateClient(self):
if 'Authorization' in self.headers: def APIAuthenticateClient(self):
# handle Basic authentication if 'Authorization' in self.headers:
(enctype, encstr) = self.headers.get('Authorization').split() # handle Basic authentication
(emailid, password) = encstr.decode('base64').split(':') (enctype, encstr) = self.headers.get('Authorization').split()
if emailid == shared.config.get('bitmessagesettings', 'apiusername') and password == shared.config.get('bitmessagesettings', 'apipassword'): (emailid, password) = encstr.decode('base64').split(':')
return True if emailid == shared.config.get('bitmessagesettings', 'apiusername') and password == shared.config.get('bitmessagesettings', 'apipassword'):
else: return True
return False else:
else: return False
logger.warn('Authentication failed because header lacks Authentication field') else:
time.sleep(2) logger.warn('Authentication failed because header lacks Authentication field')
return False time.sleep(2)
return False
return False
return False
def _decode(self, text, decode_type):
try: def _decode(self, text, decode_type):
return text.decode(decode_type) try:
except Exception as e: return text.decode(decode_type)
raise APIError(22, "Decode error - " + str(e) + ". Had trouble while decoding string: " + repr(text)) except Exception as e:
raise APIError(22, "Decode error - " + str(e) + ". Had trouble while decoding string: " + repr(text))
def _verifyAddress(self, address):
status, addressVersionNumber, streamNumber, ripe = decodeAddress(address) def _verifyAddress(self, address):
if status != 'success': status, addressVersionNumber, streamNumber, ripe = decodeAddress(address)
logger.warn('API Error 0007: Could not decode address %s. Status: %s.', address, status) if status != 'success':
logger.warn('API Error 0007: Could not decode address %s. Status: %s.', address, status)
if status == 'checksumfailed':
raise APIError(8, 'Checksum failed for address: ' + address) if status == 'checksumfailed':
if status == 'invalidcharacters': raise APIError(8, 'Checksum failed for address: ' + address)
raise APIError(9, 'Invalid characters in address: ' + address) if status == 'invalidcharacters':
if status == 'versiontoohigh': raise APIError(9, 'Invalid characters in address: ' + address)
raise APIError(10, 'Address version number too high (or zero) in address: ' + address) if status == 'versiontoohigh':
raise APIError(7, 'Could not decode address: ' + address + ' : ' + status) raise APIError(10, 'Address version number too high (or zero) in address: ' + address)
if addressVersionNumber < 2 or addressVersionNumber > 4: raise APIError(7, 'Could not decode address: ' + address + ' : ' + status)
raise APIError(11, 'The address version number currently must be 2, 3 or 4. Others aren\'t supported. Check the address.') if addressVersionNumber < 2 or addressVersionNumber > 4:
if streamNumber != 1: raise APIError(11, 'The address version number currently must be 2, 3 or 4. Others aren\'t supported. Check the address.')
raise APIError(12, 'The stream number must be 1. Others aren\'t supported. Check the address.') if streamNumber != 1:
raise APIError(12, 'The stream number must be 1. Others aren\'t supported. Check the address.')
return (status, addressVersionNumber, streamNumber, ripe)
return (status, addressVersionNumber, streamNumber, ripe)
def _handle_request(self, method, params):
if method == 'helloWorld': def _handle_request(self, method, params):
(a, b) = params if method == 'helloWorld':
return a + '-' + b (a, b) = params
elif method == 'add': return a + '-' + b
(a, b) = params elif method == 'add':
return a + b (a, b) = params
elif method == 'statusBar': return a + b
message, = params elif method == 'statusBar':
shared.UISignalQueue.put(('updateStatusBar', message)) message, = params
elif method == 'listAddresses' or method == 'listAddresses2': shared.UISignalQueue.put(('updateStatusBar', message))
data = '{"addresses":[' elif method == 'listAddresses' or method == 'listAddresses2':
configSections = shared.config.sections() data = '{"addresses":['
for addressInKeysFile in configSections: configSections = shared.config.sections()
if addressInKeysFile != 'bitmessagesettings': for addressInKeysFile in configSections:
status, addressVersionNumber, streamNumber, hash01 = decodeAddress( if addressInKeysFile != 'bitmessagesettings':
addressInKeysFile) status, addressVersionNumber, streamNumber, hash01 = decodeAddress(
if len(data) > 20: addressInKeysFile)
data += ',' if len(data) > 20:
if shared.config.has_option(addressInKeysFile, 'chan'): data += ','
chan = shared.config.getboolean(addressInKeysFile, 'chan') if shared.config.has_option(addressInKeysFile, 'chan'):
else: chan = shared.config.getboolean(addressInKeysFile, 'chan')
chan = False else:
label = shared.config.get(addressInKeysFile, 'label') chan = False
if method == 'listAddresses2': label = shared.config.get(addressInKeysFile, 'label')
label = label.encode('base64') if method == 'listAddresses2':
data += json.dumps({'label': label, 'address': addressInKeysFile, 'stream': label = label.encode('base64')
streamNumber, 'enabled': shared.config.getboolean(addressInKeysFile, 'enabled'), 'chan': chan}, indent=4, separators=(',', ': ')) data += json.dumps({'label': label, 'address': addressInKeysFile, 'stream':
data += ']}' streamNumber, 'enabled': shared.config.getboolean(addressInKeysFile, 'enabled'), 'chan': chan}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'listAddressBookEntries' or method == 'listAddressbook': # the listAddressbook alias should be removed eventually. return data
queryreturn = sqlQuery('''SELECT label, address from addressbook''') elif method == 'listAddressBookEntries' or method == 'listAddressbook': # the listAddressbook alias should be removed eventually.
data = '{"addresses":[' queryreturn = sqlQuery('''SELECT label, address from addressbook''')
for row in queryreturn: data = '{"addresses":['
label, address = row for row in queryreturn:
label = shared.fixPotentiallyInvalidUTF8Data(label) label, address = row
if len(data) > 20: label = shared.fixPotentiallyInvalidUTF8Data(label)
data += ',' if len(data) > 20:
data += json.dumps({'label':label.encode('base64'), 'address': address}, indent=4, separators=(',', ': ')) data += ','
data += ']}' data += json.dumps({'label':label.encode('base64'), 'address': address}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'addAddressBookEntry' or method == 'addAddressbook': # the addAddressbook alias should be deleted eventually. return data
if len(params) != 2: elif method == 'addAddressBookEntry' or method == 'addAddressbook': # the addAddressbook alias should be deleted eventually.
raise APIError(0, "I need label and address") if len(params) != 2:
address, label = params raise APIError(0, "I need label and address")
label = self._decode(label, "base64") address, label = params
address = addBMIfNotPresent(address) label = self._decode(label, "base64")
self._verifyAddress(address) address = addBMIfNotPresent(address)
queryreturn = sqlQuery("SELECT address FROM addressbook WHERE address=?", address) self._verifyAddress(address)
if queryreturn != []: queryreturn = sqlQuery("SELECT address FROM addressbook WHERE address=?", address)
raise APIError(16, 'You already have this address in your address book.') if queryreturn != []:
raise APIError(16, 'You already have this address in your address book.')
sqlExecute("INSERT INTO addressbook VALUES(?,?)", label, address)
shared.UISignalQueue.put(('rerenderInboxFromLabels','')) sqlExecute("INSERT INTO addressbook VALUES(?,?)", label, address)
shared.UISignalQueue.put(('rerenderSentToLabels','')) shared.UISignalQueue.put(('rerenderInboxFromLabels',''))
shared.UISignalQueue.put(('rerenderAddressBook','')) shared.UISignalQueue.put(('rerenderSentToLabels',''))
return "Added address %s to address book" % address shared.UISignalQueue.put(('rerenderAddressBook',''))
elif method == 'deleteAddressBookEntry' or method == 'deleteAddressbook': # The deleteAddressbook alias should be deleted eventually. return "Added address %s to address book" % address
if len(params) != 1: elif method == 'deleteAddressBookEntry' or method == 'deleteAddressbook': # The deleteAddressbook alias should be deleted eventually.
raise APIError(0, "I need an address") if len(params) != 1:
address, = params raise APIError(0, "I need an address")
address = addBMIfNotPresent(address) address, = params
self._verifyAddress(address) address = addBMIfNotPresent(address)
sqlExecute('DELETE FROM addressbook WHERE address=?', address) self._verifyAddress(address)
shared.UISignalQueue.put(('rerenderInboxFromLabels','')) sqlExecute('DELETE FROM addressbook WHERE address=?', address)
shared.UISignalQueue.put(('rerenderSentToLabels','')) shared.UISignalQueue.put(('rerenderInboxFromLabels',''))
shared.UISignalQueue.put(('rerenderAddressBook','')) shared.UISignalQueue.put(('rerenderSentToLabels',''))
return "Deleted address book entry for %s if it existed" % address shared.UISignalQueue.put(('rerenderAddressBook',''))
elif method == 'createRandomAddress': return "Deleted address book entry for %s if it existed" % address
if len(params) == 0: elif method == 'createRandomAddress':
raise APIError(0, 'I need parameters!') if len(params) == 0:
elif len(params) == 1: raise APIError(0, 'I need parameters!')
label, = params elif len(params) == 1:
eighteenByteRipe = False label, = params
nonceTrialsPerByte = shared.config.get( eighteenByteRipe = False
'bitmessagesettings', 'defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get( 'bitmessagesettings', 'defaultnoncetrialsperbyte')
'bitmessagesettings', 'defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.get(
elif len(params) == 2: 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
label, eighteenByteRipe = params elif len(params) == 2:
nonceTrialsPerByte = shared.config.get( label, eighteenByteRipe = params
'bitmessagesettings', 'defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get( 'bitmessagesettings', 'defaultnoncetrialsperbyte')
'bitmessagesettings', 'defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.get(
elif len(params) == 3: 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
label, eighteenByteRipe, totalDifficulty = params elif len(params) == 3:
nonceTrialsPerByte = int( label, eighteenByteRipe, totalDifficulty = params
shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) nonceTrialsPerByte = int(
payloadLengthExtraBytes = shared.config.get( shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
'bitmessagesettings', 'defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.get(
elif len(params) == 4: 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
label, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params elif len(params) == 4:
nonceTrialsPerByte = int( label, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params
shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) nonceTrialsPerByte = int(
payloadLengthExtraBytes = int( shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty) payloadLengthExtraBytes = int(
else: shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty)
raise APIError(0, 'Too many parameters!') else:
label = self._decode(label, "base64") raise APIError(0, 'Too many parameters!')
try: label = self._decode(label, "base64")
unicode(label, 'utf-8') try:
except: unicode(label, 'utf-8')
raise APIError(17, 'Label is not valid UTF-8 data.') except:
shared.apiAddressGeneratorReturnQueue.queue.clear() raise APIError(17, 'Label is not valid UTF-8 data.')
streamNumberForAddress = 1 shared.apiAddressGeneratorReturnQueue.queue.clear()
shared.addressGeneratorQueue.put(( streamNumberForAddress = 1
'createRandomAddress', 4, streamNumberForAddress, label, 1, "", eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes)) shared.addressGeneratorQueue.put((
return shared.apiAddressGeneratorReturnQueue.get() 'createRandomAddress', 4, streamNumberForAddress, label, 1, "", eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes))
elif method == 'createDeterministicAddresses': return shared.apiAddressGeneratorReturnQueue.get()
if len(params) == 0: elif method == 'createDeterministicAddresses':
raise APIError(0, 'I need parameters!') if len(params) == 0:
elif len(params) == 1: raise APIError(0, 'I need parameters!')
passphrase, = params elif len(params) == 1:
numberOfAddresses = 1 passphrase, = params
addressVersionNumber = 0 numberOfAddresses = 1
streamNumber = 0 addressVersionNumber = 0
eighteenByteRipe = False streamNumber = 0
nonceTrialsPerByte = shared.config.get( eighteenByteRipe = False
'bitmessagesettings', 'defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get( 'bitmessagesettings', 'defaultnoncetrialsperbyte')
'bitmessagesettings', 'defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.get(
elif len(params) == 2: 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
passphrase, numberOfAddresses = params elif len(params) == 2:
addressVersionNumber = 0 passphrase, numberOfAddresses = params
streamNumber = 0 addressVersionNumber = 0
eighteenByteRipe = False streamNumber = 0
nonceTrialsPerByte = shared.config.get( eighteenByteRipe = False
'bitmessagesettings', 'defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get( 'bitmessagesettings', 'defaultnoncetrialsperbyte')
'bitmessagesettings', 'defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.get(
elif len(params) == 3: 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
passphrase, numberOfAddresses, addressVersionNumber = params elif len(params) == 3:
streamNumber = 0 passphrase, numberOfAddresses, addressVersionNumber = params
eighteenByteRipe = False streamNumber = 0
nonceTrialsPerByte = shared.config.get( eighteenByteRipe = False
'bitmessagesettings', 'defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get( 'bitmessagesettings', 'defaultnoncetrialsperbyte')
'bitmessagesettings', 'defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.get(
elif len(params) == 4: 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
passphrase, numberOfAddresses, addressVersionNumber, streamNumber = params elif len(params) == 4:
eighteenByteRipe = False passphrase, numberOfAddresses, addressVersionNumber, streamNumber = params
nonceTrialsPerByte = shared.config.get( eighteenByteRipe = False
'bitmessagesettings', 'defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get( 'bitmessagesettings', 'defaultnoncetrialsperbyte')
'bitmessagesettings', 'defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.get(
elif len(params) == 5: 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe = params elif len(params) == 5:
nonceTrialsPerByte = shared.config.get( passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe = params
'bitmessagesettings', 'defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get( 'bitmessagesettings', 'defaultnoncetrialsperbyte')
'bitmessagesettings', 'defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.get(
elif len(params) == 6: 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty = params elif len(params) == 6:
nonceTrialsPerByte = int( passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty = params
shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) nonceTrialsPerByte = int(
payloadLengthExtraBytes = shared.config.get( shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
'bitmessagesettings', 'defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.get(
elif len(params) == 7: 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params elif len(params) == 7:
nonceTrialsPerByte = int( passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params
shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) nonceTrialsPerByte = int(
payloadLengthExtraBytes = int( shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty) payloadLengthExtraBytes = int(
else: shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty)
raise APIError(0, 'Too many parameters!') else:
if len(passphrase) == 0: raise APIError(0, 'Too many parameters!')
raise APIError(1, 'The specified passphrase is blank.') if len(passphrase) == 0:
if not isinstance(eighteenByteRipe, bool): raise APIError(1, 'The specified passphrase is blank.')
raise APIError(23, 'Bool expected in eighteenByteRipe, saw %s instead' % type(eighteenByteRipe)) if not isinstance(eighteenByteRipe, bool):
passphrase = self._decode(passphrase, "base64") raise APIError(23, 'Bool expected in eighteenByteRipe, saw %s instead' % type(eighteenByteRipe))
if addressVersionNumber == 0: # 0 means "just use the proper addressVersionNumber" passphrase = self._decode(passphrase, "base64")
addressVersionNumber = 4 if addressVersionNumber == 0: # 0 means "just use the proper addressVersionNumber"
if addressVersionNumber != 3 and addressVersionNumber != 4: addressVersionNumber = 4
raise APIError(2,'The address version number currently must be 3, 4, or 0 (which means auto-select). ' + addressVersionNumber + ' isn\'t supported.') if addressVersionNumber != 3 and addressVersionNumber != 4:
if streamNumber == 0: # 0 means "just use the most available stream" raise APIError(2,'The address version number currently must be 3, 4, or 0 (which means auto-select). ' + addressVersionNumber + ' isn\'t supported.')
streamNumber = 1 if streamNumber == 0: # 0 means "just use the most available stream"
if streamNumber != 1: streamNumber = 1
raise APIError(3,'The stream number must be 1 (or 0 which means auto-select). Others aren\'t supported.') if streamNumber != 1:
if numberOfAddresses == 0: raise APIError(3,'The stream number must be 1 (or 0 which means auto-select). Others aren\'t supported.')
raise APIError(4, 'Why would you ask me to generate 0 addresses for you?') if numberOfAddresses == 0:
if numberOfAddresses > 999: raise APIError(4, 'Why would you ask me to generate 0 addresses for you?')
raise APIError(5, '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.') if numberOfAddresses > 999:
shared.apiAddressGeneratorReturnQueue.queue.clear() raise APIError(5, '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.')
logger.debug('Requesting that the addressGenerator create %s addresses.', numberOfAddresses) shared.apiAddressGeneratorReturnQueue.queue.clear()
shared.addressGeneratorQueue.put( logger.debug('Requesting that the addressGenerator create %s addresses.', numberOfAddresses)
('createDeterministicAddresses', addressVersionNumber, streamNumber, shared.addressGeneratorQueue.put(
'unused API address', numberOfAddresses, passphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes)) ('createDeterministicAddresses', addressVersionNumber, streamNumber,
data = '{"addresses":[' 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes))
queueReturn = shared.apiAddressGeneratorReturnQueue.get() data = '{"addresses":['
for item in queueReturn: queueReturn = shared.apiAddressGeneratorReturnQueue.get()
if len(data) > 20: for item in queueReturn:
data += ',' if len(data) > 20:
data += "\"" + item + "\"" data += ','
data += ']}' data += "\"" + item + "\""
return data data += ']}'
elif method == 'getDeterministicAddress': return data
if len(params) != 3: elif method == 'getDeterministicAddress':
raise APIError(0, 'I need exactly 3 parameters.') if len(params) != 3:
passphrase, addressVersionNumber, streamNumber = params raise APIError(0, 'I need exactly 3 parameters.')
numberOfAddresses = 1 passphrase, addressVersionNumber, streamNumber = params
eighteenByteRipe = False numberOfAddresses = 1
if len(passphrase) == 0: eighteenByteRipe = False
raise APIError(1, 'The specified passphrase is blank.') if len(passphrase) == 0:
passphrase = self._decode(passphrase, "base64") raise APIError(1, 'The specified passphrase is blank.')
if addressVersionNumber != 3 and addressVersionNumber != 4: passphrase = self._decode(passphrase, "base64")
raise APIError(2, 'The address version number currently must be 3 or 4. ' + addressVersionNumber + ' isn\'t supported.') if addressVersionNumber != 3 and addressVersionNumber != 4:
if streamNumber != 1: raise APIError(2, 'The address version number currently must be 3 or 4. ' + addressVersionNumber + ' isn\'t supported.')
raise APIError(3, ' The stream number must be 1. Others aren\'t supported.') if streamNumber != 1:
shared.apiAddressGeneratorReturnQueue.queue.clear() raise APIError(3, ' The stream number must be 1. Others aren\'t supported.')
logger.debug('Requesting that the addressGenerator create %s addresses.', numberOfAddresses) shared.apiAddressGeneratorReturnQueue.queue.clear()
shared.addressGeneratorQueue.put( logger.debug('Requesting that the addressGenerator create %s addresses.', numberOfAddresses)
('getDeterministicAddress', addressVersionNumber, shared.addressGeneratorQueue.put(
streamNumber, 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe)) ('getDeterministicAddress', addressVersionNumber,
return shared.apiAddressGeneratorReturnQueue.get() streamNumber, 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe))
return shared.apiAddressGeneratorReturnQueue.get()
elif method == 'createChan':
if len(params) == 0: elif method == 'createChan':
raise APIError(0, 'I need parameters.') if len(params) == 0:
elif len(params) == 1: raise APIError(0, 'I need parameters.')
passphrase, = params elif len(params) == 1:
passphrase = self._decode(passphrase, "base64") passphrase, = params
if len(passphrase) == 0: passphrase = self._decode(passphrase, "base64")
raise APIError(1, 'The specified passphrase is blank.') if len(passphrase) == 0:
# It would be nice to make the label the passphrase but it is raise APIError(1, 'The specified passphrase is blank.')
# possible that the passphrase contains non-utf-8 characters. # It would be nice to make the label the passphrase but it is
try: # possible that the passphrase contains non-utf-8 characters.
unicode(passphrase, 'utf-8') try:
label = str_chan + ' ' + passphrase unicode(passphrase, 'utf-8')
except: label = str_chan + ' ' + passphrase
label = str_chan + ' ' + repr(passphrase) except:
label = str_chan + ' ' + repr(passphrase)
addressVersionNumber = 4
streamNumber = 1 addressVersionNumber = 4
shared.apiAddressGeneratorReturnQueue.queue.clear() streamNumber = 1
logger.debug('Requesting that the addressGenerator create chan %s.', passphrase) shared.apiAddressGeneratorReturnQueue.queue.clear()
shared.addressGeneratorQueue.put(('createChan', addressVersionNumber, streamNumber, label, passphrase)) logger.debug('Requesting that the addressGenerator create chan %s.', passphrase)
queueReturn = shared.apiAddressGeneratorReturnQueue.get() shared.addressGeneratorQueue.put(('createChan', addressVersionNumber, streamNumber, label, passphrase))
if len(queueReturn) == 0: queueReturn = shared.apiAddressGeneratorReturnQueue.get()
raise APIError(24, 'Chan address is already present.') if len(queueReturn) == 0:
address = queueReturn[0] raise APIError(24, 'Chan address is already present.')
return address address = queueReturn[0]
elif method == 'joinChan': return address
if len(params) < 2: elif method == 'joinChan':
raise APIError(0, 'I need two parameters.') if len(params) < 2:
elif len(params) == 2: raise APIError(0, 'I need two parameters.')
passphrase, suppliedAddress= params elif len(params) == 2:
passphrase = self._decode(passphrase, "base64") passphrase, suppliedAddress= params
if len(passphrase) == 0: passphrase = self._decode(passphrase, "base64")
raise APIError(1, 'The specified passphrase is blank.') if len(passphrase) == 0:
# It would be nice to make the label the passphrase but it is raise APIError(1, 'The specified passphrase is blank.')
# possible that the passphrase contains non-utf-8 characters. # It would be nice to make the label the passphrase but it is
try: # possible that the passphrase contains non-utf-8 characters.
unicode(passphrase, 'utf-8') try:
label = str_chan + ' ' + passphrase unicode(passphrase, 'utf-8')
except: label = str_chan + ' ' + passphrase
label = str_chan + ' ' + repr(passphrase) except:
label = str_chan + ' ' + repr(passphrase)
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(suppliedAddress)
suppliedAddress = addBMIfNotPresent(suppliedAddress) status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(suppliedAddress)
shared.apiAddressGeneratorReturnQueue.queue.clear() suppliedAddress = addBMIfNotPresent(suppliedAddress)
shared.addressGeneratorQueue.put(('joinChan', suppliedAddress, label, passphrase)) shared.apiAddressGeneratorReturnQueue.queue.clear()
addressGeneratorReturnValue = shared.apiAddressGeneratorReturnQueue.get() shared.addressGeneratorQueue.put(('joinChan', suppliedAddress, label, passphrase))
addressGeneratorReturnValue = shared.apiAddressGeneratorReturnQueue.get()
if addressGeneratorReturnValue == 'chan name does not match address':
raise APIError(18, 'Chan name does not match address.') if addressGeneratorReturnValue == 'chan name does not match address':
if len(addressGeneratorReturnValue) == 0: raise APIError(18, 'Chan name does not match address.')
raise APIError(24, 'Chan address is already present.') if len(addressGeneratorReturnValue) == 0:
#TODO: this variable is not used to anything raise APIError(24, 'Chan address is already present.')
createdAddress = addressGeneratorReturnValue[0] # in case we ever want it for anything. #TODO: this variable is not used to anything
return "success" createdAddress = addressGeneratorReturnValue[0] # in case we ever want it for anything.
elif method == 'leaveChan': return "success"
if len(params) == 0: elif method == 'leaveChan':
raise APIError(0, 'I need parameters.') if len(params) == 0:
elif len(params) == 1: raise APIError(0, 'I need parameters.')
address, = params elif len(params) == 1:
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address) address, = params
address = addBMIfNotPresent(address) status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
if not shared.config.has_section(address): address = addBMIfNotPresent(address)
raise APIError(13, 'Could not find this address in your keys.dat file.') if not shared.config.has_section(address):
if not shared.safeConfigGetBoolean(address, 'chan'): raise APIError(13, 'Could not find this address in your keys.dat file.')
raise APIError(25, 'Specified address is not a chan address. Use deleteAddress API call instead.') if not shared.safeConfigGetBoolean(address, 'chan'):
shared.config.remove_section(address) raise APIError(25, 'Specified address is not a chan address. Use deleteAddress API call instead.')
with open(shared.appdata + 'keys.dat', 'wb') as configfile: shared.config.remove_section(address)
shared.config.write(configfile) with open(shared.appdata + 'keys.dat', 'wb') as configfile:
return 'success' shared.config.write(configfile)
return 'success'
elif method == 'deleteAddress':
if len(params) == 0: elif method == 'deleteAddress':
raise APIError(0, 'I need parameters.') if len(params) == 0:
elif len(params) == 1: raise APIError(0, 'I need parameters.')
address, = params elif len(params) == 1:
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address) address, = params
address = addBMIfNotPresent(address) status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
if not shared.config.has_section(address): address = addBMIfNotPresent(address)
raise APIError(13, 'Could not find this address in your keys.dat file.') if not shared.config.has_section(address):
shared.config.remove_section(address) raise APIError(13, 'Could not find this address in your keys.dat file.')
with open(shared.appdata + 'keys.dat', 'wb') as configfile: shared.config.remove_section(address)
shared.config.write(configfile) with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.UISignalQueue.put(('rerenderInboxFromLabels','')) shared.config.write(configfile)
shared.UISignalQueue.put(('rerenderSentToLabels','')) shared.UISignalQueue.put(('rerenderInboxFromLabels',''))
shared.reloadMyAddressHashes() shared.UISignalQueue.put(('rerenderSentToLabels',''))
return 'success' shared.reloadMyAddressHashes()
return 'success'
elif method == 'getAllInboxMessages':
queryreturn = sqlQuery( elif method == 'getAllInboxMessages':
'''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype, read FROM inbox where folder='inbox' ORDER BY received''') queryreturn = sqlQuery(
data = '{"inboxMessages":[' '''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype, read FROM inbox where folder='inbox' ORDER BY received''')
for row in queryreturn: data = '{"inboxMessages":['
msgid, toAddress, fromAddress, subject, received, message, encodingtype, read = row for row in queryreturn:
subject = shared.fixPotentiallyInvalidUTF8Data(subject) msgid, toAddress, fromAddress, subject, received, message, encodingtype, read = row
message = shared.fixPotentiallyInvalidUTF8Data(message) subject = shared.fixPotentiallyInvalidUTF8Data(subject)
if len(data) > 25: message = shared.fixPotentiallyInvalidUTF8Data(message)
data += ',' if len(data) > 25:
data += json.dumps({'msgid': msgid.encode('hex'), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': subject.encode( data += ','
'base64'), 'message': message.encode('base64'), 'encodingType': encodingtype, 'receivedTime': received, 'read': read}, indent=4, separators=(',', ': ')) data += json.dumps({'msgid': msgid.encode('hex'), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': subject.encode(
data += ']}' 'base64'), 'message': message.encode('base64'), 'encodingType': encodingtype, 'receivedTime': received, 'read': read}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'getAllInboxMessageIds' or method == 'getAllInboxMessageIDs': return data
queryreturn = sqlQuery( elif method == 'getAllInboxMessageIds' or method == 'getAllInboxMessageIDs':
'''SELECT msgid FROM inbox where folder='inbox' ORDER BY received''') queryreturn = sqlQuery(
data = '{"inboxMessageIds":[' '''SELECT msgid FROM inbox where folder='inbox' ORDER BY received''')
for row in queryreturn: data = '{"inboxMessageIds":['
msgid = row[0] for row in queryreturn:
if len(data) > 25: msgid = row[0]
data += ',' if len(data) > 25:
data += json.dumps({'msgid': msgid.encode('hex')}, indent=4, separators=(',', ': ')) data += ','
data += ']}' data += json.dumps({'msgid': msgid.encode('hex')}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'getInboxMessageById' or method == 'getInboxMessageByID': return data
if len(params) == 0: elif method == 'getInboxMessageById' or method == 'getInboxMessageByID':
raise APIError(0, 'I need parameters!') if len(params) == 0:
elif len(params) == 1: raise APIError(0, 'I need parameters!')
msgid = self._decode(params[0], "hex") elif len(params) == 1:
elif len(params) >= 2: msgid = self._decode(params[0], "hex")
msgid = self._decode(params[0], "hex") elif len(params) >= 2:
readStatus = params[1] msgid = self._decode(params[0], "hex")
if not isinstance(readStatus, bool): readStatus = params[1]
raise APIError(23, 'Bool expected in readStatus, saw %s instead.' % type(readStatus)) if not isinstance(readStatus, bool):
queryreturn = sqlQuery('''SELECT read FROM inbox WHERE msgid=?''', msgid) raise APIError(23, 'Bool expected in readStatus, saw %s instead.' % type(readStatus))
# UPDATE is slow, only update if status is different queryreturn = sqlQuery('''SELECT read FROM inbox WHERE msgid=?''', msgid)
if queryreturn != [] and (queryreturn[0][0] == 1) != readStatus: # UPDATE is slow, only update if status is different
sqlExecute('''UPDATE inbox set read = ? WHERE msgid=?''', readStatus, msgid) if queryreturn != [] and (queryreturn[0][0] == 1) != readStatus:
shared.UISignalQueue.put(('changedInboxUnread', None)) sqlExecute('''UPDATE inbox set read = ? WHERE msgid=?''', readStatus, msgid)
queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype, read FROM inbox WHERE msgid=?''', msgid) shared.UISignalQueue.put(('changedInboxUnread', None))
data = '{"inboxMessage":[' queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype, read FROM inbox WHERE msgid=?''', msgid)
for row in queryreturn: data = '{"inboxMessage":['
msgid, toAddress, fromAddress, subject, received, message, encodingtype, read = row for row in queryreturn:
subject = shared.fixPotentiallyInvalidUTF8Data(subject) msgid, toAddress, fromAddress, subject, received, message, encodingtype, read = row
message = shared.fixPotentiallyInvalidUTF8Data(message) subject = shared.fixPotentiallyInvalidUTF8Data(subject)
data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'receivedTime':received, 'read': read}, indent=4, separators=(',', ': ')) message = shared.fixPotentiallyInvalidUTF8Data(message)
data += ']}' data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'receivedTime':received, 'read': read}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'getAllSentMessages': return data
queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent where folder='sent' ORDER BY lastactiontime''') elif method == 'getAllSentMessages':
data = '{"sentMessages":[' queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent where folder='sent' ORDER BY lastactiontime''')
for row in queryreturn: data = '{"sentMessages":['
msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row for row in queryreturn:
subject = shared.fixPotentiallyInvalidUTF8Data(subject) msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row
message = shared.fixPotentiallyInvalidUTF8Data(message) subject = shared.fixPotentiallyInvalidUTF8Data(subject)
if len(data) > 25: message = shared.fixPotentiallyInvalidUTF8Data(message)
data += ',' if len(data) > 25:
data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': ')) data += ','
data += ']}' data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'getAllSentMessageIds' or method == 'getAllSentMessageIDs': return data
queryreturn = sqlQuery('''SELECT msgid FROM sent where folder='sent' ORDER BY lastactiontime''') elif method == 'getAllSentMessageIds' or method == 'getAllSentMessageIDs':
data = '{"sentMessageIds":[' queryreturn = sqlQuery('''SELECT msgid FROM sent where folder='sent' ORDER BY lastactiontime''')
for row in queryreturn: data = '{"sentMessageIds":['
msgid = row[0] for row in queryreturn:
if len(data) > 25: msgid = row[0]
data += ',' if len(data) > 25:
data += json.dumps({'msgid':msgid.encode('hex')}, indent=4, separators=(',', ': ')) data += ','
data += ']}' data += json.dumps({'msgid':msgid.encode('hex')}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'getInboxMessagesByReceiver' or method == 'getInboxMessagesByAddress': #after some time getInboxMessagesByAddress should be removed return data
if len(params) == 0: elif method == 'getInboxMessagesByReceiver' or method == 'getInboxMessagesByAddress': #after some time getInboxMessagesByAddress should be removed
raise APIError(0, 'I need parameters!') if len(params) == 0:
toAddress = params[0] raise APIError(0, 'I need parameters!')
queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype FROM inbox WHERE folder='inbox' AND toAddress=?''', toAddress) toAddress = params[0]
data = '{"inboxMessages":[' queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype FROM inbox WHERE folder='inbox' AND toAddress=?''', toAddress)
for row in queryreturn: data = '{"inboxMessages":['
msgid, toAddress, fromAddress, subject, received, message, encodingtype = row for row in queryreturn:
subject = shared.fixPotentiallyInvalidUTF8Data(subject) msgid, toAddress, fromAddress, subject, received, message, encodingtype = row
message = shared.fixPotentiallyInvalidUTF8Data(message) subject = shared.fixPotentiallyInvalidUTF8Data(subject)
if len(data) > 25: message = shared.fixPotentiallyInvalidUTF8Data(message)
data += ',' if len(data) > 25:
data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'receivedTime':received}, indent=4, separators=(',', ': ')) data += ','
data += ']}' data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'receivedTime':received}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'getSentMessageById' or method == 'getSentMessageByID': return data
if len(params) == 0: elif method == 'getSentMessageById' or method == 'getSentMessageByID':
raise APIError(0, 'I need parameters!') if len(params) == 0:
msgid = self._decode(params[0], "hex") raise APIError(0, 'I need parameters!')
queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE msgid=?''', msgid) msgid = self._decode(params[0], "hex")
data = '{"sentMessage":[' queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE msgid=?''', msgid)
for row in queryreturn: data = '{"sentMessage":['
msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row for row in queryreturn:
subject = shared.fixPotentiallyInvalidUTF8Data(subject) msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row
message = shared.fixPotentiallyInvalidUTF8Data(message) subject = shared.fixPotentiallyInvalidUTF8Data(subject)
data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': ')) message = shared.fixPotentiallyInvalidUTF8Data(message)
data += ']}' data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'getSentMessagesByAddress' or method == 'getSentMessagesBySender': return data
if len(params) == 0: elif method == 'getSentMessagesByAddress' or method == 'getSentMessagesBySender':
raise APIError(0, 'I need parameters!') if len(params) == 0:
fromAddress = params[0] raise APIError(0, 'I need parameters!')
queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE folder='sent' AND fromAddress=? ORDER BY lastactiontime''', fromAddress = params[0]
fromAddress) queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE folder='sent' AND fromAddress=? ORDER BY lastactiontime''',
data = '{"sentMessages":[' fromAddress)
for row in queryreturn: data = '{"sentMessages":['
msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row for row in queryreturn:
subject = shared.fixPotentiallyInvalidUTF8Data(subject) msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row
message = shared.fixPotentiallyInvalidUTF8Data(message) subject = shared.fixPotentiallyInvalidUTF8Data(subject)
if len(data) > 25: message = shared.fixPotentiallyInvalidUTF8Data(message)
data += ',' if len(data) > 25:
data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': ')) data += ','
data += ']}' data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'getSentMessageByAckData': return data
if len(params) == 0: elif method == 'getSentMessageByAckData':
raise APIError(0, 'I need parameters!') if len(params) == 0:
ackData = self._decode(params[0], "hex") raise APIError(0, 'I need parameters!')
queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE ackdata=?''', ackData = self._decode(params[0], "hex")
ackData) queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE ackdata=?''',
data = '{"sentMessage":[' ackData)
for row in queryreturn: data = '{"sentMessage":['
msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row for row in queryreturn:
subject = shared.fixPotentiallyInvalidUTF8Data(subject) msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row
message = shared.fixPotentiallyInvalidUTF8Data(message) subject = shared.fixPotentiallyInvalidUTF8Data(subject)
data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': ')) message = shared.fixPotentiallyInvalidUTF8Data(message)
data += ']}' data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'trashMessage': return data
if len(params) == 0: elif method == 'trashMessage':
raise APIError(0, 'I need parameters!') if len(params) == 0:
msgid = self._decode(params[0], "hex") raise APIError(0, 'I need parameters!')
msgid = self._decode(params[0], "hex")
# Trash if in inbox table
helper_inbox.trash(msgid) # Trash if in inbox table
# Trash if in sent table helper_inbox.trash(msgid)
sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid) # Trash if in sent table
return 'Trashed message (assuming message existed).' sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid)
elif method == 'trashInboxMessage': return 'Trashed message (assuming message existed).'
if len(params) == 0: elif method == 'trashInboxMessage':
raise APIError(0, 'I need parameters!') if len(params) == 0:
msgid = self._decode(params[0], "hex") raise APIError(0, 'I need parameters!')
helper_inbox.trash(msgid) msgid = self._decode(params[0], "hex")
return 'Trashed inbox message (assuming message existed).' helper_inbox.trash(msgid)
elif method == 'trashSentMessage': return 'Trashed inbox message (assuming message existed).'
if len(params) == 0: elif method == 'trashSentMessage':
raise APIError(0, 'I need parameters!') if len(params) == 0:
msgid = self._decode(params[0], "hex") raise APIError(0, 'I need parameters!')
sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid) msgid = self._decode(params[0], "hex")
return 'Trashed sent message (assuming message existed).' sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid)
elif method == 'trashSentMessageByAckData': return 'Trashed sent message (assuming message existed).'
# This API method should only be used when msgid is not available elif method == 'trashSentMessageByAckData':
if len(params) == 0: # This API method should only be used when msgid is not available
raise APIError(0, 'I need parameters!') if len(params) == 0:
ackdata = self._decode(params[0], "hex") raise APIError(0, 'I need parameters!')
sqlExecute('''UPDATE sent SET folder='trash' WHERE ackdata=?''', ackdata = self._decode(params[0], "hex")
ackdata) sqlExecute('''UPDATE sent SET folder='trash' WHERE ackdata=?''',
return 'Trashed sent message (assuming message existed).' ackdata)
elif method == 'sendMessage': return 'Trashed sent message (assuming message existed).'
if len(params) == 0: elif method == 'sendMessage':
raise APIError(0, 'I need parameters!') if len(params) == 0:
elif len(params) == 4: raise APIError(0, 'I need parameters!')
toAddress, fromAddress, subject, message = params elif len(params) == 4:
encodingType = 2 toAddress, fromAddress, subject, message = params
elif len(params) == 5: encodingType = 2
toAddress, fromAddress, subject, message, encodingType = params elif len(params) == 5:
if encodingType != 2: toAddress, fromAddress, subject, message, encodingType = params
raise APIError(6, 'The encoding type must be 2 because that is the only one this program currently supports.') if encodingType != 2:
subject = self._decode(subject, "base64") raise APIError(6, 'The encoding type must be 2 because that is the only one this program currently supports.')
message = self._decode(message, "base64") subject = self._decode(subject, "base64")
toAddress = addBMIfNotPresent(toAddress) message = self._decode(message, "base64")
fromAddress = addBMIfNotPresent(fromAddress) toAddress = addBMIfNotPresent(toAddress)
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(toAddress) fromAddress = addBMIfNotPresent(fromAddress)
self._verifyAddress(fromAddress) status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(toAddress)
try: self._verifyAddress(fromAddress)
fromAddressEnabled = shared.config.getboolean( try:
fromAddress, 'enabled') fromAddressEnabled = shared.config.getboolean(
except: fromAddress, 'enabled')
raise APIError(13, 'Could not find your fromAddress in the keys.dat file.') except:
if not fromAddressEnabled: raise APIError(13, 'Could not find your fromAddress in the keys.dat file.')
raise APIError(14, 'Your fromAddress is disabled. Cannot send.') if not fromAddressEnabled:
raise APIError(14, 'Your fromAddress is disabled. Cannot send.')
ackdata = OpenSSL.rand(32)
ackdata = OpenSSL.rand(32)
t = ('', toAddress, toRipe, fromAddress, subject, message, ackdata, int(
time.time()), 'msgqueued', 1, 1, 'sent', 2) t = ('', toAddress, toRipe, fromAddress, subject, message, ackdata, int(
helper_sent.insert(t) time.time()), 'msgqueued', 1, 1, 'sent', 2)
helper_sent.insert(t)
toLabel = ''
queryreturn = sqlQuery('''select label from addressbook where address=?''', toAddress) toLabel = ''
if queryreturn != []: queryreturn = sqlQuery('''select label from addressbook where address=?''', toAddress)
for row in queryreturn: if queryreturn != []:
toLabel, = row for row in queryreturn:
# apiSignalQueue.put(('displayNewSentMessage',(toAddress,toLabel,fromAddress,subject,message,ackdata))) toLabel, = row
shared.UISignalQueue.put(('displayNewSentMessage', ( # apiSignalQueue.put(('displayNewSentMessage',(toAddress,toLabel,fromAddress,subject,message,ackdata)))
toAddress, toLabel, fromAddress, subject, message, ackdata))) shared.UISignalQueue.put(('displayNewSentMessage', (
toAddress, toLabel, fromAddress, subject, message, ackdata)))
shared.workerQueue.put(('sendmessage', toAddress))
shared.workerQueue.put(('sendmessage', toAddress))
return ackdata.encode('hex')
return ackdata.encode('hex')
elif method == 'sendBroadcast':
if len(params) == 0: elif method == 'sendBroadcast':
raise APIError(0, 'I need parameters!') if len(params) == 0:
if len(params) == 3: raise APIError(0, 'I need parameters!')
fromAddress, subject, message = params if len(params) == 3:
encodingType = 2 fromAddress, subject, message = params
elif len(params) == 4: encodingType = 2
fromAddress, subject, message, encodingType = params elif len(params) == 4:
if encodingType != 2: fromAddress, subject, message, encodingType = params
raise APIError(6, 'The encoding type must be 2 because that is the only one this program currently supports.') if encodingType != 2:
subject = self._decode(subject, "base64") raise APIError(6, 'The encoding type must be 2 because that is the only one this program currently supports.')
message = self._decode(message, "base64") subject = self._decode(subject, "base64")
message = self._decode(message, "base64")
fromAddress = addBMIfNotPresent(fromAddress)
self._verifyAddress(fromAddress) fromAddress = addBMIfNotPresent(fromAddress)
try: self._verifyAddress(fromAddress)
fromAddressEnabled = shared.config.getboolean( try:
fromAddress, 'enabled') fromAddressEnabled = shared.config.getboolean(
except: fromAddress, 'enabled')
raise APIError(13, 'could not find your fromAddress in the keys.dat file.') except:
ackdata = OpenSSL.rand(32) raise APIError(13, 'could not find your fromAddress in the keys.dat file.')
toAddress = '[Broadcast subscribers]' ackdata = OpenSSL.rand(32)
ripe = '' toAddress = '[Broadcast subscribers]'
ripe = ''
t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int(
time.time()), 'broadcastqueued', 1, 1, 'sent', 2) t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int(
helper_sent.insert(t) time.time()), 'broadcastqueued', 1, 1, 'sent', 2)
helper_sent.insert(t)
toLabel = '[Broadcast subscribers]'
shared.UISignalQueue.put(('displayNewSentMessage', ( toLabel = '[Broadcast subscribers]'
toAddress, toLabel, fromAddress, subject, message, ackdata))) shared.UISignalQueue.put(('displayNewSentMessage', (
shared.workerQueue.put(('sendbroadcast', '')) toAddress, toLabel, fromAddress, subject, message, ackdata)))
shared.workerQueue.put(('sendbroadcast', ''))
return ackdata.encode('hex')
elif method == 'getStatus': return ackdata.encode('hex')
if len(params) != 1: elif method == 'getStatus':
raise APIError(0, 'I need one parameter!') if len(params) != 1:
ackdata, = params raise APIError(0, 'I need one parameter!')
if len(ackdata) != 64: ackdata, = params
raise APIError(15, 'The length of ackData should be 32 bytes (encoded in hex thus 64 characters).') if len(ackdata) != 64:
ackdata = self._decode(ackdata, "hex") raise APIError(15, 'The length of ackData should be 32 bytes (encoded in hex thus 64 characters).')
queryreturn = sqlQuery( ackdata = self._decode(ackdata, "hex")
'''SELECT status FROM sent where ackdata=?''', queryreturn = sqlQuery(
ackdata) '''SELECT status FROM sent where ackdata=?''',
if queryreturn == []: ackdata)
return 'notfound' if queryreturn == []:
for row in queryreturn: return 'notfound'
status, = row for row in queryreturn:
return status status, = row
elif method == 'addSubscription': return status
if len(params) == 0: elif method == 'addSubscription':
raise APIError(0, 'I need parameters!') if len(params) == 0:
if len(params) == 1: raise APIError(0, 'I need parameters!')
address, = params if len(params) == 1:
label = '' address, = params
if len(params) == 2: label = ''
address, label = params if len(params) == 2:
label = self._decode(label, "base64") address, label = params
try: label = self._decode(label, "base64")
unicode(label, 'utf-8') try:
except: unicode(label, 'utf-8')
raise APIError(17, 'Label is not valid UTF-8 data.') except:
if len(params) > 2: raise APIError(17, 'Label is not valid UTF-8 data.')
raise APIError(0, 'I need either 1 or 2 parameters!') if len(params) > 2:
address = addBMIfNotPresent(address) raise APIError(0, 'I need either 1 or 2 parameters!')
self._verifyAddress(address) address = addBMIfNotPresent(address)
# First we must check to see if the address is already in the self._verifyAddress(address)
# subscriptions list. # First we must check to see if the address is already in the
queryreturn = sqlQuery('''select * from subscriptions where address=?''', address) # subscriptions list.
if queryreturn != []: queryreturn = sqlQuery('''select * from subscriptions where address=?''', address)
raise APIError(16, 'You are already subscribed to that address.') if queryreturn != []:
sqlExecute('''INSERT INTO subscriptions VALUES (?,?,?)''',label, address, True) raise APIError(16, 'You are already subscribed to that address.')
shared.reloadBroadcastSendersForWhichImWatching() sqlExecute('''INSERT INTO subscriptions VALUES (?,?,?)''',label, address, True)
shared.UISignalQueue.put(('rerenderInboxFromLabels', '')) shared.reloadBroadcastSendersForWhichImWatching()
shared.UISignalQueue.put(('rerenderSubscriptions', '')) shared.UISignalQueue.put(('rerenderInboxFromLabels', ''))
return 'Added subscription.' shared.UISignalQueue.put(('rerenderSubscriptions', ''))
return 'Added subscription.'
elif method == 'deleteSubscription':
if len(params) != 1: elif method == 'deleteSubscription':
raise APIError(0, 'I need 1 parameter!') if len(params) != 1:
address, = params raise APIError(0, 'I need 1 parameter!')
address = addBMIfNotPresent(address) address, = params
sqlExecute('''DELETE FROM subscriptions WHERE address=?''', address) address = addBMIfNotPresent(address)
shared.reloadBroadcastSendersForWhichImWatching() sqlExecute('''DELETE FROM subscriptions WHERE address=?''', address)
shared.UISignalQueue.put(('rerenderInboxFromLabels', '')) shared.reloadBroadcastSendersForWhichImWatching()
shared.UISignalQueue.put(('rerenderSubscriptions', '')) shared.UISignalQueue.put(('rerenderInboxFromLabels', ''))
return 'Deleted subscription if it existed.' shared.UISignalQueue.put(('rerenderSubscriptions', ''))
elif method == 'listSubscriptions': return 'Deleted subscription if it existed.'
queryreturn = sqlQuery('''SELECT label, address, enabled FROM subscriptions''') elif method == 'listSubscriptions':
data = '{"subscriptions":[' queryreturn = sqlQuery('''SELECT label, address, enabled FROM subscriptions''')
for row in queryreturn: data = '{"subscriptions":['
label, address, enabled = row for row in queryreturn:
label = shared.fixPotentiallyInvalidUTF8Data(label) label, address, enabled = row
if len(data) > 20: label = shared.fixPotentiallyInvalidUTF8Data(label)
data += ',' if len(data) > 20:
data += json.dumps({'label':label.encode('base64'), 'address': address, 'enabled': enabled == 1}, indent=4, separators=(',',': ')) data += ','
data += ']}' data += json.dumps({'label':label.encode('base64'), 'address': address, 'enabled': enabled == 1}, indent=4, separators=(',',': '))
return data data += ']}'
elif method == 'disseminatePreEncryptedMsg': return data
# The device issuing this command to PyBitmessage supplies a msg object that has elif method == 'disseminatePreEncryptedMsg':
# already been encrypted but which still needs the POW to be done. PyBitmessage # The device issuing this command to PyBitmessage supplies a msg object that has
# accepts this msg object and sends it out to the rest of the Bitmessage network # already been encrypted but which still needs the POW to be done. PyBitmessage
# as if it had generated the message itself. Please do not yet add this to the # accepts this msg object and sends it out to the rest of the Bitmessage network
# api doc. # as if it had generated the message itself. Please do not yet add this to the
if len(params) != 3: # api doc.
raise APIError(0, 'I need 3 parameter!') if len(params) != 3:
encryptedPayload, requiredAverageProofOfWorkNonceTrialsPerByte, requiredPayloadLengthExtraBytes = params raise APIError(0, 'I need 3 parameter!')
encryptedPayload = self._decode(encryptedPayload, "hex") encryptedPayload, requiredAverageProofOfWorkNonceTrialsPerByte, requiredPayloadLengthExtraBytes = params
# Let us do the POW and attach it to the front encryptedPayload = self._decode(encryptedPayload, "hex")
target = 2**64 / ((len(encryptedPayload)+requiredPayloadLengthExtraBytes+8) * requiredAverageProofOfWorkNonceTrialsPerByte) # Let us do the POW and attach it to the front
with shared.printLock: target = 2**64 / ((len(encryptedPayload)+requiredPayloadLengthExtraBytes+8) * requiredAverageProofOfWorkNonceTrialsPerByte)
print '(For msg message via API) Doing proof of work. Total required difficulty:', float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte, 'Required small message difficulty:', float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes with shared.printLock:
powStartTime = time.time() print '(For msg message via API) Doing proof of work. Total required difficulty:', float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte, 'Required small message difficulty:', float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes
initialHash = hashlib.sha512(encryptedPayload).digest() powStartTime = time.time()
trialValue, nonce = proofofwork.run(target, initialHash) initialHash = hashlib.sha512(encryptedPayload).digest()
with shared.printLock: trialValue, nonce = proofofwork.run(target, initialHash)
print '(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce with shared.printLock:
try: print '(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce
print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.' try:
except: print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.'
pass except:
encryptedPayload = pack('>Q', nonce) + encryptedPayload pass
toStreamNumber = decodeVarint(encryptedPayload[16:26])[0] encryptedPayload = pack('>Q', nonce) + encryptedPayload
inventoryHash = calculateInventoryHash(encryptedPayload) toStreamNumber = decodeVarint(encryptedPayload[16:26])[0]
objectType = 'msg' inventoryHash = calculateInventoryHash(encryptedPayload)
shared.inventory[inventoryHash] = ( objectType = 'msg'
objectType, toStreamNumber, encryptedPayload, int(time.time()),'') shared.inventory[inventoryHash] = (
shared.inventorySets[toStreamNumber].add(inventoryHash) objectType, toStreamNumber, encryptedPayload, int(time.time()),'')
with shared.printLock: shared.inventorySets[toStreamNumber].add(inventoryHash)
print 'Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', inventoryHash.encode('hex') with shared.printLock:
shared.broadcastToSendDataQueues(( print 'Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', inventoryHash.encode('hex')
toStreamNumber, 'advertiseobject', inventoryHash)) shared.broadcastToSendDataQueues((
elif method == 'disseminatePubkey': toStreamNumber, 'advertiseobject', inventoryHash))
# The device issuing this command to PyBitmessage supplies a pubkey object to be elif method == 'disseminatePubkey':
# disseminated to the rest of the Bitmessage network. PyBitmessage accepts this # The device issuing this command to PyBitmessage supplies a pubkey object to be
# pubkey object and sends it out to the rest of the Bitmessage network as if it # disseminated to the rest of the Bitmessage network. PyBitmessage accepts this
# had generated the pubkey object itself. Please do not yet add this to the api # pubkey object and sends it out to the rest of the Bitmessage network as if it
# doc. # had generated the pubkey object itself. Please do not yet add this to the api
if len(params) != 1: # doc.
raise APIError(0, 'I need 1 parameter!') if len(params) != 1:
payload, = params raise APIError(0, 'I need 1 parameter!')
payload = self._decode(payload, "hex") payload, = params
payload = self._decode(payload, "hex")
# Let us do the POW
target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + # Let us do the POW
8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes +
print '(For pubkey message via API) Doing proof of work...' 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)
initialHash = hashlib.sha512(payload).digest() print '(For pubkey message via API) Doing proof of work...'
trialValue, nonce = proofofwork.run(target, initialHash) initialHash = hashlib.sha512(payload).digest()
print '(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce trialValue, nonce = proofofwork.run(target, initialHash)
payload = pack('>Q', nonce) + payload print '(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce
payload = pack('>Q', nonce) + payload
pubkeyReadPosition = 8 # bypass the nonce
if payload[pubkeyReadPosition:pubkeyReadPosition+4] == '\x00\x00\x00\x00': # if this pubkey uses 8 byte time pubkeyReadPosition = 8 # bypass the nonce
pubkeyReadPosition += 8 if payload[pubkeyReadPosition:pubkeyReadPosition+4] == '\x00\x00\x00\x00': # if this pubkey uses 8 byte time
else: pubkeyReadPosition += 8
pubkeyReadPosition += 4 else:
addressVersion, addressVersionLength = decodeVarint(payload[pubkeyReadPosition:pubkeyReadPosition+10]) pubkeyReadPosition += 4
pubkeyReadPosition += addressVersionLength addressVersion, addressVersionLength = decodeVarint(payload[pubkeyReadPosition:pubkeyReadPosition+10])
pubkeyStreamNumber = decodeVarint(payload[pubkeyReadPosition:pubkeyReadPosition+10])[0] pubkeyReadPosition += addressVersionLength
inventoryHash = calculateInventoryHash(payload) pubkeyStreamNumber = decodeVarint(payload[pubkeyReadPosition:pubkeyReadPosition+10])[0]
objectType = 'pubkey' inventoryHash = calculateInventoryHash(payload)
#todo: support v4 pubkeys objectType = 'pubkey'
shared.inventory[inventoryHash] = ( #todo: support v4 pubkeys
objectType, pubkeyStreamNumber, payload, int(time.time()),'') shared.inventory[inventoryHash] = (
shared.inventorySets[pubkeyStreamNumber].add(inventoryHash) objectType, pubkeyStreamNumber, payload, int(time.time()),'')
with shared.printLock: shared.inventorySets[pubkeyStreamNumber].add(inventoryHash)
print 'broadcasting inv within API command disseminatePubkey with hash:', inventoryHash.encode('hex') with shared.printLock:
shared.broadcastToSendDataQueues(( print 'broadcasting inv within API command disseminatePubkey with hash:', inventoryHash.encode('hex')
streamNumber, 'advertiseobject', inventoryHash)) shared.broadcastToSendDataQueues((
elif method == 'getMessageDataByDestinationHash' or method == 'getMessageDataByDestinationTag': streamNumber, 'advertiseobject', inventoryHash))
# Method will eventually be used by a particular Android app to elif method == 'getMessageDataByDestinationHash' or method == 'getMessageDataByDestinationTag':
# select relevant messages. Do not yet add this to the api # Method will eventually be used by a particular Android app to
# doc. # select relevant messages. Do not yet add this to the api
# doc.
if len(params) != 1:
raise APIError(0, 'I need 1 parameter!') if len(params) != 1:
requestedHash, = params raise APIError(0, 'I need 1 parameter!')
if len(requestedHash) != 32: requestedHash, = params
raise APIError(19, 'The length of hash should be 32 bytes (encoded in hex thus 64 characters).') if len(requestedHash) != 32:
requestedHash = self._decode(requestedHash, "hex") raise APIError(19, 'The length of hash should be 32 bytes (encoded in hex thus 64 characters).')
requestedHash = self._decode(requestedHash, "hex")
# This is not a particularly commonly used API function. Before we
# use it we'll need to fill out a field in our inventory database # This is not a particularly commonly used API function. Before we
# which is blank by default (first20bytesofencryptedmessage). # use it we'll need to fill out a field in our inventory database
queryreturn = sqlQuery( # which is blank by default (first20bytesofencryptedmessage).
'''SELECT hash, payload FROM inventory WHERE tag = '' and objecttype = 'msg' ; ''') queryreturn = sqlQuery(
with SqlBulkExecute() as sql: '''SELECT hash, payload FROM inventory WHERE tag = '' and objecttype = 'msg' ; ''')
for row in queryreturn: with SqlBulkExecute() as sql:
hash01, payload = row for row in queryreturn:
readPosition = 16 # Nonce length + time length hash01, payload = row
readPosition += decodeVarint(payload[readPosition:readPosition+10])[1] # Stream Number length readPosition = 16 # Nonce length + time length
t = (payload[readPosition:readPosition+32],hash01) readPosition += decodeVarint(payload[readPosition:readPosition+10])[1] # Stream Number length
sql.execute('''UPDATE inventory SET tag=? WHERE hash=?; ''', *t) t = (payload[readPosition:readPosition+32],hash01)
sql.execute('''UPDATE inventory SET tag=? WHERE hash=?; ''', *t)
queryreturn = sqlQuery('''SELECT payload FROM inventory WHERE tag = ?''',
requestedHash) queryreturn = sqlQuery('''SELECT payload FROM inventory WHERE tag = ?''',
data = '{"receivedMessageDatas":[' requestedHash)
for row in queryreturn: data = '{"receivedMessageDatas":['
payload, = row for row in queryreturn:
if len(data) > 25: payload, = row
data += ',' if len(data) > 25:
data += json.dumps({'data':payload.encode('hex')}, indent=4, separators=(',', ': ')) data += ','
data += ']}' data += json.dumps({'data':payload.encode('hex')}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'getPubkeyByHash': return data
# Method will eventually be used by a particular Android app to elif method == 'getPubkeyByHash':
# retrieve pubkeys. Please do not yet add this to the api docs. # Method will eventually be used by a particular Android app to
if len(params) != 1: # retrieve pubkeys. Please do not yet add this to the api docs.
raise APIError(0, 'I need 1 parameter!') if len(params) != 1:
requestedHash, = params raise APIError(0, 'I need 1 parameter!')
if len(requestedHash) != 40: requestedHash, = params
raise APIError(19, 'The length of hash should be 20 bytes (encoded in hex thus 40 characters).') if len(requestedHash) != 40:
requestedHash = self._decode(requestedHash, "hex") raise APIError(19, 'The length of hash should be 20 bytes (encoded in hex thus 40 characters).')
queryreturn = sqlQuery('''SELECT transmitdata FROM pubkeys WHERE hash = ? ; ''', requestedHash) requestedHash = self._decode(requestedHash, "hex")
data = '{"pubkey":[' queryreturn = sqlQuery('''SELECT transmitdata FROM pubkeys WHERE hash = ? ; ''', requestedHash)
for row in queryreturn: data = '{"pubkey":['
transmitdata, = row for row in queryreturn:
data += json.dumps({'data':transmitdata.encode('hex')}, indent=4, separators=(',', ': ')) transmitdata, = row
data += ']}' data += json.dumps({'data':transmitdata.encode('hex')}, indent=4, separators=(',', ': '))
return data data += ']}'
elif method == 'clientStatus': return data
if len(shared.connectedHostsList) == 0: elif method == 'clientStatus':
networkStatus = 'notConnected' if len(shared.connectedHostsList) == 0:
elif len(shared.connectedHostsList) > 0 and not shared.clientHasReceivedIncomingConnections: networkStatus = 'notConnected'
networkStatus = 'connectedButHaveNotReceivedIncomingConnections' elif len(shared.connectedHostsList) > 0 and not shared.clientHasReceivedIncomingConnections:
else: networkStatus = 'connectedButHaveNotReceivedIncomingConnections'
networkStatus = 'connectedAndReceivingIncomingConnections' else:
return json.dumps({'networkConnections':len(shared.connectedHostsList),'numberOfMessagesProcessed':shared.numberOfMessagesProcessed, 'numberOfBroadcastsProcessed':shared.numberOfBroadcastsProcessed, 'numberOfPubkeysProcessed':shared.numberOfPubkeysProcessed, 'networkStatus':networkStatus, 'softwareName':'PyBitmessage','softwareVersion':shared.softwareVersion}, indent=4, separators=(',', ': ')) networkStatus = 'connectedAndReceivingIncomingConnections'
elif method == 'decodeAddress': return json.dumps({'networkConnections':len(shared.connectedHostsList),'numberOfMessagesProcessed':shared.numberOfMessagesProcessed, 'numberOfBroadcastsProcessed':shared.numberOfBroadcastsProcessed, 'numberOfPubkeysProcessed':shared.numberOfPubkeysProcessed, 'networkStatus':networkStatus, 'softwareName':'PyBitmessage','softwareVersion':shared.softwareVersion}, indent=4, separators=(',', ': '))
# Return a meaningful decoding of an address. elif method == 'decodeAddress':
if len(params) != 1: # Return a meaningful decoding of an address.
raise APIError(0, 'I need 1 parameter!') if len(params) != 1:
address, = params raise APIError(0, 'I need 1 parameter!')
status, addressVersion, streamNumber, ripe = decodeAddress(address) address, = params
return json.dumps({'status':status, 'addressVersion':addressVersion, status, addressVersion, streamNumber, ripe = decodeAddress(address)
'streamNumber':streamNumber, 'ripe':ripe.encode('base64')}, indent=4, return json.dumps({'status':status, 'addressVersion':addressVersion,
separators=(',', ': ')) 'streamNumber':streamNumber, 'ripe':ripe.encode('base64')}, indent=4,
else: separators=(',', ': '))
raise APIError(20, 'Invalid method: %s' % method) else:
raise APIError(20, 'Invalid method: %s' % method)
def _dispatch(self, method, params):
self.cookies = [] def _dispatch(self, method, params):
self.cookies = []
validuser = self.APIAuthenticateClient()
if not validuser: validuser = self.APIAuthenticateClient()
time.sleep(2) if not validuser:
return "RPC Username or password incorrect or HTTP header lacks authentication at all." time.sleep(2)
return "RPC Username or password incorrect or HTTP header lacks authentication at all."
try:
return self._handle_request(method, params) try:
except APIError as e: return self._handle_request(method, params)
return str(e) except APIError as e:
except Exception as e: return str(e)
logger.exception(e) except Exception as e:
return "API Error 0021: Unexpected API Failure - %s" % str(e) logger.exception(e)
return "API Error 0021: Unexpected API Failure - %s" % str(e)

View File

@ -15,7 +15,7 @@ import singleton
import os import os
from SimpleXMLRPCServer import SimpleXMLRPCServer from SimpleXMLRPCServer import SimpleXMLRPCServer
from bitmessageapi import MySimpleXMLRPCRequestHandler from api import MySimpleXMLRPCRequestHandler
import shared import shared
from helper_sql import sqlQuery from helper_sql import sqlQuery