SlideShare a Scribd company logo
1 of 76
Download to read offline
BlockChain on Python
한국폴리텍대학(Korea Polytechnics)
스마트금융과(dept. of Smart Finance)
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
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…
Python
development environment
 Python
 Anaconda
 Jupyter
 Pycharm
 Ftp, Linux Server, REST Test Tool(ARC, Post Man, Fiddler,…)
 Git, File Compare Tools …
python http server
Simple HTTP Server
by Python (GET)
참조 : https://mafayyaz.wordpress.com/2013/02/08/writing-simple-http-server-in-python-with-rest-and-json/
참조 : https://docs.python.org/3/library/http.server.html?highlight=basehttprequesthandler#http.server.BaseHTTPRequestHandler
Simple HTTP Server
by Python (GET) – Review
 python 문자열 다루기 : split
Simple HTTP Server
by Python (GET) – Review
 좀 더 Python 한 방법은?
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
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 응답을 주면 성공
Fiddler로 테스트하기
GET POST(application/json) POST(form based)
Postman 설치
 [H/W] 크롬 웹스토어에서 postman 으로 검색하고 설치 & 테스트
Simple HTTP Server
by Python (POST)
application/json;encode=utf-8
ctype pdict
Simple HTTP Server
by Python (POST)
Simple HTTP Server
by Python (POST)
Simple HTTP Server
by Python (POST)
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, 포맷, 방식), 요청변수, 출력결과, 에러코드
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 예시
blockchain implementation on
python
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
블록의 구조
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횟수)
블록데이터 리턴
 Sequence Diagram
readBlockchain
블록체인 DB가 존재한다면?
if yes, DB를 읽어서 return
else 빈 데이터를 return
Source Code
 API Interface
Source Code
블록체인 DB가 존재한다면?
if yes, DB를 읽어서 return
블록체인 DB가 존재 X
빈 데이터를 return
At the moment,
블록데이터가 없는 상황
 블록데이터 생성이 필요
 신규API를 생성하여 Genesis Block을 생성해야 함
~/block/generateBlock를 추가하자
 블록을 구성할 데이터(Transaction Data)는 어떻게 구성할 것인가?
일단은, 임시 랜덤데이터를 구성하자
transaction = 'UserID ' + str(txFrom) + " sent " + str(amount) + ' bitTokens to UserID ' + str(txTo) + ". “
차후, 개인 또는 그룹별 블록체인 비즈니스 아이디어를 반영한 트랜잭션으로 수정예정
Source Code
(~/block/generateBlock)
 API Interface
블록데이터 생성 흐름
getTxDatareadBlockchainmineNewBlock
블록체인 DB가 존재한다면?
if yes, DB를 읽어서 return
else, “Genesis Block” 생성하여 return
calculateHashgenerateNewBlock writeBlockchain
해쉬값이 우리가 정한 난이도와 일치한다면?
if yes, 블록체인 기록
else, generateNewBlock 반복
mineNewBlock
def mineNewBlock(difficulty = 5, blockchainPath = 'blockchain.csv'):
blockchain = readBlockchain(blockchainPath)
txData = getTxData()
timestamp = time.time()
proof = 0
newBlockFound = False
print('Mining a block...')
while not newBlockFound:
#print("Trying new block proof...")
newBlockAttempt = generateNextBlock(blockchain, txData, timestamp, proof)
if newBlockAttempt.currentHash[0:difficulty] == '0'*difficulty:
stopTime = time.time()
timer = stopTime - timestamp
print('New block found with proof', proof, 'in', round(timer, 2), 'seconds.')
newBlockFound = True
else:
proof += 1
blockchain.append(newBlockAttempt)
writeBlockchain(blockchain)
def mine(blocksToMine = 5):
for _ in range(blocksToMine):
mineNewBlock()
출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
readBlockchain
getTxData (old)
def getLatestBlock(blockchain):
return blockchain[len(blockchain)-1]
def generateNextBlock(blockchain, blockData, timestamp, proof):
previousBlock = getLatestBlock(blockchain)
nextIndex = int(previousBlock.index) + 1
nextTimestamp = timestamp
nextHash = calculateHash(nextIndex, previousBlock.currentHash, nextTimestamp, proof, blockData)
return Block(nextIndex, previousBlock.currentHash, nextTimestamp, blockData, proof, nextHash)
배열
출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
generateNextBlock
def calculateHash(index, previousHash, timestamp, data, proof):
value = str(index) + str(previousHash) + str(timestamp) + str(data) + str(proof)
sha = hashlib.sha256(value.encode('utf-8'))
return str(sha.hexdigest())
Hash 대상 : 현재 블록의 인덱스 + 이전 블록의 Hash + 현 블록의 TimeStamp + 현 블록의 거래데이터 + PoW(#)
출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
calculateHash
writeBlockchain
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)
테스트
블록체인 데이터 조회하기
 블록데이터 조회
