Пример #1
0
def configure(**kwargs):
    if "username" in kwargs:
        username = kwargs.pop("username")
        if getPublicKeyFromUsername(username):
            if not os.path.exists(
                    os.path.join(zen.JSON, "%s-webhook.json" % username)):
                if not setDelegate(username,
                                   peer=kwargs.get("webhook_peer", None)):
                    return
                zen.logMsg("%s delegate webhook set" % username)
            else:
                # load update and save in a row
                zen.dumpJson(
                    dict(zen.loadJson("%s.json" % username), **kwargs),
                    "%s.json" % username)
                zen.logMsg("%s delegate set" % username)
        else:
            zen.logMsg("can not find delegate %s" % username)

    elif not len(kwargs):
        root = zen.loadJson("root.json")
        if "env" in root:
            delegates = zen.loadJson("delegates.json",
                                     os.path.dirname(root["env"]))
            for secret in delegates["secrets"]:
                setDelegate(dposlib.core.crypto.getKeys(secret)["publicKey"])
Пример #2
0
def getKeys(username):
    KEYS01 = None
    KEYS02 = None

    root = loadJson("root.json")
    config = loadJson("%s.json" % username)

    if "#1" in config:
        KEYS01 = dposlib.core.crypto.getKeys(config["#1"])
    else:
        pkey = getPublicKeyFromUsername(username)
        # for testing purpose
        # pkey = "030da05984d579395ce276c0dd6ca0a60140a3c3d964423a04e7abe110d60a15e9"
        delegates = loadJson("delegates.json", os.path.join(root["env"], "config"))
        if delegates == {}:
            delegates = loadJson("delegates.json", os.path.dirname(root["env"]))
        for secret in delegates["secrets"]:
            KEYS01 = dposlib.core.crypto.getKeys(secret)
            if KEYS01["publicKey"] == pkey: break
            else: KEYS01 = False

    if config.get("#2", None):
        KEYS02 = dposlib.core.crypto.getKeys(config["#2"])

    return KEYS01, KEYS02
Пример #3
0
def updateRegistryNonces(username):
    folder = os.path.join(zen.DATA, username)
    registries = [n for n in os.listdir(folder) if n.endswith(".registry")]
    if not len(registries):
        return False

    KEYS01, KEYS02 = getKeys(username)
    wallet = rest.GET.api.wallets(username).get("data", {})
    nonce = int(wallet["nonce"]) + 1

    if KEYS01 and len(wallet):
        for name in registries:
            full_registry = loadJson(name, folder=folder)
            registry = loadJson(name+".milestone", folder=folder)
            if len(registry):
                logMsg("updating transaction nonces in %s..." % (name+".milestone"))
                for tx in list(registry.values()):
                    old_id = tx["id"]
                    new_tx = dposlib.core.Transaction(tx)
                    new_tx.nonce = nonce
                    nonce += 1
                    new_tx.signWithKeys(KEYS01["publicKey"], KEYS01["privateKey"])
                    if KEYS02 is not None:
                        new_tx.signSignWithKey(KEYS02["privateKey"])
                    new_tx.identify()
                    registry.pop(old_id)
                    full_registry.pop(old_id)
                    registry[new_tx["id"]] = new_tx
                    full_registry[new_tx["id"]] = new_tx
            dumpJson(registry, name+".milestone", folder=folder)
            dumpJson(full_registry, name, folder=folder)

    return True
