def _create_blocks(self, city, size): blocks_count = size - 1 block_size = 96 inital_offset = 50 street_width = 4 half_street_width = street_width / 2.0 triangle_delta = 93 for x in range(blocks_count): for y in range(blocks_count): if x == y: origin = Point(street_width + 1 + x * self.multiplier, half_street_width + y * self.multiplier, 0) vertices = [ Point(0, 0, 0), Point(triangle_delta, 0, 0), Point(triangle_delta, triangle_delta, 0) ] block = Block(origin, vertices) city.add_block(block) origin = Point(half_street_width + x * self.multiplier, street_width + 1 + y * self.multiplier, 0) vertices = [ Point(0, 0, 0), Point(0, triangle_delta, 0), Point(triangle_delta, triangle_delta, 0) ] block = Block(origin, vertices) city.add_block(block) elif x + y == blocks_count - 1: origin = Point(half_street_width + x * self.multiplier, half_street_width + y * self.multiplier, 0) vertices = [ Point(0, 0, 0), Point(triangle_delta, 0, 0), Point(0, triangle_delta, 0) ] block = Block(origin, vertices) city.add_block(block) origin = Point( (x + 1) * self.multiplier - half_street_width, street_width + 1 + y * self.multiplier, 0) vertices = [ Point(0, 0, 0), Point(0, triangle_delta, 0), Point(-triangle_delta, triangle_delta, 0) ] block = Block(origin, vertices) city.add_block(block) else: origin = Point(inital_offset + x * self.multiplier, inital_offset + y * self.multiplier, 0) block = Block.square(origin, block_size) city.add_block(block)
def save_data(self): try: target_path = "../target/blockchain" + self.__node_port + ".txt" with open(target_path, mode="w") as file: reconstructed_blockchain = [ block.__dict__ for block in [ Block( block_el.prev_hash, block_el.index, [tx.__dict__ for tx in block_el.transactions], block_el.proof_of_work, block_el.timestamp, ) for block_el in self.__chain ] ] file.write(json.dumps(reconstructed_blockchain)) file.write("\n") reconstructed_outstanding_transactions = [ txn.__dict__ for txn in self.__outstanding_transactions ] file.write(json.dumps(reconstructed_outstanding_transactions)) file.write("\n") global participants file.write(json.dumps(participants)) file.write("\n") file.write(json.dumps(list(self.__peer_nodes))) file.write("\n") file.write(json.dumps(self.__node_port)) except IOError: ("------Saving failed------")
def wallet_create(user_id): user_id = user_id + "-" + str(uuid4()) wallets = CyberCellCoin.latest_block.data["wallets"].copy() wallets[user_id] = {"user_id": user_id, "balance": 0} old_transaction = CyberCellCoin.latest_block.data["transaction"].copy() data = {"transaction": old_transaction, "wallets": wallets} new = Block(data=data) CyberCellCoin.add(new) for index in range(len(CyberCellCoin.nodes)): headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } url = CyberCellCoin.nodes[index] url = url + "block" data = CyberCellCoin.latest_block.__dict__ requests.post(url, json=data, headers=headers) for index in range(len(CyberCellCoin.nodes)): headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } url = CyberCellCoin.nodes[index] url = url + "ping" data = request.url_root requests.post(url, json=data, headers=headers) print(not (request.url_root in CyberCellCoin.nodes)) if (not (request.url_root in CyberCellCoin.nodes)): CyberCellCoin.nodes.append(request.url_root) return user_id
def send_money(sender, recipient, amount): """ #send money from one user to another verify that the amount is an integer or floating value """ try: amount = float(amount) except ValueError: raise InvalidTransactionException("Invalid Transaction.") #verify that the user has positive balance (exception if it is the BANK) if amount > get_balance(sender) and sender != "BANK": raise InsufficientFundsException("Insufficient Funds.") #verify that the user is not sending money to themselves or amount is less than or 0 elif sender == recipient or amount <= 0.00: raise InvalidTransactionException("Invalid Transaction.") #verify that the recipient exists elif isnewuser(recipient): raise InvalidTransactionException("User Does Not Exist.") #update the blockchain and sync to mysql blockchain = get_blockchain() number = len(blockchain.chain) + 1 data = "%s==>%s==>%s" % (sender, recipient, amount) blockchain.mine(Block(number, data=data)) sync_blockchain(blockchain)
def post(self): args = parser.parse_args() profile = db.query(Profile).filter_by(id=args['profile_id']).first() miner = db.query(Profile).filter_by(id=args['miner_id']).first() previous = db.query(Block).order_by('-id').first() data = { "message": profile.message, "feedback": args["feedback"], "initiator": profile.email, "miner": miner.email, "reward": 30 } nonce, hash, timestamp = Block.pow(data=json.dumps(data), previous_hash=previous.hash) block = Block(data=json.dumps(data), hash=hash, previous_hash=previous.hash, nonce=nonce, creation_date=timestamp) miner.thelmies += 30 profile.thelmies -= 5 # remove message from profile profile.message = "" db.add(block) db.commit() return jsonify(block)
def convert_to_block(json): from models.block import Block transactions = json['data'] data = [convert_to_transaction(tr) for tr in transactions] return Block(json["prev_hash"], json["index"], json["timestamp"], data, json['owner_address'], json["nonce"])
def test_accept(self): vertices = [Point(0, 0, 0), Point(0, 1, 0), Point(1, 0, 0)] block = Block(Point(0, 0, 0), vertices) generator_mock = mock.Mock() calls = [mock.call.start_block(block), mock.call.end_block(block)] block.accept(generator_mock) generator_mock.assert_has_calls(calls)
def save_data(self): try: # mode should be 'rb' if using pickle, and txt should be p with open('blockchain-{}.txt'.format(self.node_id), mode='w') as f: # chain_with_dict_tx is a list of block object, which consist dict transaction # [tx.__dict__ for tx in block_el.transactions] chain_with_dict_tx = [ Block(block_el.index, block_el.previous_hash, [tx.__dict__ for tx in block_el.transactions], block_el.proof, block_el.timestamp) for block_el in self.__chain ] saveable_chain = [ block.__dict__ for block in chain_with_dict_tx ] # save as json data f.write(json.dumps(saveable_chain)) # from list to string f.write('\n') saveable_tx = [tx.__dict__ for tx in self.__open_transactions] f.write(json.dumps(saveable_tx)) # from list ot string f.write('\n') f.write(json.dumps(list(self.__peer_nodes))) """ save as binary data save_data = { 'chain': blockchain, 'ot': open_transactions } f.write(pickle.dumps(save_data)) """ except IOError: print('Saving failed!')
def __init__(self, dir_st, vocab, img_emb_size=2048, text_emb_size=4800, mlp_dimensions=[2048, 2048, 3000]): super(BaselineNet, self).__init__() # also initialise question and image encoder self.skip_thought = QuestionEncoder(dir_st, vocab) self.fusion_block = Block([text_emb_size, img_emb_size], 2048, mm_dim=1000, chunks=15, rank=15) self.mlp = MLP(2048, mlp_dimensions)
def resolve(self): winner_chain = self.chain replace = False # whether our current chain is getting replaced, initially is False for node in self.__peer_nodes: url = 'http://{}/chain'.format(node) try: response = requests.get(url) node_chain = response.json() # list of block dict # create list of block object with a list of dict transaction node_chain = [ Block(block['index'], block['previous_hash'], [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ], block['proof'], block['timestamp']) for block in node_chain ] node_chain_length = len(node_chain) local_chain_length = len(winner_chain) if node_chain_length > local_chain_length and Verification.verify_chain( node_chain): winner_chain = node_chain replace = True # if replace is True, we can assume our transactions are incorrect except requests.exceptions.ConnectionError: continue self.resolve_conflicts = False self.chain = winner_chain if replace: self.__open_transactions = [ ] # if chain is replaced, set local open tx to [] self.save_data() return replace
def add_block(self, block): # block is dict here # transactions is a list of transaction object transactions = [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ] proof_is_valid = Verification.valid_proof(transactions[:-1], block['previous_hash'], block['proof']) hashes_match = hash_block(self.chain[-1]) == block['previous_hash'] if not proof_is_valid or not hashes_match: return False converted_block = Block(block['index'], block['previous_hash'], transactions, block['proof'], block['timestamp']) self.__chain.append(converted_block) """ update open transaction on peer node, when broadcast block to peer node the some open transactions on peer node should be removed because it will be store in new block """ stored_transactions = self.__open_transactions[:] for itx in block['transactions']: # itx is incoming tx for opentx in stored_transactions: # opentx is open transaction of node # for every incoming transaction, check if it is part of my open transaction if opentx.sender == itx['sender'] and opentx.recipient == itx[ 'recipient'] and opentx.amount == itx[ 'amount'] and opentx.signature == itx['signature']: # if same, try removing it from peer node to prevent encountering second time try: self.__open_transactions.remove(opentx) except ValueError: print('Item was already removed') self.save_data() return True
def get_most_recent_block(self) -> Block: network_info = self.query_api(self.Query.GET_NETWORK_INFO) current_block_number = network_info["blocks"] current_block = self.query_api(self.Query.GET_BLOCK, current_block_number) current_block_hash = current_block["blockhash"] prev_block_hash = current_block["previous_blockhash"] return Block(current_block_hash, current_block_number, prev_block_hash)
def recive_block(): block = request.json recived = Block() recived.__dict__ = block print("Block has been recived") CyberCellCoin.add(recived) return request.json
def mine_block(self): proof_of_work = self.get_proof_of_work() mining_reward_transaction = Transaction(MINING_SENDER, self.__node_pub_key, MINING_REWARD, None) self.__outstanding_transactions.append(mining_reward_transaction) new_block = Block( hash_block(self.get_last_block()), int(self.get_last_block().index) + 1, self.__outstanding_transactions, proof_of_work, ) self.__chain.append(new_block) # Check to see if any outstanding transactions have been tampered with after being saved for txn in self.__outstanding_transactions: if not Verification.verify_transaction(txn, self.get_balance): return False if Verification.verify_blockchain(self.__chain): global participants self.__outstanding_transactions = [] participants[self.__node_pub_key] = True self.save_data() return True self.__chain.pop() self.__outstanding_transactions.pop() return False
def sendBlock(self): print("Block {} being sent...".format(self.currBlock.currHash)) for peer in self.get_peer_list(): self.sendData((4, self.currBlock), peer) self.blockChain.addBlock(self.currBlock, self.unSpentTransactions) self.currBlock = Block(self.currBlock.index + 1, self.currBlock.currHash, datetime.datetime.utcnow().__str__())
def mine_genesis(self): """ Mines the genesis block in the blockchain if current blockchain is empty. :return: """ if self.size() == 0: block = Block('0000', 0, datetime.datetime.today(), [], 1, 'This block does not bring money') self.__blockchain.append(block)
def __init__(self, hosting_node_id): gen_block = Block("", 0, [], 0, 0) self.__node_pub_key = hosting_node_id.split("-")[0] self.__node_port = str(hosting_node_id.split("-")[1]) self.__chain = [gen_block] self.__outstanding_transactions = [] self.__peer_nodes = set() self.load_data()
def new_block(self, proof, previous_hash=None): block = Block( len(self.chain) + 1, self.current_transactions, proof, previous_hash or self.hash(self.chain[-1])) # Reset the current list of transactions self.current_transactions = [] self.chain.append(block) return block
def block_user(self, identifier, active): current_user = self.current_user user = self._get_user(identifier) row_block = Block(user_id=current_user.user_id, block_id=user.user_id, active=active) db_session.merge(row_block) db_session.commit() return self._get_user(identifier)
def run_mining(self): """ The function that is attempting to mine a block. :return: A Block object, which represents a new mined block. """ new_block_index = self.blockchain.size() new_block_data = self.blockchain.get_transactions() new_block_prev_hash = self.blockchain.get_block().hash_block() nonce = 0 new_block = Block(new_block_prev_hash, new_block_index, datetime.datetime.today(), new_block_data, self.address, nonce) while not new_block.check_block(): nonce += 1 new_block = Block(new_block_prev_hash, new_block_index, datetime.datetime.today(), new_block_data, self.address, nonce) print('I created new block and it is valid {}'.format(new_block.check_block())) return new_block
def __init__(self, public_key, node_id): # hosting_node is public_key genesis_block = Block(0, '', [], 100, 0) # __open_transactions should only be accessed within this class self.chain = [genesis_block] # initialize blockchain list self.__open_transactions = [ ] # open_transactions is list of transaction, not including reward self.public_key = public_key self.__peer_nodes = set() self.node_id = node_id self.resolve_conflicts = False self.load_data()
def sync_chain(address): req = requests.get(address) global CyberCellCoin CyberCellCoin = Blockchain() CyberCellCoin.nodes = [address + "/peers"] recived = req.json() CyberCellCoin.chain = [] empty = Block() for index in range(len(recived)): new = copy.copy(empty) new.__dict__ = recived[index] CyberCellCoin.add(new)
def mine_block(self): """ take all open_transactions and add to a new block, add to blockchain """ if self.public_key is None: return None last_block = self.__chain[-1] hashed_block = hash_block(last_block) # proof of work before adding reward transaction proof = self.proof_of_work() # miner get reward, reward will be sent to the node which did mining # we never verify signature here reward_transaction = Transaction(sender='MINING', recipient=self.public_key, signature='', amount=MINING_REWARD) # now we ensure that is not managed globally but locally # could safely do that without risking that open transaction would be affected copied_transactions = self.__open_transactions[:] # loop check all transactions(not include reward transactions) which will be added in next block for tx in copied_transactions: if not Wallet.verify_transaction(tx): return None copied_transactions.append( reward_transaction) # just add into open transaction block = Block(index=len(self.__chain), previous_hash=hashed_block, transactions=copied_transactions, proof=proof) self.__chain.append(block) # add new block into blockchain self.__open_transactions = [] self.save_data() for node in self.__peer_nodes: url = 'http://{}/broadcast-block'.format(node) converted_block = block.__dict__.copy() converted_block['transactions'] = [ tx.__dict__ for tx in converted_block['transactions'] ] try: response = requests.post(url, json={'block': converted_block}) if response.status_code == 400 or response.status_code == 500: print('Broadcast block declined, needs resolving') if response.status_code == 409: # 409 means conflict self.resolve_conflicts = True except requests.exceptions.ConnectionError: continue return block
def generateFirst(self): data = '{"message": "TEX Event Genesis block"}' nonce, hash, timestamp = Block.pow(data=data, previous_hash="0") first = Block(data=data, hash=hash, previous_hash="0", nonce=nonce, creation_date=timestamp) # genesis = blockchain.genesis() db.add(first) db.commit()
def get_blockchain(): """ get the blockchain from mysql and convert to Blockchain object """ blockchain = Blockchain() blockchain_sql = Table("blockchain", "number", "hash", "previous", "data", "nonce") for b in blockchain_sql.getall(): blockchain.add( Block(int(b.get('number')), b.get('previous'), b.get('data'), int(b.get('nonce')))) return blockchain
def run(self): self.socket.listen(5) print('Node {} is up...'.format(self.node.node_id)) while True: client, caddr = self.socket.accept() serializedData = client.recv(self.bufsize) data = pickle.loads(serializedData) if data: messageType, payload = data if messageType == REQUEST_NEIGHBORS: self.node.sendData((REPLY_NEIGHBORS, self.node.peer_list), payload) if messageType == REPLY_NEIGHBORS: newPeers = set(self.node.peer_list) newPeers.update(payload) self.node.peer_list = list(newPeers) if messageType == TRANSACTION: if payload.hash not in self.node.unSpentTransactions: if payload.isValid(self.node.unSpentTransactions): self.node.unSpentTransactions[ payload.hash] = payload self.node.currBlock.addTransaction( payload, self.node.unSpentTransactions) for peer in self.node.get_peer_list(): self.node.sendData((TRANSACTION, payload), peer) if messageType == BLOCK: if self.node.blockChain.isValidBlock( payload, self.node.unSpentTransactions): for hash in payload.transactions: inputs = payload.transactions[hash].inputs for input in inputs: if input.hash != 'BLOCK-REWARD': transaction = self.node.unSpentTransactions[ input.hash] transaction.outputs[input.index] = None self.node.unSpentTransactions[ input.hash] = transaction self.node.blockChain.addBlock( payload, self.node.unSpentTransactions) self.node.currBlock = Block( payload.index + 1, payload.currHash, datetime.datetime.utcnow().__str__()) for peer in self.node.get_peer_list(): self.node.sendData((BLOCK, payload), peer) client.close()
def mount_block_to_validate(self, data, previous_hash): my_block_data = { 'tipo': data[4], 'quantidade_em_litros': data[5], 'ITGU': data[6], 'localizacao': data[7], 'temperatura': data[8], 'data': data[9], 'qualidade_do_produto': data[10], 'lote': data[11], 'product_id': data[12] } block = Block(my_block_data, data[3], previous_hash, data[1]) block.nonce = data[2] return block
def __init__(self, dim, n_layer, n_head, mlp_dim, eps, drop, attn_drop, is_visualize): super().__init__() self.is_visualize = is_visualize self.layer = nn.ModuleList() for _ in range(n_layer): layer = Block(dim=dim, n_layer=n_layer, n_head=n_head, mlp_dim=mlp_dim, eps=eps, drop=drop, attn_drop=attn_drop, is_visualize=is_visualize) self.layer.append(copy.deepcopy(layer))
def load_data(self): try: target_path = "../target/blockchain" + self.__node_port + ".txt" with open(target_path, mode="r") as file: print("------Loading existing blockchain------") file_content = file.readlines() blockchain = json.loads(file_content[0][:-1]) outstanding_transactions = json.loads(file_content[1][:-1]) updated_blockchain = [] updated_outstanding_transactions = [] for block in blockchain: updated_block = Block( block["prev_hash"], block["index"], [ Transaction( tx["sender"], tx["recepient"], tx["amount"], tx["signature"], tx["timestamp"], ) for tx in block["transactions"] ], block["proof_of_work"], block["timestamp"], ) updated_blockchain.append(updated_block) self.__chain = updated_blockchain for txn in outstanding_transactions: updated_txn = Transaction( txn["sender"], txn["recepient"], txn["amount"], txn["signature"], txn["timestamp"], ) updated_outstanding_transactions.append(updated_txn) self.__outstanding_transactions = updated_outstanding_transactions global participants participants = json.loads(file_content[2][:-1]) peer_nodes = json.loads(file_content[3][:-1]) self.__peer_nodes = set(peer_nodes) self.__node_port = json.loads(file_content[4]) except (IOError, IndexError): print("------Initializing new blockchain with genesis block------")
def newTransaction(): txData = request.get_json() print(txData) transacType = int(txData.get('transacType')) tempUser = users[txData.get('username')] tempPK = tempUser.publicKey tempPK = tempPK.replace("-----BEGIN PUBLIC KEY-----", "") tempPK = tempPK.replace(os.linesep, "") tempPK = tempPK.replace("-----END PUBLIC KEY-----", "") newBlock = Block( 0, transacType, Product(int(txData.get('prodId')), int(txData.get('productType')), False), timeStampToString(), 0, OwnerRelation(tempPK, tempUser.username, tempUser.userType), Location(float(txData.get('latitude')), float(txData.get('longitude'))), 0) blockchain.addNewTransaction(newBlock, transacType) return "Success", 200