~/block/getBlockData로 조회하자
So far we can
 Create a genesis block
 Hash blocks
 Create additional blocks
Practice #3
 Design Your Own Transaction Data
Validation Blockchain
이제 검증을 위한 API를 추가해 봅시다.
 검증로직 설계
 신규API를 생성하여 검증대상인 블록체인 데이터를 받아야 함(POST)
~/block/validateBlock/를 추가하자
- input과 output은 어떻게 설계해야 하는가?
Validation Blocks
출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
Validation Blocks
출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
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
=
테스트
Practice #4
 Design Post API of a new transaction data
manage transactions
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 #)
채굴포함여부
class txData
 5 attributes
블록 포함여부(채굴) : commitYN
송신자 : sender
금액 : amount
수신자 : receiver
고유식별값 : uuid
class txData:
def __init__(self, commitYN, sender, amount, receiver, uuid):
self.commitYN = commitYN
self.sender = sender
self.amount = amount
self.receiver = receiver
self.uuid = uuid
POST API 추가하기
(transaction data)
Transaction Data
(Dictionary  Instance of class txData)
import uuid 필요
예> 369a1e95-3723-4b26-8ab8-9bcc2c5938f0
Write
Transaction
Data
<<temp csv>><<txData csv>>
new tx data
<<temp csv>> <<txData csv>>
getTxData 수정
예> [6b3b3c1e-858d-4e3b-b012-8faac98b49a8]UserID hwang sent 333 bitTokens to UserID kim.
read txData from csv
Update txData of csv #1
(when it has been mined)
 채굴되었다면?
Update txData of csv #2
정규표현식
row[4]row[0]
테스트
Practice #5
 Design Post API of a sending transaction data
Broadcast
set up
 library, global variables
타 노드로 채굴 정보를 POST하기 위한 라이브러리
노드간 인터페이스 API
노드 정보(서버IP, Port) 를 저장하는 파일
broadcast block when it mined
타 노드로 전파
broadcastNewBlock
방금 채굴된 블록을 포함한 블록체인 정보를
인접 노드의 API(receiveNewBlock)로
POST 호출하여 전달
readNodes
노드 정보(서버IP, Port) 를 읽어오기
addNode
http://localhost:8099/node/addNode?127.0.0.1:8096
addNode
receive new block info
g_receiveNewBlock = "/node/receiveNewBlock"
compare blockchain info
 latest block +1 != broadcasted last block
latest block == broadcasted last block
latest block +1 < broadcasted last block
latest block +1 > broadcasted last block
 latest block +1 == broadcasted last block
compare and merge
ExceptionalCase
ExceptionalCase
ExceptionalCase
initSvr (1/2)
 인접 노드 정보 구하기
initSvr (2/2)
 블록체인 정보 구하기
g_bcFileName = "blockchain.csv"
붙임
related sites…
 __dict__ 설명 : https://wikidocs.net/1743
 json.dump 설명 : http://pythonstudy.xyz/python/article/205-JSON-%EB%8D%B0%EC%9D%B4%ED%83%80
https://kimdoky.github.io/python/2017/11/11/library-book-chap8-4.html
https://docs.python.org/3/library/json.html
 람다식 설명 : https://wikidocs.net/64
