Adding Loom's plasma_cash folder

This commit is contained in:
Richard Ramos 2018-07-31 11:24:58 -04:00
parent 093040d299
commit f212a4a0a3
34 changed files with 3325 additions and 0 deletions

2
plasma_cash/.flake8 Normal file
View File

@ -0,0 +1,2 @@
[flake8]
exclude = unit_test.py, config.py

86
plasma_cash/License.md Normal file
View File

@ -0,0 +1,86 @@
Copyright (C) 2018 Loom Network Inc
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

9
plasma_cash/Makefile Normal file
View File

@ -0,0 +1,9 @@
test:
pytest unit_test.py
lint:
flake8 child_chain client contract_binds utils *.py --ignore=E203,W503 --exclude unit_test.py,config.py,dump_test_data.py
format:
black --line-length 79 -S .
isort -rc .

35
plasma_cash/README.md Normal file
View File

@ -0,0 +1,35 @@
# Development Dependencies
A patched version of web3.py is used because otherwise it does not work with Ganache due to issue #674. In addition, in order to be able to monitor events, PR #827, which is not merged yet. Pyethereum dependencies broke recently so we need to manually install a slightly older version of rlp encoding. Flask is used for server purposes.
On OSX + Homebrew
```
source /usr/local/bin/virtualenvwrapper.sh
```
```
mkvirtualenv erc721plasma --python=/usr/bin/python3.6
pip install -r requirements.txt
```
## Launch Plasma Chain
1. Make sure the contracts are deployed at the correct addresses (`npm run migrate:dev` in `server` directory)
2. Run `FLASK_APP=./child_chain FLASK_ENV=development flask run --port=8546` in one terminal. This will start a Plasma Chain instance which listens at `localhost:8546` and is also connected to the deployed contracts
3. Run `python demo.py`
TODO Should probably bundle these into makefiles, i.e. `make server` should launch the plasma chain.
## Testing
```
make test
```
## Linting
```
make lint
```

View File

@ -0,0 +1,66 @@
import time
from client.client import Client
from dependency_config import container
from utils.utils import increaseTime
dan = Client(container.get_root('dan'), container.get_token('dan'))
trudy = Client(container.get_root('trudy'), container.get_token('trudy'))
authority = Client(
container.get_root('authority'), container.get_token('authority')
)
# Give Trudy 5 tokens
trudy.register()
danTokensStart = dan.token_contract.balance_of()
# Trudy deposits a coin
tx_hash, gas_used = trudy.deposit(21)
event_data = trudy.root_chain.get_event_data('Deposit', tx_hash)
deposit1_utxo = event_data[0]['args']['slot']
# wait to make sure that events get fired correctly
time.sleep(2)
trudy_submit_block = authority.get_block_number()
trudyTokensStart = trudy.token_contract.balance_of()
coin = trudy.get_plasma_coin(deposit1_utxo)
authority.submit_block()
trudy.watch_exits(deposit1_utxo)
# Trudy sends her coin to Dan
trudy_to_dan = trudy.send_transaction(
deposit1_utxo, coin['deposit_block'], dan.token_contract.account.address
)
authority.submit_block()
trudy_to_dan_block = authority.get_block_number()
trudy.stop_watching_exits(deposit1_utxo)
# Dan attempts to exit his coin
coin = dan.get_plasma_coin(deposit1_utxo)
dan.start_exit(deposit1_utxo, coin['deposit_block'], trudy_to_dan_block)
authority.submit_block()
dan.watch_exits(deposit1_utxo)
dan.watch_challenges(deposit1_utxo)
# Dan is challenged by Trudy
trudy.challenge_before(deposit1_utxo, 0, coin['deposit_block'])
# Wait for dan to automatically respond to the challenge
time.sleep(2)
# Dan successfully finalizes his exit
w3 = dan.root_chain.w3
increaseTime(w3, 8 * 24 * 3600)
authority.finalize_exits()
dan.withdraw(deposit1_utxo)
danTokensEnd = dan.token_contract.balance_of()
print('dan has {} tokens'.format(danTokensEnd))
assert (
danTokensEnd == danTokensStart + 1
), "END: dan has incorrect number of tokens"
print('Automatic challenge response success :)')

157
plasma_cash/benchmark.py Normal file
View File

@ -0,0 +1,157 @@
import collections
from client.client import Client
from dependency_config import container
from utils.utils import increaseTime
authority = Client(
container.get_root("authority"), container.get_token("authority")
)
w3 = authority.root_chain.w3 # get w3 instance
child_block_interval = 1000
block_iterations = 8
coins_per_register = 5
num_deposited_coins = 2
coin_indices = range(0, num_deposited_coins)
number_of_players = 5
players_indices = range(0, number_of_players)
gas_costs = collections.defaultdict(dict)
players = list(
map(
lambda index: Client(
container.get_root("players", index),
container.get_token("players", index),
),
players_indices,
)
)
# Step 1: All players register to the game and are given 5 coins each.
# Step 2: They then proceed to deposit 2 of their coins to Plasma Cash.
deposits = {}
deposit_gas = 0
for index in players_indices:
players[index].register()
for coin_index in coin_indices:
tx_hash, gas_used = players[index].deposit(
index * coins_per_register + coin_index + 1
)
deposit_gas += gas_used
print('GAS USED FOR A DEPOSIT', gas_used)
deposits[index] = list(
map(lambda event: event["args"], players[index].get_all_deposits())
)
print("Player {} deposited coins: {}".format(index, deposits[index]))
# Get mean gas cost for deposits
gas_costs['deposit'] = deposit_gas / (number_of_players * num_deposited_coins)
print("STEP 3")
# Step 3: Each player gives their deposited coins to the next player
# 1000 players * 2 coins = 2k Plasma transactions per round
# This loops `block_iterations` times.
for iteration in range(block_iterations):
for index in players_indices:
neighbor_index = (index + 1) % number_of_players
deposit_index = (index - iteration) % number_of_players
for coin_index in coin_indices:
prev_block = (
deposits[index][coin_index]["blockNumber"]
if iteration == 0
else iteration * child_block_interval
)
print(
'{}: PLAYER {} to {} : Coin {} from block {}'.format(
iteration,
index,
neighbor_index,
deposits[deposit_index][coin_index]['slot'],
prev_block,
)
)
players[index].send_transaction(
deposits[deposit_index][coin_index]["slot"],
prev_block,
players[neighbor_index].token_contract.account.address,
)
authority.submit_block()
print("STEP 4")
# Step 4: All players initiate an exit for the coins they own.
# Since each player gave their coin to their neighbour, player `i`
# now owns the coins that player `(i-block_iterations) % num_players`
# initially had. Everyone initializes their exits
# by referencing the last 2 blocks
exit_gas = 0
for index in players_indices:
received = (index - block_iterations) % number_of_players
for coin_index in coin_indices:
print(
'PLAYER {} exiting {} from {}'.format(index, coin_index, received)
)
slot = deposits[received][coin_index]["slot"]
prev_block = (
deposits[received][coin_index]["blockNumber"]
if block_iterations == 1
else (block_iterations - 1) * child_block_interval
)
tx_hash, gas_used = players[index].start_exit(
slot, prev_block, block_iterations * child_block_interval
)
exit_gas += gas_used
gas_costs['exit'] = exit_gas / (number_of_players * num_deposited_coins)
increaseTime(w3, 8 * 24 * 3600)
# Somebody can finalize all exits, or each user can finalize their own
# authority.finalize_exits()
# Final step: Each user finalizes their exit after challenge period
# has passed and then withdraws their coins.
withdraw_gas = 0
finalize_exit_gas = 0
for index in players_indices:
received = (index - block_iterations) % number_of_players
for coin_index in coin_indices:
slot = deposits[received][coin_index]["slot"]
tx_hash, gas_used = players[index].finalize_exit(slot)
finalize_exit_gas += gas_used
tx_hash, gas_used = players[index].withdraw(slot)
withdraw_gas += gas_used
print("Player {} withdrew coin: {}".format(index, slot))
gas_costs['finalize_exit'] = finalize_exit_gas / (
number_of_players * num_deposited_coins
)
gas_costs['withdraw'] = withdraw_gas / (
number_of_players * num_deposited_coins
)
print('Benchmarking done :)')
print(
'Mean gas cost for {} transfers: (Deposit + \
Start Exit + Finalize Exit + Withdraw) = {}'.format(
block_iterations, sum(gas_costs.values())
)
)
# Authority registers and transacts on-chain, index = 1000
authority.register()
coin = number_of_players * coins_per_register + 2
tx_hash, gas_transfer = authority.token_contract.transfer(
players[0].token_contract.account.address, coin
)
print(
'Expected Gas cost for {} on-chain transfers \
(safeTransferFrom) = {}'.format(
block_iterations, block_iterations * gas_transfer
)
)

