Ejemplo n.º 1
0
def test_block():
    corner = Block(['Y', 'O', 'G'])
    edge = Block(['Y', 'O'])
    center1 = Block(['Y'])
    center2 = Block(['Y', 'O', 'G', 'R'])

    assert type(corner.stickers) is list
    assert len(corner.stickers) == 3
    assert corner.stickers == ['Y', 'O', 'G']
    assert corner.block_type == 'corner'

    assert type(edge.stickers) is list
    assert len(edge.stickers) == 2
    assert edge.stickers == ['Y', 'O']
    assert edge.block_type == 'edge'

    assert type(center1.stickers) is list
    assert len(center1.stickers) == 1
    assert center1.stickers == ['Y']
    assert center1.block_type == 'center'

    assert type(center2.stickers) is list
    assert len(center2.stickers) == 4
    assert center2.stickers == ['Y', 'O', 'G', 'R']
    assert center2.block_type == 'center'
Ejemplo n.º 2
0
 def create_genesis_block(self):
     """
     A function to generate genesis block and appends it to
     the chain. The block has index 0, previous_hash as 0, and
     a valid hash.
     """
     genesis_block = Block(0,[],0,'0')
     genesis_block.hash = self._compute_hash()
     self.chain.append(genesis_block)
Ejemplo n.º 3
0
def start(thread_name, ip_address, port):
    import json

    addr = (ip_address, port)
    buf_size = 10240

    # 소켓 생성 및 바인딩
    tcp_socket = socket(AF_INET, SOCK_STREAM)
    tcp_socket.bind(addr)
    tcp_socket.listen(5)

    while is_running:

        # 요청이 있을경우 소켓과 송신자의 ip 주소 저장
        receive_socket, sender_ip = tcp_socket.accept()

        while is_running:
            print("Receiving")

            # 소켓으로부터 버퍼 사이즈씩 데이터 수신
            data = receive_socket.recv(buf_size)
            try:
                # 수신된 데이터가 없는 경우
                if (len(data) == 0):
                    break

                print("data received...")

                # json 형태의 데이터를 dict 타입으로 변경
                data_json_obj = json.loads(data)

                # Transaction을 받은 경우
                if data_json_obj['type'] == 'T':
                    print("Received transaction")
                    print(data_json_obj)

                    # dict 데이터로부터 transaction 객체 생성
                    tx = Transaction().from_json(data_json_obj)

                    # transaction 추가
                    transaction.add_transaction(tx)

                elif data_json_obj['type'] == 'B':
                    print("block received...")
                    # 기존 transacion 삭제
                    transaction.remove_all()

                    #블록 추가
                    received_block = Block().from_json(data_json_obj)

                    append_block(received_block)

            except:
                print("recv error...")
                traceback.print_exc()
                break

    tcp_socket.close()
    receive_socket.close()
Ejemplo n.º 4
0
def create_block():
	transactions = transaction.get_transactions()

	# transaction이 없을 경우 block을 생성하지 않음
	if len(transactions) == 0:
		return

	# 내 node 가 가지고 있는 마지막 블럭
	last_block = block.get_last_block()

	# transaction JSON 문자열로 변환
	transactions_str = list(map(lambda x: x.to_json(), transactions))

	# transaction으로부터 merkle root 생성
	merkle_root = merkle_tree(transactions_str)

	# block 정보에 merkle root 할당
	block_info = merkle_root

	# block 새로 생성
	_block = Block()

	# 마지막 block이 있는 경우
	if last_block:
		# block 정보에 마지막 블럭의 해쉬를 더함
		block_info += last_block.block_hash

		# 새로 생성한 block에 이전 block 정보 저장
		_block.prev_block_hash = last_block.block_hash
		_block.prev_block_id = last_block.block_id

	# 작업 증명을 통해 nonce값과 hash 결과 생성
	hash_result, nonce = proof_of_work(block_info, diff_bits=5)

	# block 정보
	_block.block_hash = hash_result
	_block.nonce = nonce
	_block.block_info = block_info
	_block.time_stamp = datetime.datetime.now()

	# 내 node 에 block 저장
	block.create_block(_block)

	# 내 node가 가지고 있는 transaction 삭제
	transaction.remove_all()

	# 나머지 node에게 block 전송
	sender.send_to_all_node((_block.to_json()), except_my_node=True)
Ejemplo n.º 5
0
def verify_and_add_block():
    block_data = request.get_json()
    block = Block(block_data["index"],
                  block_data["transactions"],
                  block_data["timestamp"],
                  block_data["previous_hash"],
                  block_data["nonce"])

    proof = block_data['hash']
    added = blockchain.add_block(block, proof)

    if not added:
        return "The block was discarded by the node", 400

    return "Block added to the chain", 201