정규표현식(Regular Expression)
돌아가기
정규표현식(Regular Expression)

More Related Content

What's hot

glance replicator
glance replicatorglance replicator
glance replicatoririx_jp
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in VaultGlynnForrest
 
K8s上の containerized cloud foundryとcontainerized open stackをprometheusで監視してみる
K8s上の containerized cloud foundryとcontainerized open stackをprometheusで監視してみるK8s上の containerized cloud foundryとcontainerized open stackをprometheusで監視してみる
K8s上の containerized cloud foundryとcontainerized open stackをprometheusで監視してみるJUNICHI YOSHISE
 
Roll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaRoll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaJon Moore
 
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門tamtam180
 
It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?MongoDB
 
Hyperledger Fabric v2.0 Alpha - FabToken Overview, Hands-On Lab
Hyperledger Fabric v2.0 Alpha - FabToken Overview, Hands-On LabHyperledger Fabric v2.0 Alpha - FabToken Overview, Hands-On Lab
Hyperledger Fabric v2.0 Alpha - FabToken Overview, Hands-On LabHyperledger Korea User Group
 
SSH I/O Streaming via Redis-based Persistent Message Queue -Mani Tadayon
 SSH I/O Streaming via Redis-based Persistent Message Queue -Mani Tadayon SSH I/O Streaming via Redis-based Persistent Message Queue -Mani Tadayon
SSH I/O Streaming via Redis-based Persistent Message Queue -Mani TadayonRedis Labs
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsAndrei Pangin
 
9 password security
9   password security9   password security
9 password securitydrewz lin
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploySimon Su
 
Distributed systems at ok.ru #rigadevday
Distributed systems at ok.ru #rigadevdayDistributed systems at ok.ru #rigadevday
Distributed systems at ok.ru #rigadevdayodnoklassniki.ru
 
Riak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup GroupRiak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup Groupsiculars
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBMongoDB
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?Andrei Pangin
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with phpElizabeth Smith
 

What's hot (20)

glance replicator
glance replicatorglance replicator
glance replicator
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in Vault
 
K8s上の containerized cloud foundryとcontainerized open stackをprometheusで監視してみる
K8s上の containerized cloud foundryとcontainerized open stackをprometheusで監視してみるK8s上の containerized cloud foundryとcontainerized open stackをprometheusで監視してみる
K8s上の containerized cloud foundryとcontainerized open stackをprometheusで監視してみる
 
Top Node.js Metrics to Watch
Top Node.js Metrics to WatchTop Node.js Metrics to Watch
Top Node.js Metrics to Watch
 
Roll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaRoll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and Lua
 
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
 
It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?
 
Hyperledger Fabric v2.0 Alpha - FabToken Overview, Hands-On Lab
Hyperledger Fabric v2.0 Alpha - FabToken Overview, Hands-On LabHyperledger Fabric v2.0 Alpha - FabToken Overview, Hands-On Lab
Hyperledger Fabric v2.0 Alpha - FabToken Overview, Hands-On Lab
 
OWASP Proxy
OWASP ProxyOWASP Proxy
OWASP Proxy
 
SSH I/O Streaming via Redis-based Persistent Message Queue -Mani Tadayon
 SSH I/O Streaming via Redis-based Persistent Message Queue -Mani Tadayon SSH I/O Streaming via Redis-based Persistent Message Queue -Mani Tadayon
SSH I/O Streaming via Redis-based Persistent Message Queue -Mani Tadayon
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
 
Django cryptography
Django cryptographyDjango cryptography
Django cryptography
 
9 password security
9   password security9   password security
9 password security
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploy
 
Distributed systems at ok.ru #rigadevday
Distributed systems at ok.ru #rigadevdayDistributed systems at ok.ru #rigadevday
Distributed systems at ok.ru #rigadevday
 
Riak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup GroupRiak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup Group
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDB
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
 

Similar to BlockChain implementation by python

