xpub.py 15.6 KB
Newer Older
Freeman's avatar
Freeman committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
#!/usr/bin/env python3

import sys
import os
import re
import datetime
import qrcode
import io
import random
import base64
import json
import time

#dataset
import dataset
from stuf import stuf

# Bottle
from bottle import Bottle, route, request, response, get, post, abort, debug, template, static_file, redirect, run

# MTServer - Multi Threaded wsgi server
from mtbottle import MTServer

# Paste - Multi Threaded wsgi server
from paste import httpserver


#bitcoin stuff
from pycoin.key.key_from_text import key_from_text
os.environ["PYCOIN_NATIVE"]="openssl"
from cashaddress import convert

import verify_tx
import exchangerate

debug(True)

db_name = 'sqlite:///pyxpub.db?check_same_thread=False'


# Look for the directory containing the configuration files
def find_data_dir():
  lib_dir = os.path.dirname(os.path.abspath(__file__))
  data_dir_locations = [
    os.path.join(os.path.expanduser('~'), '.pyxpub'),
    os.path.join(os.path.expanduser('~'), '.config', 'pyxpub'),
    lib_dir,
    os.getcwd()
  ]
  if len(sys.argv) > 1:
    if sys.argv[1] == '-h' or sys.argv[1] == '--help':
      print(usage)
      sys.exit(0)
    else:
      data_dir_locations.insert(0, os.path.abspath(sys.argv[1]))
      if not os.path.isdir(data_dir_locations[0]):
        print('No such directory: ' + data_dir_locations[0])
  for data_dir in data_dir_locations:
    try:
      os.chdir(data_dir)
    except (OSError):
      continue
    if os.path.isfile('key.list'):
      print('Using {dir} as data directory'.format(dir=data_dir))
      break
    
def init_db():
  db = dataset.connect(db_name, row_type=stuf)
    
  return db

def get_wallet_index():
  _db = init_db()
  _id = 0
  results = _db.query('SELECT MAX(id) as id FROM payment_requests')

  for result in results:
    if (result.id):
      _id = result.id
  
  return _id

# Read the xpub key from  key.list file
def get_xpub():
  _xpub = 0
  try:
    f = open('key.list', 'r')
    for line in f.readlines():
      _key = line.strip()
      pattern = re.compile("xpub")
      if pattern.match(_key, 0):
        _xpub = key_from_text(_key, net_code='STAK')
        f.close()
        return _xpub
    f.close()
    if _xpub == 0:
      print('ERROR: No xpub in key.list')
      sys.exit(2)
  except (IOError, OSError, FileNotFoundError, PermissionError):
    print('ERROR: Could not open key.list')
    sys.exit(2)

# Derive address from xpub key and increment address index
def get_xpub_address(xpub, index):
  # 0 => public addresses
  # 1 => change addresses, only for internal use
  account_type = 0
  xpub_subkey = xpub.subkey(account_type)
  addr = xpub_subkey.subkey(index).address()

  return addr

def get_payment_by_ip(ip):
  _db = init_db()
  _table = _db['payment_requests']
  _payment = _table.find_one(ip=ip)
  if _payment:
    return _payment
  else:
    return False
  
def get_payment_by_label(label):
  _db = init_db()
  _table = _db['payment_requests']
  _payment = _table.find_one(label=label)
  if _payment:
    return _payment
  else:
    return False
  
def get_payment_by_addr(addr):
  _db = init_db()
  _table = _db['payment_requests']
  _payment = _table.find_one(addr=addr)
  if _payment:
    return _payment
  else:
    return False

def update_payment_received(payment_id, received, txid):
  _db = init_db()
  _table = _db['payment_requests']

  _table.update(dict(id=payment_id, received=received, txid=txid), ['id'])
  
def get_address(ip_addr, amount="", label=""):
  _payment = False
  _order = 0
  #if ratelimit_ip:
    #_payment = get_payment_by_ip(ip_addr)
  #if ratelimit_label and label:
    #_payment = get_payment_by_label(label)
    
  if label:
    _db = init_db()
    _table = _db['order_items']
    _item = _table.find_one(label=label)
    if _item:
      _order = 1
  
  if _payment:
    _addr =  _payment.addr
    return _addr
  else:
    _xpub = get_xpub()
    _index = get_wallet_index()
    _addr = get_xpub_address(_xpub, _index)
    with dataset.connect(db_name, row_type=stuf) as tx:
      tx['payment_requests'].insert(dict(timestamp=time.time(), ip=ip_addr, addr=_addr, amount=amount, label=label, received=0, confirmations=0, txid="NoTX", order=_order))
    return _addr
  
