Esempio n. 1
0
 def create_genesis_block(self):
     bc = BlockChain()
     w = Wallet.generate_wallet()
     ws = Wallets()
     ws[w.address] = w
     ws.save()
     tx = bc.coin_base_tx(w.address)
     bc.new_genesis_block(tx)
     return w.address
Esempio n. 2
0
    def __init__(self, user, conn=None):
        self.conn = user
        if conn:
            self.conn = os.path.join(conn, user)

        if not os.path.isdir(self.conn):
            msg = 'User {} does not exist'.format(user)
            raise Exception(msg)

        self.wallets = Wallets(self.conn)
        self.accounts = Accounts(self.conn)
        self.funding_templates = FundingTemplates(self.conn)
 def register_user(cls, new_user: dict[str, str]) -> str:
     "register a user"
     if not new_user["user_name"] in cls._users:
         # generate really complicated unique user_id.
         # Using the existing user_name as the id for simplicity
         user_id = new_user["user_name"]
         cls._users[user_id] = new_user
         Reports.log_event(f"new user `{user_id}` created")
         # create a wallet for the new user
         Wallets().create_wallet(user_id)
         # give the user a sign up bonus
         Reports.log_event(f"Give new user `{user_id}` sign up bonus of 10")
         Wallets().adjust_balance(user_id, Decimal(10))
         return user_id
     return ""
Esempio n. 4
0
    def add_block(self, transactions, fee=0):  # change add "fee"  6.19
        last_block = self.get_last_block()
        prev_hash = last_block.get_header_hash()
        height = last_block.block_header.height + 1
        block_header = BlockHeader('', height, prev_hash)

        # reward to wallets[0]
        wallets = Wallets()
        keys = list(wallets.wallets.keys())
        w = wallets[keys[0]]
        coin_base_tx = self.coin_base_tx(w.address, fee)  # change 6.19
        transactions.insert(0, coin_base_tx)

        utxo_set = UTXOSet()
        # txs = transactions  # change 6.21
        txs = utxo_set.clear_transactions(
            transactions)  # change clear transactions(add sort)

        block = Block(block_header, txs)
        block.mine(self)
        block.set_header_hash()
        self.db.create(block.block_header.hash, block.serialize())
        last_hash = block.block_header.hash
        self.set_last_hash(last_hash)

        utxo_set.update(block)
Esempio n. 5
0
    def new_transaction(self, from_addr, to_addr, amount, fee):
        inputs = []
        outputs = []
        ifname = 'ens33'  # enp2s0
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ip = socket.inet_ntoa(
            fcntl.ioctl(s.fileno(), 0x8915,
                        struct.pack('256s', bytes(ifname[:15],
                                                  'utf-8')))[20:24])

        wallets = Wallets()
        from_wallet = wallets[from_addr]
        pub_key = from_wallet.public_key

        acc, valid_outpus = self._find_spendable_outputs(from_addr, amount)
        # if acc < amount + fee:  # change
        # raise NotEnoughAmountError(u'not enough coin')
        for fout in valid_outpus:
            index = fout.index
            txid = fout.txid
            input = TXInput(txid, index, pub_key)
            inputs.append(input)

        output = TXOutput(amount, to_addr)
        outputs.append(output)
        if acc > amount + fee:  # change
            # a change
            outputs.append(TXOutput(acc - amount - fee, from_addr))  # change

        tx = Transaction(inputs, outputs, fee, ip)  # change
        tx.set_id()
        self.sign_transaction(tx, from_wallet.private_key)
        return tx
Esempio n. 6
0
 def submit_entry(cls, user_id: str, entry: Decimal) -> bool:
     "Submit a new entry for the user in this game"
     now = int(time.time())
     time_remaining = cls._start_time - now + cls._clock
     if time_remaining > 0:
         if Wallets.get_balance(user_id) > Decimal('1'):
             if Wallets.adjust_balance(user_id, Decimal('-1')):
                 cls._entries.append((user_id, entry))
                 Reports.log_event(
                     f"New entry `{entry}` submitted by `{user_id}`")
                 return True
             Reports.log_event(
                 f"Problem adjusting balance for `{user_id}`")
             return False
         Reports.log_event(f"User Balance for `{user_id}` to low")
         return False
     Reports.log_event("Game Closed")
     return False
