Exemple #1
0
def init():
    global DAEMON_PEERS

    data = rest.GET.api.v2.node.configuration().get("data", {})

    constants = data["constants"]
    cfg.blocktime = constants["blocktime"]
    cfg.begintime = pytz.utc.localize(
        datetime.strptime(constants["epoch"], "%Y-%m-%dT%H:%M:00.000Z"))
    cfg.delegate = constants["activeDelegates"]

    cfg.headers["nethash"] = data["nethash"]
    cfg.headers["version"] = str(data["version"])
    cfg.headers["API-Version"] = "2"

    cfg.fees = constants["fees"]
    cfg.doffsets = constants["dynamicOffsets"]
    cfg.feestats = dict([i["type"], i["fees"]]
                        for i in data.get("feeStatistics", {}))
    cfg.explorer = data["explorer"]
    cfg.token = data["token"]
    cfg.symbol = data["symbol"]
    cfg.ports = data["ports"]

    select_peers()
    DAEMON_PEERS = rotate_peers()
    Transaction.setDynamicFee()
Exemple #2
0
def logout():
	"""Clean up all global variables and reset session cookies"""
	global LOGGED, CURRENT_TX, TX_GENESIS
	flask.session.clear()
	Transaction.unlink()
	LOGGED = False
	TX_GENESIS = []
	return flask.redirect(flask.url_for("login"))
Exemple #3
0
	def send(self, amount, recipientId, vendorField=None, **kw):
		# create a type-1-transaction
		tx = Transaction(type=0, amount=amount*100000000, recipientId=recipientId, vendorField=vendorField, **kw)
		# sign if a public and private keys exists
		try: tx.finalize()
		# if no key: return orphan tx
		except: return tx
		# else broadcast tx
		else: return rest.POST.api.transactions(transactions=[tx])
Exemple #4
0
def use(network):
	global LOGGED
	if network != flask.session.get("network", False):
		rest.use(network)
		flask.session["network"] = cfg.network
		Transaction.unlink()
		LOGGED = False
		return flask.redirect(flask.url_for("logout"))
	else:
		return flask.redirect(flask.url_for("account"))
Exemple #5
0
def unlock():
	if flask.request.method == "POST":
		Transaction.link(None, flask.request.form["secondSecret"])
		if Transaction._secondPublicKey == flask.session["secondPublicKey"]:
			flask.session["secondPublicKey"] = False
			flask.flash('Account unlocked !', category="success")
			return flask.redirect(flask.url_for("account"))
		else:
			flask.flash('Second public key does not match !', category="error")
			return flask.redirect(flask.url_for("unlock"))
	else:
		return flask.render_template("unlock.html")
Exemple #6
0
def downVote(*usernames):
	return Transaction(
		type=3,
		asset={
			"votes": ["-"+rest.GET.api.delegates(username, returnKey="data")["publicKey"] for username in usernames]
		},
	)
Exemple #7
0
def registerIPFS(dag):
	return Transaction(
		type=5,
		asset={
			"ipfs": {"dag": dag}
		}
	)
Exemple #8
0
def init():
	global DAEMON_PEERS

	data = rest.GET.api.v2.node.configuration().get("data", {})
	cfg.__data__ = data

	if data != {}:
		cfg.explorer = data["explorer"]
		cfg.pubKeyHash = data["version"]
		cfg.token = data["token"]
		cfg.symbol = data["symbol"]
		cfg.ports = dict([k.split("/")[-1],v] for k,v in data["ports"].items())
		cfg.headers["nethash"] = data["nethash"]
		cfg.headers["API-Version"] = "2"

		constants =  data["constants"]
		cfg.delegate = constants["activeDelegates"]
		cfg.maxlimit = constants["block"]["maxTransactions"]
		cfg.blocktime = constants["blocktime"]
		cfg.begintime = pytz.utc.localize(datetime.strptime(constants["epoch"], "%Y-%m-%dT%H:%M:%S.000Z"))
		cfg.blockreward = constants["reward"]/100000000.
		cfg.fees = constants["fees"]

		cfg.feestats = dict([i["type"],i["fees"]] for i in data.get("feeStatistics", {}))
		# on v 2.0.x dynamicFees field is in "fees" field
		cfg.doffsets = cfg.fees.get("dynamicFees", {}).get("addonBytes", {})
		# on v 2.1.x dynamicFees field is in "transactionPool" Field
		cfg.doffsets.update(data.get("transactionPool", {}).get("dynamicFees", {}).get("addonBytes", {}))
		# on v 2.4.x wif and slip44 are provided by network
		if "wif" in data: cfg.wif = hex(data["wif"])[2:]
		if "slip44" in data: cfg.slip44 = str(data["slip44"])
		# on v 2.4.x feestatistics moved to api.node.fees endpoint
		if cfg.feestats == {}:
			cfg.feestats = dict([int(i["type"]), {
				"avgFee": int(i["avg"]),
				"minFee": int(i["min"]),
				"maxFee": int(i["min"]),
				"medFee": int(i["median"])
			}] for i in rest.GET.api.node.fees().get("data", []))

		DAEMON_PEERS = rotate_peers()
		Transaction.useDynamicFee()

	else:
		raise Exception("Initialization error")