View File

@ -0,0 +1,87 @@
import time
from client.client import Client
from dependency_config import container
from utils.utils import increaseTime
dan = Client(container.get_root('dan'), container.get_token('dan'))
mallory = Client(container.get_root('mallory'), container.get_token('mallory'))
authority = Client(
container.get_root('authority'), container.get_token('authority')
)
# Give Mallory 5 tokens
mallory.register()
danTokensStart = dan.token_contract.balance_of()
print('Dan has {} tokens'.format(danTokensStart))
assert danTokensStart == 0, "START: Dan has incorrect number of tokens"
malloryTokensStart = mallory.token_contract.balance_of()
print('Mallory has {} tokens'.format(malloryTokensStart))
assert malloryTokensStart == 5, "START: Mallory has incorrect number of tokens"
current_block = authority.get_block_number()
print('current block: {}'.format(current_block))
# Mallory deposits one of her coins to the plasma contract
tx_hash, gas_used = mallory.deposit(6)
event_data = mallory.root_chain.get_event_data('Deposit', tx_hash)
deposit1_utxo = event_data[0]['args']['slot']
mallory.deposit(7)
# wait to make sure that events get fired correctly
time.sleep(2)
registered_deposits = mallory.get_all_deposits()
assert (
len(registered_deposits) == 2
), "Mallory has incorrect number of deposits"
malloryTokensPostDeposit = mallory.token_contract.balance_of()
print('Mallory has {} tokens'.format(malloryTokensPostDeposit))
assert (
malloryTokensPostDeposit == 3
), "POST-DEPOSIT: Mallory has incorrect number of tokens"
plasma_block1 = authority.submit_block()
plasma_block2 = authority.submit_block()
# Mallory sends her coin to Dan
# Coin 6 was the first deposit of
coin = mallory.get_plasma_coin(deposit1_utxo)
mallory_to_dan = mallory.send_transaction(
deposit1_utxo, coin['deposit_block'], dan.token_contract.account.address
)
incl_proofs, excl_proofs = mallory.get_coin_history(deposit1_utxo)
assert dan.verify_coin_history(deposit1_utxo, incl_proofs, excl_proofs)
plasma_block3 = authority.submit_block()
dan.watch_exits(deposit1_utxo)
# Mallory attempts to exit spent coin (the one sent to Dan)
# This will be auto-challenged by Dan's client
mallory.start_exit(deposit1_utxo, 0, coin['deposit_block'])
# Wait until challenge is done
time.sleep(2)
dan.start_exit(deposit1_utxo, coin['deposit_block'], plasma_block3)
dan.stop_watching_exits(deposit1_utxo)
w3 = dan.root_chain.w3 # get w3 instance
increaseTime(w3, 8 * 24 * 3600)
authority.finalize_exits()
dan.withdraw(deposit1_utxo)
dan_balance_before = w3.eth.getBalance(dan.token_contract.account.address)
dan.withdraw_bonds()
dan_balance_after = w3.eth.getBalance(dan.token_contract.account.address)
assert (
dan_balance_before < dan_balance_after
), "END: Dan did not withdraw his bonds"
malloryTokensEnd = mallory.token_contract.balance_of()
print('Mallory has {} tokens'.format(malloryTokensEnd))
assert malloryTokensEnd == 3, "END: Mallory has incorrect number of tokens"
danTokensEnd = dan.token_contract.balance_of()
print('Dan has {} tokens'.format(danTokensEnd))
assert danTokensEnd == 1, "END: Dan has incorrect number of tokens"
print('Plasma Cash `challengeAfter` success :)')

View File

@ -0,0 +1,79 @@
import time
from client.client import Client
from dependency_config import container
from utils.utils import increaseTime
dan = Client(container.get_root('dan'), container.get_token('dan'))
trudy = Client(container.get_root('trudy'), container.get_token('trudy'))
mallory = Client(container.get_root('mallory'), container.get_token('mallory'))
authority = Client(
container.get_root('authority'), container.get_token('authority')
)
# Give Dan 5 tokens
dan.register()
# Dan deposits a coin
tx_hash, gas_used = dan.deposit(16)
event_data = dan.root_chain.get_event_data('Deposit', tx_hash)
deposit1_utxo = event_data[0]['args']['slot']
# wait to make sure that events get fired correctly
time.sleep(2)
dan_submit_block = authority.get_block_number()
danTokensStart = dan.token_contract.balance_of()
coin = dan.get_plasma_coin(deposit1_utxo)
authority.submit_block()
dan.watch_exits(deposit1_utxo)
# Trudy sends her invalid coin to Mallory
trudy_to_mallory = trudy.send_transaction(
deposit1_utxo,
coin['deposit_block'],
mallory.token_contract.account.address,
)
authority.submit_block()
trudy_to_mallory_block = authority.get_block_number()
# Mallory sends her invalid coin to Trudy
mallory_to_trudy = mallory.send_transaction(
deposit1_utxo, trudy_to_mallory_block, trudy.token_contract.account.address
)
authority.submit_block()
mallory_to_trudy_block = authority.get_block_number()
# Trudy attemps to exit her illegitimate coin
trudy.start_exit(deposit1_utxo, trudy_to_mallory_block, mallory_to_trudy_block)
time.sleep(2) # need to wait a bit for authority to catch up
w3 = dan.root_chain.w3
# Dan challenges Trudy's exit
increaseTime(w3, 8 * 24 * 3600)
authority.finalize_exits()
dan.start_exit(deposit1_utxo, 0, coin['deposit_block'])
dan.stop_watching_exits(deposit1_utxo)
increaseTime(w3, 8 * 24 * 3600)
authority.finalize_exits()
dan.withdraw(deposit1_utxo)
dan_balance_before = w3.eth.getBalance(dan.token_contract.account.address)
dan.withdraw_bonds()
dan_balance_after = w3.eth.getBalance(dan.token_contract.account.address)
assert (
dan_balance_before < dan_balance_after
), "END: Dan did not withdraw his bonds"
danTokensEnd = dan.token_contract.balance_of()
print('dan has {} tokens'.format(danTokensEnd))
assert (
danTokensEnd == danTokensStart + 1
), "END: dan has incorrect number of tokens"
print('Plasma Cash `challengeBefore` success :)')

View File

@ -0,0 +1,74 @@
import time
from client.client import Client
from dependency_config import container
from utils.utils import increaseTime
alice = Client(container.get_root('alice'), container.get_token('alice'))
bob = Client(container.get_root('bob'), container.get_token('bob'))
eve = Client(container.get_root('eve'), container.get_token('eve'))
authority = Client(
container.get_root('authority'), container.get_token('authority')
)
bobTokensStart = bob.token_contract.balance_of()
# Give Eve 5 tokens
eve.register()
# Eve deposits a coin
tx_hash, gas_used = eve.deposit(11)
event_data = eve.root_chain.get_event_data('Deposit', tx_hash)
deposit1_utxo = event_data[0]['args']['slot']
# wait to make sure that events get fired correctly
time.sleep(2)
# Eve sends her plasma coin to Bob
coin = eve.get_plasma_coin(deposit1_utxo)
eve_to_bob = eve.send_transaction(
deposit1_utxo, coin['deposit_block'], bob.token_contract.account.address
)
authority.submit_block()
eve_to_bob_block = authority.get_block_number()
bob.watch_exits(deposit1_utxo)
# Eve sends this same plasma coin to Alice
eve_to_alice = eve.send_transaction(
deposit1_utxo, coin['deposit_block'], alice.token_contract.account.address
)
authority.submit_block()
eve_to_alice_block = authority.get_block_number()
# Alice attempts to exit here double-spent coin
# Bob auto-challenges Alice's exit
alice.start_exit(deposit1_utxo, coin['deposit_block'], eve_to_alice_block)
# bob.challenge_between(deposit1_utxo, eve_to_bob_block)
# Wait for challenge
time.sleep(2)
bob.start_exit(deposit1_utxo, coin['deposit_block'], eve_to_bob_block)
bob.stop_watching_exits(deposit1_utxo)
w3 = bob.root_chain.w3 # get w3 instance
increaseTime(w3, 8 * 24 * 3600)
authority.finalize_exits()
bob.withdraw(deposit1_utxo)
bob_balance_before = w3.eth.getBalance(bob.token_contract.account.address)
bob.withdraw_bonds()
bob_balance_after = w3.eth.getBalance(bob.token_contract.account.address)
assert (
bob_balance_before < bob_balance_after
), "END: Bob did not withdraw his bonds"
bobTokensEnd = bob.token_contract.balance_of()
print('Bob has {} tokens'.format(bobTokensEnd))
assert (
bobTokensEnd == bobTokensStart + 1
), "END: Bob has incorrect number of tokens"
print('Plasma Cash `challengeBetween` success :)')

