def load_data(self): try: with open( 'blockchain_{}.txt'.format(self.node_id), mode='r' ) as f: #The mode is write and not append (a) because we plan overwriting the data all the time. file_content = f.readlines() blockchain = json.loads(file_content[0][:-1]) updated_blockchain = [] for block in blockchain: converted_tx = [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ] updated_block = Block(block['hash_previous_block'], block['index'], converted_tx, block['proof'], block['timestamp']) updated_blockchain.append(updated_block) self.chain = updated_blockchain open_transactions = json.loads(file_content[1][:-1]) updated_open_transactions = [] for transaction in open_transactions: updated_transaction = Transaction(transaction['sender'], transaction['recipient'], transaction['signature'], transaction['amount']) updated_open_transactions.append(updated_transaction) self.open_transactions = updated_open_transactions peer_nodes = json.loads(file_content[2]) self.peer_nodes = set(peer_nodes) except (IOError, IndexError): pass
def new_transaction(): recipient = request.args.get("address") amount = request.args.get("amount") transaction = Transaction(myWallet.identity, recipient, amount) transaction.add_signature(myWallet.sign_transaction(transaction)) transaction_result = blockchain.add_new_transaction(transaction) if transaction_result: response = {'message': 'Transaction will be added to Block '} return jsonify(response), 201 else: response = {'message': 'Invalid Transaction!'} return jsonify(response), 406
def dataTransakci(): r = requests.get( 'https://api.csas.cz/sandbox/webapi/api/v2/transparentAccounts/', headers=headers) data = json.loads(r.text) #print(json.dumps(data, indent=4, sort_keys=True)) T = [] for i in range(len(data['accounts'])): cisloUctu = data['accounts'][i]['accountNumber'] r = requests.get( 'https://api.csas.cz/sandbox/webapi/api/v2/transparentAccounts/' + cisloUctu + '/transactions/', headers=headers) dataUcet = json.loads(r.text) for i in range(len(dataUcet.get('transactions', []))): tran = Transaction(str(dataUcet['transactions'][i]['sender']['accountNumber']), \ str(dataUcet['transactions'][i]['receiver']['accountNumber']), \ str(dataUcet['transactions'][i]['dueDate'])[:10], \ float(dataUcet['transactions'][i]['amount']['value']), dataUcet['transactions'][i]['amount']['currency'] ) T.append(tran) return T
def add_transaction(self, recipient, sender, signature, amount=1.0, is_receiving=False): '''if self.public_key == None: return None''' transaction = Transaction(sender, recipient, amount, signature) """if not Wallet.verify_signature(transaction): return False""" if Verification.verify_transaction(transaction, self.get_balance): self.open_transactions.append(transaction) self.save_data() if not is_receiving: for node in self.peer_nodes: url = 'http://{}/broadcast_transaction'.format(node) try: response = requests.post(url, json={ 'sender': sender, 'recipient': recipient, 'amount': amount, 'signature': signature }) if response.status_code == 400 or response.status_code == 500: print('Transaction declined, needs resolving') return False except requests.exceptions.ConnectionError: continue return True return False
def scrape(page, county): #r = requests.get(url) soup = BeautifulSoup(page, 'html.parser') table = soup.table # find the table references reclist = [] grantorlist = [] granteelist = [] mygrantorlist = [] mygranteelist = [] #with open(f, 'a', newline='') as outfile: if table is None: pass else: for br in table.find_all('br'): # finds the <br> and replaces with newlines (for the names) br.replace_with('\n') table_rows = table.find_all('tr') # returns a list of table rows for tr in table_rows: td = tr.find_all('td') # finds the table data row = [i.text for i in td] # returns a list of data in each row from NDO. row is type list. if len(row) == 5: row.append(county) if row[0][-9:].strip() == 'Replatted': note = '(Replatted)' row[0] = row[0][-20:-10].strip() else: row[0] = row[0][-10:].strip() note = '' row[1] = row[1].strip() row[2] = row[2].strip() row[3] = row[3].strip() # Transaction(instrument, xactdate, deedtype, county, notes=None) proprec = Transaction(None, row[0], row[4], row[5]) legallist = row[1].split('\n') grantorlist = row[2].split('\n') granteelist = row[3].split('\n') if note != '': proprec.addnotes(note) reclist.append(proprec)
def merkle_path(): values = request.form required = ['sender', 'recipient', 'value'] # Check that the required fields are in the POST data if not all(k in values for k in required): return 'Missing values', 400 transaction = Transaction(values.get('sender'), values.get('recipient'), values.get('value')) path = blockchain.merkle_path(transaction) if len(path) > 0: root = path[-1] path = path[:-1] return jsonify(path), 200
def add_transaction(self, recipient, sender, signature, amount=1.0): if self.public_key == None: return None transaction = Transaction(sender, recipient, amount, signature) """if not Wallet.verify_signature(transaction): return False""" if Verification.verify_transaction(transaction, self.get_balance): self.open_transactions.append(transaction) self.save_data() return True else: print("Solde insuffisant") return False
def transfer_money(): peer_destino = request.forms.get('peer') valor = float(request.forms.get('value')) try: if valor < 0: raise ValueError('O valor da transação deve ser positivo!') if valor > calcula_saldo(): raise ValueError('Não há saldo disponível na carteira!') increment_vector_clock() transaction = Transaction(user, peer_destino, valor, vector_clock.copy()) add_transaction(transaction) except ValueError as ve: print('Erro! -> {}'.format(ve)) redirect('/')
def mine_block(self): if self.public_key == None: return None #return False if not Verification.verify_chain(self.chain): return None last_block = self.chain[-1] hashed_blocks = hash_block(last_block) proof = self.proof_of_work() reward_transaction = Transaction('MINING', self.public_key, '', MINING_REWARD) copied_transactions = self.open_transactions[:] for tx in copied_transactions: if not Wallet.verify_signature(tx): return None #return False copied_transactions.append(reward_transaction) block = Block(hashed_blocks, len(self.chain), copied_transactions, proof) self.chain.append(block) self.open_transactions = [] self.save_data() return block
def mine_block(self): if self.public_key == None: return None #return False if not Verification.verify_chain(self.chain): return None last_block = self.chain[-1] hashed_blocks = hash_block(last_block) proof = self.proof_of_work() reward_transaction = Transaction('MINING', self.public_key, '', MINING_REWARD) copied_transactions = self.open_transactions[:] for tx in copied_transactions: if not Wallet.verify_signature(tx): return None #return False copied_transactions.append(reward_transaction) block = Block(hashed_blocks, len(self.chain), copied_transactions, proof) self.chain.append(block) self.open_transactions = [] self.save_data() for node in self.peer_nodes: url = 'http://{}/broadcast_block'.format(node) block_converted = block.__dict__.copy() block_converted['transactions'] = [ tx.__dict__ for tx in block_converted['transactions'] ] try: response = requests.post(url, json={'block': block_converted}) if response.status_code == 400: print('Block declined, needs resolving') if response.status_code == 500: print('Block declined') except requests.exceptions.ConnectionError: continue return block
def update_transactions(ngbr_transactions, ngbr): global transactions, vector_clock for transaction_dict in ngbr_transactions: transaction = Transaction(**transaction_dict) exists = False for t in transactions: if transaction == t: exists = True if not exists: if transaction.peer_origem not in vector_clock: vector_clock[ transaction.peer_origem] = transaction.vector_clock[ transaction.peer_origem] - 1 if transaction.vector_clock[ transaction. peer_origem] <= vector_clock[transaction.peer_origem] + 1: #era a transação que esperava receber desse peer update_clock(transaction.vector_clock) add_transaction(transaction) else: print("Foram perdidas mensagens do peer {}!".format( transaction.peer_origem)) #agora eu posso colocar numa fila de espera, com uma thread tentando reinseri-las de tempo em tempo :D delay_queue.append(transaction)
def add_block(self, block): transactions = [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ] proof_is_valid = Verification.valid_proof(transactions[:-1], block['hash_previous_block'], block['proof']) hashes_match = hash_block( self.chain[-1]) == block['hash_previous_block'] print("hash block ", hash_block(self.chain[-1])) print("block previous hash ", block['hash_previous_block']) print(proof_is_valid) print(hashes_match) if not proof_is_valid or not hashes_match: return False converted_block = Block(block['hash_previous_block'], block['index'], transactions, block['proof'], block['timestamp']) self.chain.append(converted_block) stored_transactions = self.open_transactions[:] for incomingtx in block['transactions']: for opentx in stored_transactions: print("incoming tx ", incomingtx) print("opentx ", opentx) if incomingtx['sender'] == opentx.sender and incomingtx[ 'recipient'] == opentx.recipient and incomingtx[ 'amount'] == opentx.amount and incomingtx[ 'signature'] == opentx.signature: #Only transactions that are the same everywhere should be mined try: self.open_transactions.remove(opentx) except ValueError: print('Item is already removed') self.save_data() return True