Пример #4
0
def extract(username):
    now = datetime.datetime.now(tz=pytz.UTC)

    if getPublicKeyFromUsername(username):
        param = loadJson("%s.json" % username)
        threshold = param.get("threshold", 0.2)
        share = param.get("share", 1.0)

        forgery = loadJson("%s.forgery" % username, os.path.join(zen.DATA, username))
        data = OrderedDict(sorted([[a,w] for a,w in forgery.get("contributions", {}).items()], key=lambda e:e[-1], reverse=True))
        tbw = OrderedDict([a,w*share] for a,w in data.items() if w*share >= threshold)
        totalDistributed = sum(tbw.values())

        dumpJson(
            {
                "timestamp": "%s" % now,
                "delegate-share": round(forgery.get("blocks", 0.) * dposlib.rest.cfg.blockreward * (1.0 - share), 8),
                "undistributed": round(sum(w for w in data.values() if w < threshold), 8),
                "distributed": round(totalDistributed, 8),
                "fees": round(forgery.get("fees", 0.), 8),
                "weight": OrderedDict(sorted([[a,s/totalDistributed] for a,s in tbw.items()], key=lambda e:e[-1], reverse=True))
            },
            "%s.tbw" % now.strftime("%Y%m%d-%H%M"),
            folder=os.path.join(zen.ROOT, "app", ".tbw", username)
        )

        # reset forgery keeping unpaind voters
        forgery["contributions"] = OrderedDict([a, 0. if a in tbw else w] for a,w in data.items())
        forgery["blocks"] = 0
        forgery["fees"] = 0.
        dumpJson(forgery, "%s.forgery" % username, os.path.join(zen.DATA, username))
Пример #5
0
def delegate_index(username):
	if username not in [name.split("-")[0] for name in os.listdir(zen.JSON) if name.endswith("-webhook.json")]:
		return "", 400

	config = zen.loadJson("%s.json" % username)
	config.pop("#1", False)
	config.pop("#2", False)
	forgery = zen.loadJson("%s.forgery" % username, os.path.join(zen.DATA, username))
	forgery["contributions"] = OrderedDict(sorted([item for item in forgery["contributions"].items()], key=lambda i:i[-1], reverse=True))
	return flask.render_template("delegate.html", username=username, forgery=forgery, config=config)
Пример #6
0
def checkApplied(username):
    folder = os.path.join(zen.DATA, username)
    sqlite = initDb(username)
    cursor = sqlite.cursor()

    for name in [n for n in os.listdir(folder) if n.endswith(".registry")]:
        full_registry = loadJson(name, folder=folder)
        # try to lad a milestone first, if no one exists
        registry = loadJson(name+".milestone", folder=folder)
        # if void dict returned by loadJson, then load registry file
        if not len(registry):
            registry = dict(full_registry) #loadJson(name, folder=folder)
            logMsg("starting transaction check from %s..." % name)
        else:
            logMsg("resuming transaction check from %s..." % (name+".milestone"))

        start = time.time()
        transactions = list(registry.values())
        for tx in transactions:
            if zen.misc.transactionApplied(tx["id"]):
                logMsg("transaction %(id)s <type %(type)s> applied" % registry.pop(tx["id"]))
                if "payments" in tx.get("asset", {}):
                    for record in tx["asset"]["payments"]:
                        cursor.execute(
                            "INSERT OR REPLACE INTO transactions(filename, timestamp, amount, address, id) VALUES(?,?,?,?,?);",
                            (os.path.splitext(name)[0], tx["timestamp"], int(record["amount"])/100000000., record["recipientId"], tx["id"])
                        )
            # set a milestone every 5 seconds
            if (time.time() - start) > 5.:
                sqlite.commit()
                dumpJson(registry, name+".milestone", folder=folder)
                logMsg("milestone set (%d transaction left to check)" % len(registry))
                start = time.time()
        dumpJson(registry, name+".milestone", folder=folder)

        if len(registry) == 0:
            dumpJson(full_registry, name, folder=os.path.join(folder, "backup"))
            try:
                os.remove(os.path.join(folder, name))
                os.remove(os.path.join(folder, name+".milestone"))
            except:
                pass
            checked_tx = full_registry.values()
            zen.misc.notify("Payroll successfully broadcasted !\n%.8f %s sent trough %d transactions" % (
                sum([sum([int(rec["amount"]) for rec in tx["asset"].get("payments", [])]) for tx in checked_tx])/100000000.,
                dposlib.rest.cfg.symbol,
                len(checked_tx)
            ))
        else:
            zen.misc.notify("Transactions are still to be checked (%d)..." % len(registry))

        sqlite.commit()
