zbxcat/xcat/cli.py

234 lines
8.9 KiB
Python
Raw Normal View History

import argparse, textwrap
2017-07-28 17:23:32 -07:00
from xcat.utils import *
2017-07-28 20:45:46 -07:00
import xcat.db as db
2017-07-31 13:51:54 -07:00
import xcat.userInput as userInput
2017-07-28 17:23:32 -07:00
from xcat.trades import *
from xcat.protocol import *
import subprocess
2017-07-28 17:23:32 -07:00
def save_state(trade, tradeid):
2017-07-26 13:23:12 -07:00
save(trade)
2017-07-28 17:23:32 -07:00
db.create(trade, tradeid)
2017-07-31 15:15:22 -07:00
def checkSellStatus(tradeid):
trade = db.get(tradeid)
status = seller_check_status(trade)
print("In checkSellStatus", status)
2017-08-02 18:06:09 -07:00
if status == 'init':
userInput.authorize_fund_sell(trade)
fund_tx = fund_sell_contract(trade)
print("Sent fund_tx", fund_tx)
trade.sell.fund_tx = fund_tx
save_state(trade, tradeid)
elif status == 'buyerFunded':
2017-08-02 18:06:09 -07:00
secret = db.get_secret(tradeid)
2017-07-26 13:23:12 -07:00
print("SECRET found in checksellactions", secret)
txs = seller_redeem_p2sh(trade, secret)
print("TXS IN SELLER REDEEM BUYER TX", txs)
trade.buy.redeem_tx = txs['redeem_tx']
2017-07-26 13:23:12 -07:00
print("TRADE SUCCESSFULLY REDEEMED", trade)
2017-07-31 15:15:22 -07:00
save_state(trade, tradeid)
2017-08-02 18:45:36 -07:00
# Remove from db? Or just from temporary file storage
cleanup(tradeid)
elif status == 'sellerFunded':
print("Buyer has not yet funded the contract where you offered to buy {0}, please wait for them to complete their part.".format(trade.buy.currency))
# elif trade.buy.get_status() == 'redeemed':
elif status == 'sellerRedeemed':
2017-07-26 13:23:12 -07:00
print("You have already redeemed the p2sh on the second chain of this trade.")
def buyer_check_status(trade):
sellState = check_fund_status(trade.sell.currency, trade.sell.p2sh)
buyState = check_fund_status(trade.buy.currency, trade.buy.p2sh)
if sellState == 'funded' and buyState == 'empty':
return 'sellerFunded' # step1
# TODO: Find funding txid. How does buyer get seller redeemed tx?
elif sellState == 'funded' and hasattr(trade.buy, 'fund_tx'):
return 'sellerRedeemed' # step3
elif sellState == 'funded' and buyState == 'funded':
return 'buyerFunded' # step2
elif sellState == 'empty' and buyState == 'empty':
2017-08-02 18:06:09 -07:00
if hasattr(trade.sell, 'redeem_tx'):
return 'buyerRedeemed' # step4
else:
return 'init'
def seller_check_status(trade):
sellState = check_fund_status(trade.sell.currency, trade.sell.p2sh)
buyState = check_fund_status(trade.buy.currency, trade.buy.p2sh)
if sellState == 'funded' and buyState == 'empty':
return 'sellerFunded' # step1
elif sellState == 'funded' and hasattr(trade.buy, 'redeem_tx'):
return 'sellerRedeemed' # step3
# TODO: How does seller get buyer funded tx?
elif sellState == 'funded' and buyState == 'funded':
return 'buyerFunded' # step2
elif sellState == 'empty' and buyState == 'empty':
if hasattr(trade.buy, 'redeem_tx'):
return 'buyerRedeemed' # step4
else:
2017-08-02 18:06:09 -07:00
return 'init' # step0
2017-07-31 15:15:22 -07:00
def checkBuyStatus(tradeid):
trade = db.get(tradeid)
status = buyer_check_status(trade)
print("In checkBuyStatus", status)
2017-08-02 18:06:09 -07:00
if status == 'init':
print("Trade has not yet started, waiting for seller to fund the sell p2sh.")
elif status == 'buyerRedeemed':
2017-07-31 16:25:49 -07:00
print("This trade is complete, both sides redeemed.")
elif status == 'sellerFunded':
print("One active trade available, fulfilling buyer contract...")
2017-07-28 13:57:44 -07:00
print("Trade commitment", trade.commitment)
2017-08-02 18:45:36 -07:00
# if verify_p2sh(trade):
2017-07-31 16:25:49 -07:00
fund_tx = fund_contract(trade.buy)
2017-08-02 18:45:36 -07:00
print("\nBuyer's funding tx: ", fund_tx)
2017-07-31 16:25:49 -07:00
trade.buy.fund_tx = fund_tx
save_state(trade, tradeid)
elif status == 'sellerRedeemed':
print("FUND TX CLI", trade.buy.fund_tx)
secret = find_secret_from_fundtx(trade.buy.currency, trade.buy.p2sh, trade.buy.fund_tx)
print("Secret in cli", secret)
2017-07-31 19:13:46 -07:00
if secret != None:
print("Found secret", secret)
txs = redeem_p2sh(trade.sell, secret)
print("TXS IN SELLER REDEEMED", txs)
trade.sell.redeem_tx = txs['redeem_tx']
print("TXID after buyer redeem", trade.sell.redeem_tx)
save_state(trade, tradeid)
2017-07-31 19:13:46 -07:00
print("XCAT trade complete!")
else:
print("Secret not found in redeemtx")
2017-07-28 17:23:32 -07:00
# Import a trade in hex, and save to db
def importtrade(tradeid, hexstr=''):
2017-07-28 20:45:46 -07:00
trade = x2s(hexstr)
2017-07-31 16:25:49 -07:00
trade = db.instantiate(trade)
import_addrs(trade)
2017-07-31 19:13:46 -07:00
print(trade.toJSON())
2017-07-31 17:06:58 -07:00
save_state(trade, tradeid)
2017-07-28 17:23:32 -07:00
def wormhole_importtrade():
res = subprocess.call('wormhole receive', shell=True)
if res == 0:
tradeid = input("Enter filename of received trade data to import (printed on line above): ")
with open(tradeid) as infile:
hexstr = infile.readline().strip()
importtrade(tradeid, hexstr)
print("Successfully imported trade using magic-wormhole")
os.remove(tradeid)
else:
print("Importing trade using magic-wormhole failed.")
2017-07-28 17:23:32 -07:00
# Export a trade by its tradeid
def exporttrade(tradeid, wormhole=False):
2017-07-28 17:23:32 -07:00
trade = db.get(tradeid)
2017-07-31 17:06:58 -07:00
hexstr = s2x(trade.toJSON())
if wormhole:
2017-08-02 18:06:09 -07:00
tradefile = os.path.join(ROOT_DIR, '.tmp/{0}'.format(tradeid))
print(tradefile)
with open(tradefile, '+w') as outfile:
outfile.write(hexstr)
print("Exporting trade to buyer using magic wormhole.")
2017-08-02 18:06:09 -07:00
subprocess.call('wormhole send {0}'.format(tradefile), shell=True)
else:
print(hexstr)
return hexstr
2017-07-31 13:32:51 -07:00
2017-07-31 16:25:49 -07:00
def findtrade(tradeid):
trade = db.get(tradeid)
2017-07-31 19:13:46 -07:00
print(trade.toJSON())
2017-07-31 17:06:58 -07:00
return trade
2017-07-28 17:23:32 -07:00
2017-07-31 16:25:49 -07:00
def checktrade(tradeid):
print("In checktrade")
trade = db.get(tradeid)
if find_role(trade.sell) == 'test':
input("Is this a test? Both buyer and seller addresses are yours, press 'enter' to test.")
checkBuyStatus(tradeid)
checkSellStatus(tradeid)
checkBuyStatus(tradeid)
elif find_role(trade.sell) == 'initiator':
print("You are the seller in this trade.")
role = 'seller'
checkSellStatus(tradeid)
else:
print("You are the buyer in this trade.")
role = 'buyer'
checkBuyStatus(tradeid)
2017-07-28 17:23:32 -07:00
def newtrade(tradeid):
erase_trade()
role = 'seller'
print("Creating new XCAT trade...")
2017-08-02 18:06:09 -07:00
trade = seller_init(tradeid)
print("Use 'xcat exporttrade <tradeid> to export the trade and sent to the buyer.'")
2017-07-28 17:23:32 -07:00
save_state(trade, tradeid)
def main():
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
description=textwrap.dedent('''\
== Trades ==
2017-07-31 16:25:49 -07:00
newtrade "tradeid" - create a new trade
checktrade "tradeid"- check for actions to be taken on an existing trade
2017-07-31 13:32:51 -07:00
importtrade "hexstr" - import an existing trade from a hex string
2017-07-31 16:25:49 -07:00
exporttrade "tradeid" - export the data of an existing trade as a hex string. Takes the tradeid as an argument
findtrade "tradeid" - find a trade by the tradeid
'''))
parser.add_argument("command", action="store", help="list commands")
parser.add_argument("arguments", action="store", nargs="*", help="add arguments")
parser.add_argument("-w", "--wormhole", action="store_true", help="Transfer trade data through magic-wormhole")
# parser.add_argument("--daemon", "-d", action="store_true", help="Run as daemon process")
2017-07-28 17:23:32 -07:00
# TODO: function to view available trades
# TODO: function to tell if tradeid already exists for newtrade
args = parser.parse_args()
# how to hold state of role
command = args.command
if command == 'importtrade':
if args.wormhole:
wormhole_importtrade()
else:
2017-08-02 18:06:09 -07:00
if len(args.arguments) != 2:
print("Usage: importtrade [tradeid] [hexstring]")
exit()
2017-08-02 18:06:09 -07:00
tradeid = args.arguments[0]
hexstr = args.arguments[1]
importtrade(tradeid, hexstr)
elif command == 'exporttrade':
2017-08-02 18:06:09 -07:00
tradeid = args.arguments[0]
exporttrade(tradeid, args.wormhole)
2017-07-31 13:32:51 -07:00
elif command == "findtrade":
print("Finding trade")
2017-08-02 18:06:09 -07:00
key = args.arguments[0]
2017-07-31 15:27:43 -07:00
findtrade(key)
2017-07-31 16:25:49 -07:00
elif command == 'checktrade':
2017-08-02 18:06:09 -07:00
tradeid = args.arguments[0]
2017-07-31 16:25:49 -07:00
checktrade(tradeid)
elif command == 'newtrade':
2017-07-31 13:51:54 -07:00
print("in new trade")
2017-07-28 17:23:32 -07:00
try:
2017-08-02 18:06:09 -07:00
tradeid = args.arguments[0]
2017-07-28 17:23:32 -07:00
newtrade(tradeid)
except:
tradeid = userInput.enter_trade_id()
newtrade(tradeid)
elif command == "daemon":
#TODO: implement
print("Run as daemon process")
2017-07-31 15:27:43 -07:00
# Ad hoc testing of workflow starts here
elif command == "step1":
2017-08-02 18:06:09 -07:00
tradeid = args.arguments[0]
checkSellStatus(tradeid)
2017-07-26 13:23:12 -07:00
elif command == "step2":
2017-07-31 14:01:20 -07:00
# trade = get_trade()
2017-08-02 18:06:09 -07:00
tradeid = args.arguments[0]
2017-07-31 15:15:22 -07:00
checkBuyStatus(tradeid)
2017-07-26 13:23:12 -07:00
elif command == "step3":
2017-08-02 18:06:09 -07:00
tradeid = args.arguments[0]
2017-07-31 15:15:22 -07:00
checkSellStatus(tradeid)
# TODO: When trade finishes, delete wormhole file in tmp dir.
2017-07-26 13:23:12 -07:00
elif command == "step4":
2017-08-02 18:06:09 -07:00
tradeid = args.arguments[0]
2017-07-31 15:15:22 -07:00
checkBuyStatus(tradeid)