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 __init__(self): self.wallet = Wallet() self.analyzer = 0 self.buyRequests = [] self.sellRequests = [] self.file = open(".bot.log", "w+") self.file.truncate()
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 _pay(self): bitcoinAmount = self.driver.find_element_by_css_selector(".ng-binding.payment__details__instruction__btc-amount").text toWallet = self.driver.find_element_by_css_selector(".payment__details__instruction__btc-address.ng-binding").text print("amount: " + bitcoinAmount) print("to wallet: " + toWallet) wallet = Wallet() return wallet.payToAutomatically(toWallet, bitcoinAmount)
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 verify_transaction(transaction, calculate_balances, check_funds=True): if check_funds == True: sender_balance = calculate_balances(transaction.sender) if sender_balance >= transaction.amount and Wallet.verify_transaction( transaction): return True else: return False else: return Wallet.verify_transaction(transaction)
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 _pay(self): """Extract the invoice information and pay for the VPS""" bitcoinAmount = self.driver.find_element_by_css_selector(".ng-binding.payment__details__instruction__btc-amount").text toWallet = self.driver.find_element_by_css_selector(".payment__details__instruction__btc-address.ng-binding").text print("Bitcoin amount to transfer: " + bitcoinAmount) print("To wallet: " + toWallet) wallet = Wallet() return wallet.payToAutomatically(toWallet, bitcoinAmount)
def _pay(self): self.driver.switch_to_frame(self.driver.find_element_by_tag_name("iframe")) text = self.driver.find_element_by_tag_name('body').text lines = text.split('\n') firstlinesplit = lines[0].split(' ') bitcoinAmount = firstlinesplit[2] toWallet = lines[2] self.pay_page_url = self.driver.current_url print("amount: " + bitcoinAmount) print("to wallet: " + toWallet) wallet = Wallet() return wallet.payToAutomatically(toWallet, bitcoinAmount)
def verify_transaction(transaction, get_balance, check_funds=True): """Verify a transaction by checking weather the sender has sufficient balance. Arguments: :transaction: The transaction that should be valid :get_balance: Then function fro get balance """ if check_funds: sender_balance = get_balance() return sender_balance >= transaction.amount and Wallet.verify_transaction(transaction) else: return Wallet.verify_transaction(transaction)
def _pay(self): self.driver.find_element_by_css_selector("input[type='submit'][value='Pay Now']").click() self.driver.implicitly_wait(10) bitcoinAmount = self.driver.find_element_by_css_selector(".ng-binding.payment__details__instruction__btc-amount").text toWallet = self.driver.find_element_by_css_selector(".payment__details__instruction__btc-address.ng-binding").text print("Bitcoin amount to transfer: " + bitcoinAmount) print("To wallet: " + toWallet) print("Email used: " + self.email) print("Password used: " + self.password) print("SSHPassword to be used: " + self.SSHPassword) print("SSHUsername to be used: " + self.SSHUsername) wallet = Wallet() return wallet.payToAutomatically(toWallet, bitcoinAmount)
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, 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,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 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)
class Issuer: 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 receiveCoins(self, coins, message=None): try: self.wallet.receiveCoins(coins, message) for coin in coins: coin = decodeCoin(coin) self.redeemed[coin.getHash()] = coin print 'money redeemed' return True except Exception, e: return False
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()
class Issuer: 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 receiveCoins(self,coins,message=None): try: self.wallet.receiveCoins(coins,message) for coin in coins: coin = decodeCoin(coin) self.redeemed[coin.getHash()] = coin print 'money redeemed' return True except Exception, e: return False
def genPersonalTrans(self, revert=False): res = True if (not revert): for row in self.Detail: ptrans = PersonalTrans() ptrans.defaults() ptrans.TransDate = row.Date ptrans.TransTime = row.Time ptrans.Type = ptrans.EXPENSE ptrans.OriginType = 9001 ptrans.OriginNr = self.SerNr from Wallet import Wallet wal = Wallet.bring(self.Wallet) if (wal): ptrans.Person = wal.Owner ptrans.Description = "Viaje en Subte - %s" %(row.Station) crow = PersonalTransConceptRow() crow.Concept = "TRANSP" crow.pasteConcept(ptrans) crow.Qty = 1 crow.Price = 1.10 crow.pastePrice(ptrans) ptrans.Concepts.append(crow) prow = PersonalTransPaymentRow() prow.Wallet = self.Wallet prow.pasteWallet(ptrans) prow.Amount = 1.10 ptrans.Payments.append(prow) ptrans.Status = 1 ptrans.sumUp() res = ptrans.save() if (not res): return res else: pquery = Query() pquery.sql = "SELECT PT.SerNr FROM PersonalTrans PT " pquery.sql += "WHERE?AND PT.OriginType = i|%s| AND PT.OriginNr = i|%s| "%(9001,self.SerNr) if (pquery.open()): for prow in pquery: ptrans = PersonalTrans.bring(prow.SerNr) if (ptrans): res = ptrans.forceDelete() if (not res): return res else: message("No se encuentra registro") return res
def genPersonalTrans(self, param, value): record = self.getRecord() from Wallet import Wallet wall = Wallet.bring(param) if (wall): from PersonalTrans import PersonalTrans, PersonalTransPaymentRow ptrans = PersonalTrans() ptrans.defaults() ptrans.TransDate = today() ptrans.Person = wall.Owner paymentrow = PersonalTransPaymentRow() paymentrow.Wallet = wall.Code paymentrow.pasteWallet(ptrans) ptrans.Payments.append(paymentrow) openWindow(ptrans)
def handleTransaction(self,transaction): data=transaction.payload() signature=transaction.signature signerPublicKey=transaction.senderPublicKey signatureValid=Wallet.signatureValid(data,signature,signerPublicKey) transactionExists=self.transitionPool.transactionExists(transaction) transactionInBlockExists=self.blockChain.transactionExists(transaction) if not transactionExists and not transactionInBlockExists and signatureValid: self.transitionPool.addTransaction(transaction) message=Message(self.p2p.socketConnector,'TRANSACTION',transaction) encodedMessage=BlockchainUtils.encode(message) self.p2p.broadcast(encodedMessage) forginRequired=self.transitionPool.forgerRequired() if forginRequired: self.forge()
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 mine_block(self): if self.hosting_node is None: return None last_block = self.__chain[-1] hashed_block = hash_block(last_block) reward_transaction = Transaction('MINING', self.hosting_node, '', MINING_REWARD) copied_transaction = self.__open_transactions[:] for tx in copied_transaction: if not Wallet.verify_transaction(tx): return False copied_transaction.append(reward_transaction) proof = self.proof_of_work() block = Block(len(self.chain), hashed_block, copied_transaction, proof) self.__chain.append(block) self.__open_transactions = [] self.save_data() return block
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 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 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 create_wallet(): wallet = Wallet() response = wallet.to_dict() client_wallets.append(wallet) return jsonify(response), 201
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)
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])
class Node: def __init__(self): # self.id = str(uuid4()) self.wallet = Wallet() self.wallet.create_keys() self.blockchain = Blockchain(self.wallet.public_key) def get_transaction_value(self): """ Returns the input of the user (a new transaction amount) as a float. """ tx_recipient = input('Enter the recipient of the transaction ') tx_amount = float(input('Enter the amount of the transaction ')) return tx_recipient, tx_amount def print_blockchain_element(self): """ Output all blocks of the blockchain. """ for element in self.blockchain.chain: print('Outputting Block') print(element) else: print('-' * 20) def listen_for_input(self): while True: print_message() user_choice = get_user_choice() if user_choice == '1': tx_data = self.get_transaction_value() recipient, amount = tx_data signature = self.wallet.sign_transaction( self.wallet.public_key, recipient, amount) print('Added transaction') if self.blockchain.add_transaction( recipient, self.wallet.public_key, signature, amt=amount) else print('Transacting failed') print('Open_Transactions: ', self.blockchain.get_open_transactions()) elif user_choice == '2': if not self.blockchain.mine_block(): print('Mining failed. Got no wallet!') elif user_choice == '3': self.print_blockchain_element() elif user_choice == '4': if Verification.verify_transactions( self.blockchain.get_open_transactions(), self.blockchain.get_balance): print('all transactions are valid') else: print('There are invalid transactions') elif user_choice == '5': self.wallet.create_keys() self.blockchain = Blockchain(self.wallet.public_key) elif user_choice == '6': self.wallet.load_keys() self.blockchain = Blockchain(self.wallet.public_key) elif user_choice == '7': self.wallet.save_keys() elif user_choice == 'q': break else: print('Input was invalid, please pick a value from the list') if not Verification.verify_chain(self.blockchain.chain): self.print_blockchain_element() print('Invalid blockchain') break print('Balance of {} : {:.2f} '.format( self.wallet.public_key, self.blockchain.get_balance())) print('Done')
class Trader: def __init__(self, indicators, marketExchange, botConfig): self.indicators = indicators self.marketExchange = marketExchange self.chartDataAnalyzer = ChartDataAnalyzer() self.botConfig = botConfig self.df = self.marketExchange.get_chart_data_() self.df = self.chartDataAnalyzer.run_feature_engineer(self.df) for indicator in indicators: indicator.trainML(self.marketExchange, self.chartDataAnalyzer) 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]) def reached_objective(self): if self.orderState.inBuy == True: current_btc = ( self.orderState.actual_price * self.wallet.getDigitalCurrency(self.orderState.toDigitalCurr) - (self.orderState.actual_price * self.wallet.getDigitalCurrency( self.orderState.toDigitalCurr) * self.marketExchange.getActiveSellFeePerc())) if current_btc / self.wallet.initialDeposit >= self.objective_gain: return True else: if self.wallet.getDigitalCurrency( self.orderState.fromDigitalCurr ) / self.wallet.initialDeposit >= self.objective_gain: return True return False def reached_limit_loss(self): if self.orderState.inBuy: current_btc = ( self.orderState.actual_price * self.wallet.getDigitalCurrency(self.orderState.toDigitalCurr) ) - (self.orderState.actual_price * self.wallet.getDigitalCurrency( self.orderState.toDigitalCurr) * self.marketExchange.getActiveSellFeePerc()) if current_btc / self.wallet.initialDeposit <= self.limit_loss: return True else: if self.wallet.getDigitalCurrency( self.orderState.fromDigitalCurr ) / self.wallet.initialDeposit <= self.limit_loss: return True return False def getActualPrice(self, i): if self.botConfig.printOrders: print 'Buscando preco atual...' self.orderState.actual_price = self.df.iloc[i]['weightedAverage'] # self.actual_price = self.poloniex.get_ticker(self, self.currencyPair)['last'] def getBuyPrice(self): if self.botConfig.printOrders: print 'Buscando preco de compra...' print 'Setando Fake buy value...' self.orderState.buy_value = self.orderState.actual_price def getSellPrice(self): if self.botConfig.printOrders: print 'Buscando preco de venda...' def wait(self, i): self.df.loc[i, 'Buy'] = self.df.iloc[i - 1]['Buy'] 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.actual_price / self.orderState.buy_value - 1) * 100 if self.orderState.buy_value > 0 else 0 def isGaining(self): return self.orderState.getGainPerc() >= 1 + self.gain def didGain(self): return self.orderState.getGainPerc() >= 1 + self.gain def isLosing(self): return self.orderState.getGainPerc() <= 1 - self.loss def didLose(self): return self.orderState.getGainPerc() <= 1 - self.loss def buyOrderWasExecuted(self): if self.botConfig.printOrders: print 'Verificando se ordem de compra foi realizada....' return True def sellOrderWasExecuted(self): if self.botConfig.printOrders: print 'Verificando se ordem de venda foi realizada....' print 'Setando Fake sell value...' # if self.reached_objective() or self.reached_limit_loss(): # # self.orderState.sell_value = self.orderState.actual_price # # if self.botConfig.printOrders: # print 'Ordem de venda realizada alcance objetivo ' + str( # self.orderState.sell_value) + ' Preco atual ' + str(self.orderState.actual_price) # # return True # # el if self.didGain(): if self.orderState.sell_order_gain_active: self.orderState.sell_value = self.orderState.buy_value * ( 1 + self.gain) if self.botConfig.printOrders: print 'Ordem de venda de ganho realizada ' + str( self.orderState.sell_value) + ' Preco atual ' + str( self.orderState.actual_price) else: self.orderState.sell_value = self.orderState.actual_price if self.botConfig.printOrders: print 'Ordem de venda realizada ganho emergencial ' + str( self.orderState.sell_value) + ' Preco atual ' + str( self.orderState.actual_price) # self.gain = self.initial_gain return True elif self.didLose(): if self.orderState.sell_order_loss_active: self.orderState.sell_value = self.orderState.buy_value * ( 1 - self.loss) if self.botConfig.printOrders: print 'Ordem de venda de perda realizada ' + str( self.orderState.sell_value) + ' Preco atual ' + str( self.orderState.actual_price) else: self.orderState.sell_value = self.orderState.actual_price if self.botConfig.printOrders: print 'Ordem de venda realizada perda emergencial ' + str( self.orderState.sell_value) + ' Preco atual ' + str( self.orderState.actual_price) # self.gain = abs(1 - self.orderState.sell_value/self.orderState.buy_value) + self.gain return True return False def cancelLastSellOrder(self): if self.botConfig.printOrders: print 'Ordem de venda anterior cancelada' def sendBuyOrder(self): if self.botConfig.printOrders: print 'Enviando ordem de compra...' def sendSellOrder(self, gain): self.cancelLastSellOrder() if self.botConfig.printOrders: if gain: print 'Enviando ordem de venda ganho ' + str( self.orderState.buy_value * (1 + self.gain)) + ' Preco atual ' + str( self.orderState.actual_price) else: print 'Enviando ordem de venda perda ' + str( self.orderState.buy_value * (1 - self.loss)) + ' Preco atual ' + str( self.orderState.actual_price) def indicators_predict_buy(self, i): shouldBuyCount = 0 for indicator in self.indicators: shouldBuyCount = shouldBuyCount + indicator.predict( self.orderState, self.df, i) self.df.loc[i, 'shouldBuy'] = shouldBuyCount return True if shouldBuyCount >= self.botConfig.shouldBuyAccept else False def pre_setup_indicators(self, df): for indicator in self.indicators: indicator.preSetup(df) def train_inidicators(self, i): for indicator in self.indicators: indicator.train(self.orderState, self.df, i) def printChart(self, df): Visualizer.print_full(df[[ 'date', # 'timestamp' 'close', # 'high', # 'low', 'open', # 'supportQuote', # 'resistanceQuote', # 'quoteVolume', # 'volume', 'isUp', 'quoteGrowth1stPeriod', 'weightedAverage', 'buyValue', 'sellValue', 'perGain', 'btc', 'actualCurrency', 'Buy', 'shouldBuy' ]])
def do_createWallet(self, args): """ ---> createWallet - создает новый кошелек <--- """ wal = Wallet() print('Ваш адрес: {}'.format(wal.getAddress()))
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 traverse_tree(starting_wallet, starting_tx): wallets = [Wallet(starting_wallet)] t = tree() return t
It's reproductive strategy will be to create a child, transfer all it's bitcoin to the child. At most it will make 1 child. It will log all output of the child. """ from ExitNode import Tunnel from Birthchamber import Birthchamber from ZappiehostBuyer import ZappiehostBuyer from Wallet import Wallet from time import sleep from Tribler.community.tunnel.tunnel_community import TunnelSettings from twisted.internet.stdio import StandardIO wallet = Wallet() settings = TunnelSettings() # For disabling anonymous downloading, limiting download to hidden services only settings.min_circuits = 0 settings.max_circuits = 0 settings.become_exitnode = True crawl_keypair_filename = None dispersy_port = -1 tunnel = Tunnel(settings, crawl_keypair_filename, dispersy_port) #StandardIO(LineHandler(tunnel, profile)) tunnel.start(None)
def placeOrder(self): """ Places an order on THCServers for a new VPS. """ try: self.spawnBrowser() self.driver.get("https://www.thcservers.com/vps-hosting") self.driver.find_element_by_class_name("vps_submit_form").click() self.fillInElement("hostname", self.generator.getRAString(10)) self.fillInElement("ns1prefix", "ns1") self.fillInElement("ns2prefix", "ns2") self.fillInElement("rootpw", self.SSHPassword) # configoption[9] #self.chooseSelectElement("configoption[5]", "Ubuntu 14.04") self.driver.execute_script("var elements = document.getElementsByName('configoption[5]'); var element = elements[0]; element.value = '87'; recalctotals();") self.driver.implicitly_wait(2) self.driver.find_element_by_class_name("checkout").click() self.driver.implicitly_wait(10) self.fillInElement('firstname', self.generator.getFirstName()) self.fillInElement('lastname', self.generator.getSurname()) self.fillInElement('email', self.email) self.fillInElement('address1', self.generator.getRAString(randint(8, 15)) + ' ' + self.generator.getRNString(randint(1, 2))) self.fillInElement('city', self.generator.getCity()) self.fillInElement('postcode', self.generator.getZipcode()) # country self.driver.execute_script("var element = document.getElementById('country'); element.value = 'US';") self.driver.execute_script("document.getElementById('stateselect').value = 'Kansas';") self.fillInElement('phonenumber', self.generator.getPhoneNum()) # password = # Generate a password self.driver.find_element_by_id("newpw").send_keys(self.password) #self.fillInElement('password', self.password) self.fillInElement('password2', self.password) self.driver.find_element_by_id('pgbtnbitpay').click() self.driver.find_element_by_name('accepttos').click() print("Email used: " + self.email) print("password used: " + self.password) self.driver.find_element_by_css_selector('.btn.btn-success').click() try: self.driver.find_element_by_css_selector('input[value="Pay Now"]').click() except Exception as e: print("Warning: Pay now button not found") bitcoinAmount = self.driver.find_element_by_css_selector(".ng-binding.payment__details__instruction__btc-amount").text toWallet = self.driver.find_element_by_css_selector(".payment__details__instruction__btc-address.ng-binding").text print("amount: " + bitcoinAmount) print("to wallet: " + toWallet) print("password: "******"email: " + self.email) wallet = Wallet() paymentSucceeded = wallet.payToAutomatically(toWallet, bitcoinAmount) if paymentSucceeded == False: return False # Wait for the transaction to be accepted wait = ui.WebDriverWait(self.driver, 666) wait.until(lambda driver: driver.find_element_by_css_selector('.payment--paid')) self.closeBrowser() except WebDriverException as e: print("Could not complete the transaction because an error occurred:") print("WebDriverException") print(e.msg) self.closeBrowser() return False except Exception as e: print("Could not complete the transaction because an error occurred:") print(unicode(e, "utf-8")) self.closeBrowser() return False #raise # Raise the exception that brought you here return True
# (c) 2007 Nils Toedtmann, Joerg Baach, License GPL import xmlrpclib from Wallet import Wallet url = 'http://opencoin.net/cur1' server = 'http://localhost:8000' i = xmlrpclib.ServerProxy(server) w = Wallet({url:i}) w.createCoins([1,1,2],url) print w.getBalance() w.fetchSignedBlinds() print w.getBalance() w.fetchSignedBlinds() print w.getBalance() coin = w.valid.values()[0] w.sendCoins(i,[coin],'foobar') w.sendCoins(i,[coin],'foobar') #w2 = xmlrpclib.ServerProxy('http://localhost:8001') #coin = w.valid.values()[0] #print `coin` #w.sendCoins(w2,[coin],'foobar')
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 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 run(self): record = self.getRecord() ofile = open(record.Filename,"r") flines = ofile.readlines() for ln in range(12,len(flines)): cline = flines[ln] col1 = (0,10) col2 = (16,71) col3 = (71,84) col4 = (84,105) col5 = (105,128) transdate = stringToDate(cline[col1[0]:col1[1]]) if (transdate >= record.FromDate and transdate <= record.ToDate): #comment = cline[16:114].strip() #debit = float(cline[114:130].replace(".","").replace(",",".")) #credit = float(cline[131:154].replace(".","").replace(",",".")) comment = cline[col2[0]:col2[1]].strip() debit = float(cline[col3[0]:col3[1]].replace(".","").replace(",",".")) credit = float(cline[col4[0]:col4[1]].replace(".","").replace(",",".")) print transdate,comment,debit,credit from PersonalTrans import PersonalTrans, PersonalTransConceptRow, PersonalTransPaymentRow ptrans = PersonalTrans() ptrans.defaults() ptrans.TransDate = transdate ptrans.Description = comment if (debit > 0): ptrans.Type = ptrans.EXPENSE amount = debit else: ptrans.Type = ptrans.INCOME amount = credit if ("EXTRACCION POR CAJEROS AUTOMATICOS" in comment): ptrans.Type = ptrans.TRANSFERENCE ptrans.SupCode = "0004" ptrans.pasteSupCode() from Wallet import Wallet person = Wallet.bring(record.Wallet).Owner ptrans.Person = person drow = PersonalTransConceptRow() drow.Concept = "VARIOS" drow.pasteConcept(ptrans) drow.Qty = 1 drow.Price = amount drow.pastePrice(ptrans) ptrans.Concepts.append(drow) prow = PersonalTransPaymentRow() prow.Wallet = record.Wallet prow.pasteWallet(ptrans) prow.Amount = amount ptrans.Payments.append(prow) ptrans.sumUp() res = ptrans.save() if (not res): message(res) else: commit()
def __init__(self): # self.id = str(uuid4()) self.wallet = Wallet() self.wallet.create_keys() self.blockchain = Blockchain(self.wallet.public_key)