Luciano Mammino - Cracking JWT tokens: a tale of magic, Node.JS and parallel...
Luciano Mammino  - Cracking JWT tokens: a tale of magic, Node.JS and parallel...Luciano Mammino  - Cracking JWT tokens: a tale of magic, Node.JS and parallel...
Luciano Mammino - Cracking JWT tokens: a tale of magic, Node.JS and parallel...Codemotion
 
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingCracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingLuciano Mammino
 
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...Luciano Mammino
 
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...Mariya James
 
Drive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteerDrive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteerVodqaBLR
 
Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
 Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
Conceptos básicos. Seminario web 2: Su primera aplicación MongoDBMongoDB
 
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019Matt Raible
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationGDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationKAI CHU CHUNG
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)MongoDB
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problemstitanlambda
 
02 banking trojans-thomassiebert
02 banking trojans-thomassiebert02 banking trojans-thomassiebert
02 banking trojans-thomassiebertgeeksec80
 
비동기 회고 발표자료
비동기 회고 발표자료비동기 회고 발표자료
비동기 회고 발표자료Benjamin Kim
 
Rpi python web
Rpi python webRpi python web
Rpi python websewoo lee
 
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET CoreNETFest
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebChristian Baranowski
 

Similar to BlockChain implementation by python (20)

Blockchain - a simple implementation
Blockchain - a simple implementationBlockchain - a simple implementation
Blockchain - a simple implementation
 
Luciano Mammino - Cracking JWT tokens: a tale of magic, Node.JS and parallel...
Luciano Mammino  - Cracking JWT tokens: a tale of magic, Node.JS and parallel...Luciano Mammino  - Cracking JWT tokens: a tale of magic, Node.JS and parallel...
Luciano Mammino - Cracking JWT tokens: a tale of magic, Node.JS and parallel...
 
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingCracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
 
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...
 
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
 
BPjs deep dive 2019
BPjs deep dive 2019BPjs deep dive 2019
BPjs deep dive 2019
 
Drive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteerDrive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteer
 
Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
 Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
 
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
 
Java
JavaJava
Java
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationGDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
02 banking trojans-thomassiebert
02 banking trojans-thomassiebert02 banking trojans-thomassiebert
02 banking trojans-thomassiebert
 
비동기 회고 발표자료
비동기 회고 발표자료비동기 회고 발표자료
비동기 회고 발표자료
 
Rpi python web
Rpi python webRpi python web
Rpi python web
 
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 

More from wonyong hwang

Hyperledger Explorer.pptx
Hyperledger Explorer.pptxHyperledger Explorer.pptx
Hyperledger Explorer.pptxwonyong hwang
 
하이퍼레저 페이지 단위 블록 조회
하이퍼레저 페이지 단위 블록 조회하이퍼레저 페이지 단위 블록 조회
하이퍼레저 페이지 단위 블록 조회wonyong hwang
 
토큰 증권 개요.pptx
토큰 증권 개요.pptx토큰 증권 개요.pptx
토큰 증권 개요.pptxwonyong hwang
 
Vue.js 기초 실습.pptx
Vue.js 기초 실습.pptxVue.js 기초 실습.pptx
Vue.js 기초 실습.pptxwonyong hwang
 
Deploying Hyperledger Fabric on Kubernetes.pptx
Deploying Hyperledger Fabric on Kubernetes.pptxDeploying Hyperledger Fabric on Kubernetes.pptx
Deploying Hyperledger Fabric on Kubernetes.pptxwonyong hwang
 
k8s practice 2023.pptx
k8s practice 2023.pptxk8s practice 2023.pptx
k8s practice 2023.pptxwonyong hwang
 
HyperLedger Fabric V2.5.pdf
HyperLedger Fabric V2.5.pdfHyperLedger Fabric V2.5.pdf
HyperLedger Fabric V2.5.pdfwonyong hwang
 
Ngrok을 이용한 Nginx Https 적용하기.pptx
Ngrok을 이용한 Nginx Https 적용하기.pptxNgrok을 이용한 Nginx Https 적용하기.pptx
Ngrok을 이용한 Nginx Https 적용하기.pptxwonyong hwang
 
