BlockChain 02 구현

Seungju Hwang·2020년 12월 25일
0

알쓸신기

목록 보기
2/3
post-thumbnail

Intro

앞선 포스팅에서 블록체인의 개념에 대해 공부했다. 이번엔 그 개념대로 간단하게나마 코드로 구현해보고자 합니다. 파이썬을 활용할 거구요. 아래의 그림을 보고 이거에 맞춰서 간단하게 코드로 바꿔봅시다 🤜


🔵 구현

1단계 : 블록만들기

import hashlib
import datetime

class Block():
    #1 
    def __init__(self,index,data):
        self.index=index
        self.data = data
        self.time = datetime.datetime.now()
        self.previoustHash = ''
        self.nonce = 0
        self.hash = self.calHash()
    #2
    def calHash(self):
        return hashlib.sha256(str(self.index).encode() + str(self.data).encode()+ str(self.nonce).encode()+ str(self.time).encode() + str(self.previoustHash).encode()).hexdigest()

    #3
    def mine(self, difficulty):
        ans = ["0"] * difficulty
        answer = "".join(ans)
        while (str(self.hash)[:difficulty] != answer):
            self.nonce += 1
            self.hash = self.calHash()

        return self.hash

#1 : 블록의 구조를 만들어 줘요
#2 : 블록이 생성되면 해쉬함수를 돌려서 해당 블록의 해쉬값을 만들어줘야해요
#3 : 마이닝. 채굴을 해야해요. 합의한 규칙대로 해쉬가 생성되면 그 블록을 연결할 수 있어요. 제가 정한 규칙은 해쉬의 첫번째 값이 '0'이어야 해요.

2단계 : 체인 (블록연결하기)

class BlockChain:
    #1
    def __init__(self):
        self.chain = []
        self.difficulty = 1
        self.createGenesis()

    #2
    def createGenesis(self):
        self.chain.append(Block(0,'Genesis Block'))

    #3
    def addBlock(self,nBlock):
        nBlock.previousHash = self.chain[len(self.chain)-1].hash
        nBlock.hash = nBlock.mine(self.difficulty)
        self.chain.append(nBlock)

    #4
    def isValid(self):
        i = 1
        while (i < len(self.chain)):
            if (self.chain[i].hash != self.chain[i].calHash()):
                return False
            if (self.chain[i].previousHash != self.chain[i - 1].hash):
                return False
            i += 1
        return True

#1 : 체인리스트 초기값 설정하고 GenesisBlock 생성하기 (채굴난이도 1디폴트)
#2 : GenesisBlock 생성하는 코드
#3 : 이전 블록의 해쉬값을 가져와서 현재 블록연결하기
#4 : 체인이 잘 연결되었는 지 확인하는 코드

3단계 : 실행

blockchains = BlockChain()
blockchains.addBlock(Block(len(blockchains.chain), '2nd'))
blockchains.addBlock(Block(len(blockchains.chain), '3rd'))

for block in blockchains.chain:
    print('prevhash: ',block.previoustHash)
    print('timestamp: ',block.time)
    print('nonce: ',block.nonce)
    print('hash: ',block.hash)
    print('data: ',block.data)
    print()

if blockchains.isValid():
    print('잘 만들어졌네요')
  • 결과
$ python blockchain.py
prevhash:  
timestamp:  2020-12-25 13:03:10.634034
nonce:  0
hash:  f5bb828c18cfb6bfbdc364fe926000e8ee5307a71c5e1a934f02cac56880636d
data:  Genesis Block

prevhash:
timestamp:  2020-12-25 13:03:10.634034
nonce:  7
hash:  0cc3fbc176ff819e4c2d7a09de2076ab2b4fd5970dc38b7dbcac443b81c185a3
data:  2nd

prevhash:
timestamp:  2020-12-25 13:03:10.634034
nonce:  25
hash:  0c434348e4bc28ee0eb67454b7564de1d00e773fe836b22d4d6cae44fe6558a5
data:  3rd

잘 만들어졌네요
profile
기록하는 습관은 쉽게 무너지지 않아요.

0개의 댓글