def generate_payment(parameters, ip_addr):
  _amount = False
  _label = False
  _payment = False
  _uri = ""
  _uri_params = ""
  _qr = "/qr?addr="
  _qr_params = ""
  
  if 'amount' in parameters:
    _amount = parameters.amount
    _qr_params += "&amount=" + _amount
    _uri_params += "?amount=" + _amount
  else:
    abort(400, "Specify an amount!")
  if 'label' in parameters:
    _label = parameters.label
    _qr_params +=  "&label=" + _label
    if _amount:
      _uri_params += "&message=" + _label
    else:
      _uri_params += "?message=" + _label
  
  _addr = get_address(ip_addr, _amount, _label)
  _qr += _addr + _qr_params
  _uri = _addr + _uri_params + "&editable=false"

  _payreq = {
    "payment": {
      "amount": _amount,
      #"addr": _addr.lstrip('BITCOINCASH:'),
      "addr": _addr,
      "label": _label,
      "qr_img": _qr,
      "payment_uri": _uri,
    }
  }
  
  _json = json.dumps(_payreq)
  return _json

# Generate QR code and return the image
def get_qr(parameters):
  _addr = False
  _amount = False
  _label = False
  _data = ""
  
  if 'addr' in parameters:
     _addr = parameters.addr.upper()
     #_addr = parameters['addr'][0].rstrip('/')
     _data = _addr
  else:
    abort(401, "Specify address")
     
  if 'amount' in parameters and 'label' in parameters:
    _amount = parameters.amount
    _label = parameters.label
    _data += "?amount=" + _amount
    _data += "&message=" + _label
  elif 'amount' in parameters:
     _amount = parameters.amount
     _data += "?amount=" + _amount
  elif 'label' in parameters:
     _label = parameters.label
     _data += "?message=" + _label
     
  _data += "&editable=false"
     
  #print(_data)
     
  qr = qrcode.QRCode(
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    border=2,
  )
  qr.add_data(_data)
  #qr.add_data(parameters['addr'][0].rstrip('/'))
  qr.make(fit=True)
  img = qr.make_image()
  
  return img

def generate_embed(addr, parameters):
  _amount = False
  _label = False
  _qruri = "/qr?addr=" + addr
  _copy = addr
  _amount_label = ""
  
  if 'amount' in parameters:
    _amount = parameters.amount
    _qruri += "&amount=" + _amount
    _amount_label += "AMOUNT: " + _amount + " BCH "
    _copy += "?amount=" + _amount
  if 'label' in parameters:
    _label = parameters.label
    _qruri += "&label=" + _label
    _amount_label += "LABEL: " + _label + " "
    if _amount:
      _copy += "&message=" + _label
    else:
      _copy += "?message=" + _label

  filler = {
    'addr': addr,
    'qruri' : _qruri,
    'label' : _amount_label,
    'copy' : _copy,
  }
  html = template('views/qr.html').format(**filler)

  return html

def generate_ledger(parameters, ip_addr):
286
  print('Generating ledger')
Freeman's avatar
Freeman committed
287 288
  _db = init_db()
  _ledger = {}
289 290 291 292 293
  print('Got payment request')
  for _payment in _db['payment_requests']:
    print('verifying')
    _verify = generate_verify(_payment, ip_addr)
    print('results: %s'%_verify)
Freeman's avatar
Freeman committed
294
  for _payment in _db['payment_requests']:
295
    print('payment', _payment)
Freeman's avatar
Freeman committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    _data = {
              'id': _payment.id,
              'timestamp': _payment.timestamp,
              'addr': _payment.addr,
              'amount': _payment.amount,
              'label': _payment.label,
              'received': _payment.received,
              'confirmations': _payment.confirmations,
              'txid': _payment.txid,
              'order': _payment.order,
            }
    _ledger[str(_payment.id)] = _data
    
  _json = json.dumps(_ledger)
  return _json

