def new_block(): global transaction_pool data = request.json block = Block.from_dict(data) if blockchain.add_block(block): # Delete transactions from pool transaction_pool = list(filter(lambda x: x not in block.transactions, transaction_pool)) return "New block added" return "Nope"
async def ws_handler(self, request): ws = web.WebSocketResponse() await ws.prepare(request) async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: msg = json.loads(msg.data) if msg["type"] == MessageType.REGISTER_ME: # 새로운 노드 연결 node = msg["nodeinfo"] await self.connect_to_peers([node]) self.nodes.append(node) elif msg["type"] == MessageType.REQUEST_NODE_LIST: # 노드 목록 알려줌 await ws.send_json(self.nodes) elif msg["type"] == MessageType.REQUEST_MAKE_BLOCK: # 블록 생성함 await asyncio.sleep(random.randint(3, 10)) # 해시 푸는 속도라고 가정하자 tr_info = msg["data"] _lastblock = self.chain.get_latest_block() new_block = Block(_lastblock.index + 1, tr_info["data"], tr_info["timestamp"], _lastblock.hash, '') new_block.calculate() if new_block.index > self.chain.latest_block.index: self.chain.add_block(new_block) # 컨펌 받기 await self.broadcast( json.dumps({ "type": MessageType.REQUEST_CONFIRM_BLOCK, "chain": self.chain.json() })) await ws.send_str("[+] Well done !") elif msg["type"] == MessageType.REQUEST_CONFIRM_BLOCK: # 블록 생성 컨펌해줌 blocks = [ Block.from_dict(j) for j in json.loads(msg["chain"]) ] if len(blocks) > self.chain.length: if BlockChain.is_valid_chain(blocks): self.chain.blocks = blocks else: pass elif msg.type == aiohttp.WSMsgType.Error: print('ws connection closed with exception ', ws.exception()) return ws
def get_blocks(): blocks = requests.get(b_url + '/').json() blocks = [Block.from_dict(x) for x in blocks['blocks']] return blocks