forked from OpenBazaar/OpenBazaar-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenbazaard.py
212 lines (178 loc) · 7.66 KB
/
openbazaard.py
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
__author__ = 'chris'
import sys
import argparse
import platform
from twisted.internet import reactor
from twisted.python import log, logfile
from twisted.web.server import Site
from twisted.web.static import File
from daemon import Daemon
import stun
import requests
from autobahn.twisted.websocket import listenWS
import obelisk
from db.datastore import Database
from keyutils.keys import KeyChain
from dht.network import Server
from dht.node import Node
from wireprotocol import OpenBazaarProtocol
from constants import DATA_FOLDER, KSIZE, ALPHA
from market import network
from market.listeners import MessageListenerImpl, NotificationListenerImpl
from api.ws import WSFactory, WSProtocol
from api.restapi import OpenBazaarAPI
from dht.storage import PersistentStorage
def run(*args):
TESTNET = args[0]
# database
db = Database(TESTNET)
# key generation
keys = KeyChain(db)
# logging
# TODO: prune this log file and prevent it from getting too large?
logFile = logfile.LogFile.fromFullPath(DATA_FOLDER + "debug.log")
log.addObserver(log.FileLogObserver(logFile).emit)
log.startLogging(sys.stdout)
# stun
# TODO: accept port from command line
port = 18467 if not TESTNET else 28467
print "Finding NAT Type.."
# TODO: maintain a list of backup STUN servers and try them if ours fails
response = stun.get_ip_info(stun_host="seed.openbazaar.org", source_port=port)
print "%s on %s:%s" % (response[0], response[1], response[2])
ip_address = response[1]
port = response[2]
# TODO: try UPnP if restricted NAT
# TODO: maintain open connection to seed node if STUN/UPnP fail
# TODO: use TURN if symmetric NAT
def on_bootstrap_complete(resp):
mlistener = MessageListenerImpl(ws_factory, db)
mserver.get_messages(mlistener)
mserver.protocol.add_listener(mlistener)
nlistener = NotificationListenerImpl(ws_factory, db)
mserver.protocol.add_listener(nlistener)
protocol = OpenBazaarProtocol((ip_address, port), testnet=TESTNET)
# kademlia
node = Node(keys.guid, ip_address, port, signed_pubkey=keys.guid_signed_pubkey)
try:
kserver = Server.loadState(DATA_FOLDER + 'cache.pickle', ip_address, port, protocol, db,
on_bootstrap_complete, storage=PersistentStorage(db.DATABASE))
except Exception:
kserver = Server(node, db, KSIZE, ALPHA, storage=PersistentStorage(db.DATABASE))
kserver.protocol.connect_multiplexer(protocol)
kserver.bootstrap(
kserver.querySeed("seed.openbazaar.org:8080",
"ddd862778e3ed71af06db0e3619a4c6269ec7468c745132dbb73982b319fc572"))\
.addCallback(on_bootstrap_complete)
# TODO: load seeds from config file
kserver.saveStateRegularly(DATA_FOLDER + 'cache.pickle', 10)
protocol.register_processor(kserver.protocol)
# market
mserver = network.Server(kserver, keys.signing_key, db)
mserver.protocol.connect_multiplexer(protocol)
protocol.register_processor(mserver.protocol)
reactor.listenUDP(port, protocol)
# websockets api
ws_factory = WSFactory("ws://127.0.0.1:18466", mserver, kserver)
ws_factory.protocol = WSProtocol
ws_factory.setProtocolOptions(allowHixie76=True)
listenWS(ws_factory)
webdir = File(".")
web = Site(webdir)
reactor.listenTCP(9000, web, interface="127.0.0.1")
# rest api
api = OpenBazaarAPI(mserver, kserver, protocol)
site = Site(api, timeout=None)
reactor.listenTCP(18469, site, interface="127.0.0.1")
# TODO: add optional SSL on rest and websocket servers
# blockchain
# TODO: listen on the libbitcoin heartbeat port instead fetching height
def height_fetched(ec, height):
print "Libbitcoin server online"
try:
timeout.cancel()
except Exception:
pass
def timeout(client):
print "Libbitcoin server offline"
client = None
if TESTNET:
libbitcoin_client = obelisk.ObeliskOfLightClient("tcp://libbitcoin2.openbazaar.org:9091")
else:
libbitcoin_client = obelisk.ObeliskOfLightClient("tcp://libbitcoin1.openbazaar.org:9091")
# TODO: load libbitcoin server url from config file
libbitcoin_client.fetch_last_height(height_fetched)
timeout = reactor.callLater(5, timeout, libbitcoin_client)
protocol.set_servers(ws_factory, libbitcoin_client)
reactor.run()
if __name__ == "__main__":
# pylint: disable=anomalous-backslash-in-string
class OpenBazaard(Daemon):
def run(self, *args):
run(*args)
class Parser(object):
def __init__(self, daemon):
self.daemon = daemon
parser = argparse.ArgumentParser(
description='OpenBazaard v0.1',
usage='''
python openbazaard.py <command> [<args>]
python openbazaard.py <command> --help
commands:
start start the OpenBazaar server
stop shutdown the server and disconnect
restart restart the server
''')
parser.add_argument('command', help='Execute the given command')
args = parser.parse_args(sys.argv[1:2])
if not hasattr(self, args.command):
parser.print_help()
exit(1)
getattr(self, args.command)()
def start(self):
parser = argparse.ArgumentParser(
description="Start the OpenBazaar server",
usage='''usage:
python openbazaard.py start [-d DAEMON]''')
parser.add_argument('-d', '--daemon', action='store_true', help="run the server in the background")
parser.add_argument('-t', '--testnet', action='store_true', help="use the test network")
args = parser.parse_args(sys.argv[2:])
OKBLUE = '\033[94m'
ENDC = '\033[0m'
print "________ " + OKBLUE + " __________" + ENDC
print "\_____ \ ______ ____ ____" + OKBLUE + \
"\______ \_____ _____________ _____ _______" + ENDC
print " / | \\\____ \_/ __ \ / \\" + OKBLUE +\
"| | _/\__ \ \___ /\__ \ \__ \\\_ __ \ " + ENDC
print "/ | \ |_> > ___/| | \ " + OKBLUE \
+ "| \ / __ \_/ / / __ \_/ __ \| | \/" + ENDC
print "\_______ / __/ \___ >___| /" + OKBLUE + "______ /(____ /_____ \(____ (____ /__|" + ENDC
print " \/|__| \/ \/ " + OKBLUE + " \/ \/ \/ \/ \/" + ENDC
print
print "OpenBazaar Server v0.1 starting..."
unix = ("linux", "linux2", "darwin")
# TODO: run as windows service (also for STOP and RESTART)
if args.daemon and platform.system().lower() in unix:
self.daemon.start(args.testnet)
else:
run(args.testnet)
def stop(self):
# pylint: disable=W0612
parser = argparse.ArgumentParser(
description="Shutdown the server and disconnect",
usage='''usage:
python openbazaard.py stop''')
print "OpenBazaar server stopping..."
try:
requests.get("http://localhost:18469/api/v1/shutdown")
except Exception:
self.daemon.stop()
def restart(self):
# pylint: disable=W0612
parser = argparse.ArgumentParser(
description="Restart the server",
usage='''usage:
python openbazaard.py restart''')
print "Restarting OpenBazaar server..."
self.daemon.restart()
Parser(OpenBazaard('/tmp/openbazaard.pid'))