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 recive_block(): block = request.json recived = Block() recived.__dict__ = block print("Block has been recived") CyberCellCoin.add(recived) return request.json
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 _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 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 post(self): json = request.get_json() blockFound = BlockDB.query.filter_by(id=json.get("id")).first() if blockFound is not None: return jsonify( message="Id {0} already exists".format(json.get("id"))) newBlock = BlockDB() newBlock.id = json.get("id"), newBlock.block_name = json.get("block_name") db.session.add(newBlock) db.session.commit() return jsonify(message="Block saved")
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 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 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 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 __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 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 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 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 load(cls): with open(cls.PATH, "r") as rf: wallet_json = json.load(rf) wallet_xpub = ExtPubKey(wallet_json["wallet_xpub"]) master_fingerprint = x(wallet_json["master_fingerprint"]) base_keypath = HDKeyPath(wallet_json["base_keypath"]) current_block = Block.from_json(wallet_json["current_block"]) raw_external_addresses = wallet_json["external_addresses"] raw_change_addresses = wallet_json["change_addresses"] external_addresses = [ WalletAddress( wallet_xpub, base_keypath, child_number, False, address["was_recovered"], address["is_fresh"], [Utxo.from_json(utxo) for utxo in address["utxos"]], address.get("label")) for child_number, address in enumerate(raw_external_addresses) ] change_addresses = [ WalletAddress( wallet_xpub, base_keypath, child_number, True, address["was_recovered"], address["is_fresh"], [Utxo.from_json(utxo) for utxo in address["utxos"]]) for child_number, address in enumerate(raw_change_addresses) ] return (wallet_xpub, master_fingerprint, base_keypath, current_block, external_addresses, change_addresses)
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 unblock(form): by = User.find_by('username', form['stalker']) blocked = User.find_by('username', form['victim']) unblock = Block.find_both('by_id', by.getId(), 'blocked_id', blocked.getId()) unblock.delete() return redirect(url_for('profile', username=form['victim']))
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 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 block(form): by = User.find_by('username', form['stalker']) blocked = User.find_by('username', form['victim']) infos = {} infos['by_id'] = by.getId() infos['blocked_id'] = blocked.getId() block = Block.create(infos) return redirect(url_for('profile', username=form['victim']))
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 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 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 __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 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 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 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 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 from_json(cls, json: dict): return cls( Block.from_json(json["block"]), TxIn( OutPoint( lx(json["prevout"]["hash"]), json["prevout"]["n"] ) ), TxOut( json["value"], lx(json["script_pubkey"]) ) )