View File

@ -0,0 +1,16 @@
from flask import Flask
from dependency_config import container
def create_app():
app = Flask(__name__)
# Create a child chain instance when creating a Flask app.
container.get_child_chain()
from . import server
app.register_blueprint(server.bp)
return app

View File

@ -0,0 +1,67 @@
import rlp
from rlp.sedes import CountableList, binary
from web3.auto import w3
from child_chain.exceptions import (CoinAlreadyIncludedException,
InvalidBlockSignatureException)
from utils.merkle.sparse_merkle_tree import SparseMerkleTree
from utils.utils import get_sender, sign
from .transaction import Transaction
class Block(rlp.Serializable):
fields = [('transaction_set', CountableList(Transaction)), ('sig', binary)]
def __init__(self, transaction_set=None, sig=b'\x00' * 65):
if transaction_set is None:
self.transactions = {}
else:
self.transactions = {tx.uid: tx for tx in transaction_set}
self.merkle = None
self.sig = sig
@property
def hash(self):
return w3.sha3(rlp.encode(self, UnsignedBlock))
@property
def merkle_hash(self):
return w3.sha3(rlp.encode(self))
@property
def transaction_set(self):
return list(self.transactions.values())
@property
def sender(self):
if self.sig == b'\x00' * 65:
raise InvalidBlockSignatureException('Block not signed')
return get_sender(self.hash, self.sig)
def merklize_transaction_set(self):
hashed_transaction_dict = {
tx.uid: tx.hash for tx in self.transactions.values()
}
self.merkle = SparseMerkleTree(64, hashed_transaction_dict)
return self.merkle.root
def add_tx(self, tx):
if tx.uid in self.transactions:
raise CoinAlreadyIncludedException('double spend rejected')
else:
self.transactions[tx.uid] = tx
# `uid` is the coin that was transferred
def get_tx_by_uid(self, uid):
if uid in self.transactions:
return self.transactions[uid]
else:
return Transaction(0, 0, 0, 0)
def sign(self, key):
self.sig = sign(self.hash, key)
UnsignedBlock = Block.exclude(['sig'])

View File

@ -0,0 +1,121 @@
import rlp
from ethereum import utils
from web3.auto import w3
from .block import Block
from .exceptions import (InvalidPrevBlockException,
InvalidTxSignatureException,
PreviousTxNotFoundException, TxAlreadySpentException)
from .transaction import Transaction
class ChildChain(object):
'''
Operator runs child chain, watches all Deposit events and creates
deposit blocks
'''
def __init__(self, root_chain):
self.root_chain = root_chain # PlasmaCash object from plasma_cash.py
self.authority = self.root_chain.account.address
self.key = self.root_chain.account.privateKey
self.blocks = {}
self.current_block = Block()
self.child_block_interval = 1000
self.current_block_number = 0
# Watch all deposit events, callback to self._send_deposit
self.root_chain.watch_event('Deposit', self._send_deposit, 0.1)
def _send_deposit(self, event):
''' Called by event watcher and creates a deposit block '''
slot = event['args']['slot']
blknum = int(event['args']['blockNumber'])
# Currently, denomination is always 1. This may change in the future.
denomination = event['args']['denomination']
depositor = event['args']['from']
deposit_tx = Transaction(slot, 0, denomination, depositor)
# create a new plasma block on deposit
deposit_block = Block([deposit_tx])
self.blocks[blknum] = deposit_block
def submit_block(self):
''' Submit the merkle root to the chain from the authority '''
block = self.current_block
block.make_mutable()
block.sign(self.key)
block.make_immutable()
self.current_block_number += self.child_block_interval
merkle_hash = w3.toHex(block.merklize_transaction_set())
self.root_chain.submit_block(merkle_hash)
self.blocks[self.current_block_number] = self.current_block
self.current_block = Block()
return str(self.current_block_number)
def send_transaction(self, transaction):
tx = rlp.decode(utils.decode_hex(transaction), Transaction)
# Reject transactions refering to a future block as prev_block
if (
tx.prev_block
> self.current_block_number + self.child_block_interval
):
raise InvalidPrevBlockException('failed to send transaction')
# If the tx we are spending is not a deposit tx
if tx.prev_block % self.child_block_interval == 0:
# If the TX we are referencing was initially a deposit TX, then it
# does not have a signature attached
# The tx we are referencing should be included in a block
prev_tx = self.blocks[tx.prev_block].get_tx_by_uid(tx.uid)
if prev_tx is None:
raise PreviousTxNotFoundException('failed to send transaction')
# The tx we are referencing should not be spent
if prev_tx.spent:
raise TxAlreadySpentException('failed to send transaction')
# deposit tx if prev_block is 0
if (
prev_tx.prev_block % self.child_block_interval == 0
and utils.normalize_address(tx.sender) != prev_tx.new_owner
):
raise InvalidTxSignatureException('failed to send transaction')
# `add_tx` automatically checks if the coin has already been moved
# in the current block
self.current_block.add_tx(tx)
prev_tx.spent = True # Mark the previous tx as spent
# If the tx we are spending is a deposit tx
else:
self.current_block.add_tx(tx)
return tx.hash
def get_current_block(self):
return rlp.encode(self.current_block).hex()
def get_block(self, blknum):
if blknum > self.current_block_number:
return rlp.encode(Block()).hex()
else:
return rlp.encode(self.blocks[blknum]).hex()
def get_block_number(self):
return self.current_block_number
def get_proof(self, blknum, slot):
block = self.blocks[blknum]
block.merklize_transaction_set()
return block.merkle.create_merkle_proof(slot).hex()
def get_tx(self, blknum, slot):
block = self.blocks[blknum]
tx = block.get_tx_by_uid(slot)
return rlp.encode(tx).hex()
def get_tx_and_proof(self, blknum, slot):
tx = self.get_tx(blknum, slot)
if blknum % self.child_block_interval != 0:
proof = '00' * 8
else:
proof = self.get_proof(blknum, slot)
return tx, proof

View File

@ -0,0 +1,26 @@
class InvalidTxSignatureException(Exception):
"""the signature of a tx is invalid"""
class CoinAlreadyIncludedException(Exception):
"""the coin uid has already been included in block"""
class InvalidBlockSignatureException(Exception):
"""the signature of a block is invalid"""
class PreviousTxNotFoundException(Exception):
"""previous transaction is not found"""
class TxAlreadySpentException(Exception):
"""the transaction is already spent"""
class TxAmountMismatchException(Exception):
"""tx input total amount is not equal to output total amount"""
class InvalidPrevBlockException(Exception):
"""prev block cannot be bigger than current block"""

View File

@ -0,0 +1,55 @@
from flask import Blueprint, jsonify, request
from dependency_config import container
bp = Blueprint('api', __name__)
@bp.route('/block/<blknum>', methods=['GET'])
def get_block(blknum):
return container.get_child_chain().get_block(int(blknum))
@bp.route('/block', methods=['GET'])
def get_current_block():
return container.get_child_chain().get_current_block()
@bp.route('/blocknumber', methods=['GET'])
def get_block_number():
return str(container.get_child_chain().get_block_number())
@bp.route('/tx_proof', methods=['GET'])
def get_tx_and_proof():
blknum = int(request.args.get('blknum'))
slot = int(request.args.get('slot'))
tx, proof = container.get_child_chain().get_tx_and_proof(
int(blknum), int(slot)
)
return jsonify({'tx': tx, 'proof': proof})
@bp.route('/tx', methods=['GET'])
def get_tx():
blknum = int(request.args.get('blknum'))
slot = int(request.args.get('slot'))
return container.get_child_chain().get_tx(blknum, slot)
@bp.route('/proof', methods=['GET'])
def get_proof():
blknum = int(request.args.get('blknum'))
slot = int(request.args.get('slot'))
return container.get_child_chain().get_proof(blknum, slot)
@bp.route('/submit_block', methods=['POST'])
def submit_block():
return container.get_child_chain().submit_block()
@bp.route('/send_tx', methods=['POST'])
def send_tx():
tx = request.form['tx']
return container.get_child_chain().send_transaction(tx)