Пример #7
0
def checkIfForging():
    config = zen.loadJson("root.json").get("tasks-enabled",
                                           {}).get("checkIfForging", {})
    active_delegates = zen.biom.dposlib.rest.cfg.activeDelegates
    notification_delay = config.get("notification-delay", 10 * 60)
    monitored_peer = config.get("monitored-peer", zen.API_PEER)
    usernames = [
        name.split("-")[0] for name in os.listdir(zen.JSON)
        if name.endswith("-webhook.json")
    ]

    for user in usernames:
        dlgt = _GET.api.delegates(user, peer=monitored_peer).get("data", {})
        last_block = dlgt.get("blocks", {}).get("last", {})
        last_computed_block = zen.loadJson("%s.last.block" % user,
                                           folder=zen.DATA)
        if dlgt and last_computed_block == {}:
            zen.dumpJson(last_block, "%s.last.block" % user, folder=zen.DATA)
            return False
        elif dlgt.get("rank", 52) <= active_delegates:
            blkchn = _GET.api.blockchain(peer=monitored_peer).get("data", {})
            height = blkchn.get("block", {}).get("height", 0)
            current_round = (height - 1) // active_delegates
            dlgt_round = (last_block["height"] - 1) // active_delegates

            diff = current_round - dlgt_round
            missed = last_computed_block.get("missed", 0)
            if diff > 1:
                now = time.time()
                last_computed_block["missed"] = missed + 1
                delay = now - last_computed_block.get("notification", 0)
                msg = ("%s just missed a block" % user) if missed < 1 else (
                    "%s is missing blocks (total %d)" % (user, missed + 1))
                if delay > notification_delay:
                    zen.misc.notify(msg)
                    last_computed_block["notification"] = now
            elif missed > 0:
                msg = "%s is forging again" % user
                zen.misc.notify(msg)
                last_computed_block.pop("notification", False)
                last_computed_block.pop("missed", False)
            else:
                msg = "%s is forging" % user

            last_computed_block.update(last_block)
            zen.dumpJson(last_computed_block,
                         "%s.last.block" % user,
                         folder=zen.DATA)
            zen.logMsg("round check [delegate:%d | blockchain:%d] - %s" %
                       (dlgt_round, current_round, msg))
    return True
Пример #8
0
def broadcast(username, chunk_size=30):
    # initialize options
    tbw = loadJson("tbw.json")
    chunk_size = max(5, tbw.get("chunk_size", chunk_size))
    folder = os.path.join(zen.DATA, username)

    # proceed all registry file found in username folder
    for name in [n for n in os.listdir(folder) if n.endswith(".registry")]:
        registry = loadJson(name, folder=folder)
        transactions = sorted(list(registry.values()), key=lambda t:t["nonce"])
        for chunk in (transactions[x:x+chunk_size] for x in range(0, len(transactions), chunk_size)):
            response = rest.POST.api.transactions(transactions=chunk, **({"peer":zen.API_PEER} if zen.misc.delegateIsForging(username) else {}))
            logMsg("broadcasting chunk of transactions...\n%s" % json.dumps(response, indent=2))
        zen.misc.notify("New payroll started : %d transactions sent to delegate node..." % len(transactions))
Пример #9
0
def regenerateUnapplied(username, filename):
    registry = zen.loadJson("%s.registry" % filename,
                            os.path.join(zen.DATA, username))
    tbw = zen.loadJson("%s.tbw" % filename,
                       os.path.join(zen.TBW, username, "history"))

    for tx in registry.values():
        if not transactionApplied(tx["id"]):
            zen.logMsg('tx %(id)s [%(amount)s --> %(recipientId)s] unapplied' %
                       tx)
        else:
            tbw["weight"].pop(tx["recipientId"], False)

    zen.dumpJson(tbw, '%s-unapplied.tbw' % filename,
                 os.path.join(zen.TBW, username))
