Ejemplo n.º 1
0
def getVoteForce(address, **kw):
    """Returns the voting force of the given address."""

    # determine timestamp
    balance = kw.pop("balance", 0) / 100000000.
    if not balance:
        balance = float(
            rest.GET.api.accounts.getBalance(address=address,
                                             returnKey="balance")) / 100000000.
    delta = timedelta(**kw)
    if delta.total_seconds() < 86400:
        return balance
    now = datetime.now(pytz.UTC)
    timestamp_limit = slots.getTime(now - delta)
    # get transaction history
    history = getHistory(address, timestamp_limit)
    # if no transaction over periode integrate balance over delay and return it
    if not history:
        return balance * delta.total_seconds() / 3600
    # else
    end = slots.getTime(now)
    sum_ = 0.
    brk = False
    for tx in history:
        delta_t = (end - tx["timestamp"]) / 3600
        sum_ += balance * delta_t
        balance += ((tx["fee"] + tx["amount"]) if tx["senderId"] == address
                    else -tx["amount"]) / 100000000.
        if tx["type"] == 3:
            brk = True
            break
        end = tx["timestamp"]
    if not brk:
        sum_ += balance * (end - timestamp_limit) / 3600
    return sum_
Ejemplo n.º 2
0
def _getVoteFidelity(contributors, delay=30):
    now = datetime.datetime.now(slots.UTC)
    delta = datetime.timedelta(days=delay)
    total_second = delta.total_seconds()
    limit = now - delta
    timestamp_limit = slots.getTime(limit)
    public_key = wlt.publicKey
    fidelity = {}
    print("Checking %s-day-fidelity from vote history...\n" % delay)
    for addr in contributors:
        data = api.Transaction.getTransactionsList(
            senderId=addr, orderBy="timestamp:desc").get("transactions", [])
        if len(data):
            while data[-1]["timestamp"] > timestamp_limit:
                search = api.Transaction.getTransactionsList(
                    senderId=addr, orderBy="timestamp:desc",
                    offset=len(data)).get("transactions", [])
                data += search
                if len(search) < 50:
                    break
            tx_3 = [t for t in data if t["type"] == 3]
            details = sorted(
                [[t["timestamp"], t["asset"]["votes"][0][0]] for t in tx_3
                 if t["timestamp"] >= timestamp_limit and public_key in
                 t["asset"]["votes"][0] and t["senderId"] != wlt.address],
                key=lambda e: e[0])

        if len(details):
            cumul = 0.
            start = timestamp_limit
            for elem in details:
                if elem[-1] == "+": start = elem[0]
                else: cumul += elem[0] - start
            if elem[-1] == "+": cumul += slots.getTime(now) - start
            fidelity[addr] = cumul / total_second
        else:
            fidelity[addr] = 1.0
    return fidelity
Ejemplo n.º 3
0
def bakeTransaction(**kw):
    if "publicKey" in kw and "privateKey" in kw:
        publicKey, privateKey = kw["publicKey"], kw["privateKey"]
    elif "secret" in kw:
        keys = crypto.getKeys(kw["secret"])
        publicKey = keys["publicKey"]
        privateKey = keys["privateKey"]
    else:
        raise Exception(
            "Can not initialize transaction (no secret or keys given)")

    # put mandatory data
    payload = {
        "timestamp":
        int(slots.getTime()),
        "type":
        int(kw.get("type", 0)),
        "amount":
        int(kw.get("amount", 0)),
        "fee":
        cfg.fees.get({
            0: "send",
            1: "secondsignature",
            2: "delegate",
            3: "vote",
            # 4: "multisignature",
            # 5: "dapp"
        }[kw.get("type", 0)])
    }
    payload["senderPublicKey"] = publicKey

    # add optional data
    for key in (k for k in ["requesterPublicKey", "recipientId", "asset"]
                if k in kw):
        payload[key] = kw[key]

    # sign payload
    payload["signature"] = crypto.getSignature(payload, privateKey)
    if kw.get("secondSecret", None):
        secondKeys = crypto.getKeys(kw["secondSecret"])
        payload["signSignature"] = crypto.getSignature(
            payload, secondKeys["privateKey"])
    elif kw.get("secondPrivateKey", None):
        payload["signSignature"] = crypto.getSignature(payload,
                                                       kw["secondPrivateKey"])

    # identify payload
    payload["id"] = crypto.getId(payload)

    return payload
Ejemplo n.º 4
0
def vote(param):

    lst, verb, to_vote = _getVoteList(param)

    if len(lst):
        sys.stdout.write("Use ledger key to confirm or or cancel :\n")
        sys.stdout.write("    %s %s ?\n" % (verb, ", ".join(to_vote)))
        tx = dict(type=3,
                  timestamp=int(slots.getTime()),
                  fee=cfg.fees["vote"],
                  amount=0,
                  recipientId=DATA.ledger["address"],
                  asset={"votes": lst})

        if _sign(tx, DATA.ledger["path"]):
            _send(tx)