View File

@ -0,0 +1,54 @@
import ethereum.utils
import rlp
from rlp.sedes import big_endian_int, binary
from web3.auto import w3
from utils.utils import get_sender, sign
from .exceptions import InvalidTxSignatureException
class Transaction(rlp.Serializable):
fields = [
('uid', big_endian_int),
('prev_block', big_endian_int),
('denomination', big_endian_int),
('new_owner', ethereum.utils.address),
('sig', binary),
]
def __init__(
self, uid, prev_block, denomination, new_owner, sig=b'\x00' * 65
):
self.uid = uid
self.prev_block = prev_block
self.denomination = denomination
self.new_owner = ethereum.utils.normalize_address(new_owner)
self.sig = sig
self.spent = False # not part of the rlp
self.make_mutable()
@property
def hash(self):
if self.prev_block != 0:
ret = w3.sha3(rlp.encode(self, UnsignedTransaction))
else:
ret = w3.soliditySha3(['uint64'], [self.uid])
return ret
@property
def merkle_hash(self):
return w3.sha3(rlp.encode(self))
@property
def sender(self):
if self.sig == b'\x00' * 65:
raise InvalidTxSignatureException('Tx not signed')
return get_sender(self.hash, self.sig)
def sign(self, key):
self.sig = sign(self.hash, key)
UnsignedTransaction = Transaction.exclude(['sig'])

View File

@ -0,0 +1,73 @@
import requests
from .exceptions import RequestFailedException
class ChildChainService(object):
def __init__(self, base_url, verify=False, timeout=5):
self.base_url = base_url
self.verify = verify
self.timeout = timeout
def request(self, end_point, method, params=None, data=None, headers=None):
url = self.base_url + end_point
response = requests.request(
method=method,
url=url,
params=params,
data=data,
headers=headers,
verify=self.verify,
timeout=self.timeout,
)
if response.ok:
return response
else:
raise RequestFailedException(
'failed with response: {}'.format(response)
)
def get_current_block(self):
end_point = '/block'
response = self.request(end_point, 'GET')
return response.text
def get_block_number(self):
end_point = '/blocknumber'
response = self.request(end_point, 'GET')
return int(response.text)
def get_block(self, blknum):
end_point = '/block/{}'.format(blknum)
response = self.request(end_point, 'GET')
return response.text
def get_proof(self, blknum, slot):
end_point = '/proof'
params = {'blknum': blknum, 'slot': slot}
response = self.request(end_point, 'GET', params=params)
return response.text
def get_tx_and_proof(self, blknum, slot):
end_point = '/tx_proof'
params = {'blknum': blknum, 'slot': slot}
response = self.request(end_point, 'GET', params=params)
return response.text
def get_tx(self, blknum, slot):
end_point = '/tx'
params = {'blknum': blknum, 'slot': slot}
response = self.request(end_point, 'GET', params=params)
return response.text
def submit_block(self):
end_point = '/submit_block'
response = self.request(end_point, 'POST')
return int(response.text)
def send_transaction(self, tx):
end_point = '/send_tx'
data = {'tx': tx}
self.request(end_point, 'POST', data=data)

View File

