2. Overview
Characteristics of blockchain
Python
Simple Http Server by Python
Make your own code and APIs
Block, Hashing
Transaction
Design your transaction model
Making Block
Merge with your BlockChain and Http Server
Propagating Block to other nodes
3. Characteristic of BlockChain
Transactions
Blocks
Snapshot or Chaining between Blocks
Hash for a integrity
Validating of existing Blocks
Interface or Interact with other nodes
etc…
9. Practice #1
사용자가 요청한 주소의 Query String을 분해하여 HTML로 리턴하시오.
예>
http://localhost:8080/api/v1/getrecord?city=seoul&zipcode=08206&mobile=01012341234&nickname=cat
위 요청에 대한 응답 (HTML)
city : seoul
zipcode : 08206
mobile : 01012341234
nickname : cat
10. Practice #2
서버에서 python socket serve를 실행하자
포트 번호 : 80 + 학번 끝 두자리로 설정
116번 서버에 본인 작업 디렉토리에서 소켓 서버를 실행하고
http://192.168.110.116:80xx/api/v1/ping 을 호출했을 때 본문없이 200 응답을 리턴
예시> 학번 끝자리가 23번인 학생의 경우
본인의 소켓서버를 116번 서버의 /home/smrt0023/ 폴더에 업로드
소켓서버를 실행(포트번호는 8023)
교수가 http://192.168.110.116:8023/api/v1/ping 을 호출했을때 200 OK 응답을 주면 성공
17. Practice #3
Make your own APIs on Development Server
포트 번호 : 80 + 학번 끝 두자리로 설정
API Spec 작성 및 테스트 결과를 Development Server에 업로드
- 업로드 위치 : /home/smrt00xx/…
- 실행 : python 000.py
- 테스트 : http://192.168.110.116:80xx/api/v1/addrecord
- API Spec. : API기본정보(요청URL, 포맷, 방식), 요청변수, 출력결과, 에러코드
18. Practice #3 (Cont.)
항목 정보 비고
요청URL http://192.168.110.116:80XX/api/v1/addrecord
요청Format JSON 형식
예> {“key1": [“value1",“value2"], “key2": “value1"}
요청Method POST
출력Format 입력요청한 JSON을 코드소유자 정보 추가하여 리턴
예> {“key1": [“value1",“value2"], “key2": “value1“, author:hwy}
결과code 성공시 200
실패시 403
…
API Specification 예시
20. Genesis Block
6 Attributes
• Index – it’s position in the blockchain
• Previous Hash – the hash of the block that came before the current block
• Timestamp – the time the block was created
• Data – the information (e.g. transactions) that the block carries
• Hash – the hash of the block itself.
• proof – proof of work
21. 블록의 구조
class Block:
#A basic block contains, index (blockheight), the previous hash, a timestamp, tx information, a nonce, and the current hash
def __init__(self, index, previousHash, timestamp, data, proof, currentHash):
self.index = index
self.previousHash = previousHash
self.timestamp = timestamp
self.data = data
self.currentHash = currentHash
self.proof = proof
출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
블록의 높이
거래 데이터
블록생성시점
이전블록의 해쉬값(이전블록의 연결고리, 스냅샷)
현재 블록의 해쉬값
작업증명 값( XX횟수)
22. 블록데이터 리턴
Sequence Diagram
readBlockchain
블록체인 DB가 존재한다면?
if yes, DB를 읽어서 return
else 빈 데이터를 return
25. At the moment,
블록데이터가 없는 상황
블록데이터 생성이 필요
신규API를 생성하여 Genesis Block을 생성해야 함
~/block/generateBlock를 추가하자
블록을 구성할 데이터(Transaction Data)는 어떻게 구성할 것인가?
일단은, 임시 랜덤데이터를 구성하자
transaction = 'UserID ' + str(txFrom) + " sent " + str(amount) + ' bitTokens to UserID ' + str(txTo) + ". “
차후, 개인 또는 그룹별 블록체인 비즈니스 아이디어를 반영한 트랜잭션으로 수정예정
34. Genesis Block
Now we can create genesis block.
def getGenesisBlock():
timestamp = time.time()
print("# timestamp를 찍어본다.")
print("time.time() => %f n" % timestamp)
tempHash = calculateHash(0,'0',timestamp,"My very first block",0)
print(tempHash)
return Block(0, '0', timestamp, "My very first block", 0, tempHash)
blockchain = [getGenesisBlock()]
출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
DB에 생성된 블록이 없을 경우 호출됨
현 블록의 해쉬값을 생성
(index, previousHash, timestamp, data, proof)
43. Validation Blocks
def isValidChain(bcToValidate):
genesisBlock = []
bcToValidateForBlock = []
# Read GenesisBlock
try:
with open('blockchain.csv', 'r') as file:
blockReader = csv.reader(file)
for line in blockReader:
block = Block(line[0], line[1], line[2], line[3], line[4], line[5])
genesisBlock.append(block)
break
except:
print("file open error in isValidChain")
pass
# transform given data to Block object
for line in bcToValidate:
# print(type(line))
# index, previousHash, timestamp, data, currentHash, proof
block = Block(line['index'], line['previousHash'], line['timestamp'], line['data'], line['currentHash'], line['proof'])
bcToValidateForBlock.append(block)
#if it fails to read block data from db(csv)
if not genesisBlock:
print("fail to read genesisBlock")
return False
# compare the given data with genesisBlock
if not isSameBlock(bcToValidateForBlock[0], genesisBlock[0]):
print('Genesis Block Incorrect')
return False
tempBlocks = [bcToValidateForBlock[0]]
for i in range(1, len(bcToValidateForBlock)):
if isValidNewBlock(bcToValidateForBlock[i], tempBlocks[i - 1]):
tempBlocks.append(bcToValidateForBlock[i])
else:
return False
return True
CSV REST Call
Genesis
Block
Genesis
Block
=
47. Transaction Data
As-Is Transaction Data (5 random data)
“UserID <random number> sent <random number> bitTokens to UserID <random number>.”
To-Be Transaction Data
index currentHash timestamp transaction data
<<Block>>
<<Transactions>>
commitYN sender amount receiver UUID(unique #)
채굴포함여부