Esempio n. 7
0
def create_wallet():
    wallets = Wallets()
    wallet = Wallet()
    address = wallet.address
    wallets.add_wallet(address, wallet)
    wallets.save_to_file()

    print("Your new address: {}".format(address))
Esempio n. 8
0
def start(
):  # wait : thread add_block(txs)   txs = []   packing function >1MB or no tx verify if tx are valid
    couch = couchdb.Server("http://127.0.0.1:5984")
    try:
        couch.delete('block_chain')
    except:
        pass
    db = DB("http://127.0.0.1:5984")

    bc = BlockChain()  # only one blockchain called bc
    utxo_set = UTXOSet()
    utxo_set.reindex(bc)

    tcpserver = TCPServer()
    tcpserver.listen()
    tcpserver.run()

    rpc = RPCServer(export_instance=Cli())
    rpc.start(False)

    p2p = P2p()
    server = PeerServer()
    server.run(p2p)
    p2p.run()

    time.sleep(30)  # automatically create a genesis block
    w1 = Wallet.generate_wallet()
    ws = Wallets()
    ws[w1.address] = w1
    ws.save()
    tx = bc.coin_base_tx(w1.address)
    bc.new_genesis_block(tx)
    fo = open("address.txt", "w")
    fo.truncate()
    fo.write(w1.address)  # save the address of the genesis block
    fo.write("\n")

    w2 = Wallet.generate_wallet()  # create another wallet to send transaction
    ws[w2.address] = w2
    ws.save()
    fo.write(w2.address)
    fo.close()
Esempio n. 9
0
 def get_balance(user_id: str) -> Decimal:
     "Get a players balance"
     return Wallets.get_balance(user_id)
Esempio n. 10
0
 def print_all_wallet(self):
     ws = Wallets()
     wallets = []
     for k, _ in ws.items():
         wallets.append(k)
     return wallets
Esempio n. 11
0
 def create_wallet(self):
     w = Wallet.generate_wallet()
     ws = Wallets()
     ws[w.address] = w
     ws.save()
     return w.address
Esempio n. 12
0
def listAddresses():
    # return a list of wallet addresses
    wallets = Wallets()
    return wallets.get_addresses()
Esempio n. 13
0
def isMineAddress(address):
    # check if address is in our wallet
    wallets = Wallets()
    return address in wallets.get_addresses()
Esempio n. 14
0
def AddAddress(address, wallet):
    # Add address to wallet
    wallets = Wallets()
    wallets.add_wallet(address, wallet)
    return wallets.save_to_file()
