示例#1
0
def dex_withdraw():

    # undeveloped definition for withdrawals
    from bitshares import BitShares
    bitshares = BitShares()
    bitshares.wallet.unlock("wallet-passphrase")
    bitshares.transfer(to=send_to,
                       amount=send_amount,
                       asset=BTS,
                       memo=None,
                       account=account)
def play_game(account, amountBet, userRoll):

    memo = Memo('bts-dice-game', account)

    nodeForConnections = 'wss://api.bitsharesdex.com'

    blockchain = Blockchain(node=nodeForConnections, mode='head')

    bitshares = BitShares(
        node=nodeForConnections,
        nobroadcast=False,
    )

    blockNum = blockchain.get_current_block_num()

    userGuess = userRoll
    seed(blockNum * (userGuess + 1))

    diceRatios = btsDiceRatios
    winRatio = diceRatios.get_ratio(userGuess)

    value = randint(1, 100)
    correctGuess = value < int(userGuess)

    bitshares.wallet.unlock('superSecretPassword')

    if winRatio is None:
        print('You submitted something not correct to this contract.')
    elif correctGuess:
        winningAmount = winRatio * amountBet
        winningString = "Correct! You guessed {0} and rolled {1}. You won {2:.5f} BTS.".format(
            userRoll, value, winningAmount)
        bitshares.transfer(account,
                           winningAmount,
                           'BTS',
                           winningString,
                           account='bts-dice-game')
        print(winningString)
    else:
        losingString = "Incorrect. You guessed {0} and rolled {1}.".format(
            userRoll, value)
        bitshares.transfer(account,
                           0.00001,
                           'BTS',
                           losingString,
                           account='bts-dice-game')
        print(
            'You guessed incorrectly. Your guess was {a} and you rolled {b}.'.
            format(a=userRoll, b=value))
示例#3
0
def transfer_asset():
    cybex_config(node_rpc_endpoint=NODE_WS_ENDPOINT, chain_id=CHAIN_ID)

    net = BitShares(node=NODE_WS_ENDPOINT, **{'prefix': 'cyb'})

    unlock(net)

    try:
        net.wallet.addPrivateKey(FROM_ACCOUNT_ACTIVE_PRIVATE_KEY)
    except Exception as e:
        pass

    net.wallet.unlock(WALLET_PASSWD)

    acc = Account(FROM_ACCOUNT, bitshares_instance=net)

    net.transfer(TO_ACCOUNT,
                 ASSET_AMOUNT,
                 ASSET_NAME,
                 'memo string',
                 account=acc)