def generate_verify(parameters, ip_addr):
  _addr = False
  _amount = False
  _label = False
  _received = False
  _payment = False
  
  # Find payment by label, if not verified, set parameters
  if 'label' in parameters:
    _payment = get_payment_by_label(parameters.label)
    if not _payment:
      abort(400, "ERROR: Unknown Label! - " + parameters.label)
  # Find payment by addr, if not verified, set parameters
  elif 'addr' in parameters and 'amount' in parameters:
    _amount = parameters.amount
    try:
        #key_from_text(parameters.addr, net_code='STAK')
        _addr = parameters.addr
        _payment = get_payment_by_addr(_addr)
        if not _payment:
          abort(400, "ERROR: Unknown Payment Address! - " + _addr)
    except Exception as e:
      abort(400, "Invalid address!: %s"%e)
  else:
    abort(400, "Incorrect use of API, RTFM!")
    
  # TODO: return more payment details. see verify_tx.verify()
  if _payment.received == 1:
    print('Payment recieved')
    return json.dumps({"received": 1})
  else:
    _addr = _payment.addr
    _amount = _payment.amount
    _label = _payment.label
  
  # If payment not received yet, rescan
  print("verifying transaction")
  _received = verify_tx.verify(_addr, _amount)
  
  # If rescan has positive result, update payment record in database
  if _received['received'] == 1 and _payment.received == 0:
    update_payment_received(_payment.id, 1, _received['txid'])

  # Return verification result
  if _received:
    return json.dumps(_received)
  else:
    return json.dumps({"received": 0})
  
def generate_rate(parameters, ip_addr):
  _currency = ""
  _source = ""
  if 'currency' in parameters and 'source' in parameters:
    if not exchangerate.is_supported(parameters.currency, parameters.source):
      abort(400, "ERROR: Unsupported Currency! => " + parameters.currency)
    else:
      _r = exchangerate.get_rate(parameters.currency, parameters.source)
      _price = {
          'currency': _r.currency,
          'price'   : _r.rate,
        }
      return _price
  # TODO: Error handling is_supported()
  elif 'source' in parameters:
    _r = exchangerate.get_currencies(parameters.source)
    return _r
  else:
    _r = exchangerate.get_sources()
    return _r

def generate_order(parameters, ip_addr):
  if 'label' in parameters:
    _order = get_order(parameters.label)
    _items = get_order_items(parameters.label)
    order = {}
    order['label'] = parameters.label
    items = []
    
    for _item in _items:
      item = {
                'id': _item.item_id,
                'timestamp': _item.timestamp,
                'name': _item.name,
                'currency': _item.currency,
                'bch': _item.bch,
                'count': _item.count,
                'exchangeRATE': _item.exchange_rate,
              }
      items.append(item)
      
    for _element in _order:
      order['timestamp'] = _element.timestamp
      order[_element.type] = _element.data
      
    
    order['items'] = items
    
    return order
    
  return { 'error': 0 }
  
def get_order(label):
  _db = init_db()
  _table = _db['orders']
  _order = _table.find(label=label)
  
  return _order

def get_order_items(label):
  _db = init_db()
  _table = _db['order_items']
  _items = _table.find(label=label)
  
  return _items
  
def set_headers(environ):
  if  'HTTP_ORIGIN' in environ:
    origin = environ['HTTP_ORIGIN']
    response.set_header("Access-Control-Allow-Origin", str(origin))
    response.set_header("Access-Control-Allow-Credentials", "true")
    response.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
    response.set_header("Access-Control-Allow-Headers", "Content-Type")
    response.set_header("Access-Control-Request-Headers", "X-Requested-With, accept, content-type")
    
    
  #response.set_header("Access-Control-Allow-Origin", "*")
  #response.set_header("Access-Control-Allow-Credentials", "true")

# Init bottle framework
app = application = Bottle()

@app.route('/')
@app.route('/react')
def root():
  redirect("/react/")

@app.route('/embed')
def embed():
  set_headers(request.environ)
  response.content_type = 'text/html; charset=utf-8' 
  
  _ip = request.environ.get('REMOTE_ADDR')
  _parameters = request.query
  
  _addr = get_address(_ip)
  _html = generate_embed(_addr, _parameters)
  
  return _html

