forked from icarusglider/PyRai
-
Notifications
You must be signed in to change notification settings - Fork 7
/
nanopy-wallet
executable file
·344 lines (289 loc) · 11.3 KB
/
nanopy-wallet
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
286
287
288
289
290
291
292
293
294
295
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
#!/usr/bin/env python3
import argparse, base64, configparser, getpass, json, os, pykeepass
import nanopy as npy
from nanopy.rpc import RPC
class bcolours:
_ok1 = "\033[34m"
_ok2 = "\033[35m"
_ok3 = "\033[32m"
_warn1 = "\033[33m"
_warn2 = "\033[31m"
_end = "\033[0m"
_bold = "\033[1m"
def _plain(self, s, prefix="", suffix=""):
print(prefix + s + suffix)
def ok1(self, s, prefix="", suffix=""):
print(prefix + self._ok1 + s + self._end + suffix)
def ok2(self, s, prefix="", suffix=""):
print(prefix + self._ok2 + s + self._end + suffix)
def ok3(self, s, prefix="", suffix=""):
print(prefix + self._ok3 + s + self._end + suffix)
def warn1(self, s, prefix="", suffix=""):
print(prefix + self._warn1 + s + self._end + suffix)
def warn2(self, s, prefix="", suffix=""):
print(prefix + self._warn2 + s + self._end + suffix)
def bold(self, s, prefix="", suffix=""):
print(prefix + self._bold + s + self._end + suffix)
def boldstr(self, s):
return self._bold + s + self._end
def amt(self, label, amount, colour=_plain):
colour("{:>40}".format(amount), label + " : ", " " + std_unit)
def status(self, label, msg, colour=_plain):
colour(self, msg, label + " : ")
bc = bcolours()
def get_no_value_options(section):
try:
options = config.options(section)
except:
return None
try:
options.remove("tor")
except:
pass
try:
options.remove("rpc")
except:
pass
try:
options.remove("offline")
except:
pass
try:
options.remove("account")
except:
pass
try:
options.remove("frontier")
except:
pass
try:
options.remove("balance")
except:
pass
try:
options.remove("representative")
except:
pass
return options
def nag_rep(rep):
try:
w = int(rpc.account_info(rep, weight=True)["weight"])
if w * 100 / available_supply > 2 and not args.rep:
bc.warn1("\nYour representative has too much voting weight.")
if input("Change rep?(" + bc.boldstr("y") + "/n): ") != "n":
args.rep = input("Rep : ")
except:
pass
def generate_block(sk, pk, acc):
nb = npy.state_block()
nb["account"] = acc
bc.status("Acc", acc)
state = [s for s in states if config[s]["account"] == acc]
state = state[0] if state else None
while True:
if online:
info = rpc.account_info(acc, representative=True)
rb = rpc.accounts_receivable([acc])
rb = rb["blocks"][acc] if "blocks" in rb else None
elif state:
if "frontier" in config[state]:
info["frontier"] = config[state]["frontier"]
info["balance"] = config[state]["balance"]
info["representative"] = config[state]["representative"]
rb = get_no_value_options(state)
if "frontier" in info:
nb["previous"] = info["frontier"]
nb["balance"] = info["balance"]
nb["representative"] = info["representative"]
bc.amt("Bal", npy.from_raw(nb["balance"]), bc.ok1)
bc.status("Rep", nb["representative"])
if online:
nag_rep(nb["representative"])
if (not args.send) and (not args.rep):
if state and online:
config[state]["frontier"] = info["frontier"]
config[state]["balance"] = info["balance"]
config[state]["representative"] = info["representative"]
with open(config_file, "w") as f:
config.write(f)
if not rb:
break
if input("\nReceive blocks?(" + bc.boldstr("y") + "/n): ") == "n":
break
else: # open a new acc
args.send = None
nb["balance"] = "0"
args.rep = input("Rep : ")
if args.rep:
assert npy.validate_account_number(args.rep)
nb["representative"] = args.rep
if args.send:
nb["link"] = npy.account_key(args.send)
bc.status("To ", npy.account_get(nb["link"]))
if args.empty:
bc.amt("Amt", npy.from_raw(nb["balance"]), bc.warn2)
nb["balance"] = "0"
else:
amount = int(npy.to_raw(input("Amt : ")))
assert amount <= int(nb["balance"])
nb["balance"] = str(int(nb["balance"]) - amount)
bc.amt("Bal", npy.from_raw(nb["balance"]), bc.warn1)
elif rb:
nb["link"] = rb[0]
if online:
r_block = rpc.blocks_info(rb)["blocks"][nb["link"]]
bc.status("From", r_block["block_account"])
amount = r_block["amount"]
else:
amount = config[state][rb[0]]
nb["balance"] = str(int(nb["balance"]) + int(amount))
bc.amt("Amt", npy.from_raw(amount), bc.ok3)
bc.amt("Bal", npy.from_raw(nb["balance"]), bc.ok3)
if args.send or args.rep or rb:
current_difficulty = args.send = args.rep = None
if args.network == "nano":
current_difficulty = "fffffe0000000000" if rb else "fffffff800000000"
work_hash = (
nb["previous"] if (nb["previous"] != "0" * 64) else npy.account_key(acc)
)
nb["work"] = npy.work_generate(work_hash, difficulty=current_difficulty)
nb["signature"] = npy.sign(sk, block=nb, pk=pk)
print("\n" + json.dumps(nb))
q = "\nBroadcast block" if online else "\nUpdate state"
if input(q + "?(y/" + bc.boldstr("n") + "): ") == "y" and not args.demo:
if online:
ack = rpc.process(json.dumps(nb))
assert "hash" in ack
bc.ok3(ack["hash"])
if state:
config[state]["frontier"] = npy.block_hash(nb)
config[state]["balance"] = nb["balance"]
config[state]["representative"] = nb["representative"]
if rb:
try:
config.remove_option(state, rb[0])
except:
pass
with open(config_file, "w") as f:
config.write(f)
bc.ok3("saved new state to " + config_file)
args = argparse.ArgumentParser()
args.add_argument(
"-a",
"--audit",
metavar="FILE",
type=argparse.FileType("rb"),
help="Audit accounts in FILE.",
)
args.add_argument("-b", "--broadcast", action="store_true", help="Broadcast JSON block")
args.add_argument(
"-n",
"--network",
default="nano",
choices=["nano", "beta", "banano"],
help="Choose the network to interact with.",
)
args.add_argument("--offline", action="store_true", help="Run in offline mode.")
args.add_argument("-t", "--tor", action="store_true", help="Connect via tor.")
subparsers = args.add_subparsers(dest="sub")
argOpen = subparsers.add_parser("open", help="Unlock *.kdbx file")
argOpen.add_argument("f", metavar="FILE", help="*.kdbx file.")
argOpen.add_argument("k", metavar="KEY", help="key to open/create.")
argOpen.add_argument("-g", "--group", help="Key group. (root)")
argOpen.add_argument("-i", "--index", default=0, type=int, help="Account index. (0)")
argOpen.add_argument("-r", "--rep", metavar="ADDRESS", help="Change rep")
argOpen.add_argument("--empty", action="store_true", help="Empty account")
argOpen.add_argument("-d", "--demo", action="store_true", help="Run in demo mode.")
openG = argOpen.add_mutually_exclusive_group()
openG.add_argument("-a", "--audit", action="store_true", help="Audit accounts")
openG.add_argument("-n", "--new", action="store_true", help="Add a new key.")
openG.add_argument("-s", "--send", metavar="ADDRESS", help="Send to")
args = args.parse_args()
if args.network == "beta":
npy.account_prefix = "xrb_"
rpc_url = "http://localhost:55000"
std_unit = "β"
available_supply = 340272367920938463463374607431768151531
elif args.network in ["banano", "ban"]:
args.network = "banano"
npy.account_prefix = "ban_"
npy.work_difficulty = "fffffe0000000000"
npy.standard_exponent = 29
rpc_url = "http://localhost:7072"
std_unit = "BAN"
available_supply = 340280899595938463463374589668199818054
else:
args.network = "nano"
rpc_url = "http://localhost:7076"
std_unit = "Ӿ"
available_supply = 133248061999106578273467128948453216035
home_npy = os.path.expanduser("~") + "/.config/nanopy/"
os.makedirs(home_npy, mode=0o700, exist_ok=True)
os.chmod(home_npy, 0o700)
config_file = home_npy + args.network + ".conf"
os.chmod(config_file, 0o600)
config = configparser.ConfigParser(allow_no_value=True)
config.read(config_file)
states = config.sections()
if "Accounts" in states:
states.remove("Accounts")
online = not (args.offline or config["DEFAULT"].getboolean("offline"))
tor = args.tor or config["DEFAULT"].getboolean("tor", fallback=args.tor)
if online:
iploc = RPC(url="https://ipinfo.io/json", tor=tor)._get()
bc.warn1(iploc["city"] + " " + iploc["country"])
rpc = RPC(url=config["DEFAULT"].get("rpc", fallback=rpc_url), tor=tor)
else:
bc.warn1("Running in offline mode.")
accounts = []
if args.sub:
if args.demo:
bc.warn1("Running in demo mode.")
os.chmod(args.f, 0o600)
kp = pykeepass.PyKeePass(args.f, password=getpass.getpass())
group = kp.find_groups(name=args.group, first=True) if args.group else kp.root_group
if args.new:
seed = os.urandom(32)
account0 = npy.deterministic_key(seed.hex(), 0)[2]
bc.status(args.k, account0)
if not args.demo:
kp.add_entry(group, args.k, account0, base64.b85encode(seed).decode())
kp.save()
else:
entry = kp.find_entries(title=args.k, group=group, recursive=False, first=True)
seed = base64.b85decode(entry.password).hex()
assert entry.username == npy.deterministic_key(seed, 0)[2]
if args.audit:
accounts = [
npy.deterministic_key(seed, i)[2] for i in range(args.index + 1)
]
else:
generate_block(*npy.deterministic_key(seed, args.index))
elif args.broadcast:
ack = rpc.process(input("Enter JSON block to broadcast: "))
assert "hash" in ack
bc.ok3(ack["hash"])
elif args.audit:
accounts = [line.rstrip(b"\n").decode() for line in args.audit]
else:
accounts = get_no_value_options("Accounts")
if accounts and online:
info = rpc.accounts_balances(accounts)
if "balances" in info:
for account in accounts:
accinfo = info["balances"][account]
bc.status("Acc", account)
bc.amt("Bal", npy.from_raw(accinfo["balance"]), bc.ok1)
if int(accinfo["receivable"]):
bc.ok3("Receivable block(s)")
print("")
else:
bc.warn2(info)
if online:
rpc.disconnect()
ticker = RPC(
url="https://api.kraken.com/0/public/Ticker?pair=nanoxbt,nanousd,nanoeur"
)._get()
print(ticker["result"]["NANOXBT"]["c"][0], "₿")
print(ticker["result"]["NANOUSD"]["c"][0], "$")
print(ticker["result"]["NANOEUR"]["c"][0], "€")