@ -0,0 +1,438 @@
import json
import rlp
from ethereum import utils
from child_chain.block import Block
from child_chain.transaction import Transaction, UnsignedTransaction
from .child_chain_service import ChildChainService
class Client(object):
def __init__(
self,
root_chain,
token_contract,
child_chain=ChildChainService('http://localhost:8546'),
):
self.root_chain = root_chain
self.key = token_contract.account.privateKey
self.token_contract = token_contract
self.child_chain = child_chain
self.child_block_interval = 1000
# Proof related state
self.incl_proofs = {}
self.excl_proofs = {}
self.txs = {}
# Event watchers
self.watchers = {}
self.challenge_watchers = {}
# Token Functions
def register(self):
''' Register a new player and grant 5 cards, for demo purposes'''
tx_hash, gas_used = self.token_contract.register()
return tx_hash, gas_used
def deposit(self, tokenId):
''' Deposit happens by a use calling the erc721 token contract '''
tx_hash, gas_used = self.token_contract.deposit(tokenId)
return tx_hash, gas_used
# Plasma Functions
def start_exit(self, slot, prev_tx_blk_num, tx_blk_num):
'''
As a user, you declare that you want to exit a coin at slot `slot`
at the state which happened at block `tx_blk_num` and you also need to
reference a previous block
'''
# TODO The actual proof information should be passed to a user from its
# previous owners, this is a hacky way of getting the info from the
# operator which sould be changed in the future after the exiting
# process is more standardized
if tx_blk_num % self.child_block_interval != 0:
# In case the sender is exiting a Deposit transaction, they should
# just create a signed transaction to themselves. There is no need
# for a merkle proof.
# prev_block = 0 , denomination = 1
exiting_tx = Transaction(
slot, 0, 1, self.token_contract.account.address
)
exiting_tx.make_mutable()
exiting_tx.sign(self.key)
exiting_tx.make_immutable()
tx_hash, gas_used = self.root_chain.start_exit(
slot,
b'0x0',
rlp.encode(exiting_tx, UnsignedTransaction),
b'0x0',
b'0x0',
exiting_tx.sig,
0,
tx_blk_num,
)
else:
# Otherwise, they should get the raw tx info from the block
# And the merkle proof and submit these
exiting_tx, exiting_tx_proof = self.get_tx_and_proof(
tx_blk_num, slot
)
prev_tx, prev_tx_proof = self.get_tx_and_proof(
prev_tx_blk_num, slot
)
tx_hash, gas_used = self.root_chain.start_exit(
slot,
rlp.encode(prev_tx, UnsignedTransaction),
rlp.encode(exiting_tx, UnsignedTransaction),
prev_tx_proof,
exiting_tx_proof,
exiting_tx.sig,
prev_tx_blk_num,
tx_blk_num,
)
return tx_hash, gas_used
def challenge_before(self, slot, prev_tx_blk_num, tx_blk_num):
if tx_blk_num % self.child_block_interval != 0:
# In case the sender is exiting a Deposit transaction, they should
# just create a signed transaction to themselves. There is no need
# for a merkle proof.
# prev_block = 0 , denomination = 1
exiting_tx = Transaction(
slot, 0, 1, self.token_contract.account.address
)
exiting_tx.make_mutable()
exiting_tx.sign(self.key)
exiting_tx.make_immutable()
tx_hash, gas_used = self.root_chain.challenge_before(
slot,
b'0x0',
rlp.encode(exiting_tx, UnsignedTransaction),
b'0x0',
b'0x0',
exiting_tx.sig,
0,
tx_blk_num,
)
else:
# Otherwise, they should get the raw tx info from the block
# And the merkle proof and submit these
exiting_tx, exiting_tx_proof = self.get_tx_and_proof(
tx_blk_num, slot
)
prev_tx, prev_tx_proof = self.get_tx_and_proof(
prev_tx_blk_num, slot
)
tx_hash, gas_used = self.root_chain.challenge_before(
slot,
rlp.encode(prev_tx, UnsignedTransaction),
rlp.encode(exiting_tx, UnsignedTransaction),
prev_tx_proof,
exiting_tx_proof,
exiting_tx.sig,
prev_tx_blk_num,
tx_blk_num,
)
return tx_hash, gas_used
def respond_challenge_before(self, slot, challenging_block_number):
'''
Respond to an exit with invalid history challenge by proving that
you were given the coin under question
'''
challenging_tx, proof = self.get_tx_and_proof(
challenging_block_number, slot
)
tx_hash, gas_used = self.root_chain.respond_challenge_before(
slot,
challenging_block_number,
rlp.encode(challenging_tx, UnsignedTransaction),
proof,
challenging_tx.sig,
)
return tx_hash, gas_used
def challenge_between(self, slot, challenging_block_number):
'''
`Double Spend Challenge`: Challenge a double spend of a coin
with a spend between the exit's blocks
'''
challenging_tx, proof = self.get_tx_and_proof(
challenging_block_number, slot
)
tx_hash, gas_used = self.root_chain.challenge_between(
slot,
challenging_block_number,
rlp.encode(challenging_tx, UnsignedTransaction),
proof,
challenging_tx.sig,
)
return tx_hash, gas_used
def challenge_after(self, slot, challenging_block_number):
'''
`Exit Spent Coin Challenge`: Challenge an exit with a spend
after the exit's blocks
'''
challenging_tx, proof = self.get_tx_and_proof(
challenging_block_number, slot
)
tx_hash, gas_used = self.root_chain.challenge_after(
slot,
challenging_block_number,
rlp.encode(challenging_tx, UnsignedTransaction),
proof,
challenging_tx.sig,
)
return tx_hash, gas_used
def finalize_exit(self, slot):
tx_hash, gas_used = self.root_chain.finalize_exit(slot)
return tx_hash, gas_used
def finalize_exits(self):
tx_hash, gas_used = self.root_chain.finalize_exits()
return tx_hash, gas_used
def withdraw(self, slot):
tx_hash, gas_used = self.root_chain.withdraw(slot)
return tx_hash, gas_used
def withdraw_bonds(self):
tx_hash, gas_used = self.root_chain.withdraw_bonds()
return tx_hash, gas_used
def get_plasma_coin(self, slot):
return self.root_chain.get_plasma_coin(slot)
def get_block_root(self, blknum):
return self.root_chain.get_block_root(blknum)
def check_inclusion(self, leaf, root, slot, proof):
return self.root_chain.check_inclusion(leaf, root, slot, proof)
def check_exclusion(self, root, slot, proof):
return self.root_chain.check_exclusion(root, slot, proof)
# Child Chain Functions
def get_block_numbers(self, slot):
# First get the coin's deposit block
# todo efficiency -> start_block should be updated to the last block
# obtained last time
start_block = self.get_plasma_coin(slot)['deposit_block']
# Get next non-deposit block
next_deposit = (
(start_block + self.child_block_interval)
// self.child_block_interval
* self.child_block_interval
)
end_block = self.get_block_number()
# Create a list of indexes with coin's deposit block
# and all subsequent submitted blocks that followed
block_numbers = [start_block] + list(
range(next_deposit, end_block + 1, self.child_block_interval)
)
return block_numbers
def get_coin_history(self, slot):
block_numbers = self.get_block_numbers(slot)
incl_proofs = {}
excl_proofs = {}
txs = {}
for blknum in block_numbers:
blk_root = self.root_chain.get_block_root(blknum)
tx, proof = self.get_tx_and_proof(blknum, slot)
txs[blknum] = tx
if self.check_inclusion(tx, blk_root, slot, proof):
incl_proofs[blknum] = proof
else:
excl_proofs[blknum] = proof
# Save the proofs to the client's "state", and return
self.incl_proofs[slot] = incl_proofs
self.excl_proofs[slot] = excl_proofs
self.txs[slot] = txs
return incl_proofs, excl_proofs
# received_proofs should be a dictionary with merkle branches for each
# block
def verify_coin_history(self, slot, incl_proofs, excl_proofs):
# Sanity checks, make sure incl_proofs and excl_proofs have all the
# correct keys for the coin
incl_keys = set(incl_proofs)
excl_keys = set(excl_proofs)
if len(incl_keys.intersection(excl_keys)) != 0:
return False
# gets all of the coin's block numbers
block_numbers = self.get_block_numbers(slot)
# ensure that all keys are included
if incl_keys.union(excl_keys) != set(block_numbers):
return False
# assert inclusion proofs
for blknum, proof in incl_proofs.items():
blk_root = self.root_chain.get_block_root(blknum)
# should we be polling the tx from the operator or trusting the
# receiver?
tx = self.get_tx(blknum, slot)
if not self.check_inclusion(tx, blk_root, slot, proof):
return False
# assert exclusion proof / i.e. leaf at that slot is empty hash
for blknum, proof in excl_proofs.items():
blk_root = self.root_chain.get_block_root(blknum)
if not self.check_exclusion(blk_root, slot, proof):
return False
# If it does not hit any of the return false branches, it's OK
return True
def submit_block(self):
return self.child_chain.submit_block()
def send_transaction(self, slot, prev_block, new_owner):
new_owner = utils.normalize_address(new_owner)
tx = Transaction(slot, prev_block, 1, new_owner)
tx.make_mutable()
tx.sign(self.key)
tx.make_immutable()
self.child_chain.send_transaction(rlp.encode(tx, Transaction).hex())
return tx
def watch_challenges(self, slot):
self.challenge_watchers[slot] = self.root_chain.watch_event(
'ChallengedExit',
self._respond_to_challenge,
0.1,
filters={'slot': slot},
)
def _respond_to_challenge(self, event):
slot = event['args']['slot']
print(
"CHALLENGE DETECTED by {} -- slot: {}".format(
self.token_contract.account.address, slot
)
)
# fetch coin history
incl_proofs, excl_proofs = self.get_coin_history(slot)
received_block = max(incl_proofs.keys())
self.respond_challenge_before(slot, received_block)
def stop_watching_challenges(self, slot):
# a user stops watching exits of a particular coin after transferring
# it to another plasma user
event_filter = self.challenge_watchers[slot]
self.root_chain.w3.eth.uninstallFilter(event_filter.filter_id)
def watch_exits(self, slot):
# TODO figure out how to have this function be invoked automatically
self.watchers[slot] = self.root_chain.watch_event(
'StartedExit', self._respond_to_exit, 0.1, filters={'slot': slot}
)
def _respond_to_exit(self, event):
''' Called by event watcher and checks that the exit event is
legitimate
'''
slot = event['args']['slot']
owner = event['args']['owner']
print(
"EXIT DETECTED by {} -- slot: {}, owner: {}".format(
self.token_contract.account.address, slot, owner
)
)
# A coin-owner will automatically start a challenge if he believes he
# owns a coin that has been exited by someone else
if owner != self.token_contract.account.address:
print("invalid exit...challenging")
# fetch exit information
exit_details = self.root_chain.get_exit(slot)
[owner, prev_block, exit_block, state] = exit_details
# fetch coin history
incl_proofs, excl_proofs = self.get_coin_history(slot)
blocks = self.get_block_numbers(slot) # skip the deposit tx block
for blk in blocks:
if blk not in incl_proofs:
continue
if blk > exit_block:
print(
'CHALLENGE AFTER -- {} at block {}'.format(slot, blk)
)
self.challenge_after(slot, blk)
break
elif prev_block < blk < exit_block:
print(
'CHALLENGE BETWEEN -- {} at block {}'.format(
slot, blk
)
)
self.challenge_between(slot, blk)
break
elif blk < prev_block < exit_block:
# Need to find a previous block
tx = self.get_tx(blk, slot)
print(
'CHALLENGE BEFORE -- {} at prev block {} / block {}'
.format(
slot, tx.prev_block, blk
)
)
self.challenge_before(slot, tx.prev_block, blk)
break
else:
print("valid exit")
def stop_watching_exits(self, slot):
# a user stops watching exits of a particular coin after transferring
# it to another plasma user
event_filter = self.watchers[slot]
self.root_chain.w3.eth.uninstallFilter(event_filter.filter_id)
def get_block_number(self):
return self.child_chain.get_block_number()
def get_current_block(self):
block = self.child_chain.get_current_block()
return rlp.decode(utils.decode_hex(block), Block)
def get_block(self, blknum):
block = self.child_chain.get_block(blknum)
return rlp.decode(utils.decode_hex(block), Block)
def get_tx(self, blknum, slot):
tx_bytes = self.child_chain.get_tx(blknum, slot)
tx = rlp.decode(utils.decode_hex(tx_bytes), Transaction)
return tx
def get_tx_and_proof(self, blknum, slot):
data = json.loads(self.child_chain.get_tx_and_proof(blknum, slot))
tx = rlp.decode(utils.decode_hex(data['tx']), Transaction)
proof = utils.decode_hex(data['proof'])
return tx, proof
def get_proof(self, blknum, slot):
return utils.decode_hex(self.child_chain.get_proof(blknum, slot))
def get_all_deposits(self):
return self.root_chain.get_all_deposits(
self.root_chain.account.address
)

View File

@ -0,0 +1,2 @@
class RequestFailedException(Exception):
"""request failed without success http status"""

