示例#1
0
def _getVoteList(param):
	# get account votes
	voted = rest.GET.api.accounts.delegates(address=DATA.getCurrentAddress()).get("delegates", [])

	# if usernames is/are given
	if param["<delegates>"]:
		# try to load it from file if a valid path is given
		if os.path.exists(param["<delegates>"]):
			with io.open(param["<delegates>"]) as in_:
				usernames = [str(e) for e in in_.read().split() if e != ""]
		else:
			usernames = param["<delegates>"].split(",")

		voted = [d["username"] for d in voted]
		if param["--down"]:
			verb = "Down-vote"
			fmt = "-%s"
			to_vote = [username for username in usernames if username in voted]
		else:
			verb = "Up-vote"
			fmt = "+%s"
			to_vote = [username for username in usernames if username not in voted]

		return [fmt % pk for pk in getDelegatesPublicKeys(*to_vote)], verb, to_vote

	elif len(voted):
		prettyPrint(dict([d["username"], "%s%%" % d["approval"]] for d in voted))

	return [], "", []
示例#2
0
def wsend(param):

	if DATA.account:
		amount = floatAmount(param["<amount>"])
		weighting = loadJson(param["<weighting>"])

		try:
			checksum = sum(weighting.values())
			if checksum != 1.0:
				sys.stdout.write("    Bad weighting : checksum=%f (should be 1.0)\n" % checksum)
				return
		except:
			sys.stdout.write("    Not a valid weighting file\n")
			return

		prettyPrint(weighting)
		if amount and askYesOrNo("Send %(amount).8f %(token)s to %(recipientId)s addresses ?" % \
								{"token": cfg.token, "amount": amount, "recipientId": len(weighting)}) \
				  and checkSecondKeys():

			for address, weight in weighting.items():
				share = weight * amount
				if share * 100000000 > cfg.fees["send"]:
					_send(arky.core.bakeTransaction(
						amount=share * 100000000 - cfg.fees["send"],
						recipientId=address,
						vendorField=param["<message>"],
						publicKey=DATA.firstkeys["publicKey"],
						privateKey=DATA.firstkeys["privateKey"],
						secondPrivateKey=DATA.secondkeys.get("privateKey", None)
					))

			DATA.daemon = checkRegisteredTx("%s.registry" % (DATA.account["address"]), os.path.join(HOME, ".registry", cfg.network), quiet=True)
示例#3
0
def _send(payload):
	_address = DATA.getCurrentAddress()
	if DATA.escrowed:
		folder = os.path.join(HOME, ".escrow", cfg.network)
		if not os.path.exists(folder):
			os.makedirs(folder)
		sys.stdout.write("    Writing transaction...\n")
		registry_file = "%s.escrow" % (_address if _address else "thirdparty")
		registry = loadJson(registry_file, folder)
		if registry == {}:
			registry["secondPublicKey"] = DATA.getCurrent2ndPKey()
			registry["transactions"] = []
		payload.pop("id", None)
		registry["transactions"].extend([payload])
		dumpJson(registry, registry_file, folder)
	else:
		folder = os.path.join(HOME, ".registry", cfg.network)
		if not os.path.exists(folder):
			os.makedirs(folder)
		registry_file = "%s.registry" % (_address if _address else "thirdparty")
		registry = loadJson(registry_file, folder)
		typ_ = payload["type"]
		sys.stdout.write(("    Broadcasting transaction of %.8f %s to %s\n" % (payload["amount"] / 100000000, cfg.token, payload["recipientId"])) if typ_ == 0 else \
						  "    Broadcasting vote...\n" if typ_ == 3 else \
						  "    Broadcasting transaction...\n")
		resp = arky.core.sendPayload(payload)
		prettyPrint(resp)
		if resp["success"]:
			registry[payload["id"]] = payload
			dumpJson(registry, registry_file, folder)
		DATA.daemon = checkRegisteredTx(registry_file, folder, quiet=True)
示例#4
0
    def _checkRegisteredTx(registry):
        registered = loadJson(registry, folder)
        if not len(registered):
            if not quiet:
                sys.stdout.write("\nNo transaction remaining\n")
            LOCK.set()
        else:
            if not quiet:
                sys.stdout.write("\n---\nTransaction registry check...\n")
            for tx_id, payload in list(registered.items()):
                if rest.GET.api.transactions.get(id=tx_id).get(
                        "success", False):
                    registered.pop(tx_id)
                else:
                    if not quiet:
                        sys.stdout.write("Broadcasting transaction #%s\n" %
                                         tx_id)
                    result = arky.core.sendPayload(payload)
                    if not quiet:
                        prettyPrint(result, log=False)

            dumpJson(registered, registry, folder)
            remaining = len(registered)
            if not remaining:
                if not quiet:
                    sys.stdout.write(
                        "\nCheck finished, all transactions applied\n")
                LOCK.set()
            elif not quiet:
                sys.stdout.write(
                    "\n%d transaction%s not applied in blockchain\nWaiting two blocks (%ds) before another broadcast...\n"
                    % (remaining, "s" if remaining > 1 else "",
                       2 * cfg.blocktime))
示例#5
0
def forged(param):
    if DATA.delegate:
        resp = rest.GET.api.delegates.forging.getForgedByAccount(
            generatorPublicKey=DATA.account["publicKey"])
        if resp.pop("success"):
            prettyPrint(
                dict([k, float(v) / 100000000] for k, v in resp.items()))
示例#6
0
 def test_prettyPrint(self):
     # we use OrderedDict to always guarantee the same order as a result so we can assert it
     data = OrderedDict()
     data["testing"] = True
     data["transactions"] = "many"
     with patch('sys.stdout', new=io.StringIO()) as stdout:
         prettyPrint(data, log=False)
     assert stdout.getvalue(
     ) == '\t     testing: True\n\ttransactions: many\n'
示例#7
0
def voters(param):
    if DATA.delegate:
        accounts = rest.GET.api.delegates.voters(
            publicKey=DATA.delegate["publicKey"]).get("accounts", [])
        sum_ = 0.
        log = collections.OrderedDict()
        for addr, vote in sorted(
            [[c["address"], float(c["balance"]) / 100000000]
             for c in accounts],
                key=lambda e: e[-1]):
            log[addr] = "%.3f" % vote
            sum_ += vote
        log["%d voters" % len(accounts)] = "%.3f" % sum_
        prettyPrint(log)
示例#8
0
def status(param):
	if DATA.account:
		prettyPrint(rest.GET.api.accounts(address=DATA.account["address"], returnKey="account"))
示例#9
0
def status(param):
    if DATA.ledger:
        data = rest.GET.api.accounts(address=DATA.ledger["address"],
                                     returnKey="account")
        data["derivationPath"] = DATA.ledger["path"]
        prettyPrint(data)
示例#10
0
def status(param):
    if DATA.delegate:
        account = rest.GET.api.accounts(address=DATA.account["address"],
                                        returnKey="account")
        prettyPrint(dict(account, **DATA.delegate))