-3

Sorry if this has been answered in another way or place, I just couldn't figure it out. SO I am playing around with python for the first time and was just trying to create a very simple basic blockchain model where I can add values to the chain but as I am adding values I show the total available "funds" within the list.

Here is what I have so far:

import numpy as np

name = raw_input("please enter your name: ")

# For some reason I have to use the raw_input here or get an error message
original_money = float(input("how much money do you have? "))

# Requesting user to input their original available "funds" amount
print("Hi " + name + " you have $" + str(original_money))

print("in order to make purchases, you need to add money to your wallet")
wallet = [original_money]

def get_last_wallet_value():
    return wallet [-1]

def add_value(last_added_value, existing_value=[original_money]):
    wallet.append([existing_value, last_added_value])

# I am lost here, no idea what to do to add the whole value of available "funds" within the list as they are getting added to the list
def sum_wallet_content():
    return np.sum(wallet)  

tx_value = float(input("please enter how much you would like to add: "))
add_value(tx_value)
print(name + " you now have $" + str(tx_value+original_money) + " in your        acount!")

# Here is where my problem starts since it is calling the sum_wallet_content and I am having troubles setting that up

tx_value = float(input("please enter how much you would like to add: "))
add_value(tx_value, get_last_wallet_value())
print(name + " you now have $" + sum_wallet_content() + " in your account!")

tx_value = float(input("please enter how much you would like to add: "))
add_value(tx_value, get_last_wallet_value())

tx_value = float(input("please enter how much you would like to add: "))
add_value(tx_value, get_last_wallet_value())

tx_value = float(input("please enter how much you would like to add: ")) 
add_value(tx_value, get_last_wallet_value())

print(wallet)

Basically, think of this is a simple wallet where you will get your available funds within your wallet each time you add money to it. It will also keep track of each time money was added or deducted. As mentioned on top, a very basic blockchain.

I would greatly appreciate any advice on this.

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • You might collect downvotes and closevotes due to the broadness of your text - do you have a specific problem that we can solve or are you just here for brainstorming? – Patrick Artner Feb 28 '19 at 06:30
  • 1
    @PatrickArtner unfortunately, the title and code's comments suggest that it's not working as intended so far, which is off-topic on CR. – Zeta Feb 28 '19 at 06:36
  • Maybe start with [reading a tutorial](https://medium.com/crypto-currently/lets-build-the-tiniest-blockchain-e70965a248b) – user8408080 Feb 28 '19 at 09:40
  • @PatrickArtner I tried to explain the issue within the code by commenting where the problem is. – King Randor Feb 28 '19 at 19:10

1 Answers1

1

Using list with defaults in functions will trip you up: "Least Astonishment" and the Mutable Default Argument


Storing data in a flat list that belongs to together would be better done by grouping it - f.e. as immuteable tuples. I would store your blockchain as tuple of (last_balace, new_op) and add some checking if the chain is valid on insertion.

Your current approach would need you to slice your list to get all "old values" and all "new values" or chunk it every 2 elements and operate on those slices - using tuples is more clear.

See Understanding slice notation and How do you split a list into evenly sized chunks? if you want to continue to use a flat list and using chunks / slicing for your solution.


Example of using a tuple list as chain:

def modify(chain,money):
    """Allows modification of a blockchain given as list of tuples:
       [(old_value,new_op),...]. A chain is valid if the sum of all
       new_op is the same as the sum of the last chains tuple."""
    def value():
        """Calculates the actual value of a valid chain."""
        return sum(chain[-1])
    def validate():
        """Validates chain. Raises error if invalid."""
        if not chain:
            return True
        inout = sum(c[1] for c in chain) # sum single values
        last = value()
        if inout == last:
            return True
        else:
            raise ValueError(
            "Sum of single positions {} does not match last chain element {} sum.".format(
            inout,last))

    # TODO: handle debt - this chain has unlimited credit

    if chain is None:
        raise ValueError("No chain provided")
    elif not chain:    # empty chain: []
        chain.append( (0,money) )
    elif validate():   # raises error if not valid
        chain.append( (value(),money))
    print(chain,value())

Usage:

modify(None,42)   # ValueError: No chain provided

block = []
modify(block,30)    # ([(0, 30)], 30)
modify(block,30)    # ([(0, 30), (30, 30)], 60)
modify(block,-18)   # ([(0, 30), (30, 30), (60, -18)], 42)

# fraudulent usage
block = [(0,1000),(1040,20)]
modify(block,10) 
# => ValueError: Sum of single positions 1020 does not match last chain element 1060 sum.
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69