def dealTrans(self,data): """ 生成一个交易 :param data: 接收方,发送数量 :return: 生成交易是否成功 """ (dest, amount) = data trandb = Conlmdb("tranpool") source = Wallet().PublicKey fso = self.FindSpendableOutputs(source, amount) if fso: data = Transaction.Transaction().NewUTXOTransaction(source, dest, amount, fso) privkey = Wallet().PrivateKey stc = self.SignTransaction(data,privkey) trandb.put(stc.ID,PickleStr.toStr(stc)) with futures.ProcessPoolExecutor() as executor: result = executor.submit(TClient.rmain,stc.ID).result() if result: bd = Conlmdb("utxo") while not self.Keys.empty(): bd.delete(self.Keys.get()) # 更新数据库中的信息 return True else: trandb.delete(stc.ID) # 删除没有发送成功的交易,主要发生在没有网的时候,保证tranpool中没有无效的交易 return None
def __init__(self): self.wallet = Wallet() self.analyzer = 0 self.buyRequests = [] self.sellRequests = [] self.file = open(".bot.log", "w+") self.file.truncate()
def execute(self, response, client_connection, args): try: name = args['name'] key = args['key'] sha2 = hashlib.sha256() sha2.update(key.encode('ascii')) key = sha2.hexdigest() wallet_id = generate_wallet_id(name) w = Wallet(name, key, wallet_id) self.database.create_wallet(w) # self.central_authority_server.wallets.append(w) response['success'] = True response['wallet_id'] = wallet_id # generating aliases aliases = w.get_aliases(self.central_authority_server.aliases_per_wallet) self.database.add_wallet_aliases(w) self.database.add_wallet_balance(w) response['aliases'] = aliases print("New wallet created -> {0}".format(wallet_id)) except Exception as e: print("{0} exception : {1}".format(self.__class__, e))
def main(): args = parser.parse_args() csv_file = args.csv_file wallet = Wallet() wallet.import_csv(csv_file) # build filter dictionary filter_data = dict(item.split(':') for item in args.filter.split(',')) filtered_items = wallet.filter_items(filter_data=filter_data) wallet.print_items(filtered_items, summarize=args.summarize, sortby=args.sortby)
def __init__(self, network_info_dir = None): self.wallet_dir = None self.chain_dir = None self.node_type = 'miner' self.network_info_path = os.path.join(network_info_dir, 'network_info.json') if network_info_dir else os.path.join(os.getcwd(), 'network_info.json') self.get_network_info(self.network_info_path) self.wallet = Wallet(self.wallet_dir)
def __init__(self,ip,port,key=None): self.p2p=None self.ip=ip self.port=port self.transitionPool=TransactionPool() self.wallet=Wallet() self.blockChain=BlockChain() if key is not None: self.wallet.formKey(key)
def __init__(self, url, denominations, keysize=256): """Create an issuer""" self.keysize = keysize self.url = url self.mint = Mint.Mint(url, denominations, keysize) self.signed = {} self.pending = {} self.failed = {} #blind,reason self.redeemed = {} self.wallet = Wallet({self.url: self})
def creatblock(self): """ 创建创世区块 :param dest:自己的地址 :return: """ dest = Crypt.AtoPHK(Wallet().Address) tx = self.NewCoinbaseTX(dest) # 创世区块 block = Block(tx.getresult()) self.db.put(block.Headers.gethash(), str(block)) self.db.put("l", block.Headers.gethash()) block.getstring()
def __init__(self, minerID, relayPort, WalletPassword): """Init.""" self.ID = minerID self.myWalletPassword=WalletPassword self.myWallet = Wallet(relayPort,WalletPassword) self.relayPort = relayPort self.relayIP = "http://localhost:" + str(self.relayPort) self.blockTemplate = '' self.newBlock = '' self.TempTx = '' self.tryAgainWithSameBlock = 0 self.BlockChain = '' self.unspentTxs = [] self.mainTransaction=[]
def __init__(self): db = Conlmdb() self.db = Conlmdb("utxo") pubKeyHash = Wallet().PublicHashKey startip = self.db.get("l") if startip: self.db.delete("l") utxos = self.FindUTXOs(pubKeyHash,db,startip) for key,value in utxos.items(): self.db.put(key,value) self.db.put("l",self.tip) else: utxos = self.FindUTXOs(pubKeyHash,db) for key, value in utxos.items(): self.db.put(key, value) self.db.put("l", self.tip)
def check_for_more(self): """Method that checks for new coin wallets in the inbound wallet directory, also discards of any empty or encrypted wallets""" import os, shutil, time newWalletList = [] os.chdir(cnt.GOOD_WALLET_DIR + self.wizardName) newWalletListing = os.listdir(os.getcwd()) for x in range(0, len(newWalletListing)): if not (os.path.isdir(newWalletListing[x])): print(os.path.abspath(newWalletListing[x])) newWalletList.append( Wallet(os.path.basename(newWalletListing[x]), x, self.wizardPort, self.wizardName)) for x in range(0, len(newWalletList)): result = newWalletList[x].test_wallet() # Empty wallet if (result == 0): os.remove(newWalletList[x].walletPath) print("[LOG] EMPTY " + self.wizardTicker + " - " + newWalletList[x].walletPath + " DELETED") # Unlocked nonempty wallet elif (result == 1): shutil.copy(newWalletList[x].walletPath, self.WALLET_STORE) os.remove(newWalletList[x].walletPath) print("[LOG] GOOD " + str(newWalletList[x].walletBalance) + " " + self.wizardTicker + " - " + newWalletList[x].walletPath + " STORED") # Locked wallet elif (result == 2): shutil.copy( newWalletList[x].walletPath, cnt.LOCKED_WALLET_DIR + self.wizardName + "/" + newWalletList[x].walletPath) os.remove(newWalletList[x].walletPath) print("[LOG] LOCKED " + str(newWalletList[x].walletBalance) + " " + self.wizardTicker + " - " + newWalletList[x].walletPath + " MOVED")
def execute(self, response, client_connection, args): response["type"] = 'register_wallet' try: name = args['name'] key = args['key'] signature = args['signature'] # generating Id from key pub_key = RSA.importKey(key) sha2 = SHA256.new() sha2.update(pub_key.exportKey(format='DER')) wallet_id = sha2.hexdigest() existing_wallet = self.database.get_wallet_by_id(wallet_id) if existing_wallet is not None: response["error"] = "Wallet {0} already registered".format( wallet_id) return # verifying the signature signer = PKCS1_v1_5.new(pub_key) sign_bytes = bytes.fromhex(signature) if not signer.verify(sha2, sign_bytes): print("Invalid Signature for Wallet Id {0}".format(wallet_id)) response["error"] = "Invalid Signature" return w = Wallet(name, key, wallet_id) self.database.create_wallet(w) response['wallet_id'] = wallet_id self.database.add_wallet_balance(w) print("New wallet registered -> {0}".format(wallet_id)) except KeyError as e: response["error"] = "Missing argument(s)" except Exception as e: print("{0} exception : {1}".format(self.__class__, e))
def game(): print("\033[1;35;40m Welcome!!! \n") wallet = Wallet() while (input("\033[1;36;40m Play (y/n)?") == 'y'): bet = int(input( f"You have {wallet.currentValue}, how much would you like to bet?" )) while (bet > wallet.currentValue): bet = int(input( f"You have {wallet.currentValue}, but you bet {bet}, please do not enter more than you have!" )) result = play(wallet) if(result.humanHasWon): wallet.win(bet) else: wallet.loose(bet) print(result)
def addblock(self): """ 添加区块 data中含有 source:来源地址 dest:目的地址 amount:转账数量 """ #添加区块 db = Conlmdb("tranpool") mer = None tsize = db.dbsize() keys = []#存储正在被挖矿的交易 if tsize >= 5: dtrans = db.rawiter() trans = [] for key,value in dtrans.items(): keys.append(key) trans.append(PickleStr.toObj(value)) if value[:1] != b"U": db.set(key, b"U"+value) trans.append(self.mineTran("520",Wallet().Address)) mer = MerkleTree.Merkle(trans).getresult() if mer: block = Block(mer,self.db.get("l")) if POW().VailPow(block): self.db.put(block.Headers.gethash(), str(block)) self.db.delete("l") self.db.put("l", block.Headers.gethash()) for key in keys: #删除挖矿成功的交易 db.delete(key) else: pass else: pass
def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "ATCion钱包客户端")) self.label.setText(_translate("MainWindow", "账户地址")) self.label_2.setText(_translate("MainWindow", "转账数量")) self.pushButton.setText(_translate("MainWindow", "生成交易")) self.pushButton.clicked.connect(self.creatTran) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "交易生成")) self.label_3.setText(_translate("MainWindow", "开始同步区块")) self.groupBox.setTitle(_translate("MainWindow", "本机区块信息")) self.label_4.setText(_translate("MainWindow", "高度")) self.label_5.setText(_translate("MainWindow", "版本号")) self.label_6.setText(_translate("MainWindow", "地址")) #地址 self.textBrowser.setHtml( _translate( "MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'.SF NS Text\'; font-size:13pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#ffffff;\"><span style=\" font-family:\'Menlo\'; font-size:10.5pt; font-weight:600; color:#008080;\">" + Wallet().Address + "</span></p></body></html>")) #区块高度 self.textBrowser_2.setHtml( _translate( "MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'.SF NS Text\'; font-size:13pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#ffffff;\"><span style=\" font-family:\'Menlo\'; font-size:16pt; font-weight:600; color:#008080;\">" + str(self.db.dbsize()) + "</span></p></body></html>")) #版本号 self.textBrowser_3.setHtml( _translate( "MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'.SF NS Text\'; font-size:13pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#ffffff;\"><span style=\" font-family:\'Menlo\'; font-size:16pt; font-weight:600; color:#008080;\">" + Utils().blockversion + "-" + Utils().addrversion + "</span></p></body></html>")) #进度条显示 self.timer = QtCore.QBasicTimer() self.step = 0 self.timer.start(100, self) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "区块同步")) self.textBrowser_4.setHtml( _translate( "MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'.SF NS Text\'; font-size:13pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:18pt;\">帮助信息:</span></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1.本项目为ATCoin钱包客户端,使用前请注明来源。</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">2.相关资料获取可访问www.lcase.org。</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">3.如运行期间遇到问题,欢迎提bug至[email protected]。</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">4.本程序最终解释权归林型所有。</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:18pt;\">版本说明:</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> ATCoin-lx-1.0-01@linxing</p></body></html>" )) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "帮助"))
def walletCreate(wallet): w = wallet dbAcnt = Wallet(name=w['name'], description=w['description'], rateOfInterest=w['rateOfInterest']).save() print("Wallet", colored(dbAcnt.name), "created")
from Transaction import Transaction from Wallet import Wallet from BlockchainUtils import BlockchainUtils import requests if __name__ == '__main__': bob = Wallet() alice = Wallet() exchange = Wallet() transaction = exchange.createTransaction(alice.publicKeyString(), 10, 'EXCHANGE') url = 'http://localhost:5000/transaction' package = {'transaction': BlockchainUtils.encode(transaction)} request = requests.post(url, json=package) print(request.text)
def test(): """Test cases """ exampleWallet = generateSampleWallet(["Alice"]) pubKeyMap = exampleWallet.toPublicKeyMap() exampleMessage = Message() exampleMessage.addInteger(15) exampleSignature = exampleWallet.signMessage(exampleMessage, "Alice") ################################################################## # Task 5 # add to the test case the test as described in the lab sheet # # You can use the above exampleSignature, when a sample # signature is needed, which cannot be computed from the data. # ################################################################## print( " 5.1 Create a sample wallet for Alice containing keys with names A1, A2, for Bob containing keynames B1, B2, for Carol containing keynames C1, C2, C3, and for David containing keyname D1 by using the method generate of SampleWallet" ) Alicewallet = Wallet() Bobwallet = Wallet() Carolwallet = Wallet() Davidwallet = Wallet() Alicewallet = generateSampleWallet(["A1", "A2"]) Bobwallet = generateSampleWallet(["B1", "B2"]) Carolwallet = generateSampleWallet(["C1", "C2", "C3"]) Davidwallet = generateSampleWallet(["D1"]) print( "5.2 Compute the PublicKeyMap containing the public keys of all these wallets. The PublicKeyMap is for convenience, since comparing public keys is cumbersome." ) pubKeyMapa = Alicewallet.toPublicKeyMap() pubKeyMapb = Bobwallet.toPublicKeyMap() pubKeyMapc = Carolwallet.toPublicKeyMap() pubKeyMapd = Davidwallet.toPublicKeyMap() pubKeyMapabcd = PublicKeyMap() pubKeyMapabcd.addPublicKeyMap(pubKeyMapa) pubKeyMapabcd.addPublicKeyMap(pubKeyMapb) pubKeyMapabcd.addPublicKeyMap(pubKeyMapc) pubKeyMapabcd.addPublicKeyMap(pubKeyMapd) pubKeyA1 = pubKeyMapabcd.getPublicKey("A1") pubKeyA2 = pubKeyMapabcd.getPublicKey("A2") pubKeyB1 = pubKeyMapabcd.getPublicKey("B1") pubKeyB2 = pubKeyMapabcd.getPublicKey("B2") pubKeyC1 = pubKeyMapabcd.getPublicKey("C1") pubKeyC2 = pubKeyMapabcd.getPublicKey("C2") pubKeyC3 = pubKeyMapabcd.getPublicKey("C3") pubKeyD1 = pubKeyMapabcd.getPublicKey("D1") print( "– Create an empty AccountBalance and add to it the keynames of the wallets created before initialised with the amount 0 for each key" ) AccBal = AccountBalance() AccBal.addAccount(pubKeyA1, 0) AccBal.addAccount(pubKeyA2, 0) AccBal.addAccount(pubKeyB1, 0) AccBal.addAccount(pubKeyB2, 0) AccBal.addAccount(pubKeyC1, 0) AccBal.addAccount(pubKeyC2, 0) AccBal.addAccount(pubKeyC3, 0) AccBal.addAccount(pubKeyD1, 0) AccBal.print(pubKeyMapabcd) print("5.4Set the balance for A1 to 20") AccBal.setBalance(pubKeyA1, 20) AccBal.print(pubKeyMapabcd) print("5.5 Add 15 to the balance for B1") AccBal.addToBalance(pubKeyB1, 5) AccBal.print(pubKeyMapabcd) print("5.6 – Subtract 5 from the balance for B1") AccBal.subtractFromBalance(pubKeyB1, 5) AccBal.print(pubKeyMapabcd) print("5.7 Set the balance for C1 to 10.") AccBal.setBalance(pubKeyC1, 10) AccBal.print(pubKeyMapabcd) print( "5.8 Check whether the TxInputList txil1 giving A1 15 units, and B1 5 units (withsample signatures used) can be deducted." ) txiL1 = TxInputList() tx1 = (AccBal.checkTxInputListCanBeDeducted(txiL1)) txiL1 = TxInputList([ TxInput(pubKeyA1, 10, exampleSignature), TxInput(pubKeyB1, 5, exampleSignature) ]) print("can txil1 be deducted?? : ", AccBal.checkTxInputListCanBeDeducted(txiL1)) print( "5.9 – Check whether the TxInputList txil2 giving A1 15 units, and giving A1 again15 units can be deducted." ) txiL2 = TxInputList() txiL2 = TxInputList([ TxInput(pubKeyA1, 15, exampleSignature), TxInput(pubKeyA1, 15, exampleSignature) ]) tx1 = (AccBal.checkTxInputListCanBeDeducted(txiL2)) print("can txil1 be deducted?? : ", AccBal.checkTxInputListCanBeDeducted(txiL2)) print("6.0 Deduct txil1 from the AccountBalance") AccBal.subtractTxInputList(txiL1) AccBal.print(pubKeyMapabcd) print( "6.1Create a TxOutputList corresponding to txil2 which gives A1 twice 15 Units,and add it to the AccountBalance." ) txoL2 = TxOutputList() txoL2 = TxOutputList([TxOutput(pubKeyA1, 15), TxOutput(pubKeyA1, 15)]) AccBal.addTxOutputList(txoL2) AccBal.print(pubKeyMapabcd) print( "6.2 Create a correctly signed input, where A1 is spending 30, referring to an outputlist giving B2 10 and C1 20 The output list is needed in order to create the message to be signed(consisting of A1 spending 30, B1 receiving 10 and C1receiving 20). Check whether the signature is valid for this signed input." ) txoL3 = TxOutputList() txoL3 = TxOutputList([TxOutput(pubKeyB2, 10), TxOutput(pubKeyC1, 20)]) TIU = TxInputUnsigned(pubKeyA1, 30) message = TIU.getMessageToSign(txoL2) A1Signature = Alicewallet.signMessage(message, "A1") txiL3 = TxInputList() txiL3 = TxInputList([createTxInput("A1", 30, txoL3, Alicewallet)]) valid = txiL3.checkSignature(txoL3) print("Is the signature valid for signed input? : ", valid) print( "6.3Create a wrongly signed input, which gives A1 30, and uses instead of the correctly created signature an example signature (example signatures are provided in thecode). Check whether the signature is valid for this signed input." ) txisL4 = TxInputList() txisL4 = TxInputList([TxInput(pubKeyA1, 30, exampleSignature)]) valid_check = txisL4.checkSignature(txoL3) print("Is the signature valid for signed input? : " + str(valid_check)) print( "6.4 Create a transaction tx1 which takes as input for A1 35 units and gives B2 10, C2 10, and returns the change (whatever is left) to A2." ) TxOuLi = TxOutputList([ TxOutput(pubKeyB2, 10), TxOutput(pubKeyC2, 10), TxOutput(pubKeyA2, 15) ]) Tiu1 = TxInputList([createTxInput("A1", 35, TxOuLi, Alicewallet)]) #A1message = Tiu1.getMessageToSign(TxOuLi) #signA1 = Alicewallet.signMessage(A1message,"A1" ) #txiL5 = TxInputList(pubKeyA1,35,signA1) tx1 = Transaction(Tiu1, TxOuLi) #AccBal.print(pubKeyMapabcd) print( "6.5 Check whether the signature is approved for the transaction input, and whether the transaction is valid. Then update the AccountBalance using that transaction." ) if Tiu1.checkSignature(TxOuLi): print( "signature is approved transaction input and the transaction is valid" ) AccBal.processTransaction(tx1) print("Account balance updated") AccBal.print(pubKeyMapabcd) else: print("Transaction is invalid") print( "6.6 Create a transaction tx2 which takes as inputs from B2 10, C2 10, and as outputs given D1 15 and C3 the change (whatever is left) " ) TxOuLi1 = TxOutputList(pubKeyD1, 15, pubKeyC3, 5) Tiu2 = TxInputUnsigned(pubKeyB2, 10) B2message = Tiu2.getMessageToSign(TxOuLi1) signB2 = Bobwallet.signMessage(B2message, "B2") Tiu3 = TxInputUnsigned(pubKeyC2, 10) C2message = Tiu3.getMessageToSign(TxOuLi1) signC2 = Carolwallet.signMessage(C2message, "C2") txil6 = TxInputList(pubKeyB2, 10, signB2, pubKeyC2, 10, signC2) trx = Transaction(txil6, TxOuLi1) AccBal.print(pubKeyMapabcd) print( "6.7 Check whether the signature is approved for the transaction input, and whether the transaction is valid. Then update the AccountBalance using that transaction." ) if AccBal.checkTransactionValid(trx): print( "signature is approved transaction input and the transaction is valid" ) AccBal.processTransaction(trx) print("Account balance updated") AccBal.print(pubKeyMapabcd) else: print("Transaction is invalid")
def do_createWallet(self, args): """ ---> createWallet - создает новый кошелек <--- """ wal = Wallet() print('Ваш адрес: {}'.format(wal.getAddress()))
def traverse_tree(starting_wallet, starting_tx): wallets = [Wallet(starting_wallet)] t = tree() return t
from AutoTrader import AutoTrader from BackTester import BackTester from MovingAverageStrategy import MovingAverageStrategy from Wallet import Wallet btcFile = './PriceData/coinbaseUSD.csv' numTrades = 10000 startingTradeIndex = 200000 strategy = MovingAverageStrategy(1500, 3000) wallet = Wallet(500, 0) trader = AutoTrader(wallet, strategy) tester = BackTester(btcFile, startingTradeIndex, numTrades, trader, wallet) tradeHistory = tester.getPriceData(btcFile, numTrades, startingTradeIndex) tester.simulate(trader, tradeHistory) tester.printResults() tester.plotTrades()
def startTrading(self, btc, currencyPair, objective_gain, limit_loss, gain, loss): self.orderState = OrderState(currencyPair) self.wallet = Wallet(self.orderState.fromDigitalCurr, self.orderState.toDigitalCurr, btc) self.objective_gain = objective_gain self.limit_loss = limit_loss self.gain = gain self.initial_gain = gain self.loss = loss self.stop = False self.df['indexGain'] = 0 self.df['perGain'] = 0 self.df['buyValue'] = 0 self.df['sellValue'] = 0 self.df['gained'] = False self.df['Buy'] = 0 self.pre_setup_indicators(self.df) for i, row in self.df.iterrows(): if (i < len(self.df.index) - 1): self.getActualPrice(i) self.train_inidicators(i) if self.stop == False: if self.orderState.waitingForBuyOpportunity(): if self.reached_objective() or self.reached_limit_loss( ): self.stop = True self.df.loc[i, 'Buy'] = 5 self.df.loc[i, 'buyValue'] = self.orderState.buy_value self.df.loc[ i, 'sellValue'] = self.orderState.sell_value self.df.loc[i, 'btc'] = self.wallet.wallet[Wallet.BTC] self.df.loc[i, 'actualCurrency'] = self.wallet.wallet[ self.orderState.toDigitalCurr] self.df.loc[i, 'perGain'] = ( self.orderState.actual_price / self.orderState.buy_value - 1 ) * 100 if self.orderState.buy_value > 0 else 0 elif self.indicators_predict_buy(i): self.sendBuyOrder() self.orderState.setBuyOrderStatus(True) self.df.loc[i, 'Buy'] = 2 self.df.loc[i, 'buyValue'] = self.orderState.buy_value self.df.loc[ i, 'sellValue'] = self.orderState.sell_value self.df.loc[i, 'btc'] = self.wallet.wallet[Wallet.BTC] self.df.loc[i, 'actualCurrency'] = self.wallet.wallet[ self.orderState.toDigitalCurr] self.df.loc[i, 'perGain'] = ( self.orderState.actual_price / self.orderState.buy_value - 1 ) * 100 if self.orderState.buy_value > 0 else 0 if self.buyOrderWasExecuted(): self.getBuyPrice() self.orderState.setInBuyStatus() self.wallet.exchange( Wallet.BTC, self.orderState.toDigitalCurr, self.orderState.buy_value, self.marketExchange.getActiveBuyFeePerc()) self.df.loc[i, 'Buy'] = 1 self.df.loc[ i, 'buyValue'] = self.orderState.buy_value self.df.loc[ i, 'sellValue'] = self.orderState.sell_value self.df.loc[i, 'btc'] = self.wallet.wallet[ Wallet.BTC] self.df.loc[ i, 'actualCurrency'] = self.wallet.wallet[ self.orderState.toDigitalCurr] self.df.loc[i, 'perGain'] = ( self.orderState.actual_price / self.orderState.buy_value - 1) * 100 else: self.wait(i) elif self.orderState.waitingForBuyOrderToBeExecuted(): if self.buyOrderWasExecuted(): self.getBuyPrice() self.orderState.setInBuyStatus() self.wallet.exchange( Wallet.BTC, self.orderState.toDigitalCurr, self.orderState.buy_value, self.marketExchange.getActiveBuyFeePerc()) self.df.loc[i, 'Buy'] = 1 self.df.loc[i, 'buyValue'] = self.orderState.buy_value self.df.loc[ i, 'sellValue'] = self.orderState.sell_value self.df.loc[i, 'btc'] = self.wallet.wallet[Wallet.BTC] self.df.loc[i, 'actualCurrency'] = self.wallet.wallet[ self.orderState.toDigitalCurr] self.df.loc[i, 'perGain'] = ( self.orderState.actual_price / self.orderState.buy_value - 1) * 100 elif self.orderState.waitingForSellOpportunity(): if self.isGaining(): self.sendSellOrder(True) self.orderState.setSellOrderStatus(True) self.df.loc[i, 'Buy'] = 3 self.df.loc[i, 'buyValue'] = self.orderState.buy_value self.df.loc[ i, 'sellValue'] = self.orderState.sell_value self.df.loc[i, 'btc'] = self.wallet.wallet[Wallet.BTC] self.df.loc[i, 'actualCurrency'] = self.wallet.wallet[ self.orderState.toDigitalCurr] self.df.loc[i, 'perGain'] = ( self.orderState.actual_price / self.orderState.buy_value - 1) * 100 elif self.isLosing(): self.sendSellOrder(False) self.orderState.setSellOrderStatus(True) self.df.loc[i, 'Buy'] = 4 self.df.loc[i, 'buyValue'] = self.orderState.buy_value self.df.loc[ i, 'sellValue'] = self.orderState.sell_value self.df.loc[i, 'btc'] = self.wallet.wallet[Wallet.BTC] self.df.loc[i, 'actualCurrency'] = self.wallet.wallet[ self.orderState.toDigitalCurr] self.df.loc[i, 'perGain'] = ( self.orderState.actual_price / self.orderState.buy_value - 1) * 100 else: self.wait(i) elif self.orderState.waitingForSellOrderToBeExecuted(): if self.sellOrderWasExecuted(): self.getSellPrice() self.orderState.setSoldStatus() self.wallet.exchange( self.orderState.toDigitalCurr, self.orderState.fromDigitalCurr, self.orderState.sell_value, self.marketExchange.getActiveSellFeePerc()) self.df.loc[i, 'Buy'] = 0 self.df.loc[i, 'buyValue'] = self.orderState.buy_value self.df.loc[ i, 'sellValue'] = self.orderState.sell_value self.df.loc[i, 'btc'] = self.wallet.wallet[ self.orderState.fromDigitalCurr] self.df.loc[i, 'actualCurrency'] = self.wallet.wallet[ self.orderState.toDigitalCurr] self.df.loc[i, 'perGain'] = ( self.orderState.sell_value / self.orderState.buy_value - 1) * 100 self.df.loc[i, 'gained'] = True self.wallet.transferToPiggy() self.orderState.resetValues() elif self.isGaining(): self.sendSellOrder(True) self.orderState.setSellOrderStatus(True) self.df.loc[i, 'Buy'] = 3 self.df.loc[i, 'buyValue'] = self.orderState.buy_value self.df.loc[ i, 'sellValue'] = self.orderState.sell_value self.df.loc[i, 'btc'] = self.wallet.wallet[Wallet.BTC] self.df.loc[i, 'actualCurrency'] = self.wallet.wallet[ self.orderState.toDigitalCurr] self.df.loc[i, 'perGain'] = ( self.orderState.actual_price / self.orderState.buy_value - 1) * 100 elif self.isLosing(): self.sendSellOrder(False) self.orderState.setSellOrderStatus(True) self.df.loc[i, 'Buy'] = 4 self.df.loc[i, 'buyValue'] = self.orderState.buy_value self.df.loc[ i, 'sellValue'] = self.orderState.sell_value self.df.loc[i, 'btc'] = self.wallet.wallet[Wallet.BTC] self.df.loc[i, 'actualCurrency'] = self.wallet.wallet[ self.orderState.toDigitalCurr] self.df.loc[i, 'perGain'] = ( self.orderState.actual_price / self.orderState.buy_value - 1) * 100 else: self.wait(i) if self.botConfig.printRow: self.printChart(self.df.iloc[i])
import hashing from Wallet import Wallet from Blockchain import get_blockchain from Miner import Miner if __name__ == "__main__": print(hashing.hash("Jetzt liken und abonnieren!!! The Morpheus Tutorials :)")) w = Wallet() print(w.public_key) print(w.private_key) print(w.password) print(w.send_money([w.public_key], [50])) print(get_blockchain().get_json()) miner = Miner(own_public_key=w.public_key)
def _get_backtest_assets(self, price_dta, skip_first_n=1): """ parameters: ----------- skip_first_n : int allows calculations to catch up. must be >= 1 """ assert skip_first_n > 0 wallet = Wallet() assets = [{ **wallet.asset_dict(), 'date_time': price_dta['Date(UTC)'][0], 'netHoldings': 0, 'trade': 0, }] # Iterate over all rows, adding trade data # trades = pd.DataFrame(columns=['date_time', 'price', 'trade']) for index, row in price_dta.iterrows(): if index < skip_first_n: continue # implied else trade_amt = trade_function_map[self.trade_fn.value]( price=row['Value'], bollinger_lower=row['Lower Band'], bollinger_upper=row['Upper Band'], max_trade=floor(assets[-1]['btc']*0.5), eth_btc_ratio=(1+assets[-1]['eth']) / (1+assets[-1]['btc']), ) # if (trade_amt != 0): # trades = trades.append({ # "price": row['Value'], # "trade": trade_amt # }, ignore_index=True) # else: # trades = trades.append([ # row['Date(UTC)'], # row['Value'], # 0 # ]) # trades.to_csv(self.output()["trades"].path, index=False) trade_penalty = .05 if trade_amt != 0: wallet.trade( {'btc': - trade_amt}, {'eth': - trade_amt / row['Value'] * (1 - trade_penalty)}, ) assets.append({ "date_time": row['Date(UTC)'], **wallet.asset_dict(), "trade": trade_amt }) # Convert values to exchange currency assets[-1]['eth'] = assets[-1]['eth'] * row['Value'] # Calculate net value of holdings assets[-1]['netHoldings'] = ( assets[-1]['btc'] + assets[-1]['eth'] ) # Convert List to DataFrame return pd.DataFrame(assets)
def create_wallet(): wallet = Wallet() response = wallet.to_dict() client_wallets.append(wallet) return jsonify(response), 201
def generateSampleWallet(keyNames): """Generates a Wallet for a given list of keyNames in a random way""" wallet = Wallet() for keyName in keyNames: wallet.addKey(keyName, generatePrivateKey()) return wallet
import random if __name__ == "__main__": ovi_coin = Blockchain(difficulty=2, mining_reward=100) keygen = KeyGenerator() names = [ "Miner", "Ovi", "Bob", "Alice", "Peter", "Collin", "Mark", "Daniel", "Alex", "Jane", "Jill" ] threads = [] # create 11 wallets wallets = [] for i in range(11): sk, pk = keygen.generate() wallets.append(Wallet(names[i], pk, sk)) # have a designated miner miner = wallets[0] wallets = wallets[1:] # everybody starts with $100 for i in range(10): tx = Transaction(None, wallets[i].pk, 100) ovi_coin.add_transaction(tx) threads.append(ovi_coin.mine_pending_transactions(miner.pk)) # randomly execute 100 transactions between the wallets # and mine every 10 for i in range(1, 101):
block = values['block'] if block['index'] == blockchain.get_chain()[-1].index + 1: success = blockchain.add_block(block) if success == True: message = { "Success" : "Block was broadcasted Successfully" } return jsonify(message),200 else: message = { "Error" : "Block was not broadcasted due to some reasons" } return jsonify(message),400 elif block['index'] > blockchain.get_chain()[-1].index: pass else: message = { "Error :": "Block recieved was from a shorted blockchain" } return jsonify(message),500 if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('-p','--port',type = int,default = 5000) args = parser.parse_args() port = args.port print(port) wallet = Wallet(port) blockchain = Blockchain(wallet.public_key,port) app.run(host = "0.0.0.0",port = port)
from flask import Flask, jsonify, request, send_from_directory from flask_cors import CORS from Wallet import Wallet from Blockchain import Blockchain app = Flask(__name__) wallet = Wallet() blockchain = Blockchain(wallet.public_key) CORS(app) @app.route('/', methods=['GET']) def get_node_ui(): return send_from_directory("UI", 'node.html') @app.route('/network', methods=['GET']) def get_network_ui(): return send_from_directory('UI', 'network.html') @app.route('/wallet', methods=['POST']) def create_keys(): wallet.create_keys() if wallet.save_keys(): global blockchain blockchain = Blockchain(wallet.public_key) response = { 'public_key': wallet.public_key, 'private_key': wallet.private_key,
def __init__(self): # self.id = str(uuid4()) self.wallet = Wallet() self.wallet.create_keys() self.blockchain = Blockchain(self.wallet.public_key)