Ejemplo n.º 5
0
    def test_signTx(self):
        """
		Test signing a transaction directly from a ledger wallet
		"""
        rest.use("dark")

        with patch.object(ldgr,
                          'getDongle',
                          return_value=MockedHIDDongleHIDAPI()):
            tx = dict(vendorField="First Tx using ledger with arky!",
                      timestamp=int(slots.getTime()),
                      type=0,
                      amount=1,
                      recipientId='DUGvQBxLzQqrNy68asPcU3stWQyzVq8G49',
                      fee=10000000)
            signed_tx = ldgr.signTx(tx, self.path)
        assert signed_tx
Ejemplo n.º 6
0
def send(param):

    if DATA.ledger:
        amount = floatAmount(param["<amount>"])
        if amount:
            sys.stdout.write("Use ledger key to confirm or or cancel :\n")
            sys.stdout.write("    Send %(amount).8f %(token)s to %(recipientId)s ?\n" % \
                {"token": cfg.token, "amount": amount, "recipientId": param["<address>"]})
            tx = dict(
                type=0,
                timestamp=int(slots.getTime()),
                fee=cfg.fees["send"],
                amount=int(amount * 100000000),
                recipientId=param["<address>"],
                vendorField=param["<message>"],
            )

            if _sign(tx, DATA.ledger["path"]):
                _send(tx)
Ejemplo n.º 7
0
    raise Exception("Can not do something for now !")

logfile = os.path.join(HOME, "Lucky",
                       "%s.pay" % datetime.datetime.now().strftime("%y-%m-%d"))
try:
    os.makedirs(os.path.dirname(logfile))
except:
    pass

log = open(logfile, "w")
header = ["Date", datetime.datetime.now(), ""]
content = ["", "", ""]

wlt.update()
limit = datetime.datetime.now(slots.UTC) - datetime.timedelta(days=7)
timestamp_limit = slots.getTime(limit)

tx = api.Transaction.getTransactionsList(recipientId=wlt.address,
                                         limit=20).get("transactions", [])

if len(tx):
    # get all tx received after timestamp limit
    if tx[0]["timestamp"] > timestamp_limit:
        while tx[0]["timestamp"] > timestamp_limit:
            tx = api.Transaction.getTransactionsList(
                recipientId=wlt.address, limit=20, offset=len(tx)).get(
                    "transactions", []) + tx
    # last filter
    tx = [
        t for t in tx if t["timestamp"] >= timestamp_limit
        and t["amount"] >= 90000000 and t["senderId"] != wlt.address
Ejemplo n.º 8
0
def bakeTransaction(**kw):
    """
	Create transaction localy.

	Argument:
	tx (dict) -- transaction object

	Return dict
	"""
    kw = dict([k, v] for k, v in kw.items() if v)

    if "publicKey" in kw and "privateKey" in kw:
        keys = {}
        keys["publicKey"] = kw["publicKey"]
        keys["privateKey"] = kw["privateKey"]
    elif "secret" in kw:
        keys = crypto.getKeys(kw["secret"])
    else:
        keys = {}
        # raise Exception("Can not initialize transaction (no secret or keys given)")

    # put mandatory data
    payload = {
        "timestamp":
        kw.get("timestamp", int(slots.getTime())),
        "type":
        int(kw.get("type", 0)),
        "amount":
        int(kw.get("amount", 0)),
        "fee":
        cfg.fees.get({
            0: "send",
            1: "secondsignature",
            2: "delegate",
            3: "vote",
            # 4: "multisignature",
            # 5: "dapp"
        }[kw.get("type", 0)])
    }

    # add optional data
    for key in [
            "requesterPublicKey", "recipientId", "vendorField", "asset",
            "signature", "signSignature", "id"
    ]:
        if key in kw:
            payload[key] = kw[key]

    # add sender public key if any key or secret is given
    if len(keys):
        payload["senderPublicKey"] = keys.get("publicKey", None)

        # sign payload if possible
        # if len(keys):
        payload["signature"] = crypto.getSignature(payload, keys["privateKey"])
        if kw.get("secondSecret", False):
            secondKeys = crypto.getKeys(kw["secondSecret"])
            payload["signSignature"] = crypto.getSignature(
                payload, secondKeys["privateKey"])
        elif kw.get("secondPrivateKey", False):
            payload["signSignature"] = crypto.getSignature(
                payload, kw["secondPrivateKey"])
        # identify payload
        payload["id"] = crypto.getId(payload)

    return payload