1006
plasma_cash/config.py Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,147 @@
import json
import time
from threading import Thread
from web3.utils.events import get_event_data
from ..utils.getWeb3 import getWeb3
class Contract(object):
'''Base class for interfacing with a contract'''
def __init__(self, keystore, address, abi_file, endpoint):
w3 = getWeb3(endpoint)
with open(abi_file) as f:
abi = json.load(f)['abiDefinition']
contract = w3.eth.contract(abi=abi, address=address)
self.w3 = w3
if keystore is not None:
self.account = self.to_account(keystore)
self.contract = contract
def to_account(self, data):
account = self.w3.eth.account.privateKeyToAccount(data)
del data
return account
def sign_and_send(self, func, args, value=0, gas=1000000):
''' Expecting all arguments in 1 array '''
signed_tx = self._sign_function_call(
func,
args,
value,
# may need to change gas
gas,
)
try:
tx_hash, gas_used = self._send_raw_tx(signed_tx)
except Exception as e:
print('FAILURE: ', e)
info = 'Failed: {}, Args: {}'.format(func.__name__, args)
print(info)
return tx_hash, gas_used
def send_transaction(self, to, value):
signed_tx = self._sign_transaction(to, value)
return self._send_raw_tx(signed_tx)
def _sign_transaction(self, to, value):
gas = 21000
gasPrice = self.w3.toWei('10', 'gwei')
raw_tx = {
'chainId': int(self.w3.version.network),
'to': self.w3.toChecksumAddress(to),
'value': value,
'gas': gas,
'gasPrice': gasPrice,
'nonce': self.w3.eth.getTransactionCount(self.account.address),
}
# print(raw_tx)
signed_tx = self.account.signTransaction(raw_tx)
return signed_tx
def _sign_function_call(self, func, args, value, gas):
"""
Takes reading and timestamp and creates a
raw transaction call to `ping` at the target contract
TODO: Add option to modify gas
"""
# Build the raw transaction
raw_tx = func(*args).buildTransaction(
{
'gas': gas,
'value': value,
'nonce': self.w3.eth.getTransactionCount(self.account.address),
}
)
raw_tx['to'] = self.w3.toChecksumAddress(raw_tx['to'])
# Sign the transaction with the meter's private key
signed_tx = self.account.signTransaction(raw_tx)
return signed_tx
def _send_raw_tx(self, signed_tx):
tx_hash = self.w3.eth.sendRawTransaction(signed_tx.rawTransaction)
gas_used = self.waitForTxReceipt(tx_hash)['gasUsed']
return tx_hash, gas_used
def waitForTxReceipt(self, tx):
receipt = self.w3.eth.getTransactionReceipt(tx)
while receipt is None:
time.sleep(1) # Block time avg
receipt = self.w3.eth.getTransactionReceipt(tx)
return receipt
def get_event_data(self, event_name, tx_hash):
tx_logs = self.w3.eth.getTransactionReceipt(tx_hash)['logs']
event_abi = self.contract._find_matching_event_abi(event_name)
matched = []
for log in tx_logs:
try:
d = get_event_data(event_abi, log)
except Exception as e:
continue
matched.append(d)
return matched
def watch_event(
self,
event_name,
callback,
interval,
fromBlock=0,
toBlock='latest',
filters=None,
):
event_filter = self.install_filter(
event_name, fromBlock, toBlock, filters
)
Thread(
target=self.watcher,
args=(event_filter, callback, interval),
daemon=True,
).start()
return event_filter
def watcher(self, event_filter, callback, interval):
while True:
for event in event_filter.get_new_entries():
callback(event)
time.sleep(interval)
def install_filter(
self, event_name, fromBlock=0, toBlock='latest', filters=None
):
event = getattr(self.contract.events, event_name)
eventFilter = event.createFilter(
fromBlock=fromBlock, toBlock=toBlock, argument_filters=filters
)
return eventFilter

View File

@ -0,0 +1,35 @@
from .base.contract import Contract
class ERC721(Contract):
'''ERC721 bindings for python '''
def __init__(self, private_key, abi_file, address, endpoint):
super().__init__(private_key, address, abi_file, endpoint)
def register(self):
args = []
return self.sign_and_send(self.contract.functions.register, args)
def transfer(self, to, tokenId, data=None):
if data is None:
args = [self.account.address, to, tokenId]
else:
args = [self.account.address, to, tokenId, data]
return self.sign_and_send(
self.contract.functions.safeTransferFrom, args
)
def deposit(self, tokenId):
'''
Slot is providable by the user however there is a validity check
performed in the contract. It always needs to be the value of
`NUM_COINS` in the plasma contract
'''
args = [tokenId]
return self.sign_and_send(
self.contract.functions.depositToPlasma, args
)
def balance_of(self):
return self.contract.functions.balanceOf(self.account.address).call()

View File

@ -0,0 +1,179 @@
from .base.contract import Contract
class PlasmaCash(Contract):
'''Plasma Cash bindings for python '''
def __init__(self, private_key, abi_file, address, endpoint):
super().__init__(private_key, address, abi_file, endpoint)
self.BOND = self.w3.toWei(0.1, 'ether')
def challenge_before(
self,
slot,
prev_tx_bytes,
exiting_tx_bytes,
prev_tx_inclusion_proof,
exiting_tx_inclusion_proof,
sig,
prev_tx_block_num,
exiting_tx_block_num,
):
args = [
slot,
prev_tx_bytes,
exiting_tx_bytes,
prev_tx_inclusion_proof,
exiting_tx_inclusion_proof,
sig,
[prev_tx_block_num, exiting_tx_block_num],
]
return self.sign_and_send(
self.contract.functions.challengeBefore, args, value=self.BOND
)
def respond_challenge_before(
self,
slot,
challenging_block_number,
challenging_transaction,
proof,
sig,
):
args = [
slot,
challenging_block_number,
challenging_transaction,
proof,
sig,
]
return self.sign_and_send(
self.contract.functions.respondChallengeBefore, args
)
def challenge_between(
self,
slot,
challenging_block_number,
challenging_transaction,
proof,
sig,
):
args = [
slot,
challenging_block_number,
challenging_transaction,
proof,
sig,
]
return self.sign_and_send(
self.contract.functions.challengeBetween, args
)
def challenge_after(
self,
slot,
challenging_block_number,
challenging_transaction,
proof,
sig,
):
args = [
slot,
challenging_block_number,
challenging_transaction,
proof,
sig,
]
return self.sign_and_send(self.contract.functions.challengeAfter, args)
def start_exit(
self,
uid,
prev_tx,
exiting_tx,
prev_tx_proof,
exiting_tx_proof,
sigs,
prev_tx_blk_num,
tx_blk_num,
):
args = [
uid,
prev_tx,
exiting_tx,
prev_tx_proof,
exiting_tx_proof,
sigs,
[prev_tx_blk_num, tx_blk_num],
]
return self.sign_and_send(
self.contract.functions.startExit, args, value=self.BOND
)
def finalize_exits(self):
args = []
return self.sign_and_send(self.contract.functions.finalizeExits, args)
def finalize_exit(self, slot):
args = [slot]
return self.sign_and_send(self.contract.functions.finalizeExit, args)
def withdraw(self, uid):
args = [uid]
return self.sign_and_send(self.contract.functions.withdraw, args)
def submit_block(self, root):
args = [root]
return self.sign_and_send(self.contract.functions.submitBlock, args)
def withdraw_bonds(self):
return self.sign_and_send(self.contract.functions.withdrawBonds, [])
def get_plasma_coin(self, slot):
data = self.contract.functions.getPlasmaCoin(slot).call()
ret = {
'uid': data[0],
'deposit_block': data[1],
'denomination': data[2],
'owner': data[3],
'contract_address': data[4],
'state': data[5],
}
return ret
def get_all_deposits(self, address, fromBlock=0):
event_filter = self.contract.events.Deposit.createFilter(
fromBlock=fromBlock,
toBlock='latest',
argument_filters={'from': address},
)
return event_filter.get_all_entries()
def get_block_root(self, blknum):
ret = self.contract.functions.getBlockRoot(blknum).call()
return ret
def get_exit(self, slot):
ret = self.contract.functions.getExit(slot).call()
return ret
def check_inclusion(self, tx, root, slot, proof):
if tx.prev_block == 0: # deposit tx
ret = tx.hash == root
else:
ret = self.contract.functions.checkMembership(
tx.hash, root, slot, proof
).call()
return ret
def check_exclusion(self, root, slot, proof):
empty_hash = (
'0x290decd9548b62a8d60345a988386'
+ 'fc84ba6bc95484008f6362f93160ef3e563'
)
ret = self.contract.functions.checkMembership(
empty_hash, root, slot, proof
).call()
return ret

View File

@ -0,0 +1,17 @@
class Colors:
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
END = '\033[0m'
def green(txt):
return Colors.GREEN + txt + Colors.END
def yellow(txt):
return Colors.YELLOW + txt + Colors.END
def red(txt):
return Colors.RED + txt + Colors.END

View File

@ -0,0 +1,7 @@
def normalize(d):
if type(d) is str:
return bytes(d, 'utf-8')
elif type(d) is list:
return [bytes(x, 'utf-8') for x in d]
else:
return d

View File