Пример #10
0
def load():
    zen.ENV = None
    zen.PUBLIC_IP = None
    zen.WEBHOOK_PEER = None
    zen.API_PEER = None

    root = zen.loadJson("root.json")
    zen.PORT = root.get("port", 5000)
    if "env" in root:
        zen.ENV = loadEnv(root["env"])
        zen.PUBLIC_IP = '127.0.0.1'
        zen.WEBHOOK_PEER = "http://127.0.0.1:%s" % zen.ENV.get(
            "CORE_WEBHOOKS_PORT", "4004")
        zen.API_PEER = "http://127.0.0.1:%s" % zen.ENV.get(
            "CORE_API_PORT", "4003")
    else:
        zen.WEBHOOK_PEER = root.get("webhook", False)
        zen.API_PEER = root.get("api", False)

    if zen.PUBLIC_IP != '127.0.0.1':
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            # doesn't even have to be reachable
            s.connect(('10.255.255.255', 1))
            zen.PUBLIC_IP = s.getsockname()[0]
        except Exception:
            zen.PUBLIC_IP = '127.0.0.1'
        finally:
            s.close()

    dposlib.rest.use(root.get("blockchain", "dark"))
    custom_peers = root.get("custom_peers", [])
    if len(custom_peers) > 0:
        zen.biom.dposlib.core.stop()
        zen.biom.dposlib.rest.cfg.peers = custom_peers
Пример #11
0
def zen_history(username, page, n):
	if username not in [name.split("-")[0] for name in os.listdir(zen.JSON) if name.endswith("-webhook.json")]:
		return "", 400
	
	cursor = connect(username)
	history_folder = os.path.join(zen.ROOT, "app", ".tbw", username, "history")

	tbw_list = [r["filename"] for r in cursor.execute("SELECT DISTINCT filename FROM transactions").fetchall()]
	tbw_list.sort(reverse=True)

	n_tbw = len(tbw_list)
	n_page = int(math.ceil(float(n_tbw) / n))
	start = page*n

	selection = list(sorted(tbw_list, reverse=True))[start:start+n]
	data = dict([name, zen.loadJson(name+".tbw", folder=history_folder)] for name in selection)

	details = dict(
		[name, cursor.execute("SELECT * FROM transactions WHERE filename = ? ORDER BY amount DESC", (name,)).fetchall()] \
		for name in selection
	)

	return flask.render_template("history.html",
		username=username,
		curent_page=page,
		page_number=n_page,
		entry_number=n,
		selection=selection,
		data=data,
		details=details
	)
Пример #12
0
def faq():
    registered_usernames = [
        name.split("-")[0] for name in os.listdir(zen.JSON)
        if name.endswith("-webhook.json")
    ]

    data = dict((k, v) for k, v in dposlib.core.cfg.__dict__.items()
                if not k.startswith('_'))
    data["begintime"] = data["begintime"].strftime("%Y-%m-%dT%H:%M:%S.000Z")
    try:
        data["blocktime"] = dposlib.core.mixin.deltas()["real blocktime"]
    except Exception as e:
        zen.logMsg('error occured computing deltas : %s' % e)

    delegates = dict([
        username,
        dict(zen.loadJson(username + ".json", zen.JSON),
             **dposlib.rest.GET.api.delegates(username, returnKey="data"))
    ] for username in registered_usernames)

    for username in registered_usernames:
        minvote = delegates[username].get("minimum_vote", 0.) * 100000000
        maxvote = delegates[username].get("maximum_vote", None)
        if isinstance(maxvote, (int, float)):
            maxvote *= 100000000
            _max = lambda v, maxi=maxvote: min(maxi, v)
        else:
            _max = lambda v, maxi=maxvote: v
        _min = lambda v, mini=minvote: v if v >= mini else 0
        delegates[username]["votes"] = sum([
            _min(_max(float(v["balance"]))) for v in zen.misc.loadPages(
                dposlib.rest.GET.api.delegates.__getattr__(username).voters)
        ]) / 100000000

    return flask.render_template("faq.html", info=data, delegates=delegates)
