-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransactions.py
46 lines (39 loc) · 1.79 KB
/
transactions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import random
random.seed(0)
def randomTransaction(maxValue=3):
# This will create valid transactions in the range of (1,maxValue)
sign = int(random.getrandbits(1))*2 - 1 # This will randomly choose -1 or 1
amount = random.randint(1,maxValue)
alicePays = sign * amount
bobPays = -1 * alicePays
# By construction, this will always return transactions that respect the conservation of tokens.
# However, note that we have not done anything to check whether these overdraft an account
return {u'Ada':alicePays,u'Charlie':bobPays}
def updateState(txn, state):
# Inputs: txn, state: dictionaries keyed with account names, holding numeric values for transfer amount (txn) or account balance (state)
# Returns: Updated state, with additional users added to state if necessary
# NOTE: This does not not validate the transaction- just updates the state!
# If the transaction is valid, then update the state
state = state.copy() # As dictionaries are mutable, let's avoid any confusion by creating a working copy of the data.
for key in txn:
if key in state.keys():
state[key] += txn[key]
else:
state[key] = txn[key]
return state
# This function validates each piece of data based on the business logic of the
# application.
def isValidData(txn,state):
# Assume that the transaction is a dictionary keyed by account names
# Check that the sum of the deposits and withdrawals is 0
if sum(txn.values()) is not 0:
return False
# Check that the transaction does not cause an overdraft
for key in txn.keys():
if key in state.keys():
acctBalance = state[key]
else:
acctBalance = 0
if (acctBalance + txn[key]) < 0:
return False
return True