Ejemplo n.º 1
0
def init(seed=None):
    token = None
    json_file = os.path.join(ROOT, ".json", "blockfrost.token")
    tokens = data.loadJson(json_file)

    available = [t for t in tokens if tokens[t] == rest.cfg.network]
    if available:
        try:
            sys.stdout.write("Available token [0=last]:\n")
            for t in available:
                sys.stdout.write(" - %d : %s\n" % (available.index(t)+1, t))
            token = available[int(input("Select token number > "))-1]
        except Exception:
            pass
        else:
            sys.stdout.write("Blockfrost account: %s\n" % token)

    if not token:
        token = input("Paste your blockfrost.io token > ")

    cfg.headers["project_id"] = token

    check = rest.GET.health.clock().get("status", False) == 200
    if check:
        tokens[token] = rest.cfg.network
        data.dumpJson(tokens, json_file)

    return check
Ejemplo n.º 2
0
def _storage_clean_up():
    if not hasattr(rest.cfg, "pubkeyHash"):
        return

    path = os.path.join(dposlib.ROOT, ".registry", rest.cfg.network)
    if not os.path.exists(path):
        return

    for name in os.listdir(path):
        address = dposlib.core.crypto.getAddress(name)
        filepath = os.path.join(path, name)
        nonce = int(
            rest.GET.api.wallets(address).get("data", {}).get("nonce", 0))

        data = loadJson(filepath)
        msg = []
        for txid in list(data.keys()):
            if data[txid].get("nonce", 0) <= nonce:
                data.pop(txid)
                msg.append(txid)

        if len(data):
            dumpJson(data, filepath)
        else:
            os.remove(filepath)

        if len(msg):
            flask.flash("%s - nonce expiration cleanup:\n%s" %
                        (rest.cfg.network, "\n   ".join(msg)))
Ejemplo n.º 3
0
 def open(whk_id):
     data = loadJson(
         os.path.join(dposlib.ROOT, ".webhooks", dposlib.rest.cfg.network,
                      whk_id))
     if len(data):
         return Webhook(data["id"], peer=data["peer"])
     else:
         raise Exception("cannot open webhook %s" % whk_id)
Ejemplo n.º 4
0
 def dump(self):
     """Dumps transaction in current registry."""
     if "id" in self:
         id_ = self["id"]
         pathfile = Transaction.path()
         registry = loadJson(pathfile)
         registry[self["id"]] = self
         dumpJson(registry, pathfile)
Ejemplo n.º 5
0
    def setUpClass(self):
        def fix_fixture(tx):
            for key in [k for k in ["amount", "fee", "nonce"] if k in tx]:
                tx[key] = int(tx.pop(key))
            return tx

        self.fixtures = [
            fix_fixture(tx) for tx in data.loadJson(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             "fixtures.json"))
        ]
        rest.use("ark")
Ejemplo n.º 6
0
def loadNetwork(network):
    # call to multisignature server
    resp = rest.GET.multisignature(network, peer=app.peer)
    # get data from official servers
    resp2 = loadJson(
        os.path.join(SYNCH_FOLDER, "data.%d" % rest.cfg.pubkeyHash))
    # flash a message if nothing found
    if not len(resp.get("data", [])):
        flask.flash("no pending transaction found")
    return flask.render_template("network.html",
                                 response2=resp2,
                                 response=resp,
                                 network=network)
Ejemplo n.º 7
0
def load(network, ms_publicKey, txid):
    """
    Load a transaction from a specific registry.

    Args:
        network (:class:`str`): blockchain name
        ms_publicKey (:class:`str`): encoded-compresed public key as hex string
        txid (:class:`str`): transaction id

    Returns:
        :class:`dict`: transaction data
    """
    registry = loadJson(
        os.path.join(dposlib.ROOT, ".registry", network, ms_publicKey))
    return registry.get(txid, False)
Ejemplo n.º 8
0
def pop(network, tx):
    """
    Remove a transaction from registry. Wallet registry is removed if empty.

    Args:
        network (:class:`str`): blockchain name
        publicKey (:class:`str`): encoded-compresed public key as hex string
    """
    path = os.path.join(dposlib.ROOT, ".registry", network,
                        tx["senderPublicKey"])
    registry = loadJson(path)
    tx.pop("id", False)
    registry.pop(identify(tx), False)
    if not (len(registry)):
        os.remove(path)
    else:
        dumpJson(registry, path)
Ejemplo n.º 9
0
def getWallet(network, ms_publicKey):
    """
    ``GET /multisignature/{network}/{ms_publicKey}`` endpoint. Return all
    pending transactions issued by a specific public key.
    """
    if flask.request.method != "GET":
        return json.dumps({
            "success": False,
            "API error": "GET request only allowed here"
        })

    wallet = loadJson(
        os.path.join(dposlib.ROOT, ".registry", network, ms_publicKey))
    if len(wallet):
        return json.dumps({"success": True, "data": wallet}), 200
    else:
        return json.dumps({"success": False})