Пример #13
0
def freemobile_sendmsg(title, body):
    freemobile = zen.loadJson("freemobile.json")
    if freemobile != {}:
        freemobile["msg"] = title + ":\n" + body
        return zen.biom.dposlib.rest.POST.sendmsg(
            peer="https://smsapi.free-mobile.fr",
            _jsonify=freemobile
        )
Пример #14
0
def checkNode():
    global REPORT
    REPORT = {}

    root = zen.loadJson("root.json")
    config = root.get("tasks-enabled", {}).get("checkNode", {})

    seed_peer = config.get("seed-peer", False)
    if not seed_peer:
        zen.logMsg("no seed peer defined")
        return "no seed peer defined"

    monitored_peer = config.get("monitored-peer", zen.API_PEER)
    syncing = _GET.api.node.syncing(peer=monitored_peer).get("data", {})
    status = _GET.api.node.status(peer=seed_peer).get("data", {})
    notification_delay = config.get("notification-delay", 5 * 60)

    if syncing == {}:
        msg = "%s not responding" % monitored_peer
        now = time.time()
        if now - REPORT.get("not responding", now) > notification_delay:
            REPORT["not responding"] = time.time()
            zen.logMsg(msg)
            zen.misc.notify(msg)
        return msg
    elif REPORT.pop("not responding", False):
        msg = "%s is active again" % monitored_peer
        zen.logMsg(msg)
        zen.misc.notify(msg)

    if root.get("env", False):
        height = int(
            subprocess.check_output(
                shlex.split(
                    '/usr/bin/psql -qtAX -d ark_mainnet -c '
                    '"SELECT height FROM blocks ORDER BY height DESC LIMIT 1"')
            ).strip())
    else:
        height = syncing["height"]

    height_diff = status.get("now", height) - height

    if syncing.get("syncing", False):
        msg = "%s not synced: height diff %s" % (monitored_peer, height_diff)
        now = time.time()
        if now - REPORT.get("not synced", now) > notification_delay:
            REPORT["not synced"] = time.time()
            zen.logMsg(msg)
            zen.misc.notify(msg)
    elif REPORT.pop("not responding", False):
        msg = "%s synced at height %s" % (monitored_peer, height_diff)
        zen.logMsg(msg)
        zen.misc.notify(msg)
    else:
        msg = "%s synced @ height %s" % (monitored_peer, height)

    return msg
Пример #15
0
def pushover_messages(title, body):
    pushover = zen.loadJson("pushover.json")
    if pushover != {}:
        return zen.rest.POST("1",
                             "messages.json",
                             peer="https://api.pushover.net",
                             urlencode=dict(message=body,
                                            title=title,
                                            **pushover))
Пример #16
0
def _enableTask(delay, func, **params):
    if func not in ["enableTask", "disableTask"]:
        config = zen.loadJson("root.json")
        params.update(interval=delay)
        config["tasks-enabled"] = dict(
            config.get("tasks-enabled", {}), **{
                func: dict([k.replace("_", "-"), v] for k, v in params.items())
            })
        zen.dumpJson(config, "root.json")
Пример #17
0
def pushbullet_pushes(title, body):
    pushbullet = zen.loadJson("pushbullet.json")
    if pushbullet != {}:
        return zen.biom.dposlib.rest.POST.v2.pushes(
            peer="https://api.pushbullet.com",
            body=body, title=title, type="note",
            headers={
                'Access-Token': pushbullet["token"],
            }
        )
