This repository has been archived by the owner on Nov 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 192
/
Wallet.py
357 lines (261 loc) · 10.2 KB
/
Wallet.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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
from neo.Core.Blockchain import Blockchain
from neo.Wallets.NEP5Token import NEP5Token
from neo.Core.TX.ClaimTransaction import ClaimTransaction
from neo.Core.TX.Transaction import ContractTransaction
from neo.Core.TX.Transaction import TransactionOutput
from neo.Core.TX.TransactionAttribute import TransactionAttribute, TransactionAttributeUsage
from neo.SmartContract.ContractParameterContext import ContractParametersContext
from neo.Network.NodeLeader import NodeLeader
from neo.Prompt.Utils import get_asset_id, get_from_addr, get_arg
from neocore.Fixed8 import Fixed8
from neocore.UInt160 import UInt160
from prompt_toolkit import prompt
from neo.Implementations.Wallets.peewee import UserWallet
import binascii
import json
import math
from logzero import logger
def CreateAddress(prompter, wallet, args):
try:
int_args = int(args)
except Exception as e:
print('Enter the number of addresses to create <= 3.')
return False
if wallet is None:
print("Please open a wallet.")
return False
if int_args > 3:
print('Please create 3 or less addresses at a time.')
return False
if int_args <= 0:
print('Enter a number greater than 0.')
return False
if int_args > 0 and int_args <= 3:
x = int_args + 1
while x > 1:
wallet.CreateKey()
x = x - 1
return wallet
def DeleteAddress(prompter, wallet, addr):
scripthash = wallet.ToScriptHash(addr)
success, coins = wallet.DeleteAddress(scripthash)
if success:
print("Deleted address %s " % addr)
else:
print("error deleting addr %s " % addr)
return success
def DeleteToken(wallet, contract_hash):
hash = UInt160.ParseString(contract_hash)
success = wallet.DeleteNEP5Token(hash)
if success:
print("Deleted token %s " % contract_hash)
else:
print("error deleting token %s " % contract_hash)
return False
def ImportWatchAddr(wallet, addr):
if wallet is None:
print("Please open a wallet")
return False
script_hash = None
try:
script_hash = wallet.ToScriptHash(addr)
except Exception as e:
pass
if not script_hash:
try:
data = bytearray(binascii.unhexlify(addr.encode('utf-8')))
data.reverse()
script_hash = UInt160(data=data)
except Exception as e:
pass
if script_hash:
wallet.AddWatchOnly(script_hash)
print("added watch address")
else:
print("incorrect format for watch address")
def ImportToken(wallet, contract_hash):
if wallet is None:
print("please open a wallet")
return False
contract = Blockchain.Default().GetContract(contract_hash)
if contract:
hex_script = binascii.hexlify(contract.Code.Script)
token = NEP5Token(script=hex_script)
result = token.Query()
if result:
wallet.AddNEP5Token(token)
print("added token %s " % json.dumps(token.ToJson(), indent=4))
else:
print("Could not import token")
def AddAlias(wallet, addr, title):
if wallet is None:
print("Please open a wallet")
return False
try:
script_hash = wallet.ToScriptHash(addr)
wallet.AddNamedAddress(script_hash, title)
except Exception as e:
print(e)
def ClaimGas(wallet, require_password=True, args=None):
if args:
params, from_addr_str = get_from_addr(args)
else:
params = None
from_addr_str = None
unclaimed_coins = wallet.GetUnclaimedCoins()
unclaimed_count = len(unclaimed_coins)
if unclaimed_count == 0:
print("no claims to process")
return False
max_coins_per_claim = None
if params:
max_coins_per_claim = get_arg(params, 0, convert_to_int=True)
if not max_coins_per_claim:
print("max_coins_to_claim must be an integer")
return False
if max_coins_per_claim <= 0:
print("max_coins_to_claim must be greater than zero")
return False
if max_coins_per_claim and unclaimed_count > max_coins_per_claim:
unclaimed_coins = unclaimed_coins[:max_coins_per_claim]
unclaimed_coin_refs = [coin.Reference for coin in unclaimed_coins]
available_bonus = Blockchain.Default().CalculateBonusIgnoreClaimed(unclaimed_coin_refs)
if available_bonus == Fixed8.Zero():
print("No gas to claim")
return False
claim_tx = ClaimTransaction()
claim_tx.Claims = unclaimed_coin_refs
claim_tx.Attributes = []
claim_tx.inputs = []
script_hash = wallet.GetChangeAddress()
# the following can be used to claim gas that is in an imported contract_addr
# example, wallet claim --from-addr={smart contract addr}
if from_addr_str:
script_hash = wallet.ToScriptHash(from_addr_str)
standard_contract = wallet.GetStandardAddress()
claim_tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script,
data=standard_contract.Data)]
claim_tx.outputs = [
TransactionOutput(AssetId=Blockchain.SystemCoin().Hash, Value=available_bonus, script_hash=script_hash)
]
context = ContractParametersContext(claim_tx)
wallet.Sign(context)
print("\n---------------------------------------------------------------")
print("Will make claim for %s GAS" % available_bonus.ToString())
if max_coins_per_claim and unclaimed_count > max_coins_per_claim:
print("NOTE: You are claiming GAS on %s unclaimed coins. %s additional claim transactions will be required to claim all available GAS." % (max_coins_per_claim, math.floor(unclaimed_count / max_coins_per_claim)))
print("------------------------------------------------------------------\n")
if require_password:
print("Enter your password to complete this claim")
passwd = prompt("[Password]> ", is_password=True)
if not wallet.ValidatePassword(passwd):
print("incorrect password")
return
if context.Completed:
claim_tx.scripts = context.GetScripts()
print("claim tx: %s " % json.dumps(claim_tx.ToJson(), indent=4))
relayed = NodeLeader.Instance().Relay(claim_tx)
if relayed:
print("Relayed Tx: %s " % claim_tx.Hash.ToString())
wallet.SaveTransaction(claim_tx)
else:
print("Could not relay tx %s " % claim_tx.Hash.ToString())
return claim_tx, relayed
else:
print("could not sign tx")
return None, False
def ShowUnspentCoins(wallet, args):
addr = None
asset_type = None
watch_only = 0
do_count = False
try:
for item in args:
if len(item) == 34:
addr = wallet.ToScriptHash(item)
elif len(item) > 1:
asset_type = get_asset_id(wallet, item)
if item == '--watch':
watch_only = 64
elif item == '--count':
do_count = True
except Exception as e:
print("Invalid arguments specified")
if asset_type:
unspents = wallet.FindUnspentCoinsByAsset(asset_type, from_addr=addr, watch_only_val=watch_only)
else:
unspents = wallet.FindUnspentCoins(from_addr=addr, watch_only_val=watch_only)
if do_count:
print('\n-----------------------------------------------')
print('Total Unspent: %s' % len(unspents))
return unspents
for unspent in unspents:
print('\n-----------------------------------------------')
print(json.dumps(unspent.ToJson(), indent=4))
return unspents
def SplitUnspentCoin(wallet, args, prompt_passwd=True):
"""
example ``wallet split Ab8RGQEWetkhVqXjPHeGN9LJdbhaFLyUXz neo 1 100``
this would split the second unspent neo vin into 100 vouts
:param wallet:
:param args (list): A list of arguments as [Address, asset type, unspent index, divisions]
:return: bool
"""
fee = Fixed8.Zero()
try:
addr = wallet.ToScriptHash(args[0])
asset = get_asset_id(wallet, args[1])
index = int(args[2])
divisions = int(args[3])
if len(args) == 5:
fee = Fixed8.TryParse(args[4])
except Exception as e:
logger.info("Invalid arguments specified: %s " % e)
return None
try:
unspentItem = wallet.FindUnspentCoinsByAsset(asset, from_addr=addr)[index]
except Exception as e:
logger.info("Could not find unspent item for asset with index %s %s : %s" % (asset, index, e))
return None
outputs = split_to_vouts(asset, addr, unspentItem.Output.Value, divisions)
# subtract a fee from the first vout
if outputs[0].Value > fee:
outputs[0].Value -= fee
else:
raise Exception("Fee could not be subtracted from outputs.")
contract_tx = ContractTransaction(outputs=outputs, inputs=[unspentItem.Reference])
ctx = ContractParametersContext(contract_tx)
wallet.Sign(ctx)
print("Splitting: %s " % json.dumps(contract_tx.ToJson(), indent=4))
if prompt_passwd:
passwd = prompt("[Password]> ", is_password=True)
if not wallet.ValidatePassword(passwd):
print("incorrect password")
return None
if ctx.Completed:
contract_tx.scripts = ctx.GetScripts()
relayed = NodeLeader.Instance().Relay(contract_tx)
if relayed:
wallet.SaveTransaction(contract_tx)
print("Relayed Tx: %s " % contract_tx.Hash.ToString())
return contract_tx
else:
print("Could not relay tx %s " % contract_tx.Hash.ToString())
return None
def split_to_vouts(asset, addr, input_val, divisions):
divisor = Fixed8(divisions)
new_amounts = input_val / divisor
outputs = []
total = Fixed8.Zero()
if asset == Blockchain.Default().SystemShare().Hash:
if new_amounts % Fixed8.FD() > Fixed8.Zero():
new_amounts = new_amounts.Ceil()
while total < input_val:
if total + new_amounts < input_val:
outputs.append(TransactionOutput(asset, new_amounts, addr))
total += new_amounts
else:
diff = input_val - total
outputs.append(TransactionOutput(asset, diff, addr))
total += diff
return outputs