diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp index b2fa534a1..3c5cfe4d6 100644 --- a/src/bitcoind.cpp +++ b/src/bitcoind.cpp @@ -59,13 +59,16 @@ static bool fDaemon; #include "komodo_defs.h" #define KOMODO_ASSETCHAIN_MAXLEN 65 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; +extern uint32_t ASSETCHAINS_BLOCKTIME; +extern uint64_t ASSETCHAINS_CBOPRET; void komodo_passport_iteration(); uint64_t komodo_interestsum(); int32_t komodo_longestchain(); +void komodo_cbopretupdate(); void WaitForShutdown(boost::thread_group* threadGroup) { - bool fShutdown = ShutdownRequested(); + int32_t i; bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { @@ -73,13 +76,27 @@ void WaitForShutdown(boost::thread_group* threadGroup) if ( ASSETCHAINS_SYMBOL[0] == 0 ) { komodo_passport_iteration(); - MilliSleep(10000); + for (i=0; i<10; i++) + { + fShutdown = ShutdownRequested(); + if ( fShutdown != 0 ) + break; + MilliSleep(1000); + } } else { //komodo_interestsum(); //komodo_longestchain(); - MilliSleep(20000); + if ( ASSETCHAINS_CBOPRET != 0 ) + komodo_cbopretupdate(); + for (i=0; i> 32); + uprice = (uint32_t)pricebits; + bar->sum += uprice, bar->num++; + if ( bar->open == 0 ) + bar->open = bar->high = bar->low = pricebits; + if ( uprice > (uint32_t)bar->high ) + bar->high = pricebits; + else if ( uprice < (uint32_t)bar->low ) + bar->low = pricebits; + bar->close = pricebits; + return(0); +} + +int64_t prices_bardist(struct prices_bar *bar,uint32_t aveprice,uint64_t pricebits) +{ + int64_t a,dist = 0; + if ( aveprice != 0 ) + { + a = (pricebits & 0xffffffff); + dist = (a - aveprice); + dist *= dist; + //fprintf(stderr,"dist.%lld (u %u - ave %u) %d\n",(long long)dist,uprice,aveprice,uprice-aveprice); + } + return(dist); +} + +void prices_bardisp(struct prices_bar *bar) +{ + if ( bar->num == 0 ) + fprintf(stderr,"BAR null\n"); + else fprintf(stderr,"BAR ave %.4f (O %.4f, H %.4f, L %.4f, C %.4f)\n",bstr(bar->sum/bar->num),bstr(bar->open),bstr(bar->high),bstr(bar->low),bstr(bar->close)); +} int64_t prices_blockinfo(int32_t height,char *acaddr) { - std::vector vopret; CBlockIndex *pindex; CBlock block; CTransaction tx,vintx; uint64_t pricebits; char destaddr[64]; uint32_t timestamp,uprice; uint256 hashBlock; int64_t prizefund = 0; int32_t i,n,vini,numvouts; + std::vector vopret; CBlockIndex *pindex; CBlock block; CTransaction tx,vintx; uint64_t pricebits; char destaddr[64]; uint32_t aveprice=0,timestamp,uprice; uint256 hashBlock; int64_t dist,mindist=(1LL<<60),prizefund = 0; int32_t mini=-1,i,n,vini,numvouts,iter; struct prices_bar refbar; if ( (pindex= komodo_chainactive(height)) != 0 ) { if ( komodo_blockload(block,pindex) == 0 ) { n = block.vtx.size(); vini = 0; - for (i=0; i= vintx.vout.size() || Getscriptaddress(destaddr,vintx.vout[tx.vin[vini].prevout.n].scriptPubKey) == 0 ) - continue; - else if ( (numvouts= tx.vout.size()) > 1 && tx.vout[numvouts-1].scriptPubKey[0] == 0x6a ) + for (i=0; i= vintx.vout.size() || Getscriptaddress(destaddr,vintx.vout[tx.vin[vini].prevout.n].scriptPubKey) == 0 ) + continue; + else if ( (numvouts= tx.vout.size()) > 1 && tx.vout[numvouts-1].scriptPubKey[0] == 0x6a ) { - E_UNMARSHAL(vopret,ss >> pricebits); - timestamp = (uint32_t)(pricebits >> 32); - uprice = (uint32_t)pricebits; - if ( strcmp(acaddr,destaddr) == 0 ) - fprintf(stderr,"REF "); - fprintf(stderr,"[%02x] i.%d %.8f %llx t%u %.4f numvouts.%d %s lag.%d\n",tx.vout[numvouts-1].scriptPubKey[0],i,(double)tx.vout[0].nValue/COIN,(long long)pricebits,timestamp,(double)uprice/10000,numvouts,destaddr,(int32_t)(pindex->nTime-timestamp)); - } else return(-3); + GetOpReturnData(tx.vout[numvouts-1].scriptPubKey,vopret); + if ( vopret.size() == 8 ) + { + E_UNMARSHAL(vopret,ss >> pricebits); + timestamp = (uint32_t)(pricebits >> 32); + uprice = (uint32_t)pricebits; + if ( iter == 0 ) + { + prizefund += tx.vout[0].nValue; + if ( strcmp(acaddr,destaddr) == 0 ) + { + //fprintf(stderr,"REF "); + prices_barupdate(&refbar,pricebits); + } + } + else if ( strcmp(acaddr,destaddr) != 0 ) + { + dist = prices_bardist(&refbar,aveprice,pricebits); + if ( dist < mindist ) + { + mindist = dist; + mini = i; + } + fprintf(stderr,"mini.%d i.%d %.8f t%u %.4f v.%d %s lag.%d i.%d dist.%lld\n",mini,i,(double)tx.vout[0].nValue/COIN,timestamp,(double)uprice/10000,numvouts,destaddr,(int32_t)(pindex->nTime-timestamp),iter,(long long)dist); + } + } else return(-3); + } + } + if ( iter == 0 ) + { + prices_bardisp(&refbar); + if ( refbar.num != 0 ) + aveprice = (uint32_t)refbar.sum / refbar.num; } } return(prizefund); diff --git a/src/gui/komodoku/README.md b/src/gui/komodoku/README.md new file mode 100644 index 000000000..8a3778ea0 --- /dev/null +++ b/src/gui/komodoku/README.md @@ -0,0 +1,27 @@ +About +----- +Komodo SudokuCC GUI + +Just solve Sudoku and earn SUDOKU coins! + +![alt text](https://i.imgur.com/std99XW.png) + +To run you need up and running SUDOKU chain daemon built from latest https://github.com/jl777/komodo/tree/FSM and started with valid for your wallet pubkey in `-pubkey=` param. + +SUDOKU chain params: +```./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc &``` + +1) install dependencies: + +``` +$ sudo apt-get install python-pygame libgnutls28-dev +$ pip install requests wheel slick-bitcoinrpc pygame +``` + +2) and then start: + +``` +$ git clone https://github.com/tonymorony/Komodoku +$ cd Komodoku +$ python Sudoku.py +``` diff --git a/src/gui/komodoku/Roboto-Light.ttf b/src/gui/komodoku/Roboto-Light.ttf new file mode 100755 index 000000000..664e1b2f9 Binary files /dev/null and b/src/gui/komodoku/Roboto-Light.ttf differ diff --git a/src/gui/komodoku/Sudoku.py b/src/gui/komodoku/Sudoku.py new file mode 100644 index 000000000..7b46d93fc --- /dev/null +++ b/src/gui/komodoku/Sudoku.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python + +# Copyright (C) 2010 Paul Bourke +# Copyright (C) 2019 Anton Lysakov +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import pygame +import sys +import random +import sudoku_kmdlib +import time + +class PyGameBoard(): + """Represents the game's frontend using pygame""" + + def __init__(self, engine, windowSize, gridValues, timestampValues): + pygame.init() + pygame.display.set_caption('Sudoku') + self.__engine = engine + self.__gridValues = gridValues + self.__timestampValues = timestampValues + self.__screen = pygame.display.set_mode(windowSize) + background = pygame.image.load(sys.path[0] + '/background.png').convert() + board = pygame.image.load(sys.path[0] + '/board.png') + boardX = boardY = 10 + self.__screen.blit(background, (0, 0)) + self.__screen.blit(board, (boardX, boardY)) + self.__tiles = self.__createTiles(boardX, boardY) + self.__drawUI() + self.__draw() + + def __draw(self): + """Handles events and updates display buffer""" + while True: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + sys.exit() + elif event.type == pygame.MOUSEBUTTONUP and event.button == 1: + self.__handleMouse(event.pos) + elif (event.type == pygame.KEYUP): + self.__handleKeyboard(event.key) + pygame.display.flip() + + def __drawUI(self): + '''Draws the text buttons along the right panel''' + font = pygame.font.Font(sys.path[0] + '/Roboto-Light.ttf', 28) + font.set_underline(True) + self.__titleText = font.render('Sudoku', 1, (0, 0, 0)) + self.__titleTextRect = self.__titleText.get_rect() + self.__titleTextRect.centerx = 445 + self.__titleTextRect.centery = 30 + self.__screen.blit(self.__titleText, self.__titleTextRect) + + font = pygame.font.Font(sys.path[0] + '/Roboto-Light.ttf', 14) + self.__titleText = font.render('TonyL 2019', 1, (0, 0, 0)) + self.__titleTextRect = self.__titleText.get_rect() + self.__titleTextRect.centerx = 445 + self.__titleTextRect.centery = 55 + self.__screen.blit(self.__titleText, self.__titleTextRect) + + font = pygame.font.Font(sys.path[0] + '/Roboto-Light.ttf', 24) + self.__newGameText = font.render('-New Game-', 1, (0, 0, 0)) + self.__newGameTextRect = self.__newGameText.get_rect() + self.__newGameTextRect.centerx = 495 + self.__newGameTextRect.centery = 180 + self.__screen.blit(self.__newGameText, self.__newGameTextRect) + + self.__solveText = font.render('-Check Balance-', 1, (0, 0, 0)) + self.__solveTextRect = self.__solveText.get_rect() + self.__solveTextRect.centerx = 495 + self.__solveTextRect.centery = 220 + self.__screen.blit(self.__solveText, self.__solveTextRect) + + font = pygame.font.Font(sys.path[0] + '/Roboto-Light.ttf', 24) + self.__checkText = font.render('-Check Solution-', 1, (0, 0, 0)) + self.__checkTextRect = self.__checkText.get_rect() + self.__checkTextRect.centerx = 495 + self.__checkTextRect.centery = 260 + self.__screen.blit(self.__checkText, self.__checkTextRect) + + def __handleKeyboard(self, key): + """Get key pressed and update the game board""" + validKeys = {pygame.K_0: "0", pygame.K_1: "1", pygame.K_2: "2", + pygame.K_3: "3", pygame.K_4: "4", pygame.K_5: "5", + pygame.K_6: "6", pygame.K_7: "7", pygame.K_8: "8", + pygame.K_9: "9", pygame.K_BACKSPACE: "", pygame.K_DELETE: ""} + if key == pygame.K_ESCAPE: + sys.exit() + elif key in validKeys: + i = self.__currentTile.getGridLoc()[0] + j = self.__currentTile.getGridLoc()[1] + cell_num = 9 * i + (j + 1) + self.__currentTile.setFontColor(pygame.color.THECOLORS['blue']) + self.__currentTile.updateValue(validKeys[key]) + self.__gridValues[i][j] = self.__currentTile.getValue() + self.__timestampValues[cell_num] = int(round(time.time())) + + def __handleMouse(self, (x, y)): + for row in self.__tiles: + for tile in row: + if tile.getRect().collidepoint(x, y): + if not tile.isReadOnly(): + tile.highlight(pygame.color.THECOLORS['lightyellow']) + if self.__currentTile.isCorrect(): + self.__currentTile.unhighlight() + else: + self.__currentTile.highlight((255, 164, 164)) + self.__currentTile = tile + if self.__newGameTextRect.collidepoint(x, y): + self.__engine.startNewGame() + elif self.__solveTextRect.collidepoint(x, y): + self.__engine.getSolution() + elif self.__checkTextRect.collidepoint(x, y): + ret = self.__engine.checkSolution(self.__gridValues, self.__timestampValues) + + def __updateBoard(self, gridValues): + for i in range(9): + for j in range(9): + self.__tiles[i][j].updateValue(gridValues[i][j]) + + def __unhightlightBoard(self): + for i in range(9): + for j in range(9): + self.__tiles[i][j].unhighlight() + + def __createTiles(self, initX=0, initY=0): + """Set up a list of tiles corresponding to the grid, along with + each ones location coordinates on the board""" + square_size = 40 + tiles = list() + x = y = 0 + for i in range(0, 9): + row = list() + for j in range(0, 9): + if j in (0, 1, 2): + x = (j * 41) + (initX + 2) + if j in (3, 4, 5): + x = (j * 41) + (initX + 6) + if j in (6, 7, 8): + x = (j * 41) + (initX + 10) + if i in (0, 1, 2): + y = (i * 41) + (initY + 2) + if i in (3, 4, 5): + y = (i * 41) + (initY + 6) + if i in (6, 7, 8): + y = (i * 41) + (initY + 10) + tile = Tile(self.__gridValues[i][j], (x, y), (i, j), square_size) + row.append(tile) + tiles.append(row) + self.__currentTile = tiles[0][0] + return tiles + + +class Tile(): + """Represents a graphical tile on the board""" + + def __init__(self, value, coords, gridLoc, size): + xpos = coords[0] + ypos = coords[1] + self.__fontColor = pygame.color.THECOLORS["black"] + self.__readOnly = False + self.__colorSquare = pygame.Surface((size, size)).convert() + self.__colorSquare.fill(pygame.color.THECOLORS['white'], None, pygame.BLEND_RGB_ADD) + self.__colorSquareRect = self.__colorSquare.get_rect() + self.__colorSquareRect = self.__colorSquareRect.move(xpos + 1, ypos + 1) + self.__value = value + self.__gridLoc = gridLoc + self.__screen = pygame.display.get_surface() + self.__rect = pygame.Rect(xpos, ypos, size, size) + self.__isCorrect = True + if self.__value is not '-': + self.__readOnly = True + self.__draw() + + def updateValue(self, value): + self.__value = value + self.__draw() + + def isCorrect(self): + return self.__isCorrect + + def setCorrect(self, isCorrect): + self.__isCorrect = isCorrect + + def setFontColor(self, fontColor): + self.__fontColor = fontColor + + def getValue(self): + return self.__value + + def getRect(self): + return self.__rect + + def getGridLoc(self): + return self.__gridLoc + + def isReadOnly(self): + return self.__readOnly + + def highlight(self, color): + if self.__readOnly is True: + return + self.__colorSquare.fill(color) + self.__draw() + + def unhighlight(self): + self.__colorSquare.fill((255, 225, 255), None, pygame.BLEND_RGB_ADD) + self.__draw() + + def __draw(self): + value = self.__value + if self.__value == '-': + value = '' + font = pygame.font.Font(sys.path[0] + '/Roboto-Light.ttf', 24) + text = font.render(str(value), 1, self.__fontColor) + textpos = text.get_rect() + textpos.centerx = self.__rect.centerx + textpos.centery = self.__rect.centery + self.__screen.blit(self.__colorSquare, self.__colorSquareRect) + self.__screen.blit(text, textpos) + + +class Sudoku: + """Represents the game's backend and logic""" + + def __init__(self, puzzleFile, rpc_connection): + self.__puzzleFile = puzzleFile + self.__rpc_connection = rpc_connection + self.startNewGame() + + def startNewGame(self): + self.__linePuzzle = self.__loadPuzzle(self.__puzzleFile) + gridValues = self.lineToGrid(self.__linePuzzle) + # prefill 0 timestamps for already known numbers + timestampValues = self.prefill_timestamps(gridValues) + board = PyGameBoard(self, (600, 400), gridValues, timestampValues) + board.setValues(gridValues) + + def __loadPuzzle(self, listName): + self.__chosen_puzzle = random.choice(listName) + puzzle = self.__rpc_connection.cclib("txidinfo", "17", '"%22' + self.__chosen_puzzle + '%22"')["unsolved"] + print "Puzzle ID: " + self.__chosen_puzzle + print "Reward amount: " + str(self.__rpc_connection.cclib("txidinfo", "17", '"%22' + self.__chosen_puzzle + '%22"')["amount"]) + ret = [] + linePuzzle = str(puzzle) + for i in linePuzzle: + ret.append(i) + return ret + + def gridToLine(self, grid): + linePuzzle = '' + for i in range(9): + for j in range(9): + linePuzzle += grid[i][j] + return linePuzzle + + def lineToGrid(self, linePuzzle): + assert (len(linePuzzle) == 81) + grid = [] + for i in xrange(0, 81, 9): + grid.append(linePuzzle[i:i + 9]) + return grid + + def getSolution(self): + balance = self.__rpc_connection.cclibaddress("17")["mybalance"] + print "Your balance: " + str(balance) + + def __solve(self, linePuzzle): + linePuzzle = ''.join(linePuzzle) + i = linePuzzle.find('-') + if i == -1: + return linePuzzle + + excluded_numbers = set() + for j in range(81): + if self.sameRow(i, j) or self.sameCol(i, j) or self.sameBlock(i, j): + excluded_numbers.add(linePuzzle[j]) + + for m in '123456789': + if m not in excluded_numbers: + funcRet = self.__solve(linePuzzle[:i] + m + linePuzzle[i + 1:]) + if funcRet is not None: + return funcRet + + def prefill_timestamps(self, grid): + timestamps = {} + for i in range(9): + for j in range(9): + if grid[i][j] != '-': + cell_num = 9 * i + ( j + 1 ) + timestamps[cell_num] = 0 + return timestamps + + def sameRow(self, i, j): + return (i / 9 == j / 9) + + def sameCol(self, i, j): + return (i - j) % 9 == 0 + + def sameBlock(self, i, j): + return (i / 27 == j / 27 and i % 9 / 3 == j % 9 / 3) + + def checkSolution(self, attemptGrid, timestampValues): + # [%22%22,%22%22,t0,t1,t2,...] + attemptLine = self.gridToLine(attemptGrid) + + #print attemptLine + #print timestampValues + timestampsline = "" + for timestamp in timestampValues.values(): + timestampsline += "," + timestampsline += str(timestamp) + arg_line = "[%22"+self.__chosen_puzzle+"%22,%22"+attemptLine+"%22"+timestampsline+"]" + print arg_line + try: + solution_info = self.__rpc_connection.cclib("solution", "17", '"' + arg_line + '"') + print solution_info + solution_txid = self.__rpc_connection.sendrawtransaction(solution_info["hex"]) + print "Solution accepted!" + print solution_txid + except Exception as e: + print(e) + print(solution_info) + solution_txid = 'error' + return solution_txid + +def main(): + while True: + # Assetchain hardcoded here + chain = 'SUDOKU' + try: + print 'Welcome to the Komodo SudokuCC' + rpc_connection = sudoku_kmdlib.def_credentials(chain) + pending_puzzles = rpc_connection.cclib("pending", "17")["pending"] + puzzle_list = [] + for puzzle in pending_puzzles: + puzzle_list.append(puzzle["txid"]) + + except Exception as e: + #print rpc_connection + print e + print 'Cant connect to SUDOKU Daemon! Please re-check if it up' + sys.exit() + else: + print 'Succesfully connected!\n' + break + newGame = Sudoku(puzzle_list, rpc_connection) + +if __name__ == '__main__': + main() diff --git a/src/gui/komodoku/background.png b/src/gui/komodoku/background.png new file mode 100644 index 000000000..dc4844a0b Binary files /dev/null and b/src/gui/komodoku/background.png differ diff --git a/src/gui/komodoku/board.png b/src/gui/komodoku/board.png new file mode 100644 index 000000000..bd77ca419 Binary files /dev/null and b/src/gui/komodoku/board.png differ diff --git a/src/gui/komodoku/sudoku_kmdlib.py b/src/gui/komodoku/sudoku_kmdlib.py new file mode 100644 index 000000000..a2b2aa239 --- /dev/null +++ b/src/gui/komodoku/sudoku_kmdlib.py @@ -0,0 +1,41 @@ +import platform +import os +import re +import random +from slickrpc import Proxy + + +# define function that fetchs rpc creds from .conf +def def_credentials(chain): + rpcport =''; + operating_system = platform.system() + if operating_system == 'Darwin': + ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' + elif operating_system == 'Linux': + ac_dir = os.environ['HOME'] + '/.komodo' + elif operating_system == 'Windows': + ac_dir = '%s/komodo/' % os.environ['APPDATA'] + if chain == 'KMD': + coin_config_file = str(ac_dir + '/komodo.conf') + else: + coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + with open(coin_config_file, 'r') as f: + for line in f: + l = line.rstrip() + if re.search('rpcuser', l): + rpcuser = l.replace('rpcuser=', '') + elif re.search('rpcpassword', l): + rpcpassword = l.replace('rpcpassword=', '') + elif re.search('rpcport', l): + rpcport = l.replace('rpcport=', '') + if len(rpcport) == 0: + if chain == 'KMD': + rpcport = 7771 + else: + print("rpcport not in conf file, exiting") + print("check "+coin_config_file) + exit(1) + + return(Proxy("http://%s:%s@127.0.0.1:%d"%(rpcuser, rpcpassword, int(rpcport)))) + + diff --git a/src/komodo_defs.h b/src/komodo_defs.h index 23f291a20..0f053f6ca 100644 --- a/src/komodo_defs.h +++ b/src/komodo_defs.h @@ -50,7 +50,7 @@ extern uint64_t ASSETCHAINS_TIMELOCKGTE; extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_VERUSHASH,ASSETCHAINS_EQUIHASH,KOMODO_INITDONE; extern int32_t KOMODO_MININGTHREADS,KOMODO_LONGESTCHAIN,ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,KOMODO_ON_DEMAND,KOMODO_PASSPORT_INITDONE,ASSETCHAINS_STAKED; -extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_LASTERA; +extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_LASTERA,ASSETCHAINS_CBOPRET; extern bool VERUS_MINTBLOCKS; extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_NOTARY_PAY[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[]; extern const char *ASSETCHAINS_ALGORITHMS[]; diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 36409e67d..6a9afd473 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -1547,3 +1547,228 @@ void komodo_passport_iteration() printf("READY for %s RPC calls at %u! done PASSPORT %s refid.%d\n",ASSETCHAINS_SYMBOL,(uint32_t)time(NULL),ASSETCHAINS_SYMBOL,refid); } } + +extern std::vector Mineropret; // opreturn data set by the data gathering code +#define PRICES_MAXCHANGE (COIN / 100) // maximum acceptable change, set at 1% +#define PRICES_SIZEBIT0 (sizeof(uint32_t) * 4) // 4 uint32_t unixtimestamp, BTCUSD, BTCGBP and BTCEUR + +// komodo_heightpricebits() extracts the price data in the coinbase for nHeight +int32_t komodo_heightpricebits(uint32_t prevbits[4],int32_t nHeight) +{ + CBlockIndex *pindex; CBlock block; CTransaction tx; int32_t numvouts; std::vector vopret; + if ( (pindex= komodo_chainactive(nHeight)) != 0 ) + { + if ( komodo_blockload(block,pindex) == 0 ) + { + tx = block.vtx[0]; + numvouts = (int32_t)tx.vout.size(); + GetOpReturnData(tx.vout[numvouts-1].scriptPubKey,vopret); + if ( vopret.size() >= PRICES_SIZEBIT0 ) + { + memcpy(prevbits,&vopret[0],PRICES_SIZEBIT0); + return(0); + } + } + } + fprintf(stderr,"couldnt get pricebits for %d\n",nHeight); + return(-1); +} + +/* + komodo_pricenew() is passed in a reference price, the change tolerance and the proposed price. it needs to return a clipped price if it is too big and also set a flag if it is at or above the limit + */ +uint32_t komodo_pricenew(int32_t *maxflagp,uint32_t price,uint32_t refprice,int64_t tolerance) +{ + uint32_t highprice,lowprice; + highprice = ((uint64_t)refprice * (COIN + tolerance)) / COIN; // calc highest acceptable price + lowprice = ((uint64_t)refprice * (COIN - tolerance)) / COIN; // and lowest + if ( price >= highprice ) + { + *maxflagp = 1; + if ( price > highprice ) // return non-zero only if we violate the tolerance + return(highprice); + } + else if ( price <= lowprice ) + { + *maxflagp = -1; + if ( price < lowprice ) + return(lowprice); + } + else return(0); +} + +// komodo_pricecmp() returns -1 if any of the prices are beyond the tolerance +int32_t komodo_pricecmp(int32_t *maxflagp,uint32_t pricebitsA[4],uint32_t pricebitsB[4],int64_t tolerance) +{ + int32_t i; + *maxflagp = 0; + for (i=1; i<4; i++) + if ( komodo_pricenew(maxflagp,pricebitsA[i],pricebitsB[i],tolerance) != 0 ) + return(-1); + return(0); +} + +// komodo_priceclamp() clamps any price that is beyond tolerance +int32_t komodo_priceclamp(uint32_t pricebits[4],uint32_t refprices[4],int64_t tolerance) +{ + int32_t i,maxflag = 0; uint32_t newprice; + for (i=1; i<4; i++) + { + if ( (newprice= komodo_pricenew(&maxflag,pricebits[i],refprices[i],tolerance)) != 0 ) + { + fprintf(stderr,"priceclamped[%d] %u -> %u\n",i,pricebits[i],newprice); + pricebits[i] = newprice; + } + } + return(0); +} + +// komodo_mineropret() returns a valid pricedata to add to the coinbase opreturn for nHeight +CScript komodo_mineropret(int32_t nHeight) +{ + CScript opret; uint32_t pricebits[4],prevbits[4]; int32_t maxflag; + if ( Mineropret.size() >= PRICES_SIZEBIT0 ) + { + if ( komodo_heightpricebits(prevbits,nHeight-1) == 0 ) + { + memcpy(pricebits,&Mineropret[0],PRICES_SIZEBIT0); + if ( komodo_pricecmp(&maxflag,pricebits,prevbits,PRICES_MAXCHANGE) < 0 ) + { + // if the new prices are not within tolerance, update Mineropret with clipped prices + komodo_priceclamp(pricebits,prevbits,PRICES_MAXCHANGE); + fprintf(stderr,"update Mineropret to clamped prices\n"); + memcpy(&Mineropret[0],pricebits,PRICES_SIZEBIT0); + } + } + return(opret << OP_RETURN << Mineropret); + } + return(opret); +} + +/* + komodo_opretvalidate() is the entire price validation! + it prints out some useful info for debugging, like the lag from current time and prev block and the prices encoded in the opreturn. + + The only way komodo_opretvalidate() doesnt return an error is if maxflag is set or it is within tolerance of both the prior block and the local data. The local data validation only happens if it is a recent block and not a block from the past as the local node is only getting the current price data. + + */ + +int32_t komodo_opretvalidate(int32_t nHeight,CScript scriptPubKey) +{ + std::vector vopret; uint32_t localbits[4],pricebits[4],prevbits[4],newprice; int32_t i,lag,lag2,maxflag=0; + if ( ASSETCHAINS_CBOPRET != 0 ) + { + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() >= PRICES_SIZEBIT0 ) + { + memcpy(pricebits,&vopret[0],PRICES_SIZEBIT0); + lag = (int32_t)(time(NULL) - pricebits[0]); + if ( lag < 0 ) + lag = -lag; + lag2 = (int32_t)(pricebits[0] - komodo_heightstamp(nHeight-1)); + fprintf(stderr,"ht.%d: t%u lag.%d %.4f USD, %.4f GBP, %.4f EUR htstamp.%d [%d]\n",nHeight,pricebits[0],lag,(double)pricebits[1]/10000,(double)pricebits[2]/10000,(double)pricebits[3]/10000,komodo_heightstamp(nHeight-1),lag2); + if ( nHeight > 1 ) + { + if ( komodo_heightpricebits(prevbits,nHeight-1) == 0 ) + { + if ( komodo_pricecmp(&maxflag,pricebits,prevbits,PRICES_MAXCHANGE) < 0 ) + return(-1); + } else return(-1); + } + if ( lag < ASSETCHAINS_BLOCKTIME && Mineropret.size() >= PRICES_SIZEBIT0 ) + { + memcpy(localbits,&Mineropret[0],PRICES_SIZEBIT0); + if ( maxflag == 0 ) + { + if ( komodo_pricecmp(&maxflag,localbits,prevbits,PRICES_MAXCHANGE) < 0 ) + return(-1); + } + else + { + for (i=1; i<4; i++) + { + maxflag = 0; + if ( (newprice= komodo_pricenew(&maxflag,pricebits[i],prevbits[i],PRICES_MAXCHANGE)) != 0 ) // proposed price is clamped + { + // make sure local price is beyond clamped + if ( maxflag > 0 && localbits[i] < pricebits[i] ) + return(-1); + else if ( maxflag < 0 && localbits[i] > pricebits[i] ) + return(-1); + } + } + } + } + return(0); + } else fprintf(stderr,"wrong size %d vs %d, scriptPubKey size %d [%02x]\n",(int32_t)vopret.size(),(int32_t)PRICES_SIZEBIT0,(int32_t)scriptPubKey.size(),scriptPubKey[0]); + return(-1); + } + return(0); +} + +// get_urljson just returns the JSON returned by the URL using issue_curl + +#define issue_curl(cmdstr) bitcoind_RPC(0,(char *)"CBCOINBASE",cmdstr,0,0,0) + +cJSON *get_urljson(char *url) +{ + char *jsonstr; cJSON *json = 0; + if ( (jsonstr= issue_curl(url)) != 0 ) + { + //fprintf(stderr,"(%s) -> (%s)\n",url,jsonstr); + json = cJSON_Parse(jsonstr); + free(jsonstr); + } + return(json); +} + +// parse the coindesk specific data. yes, if this changes, it will require an update. However, regardless if the format from the data source changes, then the code that extracts it must be changed. One way to mitigate this is to have a large variety of data sources so that there is only a very remote chance that all of them are not available. Certainly the data gathering needs to be made more robust, but it doesnt really affect the proof of concept for the decentralized trustless oracle. The trustlessness is achieved by having all nodes get the oracle data. + +int32_t get_btcusd(uint32_t pricebits[4]) +{ + cJSON *pjson,*bpi,*obj; char str[512]; uint64_t btcusd = 0,btcgbp = 0,btceur = 0; + if ( (pjson= get_urljson((char *)"http://api.coindesk.com/v1/bpi/currentprice.json")) != 0 ) + { + if ( (bpi= jobj(pjson,(char *)"bpi")) != 0 ) + { + pricebits[0] = (uint32_t)time(NULL); + if ( (obj= jobj(bpi,(char *)"USD")) != 0 ) + { + btcusd = jdouble(obj,(char *)"rate_float") * SATOSHIDEN; + pricebits[1] = ((btcusd / 10000) & 0xffffffff); + } + if ( (obj= jobj(bpi,(char *)"GBP")) != 0 ) + { + btcgbp = jdouble(obj,(char *)"rate_float") * SATOSHIDEN; + pricebits[2] = ((btcgbp / 10000) & 0xffffffff); + } + if ( (obj= jobj(bpi,(char *)"EUR")) != 0 ) + { + btceur = jdouble(obj,(char *)"rate_float") * SATOSHIDEN; + pricebits[3] = ((btceur / 10000) & 0xffffffff); + } + } + free_json(pjson); + fprintf(stderr,"BTC/USD %.4f, BTC/GBP %.4f, BTC/EUR %.4f\n",dstr(btcusd),dstr(btcgbp),dstr(btceur)); + return(0); + } + return(-1); +} + +// komodo_cbopretupdate() obtains the external price data and encodes it into Mineropret, which will then be used by the miner and validation +void komodo_cbopretupdate() +{ + uint32_t pricebits[4]; + if ( (ASSETCHAINS_CBOPRET & 1) != 0 ) + { + if ( get_btcusd(pricebits) == 0 ) + { + if ( Mineropret.size() < PRICES_SIZEBIT0 ) + Mineropret.resize(PRICES_SIZEBIT0); + memcpy(&Mineropret[0],pricebits,PRICES_SIZEBIT0); + //int32_t i; for (i=0; i Mineropret; char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN],ASSETCHAINS_USERPASS[4096],NOTARYADDRS[64][36]; uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT,ASSETCHAINS_BEAMPORT,ASSETCHAINS_CODAPORT; @@ -66,7 +67,7 @@ int64_t MAX_MONEY = 200000000 * 100000000LL; // spec will use an op_return with CLTV at front and anything after |OP_RETURN|PUSH of rest|OPRETTYPE_TIMELOCK|script| #define _ASSETCHAINS_TIMELOCKOFF 0xffffffffffffffff uint64_t ASSETCHAINS_TIMELOCKGTE = _ASSETCHAINS_TIMELOCKOFF; -uint64_t ASSETCHAINS_TIMEUNLOCKFROM = 0, ASSETCHAINS_TIMEUNLOCKTO = 0; +uint64_t ASSETCHAINS_TIMEUNLOCKFROM = 0, ASSETCHAINS_TIMEUNLOCKTO = 0,ASSETCHAINS_CBOPRET=0; uint64_t ASSETCHAINS_LASTERA = 1; uint64_t ASSETCHAINS_ENDSUBSIDY[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_HALVING[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_DECAY[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_NOTARY_PAY[ASSETCHAINS_MAX_ERAS]; diff --git a/src/komodo_utils.h b/src/komodo_utils.h index c1f488c5c..1bc379f42 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1664,11 +1664,12 @@ uint64_t komodo_ac_block_subsidy(int nHeight) } extern int64_t MAX_MONEY; +void komodo_cbopretupdate(); void komodo_args(char *argv0) { extern const char *Notaries_elected1[][2]; - std::string name,addn; char *dirname,fname[512],arg0str[64],magicstr[9]; uint8_t magic[4],extrabuf[8192],disablebits[32],*extraptr=0; FILE *fp; uint64_t val; uint16_t port; int32_t i,nonz=0,baseid,len,n,extralen = 0; uint64_t ccenables[256]; + std::string name,addn,hexstr; char *dirname,fname[512],arg0str[64],magicstr[9]; uint8_t magic[4],extrabuf[8192],disablebits[32],*extraptr=0; FILE *fp; uint64_t val; uint16_t port; int32_t i,nonz=0,baseid,len,n,extralen = 0; uint64_t ccenables[256]; IS_KOMODO_NOTARY = GetBoolArg("-notary", false); IS_STAKED_NOTARY = GetArg("-stakednotary", -1); if ( IS_STAKED_NOTARY != -1 && IS_KOMODO_NOTARY == true ) { @@ -1810,6 +1811,16 @@ void komodo_args(char *argv0) ASSETCHAINS_BEAMPORT = GetArg("-ac_beam",0); ASSETCHAINS_CODAPORT = GetArg("-ac_coda",0); ASSETCHAINS_MARMARA = GetArg("-ac_marmara",0); + ASSETCHAINS_CBOPRET = GetArg("-ac_cbopret",0); + hexstr = GetArg("-ac_mineropret",""); + if ( hexstr.size() != 0 ) + { + Mineropret.resize(hexstr.size()/2); + decode_hex(&Mineropret[0],hexstr.size()/2,(char *)hexstr.c_str()); + for (i=0; i 1 || ASSETCHAINS_SELFIMPORT.size() > 0 || ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 || ASSETCHAINS_TIMELOCKGTE != _ASSETCHAINS_TIMELOCKOFF|| ASSETCHAINS_ALGO != ASSETCHAINS_EQUIHASH || ASSETCHAINS_LWMAPOS != 0 || ASSETCHAINS_LASTERA > 0 || ASSETCHAINS_BEAMPORT != 0 || ASSETCHAINS_CODAPORT != 0 || ASSETCHAINS_MARMARA != 0 || nonz > 0 || ASSETCHAINS_CCLIB.size() > 0 || ASSETCHAINS_FOUNDERS_REWARD != 0 || ASSETCHAINS_NOTARY_PAY[0] != 0 || ASSETCHAINS_BLOCKTIME != 60 ) + if ( ASSETCHAINS_ENDSUBSIDY[0] != 0 || ASSETCHAINS_REWARD[0] != 0 || ASSETCHAINS_HALVING[0] != 0 || ASSETCHAINS_DECAY[0] != 0 || ASSETCHAINS_COMMISSION != 0 || ASSETCHAINS_PUBLIC != 0 || ASSETCHAINS_PRIVATE != 0 || ASSETCHAINS_TXPOW != 0 || ASSETCHAINS_FOUNDERS != 0 || ASSETCHAINS_SCRIPTPUB.size() > 1 || ASSETCHAINS_SELFIMPORT.size() > 0 || ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 || ASSETCHAINS_TIMELOCKGTE != _ASSETCHAINS_TIMELOCKOFF|| ASSETCHAINS_ALGO != ASSETCHAINS_EQUIHASH || ASSETCHAINS_LWMAPOS != 0 || ASSETCHAINS_LASTERA > 0 || ASSETCHAINS_BEAMPORT != 0 || ASSETCHAINS_CODAPORT != 0 || ASSETCHAINS_MARMARA != 0 || nonz > 0 || ASSETCHAINS_CCLIB.size() > 0 || ASSETCHAINS_FOUNDERS_REWARD != 0 || ASSETCHAINS_NOTARY_PAY[0] != 0 || ASSETCHAINS_BLOCKTIME != 60 || ASSETCHAINS_CBOPRET != 0 || Mineropret.size() != 0 ) { fprintf(stderr,"perc %.4f%% ac_pub=[%02x%02x%02x...] acsize.%d\n",dstr(ASSETCHAINS_COMMISSION)*100,ASSETCHAINS_OVERRIDE_PUBKEY33[0],ASSETCHAINS_OVERRIDE_PUBKEY33[1],ASSETCHAINS_OVERRIDE_PUBKEY33[2],(int32_t)ASSETCHAINS_SCRIPTPUB.size()); extraptr = extrabuf; @@ -2048,6 +2059,17 @@ void komodo_args(char *argv0) } if ( ASSETCHAINS_BLOCKTIME != 60 ) extralen += iguana_rwnum(1,&extraptr[extralen],sizeof(ASSETCHAINS_BLOCKTIME),(void *)&ASSETCHAINS_BLOCKTIME); + if ( Mineropret.size() != 0 ) + { + for (i=0; i 0 && (nHeight & 1) == 0 ) + { + + } + else if ( ASSETCHAINS_CBOPRET != 0 && nHeight > 0 && tx.vout.size() > 0 ) + { + if ( komodo_opretvalidate(nHeight,tx.vout[tx.vout.size()-1].scriptPubKey) < 0 ) + return(false); + } return(true); } diff --git a/src/miner.cpp b/src/miner.cpp index 48b8c5c62..f131bc90e 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -155,6 +155,7 @@ CScript MarmaraCoinbaseOpret(uint8_t funcid,int32_t height,CPubKey pk); uint64_t komodo_notarypay(CMutableTransaction &txNew, std::vector &NotarisationNotaries, uint32_t timestamp, int32_t height, uint8_t *script, int32_t len); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp); int32_t komodo_getnotarizedheight(uint32_t timestamp,int32_t height, uint8_t *script, int32_t len); +CScript komodo_mineropret(int32_t nHeight); CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake) { @@ -723,7 +724,14 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32 fprintf(stderr, "Created notary payment coinbase totalsat.%lu\n",totalsats); } else fprintf(stderr, "vout 2 of notarisation is not OP_RETURN scriptlen.%i\n", scriptlen); } - + if ( ASSETCHAINS_CBOPRET != 0 ) + { + int32_t numv = (int32_t)txNew.vout.size(); + txNew.vout.resize(numv+1); + txNew.vout[numv].nValue = 0; + txNew.vout[numv].scriptPubKey = komodo_mineropret(nHeight); + //printf("autocreate commision/cbopret.%lld vout[%d]\n",(long long)ASSETCHAINS_CBOPRET,(int32_t)txNew.vout.size()); + } pblock->vtx[0] = txNew; pblocktemplate->vTxFees[0] = -nFees; diff --git a/src/tui/LICENSE b/src/tui/LICENSE new file mode 100644 index 000000000..3300ef648 --- /dev/null +++ b/src/tui/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Anton Lysakov + +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. diff --git a/src/tui/README.md b/src/tui/README.md new file mode 100644 index 000000000..61e733794 --- /dev/null +++ b/src/tui/README.md @@ -0,0 +1,58 @@ +# Komodo Cryptoconditons Terminal User Interfaces (aka TUIs) + +These tools creating for demonstration and partial automation of Komodo cryptoconditions modules testing. (RogueCC game, AssetsCC, OraclesCC, GatewaysCC, MarmaraCC, ...) + + +Developer installation (on Ubuntu 18.04) : + +Python3 required for execution: + +* `sudo apt-get install python3.6 python3-pip libgnutls28-dev` + +pip packages needed: + +* `pip3 install setuptools wheel slick-bitcoinrpc` +* or `pip3 install -r requirements.txt` + +Starting: + +# TUI for RogueCC + +If you're looking for player 3 in 1 (daemon + game + TUI) multiOS bundle - please check `releases` of this repo. + +`python3 rogue_tui.py` + +![alt text](https://i.imgur.com/gkcxMGt.png) + +# TUI for OraclesCC + +Have files uploader/downloader functionality - also there is a AWS branch for AWS certificates uploading demonstration + +`python3 oracles_cc_tui.py` + +![alt text](https://i.imgur.com/tfHwRqc.png) + +# TUI for GatewaysCC + +![alt text](https://i.imgur.com/c8DPfpp.png) + +`python3 gateways_creation_tui.py` + +`python3 gateways_usage_tui.py` + +At the moment raw version of manual gateway how-to guide can be found here: https://docs.komodoplatform.com/cc/contracts/gateways/scenarios/tutorial.html I advice to read it before you start use this tool to understand the flow. + +# TUI for MarmaraCC + +`python3 marmara_tui.py` + +![alt text](https://i.imgur.com/uonMWHl.png) + +# TUI for AssetsCC (not much finished) + +`python3 assets_cc_tui.py` + +Before execution be sure than daemon for needed AC up. + + + diff --git a/src/tui/lib/logo.txt b/src/tui/lib/logo.txt new file mode 100644 index 000000000..15ace1ad5 --- /dev/null +++ b/src/tui/lib/logo.txt @@ -0,0 +1,39 @@ +MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0xlc:ldOKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0xo:,........';lxOXNMMMMMMMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMMMMMMWNKkoc,..................':ox0XWMMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMWNKkdc;............................,:ok0NWMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMWNKOdl;'.....................................,cdkKNWMMMMMMMMMMMMMM +MMMMMMMMMMMMMW0c'..............................................';kNMMMMMMMMMMMMM +MMMMMMMMMMMMMK:......................';:c:'......................,kWMMMMMMMMMMMM +MMMMMMMMMMMMXl...................;cdkKNWWNXOdl;'..................;OWMMMMMMMMMMM +MMMMMMMMMMMNo...............,cok0XWMMMMMMMMMMWNKkdc;'..............:KMMMMMMMMMMM +MMMMMMMMMMWx'...........;ox0XWMMMMMMMMMMMMMMMMMMMMWNKko:............lXMMMMMMMMMM +MMMMMMMMMWk,...........lXWMMMMMMMMMMMMWWWWMMMMMMMMMMMMMNx'...........oNMMMMMMMMM +MMMMMMMMW0;...........cKMMMMMMMMMWNXOdl::cdkKNWMMMMMMMMMNo...........'xWMMMMMMMM +MMMMMMMMKc...........;0WMMMMMWN0xl:,........';ldOXWMMMMMMXl...........,OWMMMMMMM +MMMMMMMXl...........,kWMMMMMMKl..................;OWMMMMMMK:...........;0MMMMMMM +MMMMMMNd...........'xNMMMMMMXl....................:0WMMMMMWO;...........cKMMMMMM +MMMMMNx'...........oNMMMMMMNd......................cKMMMMMMWk'...........lXMMMMM +MMMMWO,...........lXMMMMMMWx'.......................oXMMMMMMNd'...........dNMMMM +MMMMXc...........,OWMMMMMMK:........................,kWMMMMMMKc...........;0MMMM +MMMMWx'...........oXMMMMMMNd........................cKMMMMMMWk,...........lXMMMM +MMMMMNd...........'dNMMMMMMXl......................:0MMMMMMWO;...........cKMMMMM +MMMMMMXl...........,kWMMMMMMKc....................,OWMMMMMM0:...........;0MMMMMM +MMMMMMMKc...........;OWMMMMMW0:..................,kWMMMMMMXc...........,OWMMMMMM +MMMMMMMM0;...........:KMMMMMMWKko:,..........';lx0WMMMMMMNo...........'xWMMMMMMM +MMMMMMMMWk,...........lXMMMMMMMMWWXOxl:,,;cdOKNWMMMMMMMMNx'...........dNMMMMMMMM +MMMMMMMMMWx'...........dNMMMMMMMMMMMMWNXXNWMMMMMMMMMMMMWk,...........lXMMMMMMMMM +MMMMMMMMMMNo............cx0XWMMMMMMMMMMMMMMMMMMMMMMWN0kl,...........cKMMMMMMMMMM +MMMMMMMMMMMXl..............,:ok0XWMMMMMMMMMMMMWNKkdc;..............;0WMMMMMMMMMM +MMMMMMMMMMMMK:..................,cokKNWMMWNKOdl;'.................,kWMMMMMMMMMMM +MMMMMMMMMMMMWO;......................;cool;'.....................'xNMMMMMMMMMMMM +MMMMMMMMMMMMMWk;................................................'dNMMMMMMMMMMMMM +MMMMMMMMMMMMMMWXOxl;'.......................................,cdkKWMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMWNKOdc;..............................,cok0NWMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMMMMMWNKkoc,....................,:ox0XWMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0ko:,..........':lx0XWMMMMMMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0xl:,,;ldOKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNNXNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM \ No newline at end of file diff --git a/src/tui/lib/rpclib.py b/src/tui/lib/rpclib.py new file mode 100644 index 000000000..a79fc73d4 --- /dev/null +++ b/src/tui/lib/rpclib.py @@ -0,0 +1,129 @@ +import http +from slickrpc import Proxy + + +# RPC connection +def rpc_connect(rpc_user, rpc_password, port): + try: + rpc_connection = Proxy("http://%s:%s@127.0.0.1:%d"%(rpc_user, rpc_password, port)) + except Exception: + raise Exception("Connection error! Probably no daemon on selected port.") + return rpc_connection + + +# Non CC calls +def getinfo(rpc_connection): + try: + getinfo = rpc_connection.getinfo() + except Exception: + raise Exception("Connection error!") + return getinfo + + +def sendrawtransaction(rpc_connection, hex): + tx_id = rpc_connection.sendrawtransaction(hex) + return tx_id + + +def gettransaction(rpc_connection, tx_id): + transaction_info = rpc_connection.gettransaction(tx_id) + return transaction_info + + +def getrawtransaction(rpc_connection, tx_id): + rawtransaction = rpc_connection.getrawtransaction(tx_id) + return rawtransaction + + +def getbalance(rpc_connection): + balance = rpc_connection.getbalance() + return balance + +# Token CC calls +def token_create(rpc_connection, name, supply, description): + token_hex = rpc_connection.tokencreate(name, supply, description) + return token_hex + + +def token_info(rpc_connection, token_id): + token_info = rpc_connection.tokeninfo(token_id) + return token_info + + +#TODO: have to add option with pubkey input +def token_balance(rpc_connection, token_id): + token_balance = rpc_connection.tokenbalance(token_id) + return token_balance + +def token_list(rpc_connection): + token_list = rpc_connection.tokenlist() + return token_list + + +def token_convert(rpc_connection, evalcode, token_id, pubkey, supply): + token_convert_hex = rpc_connection.tokenconvert(evalcode, token_id, pubkey, supply) + return token_convert_hex + +def get_rawmempool(rpc_connection): + mempool = rpc_connection.getrawmempool() + return mempool + +# Oracle CC calls +def oracles_create(rpc_connection, name, description, data_type): + oracles_hex = rpc_connection.oraclescreate(name, description, data_type) + return oracles_hex + + +def oracles_register(rpc_connection, oracle_id, data_fee): + oracles_register_hex = rpc_connection.oraclesregister(oracle_id, data_fee) + return oracles_register_hex + + +def oracles_subscribe(rpc_connection, oracle_id, publisher_id, data_fee): + oracles_subscribe_hex = rpc_connection.oraclessubscribe(oracle_id, publisher_id, data_fee) + return oracles_subscribe_hex + + +def oracles_info(rpc_connection, oracle_id): + oracles_info = rpc_connection.oraclesinfo(oracle_id) + return oracles_info + + +def oracles_data(rpc_connection, oracle_id, hex_string): + oracles_data = rpc_connection.oraclesdata(oracle_id, hex_string) + return oracles_data + + +def oracles_list(rpc_connection): + oracles_list = rpc_connection.oracleslist() + return oracles_list + + +def oracles_samples(rpc_connection, oracletxid, batonutxo, num): + oracles_sample = rpc_connection.oraclessamples(oracletxid, batonutxo, num) + return oracles_sample + + +# Gateways CC calls +# Arguments changing dynamically depends of M N, so supposed to wrap it this way +# token_id, oracle_id, coin_name, token_supply, M, N + pubkeys for each N +def gateways_bind(rpc_connection, *args): + gateways_bind_hex = rpc_connection.gatewaysbind(*args) + return gateways_bind_hex + + +def gateways_deposit(rpc_connection, gateway_id, height, coin_name,\ + coin_txid, claim_vout, deposit_hex, proof, dest_pub, amount): + gateways_deposit_hex = rpc_connection.gatewaysdeposit(gateway_id, height, coin_name,\ + coin_txid, claim_vout, deposit_hex, proof, dest_pub, amount) + return gateways_deposit_hex + + +def gateways_claim(rpc_connection, gateway_id, coin_name, deposit_txid, dest_pub, amount): + gateways_claim_hex = rpc_connection.gatewaysclaim(gateway_id, coin_name, deposit_txid, dest_pub, amount) + return gateways_claim_hex + + +def gateways_withdraw(rpc_connection, gateway_id, coin_name, withdraw_pub, amount): + gateways_withdraw_hex = rpc_connection.gatewayswithdraw(gateway_id, coin_name, withdraw_pub, amount) + return gateways_withdraw_hex diff --git a/src/tui/lib/tuilib.py b/src/tui/lib/tuilib.py new file mode 100755 index 000000000..da1d7658a --- /dev/null +++ b/src/tui/lib/tuilib.py @@ -0,0 +1,1965 @@ +from lib import rpclib +import json +import time +import re +import sys +import pickle +import platform +import os +import subprocess +import signal +from slickrpc import Proxy +from binascii import hexlify +from binascii import unhexlify +from functools import partial +from shutil import copy + + +operating_system = platform.system() +if operating_system != 'Win64' and operating_system != 'Windows': + import readline + + +def colorize(string, color): + + colors = { + 'blue': '\033[94m', + 'magenta': '\033[95m', + 'green': '\033[92m', + 'red': '\033[91m' + } + if color not in colors: + return string + else: + return colors[color] + string + '\033[0m' + + +def rpc_connection_tui(): + # TODO: possible to save multiply entries from successfull sessions and ask user to choose then + while True: + restore_choice = input("Do you want to use connection details from previous session? [y/n]: ") + if restore_choice == "y": + try: + with open("connection.json", "r") as file: + connection_json = json.load(file) + rpc_user = connection_json["rpc_user"] + rpc_password = connection_json["rpc_password"] + rpc_port = connection_json["rpc_port"] + rpc_connection = rpclib.rpc_connect(rpc_user, rpc_password, int(rpc_port)) + except FileNotFoundError: + print(colorize("You do not have cached connection details. Please select n for connection setup", "red")) + break + elif restore_choice == "n": + rpc_user = input("Input your rpc user: ") + rpc_password = input("Input your rpc password: ") + rpc_port = input("Input your rpc port: ") + connection_details = {"rpc_user": rpc_user, + "rpc_password": rpc_password, + "rpc_port": rpc_port} + connection_json = json.dumps(connection_details) + with open("connection.json", "w+") as file: + file.write(connection_json) + rpc_connection = rpclib.rpc_connect(rpc_user, rpc_password, int(rpc_port)) + break + else: + print(colorize("Please input y or n", "red")) + return rpc_connection + + +def def_credentials(chain): + rpcport =''; + operating_system = platform.system() + if operating_system == 'Darwin': + ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' + elif operating_system == 'Linux': + ac_dir = os.environ['HOME'] + '/.komodo' + elif operating_system == 'Win64' or operating_system == 'Windows': + ac_dir = '%s/komodo/' % os.environ['APPDATA'] + if chain == 'KMD': + coin_config_file = str(ac_dir + '/komodo.conf') + else: + coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + with open(coin_config_file, 'r') as f: + for line in f: + l = line.rstrip() + if re.search('rpcuser', l): + rpcuser = l.replace('rpcuser=', '') + elif re.search('rpcpassword', l): + rpcpassword = l.replace('rpcpassword=', '') + elif re.search('rpcport', l): + rpcport = l.replace('rpcport=', '') + if len(rpcport) == 0: + if chain == 'KMD': + rpcport = 7771 + else: + print("rpcport not in conf file, exiting") + print("check "+coin_config_file) + exit(1) + + return(Proxy("http://%s:%s@127.0.0.1:%d"%(rpcuser, rpcpassword, int(rpcport)))) + + +def getinfo_tui(rpc_connection): + + info_raw = rpclib.getinfo(rpc_connection) + if isinstance(info_raw, dict): + for key in info_raw: + print("{}: {}".format(key, info_raw[key])) + input("Press [Enter] to continue...") + else: + print("Error!\n") + print(info_raw) + input("\nPress [Enter] to continue...") + + +def token_create_tui(rpc_connection): + + while True: + try: + name = input("Set your token name: ") + supply = input("Set your token supply: ") + description = input("Set your token description: ") + except KeyboardInterrupt: + break + else: + token_hex = rpclib.token_create(rpc_connection, name, supply, description) + if token_hex['result'] == "error": + print(colorize("\nSomething went wrong!\n", "pink")) + print(token_hex) + print("\n") + input("Press [Enter] to continue...") + break + else: + try: + token_txid = rpclib.sendrawtransaction(rpc_connection, + token_hex['hex']) + except KeyError: + print(token_txid) + print("Error") + input("Press [Enter] to continue...") + break + finally: + print(colorize("Token creation transaction broadcasted: " + token_txid, "green")) + file = open("tokens_list", "a") + file.writelines(token_txid + "\n") + file.close() + print(colorize("Entry added to tokens_list file!\n", "green")) + input("Press [Enter] to continue...") + break + + +def oracle_create_tui(rpc_connection): + + print(colorize("\nAvailiable data types:\n", "blue")) + oracles_data_types = ["Ihh -> height, blockhash, merkleroot\ns -> <256 char string\nS -> <65536 char string\nd -> <256 binary data\nD -> <65536 binary data", + "c -> 1 byte signed little endian number, C unsigned\nt -> 2 byte signed little endian number, T unsigned", + "i -> 4 byte signed little endian number, I unsigned\nl -> 8 byte signed little endian number, L unsigned", + "h -> 32 byte hash\n"] + for oracles_type in oracles_data_types: + print(str(oracles_type)) + while True: + try: + name = input("Set your oracle name: ") + description = input("Set your oracle description: ") + oracle_data_type = input("Set your oracle type (e.g. Ihh): ") + except KeyboardInterrupt: + break + else: + oracle_hex = rpclib.oracles_create(rpc_connection, name, description, oracle_data_type) + if oracle_hex['result'] == "error": + print(colorize("\nSomething went wrong!\n", "pink")) + print(oracle_hex) + print("\n") + input("Press [Enter] to continue...") + break + else: + try: + oracle_txid = rpclib.sendrawtransaction(rpc_connection, oracle_hex['hex']) + except KeyError: + print(oracle_txid) + print("Error") + input("Press [Enter] to continue...") + break + finally: + print(colorize("Oracle creation transaction broadcasted: " + oracle_txid, "green")) + file = open("oracles_list", "a") + file.writelines(oracle_txid + "\n") + file.close() + print(colorize("Entry added to oracles_list file!\n", "green")) + input("Press [Enter] to continue...") + break + + +def oracle_register_tui(rpc_connection): + #TODO: have an idea since blackjoker new RPC call + #grab all list and printout only or which owner match with node pubkey + try: + print(colorize("Oracles created from this instance by TUI: \n", "blue")) + with open("oracles_list", "r") as file: + for oracle in file: + print(oracle) + print(colorize('_' * 65, "blue")) + print("\n") + except FileNotFoundError: + print("Seems like a no oracles created from this instance yet\n") + pass + while True: + try: + oracle_id = input("Input txid of oracle you want to register to: ") + data_fee = input("Set publisher datafee (in satoshis): ") + except KeyboardInterrupt: + break + oracle_register_hex = rpclib.oracles_register(rpc_connection, oracle_id, data_fee) + if oracle_register_hex['result'] == "error": + print(colorize("\nSomething went wrong!\n", "pink")) + print(oracle_register_hex) + print("\n") + input("Press [Enter] to continue...") + break + else: + try: + oracle_register_txid = rpclib.sendrawtransaction(rpc_connection, oracle_register_hex['hex']) + except KeyError: + print(oracle_register_hex) + print("Error") + input("Press [Enter] to continue...") + break + else: + print(colorize("Oracle registration transaction broadcasted: " + oracle_register_txid, "green")) + input("Press [Enter] to continue...") + break + + +def oracle_subscription_utxogen(rpc_connection): + # TODO: have an idea since blackjoker new RPC call + # grab all list and printout only or which owner match with node pubkey + try: + print(colorize("Oracles created from this instance by TUI: \n", "blue")) + with open("oracles_list", "r") as file: + for oracle in file: + print(oracle) + print(colorize('_' * 65, "blue")) + print("\n") + except FileNotFoundError: + print("Seems like a no oracles created from this instance yet\n") + pass + while True: + try: + oracle_id = input("Input oracle ID you want to subscribe to: ") + #printout to fast copypaste publisher id + oracle_info = rpclib.oracles_info(rpc_connection, oracle_id) + publishers = 0 + print(colorize("\nPublishers registered for a selected oracle: \n", "blue")) + try: + for entry in oracle_info["registered"]: + publisher = entry["publisher"] + print(publisher + "\n") + publishers = publishers + 1 + print("Total publishers:{}".format(publishers)) + except (KeyError, ConnectionResetError): + print(colorize("Please re-check your input. Oracle txid seems not valid.", "red")) + pass + print(colorize('_' * 65, "blue")) + print("\n") + if publishers == 0: + print(colorize("This oracle have no publishers to subscribe.\n" + "Please register as an oracle publisher first and/or wait since registration transaciton mined!", "red")) + input("Press [Enter] to continue...") + break + publisher_id = input("Input oracle publisher id you want to subscribe to: ") + data_fee = input("Input subscription fee (in COINS!): ") + utxo_num = int(input("Input how many transactions you want to broadcast: ")) + except KeyboardInterrupt: + break + while utxo_num > 0: + while True: + oracle_subscription_hex = rpclib.oracles_subscribe(rpc_connection, oracle_id, publisher_id, data_fee) + oracle_subscription_txid = rpclib.sendrawtransaction(rpc_connection, oracle_subscription_hex['hex']) + mempool = rpclib.get_rawmempool(rpc_connection) + if oracle_subscription_txid in mempool: + break + else: + pass + print(colorize("Oracle subscription transaction broadcasted: " + oracle_subscription_txid, "green")) + utxo_num = utxo_num - 1 + input("Press [Enter] to continue...") + break + +def gateways_bind_tui(rpc_connection): + # main loop with keyboard interrupt handling + while True: + try: + while True: + try: + print(colorize("Tokens created from this instance by TUI: \n", "blue")) + with open("tokens_list", "r") as file: + for oracle in file: + print(oracle) + print(colorize('_' * 65, "blue")) + print("\n") + except FileNotFoundError: + print("Seems like a no oracles created from this instance yet\n") + pass + token_id = input("Input id of token you want to use in gw bind: ") + try: + token_name = rpclib.token_info(rpc_connection, token_id)["name"] + except KeyError: + print(colorize("Not valid tokenid. Please try again.", "red")) + input("Press [Enter] to continue...") + token_info = rpclib.token_info(rpc_connection, token_id) + print(colorize("\n{} token total supply: {}\n".format(token_id, token_info["supply"]), "blue")) + token_supply = input("Input supply for token binding: ") + try: + print(colorize("\nOracles created from this instance by TUI: \n", "blue")) + with open("oracles_list", "r") as file: + for oracle in file: + print(oracle) + print(colorize('_' * 65, "blue")) + print("\n") + except FileNotFoundError: + print("Seems like a no oracles created from this instance yet\n") + pass + oracle_id = input("Input id of oracle you want to use in gw bind: ") + try: + oracle_name = rpclib.oracles_info(rpc_connection, oracle_id)["name"] + except KeyError: + print(colorize("Not valid oracleid. Please try again.", "red")) + input("Press [Enter] to continue...") + while True: + coin_name = input("Input external coin ticker (binded oracle and token need to have same name!): ") + if token_name == oracle_name and token_name == coin_name: + break + else: + print(colorize("Token name, oracle name and external coin ticker should match!", "red")) + while True: + M = input("Input minimal amount of pubkeys needed for transaction confirmation (1 for non-multisig gw): ") + N = input("Input maximal amount of pubkeys needed for transaction confirmation (1 for non-multisig gw): ") + if (int(N) >= int(M)): + break + else: + print("Maximal amount of pubkeys should be more or equal than minimal. Please try again.") + pubkeys = [] + for i in range(int(N)): + pubkeys.append(input("Input pubkey {}: ".format(i+1))) + pubtype = input("Input pubtype of external coin: ") + p2shtype = input("Input p2shtype of external coin: ") + wiftype = input("Input wiftype of external coin: ") + args = [rpc_connection, token_id, oracle_id, coin_name, token_supply, M, N] + new_args = [str(pubtype), str(p2shtype), wiftype] + args = args + pubkeys + new_args + # broadcasting block + try: + gateways_bind_hex = rpclib.gateways_bind(*args) + except Exception as e: + print(e) + input("Press [Enter] to continue...") + break + try: + gateways_bind_txid = rpclib.sendrawtransaction(rpc_connection, gateways_bind_hex["hex"]) + except Exception as e: + print(e) + print(gateways_bind_hex) + input("Press [Enter] to continue...") + break + else: + print(colorize("Gateway bind transaction broadcasted: " + gateways_bind_txid, "green")) + file = open("gateways_list", "a") + file.writelines(gateways_bind_txid + "\n") + file.close() + print(colorize("Entry added to gateways_list file!\n", "green")) + input("Press [Enter] to continue...") + break + break + except KeyboardInterrupt: + break + +# temporary :trollface: custom connection function solution +# to have connection to KMD daemon and cache it in separate file + + +def rpc_kmd_connection_tui(): + while True: + restore_choice = input("Do you want to use KMD daemon connection details from previous session? [y/n]: ") + if restore_choice == "y": + try: + with open("connection_kmd.json", "r") as file: + connection_json = json.load(file) + rpc_user = connection_json["rpc_user"] + rpc_password = connection_json["rpc_password"] + rpc_port = connection_json["rpc_port"] + rpc_connection_kmd = rpclib.rpc_connect(rpc_user, rpc_password, int(rpc_port)) + try: + print(rpc_connection_kmd.getinfo()) + print(colorize("Successfully connected!\n", "green")) + input("Press [Enter] to continue...") + break + except Exception as e: + print(e) + print(colorize("NOT CONNECTED!\n", "red")) + input("Press [Enter] to continue...") + break + except FileNotFoundError: + print(colorize("You do not have cached KMD daemon connection details." + " Please select n for connection setup", "red")) + input("Press [Enter] to continue...") + elif restore_choice == "n": + rpc_user = input("Input your rpc user: ") + rpc_password = input("Input your rpc password: ") + rpc_port = input("Input your rpc port: ") + connection_details = {"rpc_user": rpc_user, + "rpc_password": rpc_password, + "rpc_port": rpc_port} + connection_json = json.dumps(connection_details) + with open("connection_kmd.json", "w+") as file: + file.write(connection_json) + rpc_connection_kmd = rpclib.rpc_connect(rpc_user, rpc_password, int(rpc_port)) + try: + print(rpc_connection_kmd.getinfo()) + print(colorize("Successfully connected!\n", "green")) + input("Press [Enter] to continue...") + break + except Exception as e: + print(e) + print(colorize("NOT CONNECTED!\n", "red")) + input("Press [Enter] to continue...") + break + else: + print(colorize("Please input y or n", "red")) + return rpc_connection_kmd + + +def z_sendmany_twoaddresses(rpc_connection, sendaddress, recepient1, amount1, recepient2, amount2): + str_sending_block = "[{{\"address\":\"{}\",\"amount\":{}}},{{\"address\":\"{}\",\"amount\":{}}}]".format(recepient1, amount1, recepient2, amount2) + sending_block = json.loads(str_sending_block) + operation_id = rpc_connection.z_sendmany(sendaddress,sending_block) + return operation_id + + +def operationstatus_to_txid(rpc_connection, zstatus): + str_sending_block = "[\"{}\"]".format(zstatus) + sending_block = json.loads(str_sending_block) + operation_json = rpc_connection.z_getoperationstatus(sending_block) + operation_dump = json.dumps(operation_json) + operation_dict = json.loads(operation_dump)[0] + txid = operation_dict['result']['txid'] + return txid + + +def gateways_send_kmd(rpc_connection): + # TODO: have to handle CTRL+C on text input + print(colorize("Please be carefull when input wallet addresses and amounts since all transactions doing in real KMD!", "pink")) + print("Your addresses with balances: ") + list_address_groupings = rpc_connection.listaddressgroupings() + for address in list_address_groupings: + print(str(address) + "\n") + sendaddress = input("Input address from which you transfer KMD: ") + recepient1 = input("Input address which belongs to pubkey which will receive tokens: ") + amount1 = 0.0001 + recepient2 = input("Input gateway deposit address: ") + file = open("deposits_list", "a") + #have to show here deposit addresses for gateways created by user + amount2 = input("Input how many KMD you want to deposit on this gateway: ") + operation = z_sendmany_twoaddresses(rpc_connection, sendaddress, recepient1, amount1, recepient2, amount2) + print("Operation proceed! " + str(operation) + " Let's wait 2 seconds to get txid") + # trying to avoid pending status of operation + time.sleep(2) + txid = operationstatus_to_txid(rpc_connection, operation) + file.writelines(txid + "\n") + file.close() + print(colorize("KMD Transaction ID: " + str(txid) + " Entry added to deposits_list file", "green")) + input("Press [Enter] to continue...") + + +def gateways_deposit_tui(rpc_connection_assetchain, rpc_connection_komodo): + while True: + bind_txid = input("Input your gateway bind txid: ") + coin_name = input("Input your external coin ticker (e.g. KMD): ") + coin_txid = input("Input your deposit txid: ") + dest_pub = input("Input pubkey which claim deposit: ") + amount = input("Input amount of your deposit: ") + height = rpc_connection_komodo.getrawtransaction(coin_txid, 1)["height"] + deposit_hex = rpc_connection_komodo.getrawtransaction(coin_txid, 1)["hex"] + claim_vout = "0" + proof_sending_block = "[\"{}\"]".format(coin_txid) + proof = rpc_connection_komodo.gettxoutproof(json.loads(proof_sending_block)) + deposit_hex = rpclib.gateways_deposit(rpc_connection_assetchain, bind_txid, str(height), coin_name, \ + coin_txid, claim_vout, deposit_hex, proof, dest_pub, amount) + print(deposit_hex) + deposit_txid = rpclib.sendrawtransaction(rpc_connection_assetchain, deposit_hex["hex"]) + print("Done! Gateways deposit txid is: " + deposit_txid + " Please not forget to claim your deposit!") + input("Press [Enter] to continue...") + break + + +def gateways_claim_tui(rpc_connection): + while True: + bind_txid = input("Input your gateway bind txid: ") + coin_name = input("Input your external coin ticker (e.g. KMD): ") + deposit_txid = input("Input your gatewaysdeposit txid: ") + dest_pub = input("Input pubkey which claim deposit: ") + amount = input("Input amount of your deposit: ") + claim_hex = rpclib.gateways_claim(rpc_connection, bind_txid, coin_name, deposit_txid, dest_pub, amount) + try: + claim_txid = rpclib.sendrawtransaction(rpc_connection, claim_hex["hex"]) + except Exception as e: + print(e) + print(claim_hex) + input("Press [Enter] to continue...") + break + else: + print("Succesfully claimed! Claim transaction id: " + claim_txid) + input("Press [Enter] to continue...") + break + + +def gateways_withdrawal_tui(rpc_connection): + while True: + bind_txid = input("Input your gateway bind txid: ") + coin_name = input("Input your external coin ticker (e.g. KMD): ") + withdraw_pub = input("Input pubkey to which you want to withdraw: ") + amount = input("Input amount of withdrawal: ") + withdraw_hex = rpclib.gateways_withdraw(rpc_connection, bind_txid, coin_name, withdraw_pub, amount) + withdraw_txid = rpclib.sendrawtransaction(rpc_connection, withdraw_hex["hex"]) + print(withdraw_txid) + input("Press [Enter] to continue...") + break + + +def print_mempool(rpc_connection): + while True: + mempool = rpclib.get_rawmempool(rpc_connection) + tx_counter = 0 + print(colorize("Transactions in mempool: \n", "magenta")) + for transaction in mempool: + print(transaction + "\n") + tx_counter = tx_counter + 1 + print("Total: " + str(tx_counter) + " transactions\n") + print("R + Enter to refresh list. E + Enter to exit menu." + "\n") + is_refresh = input("Choose your destiny: ") + if is_refresh == "R": + print("\n") + pass + elif is_refresh == "E": + print("\n") + break + else: + print("\nPlease choose R or E\n") + + +def print_tokens_list(rpc_connection): + # TODO: have to print it with tokeninfo to have sense + pass + + +def print_tokens_balances(rpc_connection): + # TODO: checking tokenbalance for each token from tokenlist and reflect non zero ones + pass + + +def hexdump(filename, chunk_size=1<<15): + data = "" + #add_spaces = partial(re.compile(b'(..)').sub, br'\1 ') + #write = getattr(sys.stdout, 'buffer', sys.stdout).write + with open(filename, 'rb') as file: + for chunk in iter(partial(file.read, chunk_size), b''): + data += str(hexlify(chunk).decode()) + return data + + +def convert_file_oracle_d(rpc_connection): + while True: + path = input("Input path to file you want to upload to oracle: ") + try: + hex_data = (hexdump(path, 1))[2:] + except Exception as e: + print(e) + print("Seems something goes wrong (I guess you've specified wrong path)!") + input("Press [Enter] to continue...") + break + else: + length = round(len(hex_data) / 2) + if length > 256: + print("Length: " + str(length) + " bytes") + print("File is too big for this app") + input("Press [Enter] to continue...") + break + else: + hex_length = format(length, '#04x')[2:] + data_for_oracle = str(hex_length) + hex_data + print("File hex representation: \n") + print(data_for_oracle + "\n") + print("Length: " + str(length) + " bytes") + print("File converted!") + new_oracle_hex = rpclib.oracles_create(rpc_connection, "tonyconvert", path, "d") + new_oracle_txid = rpclib.sendrawtransaction(rpc_connection, new_oracle_hex["hex"]) + time.sleep(0.5) + oracle_register_hex = rpclib.oracles_register(rpc_connection, new_oracle_txid, "10000") + oracle_register_txid = rpclib.sendrawtransaction(rpc_connection, oracle_register_hex["hex"]) + time.sleep(0.5) + oracle_subscribe_hex = rpclib.oracles_subscribe(rpc_connection, new_oracle_txid, rpclib.getinfo(rpc_connection)["pubkey"], "0.001") + oracle_subscribe_txid = rpclib.sendrawtransaction(rpc_connection, oracle_subscribe_hex["hex"]) + time.sleep(0.5) + while True: + mempool = rpclib.get_rawmempool(rpc_connection) + if oracle_subscribe_txid in mempool: + print("Waiting for oracle subscribtion tx to be mined" + "\n") + time.sleep(6) + pass + else: + break + oracles_data_hex = rpclib.oracles_data(rpc_connection, new_oracle_txid, data_for_oracle) + try: + oracle_data_txid = rpclib.sendrawtransaction(rpc_connection, oracles_data_hex["hex"]) + except Exception as e: + print(oracles_data_hex) + print(e) + print("Oracle created: " + str(new_oracle_txid)) + print("Data published: " + str(oracle_data_txid)) + input("Press [Enter] to continue...") + break + + +def convert_file_oracle_D(rpc_connection): + while True: + path = input("Input path to file you want to upload to oracle: ") + try: + hex_data = (hexdump(path, 1)) + except Exception as e: + print(e) + print("Seems something goes wrong (I guess you've specified wrong path)!") + input("Press [Enter] to continue...") + break + else: + length = round(len(hex_data) / 2) + # if length > 800000: + # print("Too big file size to upload for this version of program. Maximum size is 800KB.") + # input("Press [Enter] to continue...") + # break + if length > 8000: + # if file is more than 8000 bytes - slicing it to <= 8000 bytes chunks (16000 symbols = 8000 bytes) + data = [hex_data[i:i + 16000] for i in range(0, len(hex_data), 16000)] + chunks_amount = len(data) + # TODO: have to create oracle but subscribe this time chunks amount times to send whole file in same block + # TODO: 2 - on some point file will not fit block - have to find this point + # TODO: 3 way how I want to implement it first will keep whole file in RAM - have to implement some way to stream chunks to oracle before whole file readed + # TODO: have to "optimise" registration fee + # Maybe just check size first by something like a du ? + print("Length: " + str(length) + " bytes.\n Chunks amount: " + str(chunks_amount)) + new_oracle_hex = rpclib.oracles_create(rpc_connection, "tonyconvert_" + str(chunks_amount), path, "D") + new_oracle_txid = rpclib.sendrawtransaction(rpc_connection, new_oracle_hex["hex"]) + time.sleep(0.5) + oracle_register_hex = rpclib.oracles_register(rpc_connection, new_oracle_txid, "10000") + oracle_register_txid = rpclib.sendrawtransaction(rpc_connection, oracle_register_hex["hex"]) + # subscribe chunks_amount + 1 times, but lets limit our broadcasting 100 tx per block (800KB/block) + if chunks_amount > 100: + utxo_num = 101 + else: + utxo_num = chunks_amount + while utxo_num > 0: + while True: + oracle_subscription_hex = rpclib.oracles_subscribe(rpc_connection, new_oracle_txid, rpclib.getinfo(rpc_connection)["pubkey"], "0.001") + oracle_subscription_txid = rpclib.sendrawtransaction(rpc_connection, + oracle_subscription_hex['hex']) + mempool = rpclib.get_rawmempool(rpc_connection) + if oracle_subscription_txid in mempool: + break + else: + pass + print(colorize("Oracle subscription transaction broadcasted: " + oracle_subscription_txid, "green")) + utxo_num = utxo_num - 1 + # waiting for last broadcasted subscribtion transaction to be mined to be sure that money are on oracle balance + while True: + mempool = rpclib.get_rawmempool(rpc_connection) + if oracle_subscription_txid in mempool: + print("Waiting for oracle subscribtion tx to be mined" + "\n") + time.sleep(6) + pass + else: + break + print("Oracle preparation is finished. Oracle txid: " + new_oracle_txid) + # can publish data now + counter = 0 + for chunk in data: + hex_length_bigendian = format(round(len(chunk) / 2), '#06x')[2:] + # swap to get little endian length + a = hex_length_bigendian[2:] + b = hex_length_bigendian[:2] + hex_length = a + b + data_for_oracle = str(hex_length) + chunk + counter = counter + 1 + # print("Chunk number: " + str(counter) + "\n") + # print(data_for_oracle) + try: + oracles_data_hex = rpclib.oracles_data(rpc_connection, new_oracle_txid, data_for_oracle) + except Exception as e: + print(data_for_oracle) + print(e) + input("Press [Enter] to continue...") + break + # on broadcasting ensuring that previous one reached mempool before blast next one + while True: + mempool = rpclib.get_rawmempool(rpc_connection) + oracle_data_txid = rpclib.sendrawtransaction(rpc_connection, oracles_data_hex["hex"]) + #time.sleep(0.1) + if oracle_data_txid in mempool: + break + else: + pass + # blasting not more than 100 at once (so maximum capacity per block can be changed here) + # but keep in mind that registration UTXOs amount needs to be changed too ! + if counter % 100 == 0 and chunks_amount > 100: + while True: + mempool = rpclib.get_rawmempool(rpc_connection) + if oracle_data_txid in mempool: + print("Waiting for previous data chunks to be mined before send new ones" + "\n") + print("Sent " + str(counter) + " chunks from " + str(chunks_amount)) + time.sleep(6) + pass + else: + break + + print("Last baton: " + oracle_data_txid) + input("Press [Enter] to continue...") + break + # if file suits single oraclesdata just broadcasting it straight without any slicing + else: + hex_length_bigendian = format(length, '#06x')[2:] + # swap to get little endian length + a = hex_length_bigendian[2:] + b = hex_length_bigendian[:2] + hex_length = a + b + data_for_oracle = str(hex_length) + hex_data + print("File hex representation: \n") + print(data_for_oracle + "\n") + print("Length: " + str(length) + " bytes") + print("File converted!") + new_oracle_hex = rpclib.oracles_create(rpc_connection, "tonyconvert_" + "1", path, "D") + new_oracle_txid = rpclib.sendrawtransaction(rpc_connection, new_oracle_hex["hex"]) + time.sleep(0.5) + oracle_register_hex = rpclib.oracles_register(rpc_connection, new_oracle_txid, "10000") + oracle_register_txid = rpclib.sendrawtransaction(rpc_connection, oracle_register_hex["hex"]) + time.sleep(0.5) + oracle_subscribe_hex = rpclib.oracles_subscribe(rpc_connection, new_oracle_txid, rpclib.getinfo(rpc_connection)["pubkey"], "0.001") + oracle_subscribe_txid = rpclib.sendrawtransaction(rpc_connection, oracle_subscribe_hex["hex"]) + time.sleep(0.5) + while True: + mempool = rpclib.get_rawmempool(rpc_connection) + if oracle_subscribe_txid in mempool: + print("Waiting for oracle subscribtion tx to be mined" + "\n") + time.sleep(6) + pass + else: + break + oracles_data_hex = rpclib.oracles_data(rpc_connection, new_oracle_txid, data_for_oracle) + try: + oracle_data_txid = rpclib.sendrawtransaction(rpc_connection, oracles_data_hex["hex"]) + except Exception as e: + print(oracles_data_hex) + print(e) + input("Press [Enter] to continue...") + break + else: + print("Oracle created: " + str(new_oracle_txid)) + print("Data published: " + str(oracle_data_txid)) + input("Press [Enter] to continue...") + break + + +def get_files_list(rpc_connection): + + start_time = time.time() + oracles_list = rpclib.oracles_list(rpc_connection) + files_list = [] + for oracle_txid in oracles_list: + oraclesinfo_result = rpclib.oracles_info(rpc_connection, oracle_txid) + description = oraclesinfo_result['description'] + name = oraclesinfo_result['name'] + if name[0:12] == 'tonyconvert_': + new_file = '[' + name + ': ' + description + ']: ' + oracle_txid + files_list.append(new_file) + print("--- %s seconds ---" % (time.time() - start_time)) + return files_list + + +def display_files_list(rpc_connection): + print("Scanning oracles. Please wait...") + list_to_display = get_files_list(rpc_connection) + while True: + for file in list_to_display: + print(file + "\n") + input("Press [Enter] to continue...") + break + + +def files_downloader(rpc_connection): + while True: + display_files_list(rpc_connection) + print("\n") + oracle_id = input("Input oracle ID you want to download file from: ") + output_path = input("Input output path for downloaded file (name included) e.g. /home/test.txt: ") + oracle_info = rpclib.oracles_info(rpc_connection, oracle_id) + name = oracle_info['name'] + latest_baton_txid = oracle_info['registered'][0]['batontxid'] + if name[0:12] == 'tonyconvert_': + # downloading process here + chunks_amount = int(name[12:]) + data = rpclib.oracles_samples(rpc_connection, oracle_id, latest_baton_txid, str(chunks_amount))["samples"] + for chunk in reversed(data): + with open(output_path, 'ab+') as file: + file.write(unhexlify(chunk[0])) + print("I hope that file saved to " + output_path + "\n") + input("Press [Enter] to continue...") + break + + else: + print("I cant recognize file inside this oracle. I'm very sorry, boss.") + input("Press [Enter] to continue...") + break + + +def marmara_receive_tui(rpc_connection): + while True: + issuer_pubkey = input("Input pubkey of person who do you want to receive MARMARA from: ") + issuance_sum = input("Input amount of MARMARA you want to receive: ") + blocks_valid = input("Input amount of blocks for cheque matures: ") + try: + marmara_receive_txinfo = rpc_connection.marmarareceive(issuer_pubkey, issuance_sum, "MARMARA", blocks_valid) + marmara_receive_txid = rpc_connection.sendrawtransaction(marmara_receive_txinfo["hex"]) + print("Marmara receive txid broadcasted: " + marmara_receive_txid + "\n") + print(json.dumps(marmara_receive_txinfo, indent=4, sort_keys=True) + "\n") + with open("receive_txids.txt", 'a+') as file: + file.write(marmara_receive_txid + "\n") + file.write(json.dumps(marmara_receive_txinfo, indent=4, sort_keys=True) + "\n") + print("Transaction id is saved to receive_txids.txt file.") + input("Press [Enter] to continue...") + break + except Exception as e: + print(marmara_receive_txinfo) + print(e) + print("Something went wrong. Please check your input") + + +def marmara_issue_tui(rpc_connection): + while True: + receiver_pubkey = input("Input pubkey of person who do you want to issue MARMARA: ") + issuance_sum = input("Input amount of MARMARA you want to issue: ") + maturing_block = input("Input number of block on which issuance mature: ") + approval_txid = input("Input receiving request transaction id: ") + try: + marmara_issue_txinfo = rpc_connection.marmaraissue(receiver_pubkey, issuance_sum, "MARMARA", maturing_block, approval_txid) + marmara_issue_txid = rpc_connection.sendrawtransaction(marmara_issue_txinfo["hex"]) + print("Marmara issuance txid broadcasted: " + marmara_issue_txid + "\n") + print(json.dumps(marmara_issue_txinfo, indent=4, sort_keys=True) + "\n") + with open("issue_txids.txt", "a+") as file: + file.write(marmara_issue_txid + "\n") + file.write(json.dumps(marmara_issue_txinfo, indent=4, sort_keys=True) + "\n") + print("Transaction id is saved to issue_txids.txt file.") + input("Press [Enter] to continue...") + break + except Exception as e: + print(marmara_issue_txinfo) + print(e) + print("Something went wrong. Please check your input") + + +def marmara_creditloop_tui(rpc_connection): + while True: + loop_txid = input("Input transaction ID of credit loop you want to get info about: ") + try: + marmara_creditloop_info = rpc_connection.marmaracreditloop(loop_txid) + print(json.dumps(marmara_creditloop_info, indent=4, sort_keys=True) + "\n") + input("Press [Enter] to continue...") + break + except Exception as e: + print(marmara_creditloop_info) + print(e) + print("Something went wrong. Please check your input") + + +def marmara_settlement_tui(rpc_connection): + while True: + loop_txid = input("Input transaction ID of credit loop to make settlement: ") + try: + marmara_settlement_info = rpc_connection.marmarasettlement(loop_txid) + marmara_settlement_txid = rpc_connection.sendrawtransaction(marmara_settlement_info["hex"]) + print("Loop " + loop_txid + " succesfully settled!\nSettlement txid: " + marmara_settlement_txid) + with open("settlement_txids.txt", "a+") as file: + file.write(marmara_settlement_txid + "\n") + file.write(json.dumps(marmara_settlement_info, indent=4, sort_keys=True) + "\n") + print("Transaction id is saved to settlement_txids.txt file.") + input("Press [Enter] to continue...") + break + except Exception as e: + print(marmara_settlement_info) + print(e) + print("Something went wrong. Please check your input") + input("Press [Enter] to continue...") + break + + +def marmara_lock_tui(rpc_connection): + while True: + amount = input("Input amount of coins you want to lock for settlement and staking: ") + unlock_height = input("Input height on which coins should be unlocked: ") + try: + marmara_lock_info = rpc_connection.marmaralock(amount, unlock_height) + marmara_lock_txid = rpc_connection.sendrawtransaction(marmara_lock_info["hex"]) + with open("lock_txids.txt", "a+") as file: + file.write(marmara_lock_txid + "\n") + file.write(json.dumps(marmara_lock_info, indent=4, sort_keys=True) + "\n") + print("Transaction id is saved to lock_txids.txt file.") + input("Press [Enter] to continue...") + break + except Exception as e: + print(e) + print("Something went wrong. Please check your input") + input("Press [Enter] to continue...") + break + + +def marmara_info_tui(rpc_connection): + while True: + firstheight = input("Input first height (default 0): ") + if not firstheight: + firstheight = "0" + lastheight = input("Input last height (default current (0) ): ") + if not lastheight: + lastheight = "0" + minamount = input("Input min amount (default 0): ") + if not minamount: + minamount = "0" + maxamount = input("Input max amount (default 0): ") + if not maxamount: + maxamount = "0" + issuerpk = input("Optional. Input issuer public key: ") + try: + if issuerpk: + marmara_info = rpc_connection.marmarainfo(firstheight, lastheight, minamount, maxamount, "MARMARA", issuerpk) + else: + marmara_info = rpc_connection.marmarainfo(firstheight, lastheight, minamount, maxamount) + print(json.dumps(marmara_info, indent=4, sort_keys=True) + "\n") + input("Press [Enter] to continue...") + break + except Exception as e: + print(marmara_info) + print(e) + print("Something went wrong. Please check your input") + input("Press [Enter] to continue...") + break + + +def rogue_game_info(rpc_connection, game_txid): + game_info_arg = '"' + "[%22" + game_txid + "%22]" + '"' + game_info = rpc_connection.cclib("gameinfo", "17", game_info_arg) + return game_info + + +def rogue_game_register(rpc_connection, game_txid, player_txid = False): + if player_txid: + registration_info_arg = '"' + "[%22" + game_txid + "%22,%22" + player_txid + "%22]" + '"' + else: + registration_info_arg = '"' + "[%22" + game_txid + "%22]" + '"' + registration_info = rpc_connection.cclib("register", "17", registration_info_arg) + return registration_info + + +def rogue_pending(rpc_connection): + rogue_pending_list = rpc_connection.cclib("pending", "17") + return rogue_pending_list + + +def rogue_bailout(rpc_connection, game_txid): + bailout_info_arg = '"' + "[%22" + game_txid + "%22]" + '"' + bailout_info = rpc_connection.cclib("bailout", "17", bailout_info_arg) + return bailout_info + + +def rogue_highlander(rpc_connection, game_txid): + highlander_info_arg = '"' + "[%22" + game_txid + "%22]" + '"' + highlander_info = rpc_connection.cclib("highlander", "17", highlander_info_arg) + return highlander_info + + +def rogue_players_list(rpc_connection): + rogue_players_list = rpc_connection.cclib("players", "17") + return rogue_players_list + + +def rogue_player_info(rpc_connection, playertxid): + player_info_arg = '"' + "[%22" + playertxid + "%22]" + '"' + player_info = rpc_connection.cclib("playerinfo", "17", player_info_arg) + return player_info + + +def rogue_extract(rpc_connection, game_txid, pubkey): + extract_info_arg = '"' + "[%22" + game_txid + "%22,%22" + pubkey + "%22]" + '"' + extract_info = rpc_connection.cclib("extract", "17", extract_info_arg) + return extract_info + + +def rogue_keystrokes(rpc_connection, game_txid, keystroke): + rogue_keystrokes_arg = '"' + "[%22" + game_txid + "%22,%22" + keystroke + "%22]" + '"' + keystroke_info = rpc_connection.cclib("keystrokes", "17", rogue_keystrokes_arg) + return keystroke_info + + +def print_multiplayer_games_list(rpc_connection): + while True: + pending_list = rogue_pending(rpc_connection) + multiplayer_pending_list = [] + for game in pending_list["pending"]: + if rogue_game_info(rpc_connection, game)["maxplayers"] > 1: + multiplayer_pending_list.append(game) + print("Multiplayer games availiable to join: \n") + for active_multiplayer_game in multiplayer_pending_list: + game_info = rogue_game_info(rpc_connection, active_multiplayer_game) + print(colorize("\n================================\n", "green")) + print("Game txid: " + game_info["gametxid"]) + print("Game buyin: " + str(game_info["buyin"])) + print("Game height: " + str(game_info["gameheight"])) + print("Start height: " + str(game_info["start"])) + print("Alive players: " + str(game_info["alive"])) + print("Registered players: " + str(game_info["numplayers"])) + print("Max players: " + str(game_info["maxplayers"])) + print(colorize("\n***\n", "blue")) + print("Players in game:") + for player in game_info["players"]: + print("Slot: " + str(player["slot"])) + if "baton" in player.keys(): + print("Baton: " + str(player["baton"])) + if "tokenid" in player.keys(): + print("Tokenid: " + str(player["tokenid"])) + print("Is mine?: " + str(player["ismine"])) + print(colorize("\nR + Enter - refresh list.\nE + Enter - to the game choice.\nCTRL + C - back to main menu", "blue")) + is_refresh = input("Choose your destiny: ") + if is_refresh == "R": + print("\n") + pass + elif is_refresh == "E": + print("\n") + break + else: + print("\nPlease choose R or E\n") + + +def rogue_newgame_singleplayer(rpc_connection, is_game_a_rogue=True): + try: + new_game_txid = rpc_connection.cclib("newgame", "17", "[1]")["txid"] + print("New singleplayer training game succesfully created. txid: " + new_game_txid) + while True: + mempool = rpc_connection.getrawmempool() + if new_game_txid in mempool: + print(colorize("Waiting for game transaction to be mined", "blue")) + time.sleep(5) + else: + print(colorize("Game transaction is mined", "green")) + break + players_list = rogue_players_list(rpc_connection) + if len(players_list["playerdata"]) > 0: + print_players_list(rpc_connection) + while True: + is_choice_needed = input("Do you want to choose a player for this game? [y/n] ") + if is_choice_needed == "y": + player_txid = input("Please input player txid: ") + newgame_regisration_txid = rogue_game_register(rpc_connection, new_game_txid, player_txid)["txid"] + break + elif is_choice_needed == "n": + set_warriors_name(rpc_connection) + newgame_regisration_txid = rogue_game_register(rpc_connection, new_game_txid)["txid"] + break + else: + print("Please choose y or n !") + else: + print("No players available to select") + input("Press [Enter] to continue...") + newgame_regisration_txid = rogue_game_register(rpc_connection, new_game_txid)["txid"] + while True: + mempool = rpc_connection.getrawmempool() + if newgame_regisration_txid in mempool: + print(colorize("Waiting for registration transaction to be mined", "blue")) + time.sleep(5) + else: + print(colorize("Registration transaction is mined", "green")) + break + game_info = rogue_game_info(rpc_connection, new_game_txid) + start_time = time.time() + while True: + if is_game_a_rogue: + subprocess.call(["../cc/rogue/rogue", str(game_info["seed"]), str(game_info["gametxid"])]) + else: + subprocess.call(["../cc/games/tetris", str(game_info["seed"]), str(game_info["gametxid"])]) + time_elapsed = time.time() - start_time + if time_elapsed > 1: + break + else: + print("Game less than 1 second. Trying to start again") + time.sleep(1) + game_end_height = int(rpc_connection.getinfo()["blocks"]) + while True: + current_height = int(rpc_connection.getinfo()["blocks"]) + height_difference = current_height - game_end_height + if height_difference == 0: + print(current_height) + print(game_end_height) + print(colorize("Waiting for next block before bailout", "blue")) + time.sleep(5) + else: + break + #print("\nKeystrokes of this game:\n") + #time.sleep(0.5) + while True: + keystrokes_rpc_responses = find_game_keystrokes_in_log(new_game_txid)[1::2] + if len(keystrokes_rpc_responses) < 1: + print("No keystrokes broadcasted yet. Let's wait 5 seconds") + time.sleep(5) + else: + break + #print(keystrokes_rpc_responses) + for keystroke in keystrokes_rpc_responses: + json_keystroke = json.loads(keystroke)["result"] + if "status" in json_keystroke.keys() and json_keystroke["status"] == "error": + while True: + print("Trying to re-brodcast keystroke") + keystroke_rebroadcast = rogue_keystrokes(rpc_connection, json_keystroke["gametxid"], json_keystroke["keystrokes"]) + if "txid" in keystroke_rebroadcast.keys(): + print("Keystroke broadcasted! txid: " + keystroke_rebroadcast["txid"]) + break + else: + print("Let's try again in 5 seconds") + time.sleep(5) + # waiting for last keystroke confirmation here + last_keystroke_json = json.loads(keystrokes_rpc_responses[-1]) + while True: + while True: + try: + rpc_connection.sendrawtransaction(last_keystroke_json["result"]["hex"]) + except Exception as e: + pass + try: + confirmations_amount = rpc_connection.getrawtransaction(last_keystroke_json["result"]["txid"], 1)["confirmations"] + break + except Exception as e: + print(e) + print("Let's wait a little bit more") + time.sleep(5) + pass + if confirmations_amount < 2: + print("Last keystroke not confirmed yet! Let's wait a little") + time.sleep(10) + else: + print("Last keystroke confirmed!") + break + while True: + print("\nExtraction info:\n") + extraction_info = rogue_extract(rpc_connection, new_game_txid, rpc_connection.getinfo()["pubkey"]) + if extraction_info["status"] == "error": + print(colorize("Your warrior died or no any information about game was saved on blockchain", "red")) + print("If warrior was alive - try to wait a little (choose n to wait for a next block). If he is dead - you can bailout now (choose y).") + else: + print("Current game state:") + print("Game txid: " + extraction_info["gametxid"]) + print("Information about game saved on chain: " + extraction_info["extracted"]) + print("\n") + is_bailout_needed = input("Do you want to make bailout now [y] or wait for one more block [n]? [y/n]: ") + if is_bailout_needed == "y": + bailout_info = rogue_bailout(rpc_connection, new_game_txid) + while True: + try: + confirmations_amount = rpc_connection.getrawtransaction(bailout_info["txid"], 1)["confirmations"] + break + except Exception as e: + print(e) + print("Bailout not on blockchain yet. Let's wait a little bit more") + time.sleep(20) + pass + break + elif is_bailout_needed == "n": + game_end_height = int(rpc_connection.getinfo()["blocks"]) + while True: + current_height = int(rpc_connection.getinfo()["blocks"]) + height_difference = current_height - game_end_height + if height_difference == 0: + print(current_height) + print(game_end_height) + print(colorize("Waiting for next block before bailout", "blue")) + time.sleep(5) + else: + break + else: + print("Please choose y or n !") + print(bailout_info) + print("\nGame is finished!\n") + bailout_txid = bailout_info["txid"] + input("Press [Enter] to continue...") + except Exception as e: + print("Something went wrong.") + print(e) + input("Press [Enter] to continue...") + + +def play_multiplayer_game(rpc_connection): + # printing list of user active multiplayer games + active_games_list = rpc_connection.cclib("games", "17")["games"] + active_multiplayer_games_list = [] + for game in active_games_list: + gameinfo = rogue_game_info(rpc_connection, game) + if gameinfo["maxplayers"] > 1: + active_multiplayer_games_list.append(gameinfo) + games_counter = 0 + for active_multiplayer_game in active_multiplayer_games_list: + games_counter = games_counter + 1 + is_ready_to_start = False + try: + active_multiplayer_game["seed"] + is_ready_to_start = True + except Exception as e: + pass + print(colorize("\n================================\n", "green")) + print("Game txid: " + active_multiplayer_game["gametxid"]) + print("Game buyin: " + str(active_multiplayer_game["buyin"])) + if is_ready_to_start: + print(colorize("Ready for start!", "green")) + else: + print(colorize("Not ready for start yet, wait until start height!", "red")) + print("Game height: " + str(active_multiplayer_game["gameheight"])) + print("Start height: " + str(active_multiplayer_game["start"])) + print("Alive players: " + str(active_multiplayer_game["alive"])) + print("Registered players: " + str(active_multiplayer_game["numplayers"])) + print("Max players: " + str(active_multiplayer_game["maxplayers"])) + print(colorize("\n***\n", "blue")) + print("Players in game:") + for player in active_multiplayer_game["players"]: + print("Slot: " + str(player["slot"])) + print("Baton: " + str(player["baton"])) + print("Tokenid: " + str(player["tokenid"])) + print("Is mine?: " + str(player["ismine"])) + # asking user if he want to start any of them + while True: + start_game = input("\nDo you want to start any of your pendning multiplayer games?[y/n]: ") + if start_game == "y": + new_game_txid = input("Input txid of game which you want to start: ") + game_info = rogue_game_info(rpc_connection, new_game_txid) + try: + start_time = time.time() + while True: + subprocess.call(["cc/rogue/rogue", str(game_info["seed"]), str(game_info["gametxid"])]) + time_elapsed = time.time() - start_time + if time_elapsed > 1: + break + else: + print("Game less than 1 second. Trying to start again") + time.sleep(1) + except Exception as e: + print("Maybe game isn't ready for start yet or your input was not correct, sorry.") + input("Press [Enter] to continue...") + break + game_end_height = int(rpc_connection.getinfo()["blocks"]) + while True: + current_height = int(rpc_connection.getinfo()["blocks"]) + height_difference = current_height - game_end_height + if height_difference == 0: + print(current_height) + print(game_end_height) + print(colorize("Waiting for next block before bailout or highlander", "blue")) + time.sleep(5) + else: + break + while True: + keystrokes_rpc_responses = find_game_keystrokes_in_log(new_game_txid)[1::2] + if len(keystrokes_rpc_responses) < 1: + print("No keystrokes broadcasted yet. Let's wait 5 seconds") + time.sleep(5) + else: + break + for keystroke in keystrokes_rpc_responses: + json_keystroke = json.loads(keystroke)["result"] + if "status" in json_keystroke.keys() and json_keystroke["status"] == "error": + while True: + print("Trying to re-brodcast keystroke") + keystroke_rebroadcast = rogue_keystrokes(rpc_connection, json_keystroke["gametxid"], + json_keystroke["keystrokes"]) + if "txid" in keystroke_rebroadcast.keys(): + print("Keystroke broadcasted! txid: " + keystroke_rebroadcast["txid"]) + break + else: + print("Let's try again in 5 seconds") + time.sleep(5) + last_keystroke_json = json.loads(keystrokes_rpc_responses[-1]) + while True: + while True: + try: + confirmations_amount = rpc_connection.getrawtransaction(last_keystroke_json["result"]["txid"], 1)["confirmations"] + break + except Exception as e: + print(e) + print("Let's wait a little bit more") + rpc_connection.sendrawtransaction(last_keystroke_json["result"]["hex"]) + time.sleep(5) + pass + if confirmations_amount < 2: + print("Last keystroke not confirmed yet! Let's wait a little") + time.sleep(10) + else: + print("Last keystroke confirmed!") + break + while True: + print("\nExtraction info:\n") + extraction_info = rogue_extract(rpc_connection, new_game_txid, rpc_connection.getinfo()["pubkey"]) + if extraction_info["status"] == "error": + print(colorize("Your warrior died or no any information about game was saved on blockchain", "red")) + print("If warrior was alive - try to wait a little (choose n to wait for a next block). If he is dead - you can bailout now (choose y).") + else: + print("Current game state:") + print("Game txid: " + extraction_info["gametxid"]) + print("Information about game saved on chain: " + extraction_info["extracted"]) + print("\n") + is_bailout_needed = input( + "Do you want to make bailout now [y] or wait for one more block [n]? [y/n]: ") + if is_bailout_needed == "y": + if game_info["alive"] > 1: + bailout_info = rogue_bailout(rpc_connection, new_game_txid) + try: + bailout_txid = bailout_info["txid"] + print(bailout_info) + print("\nGame is finished!\n") + input("Press [Enter] to continue...") + break + except Exception: + highlander_info = rogue_highlander(rpc_connection, new_game_txid) + highlander_info = highlander_info["txid"] + print(highlander_info) + print("\nGame is finished!\n") + input("Press [Enter] to continue...") + break + else: + highlander_info = rogue_highlander(rpc_connection, new_game_txid) + if 'error' in highlander_info.keys() and highlander_info["error"] == 'numplayers != maxplayers': + bailout_info = rogue_bailout(rpc_connection, new_game_txid) + print(bailout_info) + print("\nGame is finished!\n") + input("Press [Enter] to continue...") + break + else: + print(highlander_info) + print("\nGame is finished!\n") + input("Press [Enter] to continue...") + break + elif is_bailout_needed == "n": + game_end_height = int(rpc_connection.getinfo()["blocks"]) + while True: + current_height = int(rpc_connection.getinfo()["blocks"]) + height_difference = current_height - game_end_height + if height_difference == 0: + print(current_height) + print(game_end_height) + print(colorize("Waiting for next block before bailout", "blue")) + time.sleep(5) + else: + break + break + break + if start_game == "n": + print("As you wish!") + input("Press [Enter] to continue...") + break + else: + print(colorize("Choose y or n!", "red")) + + +def rogue_newgame_multiplayer(rpc_connection): + while True: + max_players = input("Input game max. players (>1): ") + if int(max_players) > 1: + break + else: + print("Please re-check your input") + input("Press [Enter] to continue...") + while True: + buyin = input("Input game buyin (>0.001): ") + if float(buyin) > 0.001: + break + else: + print("Please re-check your input") + input("Press [Enter] to continue...") + try: + new_game_txid = rpc_connection.cclib("newgame", "17", '"[' + max_players + "," + buyin + ']"')["txid"] + print(colorize("New multiplayer game succesfully created. txid: " + new_game_txid, "green")) + input("Press [Enter] to continue...") + except Exception as e: + print("Something went wrong.") + print(e) + input("Press [Enter] to continue...") + + +def rogue_join_multiplayer_game(rpc_connection): + while True: + try: + print_multiplayer_games_list(rpc_connection) + # TODO: optional player data txid (print players you have and ask if you want to choose one) + game_txid = input("Input txid of game you want to join: ") + try: + while True: + print_players_list(rpc_connection) + is_choice_needed = input("Do you want to choose a player for this game? [y/n] ") + if is_choice_needed == "y": + player_txid = input("Please input player txid: ") + newgame_regisration_txid = rogue_game_register(rpc_connection, game_txid, player_txid)["txid"] + break + elif is_choice_needed == "n": + set_warriors_name(rpc_connection) + newgame_regisration_txid = rogue_game_register(rpc_connection, game_txid)["txid"] + break + else: + print("Please choose y or n !") + except Exception as e: + print("Something went wrong. Maybe you're trying to register on game twice or don't have enough funds to pay buyin.") + print(e) + input("Press [Enter] to continue...") + break + print(colorize("Succesfully registered.", "green")) + while True: + mempool = rpc_connection.getrawmempool() + if newgame_regisration_txid in mempool: + print(colorize("Waiting for registration transaction to be mined", "blue")) + time.sleep(5) + else: + print(colorize("Registration transaction is mined", "green")) + break + print(newgame_regisration_txid) + input("Press [Enter] to continue...") + break + except KeyboardInterrupt: + break + + +def print_players_list(rpc_connection): + players_list = rogue_players_list(rpc_connection) + print(colorize("\nYou own " + str(players_list["numplayerdata"]) + " warriors\n", "blue")) + warrior_counter = 0 + for player in players_list["playerdata"]: + warrior_counter = warrior_counter + 1 + player_data = rogue_player_info(rpc_connection, player)["player"] + print(colorize("\n================================\n","green")) + print("Warrior " + str(warrior_counter)) + print("Name: " + player_data["pname"] + "\n") + print("Player txid: " + player_data["playertxid"]) + print("Token txid: " + player_data["tokenid"]) + print("Hitpoints: " + str(player_data["hitpoints"])) + print("Strength: " + str(player_data["strength"])) + print("Level: " + str(player_data["level"])) + print("Experience: " + str(player_data["experience"])) + print("Dungeon Level: " + str(player_data["dungeonlevel"])) + print("Chain: " + player_data["chain"]) + print(colorize("\nInventory:\n","blue")) + for item in player_data["pack"]: + print(item) + print("\nTotal packsize: " + str(player_data["packsize"]) + "\n") + input("Press [Enter] to continue...") + + +def sell_warrior(rpc_connection): + print(colorize("Your brave warriors: \n", "blue")) + print_players_list(rpc_connection) + print("\n") + while True: + need_sell = input("Do you want to place order to sell any? [y/n]: ") + if need_sell == "y": + playertxid = input("Input playertxid of warrior you want to sell: ") + price = input("Input price (in ROGUE coins) you want to sell warrior for: ") + try: + tokenid = rogue_player_info(rpc_connection, playertxid)["player"]["tokenid"] + except Exception as e: + print(e) + print("Something went wrong. Be careful with input next time.") + input("Press [Enter] to continue...") + break + token_ask_raw = rpc_connection.tokenask("1", tokenid, price) + try: + token_ask_txid = rpc_connection.sendrawtransaction(token_ask_raw["hex"]) + except Exception as e: + print(e) + print(token_ask_raw) + print("Something went wrong. Be careful with input next time.") + input("Press [Enter] to continue...") + break + print(colorize("Ask succesfully placed. Ask txid is: " + token_ask_txid, "green")) + input("Press [Enter] to continue...") + break + if need_sell == "n": + print("As you wish!") + input("Press [Enter] to continue...") + break + else: + print(colorize("Choose y or n!", "red")) + + +#TODO: have to combine into single scanner with different cases +def is_warrior_alive(rpc_connection, warrior_txid): + warrior_alive = False + raw_transaction = rpc_connection.getrawtransaction(warrior_txid, 1) + for vout in raw_transaction["vout"]: + if vout["value"] == 0.00000001 and rpc_connection.gettxout(raw_transaction["txid"], vout["n"]): + warrior_alive = True + return warrior_alive + + +def warriors_scanner(rpc_connection): + start_time = time.time() + token_list = rpc_connection.tokenlist() + my_warriors_list = rogue_players_list(rpc_connection) + warriors_list = {} + for token in token_list: + player_info = rogue_player_info(rpc_connection, token) + if "status" in player_info and player_info["status"] == "error": + pass + elif player_info["player"]["playertxid"] in my_warriors_list["playerdata"]: + pass + elif not is_warrior_alive(rpc_connection, player_info["player"]["playertxid"]): + pass + else: + warriors_list[token] = player_info["player"] + print("--- %s seconds ---" % (time.time() - start_time)) + return warriors_list + + +def warriors_scanner_for_rating(rpc_connection): + print("It can take some time") + token_list = rpc_connection.tokenlist() + my_warriors_list = rogue_players_list(rpc_connection) + actual_playerids = [] + warriors_list = {} + for token in token_list: + player_info = rogue_player_info(rpc_connection, token) + if "status" in player_info and player_info["status"] == "error": + pass + else: + while True: + if "batontxid" in player_info["player"].keys(): + player_info = rogue_player_info(rpc_connection, player_info["player"]["batontxid"]) + else: + actual_playerids.append(player_info["player"]["playertxid"]) + break + for player_id in actual_playerids: + player_info = rogue_player_info(rpc_connection, player_id) + if not is_warrior_alive(rpc_connection, player_info["player"]["playertxid"]): + pass + else: + warriors_list[player_id] = player_info["player"] + return warriors_list + + +def warriors_scanner_for_dex(rpc_connection): + start_time = time.time() + token_list = rpc_connection.tokenlist() + my_warriors_list = rogue_players_list(rpc_connection) + warriors_list = {} + for token in token_list: + player_info = rogue_player_info(rpc_connection, token) + if "status" in player_info and player_info["status"] == "error": + pass + elif player_info["player"]["tokenid"] in my_warriors_list["playerdata"]: + pass + else: + warriors_list[token] = player_info["player"] + print("--- %s seconds ---" % (time.time() - start_time)) + return warriors_list + + +def print_warrior_list(rpc_connection): + players_list = warriors_scanner(rpc_connection) + print(colorize("All warriors on ROGUE chain: \n", "blue")) + warrior_counter = 0 + for player in players_list: + warrior_counter = warrior_counter + 1 + player_data = rogue_player_info(rpc_connection, player)["player"] + print(colorize("\n================================\n","green")) + print("Warrior " + str(warrior_counter)) + print("Name: " + player_data["pname"] + "\n") + print("Player txid: " + player_data["playertxid"]) + print("Token txid: " + player_data["tokenid"]) + print("Hitpoints: " + str(player_data["hitpoints"])) + print("Strength: " + str(player_data["strength"])) + print("Level: " + str(player_data["level"])) + print("Experience: " + str(player_data["experience"])) + print("Dungeon Level: " + str(player_data["dungeonlevel"])) + print("Chain: " + player_data["chain"]) + print(colorize("\nInventory:\n","blue")) + for item in player_data["pack"]: + print(item) + print("\nTotal packsize: " + str(player_data["packsize"]) + "\n") + input("Press [Enter] to continue...") + + +def place_bid_on_warriror(rpc_connection): + warriors_list = print_warrior_list(rpc_connection) + # TODO: have to drop my warriors or at least print my warriors ids + while True: + need_buy = input("Do you want to place order to buy some warrior? [y/n]: ") + if need_buy == "y": + playertxid = input("Input playertxid of warrior you want to place bid for: ") + price = input("Input price (in ROGUE coins) you want to buy warrior for: ") + tokenid = rogue_player_info(rpc_connection, playertxid)["player"]["tokenid"] + token_bid_raw = rpc_connection.tokenbid("1", tokenid, price) + try: + token_bid_txid = rpc_connection.sendrawtransaction(token_bid_raw["hex"]) + except Exception as e: + print(e) + print(token_bid_raw) + print("Something went wrong. Be careful with input next time.") + input("Press [Enter] to continue...") + break + print(colorize("Bid succesfully placed. Bid txid is: " + token_bid_txid, "green")) + input("Press [Enter] to continue...") + break + if need_buy == "n": + print("As you wish!") + input("Press [Enter] to continue...") + break + else: + print(colorize("Choose y or n!", "red")) + + +def check_incoming_bids(rpc_connection): + # TODO: have to scan for warriors which are in asks as well + players_list = rogue_players_list(rpc_connection) + incoming_orders = [] + for player in players_list["playerdata"]: + token_id = rogue_player_info(rpc_connection, player)["player"]["tokenid"] + orders = rpc_connection.tokenorders(token_id) + if len(orders) > 0: + for order in orders: + if order["funcid"] == "b": + incoming_orders.append(order) + return incoming_orders + + +def print_icoming_bids(rpc_connection): + incoming_bids = check_incoming_bids(rpc_connection) + for bid in incoming_bids: + print("Recieved bid for warrior " + bid["tokenid"]) + player_data = rogue_player_info(rpc_connection, bid["tokenid"])["player"] + print(colorize("\n================================\n", "green")) + print("Name: " + player_data["pname"] + "\n") + print("Player txid: " + player_data["playertxid"]) + print("Token txid: " + player_data["tokenid"]) + print("Hitpoints: " + str(player_data["hitpoints"])) + print("Strength: " + str(player_data["strength"])) + print("Level: " + str(player_data["level"])) + print("Experience: " + str(player_data["experience"])) + print("Dungeon Level: " + str(player_data["dungeonlevel"])) + print("Chain: " + player_data["chain"]) + print(colorize("\nInventory:\n", "blue")) + for item in player_data["pack"]: + print(item) + print("\nTotal packsize: " + str(player_data["packsize"]) + "\n") + print(colorize("\n================================\n", "blue")) + print("Order info: \n") + print("Bid txid: " + bid["txid"]) + print("Price: " + str(bid["price"]) + "\n") + if len(incoming_bids) == 0: + print(colorize("There is no any incoming orders!", "blue")) + input("Press [Enter] to continue...") + else: + while True: + want_to_sell = input("Do you want to fill any incoming bid? [y/n]: ") + if want_to_sell == "y": + bid_txid = input("Input bid txid you want to fill: ") + for bid in incoming_bids: + if bid_txid == bid["txid"]: + tokenid = bid["tokenid"] + fill_sum = bid["totalrequired"] + fillbid_hex = rpc_connection.tokenfillbid(tokenid, bid_txid, str(fill_sum)) + try: + fillbid_txid = rpc_connection.sendrawtransaction(fillbid_hex["hex"]) + except Exception as e: + print(e) + print(fillbid_hex) + print("Something went wrong. Be careful with input next time.") + input("Press [Enter] to continue...") + break + print(colorize("Warrior succesfully sold. Txid is: " + fillbid_txid, "green")) + input("Press [Enter] to continue...") + break + if want_to_sell == "n": + print("As you wish!") + input("Press [Enter] to continue...") + break + else: + print(colorize("Choose y or n!", "red")) + + +def find_warriors_asks(rpc_connection): + warriors_list = warriors_scanner_for_dex(rpc_connection) + warriors_asks = [] + for player in warriors_list: + orders = rpc_connection.tokenorders(player) + if len(orders) > 0: + for order in orders: + if order["funcid"] == "s": + warriors_asks.append(order) + for ask in warriors_asks: + print(colorize("\n================================\n", "green")) + print("Warrior selling on marketplace: " + ask["tokenid"]) + player_data = rogue_player_info(rpc_connection, ask["tokenid"])["player"] + print("Name: " + player_data["pname"] + "\n") + print("Player txid: " + player_data["playertxid"]) + print("Token txid: " + player_data["tokenid"]) + print("Hitpoints: " + str(player_data["hitpoints"])) + print("Strength: " + str(player_data["strength"])) + print("Level: " + str(player_data["level"])) + print("Experience: " + str(player_data["experience"])) + print("Dungeon Level: " + str(player_data["dungeonlevel"])) + print("Chain: " + player_data["chain"]) + print(colorize("\nInventory:\n", "blue")) + for item in player_data["pack"]: + print(item) + print("\nTotal packsize: " + str(player_data["packsize"]) + "\n") + print(colorize("Order info: \n", "red")) + print("Ask txid: " + ask["txid"]) + print("Price: " + str(ask["price"]) + "\n") + while True: + want_to_buy = input("Do you want to buy any warrior? [y/n]: ") + if want_to_buy == "y": + ask_txid = input("Input asktxid which you want to fill: ") + for ask in warriors_asks: + if ask_txid == ask["txid"]: + tokenid = ask["tokenid"] + try: + fillask_raw = rpc_connection.tokenfillask(tokenid, ask_txid, "1") + except Exception as e: + print("Something went wrong. Be careful with input next time.") + input("Press [Enter] to continue...") + break + try: + fillask_txid = rpc_connection.sendrawtransaction(fillask_raw["hex"]) + except Exception as e: + print(e) + print(fillask_raw) + print("Something went wrong. Be careful with input next time.") + input("Press [Enter] to continue...") + break + print(colorize("Warrior succesfully bought. Txid is: " + fillask_txid, "green")) + input("Press [Enter] to continue...") + break + if want_to_buy == "n": + print("As you wish!") + input("Press [Enter] to continue...") + break + else: + print(colorize("Choose y or n!", "red")) + + +def warriors_orders_check(rpc_connection): + my_orders_list = rpc_connection.mytokenorders("17") + warriors_orders = {} + for order in my_orders_list: + player_info = rogue_player_info(rpc_connection, order["tokenid"]) + if "status" in player_info and player_info["status"] == "error": + pass + else: + warriors_orders[order["tokenid"]] = order + bids_list = [] + asks_list = [] + for order in warriors_orders: + if warriors_orders[order]["funcid"] == "s": + asks_list.append(warriors_orders[order]) + else: + bids_list.append(order) + print(colorize("\nYour asks:\n", "blue")) + print(colorize("\n********************************\n", "red")) + for ask in asks_list: + print("txid: " + ask["txid"]) + print("Price: " + ask["price"]) + print("Warrior tokenid: " + ask["tokenid"]) + print(colorize("\n================================\n", "green")) + print("Warrior selling on marketplace: " + ask["tokenid"]) + player_data = rogue_player_info(rpc_connection, ask["tokenid"])["player"] + print("Name: " + player_data["pname"] + "\n") + print("Player txid: " + player_data["playertxid"]) + print("Token txid: " + player_data["tokenid"]) + print("Hitpoints: " + str(player_data["hitpoints"])) + print("Strength: " + str(player_data["strength"])) + print("Level: " + str(player_data["level"])) + print("Experience: " + str(player_data["experience"])) + print("Dungeon Level: " + str(player_data["dungeonlevel"])) + print("Chain: " + player_data["chain"]) + print(colorize("\nInventory:\n", "blue")) + for item in player_data["pack"]: + print(item) + print("\nTotal packsize: " + str(player_data["packsize"]) + "\n") + print(colorize("\n================================\n", "green")) + print(colorize("\nYour bids:\n", "blue")) + print(colorize("\n********************************\n", "red")) + for bid in bids_list: + print("txid: " + bid["txid"]) + print("Price: " + bid["price"]) + print("Warrior tokenid: " + bid["tokenid"]) + print(colorize("\n================================\n", "green")) + print("Warrior selling on marketplace: " + bid["tokenid"]) + player_data = rogue_player_info(rpc_connection, bid["tokenid"])["player"] + print("Name: " + player_data["pname"] + "\n") + print("Player txid: " + player_data["playertxid"]) + print("Token txid: " + player_data["tokenid"]) + print("Hitpoints: " + str(player_data["hitpoints"])) + print("Strength: " + str(player_data["strength"])) + print("Level: " + str(player_data["level"])) + print("Experience: " + str(player_data["experience"])) + print("Dungeon Level: " + str(player_data["dungeonlevel"])) + print("Chain: " + player_data["chain"]) + print(colorize("\nInventory:\n", "blue")) + for item in player_data["pack"]: + print(item) + print("\nTotal packsize: " + str(player_data["packsize"]) + "\n") + print(colorize("\n================================\n", "green")) + while True: + need_order_change = input("Do you want to cancel any of your orders? [y/n]: ") + if need_order_change == "y": + while True: + ask_or_bid = input("Do you want cancel ask or bid? [a/b]: ") + if ask_or_bid == "a": + ask_txid = input("Input txid of ask you want to cancel: ") + warrior_tokenid = input("Input warrior token id for this ask: ") + try: + ask_cancellation_hex = rpc_connection.tokencancelask(warrior_tokenid, ask_txid) + ask_cancellation_txid = rpc_connection.sendrawtransaction(ask_cancellation_hex["hex"]) + except Exception as e: + print(colorize("Please re-check your input!", "red")) + print(colorize("Ask succefully cancelled. Cancellation txid: " + ask_cancellation_txid, "green")) + break + if ask_or_bid == "b": + bid_txid = input("Input txid of bid you want to cancel: ") + warrior_tokenid = input("Input warrior token id for this bid: ") + try: + bid_cancellation_hex = rpc_connection.tokencancelbid(warrior_tokenid, bid_txid) + bid_cancellation_txid = rpc_connection.sendrawtransaction(bid_cancellation_hex["hex"]) + except Exception as e: + print(colorize("Please re-check your input!", "red")) + print(colorize("Bid succefully cancelled. Cancellation txid: " + bid_cancellation_txid, "green")) + break + else: + print(colorize("Choose a or b!", "red")) + input("Press [Enter] to continue...") + break + if need_order_change == "n": + print("As you wish!") + input("Press [Enter] to continue...") + break + else: + print(colorize("Choose y or n!", "red")) + + +def set_warriors_name(rpc_connection): + warriors_name = input("What warrior name do you want for legends and tales about your brave adventures?: ") + warrior_name_arg = '"' + "[%22" + warriors_name + "%22]" + '"' + set_name_status = rpc_connection.cclib("setname", "17", warrior_name_arg) + print(colorize("Warrior name succesfully set", "green")) + print("Result: " + set_name_status["result"]) + print("Name: " + set_name_status["pname"]) + input("Press [Enter] to continue...") + + +def top_warriors_rating(rpc_connection): + start_time = time.time() + warriors_list = warriors_scanner_for_rating(rpc_connection) + warriors_exp = {} + for warrior in warriors_list: + warriors_exp[warrior] = warriors_list[warrior]["experience"] + warriors_exp_sorted = {} + temp = [(k, warriors_exp[k]) for k in sorted(warriors_exp, key=warriors_exp.get, reverse=True)] + for k,v in temp: + warriors_exp_sorted[k] = v + counter = 0 + for experienced_warrior in warriors_exp_sorted: + if counter < 20: + counter = counter + 1 + print("\n" + str(counter) + " place.") + print(colorize("\n================================\n", "blue")) + player_data = rogue_player_info(rpc_connection, experienced_warrior)["player"] + print("Name: " + player_data["pname"] + "\n") + print("Player txid: " + player_data["playertxid"]) + print("Token txid: " + player_data["tokenid"]) + print("Hitpoints: " + str(player_data["hitpoints"])) + print("Strength: " + str(player_data["strength"])) + print("Level: " + str(player_data["level"])) + print("Experience: " + str(player_data["experience"])) + print("Dungeon Level: " + str(player_data["dungeonlevel"])) + print("Chain: " + player_data["chain"]) + print("--- %s seconds ---" % (time.time() - start_time)) + input("Press [Enter] to continue...") + + +def exit(): + sys.exit() + + +def warrior_trasnfer(rpc_connection): + print(colorize("Your brave warriors: \n", "blue")) + print_players_list(rpc_connection) + print("\n") + while True: + need_transfer = input("Do you want to transfer any warrior? [y/n]: ") + if need_transfer == "y": + warrior_tokenid = input("Input warrior tokenid: ") + recepient_pubkey = input("Input recepient pubkey: ") + try: + token_transfer_hex = rpc_connection.tokentransfer(warrior_tokenid, recepient_pubkey, "1") + token_transfer_txid = rpc_connection.sendrawtransaction(token_transfer_hex["hex"]) + except Exception as e: + print(e) + print("Something went wrong. Please be careful with your input next time!") + input("Press [Enter] to continue...") + break + print(colorize("Warrior succesfully transferred! Transfer txid: " + token_transfer_txid, "green")) + input("Press [Enter] to continue...") + break + if need_transfer == "n": + print("As you wish!") + input("Press [Enter] to continue...") + break + else: + print(colorize("Choose y or n!", "red")) + + +def check_if_config_is_here(rpc_connection, assetchain_name): + config_name = assetchain_name + ".conf" + if os.path.exists(config_name): + print(colorize("Config is already in daemon folder", "green")) + else: + if operating_system == 'Darwin': + path_to_config = os.environ['HOME'] + '/Library/Application Support/Komodo/' + assetchain_name + '/' + config_name + elif operating_system == 'Linux': + path_to_config = os.environ['HOME'] + '/.komodo/' + assetchain_name + '/' + config_name + elif operating_system == 'Win64' or operating_system == 'Windows': + path_to_config = '%s/komodo/' + assetchain_name + '/' + config_name % os.environ['APPDATA'] + try: + copy(path_to_config, os.getcwd()) + except Exception as e: + print(e) + print("Can't copy config to current daemon directory automatically by some reason.") + print("Please copy it manually. It's locating here: " + path_to_config) + + +def find_game_keystrokes_in_log(gametxid): + + operating_system = platform.system() + if operating_system == 'Win64' or operating_system == 'Windows': + p1 = subprocess.Popen(["type", "keystrokes.log"], stdout=subprocess.PIPE, shell=True) + p2 = subprocess.Popen(["findstr", gametxid], stdin=p1.stdout, stdout=subprocess.PIPE, shell=True) + else: + p1 = subprocess.Popen(["cat", "keystrokes.log"], stdout=subprocess.PIPE) + p2 = subprocess.Popen(["grep", gametxid], stdin=p1.stdout, stdout=subprocess.PIPE) + p1.stdout.close() + output = p2.communicate()[0] + keystrokes_log_for_game = bytes.decode(output).split("\n") + return keystrokes_log_for_game + + +def check_if_tx_in_mempool(rpc_connection, txid): + while True: + mempool = rpc_connection.getrawmempool() + if txid in mempool: + print(colorize("Waiting for " + txid + " transaction to be mined", "blue")) + time.sleep(5) + else: + print(colorize("Transaction is mined", "green")) + break diff --git a/src/tui/requirements.txt b/src/tui/requirements.txt new file mode 100644 index 000000000..734da529c --- /dev/null +++ b/src/tui/requirements.txt @@ -0,0 +1,8 @@ +configobj==5.0.6 +pip==9.0.1 +pycurl==7.43.0.2 +setuptools==39.0.1 +six==1.12.0 +slick-bitcoinrpc==0.1.4 +ujson==1.35 +wheel==0.32.3 diff --git a/src/tui/tui_assets.py b/src/tui/tui_assets.py new file mode 100755 index 000000000..091484a40 --- /dev/null +++ b/src/tui/tui_assets.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 + +from lib import rpclib, tuilib +import os +import time + + +header = "\ + ___ _ _____ \n\ + / _ \ | | / __ \\\n\ +/ /_\ \ ___ ___ ___ | |_ ___ | / \/\n\ +| _ |/ __|/ __| / _ \| __|/ __|| | \n\ +| | | |\__ \\\__ \| __/| |_ \__ \| \__/\\\n\ +\_| |_/|___/|___/ \___| \__||___/ \____/\n" + + +menuItems = [ + {"Check current connection": tuilib.getinfo_tui}, + {"Check mempool": tuilib.print_mempool}, + {"Print tokens list": tuilib.print_tokens_list}, + {"Check my tokens balances" : tuilib.print_tokens_balances}, + # transfer tokens (pre-print tokens balances) + {"Create token": tuilib.token_create_tui}, + # trading zone - pre-print token orders - possible to open order or fill existing one + {"Exit": exit} +] + + +def main(): + while True: + os.system('clear') + print(tuilib.colorize(header, 'pink')) + print(tuilib.colorize('CLI version 0.2 by Anton Lysakov\n', 'green')) + for item in menuItems: + print(tuilib.colorize("[" + str(menuItems.index(item)) + "] ", 'blue') + list(item.keys())[0]) + choice = input(">> ") + try: + if int(choice) < 0: + raise ValueError + # Call the matching function + if list(menuItems[int(choice)].keys())[0] == "Exit": + list(menuItems[int(choice)].values())[0]() + else: + list(menuItems[int(choice)].values())[0](rpc_connection) + except (ValueError, IndexError): + pass + + +if __name__ == "__main__": + while True: + try: + print(tuilib.colorize("Welcome to the GatewaysCC TUI!\n" + "Please provide asset chain RPC connection details for initialization", "blue")) + rpc_connection = tuilib.rpc_connection_tui() + rpclib.getinfo(rpc_connection) + except Exception: + print(tuilib.colorize("Cant connect to RPC! Please re-check credentials.", "pink")) + else: + print(tuilib.colorize("Succesfully connected!\n", "green")) + with (open("lib/logo.txt", "r")) as logo: + for line in logo: + print(line, end='') + time.sleep(0.04) + print("\n") + break + main() + diff --git a/src/tui/tui_gateways_creation.py b/src/tui/tui_gateways_creation.py new file mode 100755 index 000000000..7bb489c7f --- /dev/null +++ b/src/tui/tui_gateways_creation.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 + +from lib import rpclib, tuilib +import os +import time + +header = "\ + _____ _ _____ _____ \n\ +| __ \ | | / __ \/ __ \\\n\ +| | \/ __ _| |_ _____ ____ _ _ _ ___| / \/| / \/\n\ +| | __ / _` | __/ _ \ \ /\ / / _` | | | / __| | | | \n\ +| |_\ \ (_| | || __/\ V V / (_| | |_| \__ \ \__/\| \__/\\\n\ + \____/\__,_|\__\___| \_/\_/ \__,_|\__, |___/\____/ \____/\n\ + __/ | \n\ + |___/ \n" + + +menuItems = [ + {"Check current connection": tuilib.getinfo_tui}, + {"Check mempool": tuilib.print_mempool}, + {"Create token": tuilib.token_create_tui}, + {"Create oracle": tuilib.oracle_create_tui}, + {"Register as publisher for oracle": tuilib.oracle_register_tui}, + {"Subscribe on oracle (+UTXO generator)": tuilib.oracle_subscription_utxogen}, + {"Bind Gateway": tuilib.gateways_bind_tui}, + {"Exit": exit} +] + + +def main(): + while True: + os.system('clear') + print(tuilib.colorize(header, 'pink')) + print(tuilib.colorize('CLI version 0.2\n', 'green')) + for item in menuItems: + print(tuilib.colorize("[" + str(menuItems.index(item)) + "] ", 'blue') + list(item.keys())[0]) + choice = input(">> ") + try: + if int(choice) < 0: + raise ValueError + # Call the matching function + if list(menuItems[int(choice)].keys())[0] == "Exit": + list(menuItems[int(choice)].values())[0]() + else: + list(menuItems[int(choice)].values())[0](rpc_connection) + except (ValueError, IndexError): + pass + + +if __name__ == "__main__": + while True: + try: + print(tuilib.colorize("Welcome to the GatewaysCC TUI!\n" + "Please provide asset chain RPC connection details for initialization", "blue")) + rpc_connection = tuilib.rpc_connection_tui() + rpclib.getinfo(rpc_connection) + except Exception: + print(tuilib.colorize("Cant connect to RPC! Please re-check credentials.", "pink")) + else: + print(tuilib.colorize("Succesfully connected!\n", "green")) + with (open("lib/logo.txt", "r")) as logo: + for line in logo: + print(line, end='') + time.sleep(0.04) + print("\n") + break + main() diff --git a/src/tui/tui_gateways_usage.py b/src/tui/tui_gateways_usage.py new file mode 100755 index 000000000..0c989e3af --- /dev/null +++ b/src/tui/tui_gateways_usage.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 + +from lib import rpclib, tuilib +import os, time + +header = "\ + _____ _ _____ _____ \n\ +| __ \ | | / __ \/ __ \\\n\ +| | \/ __ _| |_ _____ ____ _ _ _ ___| / \/| / \/\n\ +| | __ / _` | __/ _ \ \ /\ / / _` | | | / __| | | | \n\ +| |_\ \ (_| | || __/\ V V / (_| | |_| \__ \ \__/\| \__/\\\n\ + \____/\__,_|\__\___| \_/\_/ \__,_|\__, |___/\____/ \____/\n\ + __/ | \n\ + |___/ \n" + +menuItems = [ + {"Check connection to assetchain": tuilib.getinfo_tui}, + {"Check assetchain mempool": tuilib.print_mempool}, + {"Check connection to KMD": tuilib.getinfo_tui}, + {"Connect to KMD daemon": tuilib.rpc_kmd_connection_tui}, + {"Send KMD gateway deposit transaction": tuilib.gateways_send_kmd}, + {"Execute gateways deposit": tuilib.gateways_deposit_tui}, + {"Execute gateways claim": tuilib.gateways_claim_tui}, + {"Execute gateways withdrawal": tuilib.gateways_withdrawal_tui}, + {"Exit": exit} +] + +def main(): + while True: + os.system('clear') + print(tuilib.colorize(header, 'pink')) + print(tuilib.colorize('CLI version 0.2\n', 'green')) + for item in menuItems: + print(tuilib.colorize("[" + str(menuItems.index(item)) + "] ", 'blue') + list(item.keys())[0]) + choice = input(">> ") + try: + if int(choice) < 0: + raise ValueError + # Call the matching function + if list(menuItems[int(choice)].keys())[0] == "Exit": + list(menuItems[int(choice)].values())[0]() + # We have to call KMD specific functions with connection to KMD daemon + elif list(menuItems[int(choice)].keys())[0] == "Connect to KMD daemon": + rpc_connection_kmd = list(menuItems[int(choice)].values())[0]() + elif list(menuItems[int(choice)].keys())[0] == "Check connection to KMD": + while True: + try: + list(menuItems[int(choice)].values())[0](rpc_connection_kmd) + break + except Exception as e: + print("Please connect to KMD daemon first!") + input("Press [Enter] to continue...") + break + elif list(menuItems[int(choice)].keys())[0] == "Send KMD gateway deposit transaction": + while True: + try: + list(menuItems[int(choice)].values())[0](rpc_connection_kmd) + break + except Exception as e: + print(e) + print("Please connect to KMD daemon first!") + input("Press [Enter] to continue...") + break + elif list(menuItems[int(choice)].keys())[0] == "Execute gateways deposit": + while True: + try: + list(menuItems[int(choice)].values())[0](rpc_connection, rpc_connection_kmd) + break + except Exception as e: + print(e) + print("Please connect to KMD daemon first!") + input("Press [Enter] to continue...") + break + else: + list(menuItems[int(choice)].values())[0](rpc_connection) + except (ValueError, IndexError): + pass + + +if __name__ == "__main__": + while True: + try: + print(tuilib.colorize("Welcome to the GatewaysCC TUI!\nPlease provide RPC connection details for initialization", "blue")) + rpc_connection = tuilib.rpc_connection_tui() + rpclib.getinfo(rpc_connection) + except Exception: + print(tuilib.colorize("Cant connect to RPC! Please re-check credentials.", "pink")) + else: + print(tuilib.colorize("Succesfully connected!\n", "green")) + with (open("lib/logo.txt", "r")) as logo: + for line in logo: + print(line, end='') + time.sleep(0.04) + print("\n") + break + main() diff --git a/src/tui/tui_marmara.py b/src/tui/tui_marmara.py new file mode 100755 index 000000000..cfe628890 --- /dev/null +++ b/src/tui/tui_marmara.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 + +from lib import rpclib, tuilib +import os +import time + + +header = "\ +___ ___ _____ _ _ _____ \n\ +| \/ | |_ _| | | |_ _|\n\ +| . . | __ _ _ __ _ __ ___ __ _ _ __ __ _ | | | | | | | |\n\ +| |\/| |/ _` | '__| '_ ` _ \ / _` | '__/ _` | | | | | | | | |\n\ +| | | | (_| | | | | | | | | (_| | | | (_| | | | | |_| |_| |_\n\ +\_| |_/\__,_|_| |_| |_| |_|\__,_|_| \__,_| \_/ \___/ \___/\n" + + +menuItems = [ + {"Check current connection": tuilib.getinfo_tui}, + {"Check mempool": tuilib.print_mempool}, + {"Check MARMARA info": tuilib.marmara_info_tui}, + {"Lock funds for MARMARA": tuilib.marmara_lock_tui}, + {"Request MARMARA cheque": tuilib.marmara_receive_tui}, + {"Issue MARMARA cheque": tuilib.marmara_issue_tui}, + {"Check credit loop status": tuilib.marmara_creditloop_tui}, + {"Settle MARMARA loop": tuilib.marmara_settlement_tui}, + {"Exit": exit} +] + + +def main(): + while True: + os.system('clear') + print(tuilib.colorize(header, 'pink')) + print(tuilib.colorize('CLI version 0.1\n', 'green')) + for item in menuItems: + print(tuilib.colorize("[" + str(menuItems.index(item)) + "] ", 'blue') + list(item.keys())[0]) + choice = input(">> ") + try: + if int(choice) < 0: + raise ValueError + # Call the matching function + if list(menuItems[int(choice)].keys())[0] == "Exit": + list(menuItems[int(choice)].values())[0]() + else: + list(menuItems[int(choice)].values())[0](rpc_connection) + except (ValueError, IndexError): + pass + + +if __name__ == "__main__": + while True: + chain = input("Input assetchain name (-ac_name= value) you want to work with: ") + try: + print(tuilib.colorize("Welcome to the MarmaraCC TUI!\n" + "Please provide asset chain RPC connection details for initialization", "blue")) + rpc_connection = tuilib.def_credentials(chain) + rpclib.getinfo(rpc_connection) + except Exception: + print(tuilib.colorize("Cant connect to RPC! Please re-check credentials.", "pink")) + else: + print(tuilib.colorize("Succesfully connected!\n", "green")) + with (open("lib/logo.txt", "r")) as logo: + for line in logo: + print(line, end='') + time.sleep(0.04) + print("\n") + break + main() diff --git a/src/tui/tui_oracles.py b/src/tui/tui_oracles.py new file mode 100755 index 000000000..fec874d35 --- /dev/null +++ b/src/tui/tui_oracles.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 + +from lib import rpclib, tuilib +import os +import time + +header = "\ + _____ _ _____ _____ \n\ +| _ | | | / __ \/ __ \\\n\ +| | | | _ __ __ _ ___ | | ___ ___ | / \/| / \/\n\ +| | | || '__| / _` | / __|| | / _ \/ __|| | | |\n\ +\ \_/ /| | | (_| || (__ | || __/\__ \| \__/\| \__/\\\n\ + \___/ |_| \__,_| \___||_| \___||___/ \____/ \____/\n" + +menuItems = [ + # TODO: Have to implement here native oracle file uploader / reader, should be dope + # TODO: data publisher / converter for different types + {"Check current connection": tuilib.getinfo_tui}, + {"Check mempool": tuilib.print_mempool}, + {"Create oracle": tuilib.oracle_create_tui}, + {"Register as publisher for oracle": tuilib.oracle_register_tui}, + {"Subscribe on oracle (+UTXO generator)": tuilib.oracle_subscription_utxogen}, + {"Upload file to oracle": tuilib.convert_file_oracle_D}, + {"Display list of files uploaded to this AC": tuilib.display_files_list}, + {"Download files from oracle": tuilib.files_downloader}, + {"Exit": exit} +] + + +def main(): + while True: + os.system('clear') + print(tuilib.colorize(header, 'pink')) + print(tuilib.colorize('CLI version 0.2 by Anton Lysakov\n', 'green')) + for item in menuItems: + print(tuilib.colorize("[" + str(menuItems.index(item)) + "] ", 'blue') + list(item.keys())[0]) + choice = input(">> ") + try: + if int(choice) < 0: + raise ValueError + # Call the matching function + if list(menuItems[int(choice)].keys())[0] == "Exit": + list(menuItems[int(choice)].values())[0]() + else: + list(menuItems[int(choice)].values())[0](rpc_connection) + except (ValueError, IndexError): + pass + + +if __name__ == "__main__": + while True: + try: + print(tuilib.colorize("Welcome to the GatewaysCC TUI!\n" + "Please provide asset chain RPC connection details for initialization", "blue")) + rpc_connection = tuilib.rpc_connection_tui() + rpclib.getinfo(rpc_connection) + except Exception: + print(tuilib.colorize("Cant connect to RPC! Please re-check credentials.", "pink")) + else: + print(tuilib.colorize("Succesfully connected!\n", "green")) + with (open("lib/logo.txt", "r")) as logo: + for line in logo: + print(line, end='') + time.sleep(0.04) + print("\n") + break + main() diff --git a/src/tui/tui_rogue.py b/src/tui/tui_rogue.py new file mode 100755 index 000000000..9942369e2 --- /dev/null +++ b/src/tui/tui_rogue.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 + +from lib import rpclib, tuilib +import os +import time +import sys +import platform + +header = "\ +______ _____ _____ \n\ +| ___ \ / __ \/ __ \\\n\ +| |_/ /___ __ _ _ _ ___| / \/| / \/\n\ +| // _ \ / _` | | | |/ _ \ | | |\n\ +| |\ \ (_) | (_| | |_| | __/ \__/\| \__/\\\n\ +\_| \_\___/ \__, |\__,_|\___|\____/ \____/\n\ + __/ |\n\ + |___/\n" + + +menuItems = [ + {"Check current connection": tuilib.getinfo_tui}, + {"Check mempool": tuilib.print_mempool}, + {"Check my warriors list": tuilib.print_players_list}, + {"Transfer warrior to other pubkey": tuilib.warrior_trasnfer}, + {"TOP-20 ROGUE Warriors": tuilib.top_warriors_rating}, + {"Set warriors name": tuilib.set_warriors_name}, + {"Start singleplayer training game (creating, registering and starting game)": tuilib.rogue_newgame_singleplayer}, + {"Create multiplayer game": tuilib.rogue_newgame_multiplayer}, + {"Join (register) multiplayer game": tuilib.rogue_join_multiplayer_game}, + {"Check my multiplayer games status / start": tuilib.play_multiplayer_game}, + {"Check if somebody wants to buy your warrior (incoming bids)": tuilib.print_icoming_bids}, + {"Place order to sell warrior": tuilib.sell_warrior}, + {"Place order to buy someones warrior": tuilib.place_bid_on_warriror}, + {"Check if somebody selling warrior": tuilib.find_warriors_asks}, + {"Check / cancel my warriors trade orders": tuilib.warriors_orders_check}, + # {"Manually exit the game (bailout)": "test"}, + # {"Manually claim ROGUE coins for game (highlander)": "test"}, + {"Exit": tuilib.exit} +] + +def main(): + while True: + operating_system = platform.system() + if operating_system != 'Win64' and operating_system != 'Windows': + os.system('clear') + else: + os.system('cls') + print(tuilib.colorize(header, 'pink')) + print(tuilib.colorize('TUI v0.0.3\n', 'green')) + menu_items_counter = 0 + for item in menuItems: + if menu_items_counter == 0: + print("\nUtility:\n") + menu_items_counter = menu_items_counter + 1 + print(tuilib.colorize("[" + str(menuItems.index(item)) + "] ", 'blue') + list(item.keys())[0]) + if menu_items_counter == 6: + print("\nNew singleplayer game:\n") + if menu_items_counter == 7: + print("\nMultiplayer games:\n") + if menu_items_counter == 10: + print("\nDEX features:\n") + choice = input(">> ") + try: + if int(choice) < 0: + raise ValueError + # Call the matching function + if list(menuItems[int(choice)].keys())[0] == "Exit": + list(menuItems[int(choice)].values())[0]() + else: + list(menuItems[int(choice)].values())[0](rpc_connection) + except (ValueError, IndexError): + pass + + +if __name__ == "__main__": + while True: + chain = "ROGUE" + try: + print(tuilib.colorize("Welcome to the RogueCC TUI!\n" + "Please provide asset chain RPC connection details for initialization", "blue")) + rpc_connection = tuilib.def_credentials(chain) + rpclib.getinfo(rpc_connection) + # waiting until chain is in sync + while True: + have_blocks = rpclib.getinfo(rpc_connection)["blocks"] + longest_chain = rpclib.getinfo(rpc_connection)["longestchain"] + if have_blocks != longest_chain: + print(tuilib.colorize("ROGUE not synced yet.", "red")) + print("Have " + str(have_blocks) + " from " + str(longest_chain) + " blocks") + time.sleep(5) + else: + print(tuilib.colorize("Chain is synced!", "green")) + break + # checking if pubkey is set and set valid if not + info = rpclib.getinfo(rpc_connection) + if "pubkey" in info.keys(): + print("Pubkey is already set") + else: + valid_address = rpc_connection.getaccountaddress("") + valid_pubkey = rpc_connection.validateaddress(valid_address)["pubkey"] + rpc_connection.setpubkey(valid_pubkey) + print(tuilib.colorize("Pubkey is succesfully set!", "green")) + # copy ROGUE config to current daemon directory if it's not here + tuilib.check_if_config_is_here(rpc_connection, "ROGUE") + except Exception: + print(tuilib.colorize("Cant connect to ROGUE daemon RPC! Please check if daemon is up.", "pink")) + tuilib.exit() + else: + print(tuilib.colorize("Succesfully connected!\n", "green")) + with (open("lib/logo.txt", "r")) as logo: + for line in logo: + print(line, end='') + time.sleep(0.04) + print("\n") + break + main() diff --git a/src/tui/tui_tetris.py b/src/tui/tui_tetris.py new file mode 100755 index 000000000..3c42d4daa --- /dev/null +++ b/src/tui/tui_tetris.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 + +from lib import rpclib, tuilib +import os +import time +import sys +import platform + +header = "\ + _____ _ _ ______\n\ +|_ _| | | (_) | _ \n\ + | | ___| |_ _ __ _ ___| | | |__ _ _ __ _ __\n\ + | |/ _ \ __| '__| / __| | | / _` | '_ \| '_ \\\n\ + | | __/ |_| | | \__ \ |/ / (_| | |_) | |_) |\n\ + \_/\___|\__|_| |_|___/___/ \__,_| .__/| .__/\n\ + | | | |\n\ + |_| |_|" + + +menuItems = [ + {"Check current connection": tuilib.getinfo_tui}, + {"Check mempool": tuilib.print_mempool}, + {"Start singleplayer tetris game (creating, registering and starting game)": tuilib.rogue_newgame_singleplayer}, + {"Exit": tuilib.exit} +] + + +def main(): + while True: + operating_system = platform.system() + if operating_system != 'Win64' and operating_system != 'Windows': + os.system('clear') + else: + os.system('cls') + print(tuilib.colorize(header, 'pink')) + print(tuilib.colorize('TUI v0.0.3\n', 'green')) + menu_items_counter = 0 + for item in menuItems: + print(tuilib.colorize("[" + str(menuItems.index(item)) + "] ", 'blue') + list(item.keys())[0]) + choice = input(">> ") + try: + if int(choice) < 0: + raise ValueError + # Call the matching function + if list(menuItems[int(choice)].keys())[0] == "Exit": + list(menuItems[int(choice)].values())[0]() + elif list(menuItems[int(choice)].keys())[0] == "Start singleplayer tetris game (creating, registering and starting game)": + list(menuItems[int(choice)].values())[0](rpc_connection, False) + else: + list(menuItems[int(choice)].values())[0](rpc_connection) + except (ValueError, IndexError): + pass + + +if __name__ == "__main__": + while True: + chain = "GTEST" + try: + print(tuilib.colorize("Welcome to the Tetris TUI!\n" + "Please provide asset chain RPC connection details for initialization", "blue")) + rpc_connection = tuilib.def_credentials(chain) + rpclib.getinfo(rpc_connection) + # waiting until chain is in sync + while True: + have_blocks = rpclib.getinfo(rpc_connection)["blocks"] + longest_chain = rpclib.getinfo(rpc_connection)["longestchain"] + if have_blocks != longest_chain: + print(tuilib.colorize("GTEST not synced yet.", "red")) + print("Have " + str(have_blocks) + " from " + str(longest_chain) + " blocks") + time.sleep(5) + else: + print(tuilib.colorize("Chain is synced!", "green")) + break + # checking if pubkey is set and set valid if not + info = rpclib.getinfo(rpc_connection) + if "pubkey" in info.keys(): + print("Pubkey is already set") + else: + valid_address = rpc_connection.getaccountaddress("") + valid_pubkey = rpc_connection.validateaddress(valid_address)["pubkey"] + rpc_connection.setpubkey(valid_pubkey) + print(tuilib.colorize("Pubkey is succesfully set!", "green")) + # copy ROGUE config to current daemon directory if it's not here + tuilib.check_if_config_is_here(rpc_connection, "GTEST") + except Exception: + print(tuilib.colorize("Cant connect to GTEST daemon RPC! Please check if daemon is up.", "pink")) + tuilib.exit() + else: + print(tuilib.colorize("Succesfully connected!\n", "green")) + with (open("lib/logo.txt", "r")) as logo: + for line in logo: + print(line, end='') + time.sleep(0.04) + print("\n") + break + main()