Exemple #9
0
def multiSignature(*publicKeys, **kwargs):  #lifetime=72, minimum=2):
    return Transaction(type=4,
                       asset={
                           "multisignature": {
                               "keysgroup": publicKeys,
                               "lifetime": kwargs.get("lifetime", 72),
                               "min": kwargs.get("minimum", 2),
                           }
                       })
Exemple #10
0
def multiPayment(*pairs, **kwargs):
	return Transaction(
		type=7,
		vendorField=kwargs.get("vendorField", None),
		asset={
			"payments": [
				{"amount":a, "recipientId":r} for r,a in pairs
			]
		}
	)
Exemple #11
0
def timelockTransfer(amount, address, lockvalue, locktype="timestamp", vendorField=None):
	return Transaction(
		type=6,
		amount=amount*100000000,
		recipientId=address,
		vendorField=vendorField,
		timelock=lockvalue,
		timelockType={
			"timestamp":0,
			"blockheight":1
		}[locktype]
	)
Exemple #12
0
def init():
    global DAEMON_PEERS
    Transaction.setStaticFee()

    cfg.begintime = datetime(*cfg.begintime, tzinfo=pytz.UTC)
    response = rest.GET.api.loader.autoconfigure()
    if response["success"]:
        network = response["network"]
        if "version" not in cfg.headers:
            cfg.headers["version"] = str(network.pop('version'))
        cfg.headers["nethash"] = network.pop('nethash')
        cfg.headers["API-Version"] = "1"
        cfg.__dict__.update(network)
        cfg.fees = rest.GET.api.blocks.getFees()["fees"]
        # select peers immediately and keep refreshing them in a thread so we
        # are sure we make requests to working peers
        select_peers()
        DAEMON_PEERS = rotate_peers()
    else:
        raise Exception("Initialization error with peer %s" %
                        response.get("peer", "???"))
Exemple #13
0
def upVote(*usernames):
    return Transaction(
        type=3,
        asset={
            "votes": {
                "username": [
                    "+" + rest.GET.api.delegates.get(
                        username=username, returnKey="delegate")["publicKey"]
                    for username in usernames
                ]
            }
        })
Exemple #14
0
def login():
	global LOGGED

	flask.session["permanent"] = True

	if LOGGED:
		if not flask.session.get("data", False):
			flask.flash("Session expired !", category="warning")
			Transaction.unlink()
			LOGGED = False
		else:
			return flask.redirect(flask.url_for("account"))

	elif not flask.session.get("network", False):
		flask.session["network"] = cfg.network

	# 
	if flask.request.method == "POST":
		Transaction.link(flask.request.form["secret"])
		publicKey = Transaction._publicKey
		address = dposlib.core.crypto.getAddress(publicKey)
		# get info from address and public key
		account = rest.GET.api.accounts(address=address).get("account", {})
		# account.update(**rest.GET.api.delegates.get(publicKey=KEYS["publicKey"]).get("delegate", {}))
		account.update(**rest.GET.api.delegates.get(publicKey=publicKey).get("delegate", {}))
		account["voted"] = [d["username"] for d in rest.GET.api.accounts.delegates(address=address).get("delegates", [])]
		account["address"]= address

		flask.session.clear()
		flask.session["data"] = account
		flask.session["secondPublicKey"] = account.get("secondPublicKey", False)
		flask.session["begin"] = (cfg.begintime - datetime.datetime(1970,1,1, tzinfo=pytz.UTC)).total_seconds()
		flask.session["explorer"] = cfg.explorer
		flask.session["symbol"] = cfg.symbol
		flask.session["dlgtnum"] = cfg.delegate
		flask.session["maxvote"] = cfg.maxvote
		flask.session["network"] = cfg.network
		#
		flask.flash('You are now logged to %s wallet...' % address, category="success")
		LOGGED = True

	# if data is set to session --> login successfull
	if flask.session.get("data", False):
		return flask.render_template("account.html")
	else:
		Transaction.unlink()
		LOGGED = False
		return flask.render_template("login.html")
Exemple #15
0
def transfer(amount, address, vendorField=None):
    return Transaction(type=0,
                       amount=amount * 100000000,
                       recipientId=address,
                       vendorField=vendorField)
Exemple #16
0
def registerAsDelegate(username):
    return Transaction(type=2, asset={"delegate": {"username": username}})
Exemple #17
0
def registerSecondPublicKey(secondPublicKey):
    return Transaction(type=1,
                       asset={"signature": {
                           "publicKey": secondPublicKey
                       }})
Exemple #18
0
def delegateResignation():
	return Transaction(
		type=8
	)
Exemple #19
0
def nTransfer(*pairs, **kwargs):  #, vendorField=None):
    return Transaction(type=7,
                       vendorField=kwargs.get("vendorField", None),
                       asset=dict(pairs))