Nginx Https 적용하기.pptx
Nginx Https 적용하기.pptxNginx Https 적용하기.pptx
Nginx Https 적용하기.pptxwonyong hwang
 
Kafka JDBC Connect Guide(Postgres Sink).pptx
Kafka JDBC Connect Guide(Postgres Sink).pptxKafka JDBC Connect Guide(Postgres Sink).pptx
Kafka JDBC Connect Guide(Postgres Sink).pptxwonyong hwang
 
Nginx Reverse Proxy with Kafka.pptx
Nginx Reverse Proxy with Kafka.pptxNginx Reverse Proxy with Kafka.pptx
Nginx Reverse Proxy with Kafka.pptxwonyong hwang
 
Kafka monitoring using Prometheus and Grafana
Kafka monitoring using Prometheus and GrafanaKafka monitoring using Prometheus and Grafana
Kafka monitoring using Prometheus and Grafanawonyong hwang
 
주가 정보 다루기.pdf
주가 정보 다루기.pdf주가 정보 다루기.pdf
주가 정보 다루기.pdfwonyong hwang
 
App development with quasar (pdf)
App development with quasar (pdf)App development with quasar (pdf)
App development with quasar (pdf)wonyong hwang
 
Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0) Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0) wonyong hwang
 
Hyperledger fabric practice(pdf)
Hyperledger fabric practice(pdf)Hyperledger fabric practice(pdf)
Hyperledger fabric practice(pdf)wonyong hwang
 

More from wonyong hwang (20)

Hyperledger Explorer.pptx
Hyperledger Explorer.pptxHyperledger Explorer.pptx
Hyperledger Explorer.pptx
 
하이퍼레저 페이지 단위 블록 조회
하이퍼레저 페이지 단위 블록 조회하이퍼레저 페이지 단위 블록 조회
하이퍼레저 페이지 단위 블록 조회
 
토큰 증권 개요.pptx
토큰 증권 개요.pptx토큰 증권 개요.pptx
토큰 증권 개요.pptx
 
Vue.js 기초 실습.pptx
Vue.js 기초 실습.pptxVue.js 기초 실습.pptx
Vue.js 기초 실습.pptx
 
Deploying Hyperledger Fabric on Kubernetes.pptx
Deploying Hyperledger Fabric on Kubernetes.pptxDeploying Hyperledger Fabric on Kubernetes.pptx
Deploying Hyperledger Fabric on Kubernetes.pptx
 
k8s practice 2023.pptx
k8s practice 2023.pptxk8s practice 2023.pptx
k8s practice 2023.pptx
 
HyperLedger Fabric V2.5.pdf
HyperLedger Fabric V2.5.pdfHyperLedger Fabric V2.5.pdf
HyperLedger Fabric V2.5.pdf
 
Ngrok을 이용한 Nginx Https 적용하기.pptx
Ngrok을 이용한 Nginx Https 적용하기.pptxNgrok을 이용한 Nginx Https 적용하기.pptx
Ngrok을 이용한 Nginx Https 적용하기.pptx
 
Nginx Https 적용하기.pptx
Nginx Https 적용하기.pptxNginx Https 적용하기.pptx
Nginx Https 적용하기.pptx
 
Kafka JDBC Connect Guide(Postgres Sink).pptx
Kafka JDBC Connect Guide(Postgres Sink).pptxKafka JDBC Connect Guide(Postgres Sink).pptx
Kafka JDBC Connect Guide(Postgres Sink).pptx
 
Nginx Reverse Proxy with Kafka.pptx
Nginx Reverse Proxy with Kafka.pptxNginx Reverse Proxy with Kafka.pptx
Nginx Reverse Proxy with Kafka.pptx
 
Kafka Rest.pptx
Kafka Rest.pptxKafka Rest.pptx
Kafka Rest.pptx
 
Kafka monitoring using Prometheus and Grafana
Kafka monitoring using Prometheus and GrafanaKafka monitoring using Prometheus and Grafana
Kafka monitoring using Prometheus and Grafana
 
주가 정보 다루기.pdf
주가 정보 다루기.pdf주가 정보 다루기.pdf
주가 정보 다루기.pdf
 