示例#4
0
class Testcases(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.bts = BitShares(
            nobroadcast=True,
            # We want to bundle many operations into a single transaction
            bundle=True,
            # Overwrite wallet to use this list of wifs only
            wif=[wif]
        )
        set_shared_blockchain_instance(self.bts)
        self.bts.set_default_account("init0")

    def test_fee_on_transfer(self):
        tx = self.bts.transfer("init1", 1, "1.3.0", account="init0", fee_asset="1.3.121")
        op = tx["operations"][0][1]
        self.assertEqual(op["fee"]["asset_id"], "1.3.121")
示例#5
0
account = "alfredo-worker"
proposer = "oxarbitrage.a699"
vesting_id = "1.13.1608"

bitshares = BitShares(
    nobroadcast=False,
    bundle=True,
    proposer=proposer,
    proposal_expiration=60 * 60 * 24 * 2,
)
set_shared_bitshares_instance(bitshares)
market = Market("USD:BTS")
price = market.ticker()["quoteSettlement_price"]

bitshares.wallet.unlock(getpass())
vesting = Vesting(vesting_id)

print("Claiming Vesting Balance: %s" % vesting.claimable)
bitshares.vesting_balance_withdraw(vesting["id"],
                                   amount=vesting.claimable,
                                   account=account)

print("Buying as much bitUSD at price up to %s or %s" %
      (price * 0.90, (price * 0.90).copy().invert()))
market.buy(price * 0.9, Amount(3200, "USD"), killfill=True, account=account)

print("Worker alfredo payment - 15 days")
bitshares.transfer("oxarbitrage.a699", 3200, "USD", account=account)

pprint(bitshares.broadcast())
示例#6
0
    testnet.transfer(acc_name, init_supply, "ZGV", account=source_account)


#create the required number of accounts
for i in range(accs_count):
    acc_name = get_name(i)
    create_account(acc_name)

#make the required number of transactions
random.seed(dt.datetime.now())
for i in range(tran_count):

    #sender is picked random
    sender = get_name(random.randint(0, accs_count - 1))

    #receiver is picked random until it is different from sender
    receiver = sender
    while receiver == sender:
        receiver = get_name(random.randint(0, accs_count - 1))

    #transaction amount is the random part of the sender's balance
    sender_acc = Account(sender, bitshares_instance=testnet)
    sender_balance = sender_acc.balances[0].amount
    amount = sender_balance * random.random()

    try:
        print("transfer " + str(amount) + " from " + sender + " to " +
              receiver)
        testnet.transfer(receiver, amount, "ZGV", account=sender_acc)
    except Exception as e:
        print(traceback.format_exc())
示例#7
0
class Testcases(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.bts = BitShares(
            "wss://node.testnet.bitshares.eu",
            nobroadcast=True,
            keys={"active": wif},
        )
        # from getpass import getpass
        # self.bts.wallet.unlock(getpass())
        set_shared_bitshares_instance(self.bts)
        self.bts.set_default_account("init0")

    def test_finalizeOps_proposal(self):
        bts = self.bts
        # proposal = bts.new_proposal(bts.tx())
        proposal = bts.proposal()
        self.bts.transfer("init1", 1, "TEST", append_to=proposal)
        tx = bts.tx().json()  # default tx buffer
        ops = tx["operations"]
        self.assertEqual(len(ops), 1)
        self.assertEqual(getOperationNameForId(ops[0][0]), "proposal_create")
        prop = ops[0][1]
        self.assertEqual(len(prop["proposed_ops"]), 1)
        self.assertEqual(
            getOperationNameForId(prop["proposed_ops"][0]["op"][0]),
            "transfer")

    def test_finalizeOps_proposal2(self):
        bts = self.bts
        proposal = bts.new_proposal()
        # proposal = bts.proposal()
        self.bts.transfer("init1", 1, "TEST", append_to=proposal)
        tx = bts.tx().json()  # default tx buffer
        ops = tx["operations"]
        self.assertEqual(len(ops), 1)
        self.assertEqual(getOperationNameForId(ops[0][0]), "proposal_create")
        prop = ops[0][1]
        self.assertEqual(len(prop["proposed_ops"]), 1)
        self.assertEqual(
            getOperationNameForId(prop["proposed_ops"][0]["op"][0]),
            "transfer")

    def test_finalizeOps_combined_proposal(self):
        bts = self.bts
        parent = bts.new_tx()
        proposal = bts.new_proposal(parent)
        self.bts.transfer("init1", 1, "TEST", append_to=proposal)
        self.bts.transfer("init1", 1, "TEST", append_to=parent)
        tx = parent.json()
        ops = tx["operations"]
        self.assertEqual(len(ops), 2)
        self.assertEqual(getOperationNameForId(ops[0][0]), "proposal_create")
        self.assertEqual(getOperationNameForId(ops[1][0]), "transfer")
        prop = ops[0][1]
        self.assertEqual(len(prop["proposed_ops"]), 1)
        self.assertEqual(
            getOperationNameForId(prop["proposed_ops"][0]["op"][0]),
            "transfer")

    def test_finalizeOps_changeproposer_new(self):
        bts = self.bts
        proposal = bts.proposal(proposer="init5")
        bts.transfer("init1", 1, "TEST", append_to=proposal)
        tx = bts.tx().json()
        ops = tx["operations"]
        self.assertEqual(len(ops), 1)
        self.assertEqual(getOperationNameForId(ops[0][0]), "proposal_create")
        prop = ops[0][1]
        self.assertEqual(len(prop["proposed_ops"]), 1)
        self.assertEqual(prop["fee_paying_account"], "1.2.11")
        self.assertEqual(
            getOperationNameForId(prop["proposed_ops"][0]["op"][0]),
            "transfer")

    """
    def test_finalizeOps_changeproposer_legacy(self):
        bts = self.bts
        bts.proposer = "init5"
        tx = bts.transfer("init1", 1, "TEST")
        ops = tx["operations"]
        self.assertEqual(len(ops), 1)
        self.assertEqual(
            getOperationNameForId(ops[0][0]),
            "proposal_create")
        prop = ops[0][1]
        self.assertEqual(len(prop["proposed_ops"]), 1)
        self.assertEqual(prop["fee_paying_account"], "1.2.11")
        self.assertEqual(
            getOperationNameForId(prop["proposed_ops"][0]["op"][0]),
            "transfer")
    """

    def test_new_proposals(self):
        bts = self.bts
        p1 = bts.new_proposal()
        p2 = bts.new_proposal()
        self.assertIsNotNone(id(p1), id(p2))

    def test_new_txs(self):
        bts = self.bts
        p1 = bts.new_tx()
        p2 = bts.new_tx()
        self.assertIsNotNone(id(p1), id(p2))
示例#8
0
    acc = create_acc(acc_num)
    acc_list.append(acc)

turn_counter = 0
while True:
    sender = max(acc_list, key=lambda x: x["balance"])
    random.seed(datetime.now())
    acc_count = len(acc_list)
    receiver = acc_list[random.randint(0, acc_count - 1)]
    if sender["name"] == receiver["name"]:
        continue
    sender_acc = Account(sender["name"], bitshares_instance=testnet)
    receiver_acc = Account(receiver["name"], bitshares_instance=testnet)
    try:
        testnet.transfer(receiver["name"],
                         sender["balance"] - 20,
                         "ZGV",
                         account=sender_acc)
    except:
        print(traceback.format_exc())
    print("%d transaction %s %s %d" %
          (turn_counter, sender["name"], receiver["name"],
           sender["balance"] - 20))
    sender_acc = Account(sender["name"], bitshares_instance=testnet)
    receiver_acc = Account(receiver["name"], bitshares_instance=testnet)
    sender["balance"] = sender_acc.balances[0].amount
    receiver["balance"] = receiver_acc.balances[0].amount

    turn_counter = turn_counter + 1
#    if turn_counter % 100 == 99:
#        acc = create_acc(len(acc_list))
#        acc_list.append(acc)
示例#9
0
def transfert(acc_from, acc_to, asset, amount):
    bitshares = BitShares(btsNode, acc_from.name, acc_from.pwd)
    bitshares.wallet.unlock("supersecret")
    bitshares.transfer(acc_to.name, float(amount), asset, account=acc_from.name)
    bitshares.wallet.lock()
                           password="******",
                           additional_owner_keys=[],
                           additional_active_keys=[],
                           additional_owner_accounts=["vel-ma", "oatrick1995"],
                           additional_active_accounts=[],
                           proxy_account="proxy-to-self",
                           storekeys=True))