Esempio n. 15
0
class App(object):
    def __init__(self, user, conn=None):
        self.conn = user
        if conn:
            self.conn = os.path.join(conn, user)

        if not os.path.isdir(self.conn):
            msg = 'User {} does not exist'.format(user)
            raise Exception(msg)

        self.wallets = Wallets(self.conn)
        self.accounts = Accounts(self.conn)
        self.funding_templates = FundingTemplates(self.conn)

    #TODO(steve): make this more pythonic
    # by removing them from the class
    @staticmethod
    def create_user(user, conn=None):
        data = user
        if conn:
            data = os.path.join(conn, user)

        if os.path.isdir(data):
            raise Exception('User already exists: {}'.format(user))

        os.mkdir(data)
        files = ['accounts.csv', 'wallets.csv', 'funding.csv']
        for f in files:
            f = os.path.join(data, f)
            open(f, 'wb').close()

    @staticmethod
    def remove_user(user, conn=None):
        data = user
        if conn:
            data = os.path.join(conn, user)

        if not os.path.isdir(data):
            msg = 'User does not exist: {}'.format(user)
            raise Exception(msg)

        shutil.rmtree(data)

    # TODO(steve): should we check that wallet is of
    # type string?? Could have unwanted behaviour
    # if not.
    def create_wallet(self, wallet, opening_balance):
        try:
            valid_balance = float(opening_balance)
        except ValueError as e:
            raise e

        self.wallets.create_item(wallet, Wallet(valid_balance))

    def create_account(self, account, opening_balance):
        try:
            valid_balance = float(opening_balance)
        except ValueError as e:
            raise e

        self.accounts.create_item(account, Wallet(valid_balance))

    def create_funding_template(self, template, amount, account, frequency,
                                allocation):

        if template in self.funding_templates:
            msg = 'Funding template {} already exists'.format(template)
            raise Exception(msg)

        funding_template = self._create_funding_template(
            template, amount, account, frequency, allocation)
        self.funding_templates.create_item(template, funding_template)

    def _create_funding_template(self, template, amount, account, frequency,
                                 allocation):

        if account not in self.accounts:
            msg = 'Account {} does not exist'.format(account)
            raise Exception(msg)

        try:
            funding_template = FundingTemplate(template, amount, account,
                                               frequency)
        except Exception as e:
            raise e

        for (k, v) in allocation.iteritems():
            if k not in self.wallets:
                msg = 'Wallet {} does not exist'.format(k)
                raise Exception(msg)

            funding_template.add_wallet_to_allocation(k, v)

        if not funding_template.valid():
            msg = 'Allocation amount != funding amount'
            raise Exception(msg)

        return funding_template

    def remove_wallet(self, wallet, transfer):
        if wallet not in self.wallets:
            msg = 'Wallet does not exist. {}'.format(wallet)
            raise Exception(msg)

        if transfer not in self.wallets:
            msg = 'Transfer wallet does not exist. {}'.format(transfer)
            raise Exception(msg)

        bal = self.wallets[wallet].balance()
        self.wallets[transfer].add(bal)
        del self.wallets[wallet]

        for f in self.funding_templates:
            self.funding_templates[f].remove_wallet_from_allocation(
                wallet, transfer=transfer)

    def remove_account(self, account, transfer):
        if account not in self.accounts:
            msg = 'Account does not exist. {}'.format(account)
            raise Exception(msg)

        if transfer not in self.accounts:
            msg = 'Transfer account does not exist. {}'.format(transfer)
            raise Exception(msg)

        bal = self.accounts[account].balance()
        self.accounts[transfer].add(bal)
        del self.accounts[account]

        for f in self.funding_templates:
            if self.funding_templates[f].account() == account:
                self.funding_templates[f].update_account(transfer)

    def remove_funding_template(self, template):
        if template not in self.funding_templates:
            msg = 'Funding template does not exist. {}'.format(template)
            raise Exception(msg)

        del self.funding_templates[template]

    def update_funding_template(self, template, amount, account, frequency,
                                allocation):

        if template not in self.funding_templates:
            msg = 'Funding template does not exist: {}'.format(template)
            raise Exception(msg)

        try:
            funding_template = self._create_funding_template(
                template, amount, account, frequency, allocation)
        except Exception as e:
            raise e

        self.funding_templates[template] = funding_template

    def add_expense(self, wallet, account, amount):
        if wallet not in self.wallets:
            msg = 'Wallet does not exist. {}'.format(wallet)
            raise Exception(msg)

        if account not in self.accounts:
            msg = 'Account does not exist. {}'.format(account)
            raise Exception(msg)

        try:
            valid_amount = float(amount)
        except ValueError as e:
            raise e

        self.wallets[wallet].add(-valid_amount)
        self.accounts[account].add(-valid_amount)

    def transfer_funds(self, amount, from_acct, to_acct, transfer_type):
        try:
            valid_amount = float(amount)
        except ValueError as e:
            raise e

        collection = None
        if transfer_type == 'account':
            collection = self.accounts
        elif transfer_type == 'wallet':
            collection = self.wallets
        else:
            msg = 'Invalid transfer type: {}'.format(transfer_type)
            raise Exception(msg)

        if from_acct not in collection:
            msg = 'From {} does not exist: {}'.format(transfer_type, from_acct)
            raise Exception(msg)

        if to_acct not in collection:
            msg = 'To {} does not exist: {}'.format(transfer_type, to_acct)
            raise Exception(msg)

        if collection[from_acct].balance() < valid_amount:
            msg = '{} has insufficient funds to transfer {}'.format(
                from_acct, amount)
            raise Exception(msg)

        collection[from_acct].add(-valid_amount)
        collection[to_acct].add(valid_amount)

    def fund_wallets(self, template):
        if template not in self.funding_templates:
            msg = 'Funding does not contain template {}.'.format(template)
            raise Exception(msg)

        funding = self.funding_templates[template]
        self.accounts[funding.account()].add(funding.amount())
        for (k, v) in funding.allocation().iteritems():
            self.wallets[k].add(v)

        self.accounts.save()
        self.wallets.save()