@ -0,0 +1,27 @@
import time
def getWeb3(endpoint=None):
if endpoint is None:
from web3.auto import w3
elif 'http' in endpoint:
from web3 import Web3, HTTPProvider
w3 = Web3(HTTPProvider(endpoint))
else:
from web3 import Web3, IPCProvider
from web3.middleware import geth_poa_middleware
w3 = Web3(IPCProvider(endpoint))
w3.middleware_stack.inject(geth_poa_middleware, layer=0)
# w3.eth.defaultAccount = w3.eth.accounts[0]
return w3
def waitForTransactionReceipt(w3, tx_hash):
while True:
tx_receipt = w3.eth.getTransactionReceipt(tx_hash)
if tx_receipt is not None:
break
time.sleep(1)
return tx_receipt

114
plasma_cash/demo.py Normal file
View File

@ -0,0 +1,114 @@
from time import sleep
from client.client import Client
from dependency_config import container
from utils.utils import increaseTime
alice = Client(container.get_root('alice'), container.get_token('alice'))
bob = Client(container.get_root('bob'), container.get_token('bob'))
charlie = Client(container.get_root('charlie'), container.get_token('charlie'))
authority = Client(
container.get_root('authority'), container.get_token('authority')
)
w3 = alice.root_chain.w3 # get w3 instance
# Give alice 5 tokens
alice.register()
aliceTokensStart = alice.token_contract.balance_of()
print('Alice has {} tokens'.format(aliceTokensStart))
assert aliceTokensStart == 5, "START: Alice has incorrect number of tokens"
bobTokensStart = bob.token_contract.balance_of()
print('Bob has {} tokens'.format(bobTokensStart))
assert bobTokensStart == 0, "START: Bob has incorrect number of tokens"
charlieTokensStart = charlie.token_contract.balance_of()
print('Charlie has {} tokens'.format(charlieTokensStart))
assert charlieTokensStart == 0, "START: Charlie has incorrect number of tokens"
# Alice deposits 3 of her coins to the plasma contract and gets 3 plasma nft
# utxos in return
tokenId = 1
tx_hash, gas_used = alice.deposit(tokenId)
event_data = alice.root_chain.get_event_data('Deposit', tx_hash)
print('ALICE EVENT DATA1', event_data[0]['args'])
tx_hash, gas_used = alice.deposit(tokenId + 1)
event_data = alice.root_chain.get_event_data('Deposit', tx_hash)
deposit2_utxo = event_data[0]['args']['slot']
deposit2_block_number = event_data[0]['args']['blockNumber']
print('ALICE EVENT DATA2', event_data[0]['args'])
tx_hash, gas_used = alice.deposit(tokenId + 2)
event_data = alice.root_chain.get_event_data('Deposit', tx_hash)
deposit3_utxo = event_data[0]['args']['slot']
deposit3_block_number = event_data[0]['args']['blockNumber']
print('ALICE EVENT DATA3', event_data[0]['args'])
# Check that all deposits have registered
sleep(2)
registered_deposits = alice.get_all_deposits()
assert len(registered_deposits) == 3, "Alice has incorrect number of deposits"
# Alice to Bob, and Alice to Charlie. We care about the Alice to Bob
# transaction
alice_to_bob = alice.send_transaction(
deposit3_utxo, deposit3_block_number, bob.token_contract.account.address
)
random_tx = alice.send_transaction(
deposit2_utxo,
deposit2_block_number,
charlie.token_contract.account.address,
)
plasma_block1 = authority.submit_block()
# Add an empty block in betweeen (for proof of exclusion reasons)
authority.submit_block()
# Bob to Charlie
bob_to_charlie = bob.send_transaction(
deposit3_utxo, plasma_block1, charlie.token_contract.account.address
)
# This is the info that bob is required to send to charlie. This happens on
# the P2P layer
incl_proofs, excl_proofs = bob.get_coin_history(deposit3_utxo)
# Charlie receives them, verifies the validity. If found invalid, charlie
# should not accept them and the demo fails (similar to how you shouldn't sell
# a good when you're given counterfeit currency)
assert charlie.verify_coin_history(deposit3_utxo, incl_proofs, excl_proofs)
plasma_block2 = authority.submit_block()
# Block has been submitted, now we start watching for exits of our coin
charlie.watch_exits(deposit3_utxo)
# Charlie should be able to submit an exit by referencing blocks 0 and 1 which
# included his transaction.
charlie.start_exit(deposit3_utxo, plasma_block1, plasma_block2)
# We exited the coin so we should stop watching
charlie.stop_watching_exits(deposit3_utxo)
# Here we should start watching for challenges
# After 8 days pass, charlie's exit should be finalizable
increaseTime(w3, 8 * 24 * 3600)
authority.finalize_exits()
# Charlie should now be able to withdraw the utxo which included token 2 to his
# wallet.
charlie.withdraw(deposit3_utxo)
aliceTokensEnd = alice.token_contract.balance_of()
print('Alice has {} tokens'.format(aliceTokensEnd))
assert aliceTokensEnd == 2, "END: Alice has incorrect number of tokens"
bobTokensEnd = bob.token_contract.balance_of()
print('Bob has {} tokens'.format(bobTokensEnd))
assert bobTokensEnd == 0, "END: Bob has incorrect number of tokens"
charlieTokensEnd = charlie.token_contract.balance_of()
print('Charlie has {} tokens'.format(charlieTokensEnd))
assert charlieTokensEnd == 1, "END: Charlie has incorrect number of tokens"
print('Plasma Cash with ERC721 tokens success :)')

View File

@ -0,0 +1,48 @@
from child_chain.child_chain import ChildChain
from config import plasma_config
from contract_binds.erc721 import ERC721
from contract_binds.plasma_cash import PlasmaCash
class DependencyContainer(object):
def __init__(self):
self._child_chain = None
self.root_chain_abi = '../server/build/contracts/RootChain.json'
self.token_contract_abi = '../server/build/contracts/CryptoCards.json'
self.endpoint = 'http://localhost:8545'
self.root_chain = PlasmaCash(
plasma_config['authority'],
self.root_chain_abi,
plasma_config['root_chain'],
self.endpoint,
)
def get_root(self, key, index=None):
private_key = (
plasma_config[key] if index is None else plasma_config[key][index]
)
return PlasmaCash(
private_key,
self.root_chain_abi,
plasma_config['root_chain'],
self.endpoint,
)
def get_token(self, key, index=None):
private_key = (
plasma_config[key] if index is None else plasma_config[key][index]
)
return ERC721(
private_key,
self.token_contract_abi,
plasma_config['token_contract'],
self.endpoint,
)
def get_child_chain(self):
if self._child_chain is None:
self._child_chain = ChildChain(self.root_chain)
return self._child_chain
container = DependencyContainer()

View File

@ -0,0 +1,25 @@
import rlp
from child_chain.transaction import Transaction, UnsignedTransaction
from dependency_config import container
token_contract = container.get_token('alice')
tx = Transaction(5, 0, 1, token_contract.account.address)
tx_hex = rlp.encode(tx, UnsignedTransaction).hex()
print(
'Transaction(5, 0, 1, {}): {}'.format(
token_contract.account.address, tx_hex
)
)
tx = Transaction(5, 85478557858583, 1, token_contract.account.address)
tx_hex = rlp.encode(tx, UnsignedTransaction).hex()
print(
'Transaction(5, 85478557858583, 1, {}): {}'.format(
token_contract.account.address, tx_hex
)
)
tx.sign(token_contract.account.privateKey)
print('Transaction Hash: {}'.format(tx.hash.hex()))
print('Transaction Sig: {}'.format(tx.sig.hex()))

View File

@ -0,0 +1,15 @@
Flask==1.0.2
requests==2.18.4
rlp==0.6.0
ethereum==2.3.1
# web3 fork
-e git+https://github.com/gakonst/web3.py#egg=web3
# linting
flake8==3.5.0
black==18.6b4
isort==4.3.4
# testing
pytest==3.6.0

114
plasma_cash/unit_test.py Normal file
View File

