ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 블록체인 구조 만들기
    프로그래밍/개발 2018. 6. 15. 00:35

    https://medium.com/crypto-currently/lets-build-the-tiniest-blockchain-e70965a248b

    위 글을 참고해서 파이썬으로 블록체인 구조를 구현해 보았다.

    블록

    아래 코드의 블록체인 구조의 한 블럭은 인덱스(index), 생성 시간(timestamp), hex encoding된 형태의 데이터(data), 이전 블럭의 해시값(prev), 스스로의 해시값(hash)을 가진다.

    코드

    import hashlib
    import datetime
    import binascii
    
    class Block:
        def __init__(self, index, timestamp, data, prev):
            self.index = index
            self.timestamp = timestamp
            self.data = data
            self.prev = prev
            self.hash = self.hash_block()
    
        def hash_block(self):
            sha = hashlib.sha256()
            sha.update((str(self.index) + str(self.timestamp) + 
                       str(self.data) + str(self.prev)).encode())
            return sha.hexdigest()
    
    def encode_data(data):
        return binascii.hexlify(bytes(data, 'UTF-8')).decode()
    
    def create_genesis_block():
        return Block(0, datetime.datetime.now(), encode_data('Genesis!!'), '0')
    
    def next_block(prev_block, block_data):
        block_index = prev_block.index + 1
        block_timestamp = datetime.datetime.now()
        block_hash = prev_block.hash
        return Block(block_index, block_timestamp, block_data, block_hash)
    
    blockchain = [create_genesis_block()]
    prev_block = blockchain[0]
    print(blockchain)
    print('data : ' + blockchain[0].data)
    print('hash : ' + blockchain[0].hash)
    print('prev : ' + blockchain[0].prev)
    
    
    new_block = next_block(prev_block, encode_data('주노귀요미><'))
    blockchain.append(new_block)
    prev_block = new_block
    print(blockchain)
    
    print('data : ' + blockchain[1].data)
    print('hash : ' + blockchain[1].hash)
    print('prev : ' + blockchain[1].prev)
    

    실행 결과

    PS C:\Users\JunhoYeo\Desktop\blockmemo> python .\app.py
    [<__main__.Block object at 0x04B58830>]
    data : 47656e657369732121
    hash : 5c0bf0826a551a4802eb3b4c8bf3d10a0a48617a3c11430cd9cb511285148a0f
    prev : 0
    [<__main__.Block object at 0x04B58830>, <__main__.Block object at 0x04B58850>]
    data : eca3bceb85b8eab780ec9a94ebafb83e3c
    hash : 40645d4a608cec928cffe4bdd91d550e0cf258b3506edd8f41968fc481fe32ec
    prev : 5c0bf0826a551a4802eb3b4c8bf3d10a0a48617a3c11430cd9cb511285148a0f
    PS C:\Users\JunhoYeo\Desktop\blockmemo>
    

    댓글

Designed by Tistory