Пример #18
0
def faq():
	data = dict((k,v) for k,v in dposlib.core.cfg.__dict__.items() if not k.startswith('_'))
	data["begintime"] = data["begintime"].strftime("%Y-%m-%dT%H:%M:%S.000Z")
	try:
		data["blocktime"] = dposlib.core.mixin.deltas()["real blocktime"]
	except Exception as e:
		zen.logMsg('error occured computing deltas : %s' % e)
	delegates = dict(
		[username, dict(zen.loadJson(username+".json", zen.JSON), **dposlib.rest.GET.api.delegates(username, returnKey="data"))] for \
		username in [name.split("-")[0] for name in os.listdir(zen.JSON) if name.endswith("-webhook.json")]
	)
	return flask.render_template("faq.html", info=data, delegates=delegates)
Пример #19
0
def updateSnapshot():
	root = zen.loadJson("root.json")
	network = root["name"]
	appname = os.path.basename(root["config_folder"])
	snapdir = os.path.expanduser(os.path.join("~", ".local", "share", appname, network, "snapshots"))
	snapshots = getSnapshots(snapdir)

	if not os.system('ark snapshot:dump --blocks %(snapshot)s' % {"snapshot": snapshots[-1]}):
		for snapshot in snapshots:
			os.system('rm -rf "%s"' % os.path.join(snapdir, snapshot))
		zen.misc.notify("Blockchain snapped !")
	os.system('cd ~ && tar cf ~/last-snapshot.tar .local/share/ark-core/%(network)s/snapshots/1-*' % {"network": network})
Пример #20
0
def tweak():
    tbw_config = zen.loadJson("tbw.json")
    token = dposlib.core.cfg.symbol
    return dict(
        url_for=dated_url_for,
        tbw_config=tbw_config,
        _currency=lambda value, fmt="r": flask.Markup(("%"+fmt+"&nbsp;%s") % (round(value,8), token)),
        _dhm=lambda value: human_dhm(*dhm(value)),
        _address=lambda address: flask.Markup(
            '<span class="not-ellipsed">%s</span><span class="ellipsed">%s</span>' % 
            (address, "%s&nbsp;&#x2026;&nbsp;%s" % (address[:5],address[-5:])))
    )
Пример #21
0
def rebuildFromZero():
	root = zen.loadJson("root.json")
	appname = os.path.basename(root["config_folder"])
	snapdir = os.path.expanduser(os.path.join("~", ".local", "share", appname, root["name"], "snapshots"))
	snapshots = getSnapshots(snapdir)

	zen.misc.stop_pm2_app("ark-core")
	zen.misc.stop_pm2_app("ark-forger")
	zen.misc.stop_pm2_app("ark-relay")
	os.system('ark snapshot:restore --blocks %(snapshot)s --truncate' % {"snapshot": snapshots[-1]})
	zen.misc.start_pm2_app("ark-relay")
	zen.misc.start_pm2_app("ark-forger")
Пример #22
0
def setDelegate(uname_or_puk, peer=None):
    peer = zen.WEBHOOK_PEER if peer is None else peer
    account = dposlib.rest.GET.api.wallets(uname_or_puk).get("data", {})
    attributes = account.get("attributes", {})

    if attributes.get("delegate", False):
        username = attributes["delegate"]["username"]
        config = zen.loadJson("%s.json" % username)
        config["publicKey"] = account["publicKey"]
        zen.logMsg("%s configuration:" % username)

        if "#1" not in config:
            config["#1"] = askPrivateKey("enter first secret: ",
                                         config["publicKey"])
            if not config.get("#1", False):
                zen.logMsg("\ndelegate identification failed")
                return False

        if "secondPublicKey" in attributes:
            config["#2"] = askPrivateKey("enter second secret: ",
                                         attributes["secondPublicKey"])
            if not config.get("#2", False):
                zen.logMsg("\ndelegate identification failed")
                return False

        overwrite = input("Overwrite previous webhoook?[Y/n] ") \
            if os.path.exists(
                os.path.join(zen.JSON, "%s-webhook.json" % username)
            ) else "y"

        if overwrite in "yY":
            if not waitForPeer(peer):
                zen.logMsg("%s peer unreachable" % peer)
                return False
            webhook = setWebhook(config["publicKey"])
            if "token" in webhook:
                webhook["peer"] = peer
                zen.logMsg("webhook subscription succeded")
                zen.dumpJson(webhook, "%s-webhook.json" % username)
            else:
                zen.logMsg("an error occured with webhook subscription:\n%s" %
                           webhook)

        zen.dumpJson(config, "%s.json" % username)

    else:
        zen.logMsg(
            "%s seems not to be a valid delegate username or public key" %
            uname_or_puk)
        return False

    return True