@app.route('/qr')
def qr():
  set_headers(request.environ)
  response.content_type = 'image/png'
  
  _ip = request.environ.get('REMOTE_ADDR')
  _parameters = request.query
  _qr = get_qr(_parameters)
  _output = io.BytesIO()
  _qr.save(_output, format='PNG')
  
  return _output.getvalue()
  
@app.route('/api/payment')
def payment():
  set_headers(request.environ)
  response.content_type = 'application/json'
  
  _ip = request.environ.get('REMOTE_ADDR')
  _parameters = request.query
  _payment = generate_payment(_parameters, _ip)
  
  return _payment
  
@app.route('/api/verify')
def verify():
  set_headers(request.environ)
  response.content_type = 'application/json'
  
  _ip = request.environ.get('REMOTE_ADDR')
  _parameters = request.query
  _verify = generate_verify(_parameters, _ip)
  
  return _verify
  
@app.route('/api/ledger')
def ledger():
  set_headers(request.environ)
  response.content_type = 'application/json'
  
  _ip = request.environ.get('REMOTE_ADDR')
  _parameters = request.query
  _ledger = generate_ledger(_parameters, _ip)
  
  return _ledger

@app.route('/api/rate')
def rate():
  set_headers(request.environ)
  response.content_type = 'application/json'
  
  _ip = request.environ.get('REMOTE_ADDR')
  _parameters = request.query
  _rate = generate_rate(_parameters, _ip)
  
  return _rate

@app.route('/api/order')
def order():
  set_headers(request.environ)
  response.content_type = 'application/json'
  
  _ip = request.environ.get('REMOTE_ADDR')
  _parameters = request.query
  _order = generate_order(_parameters, _ip)
  
  return _order

@app.route('/api/ping')
def ping():
  set_headers(request.environ)
  response.content_type = 'application/json'
  
  _ip = request.environ.get('REMOTE_ADDR')
  _parameters = request.query
  
  _pong = { 'pong': 1 }
  
  return _pong

@app.route('/api/order', method=['POST', 'OPTIONS'])
def order():
  set_headers(request.environ)
  response.content_type = 'application/json'
  
  if request.method == 'POST':
    _now = time.time()
    _json = request.json
    
    label = _json['label']
    items = _json['items']
    subtotalBCH = _json['subtotalBCH']
    
    discount = _json['discount']
    discountBCH = _json['discountBCH']
    tax = _json['tax']
    taxBCH = _json['taxBCH']
    
    totalBCH = _json['totalBCH']
    exchangeRATE = _json['exchangeRATE']
    currency = _json['currency']
    
    for key in _json:
      if (key == 'items'):
        for item in _json[key]:
          print("INSERT item   (" + label + "): " + item['name'] + " => " + item['bch'])
          with dataset.connect(db_name, row_type=stuf) as tx:
            tx['order_items'].insert(dict(label=label, timestamp=item['timestamp'], item_id=item['id'], name=item['name'], currency=item['currency'], bch=item['bch'], count=item['count'], exchange_rate=item['exchangeRATE']))
      elif (key != 'label' and key != 'items'):
        print("INSERT order (" + label + "): " + key + " => " + str(_json[key]))
        with dataset.connect(db_name, row_type=stuf) as tx:
          tx['orders'].insert(dict(label=label, timestamp=_now, type=key, data=_json[key]))


# Serve static files
@app.route('/static/<filename:path>')
def send_static(filename):
  set_headers(request.environ)
  return static_file(filename, root="static/")

@app.route('/react/', strict_slashes=False)
@app.route('/react/<filename:path>')
def react(filename='index.html'):
  set_headers(request.environ)
  return static_file(filename, root="react/")


def main():
  # init
  find_data_dir()
  index = get_wallet_index()
  xpub = get_xpub()
  print('Wallet using xpub key: ' + xpub.as_text()[:20] + '...' + xpub.as_text()[-8:])
  print('Starting wallet at index: ' + str(index))
  
  # MTServer wsgi server
597
  app.run(server=MTServer, host='0.0.0.0', port=8080, thread_count=3)
Freeman's avatar
Freeman committed
598 599 600 601 602 603 604 605 606
  
  # Paste wsgi server
  #httpserver.serve(app, host='0.0.0.0', port=8080)
  
  #start_server()
  

if __name__ == "__main__":
  main()