SlideShare a Scribd company logo
1 of 116
Download to read offline
개발자가 바라보는 블록체인
Getting Started
Created by kyun (@smart-company)
목차
1. 블록체인(Blockchain)
2. 비트코인(Bitcoin)
3. 이더리움(Ethereum)
4. 기타사항
프롤로그
블록체인은 미래 사회와 경제를 바꾸는 핵심 기술이
될 것인가?
블록체인 기술을 사용하면 완전한 탈중앙화 시스템
구현이 가능한가?
블록체인 기반의 코인은 기축 통화로서의 역할을 할
수 있을까?
1. 블록체인(Blockchain)
인터넷의 두 번째 세대를 표방하며 돈과 경제, 정부
와 사회를 변화시킬 잠재력을 가진 신뢰 구축 기술
-- Don Tapscott - TedSummit, How the blockchain is
changing money and business
“
“
5
블록체인 혁명
The Internet of Information
복사본 전송이 문제 되지 않음
An Internet of Value
이중지불 문제
The Middleman
신뢰보증 -> 은행, 정부, 소셜 미디어
문제점
집중화, 지연, 수수료, 불평등
6
Internet of Value
금융기관 시스템에 대한 불신 (2008년 금융위기)
사토시 나카모토 비트코인(Bitcoin)
중계자 없이 가치 전송할 수 있는 전자화폐 프로토콜
분산/암호화 기술을 이용하여 신뢰 확보
7
블록체인 핵심기술
1. P2P(Peer to Peer) 가용성(Availability)
노드(Node) vs. 피어(Peer)
메인넷(Mainnet)
8
2. 분산원장(Distributed Ledger)
블록(Block)
Header: PreviousHash + MerkleHash + Nonce
Body: Transactions(Alice->Bob)
기밀성(Con dentiality), 무결성(Integrity)
9
해시 함수
입력값이 같으면 해시값도 반드시 같다.
불가역성 일방향 함수
출력값은 입력값의 길이와 상관없이 고정된 길이
SHA-256(Secure Hash Algorithm): 32바이트
$ echo "abcd" | sha256sum
fc4b5fd6816f75a7c81fc8eaa9499d6a299bd803397166e8c4cf9280b8
01d62c -
$ echo "abcde" | sha256sum
0283da60063abfb3a87f1aed845d17fe2d9ba8c780b478dc4ae048f5ee
97a6d5 -
10
디지털 서명
송신자
1. 송신할 데이터의 해시값 생성
2. 출력된 해시값을 송신자의 비밀키로 암호화
3. 데이터와 서명을 함께 수신자에게 송신
수신자
1. 수신된 데이터의 해시값(A) 생성
2. 서명을 송신자의 공개키로 복호화(B)
3. A와 B 두 해시값을 비교하여 검증
11
머클 루트 해시
12
3. 합의 알고리즘(Consensus Algorithm)
블록생성 권한 분배 계산 능력, 토큰 보유량
포크 발생 시 체인 선택 비트코인의 긴 체인 선택
비잔틴 장군 문제 채굴(Nonce), 보상
13
2. 비트코인(Bitcoin)
Bitcoin Architecture
15
비트코인 코어 설치
$ git clone https://github.com/bitcoin/bitcoin.git
$ sudo apt-get update
$ sudo apt-get install build-essential automake pkg-config libev
$ sudo apt-get install libtool autotools-dev autoconf
$ sudo apt-get install libssl-dev
$ sudo apt-get install libboost-all-dev
$ sudo add-apt-repository ppa:bitcoin/bitcoin
$ sudo apt-get update
$ sudo apt-get install libdb4.8-dev
$ sudo apt-get install libdb4.8++-dev
$ sudo apt-get install libminiupnpc-dev
$ sudo apt-get install libqrencode-dev
$ sudo apt-get install libqt5gui5 libqt5core5a libqt5dbus5 qttoo
$ ./autogen.sh
$ ./configure
$ make
$ sudo make install
16
테스트 네트워크
Testnet
인터네상에서 동작하는 테스트 네트워크
테스트용 BTC, 처음 시작할때 모든 데이터 취득
Regtest
로컬PC내에서의 테스트 네트워크
계정생성, 채굴, 블록체인 초기화 용이
$ bitcoind -regtest -daemon
Bitcoin server starting
17
블록 생성
# 채굴자는 보상 후 100 블록 이후에 송금이 가능
$ bitcoin-cli -regtest generate 101
블록 수 확인
$ bitcoin-cli -regtest getblockcount
101
계좌 생성
$ bitcoin-cli -regtest getnewaddress testuser100
2N7EHkYKrLbKqDybPY6cFoXXJ3ts4ArAKGb
18
잔고 확인
$ bitcoin-cli -regtest getbalance
$ bitcoin-cli -regtest getbalance testuser100
송금
$ bitcoin-cli -regtest sendtoaddress
2N7EHkYKrLbKqDybPY6cFoXXJ3ts4ArAKGb 20
99337e1bab6d56b694206781750d808e2b6a13695fa7a93c37ecead039
4204f9
트랜잭션 확인
$ bitcoin-cli -regtest listunspent
$ bitcoin-cli -regtest listunspent 0 0
19
채굴
$ bitcoin-cli -regtest generate 1
[
"096bec61ffe3b47930b04ba042127a6eac77e950d5dfa27521be2ee
e59aa6c9f"
]
블록 확인
# 블록해시 구하기
$ bitcoin-cli -regtest getblockhash 203
096bec61ffe3b47930b04ba042127a6eac77e950d5dfa27521be2eee59
aa6c9f
# 잔액 확인
$ bitcoin-cli -regtest getbalance testuser100
50.00000000
20
$ bitcoin-cli -regtest getblock 096bec61ffe3b47930b04ba042127a6e
{
"hash": "096bec61ffe3b47930b04ba042127a6eac77e950d5dfa27521be2
"confirmations": 1,
"strippedsize": 979,
"size": 1015,
"weight": 3952,
"height": 203,
"version": 805306369,
"versionHex": "30000001",
"merkleroot": "03b0c895b3893341e2cd9de85c1d7baa546f29432e4ebcb
"tx": [
"9dbf340315152e16d3c795ce76f26460dee5e296c9e28a3a91150ab5c0f
],
"time": 1527486010,
"nonce": 0,
"difficulty": 4.656542373906925e-10,
...
"previousblockhash": "50c1f5031be67b2436b45fb6ead467dbf1346783
}
21
BLOCKCHAIN.info
22
Block
23
3. 이더리움(Ethereum)
Ethereum is a decentralized platform that runs
smart contracts:
“
“
비트코인이 2G폰이라면 이더리움은 스마트폰“ “
이더리움과 비트코인의 차이점
유통되는 통화: ETH
스마트 계약: Turing complete
계정: EOA(Externally Owned Account), CA
블록의 데이터 구조: 잔액정보
상태 변화
계정과 연결된 정보: 논스, 스토리지 루트, 코드 해시
거래, 메시지, 콜(ReadOnly)
가스: 수수료, 보안
Programmable Economy
EVM(Ethereum Virtual Machine)
Solidity, a new language for smart contracts
Design and issue your own cryptocurrency
Build a new kind of decentralized application
코인(Coin) vs. 토큰(Token)
코인: 독립된 블록체인 네트워크를 소유한 경우
비트코인(BTC), 이더리움(ETH), 스팀(STEEM)
토큰: 독립된 블록체인 네트워크를 소유하지 않은 경우
이오스(EOS), 트론(TRX)
플 랫 폼(마켓) 어 플 포 인 트
이더리움 블록체인 DAPP 토큰
구글 안드로이드 앱 ?
이오스(EOS), 퀀텀(Qtum)
: ERC-20 -> 메인넷 -> 코인
28
ERC-20(Ethereum Request for Comment)
Ethereum Improvement Proposals(EIPs)
이더리움 블록체인에서 발행되는 토큰의 표준
스마트 컨트랙트 인터페이스 규약만 정의
이더리움 기반의 DAPP에서 사용할 수 있는 토큰
ERC20 개발의 정석 - OpenZeppelin
넓은 의미에서 화폐뿐만 아니라 자산의 기능“ “
29
https://github.com/ethereum/EIPs/issues/20
contract ERC20Basic {
function totalSupply() constant returns (uint totalSupply)
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to,
uint value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
constant returns (uint);
function transferFrom(address from, address to,
uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed
spender, uint value);
}
30
CoinMarketCap
31
이더리움 블록
Etherscan, https://etherscan.io/
32
이더의 단위
단위 Ether 비고
Wei 0.000000000000000001 10^18
Szabo 0.000.001 10^12
Finney 0.001 10^15
Ether 1
cf. 1 Satoshi = 10^-8 btc
33
Go Ethereum
Of cial Go implementation of the Ethereum protocol
$ sudo apt-get install software-properties-common
$ sudo add-apt-repository -y ppa:ethereum/ethereum
$ sudo add-apt-repository -y ppa:ethereum/ethereum-dev
$ sudo apt-get update
$ sudo apt-get install ethereum
$ geth version
Geth Version: 1.8.2-stable
Git Commit: b8b9f7f4476a30a0aaf6077daade6ae77f969960
Architecture: amd64
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.9.4
34
Private 네트워크 구축
Geth 초기화
$ mkdir testnet
$ cd testnet/
$ vi genesis.json
$ geth --datadir /home/vagrant/testnet/
init /home/vagrant/testnet/genesis.json
Genesis 블록(0번째 블록)
: 동일한 블록체인 네트워크에 참가하는 노드는 동일한
Genesis블록으로부터 연결되는 블록체인을 공유
35
# genesis.json
{
"config": {
"chainId": 33,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0
},
"nonce": "0x0000000000000033",
"timestamp": "0x0",
"parentHash": "0x000000000000000000000000000000000000000
0000000000000000000000000",
"gasLimit": "0x8000000",
"difficulty": "0x100",
"mixhash": "0x000000000000000000000000000000000000000
0000000000000000000000000",
"coinbase": "0x333333333333333333333333333333333333333
3",
"alloc": {}
}
36
이더리움 디렉토리 구조
$ tree /home/vagrant/testnet
.
├── genesis.json
├── geth
│   ├── chaindata
│   │   ├── 000001.log
│   │   ├── CURRENT
│   │   ├── LOCK
│   │   ├── LOG
│   │   └── MANIFEST-000000
│   └── lightchaindata
│   ├── 000001.log
│   ├── CURRENT
│   ├── LOCK
│   ├── LOG
│   └── MANIFEST-000000
└── keystore
37
Geth 실행
$ geth --identity "PrivateNetwork"
--datadir "/home/vagrant/testnet/"
--port "30303"
--rpc
--rpcaddr 0.0.0.0
--rpcport "8545"
--rpccorsdomain "*"
--nodiscover
--networkid 1900
--rpcapi "db,eth,net,web3,miner"
console 2>> /home/vagrant/testnet/geth.log
--networkid: 네트워크 식별자
--nodiscover: 다른 노드에서 검색할 수 없음
38
Geth Start & Kill Script
$ nohup geth --networkid 4649
--nodiscover
--datadir /home/vagrant/testnet
--rpc
--rpcaddr "0.0.0.0"
--rpcport 8545
--rpccorsdomain "*"
--rpcapi "admin,db,eth,debug,miner,net,shh,txpool,
personal,web3"
--verbosity 6 2>>/home/vagrant/testnet/geth.log &
$ kill $(ps aux | grep geth | grep rpc | awk '{print $2}')
Note: --rpcaddr, --rpcport, --rpccorsdomain, --rpcapi
39
Console 연결
$ geth attach http://localhost:8545
Welcome to the Geth JavaScript console!
instance: Geth/v1.8.2-stable-b8b9f7f4/linux-amd64/go1.9.4
modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0
personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
> exit
40
계정 생성과 조회
Welcome to the Geth JavaScript console!
> personal.newAccount("pass0")
"0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c"
> personal.newAccount("pass1")
"0xbd2cc6e8c322be5a43c862d39984980076930d0d"
> eth.accounts
["0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c",
"0xbd2cc6e8c322be5a43c862d39984980076930d0d"]
> eth.getBalance(eth.accounts[0])
> eth.getBalance(eth.coinbase)
EOA(Externally Owned Account): 일반 사용자 계정
CA(Contract Account): 계약용 계정
41
채굴(Mining)
> eth.mining
false
> miner.start()
null
> eth.getBalance(eth.coinbase)
115000000000000000000
> web3.fromWei(eth.getBalance(eth.coinbase))
185
> miner.stop()
true
> eth.blockNumber
37
최초 채굴 시 DAG(Directed Acyclic Graph) 생성
: 채굴의 ASIC 내성을 위해 만들어지는 파일
42
송금
> personal.unlockAccount(eth.accounts[0])
Unlock account 0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c
Passphrase: (계정의 암호 입력)
true
> eth.sendTransaction({
from:eth.accounts[0],
to:eth.accounts[1],
value:web3.toWei(10,"ether")
})
"0x8fbfdacc783756decfdd68ecdb4f7f35fdee5fb8b43e23983c7072b
f38822ae1"
43
> eth.getTransaction("0x8fbfdacc783756decfdd68ecdb4f7f35fdee5fb8
{
blockHash: "0x000000000000000000000000000000000000000000000000
blockNumber: null,
from: "0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c",
gas: 90000,
gasPrice: 18000000000,
hash: "0x8fbfdacc783756decfdd68ecdb4f7f35fdee5fb8b43e23983c707
input: "0x",
nonce: 0,
r: "0x91626fa3e14ca6407d2928d59059575cb2717ff0baadfb6c39796228
s: "0x68b26e0306a6e8ed34360cf6a650ff9ca151f9aba1139c3705cf05f1
to: "0xbd2cc6e8c322be5a43c862d39984980076930d0d",
transactionIndex: 0,
v: "0x66",
value: 10000000000000000000
}
> eth.pendingTransactions
> eth.blockNumber
44
> eth.getBlock(43)
{
difficulty: 131328,
extraData: "0xd783010802846765746887676f312e392e34856c696e7578
gasLimit: 128695843,
gasUsed: 0,
hash: "0xbfb8727fb4b56163f57fa5ebfd8cc677514a6e1e731e08c67a092
logsBloom: "0x000000000000000000000000000000000000000000000000
miner: "0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c",
mixHash: "0x646c28605eca9abf3283f7a6e1556431652b6fcba4455a33d7
nonce: "0x000510e55c54ad12",
number: 43,
parentHash: "0x53d1e0aa4a211f4e76772eb214fe1afc2be0f965fdedcef
receiptsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996ca
sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a741
size: 536,
stateRoot: "0x3a06000c8690c54e0fccb390958b519b7de12cf0d44c593a
timestamp: 1527579249,
...
}
45
Peer 연결
> admin.nodeInfo.enode
"enode://b128200b26a55a5aa2b605905b1dfa9be8426cf6d8f73c1a1
c0ea89e4d4771a98feead21cc9830b772c559d42b91ee2455fad440273
8571cad61f17c93b787ae@[::]:30303?discport=0"
> admin.addPeer(
"enode://b128200b26a55a5aa2b605905b1dfa9be8426cf6d8f73c1a1
c0ea89e4d4771a98feead21cc9830b772c559d42b91ee2455fad440273
8571cad61f17c93b787ae@192.168.0.202:30303?discport=0")
> net.peerCount
1
> admin.peers
46
이더리움 지갑(Ethereum Wallet)
이더리움에서 사용되는 공식 전자 지갑
계정 생성 / 이더 잔액 확인 및 송금 / 이벤트 확인
47
솔리디티(Solidity)
Solidity is a contract-oriented, high-level language
for implementing smart contracts.
Solidity documentation - Read the Docs
48
솔리디티 문법
자료형
string public msg; //문자형
address public owner; //주소형
int8 public counter; //정수형
bool ended; //논리형
struct Investor { //구조체
address addr;
uint amount;
}
mapping (uint => Investor) public investors; //매핑형
int[] setOfYar = [2018, 2019, 2020]; //배열 49
if
if (owner != msg.sender) {
throw;
}
for
for (uint8 i = 0; i < 3; i++) {
counter++;
}
while
while (조건식) {
//처리내용
}
50
modi er
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
payable
function someFunc() onlyOwner, payable {
// Do something
}
event
event MessageLog(string);
MessageLog(string);
51
접근제어자
public, private, external, internal
예약된 키워드
msg.sender: 함수를 호출한 계정의 주소
msg.value: 송금액
this: 현재 계약의 주소
balance: 주소의 잔액
fallback 함수: 이름, 인자, 리턴값이 없는 함수
function() payable {
revert();
}
52
Remix 개발환경
http://remix.ethereum.org
53
Remix 환경설정
Environment : Web3 Provider
Web3 Provider Endpoint
http://192.168.33.130:8545
Account 에서 계정 연결을 확인
Compile
Check "Auto compile"
Settings
Solidity version: 0.4.18+commit.9cf6e910
54
기본예제
pragma solidity ^0.4.18;
// 1. 컨트랙트 선언
contract SimpleStorage {
// 2. 상태 변수 선언
uint storedData;
// 3. 함수(메소드) 정의
function set(uint x) public {
storedData = x;
}
function get() public constant returns (uint) {
return storedData;
}
}
55
Deploy
Account 선택
Value: 1 ether
Deploy
personal.unlockAccount(eth.accounts[0])
56
동작 방식
컴파일
가상환경
Gas
Gas = Gas Fee * Gas Price (wei/Gas)
Gas Limit
57
Web3
web3.js - Ethereum JavaScript API
https://www.mobile sh.com/download/ethereum/
web3api.html
https://www.mobile sh.com/download/ethereum/
DemoDapp.html
58
Express 설치
$ sudo apt install nodejs
$ sudo apt install aptitude
$ sudo aptitude install npm
$ sudo npm install express-generator -g
$ sudo ln -s /usr/bin/nodejs /usr/bin/node
$ express -h
59
Express 페이지 생성
$ express --view=pug web3
$ cd web3 && sudo npm install
$ DEBUG=web3 npm start
http://192.168.33.150:3000/
web3 demo
/home/vagrant/web3/public
js, monitor.html 업로드
http://192.168.33.150:3000/monitor.html
60
Monitor Example
monitor.html
<script src="./js/bignumber.min.js"></script>
<script src="./js/web3-light.js"></script>
<script>
var web3 = new Web3();
var provider = new web3.providers.HttpProvider(
"http://192.168.33.150:8545");
web3.setProvider(provider);
web3.eth.defaultAccount = web3.eth.accounts[0];
var stop = false;
var startBlockNo = web3.eth.blockNumber - 20;
61
Vote Example
VoteContract.sol
contract VoteContract {
//하나의 계정 한번만 투표
mapping(address => bool) voters;
//후보자의 득표수 저장
mapping(string => uint) candidates;
//후보자 리스트
mapping(uint => string) candidateList;
//전체 후보자 수
uint8 numberOfCandidates;
address contractOwner;
} 62
ABI(Application Binary Interface)
var vc = web3.eth.contract(
ABI
).at("Contract Address");
var vc = web3.eth.contract([{
"constant": false,
"inputs": [{
"name": "cand",
"type": "string"
}],
"name": "addCandidate",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}]).at("0x128a64bd7749d38675a5ec693d08cb1a044e588a");
63
function showList() {
var table = doc ocument.getElementById("table1");
var length = vc.getNumOfCandidates();
alert(length);
for (var i = 0; i < length; i++) {
var candidate = vc.getCandidateString(i);
var row=table.insertRow();
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
cell1.innerHTML = candidate;
cell2.innerHTML = vc.getScore(candidate);
}
}
64
가상 화폐 계약
기본적인 가상 화폐 계약과 추가기능
1. 코인(Coin) 계약
블랙리스트(Blacklist)
캐시백(Cashback)
회원관리(Member)
2. 크라우드 세일(Crowd Sale)
3. 에스크로(Escrow)
65
클라우드 세일(Crowd Sale)
// (1) 소유자 관리용 계약
contract Owned {
...
}
// (2) 회원 관리용 계약
contract Members is Owned {
...
}
// (3) 회원 관리 기능이 구현된 가상 화폐
contract BluewindCoin is Owned {
...
}
// (4) 크라우드 세일
contract Crowdsale is Owned {
...
}
66
How to test
1. BluewindCoin
- Deploy: 10000, "BluewindCoin", "bc", 0
2. Clowdsale
- Deploy: 10, 5000, 100, "BluewindCoin CA"
3. Transfer
- "Clowdsale CA", 5000
4. BalanceOf
- BluewindCoin CA 계정 -> 5000
- Clowdsale CA 계정 -> 5000
5. Start
- 10
67
How to test (con't)
6. Fallback
- 1번 계정 선택, Value 5 ether, (fallback)
- 2번 계정 선택, Value 5 ether, (fallback)
7. checkGoalReached, fundingGoalReached
- 10분간 대기
- 0번 계정 선택
- checkGoalReached, fundingGoalReached
8. withdrawal
- 1번 계정선택, withdrawal
- 2번 계정선택, withdrawal
9. withdrawalOwner
- 0번 계정에서 withdrawalOwner
68
4. 트러플(Truf e)
Truf e framework for Ethereum
TRUFFLE
Smart Contracts Made Sweeter
Ganache
One Click Blockchain
Drizzle
Fresh Chain-Data For Front-Ends
Truf e is the most popular development
framework for Ethereum with a mission to make
your life a whole lot easier.
“
“
70
설치
$ npm install -g truffle
$ truffle version
Truffle v4.1.13 (core: 4.1.13)
Solidity v0.4.24 (solc-js)
프로젝트 생성
$ mkdir sample
$ cd sample
$ truffle init
71
프로젝트 폴더 구조
파일/폴더명 비고
contracts 스마튼 컨트랙트 소스 파일 폴더
migrations 배포를위한 스크립트 파일 폴더
test
개발된 컨트랙트를 테스트 하기 위한
폴더
truf e.js truf e 설정 파일 (default)
truf e-
con g.js
truf e 설정 파일 (truf e.js 파일이 없
는경우)
72
SimpleStorage Example
스마트 컨트랙트
contracts/SimpleStorage.sol
pragma solidity ^0.4.17;
contract SimpleStorage {
uint val;
function set(uint x) public {
val = x;
}
function get() constant public returns (uint) {
return val;
}
}
73
배포 스크립트
migrations/2_deploy_sample.js
var SimpleStorage = artifacts.require("SimpleStorage");
module.exports = function(deployer) {
deployer.deploy(SimpleStorage);
};
Note: 기본적으로 migrations 폴더 아래에 포함된 모든
파일을 실행 하기 때문에 배포 시 우선순위를 주기 위해
앞에 숫자를 붙여 준다.
74
테스트 컨트랙트
# test/TestSimpleStorage.sol
pragma solidity ^0.4.17;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/SimpleStorage.sol";
contract TestSimpleStorage {
function testSimpleStorage() public {
SimpleStorage ss = new SimpleStorage();
uint expected = 4;
ss.set(expected);
Assert.equal(ss.get(), expected,
"value equal test");
}
}
75
테스트용 이더리움 노드 설정
$ truffle develop
Truffle Develop started at http://127.0.0.1:9545/
Accounts:
(0) 0x627306090abab3a6e1400e9345bc60c78a8bef57
(1) 0xf17f52151ebef6c7334fad080c5704d77216b732
(2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef
(3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544
(4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2
(5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e
(6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5
(7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5
(8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc
(9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de
76
Private Keys:
(0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a
(1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974
(2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193
(3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71
(4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97
(5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917
(6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914
(7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f393956
(8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669
(9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012
Mnemonic: candy maple cake sugar pudding cream
honey rich smooth crumble sweet treat
⚠ Important ⚠ : This mnemonic was created for you by
Truffle. It is not secure. Ensure you do not use it on
production blockchains, or else you risk losing funds.
truffle(develop)>
77
ganache-cli를 직접 설치해서 실행하는 방법
$ npm install -g ganache-cli
$ ganache-cli
Ganache CLI v6.1.8 (ganache-core: 2.2.1)
Available Accounts
==================
(0) 0x4edd1f1994fa1912adb69c7f21e9697ea534a182 (~100 ETH)
(1) 0x837f7badf44aa34b28b10ba6df363464d75a921c (~100 ETH)
(2) 0x9f54595fe48cc0c107752fb7e7c127f19d2176d3 (~100 ETH)
(3) 0x080837726805dcf65e303e135beaf8d24f839164 (~100 ETH)
(4) 0x843e9e1af6a3fd260aa1cc3c3373e4a4a3562027 (~100 ETH)
(5) 0x98e49382ce52cd62d48f6126f9055f2840f0df05 (~100 ETH)
(6) 0xdfdf1219965a325dfddd6f6a4fbb4d1573e46bc2 (~100 ETH)
(7) 0x9b27fbf16f7ef0bfb678b906296eef020f430c65 (~100 ETH)
(8) 0x2bf00228ed492fa0f968c48cdfc5ac77062d7f39 (~100 ETH)
(9) 0xd990b9bfd6ebbdd73630b7758f279cacfb78a167 (~100 ETH)
78
배포 및 테스트
컴파일
truffle(develop)> compile
Compiling .contractsMigrations.sol...
Writing artifacts to .buildcontracts
배포
truffle(develop)> migrate
Using network 'develop'.
79
테스트
truffle(develop)> test
Using network 'develop'.
Compiling .contractsSimpleStorage.sol...
Compiling .testTestSimpleStorage.sol...
Compiling truffle/Assert.sol...
Compiling truffle/DeployedAddresses.sol...
TestSimpleStorage
√ testSimpleStorage (83ms)
1 passing (760ms)
80
Bank Example
트러플 프로젝트 생성
$ mkdir bank
$ cd bank
$ truffle init
Bank Contract
$ truffle create contract Bank
Truf e 과 Ganache를 이용하여 이더리움 은행을
개발
“
“
81
# contracts/Bank.sol
pragma solidity ^0.4.4;
contract Bank {
address public owner; //계좌의 소유주
function Bank(address _owner) public {
owner = _owner;
}
//입금
function deposit() public payable {
require(msg.value > 0);
}
//출금
function withdraw() public {
require(msg.sender == owner);
owner.transfer(address(this).balance);
}
} 82
What is a transaction?
The term “transaction” is used in Ethereum to refer
to the signed data package that stores a message to
be sent from an externally owned account to another
account on the blockchain.
83
Ganache
84
컴파일
$ truffle compile
Compiling .contractsBank.sol...
Writing artifacts to .buildcontracts
배포
// truffle.js
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
}
}
};
85
배포 스크립트 작성
$ truffle create migration bank
migrations/1532503784_bank.js
module.exports = function(deployer) {
// Use deployer to state migration tasks.
};
var Bank = artifacts.require("Bank");
module.exports = function(deployer) {
let ownerAddress = web3.eth.accounts[0];
deployer.deploy(Bank, ownerAddress);
};
86
배포
$ truffle migrate
Using network 'development'.
Running migration: 1_initial_migration.js
Deploying Migrations...
... 0x217a4c792c920be8e32ed59d16a14205cf81fa77da3100dcb0add8f7
Migrations: 0x13c9f9ac9691ac047e90c253b75d9ec08be13b01
Saving successful migration to network...
... 0xcd0404b13daeda92f6f27f40d2559a6905019723fa28f8dc3f8a37a3
Saving artifacts...
Running migration: 1532503784_bank.js
Deploying Bank...
... 0xe02911110604c0986dcf55ff072fb2ffac3a6d1d63ebfdb32a7f83cc
Bank: 0xdcbfcb0e112babddbca6af311a75ebb080e4f563
Saving successful migration to network...
... 0xb839d9e409c632cf9c5cbec70af02b0a0476ac3ac9178d8ce9c923fe
Saving artifacts...
87
재배포
truffle migrate --reset
4개의 트랜잭션 블럭이 추가된 것을 확인
88
테스트
$ truffle console
truffle(development)>
배포한 컨트랙트의 인스턴스를 bank 변수에 저장한다.
truffle(development)> Bank.deployed().then(instance
=> bank = instance)
truffle(development)> bank.owner()
'0x597193c7db57b66b53f7cea4877f20961a98b0d2'
참조: Account Types, Gas, and Transactions
89
deposit
truffle(development)> bank.deposit({value: web3.toWei(10,
'ether')})
{ tx: '0xbae00009b4a915c8342ceef64b06d307e99e20d3bc72e0e538770
receipt:
{ transactionHash: '0xbae00009b4a915c8342ceef64b06d307e99e20d
transactionIndex: 0,
blockHash: '0x4cdaf5ab1ea8df72ac116484771a360214b1b781fb0cc
blockNumber: 5,
gasUsed: 21453,
cumulativeGasUsed: 21453,
contractAddress: null,
logs: [],
status: '0x1',
logsBloom: '0x000000000000000000000000000000000000000000
},
logs: []
}
90
블럭과 트랜잭션 정보
deposit() 함수는 payable function 이기 때문에 송금 로
직을 작성하지 않고 이더리움을 전송 할 수 있다.
91
withdraw
truffle(development)> bank.withdraw()
{ tx: '0x85d78f1db258514b92c76420332ef04faf9a2bc49b08f43ff722ce
receipt:
{ transactionHash: '0x85d78f1db258514b92c76420332ef04faf9a2bc
transactionIndex: 0,
blockHash: '0xa2427d52882d9d20b28cb00cae5aed6844cc70c057010
blockNumber: 6,
gasUsed: 29826,
cumulativeGasUsed: 29826,
contractAddress: null,
logs: [],
status: '0x1',
logsBloom: '0x000000000000000000000000000000000000000000
},
logs: []
}
92
블럭과 트랜잭션 정보
93
과일가게 DApp
프로젝트 생성
Truf e Boxes를 이용하여 프로젝트를 생성
$ mkdir fruitshop
$ cd fruitshop
$ truffle unbox react
Shop Contract
$ truffle create contract Shop
contracts/Shop.sol
94
pragma solidity ^0.4.18;
contract Shop {
mapping (address=>uint16) myApple;
function buyApple() payable external {
myApple[msg.sender]++;
}
function getMyApples() view external returns(uint16) {
return myApple[msg.sender];
}
function sellMyApple(uint _applePrice) payable external
{
uint refund = myApple[msg.sender] * _applePrice;
myApple[msg.sender] = 0;
msg.sender.transfer(refund);
}
}
95
배포 환경 구성
truffle.js
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
}
}
};
96
배포 스크립트 작성
$ truffle create migration shop
migrations/2_bank.js
var Shop = artifacts.require("./Shop.sol");
module.exports = function(deployer) {
deployer.deploy(Shop);
};
97
컴파일
$ truffle compile
Compiling .contractsShop.sol...
Compiling .contractsMigrations.sol...
Writing artifacts to .buildcontracts
배포
$ truffle migrate
Using network 'development'.
...
Saving artifacts...
98
React.js 로 프론트엔드 구현하기
//src/App.js
import React, { Component } from "react";
import ShopContract from "../build/contracts/Shop.json";
import getWeb3 from "./utils/getWeb3";
import "./App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
shopInstance: null, // shopInstance 추가
myAccount: null, // myAccount 추가
myApples: 0, // myApples 추가
web3: null
};
} 99
componentWillMount() {
getWeb3
.then(results => {
this.setState({
web3: results.web3
});
this.instantiateContract();
})
.catch(() => {
console.log("Error finding web3.");
});
}
100
instantiateContract() {
const contract = require("truffle-contract");
const shop = contract(ShopContract);
shop.setProvider(this.state.web3.currentProvider);
/* 이것을 추가하세요. */
this.state.web3.eth.getAccounts((error, accounts) => {
if (!error) {
shop.deployed().then(instance => {
this.setState({ shopInstance: instance, myAccount
this.updateMyApples(); // 여기서 updateMyApples 호출하기
});
}
});
}
101
buyApple() {
this.state.shopInstance.buyApple({
from: this.state.myAccount,
value: this.state.web3.toWei(10, "ether"),
gas: 900000
});
}
sellApple() {
this.state.shopInstance.sellMyApple(this.state.web3.toWei(
from: this.state.myAccount,
gas: 900000
});
}
updateMyApples() {
this.state.shopInstance.getMyApples().then(result => {
this.setState({ myApples: result.toNumber() });
});
}
102
render() {
return (
<div className="App">
<h1>사과의 가격: 10 ETH</h1>
<button onClick={() => this.buyApple()}>구매하기</button
<p>내가 가진 사과: {this.state.myApples}</p>
<button onClick={() => this.sellApple()}>
판매하기 (판매 가격: {10 * this.state.myApples})
</button>
</div>
);
}
}
export default App;
103
전자지갑 설정
Metamask 설치
https://metamask.io
104
Metamask Log in
105
Custom RPC 연결
Ethereum Network -> http://127.0.0.1:8545 106
MetaMast에 계정 추가
Ganache 에서 첫번째 계정의 Private Key 복사
107
IMPORTED 계정이 생성됨
108
테스트
$ npm run start
http://localhost:3000 에 접속
구매하기
판매하기
109
5. 기타사항
ICO(Initial Coin Offering)
블록체인 비즈니스
토큰 이코노미
플랫폼/글로벌 비즈니스
투명성
백서(Whitepaper)
스마트 컨트랙트(Smart Contract)
토큰 매트릭스(Token Matrix)
참여자: Founders, Advisors, Development Team
111
블록체인 백서(Whitepaper)
무엇을 개선하려고 하는가?
왜 블록체인인가?
왜 코인이 필요한가?
진정한 탈중앙화(Decentralized)인가?
비즈니스 모델에 대한 보고서“ “
112
블록체인의 문제점 및 해결책?
트릴레마(Trilemma)
분산화(탈중앙화), 확장성(성능), 보안성(합의)
탈중앙화의 왜곡
채굴공장, 거래소
속도: 초당 7건
합의
개인정보
성숙도
113
참조
비트코인 백서
이더리움 백서
스팀 백서
Bitcoin Developer Guide
한국블록체인비즈니스 연구회 케블리
블록체인 구조와 이론, 위키북스
엔지니어를 위한 블록체인 프로그래밍, 한빛미디어
비트코인, 블록체인과 금융의 혁신, O'REILLY
114
스마트 컴퍼니
회사에 속하지 않고도 지속 가능한 삶
115
That's all!
Thank you.

More Related Content

What's hot

Ethereum Basics Part 2
Ethereum Basics Part 2Ethereum Basics Part 2
Ethereum Basics Part 2Soobok Jin
 
Blockchain Study(3) - 이더리움(Geth)
Blockchain Study(3) - 이더리움(Geth)Blockchain Study(3) - 이더리움(Geth)
Blockchain Study(3) - 이더리움(Geth)Fermat Jade
 
Blockchain 3rd smart contract programming
Blockchain 3rd smart contract programmingBlockchain 3rd smart contract programming
Blockchain 3rd smart contract programmingihpark92
 
Blockchain Study(5) - Smart Contract(스마트 계약)
Blockchain Study(5) - Smart Contract(스마트 계약)Blockchain Study(5) - Smart Contract(스마트 계약)
Blockchain Study(5) - Smart Contract(스마트 계약)Fermat Jade
 
세션1. block chain as a platform
세션1. block chain as a platform세션1. block chain as a platform
세션1. block chain as a platformJay JH Park
 
Blockchain Study(2) - POW&POS
Blockchain Study(2) - POW&POSBlockchain Study(2) - POW&POS
Blockchain Study(2) - POW&POSFermat Jade
 
Block chain introduction slideshare
Block chain introduction   slideshareBlock chain introduction   slideshare
Block chain introduction slidesharewonyong hwang
 
Blockchain 4th dapp programming
Blockchain 4th dapp programmingBlockchain 4th dapp programming
Blockchain 4th dapp programmingihpark92
 
세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발Jay JH Park
 
가상화폐 개념 및 거래 기초개발
가상화폐 개념 및 거래 기초개발가상화폐 개념 및 거래 기초개발
가상화폐 개념 및 거래 기초개발상욱 송
 
Dapp시연 150214
Dapp시연 150214Dapp시연 150214
Dapp시연 150214Jihong Shim
 
GCGC- CGCII 서버 엔진에 적용된 기술 (2) - Perfornance
GCGC- CGCII 서버 엔진에 적용된 기술 (2) - PerfornanceGCGC- CGCII 서버 엔진에 적용된 기술 (2) - Perfornance
GCGC- CGCII 서버 엔진에 적용된 기술 (2) - Perfornance상현 조
 
(130622) #fitalk the stealing windows password
(130622) #fitalk   the stealing windows password(130622) #fitalk   the stealing windows password
(130622) #fitalk the stealing windows passwordINSIGHT FORENSIC
 

What's hot (13)

Ethereum Basics Part 2
Ethereum Basics Part 2Ethereum Basics Part 2
Ethereum Basics Part 2
 
Blockchain Study(3) - 이더리움(Geth)
Blockchain Study(3) - 이더리움(Geth)Blockchain Study(3) - 이더리움(Geth)
Blockchain Study(3) - 이더리움(Geth)
 
Blockchain 3rd smart contract programming
Blockchain 3rd smart contract programmingBlockchain 3rd smart contract programming
Blockchain 3rd smart contract programming
 
Blockchain Study(5) - Smart Contract(스마트 계약)
Blockchain Study(5) - Smart Contract(스마트 계약)Blockchain Study(5) - Smart Contract(스마트 계약)
Blockchain Study(5) - Smart Contract(스마트 계약)
 
세션1. block chain as a platform
세션1. block chain as a platform세션1. block chain as a platform
세션1. block chain as a platform
 
Blockchain Study(2) - POW&POS
Blockchain Study(2) - POW&POSBlockchain Study(2) - POW&POS
Blockchain Study(2) - POW&POS
 
Block chain introduction slideshare
Block chain introduction   slideshareBlock chain introduction   slideshare
Block chain introduction slideshare
 
Blockchain 4th dapp programming
Blockchain 4th dapp programmingBlockchain 4th dapp programming
Blockchain 4th dapp programming
 
세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발
 
가상화폐 개념 및 거래 기초개발
가상화폐 개념 및 거래 기초개발가상화폐 개념 및 거래 기초개발
가상화폐 개념 및 거래 기초개발
 
Dapp시연 150214
Dapp시연 150214Dapp시연 150214
Dapp시연 150214
 
GCGC- CGCII 서버 엔진에 적용된 기술 (2) - Perfornance
GCGC- CGCII 서버 엔진에 적용된 기술 (2) - PerfornanceGCGC- CGCII 서버 엔진에 적용된 기술 (2) - Perfornance
GCGC- CGCII 서버 엔진에 적용된 기술 (2) - Perfornance
 
(130622) #fitalk the stealing windows password
(130622) #fitalk   the stealing windows password(130622) #fitalk   the stealing windows password
(130622) #fitalk the stealing windows password
 

Similar to Blockchain

[ETHCon Korea 2019] Kang Hyungseok 강형석
[ETHCon Korea 2019] Kang Hyungseok 강형석[ETHCon Korea 2019] Kang Hyungseok 강형석
[ETHCon Korea 2019] Kang Hyungseok 강형석ethconkr
 
블록체인 이슈와 전망 New db
블록체인 이슈와 전망 New db블록체인 이슈와 전망 New db
블록체인 이슈와 전망 New dbHongSuk Seo
 
W3C HTML5 컨퍼런스 2020 - 웹 환경에서 블록체인 노드와 통신 및 신원인증 (DID)
W3C HTML5 컨퍼런스 2020 - 웹 환경에서 블록체인 노드와 통신 및 신원인증 (DID)W3C HTML5 컨퍼런스 2020 - 웹 환경에서 블록체인 노드와 통신 및 신원인증 (DID)
W3C HTML5 컨퍼런스 2020 - 웹 환경에서 블록체인 노드와 통신 및 신원인증 (DID)Benjamin Oh
 
비트코인 블록체인에 영구불변 메시지 개발 삽질기 - Google Next Extended Seoul 2018
비트코인 블록체인에 영구불변 메시지 개발 삽질기 - Google Next Extended Seoul 2018비트코인 블록체인에 영구불변 메시지 개발 삽질기 - Google Next Extended Seoul 2018
비트코인 블록체인에 영구불변 메시지 개발 삽질기 - Google Next Extended Seoul 2018Harry Oh
 
Introblockchaininfra 180806105137
Introblockchaininfra 180806105137Introblockchaininfra 180806105137
Introblockchaininfra 180806105137Jong-Ki Lee
 
8 week: Technology of Platformless Media Blockchain
8 week: Technology of Platformless Media Blockchain8 week: Technology of Platformless Media Blockchain
8 week: Technology of Platformless Media BlockchainDaemin Park
 
Bitcoin 2.0(blockchain technology 2)
Bitcoin 2.0(blockchain technology 2)Bitcoin 2.0(blockchain technology 2)
Bitcoin 2.0(blockchain technology 2)Wooseung Kim
 
Blockchain Basic Concept Theory (Beginner Version) / 초보자를 위한 블록체인 기초 개념 이론
Blockchain Basic Concept Theory (Beginner Version) / 초보자를 위한 블록체인 기초 개념 이론Blockchain Basic Concept Theory (Beginner Version) / 초보자를 위한 블록체인 기초 개념 이론
Blockchain Basic Concept Theory (Beginner Version) / 초보자를 위한 블록체인 기초 개념 이론Minwoo Kim
 
Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0) Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0) wonyong hwang
 
V SYSTEMS Whitepaper_KR
V SYSTEMS Whitepaper_KRV SYSTEMS Whitepaper_KR
V SYSTEMS Whitepaper_KRV SYSTEMS
 
비트코인에 관한 교육자료 입니다.
비트코인에 관한 교육자료 입니다.비트코인에 관한 교육자료 입니다.
비트코인에 관한 교육자료 입니다.Sung Wan Yoon
 
AWS 기반 블록체인 (1부) - 블록체인 환경 구성하기 (박혜영 & 유다니엘, AWS 솔루션즈 아키텍트) :: AWS DevDay2018
AWS 기반 블록체인 (1부) - 블록체인 환경 구성하기 (박혜영 & 유다니엘, AWS 솔루션즈 아키텍트) :: AWS DevDay2018AWS 기반 블록체인 (1부) - 블록체인 환경 구성하기 (박혜영 & 유다니엘, AWS 솔루션즈 아키텍트) :: AWS DevDay2018
AWS 기반 블록체인 (1부) - 블록체인 환경 구성하기 (박혜영 & 유다니엘, AWS 솔루션즈 아키텍트) :: AWS DevDay2018Amazon Web Services Korea
 
About the Blockchain_imcloud
About the Blockchain_imcloudAbout the Blockchain_imcloud
About the Blockchain_imcloudimcloud
 
블록체인과 암호화폐 그리고 악성코드
블록체인과 암호화폐 그리고 악성코드블록체인과 암호화폐 그리고 악성코드
블록체인과 암호화폐 그리고 악성코드Jeong-woo Park
 
전자상거래 보안-블록체인(Blockchain) 기술
전자상거래 보안-블록체인(Blockchain) 기술전자상거래 보안-블록체인(Blockchain) 기술
전자상거래 보안-블록체인(Blockchain) 기술Yechan Ahn
 
[비트베리파트너스데이] 비트베리 비즈니스 솔루션 소개 자료
[비트베리파트너스데이] 비트베리 비즈니스 솔루션 소개 자료[비트베리파트너스데이] 비트베리 비즈니스 솔루션 소개 자료
[비트베리파트너스데이] 비트베리 비즈니스 솔루션 소개 자료Bitberry
 

Similar to Blockchain (20)

[ETHCon Korea 2019] Kang Hyungseok 강형석
[ETHCon Korea 2019] Kang Hyungseok 강형석[ETHCon Korea 2019] Kang Hyungseok 강형석
[ETHCon Korea 2019] Kang Hyungseok 강형석
 
블록체인 이슈와 전망 New db
블록체인 이슈와 전망 New db블록체인 이슈와 전망 New db
블록체인 이슈와 전망 New db
 
W3C HTML5 컨퍼런스 2020 - 웹 환경에서 블록체인 노드와 통신 및 신원인증 (DID)
W3C HTML5 컨퍼런스 2020 - 웹 환경에서 블록체인 노드와 통신 및 신원인증 (DID)W3C HTML5 컨퍼런스 2020 - 웹 환경에서 블록체인 노드와 통신 및 신원인증 (DID)
W3C HTML5 컨퍼런스 2020 - 웹 환경에서 블록체인 노드와 통신 및 신원인증 (DID)
 
비트코인 블록체인에 영구불변 메시지 개발 삽질기 - Google Next Extended Seoul 2018
비트코인 블록체인에 영구불변 메시지 개발 삽질기 - Google Next Extended Seoul 2018비트코인 블록체인에 영구불변 메시지 개발 삽질기 - Google Next Extended Seoul 2018
비트코인 블록체인에 영구불변 메시지 개발 삽질기 - Google Next Extended Seoul 2018
 
Introblockchaininfra 180806105137
Introblockchaininfra 180806105137Introblockchaininfra 180806105137
Introblockchaininfra 180806105137
 
8 week: Technology of Platformless Media Blockchain
8 week: Technology of Platformless Media Blockchain8 week: Technology of Platformless Media Blockchain
8 week: Technology of Platformless Media Blockchain
 
Bitcoin 2.0(blockchain technology 2)
Bitcoin 2.0(blockchain technology 2)Bitcoin 2.0(blockchain technology 2)
Bitcoin 2.0(blockchain technology 2)
 
Blockchain Basic Concept Theory (Beginner Version) / 초보자를 위한 블록체인 기초 개념 이론
Blockchain Basic Concept Theory (Beginner Version) / 초보자를 위한 블록체인 기초 개념 이론Blockchain Basic Concept Theory (Beginner Version) / 초보자를 위한 블록체인 기초 개념 이론
Blockchain Basic Concept Theory (Beginner Version) / 초보자를 위한 블록체인 기초 개념 이론
 
Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0) Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0)
 
V SYSTEMS Whitepaper_KR
V SYSTEMS Whitepaper_KRV SYSTEMS Whitepaper_KR
V SYSTEMS Whitepaper_KR
 
비트코인에 관한 교육자료 입니다.
비트코인에 관한 교육자료 입니다.비트코인에 관한 교육자료 입니다.
비트코인에 관한 교육자료 입니다.
 
AWS 기반 블록체인 (1부) - 블록체인 환경 구성하기 (박혜영 & 유다니엘, AWS 솔루션즈 아키텍트) :: AWS DevDay2018
AWS 기반 블록체인 (1부) - 블록체인 환경 구성하기 (박혜영 & 유다니엘, AWS 솔루션즈 아키텍트) :: AWS DevDay2018AWS 기반 블록체인 (1부) - 블록체인 환경 구성하기 (박혜영 & 유다니엘, AWS 솔루션즈 아키텍트) :: AWS DevDay2018
AWS 기반 블록체인 (1부) - 블록체인 환경 구성하기 (박혜영 & 유다니엘, AWS 솔루션즈 아키텍트) :: AWS DevDay2018
 
About the Blockchain_imcloud
About the Blockchain_imcloudAbout the Blockchain_imcloud
About the Blockchain_imcloud
 
Maker 오해와 진실
Maker 오해와 진실Maker 오해와 진실
Maker 오해와 진실
 
블록체인과 암호화폐 그리고 악성코드
블록체인과 암호화폐 그리고 악성코드블록체인과 암호화폐 그리고 악성코드
블록체인과 암호화폐 그리고 악성코드
 
전자상거래 보안-블록체인(Blockchain) 기술
전자상거래 보안-블록체인(Blockchain) 기술전자상거래 보안-블록체인(Blockchain) 기술
전자상거래 보안-블록체인(Blockchain) 기술
 
D app ethereum
D app ethereumD app ethereum
D app ethereum
 
쉽고 빠르게 접하는 오픈스택
쉽고 빠르게 접하는 오픈스택쉽고 빠르게 접하는 오픈스택
쉽고 빠르게 접하는 오픈스택
 
[비트베리파트너스데이] 비트베리 비즈니스 솔루션 소개 자료
[비트베리파트너스데이] 비트베리 비즈니스 솔루션 소개 자료[비트베리파트너스데이] 비트베리 비즈니스 솔루션 소개 자료
[비트베리파트너스데이] 비트베리 비즈니스 솔루션 소개 자료
 
블록체인 개요
블록체인 개요블록체인 개요
블록체인 개요
 

Blockchain

  • 1. 개발자가 바라보는 블록체인 Getting Started Created by kyun (@smart-company)
  • 2. 목차 1. 블록체인(Blockchain) 2. 비트코인(Bitcoin) 3. 이더리움(Ethereum) 4. 기타사항
  • 3. 프롤로그 블록체인은 미래 사회와 경제를 바꾸는 핵심 기술이 될 것인가? 블록체인 기술을 사용하면 완전한 탈중앙화 시스템 구현이 가능한가? 블록체인 기반의 코인은 기축 통화로서의 역할을 할 수 있을까?
  • 5. 인터넷의 두 번째 세대를 표방하며 돈과 경제, 정부 와 사회를 변화시킬 잠재력을 가진 신뢰 구축 기술 -- Don Tapscott - TedSummit, How the blockchain is changing money and business “ “ 5
  • 6. 블록체인 혁명 The Internet of Information 복사본 전송이 문제 되지 않음 An Internet of Value 이중지불 문제 The Middleman 신뢰보증 -> 은행, 정부, 소셜 미디어 문제점 집중화, 지연, 수수료, 불평등 6
  • 7. Internet of Value 금융기관 시스템에 대한 불신 (2008년 금융위기) 사토시 나카모토 비트코인(Bitcoin) 중계자 없이 가치 전송할 수 있는 전자화폐 프로토콜 분산/암호화 기술을 이용하여 신뢰 확보 7
  • 8. 블록체인 핵심기술 1. P2P(Peer to Peer) 가용성(Availability) 노드(Node) vs. 피어(Peer) 메인넷(Mainnet) 8
  • 9. 2. 분산원장(Distributed Ledger) 블록(Block) Header: PreviousHash + MerkleHash + Nonce Body: Transactions(Alice->Bob) 기밀성(Con dentiality), 무결성(Integrity) 9
  • 10. 해시 함수 입력값이 같으면 해시값도 반드시 같다. 불가역성 일방향 함수 출력값은 입력값의 길이와 상관없이 고정된 길이 SHA-256(Secure Hash Algorithm): 32바이트 $ echo "abcd" | sha256sum fc4b5fd6816f75a7c81fc8eaa9499d6a299bd803397166e8c4cf9280b8 01d62c - $ echo "abcde" | sha256sum 0283da60063abfb3a87f1aed845d17fe2d9ba8c780b478dc4ae048f5ee 97a6d5 - 10
  • 11. 디지털 서명 송신자 1. 송신할 데이터의 해시값 생성 2. 출력된 해시값을 송신자의 비밀키로 암호화 3. 데이터와 서명을 함께 수신자에게 송신 수신자 1. 수신된 데이터의 해시값(A) 생성 2. 서명을 송신자의 공개키로 복호화(B) 3. A와 B 두 해시값을 비교하여 검증 11
  • 13. 3. 합의 알고리즘(Consensus Algorithm) 블록생성 권한 분배 계산 능력, 토큰 보유량 포크 발생 시 체인 선택 비트코인의 긴 체인 선택 비잔틴 장군 문제 채굴(Nonce), 보상 13
  • 16. 비트코인 코어 설치 $ git clone https://github.com/bitcoin/bitcoin.git $ sudo apt-get update $ sudo apt-get install build-essential automake pkg-config libev $ sudo apt-get install libtool autotools-dev autoconf $ sudo apt-get install libssl-dev $ sudo apt-get install libboost-all-dev $ sudo add-apt-repository ppa:bitcoin/bitcoin $ sudo apt-get update $ sudo apt-get install libdb4.8-dev $ sudo apt-get install libdb4.8++-dev $ sudo apt-get install libminiupnpc-dev $ sudo apt-get install libqrencode-dev $ sudo apt-get install libqt5gui5 libqt5core5a libqt5dbus5 qttoo $ ./autogen.sh $ ./configure $ make $ sudo make install 16
  • 17. 테스트 네트워크 Testnet 인터네상에서 동작하는 테스트 네트워크 테스트용 BTC, 처음 시작할때 모든 데이터 취득 Regtest 로컬PC내에서의 테스트 네트워크 계정생성, 채굴, 블록체인 초기화 용이 $ bitcoind -regtest -daemon Bitcoin server starting 17
  • 18. 블록 생성 # 채굴자는 보상 후 100 블록 이후에 송금이 가능 $ bitcoin-cli -regtest generate 101 블록 수 확인 $ bitcoin-cli -regtest getblockcount 101 계좌 생성 $ bitcoin-cli -regtest getnewaddress testuser100 2N7EHkYKrLbKqDybPY6cFoXXJ3ts4ArAKGb 18
  • 19. 잔고 확인 $ bitcoin-cli -regtest getbalance $ bitcoin-cli -regtest getbalance testuser100 송금 $ bitcoin-cli -regtest sendtoaddress 2N7EHkYKrLbKqDybPY6cFoXXJ3ts4ArAKGb 20 99337e1bab6d56b694206781750d808e2b6a13695fa7a93c37ecead039 4204f9 트랜잭션 확인 $ bitcoin-cli -regtest listunspent $ bitcoin-cli -regtest listunspent 0 0 19
  • 20. 채굴 $ bitcoin-cli -regtest generate 1 [ "096bec61ffe3b47930b04ba042127a6eac77e950d5dfa27521be2ee e59aa6c9f" ] 블록 확인 # 블록해시 구하기 $ bitcoin-cli -regtest getblockhash 203 096bec61ffe3b47930b04ba042127a6eac77e950d5dfa27521be2eee59 aa6c9f # 잔액 확인 $ bitcoin-cli -regtest getbalance testuser100 50.00000000 20
  • 21. $ bitcoin-cli -regtest getblock 096bec61ffe3b47930b04ba042127a6e { "hash": "096bec61ffe3b47930b04ba042127a6eac77e950d5dfa27521be2 "confirmations": 1, "strippedsize": 979, "size": 1015, "weight": 3952, "height": 203, "version": 805306369, "versionHex": "30000001", "merkleroot": "03b0c895b3893341e2cd9de85c1d7baa546f29432e4ebcb "tx": [ "9dbf340315152e16d3c795ce76f26460dee5e296c9e28a3a91150ab5c0f ], "time": 1527486010, "nonce": 0, "difficulty": 4.656542373906925e-10, ... "previousblockhash": "50c1f5031be67b2436b45fb6ead467dbf1346783 } 21
  • 25. Ethereum is a decentralized platform that runs smart contracts: “ “ 비트코인이 2G폰이라면 이더리움은 스마트폰“ “
  • 26. 이더리움과 비트코인의 차이점 유통되는 통화: ETH 스마트 계약: Turing complete 계정: EOA(Externally Owned Account), CA 블록의 데이터 구조: 잔액정보 상태 변화 계정과 연결된 정보: 논스, 스토리지 루트, 코드 해시 거래, 메시지, 콜(ReadOnly) 가스: 수수료, 보안
  • 27. Programmable Economy EVM(Ethereum Virtual Machine) Solidity, a new language for smart contracts Design and issue your own cryptocurrency Build a new kind of decentralized application
  • 28. 코인(Coin) vs. 토큰(Token) 코인: 독립된 블록체인 네트워크를 소유한 경우 비트코인(BTC), 이더리움(ETH), 스팀(STEEM) 토큰: 독립된 블록체인 네트워크를 소유하지 않은 경우 이오스(EOS), 트론(TRX) 플 랫 폼(마켓) 어 플 포 인 트 이더리움 블록체인 DAPP 토큰 구글 안드로이드 앱 ? 이오스(EOS), 퀀텀(Qtum) : ERC-20 -> 메인넷 -> 코인 28
  • 29. ERC-20(Ethereum Request for Comment) Ethereum Improvement Proposals(EIPs) 이더리움 블록체인에서 발행되는 토큰의 표준 스마트 컨트랙트 인터페이스 규약만 정의 이더리움 기반의 DAPP에서 사용할 수 있는 토큰 ERC20 개발의 정석 - OpenZeppelin 넓은 의미에서 화폐뿐만 아니라 자산의 기능“ “ 29
  • 30. https://github.com/ethereum/EIPs/issues/20 contract ERC20Basic { function totalSupply() constant returns (uint totalSupply) function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } 30
  • 33. 이더의 단위 단위 Ether 비고 Wei 0.000000000000000001 10^18 Szabo 0.000.001 10^12 Finney 0.001 10^15 Ether 1 cf. 1 Satoshi = 10^-8 btc 33
  • 34. Go Ethereum Of cial Go implementation of the Ethereum protocol $ sudo apt-get install software-properties-common $ sudo add-apt-repository -y ppa:ethereum/ethereum $ sudo add-apt-repository -y ppa:ethereum/ethereum-dev $ sudo apt-get update $ sudo apt-get install ethereum $ geth version Geth Version: 1.8.2-stable Git Commit: b8b9f7f4476a30a0aaf6077daade6ae77f969960 Architecture: amd64 Protocol Versions: [63 62] Network Id: 1 Go Version: go1.9.4 34
  • 35. Private 네트워크 구축 Geth 초기화 $ mkdir testnet $ cd testnet/ $ vi genesis.json $ geth --datadir /home/vagrant/testnet/ init /home/vagrant/testnet/genesis.json Genesis 블록(0번째 블록) : 동일한 블록체인 네트워크에 참가하는 노드는 동일한 Genesis블록으로부터 연결되는 블록체인을 공유 35
  • 36. # genesis.json { "config": { "chainId": 33, "homesteadBlock": 0, "eip155Block": 0, "eip158Block": 0 }, "nonce": "0x0000000000000033", "timestamp": "0x0", "parentHash": "0x000000000000000000000000000000000000000 0000000000000000000000000", "gasLimit": "0x8000000", "difficulty": "0x100", "mixhash": "0x000000000000000000000000000000000000000 0000000000000000000000000", "coinbase": "0x333333333333333333333333333333333333333 3", "alloc": {} } 36
  • 37. 이더리움 디렉토리 구조 $ tree /home/vagrant/testnet . ├── genesis.json ├── geth │   ├── chaindata │   │   ├── 000001.log │   │   ├── CURRENT │   │   ├── LOCK │   │   ├── LOG │   │   └── MANIFEST-000000 │   └── lightchaindata │   ├── 000001.log │   ├── CURRENT │   ├── LOCK │   ├── LOG │   └── MANIFEST-000000 └── keystore 37
  • 38. Geth 실행 $ geth --identity "PrivateNetwork" --datadir "/home/vagrant/testnet/" --port "30303" --rpc --rpcaddr 0.0.0.0 --rpcport "8545" --rpccorsdomain "*" --nodiscover --networkid 1900 --rpcapi "db,eth,net,web3,miner" console 2>> /home/vagrant/testnet/geth.log --networkid: 네트워크 식별자 --nodiscover: 다른 노드에서 검색할 수 없음 38
  • 39. Geth Start & Kill Script $ nohup geth --networkid 4649 --nodiscover --datadir /home/vagrant/testnet --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --rpccorsdomain "*" --rpcapi "admin,db,eth,debug,miner,net,shh,txpool, personal,web3" --verbosity 6 2>>/home/vagrant/testnet/geth.log & $ kill $(ps aux | grep geth | grep rpc | awk '{print $2}') Note: --rpcaddr, --rpcport, --rpccorsdomain, --rpcapi 39
  • 40. Console 연결 $ geth attach http://localhost:8545 Welcome to the Geth JavaScript console! instance: Geth/v1.8.2-stable-b8b9f7f4/linux-amd64/go1.9.4 modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0 > exit 40
  • 41. 계정 생성과 조회 Welcome to the Geth JavaScript console! > personal.newAccount("pass0") "0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c" > personal.newAccount("pass1") "0xbd2cc6e8c322be5a43c862d39984980076930d0d" > eth.accounts ["0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c", "0xbd2cc6e8c322be5a43c862d39984980076930d0d"] > eth.getBalance(eth.accounts[0]) > eth.getBalance(eth.coinbase) EOA(Externally Owned Account): 일반 사용자 계정 CA(Contract Account): 계약용 계정 41
  • 42. 채굴(Mining) > eth.mining false > miner.start() null > eth.getBalance(eth.coinbase) 115000000000000000000 > web3.fromWei(eth.getBalance(eth.coinbase)) 185 > miner.stop() true > eth.blockNumber 37 최초 채굴 시 DAG(Directed Acyclic Graph) 생성 : 채굴의 ASIC 내성을 위해 만들어지는 파일 42
  • 43. 송금 > personal.unlockAccount(eth.accounts[0]) Unlock account 0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c Passphrase: (계정의 암호 입력) true > eth.sendTransaction({ from:eth.accounts[0], to:eth.accounts[1], value:web3.toWei(10,"ether") }) "0x8fbfdacc783756decfdd68ecdb4f7f35fdee5fb8b43e23983c7072b f38822ae1" 43
  • 44. > eth.getTransaction("0x8fbfdacc783756decfdd68ecdb4f7f35fdee5fb8 { blockHash: "0x000000000000000000000000000000000000000000000000 blockNumber: null, from: "0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c", gas: 90000, gasPrice: 18000000000, hash: "0x8fbfdacc783756decfdd68ecdb4f7f35fdee5fb8b43e23983c707 input: "0x", nonce: 0, r: "0x91626fa3e14ca6407d2928d59059575cb2717ff0baadfb6c39796228 s: "0x68b26e0306a6e8ed34360cf6a650ff9ca151f9aba1139c3705cf05f1 to: "0xbd2cc6e8c322be5a43c862d39984980076930d0d", transactionIndex: 0, v: "0x66", value: 10000000000000000000 } > eth.pendingTransactions > eth.blockNumber 44
  • 45. > eth.getBlock(43) { difficulty: 131328, extraData: "0xd783010802846765746887676f312e392e34856c696e7578 gasLimit: 128695843, gasUsed: 0, hash: "0xbfb8727fb4b56163f57fa5ebfd8cc677514a6e1e731e08c67a092 logsBloom: "0x000000000000000000000000000000000000000000000000 miner: "0x7a8f36c21f1b2f89a9f6c810c1289b88e559f85c", mixHash: "0x646c28605eca9abf3283f7a6e1556431652b6fcba4455a33d7 nonce: "0x000510e55c54ad12", number: 43, parentHash: "0x53d1e0aa4a211f4e76772eb214fe1afc2be0f965fdedcef receiptsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996ca sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a741 size: 536, stateRoot: "0x3a06000c8690c54e0fccb390958b519b7de12cf0d44c593a timestamp: 1527579249, ... } 45
  • 46. Peer 연결 > admin.nodeInfo.enode "enode://b128200b26a55a5aa2b605905b1dfa9be8426cf6d8f73c1a1 c0ea89e4d4771a98feead21cc9830b772c559d42b91ee2455fad440273 8571cad61f17c93b787ae@[::]:30303?discport=0" > admin.addPeer( "enode://b128200b26a55a5aa2b605905b1dfa9be8426cf6d8f73c1a1 c0ea89e4d4771a98feead21cc9830b772c559d42b91ee2455fad440273 8571cad61f17c93b787ae@192.168.0.202:30303?discport=0") > net.peerCount 1 > admin.peers 46
  • 47. 이더리움 지갑(Ethereum Wallet) 이더리움에서 사용되는 공식 전자 지갑 계정 생성 / 이더 잔액 확인 및 송금 / 이벤트 확인 47
  • 48. 솔리디티(Solidity) Solidity is a contract-oriented, high-level language for implementing smart contracts. Solidity documentation - Read the Docs 48
  • 49. 솔리디티 문법 자료형 string public msg; //문자형 address public owner; //주소형 int8 public counter; //정수형 bool ended; //논리형 struct Investor { //구조체 address addr; uint amount; } mapping (uint => Investor) public investors; //매핑형 int[] setOfYar = [2018, 2019, 2020]; //배열 49
  • 50. if if (owner != msg.sender) { throw; } for for (uint8 i = 0; i < 3; i++) { counter++; } while while (조건식) { //처리내용 } 50
  • 51. modi er modifier onlyOwner() { require(msg.sender == owner); _; } payable function someFunc() onlyOwner, payable { // Do something } event event MessageLog(string); MessageLog(string); 51
  • 52. 접근제어자 public, private, external, internal 예약된 키워드 msg.sender: 함수를 호출한 계정의 주소 msg.value: 송금액 this: 현재 계약의 주소 balance: 주소의 잔액 fallback 함수: 이름, 인자, 리턴값이 없는 함수 function() payable { revert(); } 52
  • 54. Remix 환경설정 Environment : Web3 Provider Web3 Provider Endpoint http://192.168.33.130:8545 Account 에서 계정 연결을 확인 Compile Check "Auto compile" Settings Solidity version: 0.4.18+commit.9cf6e910 54
  • 55. 기본예제 pragma solidity ^0.4.18; // 1. 컨트랙트 선언 contract SimpleStorage { // 2. 상태 변수 선언 uint storedData; // 3. 함수(메소드) 정의 function set(uint x) public { storedData = x; } function get() public constant returns (uint) { return storedData; } } 55
  • 56. Deploy Account 선택 Value: 1 ether Deploy personal.unlockAccount(eth.accounts[0]) 56
  • 57. 동작 방식 컴파일 가상환경 Gas Gas = Gas Fee * Gas Price (wei/Gas) Gas Limit 57
  • 58. Web3 web3.js - Ethereum JavaScript API https://www.mobile sh.com/download/ethereum/ web3api.html https://www.mobile sh.com/download/ethereum/ DemoDapp.html 58
  • 59. Express 설치 $ sudo apt install nodejs $ sudo apt install aptitude $ sudo aptitude install npm $ sudo npm install express-generator -g $ sudo ln -s /usr/bin/nodejs /usr/bin/node $ express -h 59
  • 60. Express 페이지 생성 $ express --view=pug web3 $ cd web3 && sudo npm install $ DEBUG=web3 npm start http://192.168.33.150:3000/ web3 demo /home/vagrant/web3/public js, monitor.html 업로드 http://192.168.33.150:3000/monitor.html 60
  • 61. Monitor Example monitor.html <script src="./js/bignumber.min.js"></script> <script src="./js/web3-light.js"></script> <script> var web3 = new Web3(); var provider = new web3.providers.HttpProvider( "http://192.168.33.150:8545"); web3.setProvider(provider); web3.eth.defaultAccount = web3.eth.accounts[0]; var stop = false; var startBlockNo = web3.eth.blockNumber - 20; 61
  • 62. Vote Example VoteContract.sol contract VoteContract { //하나의 계정 한번만 투표 mapping(address => bool) voters; //후보자의 득표수 저장 mapping(string => uint) candidates; //후보자 리스트 mapping(uint => string) candidateList; //전체 후보자 수 uint8 numberOfCandidates; address contractOwner; } 62
  • 63. ABI(Application Binary Interface) var vc = web3.eth.contract( ABI ).at("Contract Address"); var vc = web3.eth.contract([{ "constant": false, "inputs": [{ "name": "cand", "type": "string" }], "name": "addCandidate", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }]).at("0x128a64bd7749d38675a5ec693d08cb1a044e588a"); 63
  • 64. function showList() { var table = doc ocument.getElementById("table1"); var length = vc.getNumOfCandidates(); alert(length); for (var i = 0; i < length; i++) { var candidate = vc.getCandidateString(i); var row=table.insertRow(); var cell1=row.insertCell(0); var cell2=row.insertCell(1); cell1.innerHTML = candidate; cell2.innerHTML = vc.getScore(candidate); } } 64
  • 65. 가상 화폐 계약 기본적인 가상 화폐 계약과 추가기능 1. 코인(Coin) 계약 블랙리스트(Blacklist) 캐시백(Cashback) 회원관리(Member) 2. 크라우드 세일(Crowd Sale) 3. 에스크로(Escrow) 65
  • 66. 클라우드 세일(Crowd Sale) // (1) 소유자 관리용 계약 contract Owned { ... } // (2) 회원 관리용 계약 contract Members is Owned { ... } // (3) 회원 관리 기능이 구현된 가상 화폐 contract BluewindCoin is Owned { ... } // (4) 크라우드 세일 contract Crowdsale is Owned { ... } 66
  • 67. How to test 1. BluewindCoin - Deploy: 10000, "BluewindCoin", "bc", 0 2. Clowdsale - Deploy: 10, 5000, 100, "BluewindCoin CA" 3. Transfer - "Clowdsale CA", 5000 4. BalanceOf - BluewindCoin CA 계정 -> 5000 - Clowdsale CA 계정 -> 5000 5. Start - 10 67
  • 68. How to test (con't) 6. Fallback - 1번 계정 선택, Value 5 ether, (fallback) - 2번 계정 선택, Value 5 ether, (fallback) 7. checkGoalReached, fundingGoalReached - 10분간 대기 - 0번 계정 선택 - checkGoalReached, fundingGoalReached 8. withdrawal - 1번 계정선택, withdrawal - 2번 계정선택, withdrawal 9. withdrawalOwner - 0번 계정에서 withdrawalOwner 68
  • 70. Truf e framework for Ethereum TRUFFLE Smart Contracts Made Sweeter Ganache One Click Blockchain Drizzle Fresh Chain-Data For Front-Ends Truf e is the most popular development framework for Ethereum with a mission to make your life a whole lot easier. “ “ 70
  • 71. 설치 $ npm install -g truffle $ truffle version Truffle v4.1.13 (core: 4.1.13) Solidity v0.4.24 (solc-js) 프로젝트 생성 $ mkdir sample $ cd sample $ truffle init 71
  • 72. 프로젝트 폴더 구조 파일/폴더명 비고 contracts 스마튼 컨트랙트 소스 파일 폴더 migrations 배포를위한 스크립트 파일 폴더 test 개발된 컨트랙트를 테스트 하기 위한 폴더 truf e.js truf e 설정 파일 (default) truf e- con g.js truf e 설정 파일 (truf e.js 파일이 없 는경우) 72
  • 73. SimpleStorage Example 스마트 컨트랙트 contracts/SimpleStorage.sol pragma solidity ^0.4.17; contract SimpleStorage { uint val; function set(uint x) public { val = x; } function get() constant public returns (uint) { return val; } } 73
  • 74. 배포 스크립트 migrations/2_deploy_sample.js var SimpleStorage = artifacts.require("SimpleStorage"); module.exports = function(deployer) { deployer.deploy(SimpleStorage); }; Note: 기본적으로 migrations 폴더 아래에 포함된 모든 파일을 실행 하기 때문에 배포 시 우선순위를 주기 위해 앞에 숫자를 붙여 준다. 74
  • 75. 테스트 컨트랙트 # test/TestSimpleStorage.sol pragma solidity ^0.4.17; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/SimpleStorage.sol"; contract TestSimpleStorage { function testSimpleStorage() public { SimpleStorage ss = new SimpleStorage(); uint expected = 4; ss.set(expected); Assert.equal(ss.get(), expected, "value equal test"); } } 75
  • 76. 테스트용 이더리움 노드 설정 $ truffle develop Truffle Develop started at http://127.0.0.1:9545/ Accounts: (0) 0x627306090abab3a6e1400e9345bc60c78a8bef57 (1) 0xf17f52151ebef6c7334fad080c5704d77216b732 (2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef (3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544 (4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2 (5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e (6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5 (7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5 (8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc (9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de 76
  • 77. Private Keys: (0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a (1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974 (2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193 (3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71 (4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97 (5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917 (6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914 (7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f393956 (8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669 (9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012 Mnemonic: candy maple cake sugar pudding cream honey rich smooth crumble sweet treat ⚠ Important ⚠ : This mnemonic was created for you by Truffle. It is not secure. Ensure you do not use it on production blockchains, or else you risk losing funds. truffle(develop)> 77
  • 78. ganache-cli를 직접 설치해서 실행하는 방법 $ npm install -g ganache-cli $ ganache-cli Ganache CLI v6.1.8 (ganache-core: 2.2.1) Available Accounts ================== (0) 0x4edd1f1994fa1912adb69c7f21e9697ea534a182 (~100 ETH) (1) 0x837f7badf44aa34b28b10ba6df363464d75a921c (~100 ETH) (2) 0x9f54595fe48cc0c107752fb7e7c127f19d2176d3 (~100 ETH) (3) 0x080837726805dcf65e303e135beaf8d24f839164 (~100 ETH) (4) 0x843e9e1af6a3fd260aa1cc3c3373e4a4a3562027 (~100 ETH) (5) 0x98e49382ce52cd62d48f6126f9055f2840f0df05 (~100 ETH) (6) 0xdfdf1219965a325dfddd6f6a4fbb4d1573e46bc2 (~100 ETH) (7) 0x9b27fbf16f7ef0bfb678b906296eef020f430c65 (~100 ETH) (8) 0x2bf00228ed492fa0f968c48cdfc5ac77062d7f39 (~100 ETH) (9) 0xd990b9bfd6ebbdd73630b7758f279cacfb78a167 (~100 ETH) 78
  • 79. 배포 및 테스트 컴파일 truffle(develop)> compile Compiling .contractsMigrations.sol... Writing artifacts to .buildcontracts 배포 truffle(develop)> migrate Using network 'develop'. 79
  • 80. 테스트 truffle(develop)> test Using network 'develop'. Compiling .contractsSimpleStorage.sol... Compiling .testTestSimpleStorage.sol... Compiling truffle/Assert.sol... Compiling truffle/DeployedAddresses.sol... TestSimpleStorage √ testSimpleStorage (83ms) 1 passing (760ms) 80
  • 81. Bank Example 트러플 프로젝트 생성 $ mkdir bank $ cd bank $ truffle init Bank Contract $ truffle create contract Bank Truf e 과 Ganache를 이용하여 이더리움 은행을 개발 “ “ 81
  • 82. # contracts/Bank.sol pragma solidity ^0.4.4; contract Bank { address public owner; //계좌의 소유주 function Bank(address _owner) public { owner = _owner; } //입금 function deposit() public payable { require(msg.value > 0); } //출금 function withdraw() public { require(msg.sender == owner); owner.transfer(address(this).balance); } } 82
  • 83. What is a transaction? The term “transaction” is used in Ethereum to refer to the signed data package that stores a message to be sent from an externally owned account to another account on the blockchain. 83
  • 85. 컴파일 $ truffle compile Compiling .contractsBank.sol... Writing artifacts to .buildcontracts 배포 // truffle.js module.exports = { networks: { development: { host: "127.0.0.1", port: 7545, network_id: "*" // Match any network id } } }; 85
  • 86. 배포 스크립트 작성 $ truffle create migration bank migrations/1532503784_bank.js module.exports = function(deployer) { // Use deployer to state migration tasks. }; var Bank = artifacts.require("Bank"); module.exports = function(deployer) { let ownerAddress = web3.eth.accounts[0]; deployer.deploy(Bank, ownerAddress); }; 86
  • 87. 배포 $ truffle migrate Using network 'development'. Running migration: 1_initial_migration.js Deploying Migrations... ... 0x217a4c792c920be8e32ed59d16a14205cf81fa77da3100dcb0add8f7 Migrations: 0x13c9f9ac9691ac047e90c253b75d9ec08be13b01 Saving successful migration to network... ... 0xcd0404b13daeda92f6f27f40d2559a6905019723fa28f8dc3f8a37a3 Saving artifacts... Running migration: 1532503784_bank.js Deploying Bank... ... 0xe02911110604c0986dcf55ff072fb2ffac3a6d1d63ebfdb32a7f83cc Bank: 0xdcbfcb0e112babddbca6af311a75ebb080e4f563 Saving successful migration to network... ... 0xb839d9e409c632cf9c5cbec70af02b0a0476ac3ac9178d8ce9c923fe Saving artifacts... 87
  • 88. 재배포 truffle migrate --reset 4개의 트랜잭션 블럭이 추가된 것을 확인 88
  • 89. 테스트 $ truffle console truffle(development)> 배포한 컨트랙트의 인스턴스를 bank 변수에 저장한다. truffle(development)> Bank.deployed().then(instance => bank = instance) truffle(development)> bank.owner() '0x597193c7db57b66b53f7cea4877f20961a98b0d2' 참조: Account Types, Gas, and Transactions 89
  • 90. deposit truffle(development)> bank.deposit({value: web3.toWei(10, 'ether')}) { tx: '0xbae00009b4a915c8342ceef64b06d307e99e20d3bc72e0e538770 receipt: { transactionHash: '0xbae00009b4a915c8342ceef64b06d307e99e20d transactionIndex: 0, blockHash: '0x4cdaf5ab1ea8df72ac116484771a360214b1b781fb0cc blockNumber: 5, gasUsed: 21453, cumulativeGasUsed: 21453, contractAddress: null, logs: [], status: '0x1', logsBloom: '0x000000000000000000000000000000000000000000 }, logs: [] } 90
  • 91. 블럭과 트랜잭션 정보 deposit() 함수는 payable function 이기 때문에 송금 로 직을 작성하지 않고 이더리움을 전송 할 수 있다. 91
  • 92. withdraw truffle(development)> bank.withdraw() { tx: '0x85d78f1db258514b92c76420332ef04faf9a2bc49b08f43ff722ce receipt: { transactionHash: '0x85d78f1db258514b92c76420332ef04faf9a2bc transactionIndex: 0, blockHash: '0xa2427d52882d9d20b28cb00cae5aed6844cc70c057010 blockNumber: 6, gasUsed: 29826, cumulativeGasUsed: 29826, contractAddress: null, logs: [], status: '0x1', logsBloom: '0x000000000000000000000000000000000000000000 }, logs: [] } 92
  • 94. 과일가게 DApp 프로젝트 생성 Truf e Boxes를 이용하여 프로젝트를 생성 $ mkdir fruitshop $ cd fruitshop $ truffle unbox react Shop Contract $ truffle create contract Shop contracts/Shop.sol 94
  • 95. pragma solidity ^0.4.18; contract Shop { mapping (address=>uint16) myApple; function buyApple() payable external { myApple[msg.sender]++; } function getMyApples() view external returns(uint16) { return myApple[msg.sender]; } function sellMyApple(uint _applePrice) payable external { uint refund = myApple[msg.sender] * _applePrice; myApple[msg.sender] = 0; msg.sender.transfer(refund); } } 95
  • 96. 배포 환경 구성 truffle.js module.exports = { networks: { development: { host: "127.0.0.1", port: 7545, network_id: "*" // Match any network id } } }; 96
  • 97. 배포 스크립트 작성 $ truffle create migration shop migrations/2_bank.js var Shop = artifacts.require("./Shop.sol"); module.exports = function(deployer) { deployer.deploy(Shop); }; 97
  • 98. 컴파일 $ truffle compile Compiling .contractsShop.sol... Compiling .contractsMigrations.sol... Writing artifacts to .buildcontracts 배포 $ truffle migrate Using network 'development'. ... Saving artifacts... 98
  • 99. React.js 로 프론트엔드 구현하기 //src/App.js import React, { Component } from "react"; import ShopContract from "../build/contracts/Shop.json"; import getWeb3 from "./utils/getWeb3"; import "./App.css"; class App extends Component { constructor(props) { super(props); this.state = { shopInstance: null, // shopInstance 추가 myAccount: null, // myAccount 추가 myApples: 0, // myApples 추가 web3: null }; } 99
  • 100. componentWillMount() { getWeb3 .then(results => { this.setState({ web3: results.web3 }); this.instantiateContract(); }) .catch(() => { console.log("Error finding web3."); }); } 100
  • 101. instantiateContract() { const contract = require("truffle-contract"); const shop = contract(ShopContract); shop.setProvider(this.state.web3.currentProvider); /* 이것을 추가하세요. */ this.state.web3.eth.getAccounts((error, accounts) => { if (!error) { shop.deployed().then(instance => { this.setState({ shopInstance: instance, myAccount this.updateMyApples(); // 여기서 updateMyApples 호출하기 }); } }); } 101
  • 102. buyApple() { this.state.shopInstance.buyApple({ from: this.state.myAccount, value: this.state.web3.toWei(10, "ether"), gas: 900000 }); } sellApple() { this.state.shopInstance.sellMyApple(this.state.web3.toWei( from: this.state.myAccount, gas: 900000 }); } updateMyApples() { this.state.shopInstance.getMyApples().then(result => { this.setState({ myApples: result.toNumber() }); }); } 102
  • 103. render() { return ( <div className="App"> <h1>사과의 가격: 10 ETH</h1> <button onClick={() => this.buyApple()}>구매하기</button <p>내가 가진 사과: {this.state.myApples}</p> <button onClick={() => this.sellApple()}> 판매하기 (판매 가격: {10 * this.state.myApples}) </button> </div> ); } } export default App; 103
  • 106. Custom RPC 연결 Ethereum Network -> http://127.0.0.1:8545 106
  • 107. MetaMast에 계정 추가 Ganache 에서 첫번째 계정의 Private Key 복사 107
  • 109. 테스트 $ npm run start http://localhost:3000 에 접속 구매하기 판매하기 109
  • 111. ICO(Initial Coin Offering) 블록체인 비즈니스 토큰 이코노미 플랫폼/글로벌 비즈니스 투명성 백서(Whitepaper) 스마트 컨트랙트(Smart Contract) 토큰 매트릭스(Token Matrix) 참여자: Founders, Advisors, Development Team 111
  • 112. 블록체인 백서(Whitepaper) 무엇을 개선하려고 하는가? 왜 블록체인인가? 왜 코인이 필요한가? 진정한 탈중앙화(Decentralized)인가? 비즈니스 모델에 대한 보고서“ “ 112
  • 113. 블록체인의 문제점 및 해결책? 트릴레마(Trilemma) 분산화(탈중앙화), 확장성(성능), 보안성(합의) 탈중앙화의 왜곡 채굴공장, 거래소 속도: 초당 7건 합의 개인정보 성숙도 113
  • 114. 참조 비트코인 백서 이더리움 백서 스팀 백서 Bitcoin Developer Guide 한국블록체인비즈니스 연구회 케블리 블록체인 구조와 이론, 위키북스 엔지니어를 위한 블록체인 프로그래밍, 한빛미디어 비트코인, 블록체인과 금융의 혁신, O'REILLY 114
  • 115. 스마트 컴퍼니 회사에 속하지 않고도 지속 가능한 삶 115