Skip to content

Commit

Permalink
Merge dev squashed
Browse files Browse the repository at this point in the history
  • Loading branch information
OPReturnCode committed Sep 21, 2022
0 parents commit cbe2d57
Show file tree
Hide file tree
Showing 17 changed files with 1,694 additions and 0 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#TokenDex

A plugin for ElectronCash-SLP that allows you to trade SLP tokens with BCH (Token -> BCH and BCH -> Token) in a noncustodial manner. Everything including the order book is on the blockchain. There are no centralized servers.

##Installation
1. Download the latest release.
2. From the ElectronCash-SLP application menu select `Tools -> Installed Plugins`, then click `Add plugin` and then select the downloaded file from step 1.
3. The plugin will then be installed and enabled.

Now you should see a new tab in your wallet window.

##Brief Usage Overview

1. Select one of the tokens available in your wallet.
2. You can place a sell or buy order using the "Place Order" form.
3. You can take any of the orders from their specified sections.
4. Taking sell orders are instant but for taking the buy orders, the other party have to accept your take signal.
5. If someone signals one of your buy orders, a button will appear next to order in the "Your Orders" section.

## Support
If you had any question regarding the plugin, please feel free to drop a message in [simpleledger Telegram group](https://t.me/simpleledger).

## Support The Developer
If you wish to donate to the developer, you can use the following address: `bitcoincash:qz2q3c4svltz5x047j87g8a7gkrh03xmc5mh0lvz0j`

##Special Thanks
Very special thanks to those who helped fund the project.

##License
MIT License
129 changes: 129 additions & 0 deletions TokenDex/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/
21 changes: 21 additions & 0 deletions TokenDex/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 OPReturn

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 3 additions & 0 deletions TokenDex/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fullname = "TokenDex"
available_for = ["qt"]
description = "SLP on-chain noncustodial token swap"
114 changes: 114 additions & 0 deletions TokenDex/bfp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import hashlib

from electroncash import bitcoinfiles
from electroncash.transaction import Transaction


def upload_file(wallet, file_bytes, config={}, password=None):
file_tx_id = None
tx_batch = []

file_size = len(file_bytes)
assert file_size <= 10522

metadata = dict()
metadata['filename'] = 'data'
metadata['fileext'] = 'json'
metadata['filesize'] = file_size
metadata['file_sha256'] = hashlib.sha256(file_bytes).hexdigest()
metadata['prev_file_sha256'] = None
metadata['uri'] = None

cost = bitcoinfiles.calculateUploadCost(file_size, metadata)
file_receiver_address = wallet.get_addresses()[0] # todo change this

# TODO, guard tokens during this transaction?
#####################################################################################

file_220_chunks = []
for i in range(1, (len(file_bytes) // 220) + 2):
file_220_chunks.append(file_bytes[(i-1)*220:i*220])

funding_tx = bitcoinfiles.getFundingTxn(wallet, file_receiver_address, cost, config)
wallet.sign_transaction(funding_tx, password)
tx_batch.append(funding_tx)

prev_tx = funding_tx
for i in range(len(file_220_chunks)):
tx, is_metadata_tx = bitcoinfiles.getUploadTxn(
wallet, prev_tx=prev_tx, chunk_index=i, chunk_count=len(file_220_chunks),
chunk_data=file_220_chunks[i], config=config, metadata=metadata, file_receiver=file_receiver_address
)
wallet.sign_transaction(tx, password)
tx_batch.append(tx)
prev_tx = tx

if not is_metadata_tx: # last chunk didn't fit into the metadata tx
tx, is_metadata_tx = bitcoinfiles.getUploadTxn(
wallet, prev_tx=prev_tx, chunk_index=i+1, chunk_count=len(file_220_chunks),
chunk_data=b'', config=config, metadata=metadata, file_receiver=file_receiver_address
)
wallet.sign_transaction(tx, password)
tx_batch.append(tx)
if is_metadata_tx:
file_tx_id = tx.txid()

for tx in tx_batch:
status, tx_id = wallet.network.broadcast_transaction(tx)
assert status
return file_tx_id


def download_file(wallet, tx_id):
network = wallet.network

status, raw_metadata_tx = network.get_raw_tx_for_txid(tx_id)
assert status
metadata_tx = Transaction(raw_metadata_tx)

bitcoin_files_metadata_msg = bitcoinfiles.BfpMessage.parseBfpScriptOutput(metadata_tx.outputs()[0][1])

chunk_count = bitcoin_files_metadata_msg.op_return_fields['chunk_count']
chunk_data = bitcoin_files_metadata_msg.op_return_fields['chunk_data']
chunk_data_is_empty = chunk_data == b''

downloaded_transactions = []
assert chunk_count != 0

def get_tx_chunks(tx_id, index):
status, raw_tx = network.get_raw_tx_for_txid(tx_id)
assert status is True
tx = Transaction(raw_tx)
try:
data = bitcoinfiles.parseOpreturnToChunks(
tx.outputs()[0][1].to_script(), allow_op_0=False, allow_op_number=False
)
except bitcoinfiles.BfpOpreturnError: # It's the funding tx probably
return
downloaded_transactions.append(
{'tx_id': metadata_tx.txid(),
'data': data[0]
}
)
index += 1
if index <= chunk_count - 1: # TODO removed <= to <
get_tx_chunks(tx.inputs()[0]['prevout_hash'], index)

if chunk_count == 1:
if not chunk_data_is_empty:
downloaded_transactions.append({'tx_id': metadata_tx.txid(), 'data': chunk_data})
# DONE! FINISHED!
if chunk_count > 1 or (chunk_count == 1 and chunk_data_is_empty):
if not chunk_data_is_empty:
downloaded_transactions.append({'tx_id': metadata_tx.txid(), 'data': chunk_data})
index = 0
get_tx_chunks(metadata_tx.inputs()[0]['prevout_hash'], index)

f = b''
downloaded_transactions.reverse()
for element in downloaded_transactions:
f += element['data']
assert hashlib.sha256(f).hexdigest() == bitcoin_files_metadata_msg.op_return_fields['file_sha256'].hex()
return f


Loading

0 comments on commit cbe2d57

Please sign in to comment.