Пример #23
0
def checkRegistries():
    for username in [
            name for name in os.listdir(zen.DATA)
            if os.path.isdir(os.path.join(zen.DATA, name))
    ]:
        block_delay = zen.loadJson("%s.json" % username).get(
            "block_delay", False)
        blocks = zen.loadJson("%s.forgery" % username,
                              folder=os.path.join(zen.DATA,
                                                  username)).get("blocks", 0)
        if block_delay and blocks >= block_delay:
            zen.logMsg("%s payroll triggered by block delay : %s [>= %s]" %
                       (username, blocks, block_delay))
            zen.tbw.extract(username)
        else:
            zen.tbw.checkApplied(username)
            zen.logMsg("%s registry checked : %s [< %s]" %
                       (username, blocks, block_delay))

        if zen.tbw.dumpRegistry(username):
            zen.tbw.broadcast(username)
            zen.logMsg("%s registry dumped and broadcasted" % username)
Пример #24
0
def pushBackKeys():
    module = sys.modules[__name__]
    delegates = []
    for key, value in [(k, v) for k, v in module.__dict__.items()
                       if k[-2:] in "#1#2"]:
        username, num = key.replace("_", "").split("#")
        num = "#" + num
        config = zen.loadJson("%s.json" % username)
        config[num] = value
        zen.dumpJson(config, "%s.json" % username)
        delegates.append(username)

    for username in set(delegates):
        zen.logMsg("%s secrets pushed back" % username)
Пример #25
0
def setDelegate(pkey, webhook_peer, public=False):
    printNewLine()
    # for each publicKey, get account data (merge delegate and wallet info)
    req = rest.GET.api.delegates(pkey).get("data", {})
    account = rest.GET.api.wallets(pkey).get("data", {})
    account.update(req)

    if account != {}:
        username = account["username"]
        logMsg("setting up %s delegate..." % username)
        # load forger configuration and update with minimum data
        config = loadJson("%s.json" % username)
        config.update(**{"publicKey":pkey, "#2":askSecret(account, cmp_key="secondPublicKey")})
        dumpJson(config, "%s.json" % username)
        # create a webhook if no one is set
        webhook = loadJson("%s-webhook.json" % username)
        if not webhook.get("token", False):
            data = rest.POST.api.webhooks(
                peer=webhook_peer,
                event="block.forged",
                target="http://%s:5000/block/forged" % (zen.PUBLIC_IP if public else "127.0.0.1"),
                conditions=[{"key": "generatorPublicKey", "condition": "eq", "value": pkey}]
            )
            webhook = data.get("data", False)
            if webhook:
                webhook["peer"] = webhook_peer
                dumpJson(webhook, "%s-webhook.json" % username)
                logMsg("%s webhook set" % username)
            else:
                logMsg("error occur on webhook creation:\n%s" % data)
        else:
            logMsg("webhook already set for delegate %s" % username)
        logMsg("%s delegate set" % username)
        return account
    else:
        logMsg("%s: %s" % (req.get("error", "API Error"), req.get("message", "...")))