Ejemplo n.º 10
0
def getAll(network):
    """
    ``GET /multisignature/{network}`` endpoint. Return all public keys issuing
    multisignature transactions.

    Args:
        network (:class:`str`): blockchain network name
    Returns:
        :class:`dict`: all registries
    """
    result = {}
    search_path = os.path.join(dposlib.ROOT, ".registry", network)
    if os.path.exists(search_path) and os.path.isdir(search_path):
        for name in os.listdir(search_path):
            result[name] = loadJson(os.path.join(search_path, name))
        return json.dumps({"success": True, "data": result}), 200
    else:
        return json.dumps({"success": False})
Ejemplo n.º 11
0
 def delete(self):
     whk_path = os.path.join(dposlib.ROOT, ".webhooks",
                             dposlib.rest.cfg.network, self.id + ".json")
     if os.path.exists(whk_path):
         data = loadJson(whk_path)
         resp = dposlib.rest.DELETE.api.webhooks("%s" % self.id,
                                                 peer=data.get(
                                                     "peer", None))
         if resp.get("status", None) == 204:
             try:
                 os.remove(data["dump"])
             except Exception:
                 pass
             os.remove(whk_path)
         resp.pop('except', False)
         resp.pop('error', False)
         return resp
     else:
         raise Exception("cannot find webhook data")
Ejemplo n.º 12
0
def dump(network, tx):
    """
    Add a transaction into registry. ``senderPublicKey`` field is used to
    create registry if it does not exist.

    Args:
        network (:class:`str`):
            blockchain name
        tx (:class:`dict` or :class:`dposlib.blockchain.Transaction`):
            transaction to store
    """
    path = os.path.join(dposlib.ROOT, ".registry", network,
                        tx["senderPublicKey"])
    registry = loadJson(path)
    tx.pop("id", False)
    id_ = identify(tx)
    registry[id_] = tx
    dumpJson(registry, path)
    return id_
Ejemplo n.º 13
0
def _ark_srv_synch():
    data = {}
    if not hasattr(rest.cfg, "pubkeyHash"):
        return
    path = os.path.join(SYNCH_FOLDER, "data.%d" % rest.cfg.pubkeyHash)
    try:
        for server in loadJson(os.path.join(__path__[0], "server.json")):
            req = rest.GET.transactions(peer=server)
            if req:
                pendings = [
                    _fix_tx(elem["data"]) for elem in req
                    if elem["data"]["network"] == rest.cfg.pubkeyHash
                ]
                data.update(
                    dict([tx["senderPublicKey"], {
                        identify(tx): tx
                    }] for tx in pendings))
                dumpJson(data, path)
    except Exception as error:
        sys.stdout.write("%r\n" % error)
Ejemplo n.º 14
0
 def load(txid):
     """Loads the transaction identified by txid from current registry."""
     return Transaction(loadJson(Transaction.path())[txid])
Ejemplo n.º 15
0
def loadWallet(network, wallet):
    wlt = rest.GET.api.wallets(wallet).get("data", {})
    # if ms wallet never sent or received tx, publicKey is not public
    # so update manually wallet info
    if wlt.get("nonce", 0) and "multiSignature" in wlt:
        ms = wlt["multiSignature"]
        wlt["publicKey"] = dposlib.ark.crypto.getMultiSignaturePublicKey(
            ms["min"], *ms["publicKeys"])

    if len(wlt):

        host_url = flask.request.host_url
        form = flask.request.form
        crypto = dposlib.core.crypto

        if flask.request.method == "POST":
            # form contains secret (https or localhost mode)
            if form.get("secret", None) not in ["", None]:
                keys = crypto.getKeys(form["secret"])
                publicKey = keys["publicKey"]
                signature = crypto.getSignatureFromBytes(
                    crypto.unhexlify(form["serial"]), keys["privateKey"])
            # form contains signature
            elif form.get("signature", None) not in ["", None]:
                try:
                    data = json.loads(form["signature"].strip())
                    signature = data.get("signature", "")
                    publicKey = data.get("publicKey", form["publicKey"])
                except Exception:
                    publicKey = form["publicKey"]
                    signature = form["signature"].strip()
            # form is empty
            else:
                flask.flash("Nothing found to proceed with POST request",
                            category="red")

            try:
                flask.flash(json.dumps(
                    client.putSignature(network, form["ms_publicKey"],
                                        form["id"], publicKey, signature)),
                            category="yellow")
            except Exception:
                pass

        # call to multisignature server
        resp = rest.GET.multisignature(network,
                                       wlt["publicKey"],
                                       peer=app.peer)

        # update with what is found on ark servers
        txs = loadJson(
            os.path.join(SYNCH_FOLDER, "data.%d" % rest.cfg.pubkeyHash)).get(
                wlt["publicKey"], {})
        if len(txs):
            resp.update(txs)
            flask.flash(json.dumps(
                client.postNewTransactions(network, *txs.values())),
                        category="yellow")

        if not len(resp.get("data", {})):
            flask.flash("no pending transaction found")

        return flask.render_template("wallet.html",
                                     secure="127.0.0.1" in host_url
                                     or host_url.startswith("https"),
                                     items=sorted(resp.get("data", {}).items(),
                                                  key=lambda i: i[1]["nonce"]),
                                     network=network,
                                     wallet=wlt)

    flask.flash("'%s' wallet not found" % wallet, category="red")
    # if redirect, flash messages are losed with https
    return loadNetwork(network=network)