def handle_inject_word(self, word): self.cond.acquire() if self.trwordpool: blockchain.add_block(self.dico,self.trwordpool,word) self.cond.notify_all() else: self.wordpool.append(word) self.cond.release()
def inject_word(self, word, head): to_inject = { "word" : word, "head" : head, "politician" : self.pkstr, "signature" : crypto.sign_word(self.sk, word, head, self.pkstr) } server_coms.inject_word(self.socket, to_inject) blockchain.add_block(self.dico,self.trwordpool,to_inject)
def add(): if request.method == 'POST': try: request_data = json.loads(request.data) except: return 'bad json' if 'proof' not in request_data or 'data' not in request_data: return 'missing keys' try: add_block(node_transactions, **request_data) return 'successfully created block' except InvalidProofException: return 'bad proof'
def main(): r = requests.get('http://localhost:5000/trans') chain_repr = json.loads(r.text) genesis = chain_repr[0] validate_genesis(genesis) chain = create_blockchain() for block in chain_repr[1:]: try: add_block(chain, block['data'], block['proof']) except InvalidProofException: print('The chain has been tampered with') print_chain(chain)
def handle_full_wordpool(self, wordpool): """ Only used at the beginning of an Acteur in order to get the period and create the trwordpool """ self.cond.acquire() if self.current_period < wordpool["current_period"]: self.current_period = wordpool["current_period"] self.trwordpool = blockchain.wordpool_to_trwordpool( self.dico, wordpool) for block in self.wordpool: blockchain.add_block(self.dico, self.trwordpool, block) self.wordpool = [] self.cond.notify_all() self.cond.release()
def suggestions(DB): #the other thread called listener.server is listening to peers and adding #suggested transactions and blocks from them into these lists of #suggestions. [blockchain.add_tx(tx, DB) for tx in DB['suggested_txs']] [blockchain.add_block(block, DB) for block in DB['suggested_blocks']] DB['suggested_txs']=[] DB['suggested_blocks']=[]
def suggestions(DB): #the other thread called listener.server is listening to peers and adding #suggested transactions and blocks from them into these lists of #suggestions. for tx in DB['suggested_txs']: #print('SUGGESTED TX') #print('tx: ' +str(tx)) blockchain.add_tx(tx, DB) #[blockchain.add_tx(tx, DB) for tx in DB['suggested_txs']] [blockchain.add_block(block, DB) for block in DB['suggested_blocks']] DB['suggested_txs']=[] DB['suggested_blocks']=[]
def mine(): last_blk = blockchain.last_block last_proof = last_blk.proof proof = blockchain.proof_of_work(last_proof) blockchain.add_transaction(constant.MINER_KEY, node_address, constant.MINER_REWARD, "") prev_hash = last_blk.hash blk = blockchain.add_block(proof, prev_hash) response = { 'message': 'New block mined!', 'index': blk['index'], 'transactions': blk['transactions'], 'proof': blk['proof'], 'previous_hash': blk['prev_hash'] } return jsonify(response), 201
def suggestions(DB): [blockchain.add_tx(tx, DB) for tx in DB['suggested_txs']] DB['suggested_txs'] = [] [blockchain.add_block(block, DB) for block in DB['suggested_blocks']] DB['suggested_blocks'] = []
def suggestions(DB): [blockchain.add_tx(tx, DB) for tx in DB['suggested_txs']] DB['suggested_txs'] = [] [blockchain.add_block(block, DB) for block in DB['suggested_blocks']] DB['suggested_blocks'] = []
def add_data(self, attributes): data, sender, receiver, validator = dict(zip(self.fields, attributes)) bc.add_block(bc.create_block(data, sender, receiver, validator))
def add_new_block(): block_string = "" #set the block_number to 0 block_number = 0 #set the version number of the block to 0 version = 0 #set the id number to 0 id = 0 #set the merkle hash. currently this will be random, will be implemented later merkle_hash = random.getrandbits(128) #set the block_generator_address, this is the public key of the client or validator block_generator_address = sha256(("1234567".encode())).hexdigest() #set the block_generation_proof will be random for now block_generation_proof = "" #set nonce to be zero, but will be randomize later on nonce = 0 #set the status as propose for now status = 'proposed' #set the amount of transactions to be 0 because the genesis block do not have any transactions t_counter = 0 #set the type of statuses type_of_status = ['accepted', 'rejected', 'proposed', 'confirmed'] #this is to create random hash random_string = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f' ] #go through for loop to add the blocks to the chain for i in range(5): #add transactions to the block will be 5 each time based on the add_new_transaction() function transactions = add_new_transactions() #update the amount of transaction in the current block t_counter = t_counter + 5 #update previous hash my_last_block = blockchain.last_block previous_hash = my_last_block.hash #create a block blocks = block.Block( version=version, id=id, transactions=transactions, previous_hash=previous_hash, block_generator_address=block_generator_address, block_generation_proof=block_generation_proof, nonce=nonce, status=status, ) #create a hash for the current block #current_block_hash = blocks.compute_hash() #add the block to the chain blockchain.add_block(blocks, hash(blocks)) #update the id for the next block id = i + 1 #update the merkle root for next block merkle_hash = random.getrandbits(128) #update the block_generator_address block_generator_address = sha256( (str(random_string).encode())).hexdigest() #randomize the random_string array shuffle(random_string) #randomize the block_generation_proof of the next block block_generation_proof = random.randint(1, 101) #update the nonce value to be random nonce = random.randint(1, 101) #randomize the status of the next block status = type_of_status[random.randint(1, 3)] #randomize the type_of_status for the next block shuffle(type_of_status) #go through all the blocks in the chain and add it to block_string to return because flask can't return a list of objects for my_block in blockchain.chain: block_data = json.dumps(my_block.__dict__) block_string = block_string + '\nblock ' + str( block_number) + ': ' + block_data block_number = block_number + 1 return block_string
def consensus(): values = request.get_json() cdata = bytes(values.get('data')) sign = bytes(values.get('sign')) node_id = values.get('id') data = rsa.decrypt(cdata, blockchain.prikey) if not rsa.verify(data, sign, blockchain.nodes[node_id][1]): print("VERIFY ERROR") response = {'message': "Verify Error"} return jsonify(response), 400 data = literal_eval(data.decode('utf8')) phase = data.get('phase') response = None # to prevent replaying previous steps if phase < blockchain.status[0]: print("PREVIOUS STEPS") response = {'message': "Previous Steps {phase}"} return jsonify(response), 202 if phase == 0: # pre-prepare if node_id != blockchain.leader[0]: print("NOT LEADER ERROR") response = {'message': "Leader Error"} return jsonify(response), 400 # get block block = data.get('block') # check either index is right (prevent replay attack) block_idx = block.get('index') if not blockchain.valid_idx(block_idx): print("INVALID INDEX ERROR") response = {'message': "WRONG INDEX OF BLOCK"} return jsonify(response), 400 # check the time (prevent DDoS attack) block_time = block.get('timestamp') if not blockchain.valid_timestamp(block_time): print("WRONG TIMESTAMP ERROR") response = {'message': "WRONG TIMESTAMP OF BLOCK"} return jsonify(response), 400 # update blockchain's view block to block blockchain.current_block = block # status reset blockchain.status[0] = 1 # exec prepare phase threading.Thread(target=blockchain.prepare).start() # response response = { 'id': blockchain.node_identifier, 'result': True } # block is valid return jsonify(response), 201 elif phase == 1: # prepare # get block block = data.get('block') # check either index is right (prevent replay attack) block_idx = block.get('index') if not blockchain.valid_idx(block_idx): response = {'message': "WRONG INDEX OF BLOCK"} return jsonify(response), 400 # check either id is unique(to use set) and block is same if blockchain.status[2].get(str(block), None) is None: # if new block blockchain.status[2][str(block)] = {node_id} else: # exist block blockchain.status[2][str(block)].add(node_id) response = {'id': blockchain.node_identifier, 'result': True} # 2/3 blocks before pre-prepare if blockchain.current_block is None: response = {'id': blockchain.node_identifier, 'result': False} return jsonify(response), 201 # when count is over 2/3 nodes, exec commit phase if len(blockchain.nodes) * 2 < len(blockchain.status[2][str( blockchain.current_block)]) * 3: blockchain.status[0] = 2 threading.Thread(target=blockchain.commit).start() elif phase == 2: # commit # check either index is right (prevent replay attack) block_idx = data.get('index') if not blockchain.valid_idx(block_idx): response = {'message': "WRONG INDEX OF BLOCK"} return jsonify(response), 400 # check either id is unique(to use set) result = literal_eval(data.get('result')) if result == True: blockchain.status[3][0].add(node_id) else: blockchain.status[3][1].add(node_id) # when True count is over 2/3 nodes, send result to mid server if len(blockchain.nodes) * 2 < len(blockchain.status[3][0]) * 3: # add current block to chain blockchain.add_block() # TODO : send result to mid server # reset the settings blockchain.status = [0, None, {}, (set(), set())] blockchain.transactions_buffer = [ x for x in blockchain.transactions_buffer if x not in blockchain.current_transactions ] blockchain.current_block = None blockchain.current_transactions = [] pass # when False count is over 1/3 nodes, send result to mid server if len(blockchain.nodes) < len(blockchain.status[3][1]) * 3: # TODO : send result to mid server # TODO : reset the settings for tx in blockchain.current_transactions: rand_id = tx.get('rand_id') blockchain.utxo[rand_id] = False blockchain.transactions_buffer += blockchain.current_transactions blockchain.current_transactions = [] # TODO : leader change pass else: # error pass return jsonify(response), 201