testnet.broadcast()

##allow - change threashold
foreign_account = format(
    PasswordKey("mutual-insurance-fund-993", "somethingstupid",
                "active").get_public(), "TEST")
print_tx(
    testnet.allow(
        foreign_account,
        weight=1,
        account="vel-ma",
        permission="active",
        threshold=2,
    ))

##transfer funds
print_tx(
    testnet.transfer("mutual-insurance-fund-993", 5, "TEST", account=account))

##proposal - claim
##vote - vote

testnet.broadcast()
示例#11
0
class Testcases(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.bts = BitShares(
            "wss://node.testnet.bitshares.eu",
            nobroadcast=True,
            keys={"active": wif, "owner": wif, "memo": wif},
        )
        # from getpass import getpass
        # self.bts.wallet.unlock(getpass())
        set_shared_bitshares_instance(self.bts)
        self.bts.set_default_account("init0")

    def test_connect(self):
        self.bts.connect()

    def test_set_default_account(self):
        self.bts.set_default_account("init0")

    def test_info(self):
        info = self.bts.info()
        for key in ['current_witness',
                    'head_block_id',
                    'head_block_number',
                    'id',
                    'last_irreversible_block_num',
                    'next_maintenance_time',
                    'recently_missed_count',
                    'time']:
            self.assertTrue(key in info)

    def test_finalizeOps(self):
        bts = self.bts
        tx1 = bts.new_tx()
        tx2 = bts.new_tx()
        self.bts.transfer("init1", 1, core_unit, append_to=tx1)
        self.bts.transfer("init1", 2, core_unit, append_to=tx2)
        self.bts.transfer("init1", 3, core_unit, append_to=tx1)
        tx1 = tx1.json()
        tx2 = tx2.json()
        ops1 = tx1["operations"]
        ops2 = tx2["operations"]
        self.assertEqual(len(ops1), 2)
        self.assertEqual(len(ops2), 1)

    def test_transfer(self):
        bts = self.bts
        tx = bts.transfer(
            "1.2.8", 1.33, core_unit, memo="Foobar", account="1.2.7")
        self.assertEqual(
            getOperationNameForId(tx["operations"][0][0]),
            "transfer"
        )
        op = tx["operations"][0][1]
        self.assertIn("memo", op)
        self.assertEqual(op["from"], "1.2.7")
        self.assertEqual(op["to"], "1.2.8")
        amount = Amount(op["amount"])
        self.assertEqual(float(amount), 1.33)

    def test_create_account(self):
        bts = self.bts
        name = ''.join(random.choice(string.ascii_lowercase) for _ in range(12))
        key1 = PrivateKey()
        key2 = PrivateKey()
        key3 = PrivateKey()
        key4 = PrivateKey()
        tx = bts.create_account(
            name,
            registrar="init0",   # 1.2.7
            referrer="init1",    # 1.2.8
            referrer_percent=33,
            owner_key=format(key1.pubkey, core_unit),
            active_key=format(key2.pubkey, core_unit),
            memo_key=format(key3.pubkey, core_unit),
            additional_owner_keys=[format(key4.pubkey, core_unit)],
            additional_active_keys=[format(key4.pubkey, core_unit)],
            additional_owner_accounts=["committee-account"],  # 1.2.0
            additional_active_accounts=["committee-account"],
            proxy_account="init0",
            storekeys=False
        )
        self.assertEqual(
            getOperationNameForId(tx["operations"][0][0]),
            "account_create"
        )
        op = tx["operations"][0][1]
        role = "active"
        self.assertIn(
            format(key4.pubkey, core_unit),
            [x[0] for x in op[role]["key_auths"]])
        self.assertIn(
            format(key4.pubkey, core_unit),
            [x[0] for x in op[role]["key_auths"]])
        self.assertIn(
            "1.2.0",
            [x[0] for x in op[role]["account_auths"]])
        role = "owner"
        self.assertIn(
            format(key4.pubkey, core_unit),
            [x[0] for x in op[role]["key_auths"]])
        self.assertIn(
            format(key4.pubkey, core_unit),
            [x[0] for x in op[role]["key_auths"]])
        self.assertIn(
            "1.2.0",
            [x[0] for x in op[role]["account_auths"]])
        self.assertEqual(
            op["options"]["voting_account"],
            "1.2.6")
        self.assertEqual(
            op["registrar"],
            "1.2.6")
        self.assertEqual(
            op["referrer"],
            "1.2.7")
        self.assertEqual(
            op["referrer_percent"],
            33 * 100)

    def test_weight_threshold(self):
        bts = self.bts

        auth = {'account_auths': [['1.2.0', '1']],
                'extensions': [],
                'key_auths': [
                    ['TEST55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n', 1],
                    ['TEST7GM9YXcsoAJAgKbqW2oVj7bnNXFNL4pk9NugqKWPmuhoEDbkDv', 1]],
                'weight_threshold': 3}  # threshold fine
        bts._test_weights_treshold(auth)
        auth = {'account_auths': [['1.2.0', '1']],
                'extensions': [],
                'key_auths': [
                    ['TEST55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n', 1],
                    ['TEST7GM9YXcsoAJAgKbqW2oVj7bnNXFNL4pk9NugqKWPmuhoEDbkDv', 1]],
                'weight_threshold': 4}  # too high

        with self.assertRaises(ValueError):
            bts._test_weights_treshold(auth)

    def test_allow(self):
        bts = self.bts
        tx = bts.allow(
            "TEST55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n",
            weight=1,
            threshold=1,
            permission="owner"
        )
        self.assertEqual(
            getOperationNameForId(tx["operations"][0][0]),
            "account_update"
        )
        op = tx["operations"][0][1]
        self.assertIn("owner", op)
        self.assertIn(
            ["TEST55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n", '1'],
            op["owner"]["key_auths"])
        self.assertEqual(op["owner"]["weight_threshold"], 1)

    def test_disallow(self):
        bts = self.bts
        with self.assertRaisesRegex(ValueError, ".*Changes nothing.*"):
            bts.disallow(
                "TEST55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n",
                weight=1,
                threshold=1,
                permission="owner"
            )
        with self.assertRaisesRegex(ValueError, ".*Changes nothing!.*"):
            bts.disallow(
                "TEST6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV",
                weight=1,
                threshold=1,
                permission="owner"
            )

    def test_update_memo_key(self):
        bts = self.bts
        tx = bts.update_memo_key("TEST55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n")
        self.assertEqual(
            getOperationNameForId(tx["operations"][0][0]),
            "account_update"
        )
        op = tx["operations"][0][1]
        self.assertEqual(
            op["new_options"]["memo_key"],
            "TEST55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n")

    def test_approvewitness(self):
        bts = self.bts
        tx = bts.approvewitness("init0")
        self.assertEqual(
            getOperationNameForId(tx["operations"][0][0]),
            "account_update"
        )
        op = tx["operations"][0][1]
        self.assertIn(
            "1:0",
            op["new_options"]["votes"])

    def test_approvecommittee(self):
        bts = self.bts
        tx = bts.approvecommittee("init0")
        self.assertEqual(
            getOperationNameForId(tx["operations"][0][0]),
            "account_update"
        )
        op = tx["operations"][0][1]
        self.assertIn(
            "0:11",
            op["new_options"]["votes"])

    def test_sign_message(self):
        def new_refresh(self):
            dict.__init__(
                self, {"name": "init0",
                 "options": {
                     "memo_key": "TEST6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV"
                 }})

        with mock.patch(
            "bitshares.account.Account.refresh",
            new=new_refresh
        ):
            p = Message("message foobar").sign()
            Message(p).verify()
示例#12
0
def tapbasic(referrer):
    # test is request has 'account' key
    if not request.json or 'account' not in request.json:
        abort(400)
    account = request.json.get('account', {})

    # make sure all keys are present
    if any([
            key not in account
            for key in ["active_key", "memo_key", "owner_key", "name"]
    ]):
        abort(400)

    if len(models.Accounts.query.options().all()
           ) >= config.registrations_limit:
        return api_error("Registration limit achieved")

    # prevent massive account registration
    if request.args.get("ip") != "127.0.0.1" and models.Accounts.exists(
            request.args.get("ip")):
        return api_error("Only one account per IP")

    # Check if account name is cheap name
    if (not re.search(r"[0-9-]", account["name"])
            and re.search(r"[aeiouy]", account["name"])):
        return api_error("Only cheap names allowed!")

    # This is not really needed but added to keep API-compatibility with Rails Faucet
    account.update({"id": None})

    bitshares = BitShares(config.witness_url,
                          nobroadcast=config.nobroadcast,
                          keys=[config.wif],
                          prefix=config.prefix)

    try:
        Account(account["name"], bitshares_instance=bitshares)
        return api_error("Account exists")
    except:
        pass

    # Registrar
    registrar = account.get("registrar", config.registrar) or config.registrar
    try:
        registrar = Account(registrar, bitshares_instance=bitshares)
    except:
        return api_error("Unknown registrar: %s" % registrar)

    # Referrer
    referrer = account.get("referrer",
                           config.default_referrer) or config.default_referrer
    try:
        referrer = Account(referrer, bitshares_instance=bitshares)
    except:
        return api_error("Unknown referrer: %s" % referrer)
    referrer_percent = account.get("referrer_percent", config.referrer_percent)

    # Create new account
    try:
        bitshares.create_account(
            account["name"],
            registrar=registrar["id"],
            referrer=referrer["id"],
            referrer_percent=referrer_percent,
            owner_key=account["owner_key"],
            active_key=account["active_key"],
            memo_key=account["memo_key"],
            proxy_account=config.get("proxy", None),
            additional_owner_accounts=config.get("additional_owner_accounts",
                                                 []),
            additional_active_accounts=config.get("additional_active_accounts",
                                                  []),
            additional_owner_keys=config.get("additional_owner_keys", []),
            additional_active_keys=config.get("additional_active_keys", []),
        )
    except Exception as e:
        log.error(traceback.format_exc())
        return api_error(str(e))

    models.Accounts(account["name"], request.args.get("ip"))
    regestree = Account(account["name"], bitshares_instance=bitshares)

    try:
        bitshares.transfer(account["name"],
                           config["donation_amount"],
                           config["donation_asset"],
                           memo="AirDrop",
                           account=registrar)
    except Exception as e:
        log.error(str(e))
        pass

    balance = registrar.balance(config.core_asset)
    if balance and balance.amount < config.balance_mailthreshold:
        log.critical(
            "The faucet's balances is below {}".format(
                config.balance_mailthreshold), )

    return jsonify({
        "account": {
            "name": account["name"],
            "owner_key": account["owner_key"],
            "active_key": account["active_key"],
            "memo_key": account["memo_key"],
            "referrer": referrer["name"]
        }
    })
from pprint import pprint
from getpass import getpass
from datetime import datetime, timedelta

from bitshares import BitShares
from bitshares.amount import Amount
from bitshares.asset import Asset

bitshares = BitShares(nobroadcast=False)
bitshares.wallet.unlock(getpass())

proposal = bitshares.new_proposal(
    proposer="xeroc",
    proposal_expiration=timedelta(days=3).seconds,
    proposal_review=3600,
)

bitshares.transfer(
    "gibbs-from-ncis",
    4631.34999,
    "BTS",
    account="onboarding.bitshares.foundation",
    append_to=proposal,
)

test = Asset("TEST")
test.change_issuer("committee-issuer", append_to=proposal)

pprint(bitshares.broadcast())
            tran_count = tran_count + 1
            print(tran_count)
            print(tran)
            
            rt_delay = (tran["time"] - package_start).total_seconds() / time_scale
            rt_time = rt_start + dt.timedelta(seconds=rt_delay)

            if rt_time > dt.datetime.now():
                sleep_time = rt_time - dt.datetime.now()
                print("sleep for " + str(sleep_time))
                time.sleep(sleep_time.total_seconds())
            try:
                run_transaction(tran)
            except Exception as e:
                print(traceback.format_exc())
                
#retreive all distributed money back
csv = package["transaction_sets"][0]["csv_files"][0]
print(csv)
with open(data_dir + '/' + csv) as f:
    for line in f:
        tran = parse_line(line)
        if tran["to"] == source_name:
            continue            
        acc_to = Account(tran["to"], bitshares_instance=testnet)
        if not acc_to.balances:
            continue
        balance = acc_to.balances[0].amount
        if balance > transaction_fee:
            testnet.transfer(source_name, balance - transaction_fee, "ZGV", account=acc_to)