KAFKA 3.1.0.pdf
KAFKA 3.1.0.pdfKAFKA 3.1.0.pdf
KAFKA 3.1.0.pdf
 
App development with quasar (pdf)
App development with quasar (pdf)App development with quasar (pdf)
App development with quasar (pdf)
 
kubernetes practice
kubernetes practicekubernetes practice
kubernetes practice
 
Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0) Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0)
 
Docker practice
Docker practiceDocker practice
Docker practice
 
Hyperledger fabric practice(pdf)
Hyperledger fabric practice(pdf)Hyperledger fabric practice(pdf)
Hyperledger fabric practice(pdf)
 

Recently uploaded

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 

Recently uploaded (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 

BlockChain implementation by python

  • 1. BlockChain on Python 한국폴리텍대학(Korea Polytechnics) 스마트금융과(dept. of Smart Finance)
  • 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…
  • 4. Python development environment  Python  Anaconda  Jupyter  Pycharm  Ftp, Linux Server, REST Test Tool(ARC, Post Man, Fiddler,…)  Git, File Compare Tools …
  • 6. Simple HTTP Server by Python (GET) 참조 : https://mafayyaz.wordpress.com/2013/02/08/writing-simple-http-server-in-python-with-rest-and-json/ 참조 : https://docs.python.org/3/library/http.server.html?highlight=basehttprequesthandler#http.server.BaseHTTPRequestHandler
  • 7. Simple HTTP Server by Python (GET) – Review  python 문자열 다루기 : split
  • 8. Simple HTTP Server by Python (GET) – Review  좀 더 Python 한 방법은?
  • 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 응답을 주면 성공
  • 12. Postman 설치  [H/W] 크롬 웹스토어에서 postman 으로 검색하고 설치 & 테스트
  • 13. Simple HTTP Server by Python (POST) application/json;encode=utf-8 ctype pdict
  • 14. Simple HTTP Server by Python (POST)
  • 15. Simple HTTP Server by Python (POST)
  • 16. Simple HTTP Server by Python (POST)
  • 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
  • 23. Source Code  API Interface
  • 24. Source Code 블록체인 DB가 존재한다면? if yes, DB를 읽어서 return 블록체인 DB가 존재 X 빈 데이터를 return
  • 25. At the moment, 블록데이터가 없는 상황  블록데이터 생성이 필요  신규API를 생성하여 Genesis Block을 생성해야 함 ~/block/generateBlock를 추가하자  블록을 구성할 데이터(Transaction Data)는 어떻게 구성할 것인가? 일단은, 임시 랜덤데이터를 구성하자 transaction = 'UserID ' + str(txFrom) + " sent " + str(amount) + ' bitTokens to UserID ' + str(txTo) + ". “ 차후, 개인 또는 그룹별 블록체인 비즈니스 아이디어를 반영한 트랜잭션으로 수정예정
  • 27. 블록데이터 생성 흐름 getTxDatareadBlockchainmineNewBlock 블록체인 DB가 존재한다면? if yes, DB를 읽어서 return else, “Genesis Block” 생성하여 return calculateHashgenerateNewBlock writeBlockchain 해쉬값이 우리가 정한 난이도와 일치한다면? if yes, 블록체인 기록 else, generateNewBlock 반복
  • 28. mineNewBlock def mineNewBlock(difficulty = 5, blockchainPath = 'blockchain.csv'): blockchain = readBlockchain(blockchainPath) txData = getTxData() timestamp = time.time() proof = 0 newBlockFound = False print('Mining a block...') while not newBlockFound: #print("Trying new block proof...") newBlockAttempt = generateNextBlock(blockchain, txData, timestamp, proof) if newBlockAttempt.currentHash[0:difficulty] == '0'*difficulty: stopTime = time.time() timer = stopTime - timestamp print('New block found with proof', proof, 'in', round(timer, 2), 'seconds.') newBlockFound = True else: proof += 1 blockchain.append(newBlockAttempt) writeBlockchain(blockchain) def mine(blocksToMine = 5): for _ in range(blocksToMine): mineNewBlock() 출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
  • 31. def getLatestBlock(blockchain): return blockchain[len(blockchain)-1] def generateNextBlock(blockchain, blockData, timestamp, proof): previousBlock = getLatestBlock(blockchain) nextIndex = int(previousBlock.index) + 1 nextTimestamp = timestamp nextHash = calculateHash(nextIndex, previousBlock.currentHash, nextTimestamp, proof, blockData) return Block(nextIndex, previousBlock.currentHash, nextTimestamp, blockData, proof, nextHash) 배열 출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/ generateNextBlock
  • 32. def calculateHash(index, previousHash, timestamp, data, proof): value = str(index) + str(previousHash) + str(timestamp) + str(data) + str(proof) sha = hashlib.sha256(value.encode('utf-8')) return str(sha.hexdigest()) Hash 대상 : 현재 블록의 인덱스 + 이전 블록의 Hash + 현 블록의 TimeStamp + 현 블록의 거래데이터 + PoW(#) 출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/ calculateHash
  • 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)
  • 36. 블록체인 데이터 조회하기  블록데이터 조회 ~/block/getBlockData로 조회하자
  • 37. So far we can  Create a genesis block  Hash blocks  Create additional blocks
  • 38. Practice #3  Design Your Own Transaction Data
  • 40. 이제 검증을 위한 API를 추가해 봅시다.  검증로직 설계  신규API를 생성하여 검증대상인 블록체인 데이터를 받아야 함(POST) ~/block/validateBlock/를 추가하자 - input과 output은 어떻게 설계해야 하는가?
  • 41. Validation Blocks 출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
  • 42. Validation Blocks 출처 : http://blockxchain.org/2017/06/04/simple-local-python-blockchain-pt1/
  • 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 =
  • 45. Practice #4  Design Post API of a new transaction data
  • 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 #) 채굴포함여부
  • 48. class txData  5 attributes 블록 포함여부(채굴) : commitYN 송신자 : sender 금액 : amount 수신자 : receiver 고유식별값 : uuid class txData: def __init__(self, commitYN, sender, amount, receiver, uuid): self.commitYN = commitYN self.sender = sender self.amount = amount self.receiver = receiver self.uuid = uuid
  • 50. Transaction Data (Dictionary  Instance of class txData) import uuid 필요 예> 369a1e95-3723-4b26-8ab8-9bcc2c5938f0
  • 51. Write Transaction Data <<temp csv>><<txData csv>> new tx data <<temp csv>> <<txData csv>>
  • 54. Update txData of csv #1 (when it has been mined)  채굴되었다면?
  • 55. Update txData of csv #2 정규표현식 row[4]row[0]
  • 57. Practice #5  Design Post API of a sending transaction data
  • 59. set up  library, global variables 타 노드로 채굴 정보를 POST하기 위한 라이브러리 노드간 인터페이스 API 노드 정보(서버IP, Port) 를 저장하는 파일
  • 60. broadcast block when it mined 타 노드로 전파
  • 61. broadcastNewBlock 방금 채굴된 블록을 포함한 블록체인 정보를 인접 노드의 API(receiveNewBlock)로 POST 호출하여 전달
  • 65. receive new block info g_receiveNewBlock = "/node/receiveNewBlock"
  • 66. compare blockchain info  latest block +1 != broadcasted last block latest block == broadcasted last block latest block +1 < broadcasted last block latest block +1 > broadcasted last block  latest block +1 == broadcasted last block
  • 71. initSvr (1/2)  인접 노드 정보 구하기
  • 72. initSvr (2/2)  블록체인 정보 구하기 g_bcFileName = "blockchain.csv"
  • 74. related sites…  __dict__ 설명 : https://wikidocs.net/1743  json.dump 설명 : http://pythonstudy.xyz/python/article/205-JSON-%EB%8D%B0%EC%9D%B4%ED%83%80 https://kimdoky.github.io/python/2017/11/11/library-book-chap8-4.html https://docs.python.org/3/library/json.html  람다식 설명 : https://wikidocs.net/64