@ -0,0 +1,114 @@
import pytest
from eth_utils.crypto import keccak
from hexbytes import HexBytes
from utils.merkle.sparse_merkle_tree import SparseMerkleTree
empty_val = b'\x00' * 32
default_hash = keccak(empty_val)
dummy_val = keccak(2)
dummy_val_2 = keccak(3)
class TestSparseMerkleTree(object):
def test_size_limits(self):
with pytest.raises(SparseMerkleTree.TreeSizeExceededException):
SparseMerkleTree(depth=0, leaves={0: '0', 1: '1'})
with pytest.raises(SparseMerkleTree.TreeSizeExceededException):
SparseMerkleTree(
depth=1, leaves={0: empty_val, 1: empty_val, 2: empty_val}
)
def test_empty_SMT(self):
emptyTree = SparseMerkleTree(64, {})
assert len(emptyTree.leaves) == 0
assert (
emptyTree.root
== bytes(HexBytes('0x6f35419d1da1260bc0f33d52e8f6d73fc5d672c0dca13bb960b4ae1adec17937'))
)
def test_all_leaves_with_val(self):
leaves = {0: dummy_val, 1: dummy_val, 2: dummy_val, 3: dummy_val}
tree = SparseMerkleTree(depth=2, leaves=leaves)
mid_level_val = keccak(dummy_val * 2)
assert tree.root == keccak(mid_level_val + mid_level_val)
def test_empty_leaves(self):
tree = SparseMerkleTree(depth=2)
mid_level_val = keccak(default_hash * 2)
assert tree.root == keccak(mid_level_val * 2)
def test_empty_left_leave(self):
leaves = {1: dummy_val, 2: dummy_val, 3: dummy_val}
tree = SparseMerkleTree(depth=2, leaves=leaves)
mid_left_val = keccak(default_hash + dummy_val)
mid_right_val = keccak(dummy_val * 2)
assert tree.root == keccak(mid_left_val + mid_right_val)
def test_empty_right_leave(self):
leaves = {0: dummy_val, 2: dummy_val, 3: dummy_val}
tree = SparseMerkleTree(depth=2, leaves=leaves)
mid_left_val = keccak(dummy_val + default_hash)
mid_right_val = keccak(dummy_val * 2)
assert tree.root == keccak(mid_left_val + mid_right_val)
def test_create_merkle_proof(self):
leaves = {0: dummy_val, 2: dummy_val, 3: dummy_val_2}
tree = SparseMerkleTree(depth=2, leaves=leaves)
mid_left_val = keccak(dummy_val + default_hash)
mid_right_val = keccak(dummy_val + dummy_val_2)
assert (
tree.create_merkle_proof(0)
== (2).to_bytes(8, byteorder='big') + mid_right_val
)
assert (
tree.create_merkle_proof(1)
== (3).to_bytes(8, byteorder='big') + dummy_val + mid_right_val
)
assert (
tree.create_merkle_proof(2)
== (3).to_bytes(8, byteorder='big') + dummy_val_2 + mid_left_val
)
assert (
tree.create_merkle_proof(3)
== (3).to_bytes(8, byteorder='big') + dummy_val + mid_left_val
)
def test_old(self):
slot = 2
txHash = HexBytes(
'0xcf04ea8bb4ff94066eb84dd932f9e66d1c9f40d84d5491f5a7735200de010d84'
)
slot2 = 600
txHash2 = HexBytes(
'0xabcabcabacbc94566eb84dd932f9e66d1c9f40d84d5491f5a7735200de010d84'
)
slot3 = 30000
txHash3 = HexBytes(
'0xabcaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c9f40d84d5491f5a7735200de010d84'
)
tx = {slot: txHash, slot2: txHash2, slot3: txHash3}
tree = SparseMerkleTree(64, tx)
for s in tx.keys():
proof = tree.create_merkle_proof(s)
inc = tree.verify(s, proof)
assert inc
def test_real_slot_proofs(self):
slot = 14414645988802088183
txHash = HexBytes('0x510a183d5457e0d22951440a273f0d8e28e01d15f750d79fd1b27442299f7220')
tree = SparseMerkleTree(64, {slot: txHash})
proof = tree.create_merkle_proof(slot)
inc = tree.verify(slot, proof)
assert inc
def test_real_tree_roots(self):
slot = 14414645988802088183
txHash = HexBytes('0x4b114962ecf0d681fa416dc1a6f0255d52d701ab53433297e8962065c9d439bd')
tree = SparseMerkleTree(64, {slot: txHash})
assert tree.root == bytes(HexBytes('0x0ed6599c03641e5a20d9688f892278dbb48bbcf8b1ff2c9a0e2b7423af831a83'))
slot = 14414645988802088183
txHash = HexBytes('0x510a183d5457e0d22951440a273f0d8e28e01d15f750d79fd1b27442299f7220')
tree = SparseMerkleTree(64, {slot: txHash})
assert tree.root == bytes(HexBytes('0x8d0ae4c94eaad54df5489e5f9d62eeb4bf06ff774a00b925e8a52776256e910f'))

View File

View File

View File

@ -0,0 +1,117 @@
from collections import OrderedDict
from eth_utils.crypto import keccak
class SparseMerkleTree(object):
def __init__(self, depth=64, leaves={}):
self.depth = depth
if len(leaves) > 2 ** depth:
raise self.TreeSizeExceededException(
'tree with depth {} cannot have {} leaves'.format(
depth, len(leaves)
)
)
# Sort the transaction dict by index.
self.leaves = OrderedDict(sorted(leaves.items(), key=lambda t: t[0]))
self.default_nodes = self.create_default_nodes(self.depth)
if leaves:
self.tree = self.create_tree(
self.leaves, self.depth, self.default_nodes
)
self.root = self.tree[-1][0]
else:
self.tree = []
self.root = self.default_nodes[self.depth]
def create_default_nodes(self, depth):
# Default nodes are the nodes whose children are both empty nodes at
# each level.
default_hash = keccak(b'\x00' * 32)
default_nodes = [default_hash]
for level in range(1, depth + 1):
prev_default = default_nodes[level - 1]
default_nodes.append(keccak(prev_default * 2))
return default_nodes
def create_tree(self, ordered_leaves, depth, default_nodes):
tree = [ordered_leaves]
tree_level = ordered_leaves
for level in range(depth):
next_level = {}
for index, value in tree_level.items():
if index % 2 == 0:
co_index = index + 1
if co_index in tree_level:
next_level[index // 2] = keccak(
value + tree_level[co_index]
)
else:
next_level[index // 2] = keccak(
value + default_nodes[level]
)
else:
# If the node is a right node, check if its left sibling is
# a default node.
co_index = index - 1
if co_index not in tree_level:
next_level[index // 2] = keccak(
default_nodes[level] + value
)
tree_level = next_level
tree.append(tree_level)
return tree
def create_merkle_proof(self, uid):
# Generate a merkle proof for a leaf with provided index.
# First `depth/8` bytes of the proof are necessary for checking if
# we are at a default-node
index = uid
proof = b''
proofbits = 0
# Edge case of tree being empty
if len(self.tree) == 0:
return b'\x00\x00\x00\x00\x00\x00\x00\x00'
for level in range(self.depth):
sibling_index = index + 1 if index % 2 == 0 else index - 1
index = index // 2
if sibling_index in self.tree[level]:
proof += self.tree[level][sibling_index]
proofbits += 2 ** level
proof_bytes = proofbits.to_bytes(8, byteorder='big')
return proof_bytes + proof
def verify(self, uid, proof):
''' Checks if the proof for the leaf at `uid` is valid'''
# assert (len(proof) -8 % 32) == 0
assert len(proof) <= 2056
proofbits = int.from_bytes((proof[0:8]), byteorder='big')
index = uid
p = 8
if index in self.leaves:
computed_hash = self.leaves[index]
# in case the tx is not included, computed_hash is the default leaf
else:
computed_hash = self.default_nodes[-1]
for d in range(self.depth):
if proofbits % 2 == 0:
proof_element = self.default_nodes[d]
else:
proof_element = proof[p : p + 32]
p += 32
if index % 2 == 0:
computed_hash = keccak(computed_hash + proof_element)
else:
computed_hash = keccak(proof_element + computed_hash)
proofbits = proofbits // 2
index = index // 2
return computed_hash == self.root
class TreeSizeExceededException(Exception):
"""there are too many leaves for the tree to build"""

View File

@ -0,0 +1,27 @@
from hexbytes import HexBytes
from web3.auto import w3
from child_chain.exceptions import InvalidTxSignatureException
def sign(hash, key):
# DO NOT PREFIX!
sig = (
HexBytes('0')
+ w3.eth.account.signHash(hash, private_key=key).signature
)
return sig
def get_sender(hash, sig):
if sig is None:
raise InvalidTxSignatureException('Tx not signed')
return w3.eth.account.recoverHash(hash, signature=sig[1:])
def increaseTime(w3, time):
start = w3.eth.getBlock('latest').timestamp
# provider.make_request(method='evm_increaseTime', params=start+time)
w3.manager.request_blocking(
method='evm_increaseTime', params=[start + time]
)