Ejemplo n.º 6
0
def create_chain_from_dump(chain_dump):
    generated_blockchain = Blockchain()
    generated_blockchain.create_genesis_block()
    for idx, block_data in enumerate(chain_dump):
        if idx == 0:
            continue  # skip genesis block
        block = Block(block_data["index"],
                      block_data["transactions"],
                      block_data["timestamp"],
                      block_data["previous_hash"],
                      block_data["nonce"])
        proof = block_data['hash']
        added = generated_blockchain.add_block(block, proof)
        if not added:
            raise Exception("The chain dump is tampered!!")

    return generated_blockchain
Ejemplo n.º 7
0
    def mine(self):
        """
        This function serves as an interface to add the pending
        transactions to the blockchain by adding them to the block
        and figuring out Proof Of Work.
        """
        
        if not self.unconfirmed_transactions:
            return False

        #last block of chain
        last_block = self.last_block

        new_block = Block(index=last_block.index + 1,
                          transactions=self.unconfirmed_transactions,
                          timestamp=time.time(),
                          previous_hash=last_block.hash)

        proof = self.proof_of_work(new_block)
        self.add_block(new_block, proof)
        self.unconfirmed_transactions = []

        return True
Ejemplo n.º 8
0
def start(thread_name, ip_address, port):
    import json

    addr = (ip_address, port)
    buf_size = 1024

    # 소켓 생성 및 바인딩
    tcp_socket = socket(AF_INET, SOCK_STREAM)
    tcp_socket.bind(addr)
    tcp_socket.listen(5)

    while is_running:

        # 요청이 있을 경우 소켓과 송신자의 ip 주소 저장
        receive_socket, sender_ip = tcp_socket.accept()

        while is_running:
            log.write("Receiving")

            # 소켓으로부터 버퍼 사이즈씩 데이터 수신
            data = receive_socket.recv(buf_size)
            try:

                # 수신된 데이터가 없는 경우
                if len(data) == 0:
                    break

                # json 형태의 데이터를 dict 타입으로 변경
                data_json_obj = json.loads(data)

                # Transaction을 받은 경우
                if data_json_obj['type'] == 'T':
                    log.write("Receiving a transaction")

                    verify_msg = data_json_obj['time_stamp'] + data_json_obj[
                        'message']

                    if key.verify_signature(data_json_obj['pub_key'],
                                            data_json_obj['signature'],
                                            verify_msg) is True:
                        log.write("Transaction is valid")
                        tx = Transaction().from_json(data_json_obj)
                        transaction.add_transaction(tx)
                    else:
                        log.write("Transaction is invalid")

                # 블록을 수신한 경우
                elif data_json_obj['type'] == 'B':
                    # 기존의 트랜잭션 삭제
                    transaction.remove_all()

                    # 블록 생성
                    received_block = Block().from_json(data_json_obj)

                    # 블록 저장
                    create_block(received_block)

            except:
                traceback.print_exc()
                break

    tcp_socket.close()
    receive_socket.close()
Ejemplo n.º 9
0
 def __init__(self):
     Block.__init__(self,0,[],0,'0')
     self.unconfirmed_transactions = []
     self.chain = []
Ejemplo n.º 10
0
def create_block():

    diff_bits = 5
    transactions = transaction.get_transactions()

    # transaction이 없을 경우 block을 생성하지 않음
    if (len(transactions) == 0):
        print("No transactions...")
        return

    # 내 node가 가지고 있는 마지막 블럭
    last_block = block.get_last_block()

    #transaction JSON 문자열로 변환
    transactions_str = []
    for tx in transactions:
        transactions_str.append(tx.to_json())

    # transaction 으로부터 merkle root 생성
    merkle_root = merkle_tree(transactions_str)

    # block 새로 생성
    _block = Block()

    # 마지막 블록이 있는 경우
    if last_block:

        # last bock 에 대한 정보 저장
        _block.prev_block_id = last_block.block_id
        _block.prev_block_hash = last_block.block_hash

        # 작업 증명을 위해 nonce값과 결과 생성
        _block.block_id = last_block.block_id + 1
        _block.merkle_root = merkle_root
        _block.difficulty = diff_bits

        block_header = _block.getheader_json()
        hash_result, nonce = proof_of_work(block_header, diff_bits)

        # block 정보
        _block.block_hash = hash_result
        _block.nonce = nonce
        _block.tx_list = transactions_str

        # 내 node에 block 저장
        block.append_block(_block)

        # 내 node가 가지고 있는 transaction 삭제
        transaction.remove_all()

        # 나머지 node에게 block 전송
        sender.send_to_all_node((_block.to_json()), except_my_node=True)
Ejemplo n.º 11
0
 def __init__(self):
     Block.__init__(self, 0, [], 0, '0')