Пример #26
0
def checkRegistries():
    try:
        for username in [
                name for name in os.listdir(zen.DATA)
                if os.path.isdir(os.path.join(zen.DATA, name))
        ]:
            block_delay = zen.loadJson("%s.json" % username).get(
                "block_delay", False)
            blocks = zen.loadJson("%s.forgery" % username,
                                  folder=os.path.join(zen.DATA, username)).get(
                                      "blocks", 0)
            if block_delay and blocks >= block_delay:
                zen.logMsg("%s payroll triggered by block delay : %s [>= %s]" %
                           (username, blocks, block_delay))
                zen.tbw.extract(username)
                zen.tbw.dumpRegistry(username)
                zen.tbw.broadcast(username)
            else:
                zen.tbw.checkApplied(username)
                zen.logMsg("%s registry checked : %s [< %s]" %
                           (username, blocks, block_delay))
    except Exception as e:
        zen.logMsg("transaction check error:\n%r\n%s" %
                   (e, traceback.format_exc()))
Пример #27
0
def spread():
    if flask.request.method == "POST":
        block = json.loads(flask.request.data).get("data", False)
        if not block:
            raise Exception("Error: can not read data")
        else:
            generatorPublicKey = block["generatorPublicKey"]
        username = getUsernameFromPublicKey(generatorPublicKey)
        if not username:
            raise Exception("Error: can not reach username")
        # check autorization and exit if bad one
        webhook = loadJson("%s-webhook.json" % username)
        if not webhook["token"].startswith(flask.request.headers["Authorization"]):
            raise Exception("Not autorized here")
        zen.tbw.TaskExecutioner.JOB.put([username, generatorPublicKey, block])
    return json.dumps({"zen-tbw::block/forged":True})
Пример #28
0
def adjust(username, value):
    if getPublicKeyFromUsername(username):
        folder = os.path.join(zen.DATA, username)
        forgery = loadJson("%s.forgery" % username, folder=folder)
        total = sum(forgery["contributions"].values())
        dumpJson(
            {
                "fees": forgery.get("fees", 0.),
                "blocks": forgery.get("blocks", 0),
                "contributions": OrderedDict(sorted([[a, v/total*value] for a,v in forgery["contributions"].items()], key=lambda e:e[-1], reverse=True))
            },
            "%s.forgery" % username,
            folder=folder
        )
    else:
        logMsg("%s username does not exist" % username)
Пример #29
0
def generateCharts():
    try:
        delegates = dict(
            [username, dict(zen.loadJson(username+".json", zen.JSON), **zen.dposlib.rest.GET.api.delegates(username, returnKey="data"))] for \
            username in [name.split("-")[0] for name in os.listdir(zen.JSON) if name.endswith("-webhook.json")]
        )
        real_blocktime = mixin.deltas()["real blocktime"]
        [
            zen.misc.chartAir(delegates[username]["share"], 50, username,
                              real_blocktime) for username in delegates
        ]
        [zen.misc.generateChart(username) for username in delegates]
        zen.misc.chartAir(1., 50, "", real_blocktime)
        zen.logMsg("charts successfully generated")
    except Exception as e:
        zen.logMsg("chart generation error:\n%r\n%s" %
                   (e, traceback.format_exc()))
Пример #30
0
def pullKeys():
    module = sys.modules[__name__]
    for username in [
            n.replace("-webhook.json", "") for n in next(os.walk(zen.JSON))[-1]
            if n.endswith("-webhook.json")
    ]:
        config = zen.loadJson("%s.json" % username)
        hide = False
        if "#1" in config:
            setattr(module, "_%s_#1" % username, config.pop("#1"))
            hide = True
        if "#2" in config:
            setattr(module, "_%s_#2" % username, config.pop("#2"))
            hide = True
        if hide:
            zen.logMsg("%s secrets pulled" % username)
            zen.dumpJson(config, "%s.json" % username)