SlideShare a Scribd company logo
1 of 55
以太坊(ETHEREUM)
SOLIDITY & WEB3.JS
個人簡歷
 林和勲
 https://www.linkedin.com/in/ho-hsun-lin-0298975/
 https://www.slideshare.net/salingerslin
 salingersms@msn.com
 經歷
 現任職台灣銀行
 研究專長為機器學習、人工智慧、區塊鏈
 學歷
 國立政治大學資訊科學系
區塊鏈
 分散式資料庫:交易紀錄 (總帳)
 公私鑰對(Pair),產生帳戶位址與密碼
 定時同步、資料公開透明
 共識機制:挖礦
 Proof of Work, PoW
 挖礦者(Miner)驗證批量交易資料,賺取以太幣
 區塊鏈(Block Chain):難以竄改
 區塊(Block):批量交易資料、時間戳(Time Stamp)
 鏈(Chain):前一區塊的Hash紀錄
技術演進
 拜占庭將軍問題 (Byzantine Generals Problem) -- 1982, L. Lamport, R. Shostak, M. Pease
 eCash -- 1990, David Chaum
 時間戳數位文件安全 --1991, Stuart Haber, W. Scott Stornetta
 橢圓曲線數位簽章演算法 -- 1992, Don Johnson, Alfred Menezes, Scott Vanstone
 Hashcash (工作量證明機制 Proof of Work, PoW) -- 1997, Adam Back
 B-money -- 1998, Wei Dai
 Bit Gold (去中心化) -- 1998, Nick Szabo
 可重複使用的工作量證明機制 (Reusable Proofs of Work,RPoW) -- 2005, Hal Finney
 比特幣 -- 2008, 中本聰
以太坊 (ETHEREUM)
 2013 年底 Bitcoin 開發者Vitalik Buterin 發想「有
邏輯」的虛擬貨幣交易平台
 全球級的分散式「電腦」,可存放交易紀錄、自訂
資料,及進行邏輯運算
 平均每十五秒同步一次
 智能合約 (Smart Contract)
 Ethereum Virtual Machine
 可加入公開鏈,或部署為企業應用私有鏈
 1 以太幣(ether)
 1000 finney
 1000000000000000000 wei
 推薦平台 Enode
 以 Go 語言實做 Ethereum 協議
 支援多平台
 支援多執行序
 https://github.com/ethereum/go-
ethereum/wiki/Building-Ethereum
環境建置:GETH - ETHEREUM NODE, ENODE
公開鏈
 geth --mine --minerthread 2 --autodag –fast
建立私有鏈
 設定創世塊 (Genesis Block)
 geth init genesis.json
 連接私有鏈
 geth --networkid 16888 --port 30303 --nodiscover
--maxpeers 25 --nat "any" --rpc --rpccorsdomain
"*" --rpcapi "eth,net,web3,debug" --mine --
minerthreads 1 --autodag
 建立帳戶、部屬合約、進行交易、進行挖礦
 使用電子錢包
 https://github.com/ethereum/mist/releases
私有鏈設定檔
genesis.json
{
"difficulty": "0x0",
"extraData": "0x16888",
"gasLimit": "0x999999999",
"mixhash": “ADDRESS",
"nonce": "0x0",
"timestamp": "0x0"
}
static-nodes.json
[
"enode://ADDRESS@IP:PORT"
]
私有鏈設定:WINDOWS
重置
 delete
 C:Users使用者AppDataRoamingEthereum
 C:Users使用者AppDataEthash
設定
1. C:Users使用者
 https://build.ethdev.com/builds/Windows%20
Go%20master%20branch/Geth-Win64-
latest.zip
2. geth init genesis.json
3. geth account new
4. C:Users使用者
AppDataRoamingEthereumstatic-
nodes.json
5. 連接私有鏈
私有鏈設定:MAC
重置
 delete
 ~/Library/Ethereum
 ~/.ethash
設定
1. brew
 tap ethereum/Ethereum
 install Ethereum
2. geth init genesis.json
3. geth account new
4. ~/Library/Ethereum/static-nodes.json
5. 連接私有鏈
私有鏈設定:LINUX
重置
 delete
 ~/.ethereum
 ~/.ethash
設定
1. https://github.com/ethereum/go-
ethereum/wiki/Building-Ethereum
2. geth init genesis.json
3. geth account new
4. ~/.Ethereum/static-nodes.json
5. 連接私有鏈
GETH 指令
Enode
 進入本地端 geth 命令列控制介面
 geth attach
 加入 peer (於命令列控制介面)
 admin.addPeer("enode://ADDRESS@IP:PORT")
 設定 peer:static-nodes.json
 ["enode://ADDRESS@ IP:PORT"]
Account
 新增帳戶
 geth account new
 列出帳戶
 geth account list
智能合約
BLOCKS & TRANSACTIONS
Blocks
 資料庫 (Blockchain) 的狀態
 帳戶餘額
 智能合約中的狀態變數
 交易的對象
 個人帳號(External Account)
 合約帳號Contract Account
 公鑰私鑰
 私鑰:創立帳號時輸入的密碼
 公鑰:Account address
Transactions
 Message
 from
 To
 Value:以太幣
 binary data:合約的 bytecode,其他資料
 預設最大值 89kb
PHASES
Contract
• 合約部署
Execution
• 合約執行
State Transition
• 狀態改變
Commit
• 提交共識
智能合約設計
公開鏈
 資料公開透明,私密資料請自行加密
 鏈外 (off-chain) 流程設計
私有鏈
 same networkid
 same genesis block
 mixhash
 nonce
 extradata
交易(TXS) & 訊息(MSG)
交易(TXs)
 交易包含訊息 (Message)
 External Account傳送交易
訊息(MSG)
 內部交易 (Internal Transaction)
 Contract Account 傳送訊息 (Message)
 訊息不會被記錄
TRANSACTIONS & CALLS
Transactions
 異動資料:帳戶餘額、合約變數
 一般函式
Call
 查詢資料
 常數函式:Constant Function
SOLIDITY
SOLIDITY
程式特性
 類似 JavaScript
 強型別
 var 型別推論
開發環境建置
 Solc 編譯器(Compiler)
 npm install solc -g
 solcjs --help
 solcjs contract.sol
 文字編輯器套件
 https://github.com/juanfranblanco/vscode-solidity
 線上 IDE
 http://ethereum.github.io/browser-solidity/
SOLIDITY
Hello world
contract HelloWorld
{
string public greeting = "";
function setHelloWorld()
{
greeting = "hello, world";
}
}
基本架構
 狀態變數 (State Variable)
 狀態機 (State Machine)
 函式
 函式描述子 (Function Modifier)
 建構式
 異動資料、呼叫其他合約
 事件
 與鏈外互動互動: Web3.js
資料型別
實值型別
 bool
 int / int256, uint
 uint constant HEX_NUM = 0x123A1;
 address
 20 byte value (size of an Ethereum address)
 bytesN (1 <= N <= 32)
 fixed-size byte arrays
 常數修飾詞
 constant
參考型別
 string
 implicitly convertible to bytesN
 UTF-8 supported
 Arrays (if T is a value type)
 T[] t; // Dynamic-length array
 T[N] t; // N-length array
 T[N][M] t; // M x N array (there is M T[N])
 Mappings
 mapping (Ktype => Vtype) myMap;
 K can be almost any type except mapping
 V can be any type
 if K does not exist, V is zero
 in fatct, it uses sha3(K) to look up its value
實值型別
地址(address)
 合約帳戶(Contract Account)
 address public owner;
 外部帳戶(External Account)
 owner.balance
 mapping (string => uint) public balances;
 balances["Bob"] = 10 ether;
 靜態陣列
 bytes32[5] nicknames;
 動態陣列
 bytes32[] names;
 陣列長度
 names.length;
bytesN
參考型別 & 自訂型別
參考型別:Structs
struct Bank
{
address owner;
uint balance;
}
Bank bank
= Bank
({
owner:
"0x692a70d2e424a56d2c6c27aa97d1a86395877b3a",
balance: 5
});
自訂型別
 enums
 enum Direction { Left, Right, Up, Down }
 Direction myDirection = Direction.Up;
其他型別
全域變數
 block
 block.blockhash(uint blockNumber) returns (bytes32)
 block.coinbase // miner's address
 block.gaslimit // current block gaslimit
 block.number // current block number
 block.timestamp // current block time (before commit)
 msg
 msg.sender // sender of the message (current call)
 msg.value // how much wei sent with the message
 tx
 tx.origin // sender of the transaction (full chain call)
 now
 alias for block.timestamp
型別轉換
 隱含轉換
 uint8 -> uint16 (O)
 int8 -> int16 (O)
 int8 -> uint8 (X)
 明確轉換
 int8 y = -3; uint x = uint(y); // x is now 0xfffff..fd
 uint32 a = 0x12345678; uint16 b = uint16(a); // b is now 0x5678
流程控制
 邏輯
 If、else、?:
 迴圈
 while 、for 、break 、continue
 函式
 return; 、
 return VALUE,..;
 function NAME(ARG,..) VISIBILITY returns
(TYPE,...) {}
 能見度控制 (封裝)
 external、public 、 internal 、 private
 賦值
function f() returns (uint, bool, uint)
{
return (7, true, 2);
}
var (x, b, y) = f();
 例外
 throw;
 復原資料狀態的改變
開發智能合約
GAS
GAS
 fee = gas (fuel) * gasPrice
 合約傳送以太幣補助 (stipend) 2300 gas
 帳戶傳送以太幣花費 21000 gas
 每個 EVM 指令有相對應的 gas
 程式愈複雜愈貴
 防止惡意攻擊及維護公開鏈的系統效能
 Gas 不夠時會發生 Error
 throw 會強制花光所有 gas 以防繼續執行下去
Transation
 成功
 fee:獎勵 fuel x gasPrice 給 miner
 fuel :剩餘的 fuel x gasPrice 退回給 originator
 失敗
 fee :miner 全拿
 fuel :因為 gas (fuel) 不夠或被 throw
函式描述子(MODIFIER)
 描述子
 function onlyOwnerCanDoThis() isOwner { ... }
 參數
 function aFunctionNeedingEther costsAtLeast(10 ether) { ... }
 payable
 為保留字,附加傳送以太幣
變數重設
uint data;
function f()
{
uint x = data;
delete x;
}
密碼函式
 addmod(uint x, uint y, uint k) returns (uint)
 (x + y) % k
 mulmod(uint x, uint y, uint k) returns (uint)
 (x * y) % k
 sha3(...) returns (bytes32)
 ... means tightly packed so sha3("abc") == sha3("ab", "c")
 faster in EVM (special bytecode)
 sha256(...) returns (bytes32)
 ripemd160(...) returns (bytes20)
 ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)
 利用橢圓加密復原從簽章反推出當初簽章者的 address
 hash 為 secp256k1.sign(msg hash, privatekey) 之產物 (Tx hash 被外部帳戶 sign)
 v 為 signature.復原參數 + 27 (ethereum 橢圓參數)
 r 為 signature[0-31],s 為 signature[32-63]
ADDRESS 函式
 address.send(uint wei) returns (bool)
 ALWAYS check if sending process is successful with returned boolean
 address.balance // return wei in uint
 this // this contract's address
// 傳 10 以太幣 給呼叫合約函式者 (msg.sender)
msg.sender.send(10 ether);
// 傳 此合約擁有的所有錢 給呼叫合約函式者
msg.sender.send(this.balance);
合約(CONTRACT)函式
 this
 此 contract 的位址
 selfdestruct(address recipient)
 合約自殺時,把合約帳戶裡的餘額退還到指定帳戶
 假如合約中沒有撰寫此方法或其他傳送以太幣的方法,合約的錢永遠拿不回來
 function () {}
 被稱為 Fallback Function,沒有名字的函式
 當從外部合約呼叫此合約的方法時發生錯誤(例如函式名稱不對或參數個數放錯),
就會進到此函式,有點像是其他語言的 switch 中的 default (solidity 沒有 switch)
 當有帳戶想要單純送錢 至合約時,也會進入這個函式(因為單純送錢的函式沒有名字)
 function () payable {}
 沒有加上 payable 描述子的話將無法被 .send(),要讓其他帳戶能送錢進來的話
必須加上此描述子,並實作此 Fallback Function ( {} 內留空白亦可)
呼叫合約
import
 介面
 function F() [modifiers...] [contant] returns(T…,) {}
 狀態變數
 T [public, external] t;
呼叫合約
 Contract contract= Contract(address);
 確定 address type
 明確轉換 (Explicit Conversion)
呼叫合約
 呼叫方法
 contract.function(arg…,);
 單純送錢
 contract.send(uint wei);
 gas stipend 2300
 呼叫方法順便送錢
 contract.function.value(uint wei)(arg…,);
 設定 gas
 contract.function.gas(uint gas)(arg…,);
 Refection
 副作用極大,未來版本將逐漸移除
進階語法
 http://solidity.readthedocs.io/en/v0.4.21/index.html
 虛擬 & 繼承
 Library & Import
WEB3.JS
WEB3.JS (CONT’D) : ARCH-GRAPH
Network Web3.js
 部署合約
 交易物件 (Transaction Object)
 Reflection (反映) 方法
 ABI
 呼叫合約方法 (Contract Functions)
 Call
 Transaction
 聽取事件
 過濾事件
 全域事件
enode
enode enode
enode
Web3.js
Web3.js
通訊協定
 RPC :較彈性,目前只有 HTTP,較不安全
 Web3.js
 IPC :較快且安全
 geth attach
 WS:WebSocket ,可以高迸發處理客戶端
 適合實作網頁即時服務用
TRANSACTIONS & BLOCK
 pending transactions
 本地 enode 中還沒被放進 pending block 來mining 的交易
 pending block
 本地 enode 正在 mining 的 block
 latest block
 chain 上最新的 block
 transactionReceipt
 指 transaction 執行過後 在 chain 中 的記錄
ABI, APPLICATION BLOCKCHAIN INTERFACE
 eth
 用來透過 Enode 向 Ethereum 鏈操作、感知 Ethereum 鏈上發生的事情
 admin
 管理 Enode 的元件服務
 miner
 管理挖礦元件
 personal
 管理帳戶:解鎖、鎖定帳戶,及以指定帳戶的名義簽署交易
事件監聽
設定物件
var block = eth.filter('latest’,
{
from: Number | String,
to: Number | String,
address: String
});
開始/停止
block .watch(function(err, latestBlockHash) {});
block .stopWatching();
取得物件
 block
 eth.getBlock('latest’)
 eth.getBlock('pending’)
 eth.getBlock(NUM)
 transaction
 eth.getTransaction(HASH)
 eth.getTransactionReceipt(HASH)
 eth.pendingTransactions
 address
 eth.getBalance(addressString);
 enode
 eth.accounts
 eth.coinbase == eth.accounts[0] //挖擴者
 web3
 web3.fromWei
 web3.toWei
 minter
 miner.start(N)
 miner.stop()
 eth.mining
 eth.syncing
惰性節點
function work()
{
if (eth.getBlock("pending").transactions.length > 0)
{
if (eth.mining)
{
return;
}
miner.start(threads);
}
else
{
miner.stop();
}
}
var threads = 1
eth.filter("latest", function(err, block) {work(); });
eth.filter("pending", function(err, block) {work(); });
work();
SAFE USAGE
 Signing transactions
 https://github.com/ethereumjs/ethereumjs-tx
 HTTPS
 Node.js
 Proxy
GETTING STARTED
 https://github.com/ethereum/wiki/wiki/JavaScript-API
 npm install web3
 var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
部署合約
 推薦使用 browser-solidity 自動產生的 web3 deploy code
 編譯後,可以得到 bytecode 及 ABI
 經由 sendTransaction 搭上 data (bytecode)
 eth.sendTransaction
({
from: eth.coinbase,
data: BYTECODE,
gas: 1234567
});
 eth.getTransactionReceipt(TxHash).contractAddress
TRANSACTION OBJECT
personal.unlockAccount('帳戶位址', '密碼', 幾秒);
eth.sendTransaction
({
from: , //從什麼帳戶位址
to: , //從什麼帳戶位址,假如要部署合約可以忽略
gas: , //多少 wei,預設 90000沒用完的會退回來
gasPrice: , //多少 gas,gas 單價,Enode設定
value: , //多少 wei 要傳
data: , //附加資料:部署合約或呼叫合約,或也可以儲存資料,最大值為 89kb
nonce: , // 用於標示 Transaction 的順序,所以可以以相同的 nonce 覆蓋同 nonce 的交易
});
呼叫智能合約
Transaction
storageContract.setData("區塊鏈!",
{
from: eth.coinbase,
gas: 1234567
});
 TxHash:回傳值,後續用來追蹤區塊 Block
 eth.getTransactionReceipt(TxHash)
 gasUsed:真實使用的gas值,可用來判斷是否執行成功
Call
var data = storageContract.getData();
storageContract.getData(function(err, data)
{
console.log(err, data);
})
 Transaction vs Call
 被 mine vs 不會被 mine
 花到錢 vs 不會花到錢
 會影響資料庫 (Blockchain) vs 不會影響資料庫
 慢 vs 快
設定合約
var ABI =
[{"constant":true,"inputs":[],"name":"getData","outputs":[{"name":"","type":"string"}],"payable":false,"ty
pe":"function"},{"constant":false,"inputs":[{"name":"input","type":"string"}],"name":"setData","outputs":
[],"payable":false,"type":"function"}];
var contract = eth.conract(ABI).at("0xa5a28cbaa3d7a37394260c9f7029f5b67bea913c");
事件:SOLIDITY
contract event
{
event fire(address indexed sender, uint indexed value);
function fire()
{
fire(msg.sender, msg.value);
}
}
事件:WEB3.JS
Transaction
//
var watcher = contract.fire({},{from:?, to:?});
watcher.get(function(err, eventLog) {
console.log(JSON.stringify(eventLog, null, 2));
});
// indexed
var watcher = contract.fire({num: 1});
watcher.watch(function(e, r){console.log('1')});
watcher.stopWatching();
Call
contract.fire({}, function(err, eventLog) {
console.log(JSON.stringify(eventLog, null, 2));
});
EXAMPLE
pragma solidity ^0.4.2;
contract event
{
string public data;
event transaction(string input, address from, uint time);
function call() constant returns(string) {return data;}
function transaction(string input)
{
data = input;
transaction(input, msg.sender, now);
}
}
進階討論
常見漏洞:RE-ENTRANCY
var share = shares[msg.sender];
shares[msg.sender] = 0;
if (!msg.sender.send(share))
{
throw;
}
 Re-Entrancy
 Reflection 有可能會造成回呼,形成邏輯漏洞
 身分驗證
 tx.origin:交易發送者,不要使用於驗證
 msg.sender:訊息發送者,可能等於 tx.origin
常見漏洞: SELFDESTRUCT
 合約帳戶
 回收合約中的錢,摧毀合約並將以太幣轉至特定帳號
 堆疊深度(Call stack Depth)
 目前最深深度為 1024
 溢位
 因重要的數字記得檢查溢位檢查

More Related Content

What's hot

了解Php内核
了解Php内核了解Php内核
了解Php内核Er Zhang
 
自然语言处理 中文分词程序实验报告%28含源代码%29
自然语言处理 中文分词程序实验报告%28含源代码%29自然语言处理 中文分词程序实验报告%28含源代码%29
自然语言处理 中文分词程序实验报告%28含源代码%29aemoe
 
SQL Loader & Bulk Insert 大量資料匯入工具
SQL Loader & Bulk Insert 大量資料匯入工具SQL Loader & Bulk Insert 大量資料匯入工具
SQL Loader & Bulk Insert 大量資料匯入工具HO-HSUN LIN
 
Message Queue Service
Message Queue ServiceMessage Queue Service
Message Queue ServiceSnoopyChen
 
Mongo db技术分享
Mongo db技术分享Mongo db技术分享
Mongo db技术分享晓锋 陈
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointerschchwy Chang
 
JavaScript 快速複習 2017Q1
JavaScript 快速複習 2017Q1JavaScript 快速複習 2017Q1
JavaScript 快速複習 2017Q1Sheng-Han Su
 
LazyRecord: The Fast ORM for PHP
LazyRecord: The Fast ORM for PHPLazyRecord: The Fast ORM for PHP
LazyRecord: The Fast ORM for PHPLin Yo-An
 
Device Driver - Chapter 3字元驅動程式
Device Driver - Chapter 3字元驅動程式Device Driver - Chapter 3字元驅動程式
Device Driver - Chapter 3字元驅動程式ZongYing Lyu
 
第9章 Shell 編程
第9章 Shell 編程第9章 Shell 編程
第9章 Shell 編程kidmany2001
 

What's hot (11)

了解Php内核
了解Php内核了解Php内核
了解Php内核
 
自然语言处理 中文分词程序实验报告%28含源代码%29
自然语言处理 中文分词程序实验报告%28含源代码%29自然语言处理 中文分词程序实验报告%28含源代码%29
自然语言处理 中文分词程序实验报告%28含源代码%29
 
SQL Loader & Bulk Insert 大量資料匯入工具
SQL Loader & Bulk Insert 大量資料匯入工具SQL Loader & Bulk Insert 大量資料匯入工具
SQL Loader & Bulk Insert 大量資料匯入工具
 
Message Queue Service
Message Queue ServiceMessage Queue Service
Message Queue Service
 
Mongo db技术分享
Mongo db技术分享Mongo db技术分享
Mongo db技术分享
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers
 
JavaScript 快速複習 2017Q1
JavaScript 快速複習 2017Q1JavaScript 快速複習 2017Q1
JavaScript 快速複習 2017Q1
 
LazyRecord: The Fast ORM for PHP
LazyRecord: The Fast ORM for PHPLazyRecord: The Fast ORM for PHP
LazyRecord: The Fast ORM for PHP
 
Device Driver - Chapter 3字元驅動程式
Device Driver - Chapter 3字元驅動程式Device Driver - Chapter 3字元驅動程式
Device Driver - Chapter 3字元驅動程式
 
第9章 Shell 編程
第9章 Shell 編程第9章 Shell 編程
第9章 Shell 編程
 
Json知识分享
Json知识分享Json知识分享
Json知识分享
 

Similar to 以太坊(Ethereum) solidity & web3.js

20201006 meta_coin 六角學院
20201006 meta_coin 六角學院20201006 meta_coin 六角學院
20201006 meta_coin 六角學院Hu Kenneth
 
[Crypto Course] Blockchain Security
[Crypto Course] Blockchain Security[Crypto Course] Blockchain Security
[Crypto Course] Blockchain SecurityWEI CHIEH CHAO
 
深入浅出Netty l.t
深入浅出Netty   l.t深入浅出Netty   l.t
深入浅出Netty l.toleone
 
利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geekJohnson Gau
 
ES5 introduction
ES5 introductionES5 introduction
ES5 introductionotakustay
 
107个常用javascript语句 oss 计算技术 - ossez info of tech
107个常用javascript语句   oss 计算技术 - ossez info of tech107个常用javascript语句   oss 计算技术 - ossez info of tech
107个常用javascript语句 oss 计算技术 - ossez info of techYUCHENG HU
 
高性能远程调用解决方案
高性能远程调用解决方案高性能远程调用解决方案
高性能远程调用解决方案Ady Liu
 
主备备的两个备机转为双Master出现诡异的slave lag问题
主备备的两个备机转为双Master出现诡异的slave lag问题主备备的两个备机转为双Master出现诡异的slave lag问题
主备备的两个备机转为双Master出现诡异的slave lag问题haojiewang
 
Chapter 3 basic syntax and operator
Chapter 3  basic syntax and operatorChapter 3  basic syntax and operator
Chapter 3 basic syntax and operatorhhliu
 
Arduino應用系統設計 - Arduino程式快速入門
Arduino應用系統設計 - Arduino程式快速入門Arduino應用系統設計 - Arduino程式快速入門
Arduino應用系統設計 - Arduino程式快速入門吳錫修 (ShyiShiou Wu)
 
Java华为面试题
Java华为面试题Java华为面试题
Java华为面试题yiditushe
 
180518 ntut js and node
180518 ntut js and node180518 ntut js and node
180518 ntut js and nodePeter Yi
 
Node.js开发体验
Node.js开发体验Node.js开发体验
Node.js开发体验QLeelulu
 
Ecma script edition5-小试
Ecma script edition5-小试Ecma script edition5-小试
Ecma script edition5-小试lydiafly
 
领域驱动设计实践
领域驱动设计实践领域驱动设计实践
领域驱动设计实践Jacky Chi
 
第六章 函數與巨集
第六章 函數與巨集第六章 函數與巨集
第六章 函數與巨集shademoon
 
cppcheck源码分析
cppcheck源码分析cppcheck源码分析
cppcheck源码分析Wu Liang
 

Similar to 以太坊(Ethereum) solidity & web3.js (20)

20201006 meta_coin 六角學院
20201006 meta_coin 六角學院20201006 meta_coin 六角學院
20201006 meta_coin 六角學院
 
并发控制
并发控制并发控制
并发控制
 
[Crypto Course] Blockchain Security
[Crypto Course] Blockchain Security[Crypto Course] Blockchain Security
[Crypto Course] Blockchain Security
 
深入浅出Netty l.t
深入浅出Netty   l.t深入浅出Netty   l.t
深入浅出Netty l.t
 
利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek
 
ES5 introduction
ES5 introductionES5 introduction
ES5 introduction
 
107个常用javascript语句 oss 计算技术 - ossez info of tech
107个常用javascript语句   oss 计算技术 - ossez info of tech107个常用javascript语句   oss 计算技术 - ossez info of tech
107个常用javascript语句 oss 计算技术 - ossez info of tech
 
高性能远程调用解决方案
高性能远程调用解决方案高性能远程调用解决方案
高性能远程调用解决方案
 
主备备的两个备机转为双Master出现诡异的slave lag问题
主备备的两个备机转为双Master出现诡异的slave lag问题主备备的两个备机转为双Master出现诡异的slave lag问题
主备备的两个备机转为双Master出现诡异的slave lag问题
 
Python變數與資料運算
Python變數與資料運算Python變數與資料運算
Python變數與資料運算
 
Chapter 3 basic syntax and operator
Chapter 3  basic syntax and operatorChapter 3  basic syntax and operator
Chapter 3 basic syntax and operator
 
Arduino應用系統設計 - Arduino程式快速入門
Arduino應用系統設計 - Arduino程式快速入門Arduino應用系統設計 - Arduino程式快速入門
Arduino應用系統設計 - Arduino程式快速入門
 
Java华为面试题
Java华为面试题Java华为面试题
Java华为面试题
 
180518 ntut js and node
180518 ntut js and node180518 ntut js and node
180518 ntut js and node
 
Node.js开发体验
Node.js开发体验Node.js开发体验
Node.js开发体验
 
Ecma script edition5-小试
Ecma script edition5-小试Ecma script edition5-小试
Ecma script edition5-小试
 
领域驱动设计实践
领域驱动设计实践领域驱动设计实践
领域驱动设计实践
 
第六章 函數與巨集
第六章 函數與巨集第六章 函數與巨集
第六章 函數與巨集
 
Arduino程式快速入門
Arduino程式快速入門Arduino程式快速入門
Arduino程式快速入門
 
cppcheck源码分析
cppcheck源码分析cppcheck源码分析
cppcheck源码分析
 

More from HO-HSUN LIN

區塊鏈與金融科技(Blockchain and Fintech)
區塊鏈與金融科技(Blockchain and Fintech)區塊鏈與金融科技(Blockchain and Fintech)
區塊鏈與金融科技(Blockchain and Fintech)HO-HSUN LIN
 
Tensorflow + Keras & Open AI Gym
Tensorflow + Keras & Open AI GymTensorflow + Keras & Open AI Gym
Tensorflow + Keras & Open AI GymHO-HSUN LIN
 
Microsoft CNTK, Cognitive Toolkit 微軟深度學習工具
Microsoft CNTK, Cognitive Toolkit 微軟深度學習工具Microsoft CNTK, Cognitive Toolkit 微軟深度學習工具
Microsoft CNTK, Cognitive Toolkit 微軟深度學習工具HO-HSUN LIN
 
Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發HO-HSUN LIN
 
Net Parallel Programming .NET平行處理與執行序
Net Parallel Programming .NET平行處理與執行序Net Parallel Programming .NET平行處理與執行序
Net Parallel Programming .NET平行處理與執行序HO-HSUN LIN
 

More from HO-HSUN LIN (6)

區塊鏈與金融科技(Blockchain and Fintech)
區塊鏈與金融科技(Blockchain and Fintech)區塊鏈與金融科技(Blockchain and Fintech)
區塊鏈與金融科技(Blockchain and Fintech)
 
Tensorflow + Keras & Open AI Gym
Tensorflow + Keras & Open AI GymTensorflow + Keras & Open AI Gym
Tensorflow + Keras & Open AI Gym
 
Microsoft CNTK, Cognitive Toolkit 微軟深度學習工具
Microsoft CNTK, Cognitive Toolkit 微軟深度學習工具Microsoft CNTK, Cognitive Toolkit 微軟深度學習工具
Microsoft CNTK, Cognitive Toolkit 微軟深度學習工具
 
Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發
 
Net Parallel Programming .NET平行處理與執行序
Net Parallel Programming .NET平行處理與執行序Net Parallel Programming .NET平行處理與執行序
Net Parallel Programming .NET平行處理與執行序
 
ASP.NET AJAX
ASP.NET AJAXASP.NET AJAX
ASP.NET AJAX
 

以太坊(Ethereum) solidity & web3.js

  • 2. 個人簡歷  林和勲  https://www.linkedin.com/in/ho-hsun-lin-0298975/  https://www.slideshare.net/salingerslin  salingersms@msn.com  經歷  現任職台灣銀行  研究專長為機器學習、人工智慧、區塊鏈  學歷  國立政治大學資訊科學系
  • 3. 區塊鏈  分散式資料庫:交易紀錄 (總帳)  公私鑰對(Pair),產生帳戶位址與密碼  定時同步、資料公開透明  共識機制:挖礦  Proof of Work, PoW  挖礦者(Miner)驗證批量交易資料,賺取以太幣  區塊鏈(Block Chain):難以竄改  區塊(Block):批量交易資料、時間戳(Time Stamp)  鏈(Chain):前一區塊的Hash紀錄
  • 4. 技術演進  拜占庭將軍問題 (Byzantine Generals Problem) -- 1982, L. Lamport, R. Shostak, M. Pease  eCash -- 1990, David Chaum  時間戳數位文件安全 --1991, Stuart Haber, W. Scott Stornetta  橢圓曲線數位簽章演算法 -- 1992, Don Johnson, Alfred Menezes, Scott Vanstone  Hashcash (工作量證明機制 Proof of Work, PoW) -- 1997, Adam Back  B-money -- 1998, Wei Dai  Bit Gold (去中心化) -- 1998, Nick Szabo  可重複使用的工作量證明機制 (Reusable Proofs of Work,RPoW) -- 2005, Hal Finney  比特幣 -- 2008, 中本聰
  • 5. 以太坊 (ETHEREUM)  2013 年底 Bitcoin 開發者Vitalik Buterin 發想「有 邏輯」的虛擬貨幣交易平台  全球級的分散式「電腦」,可存放交易紀錄、自訂 資料,及進行邏輯運算  平均每十五秒同步一次  智能合約 (Smart Contract)  Ethereum Virtual Machine  可加入公開鏈,或部署為企業應用私有鏈  1 以太幣(ether)  1000 finney  1000000000000000000 wei  推薦平台 Enode  以 Go 語言實做 Ethereum 協議  支援多平台  支援多執行序  https://github.com/ethereum/go- ethereum/wiki/Building-Ethereum
  • 6. 環境建置:GETH - ETHEREUM NODE, ENODE 公開鏈  geth --mine --minerthread 2 --autodag –fast 建立私有鏈  設定創世塊 (Genesis Block)  geth init genesis.json  連接私有鏈  geth --networkid 16888 --port 30303 --nodiscover --maxpeers 25 --nat "any" --rpc --rpccorsdomain "*" --rpcapi "eth,net,web3,debug" --mine -- minerthreads 1 --autodag  建立帳戶、部屬合約、進行交易、進行挖礦  使用電子錢包  https://github.com/ethereum/mist/releases
  • 7. 私有鏈設定檔 genesis.json { "difficulty": "0x0", "extraData": "0x16888", "gasLimit": "0x999999999", "mixhash": “ADDRESS", "nonce": "0x0", "timestamp": "0x0" } static-nodes.json [ "enode://ADDRESS@IP:PORT" ]
  • 8. 私有鏈設定:WINDOWS 重置  delete  C:Users使用者AppDataRoamingEthereum  C:Users使用者AppDataEthash 設定 1. C:Users使用者  https://build.ethdev.com/builds/Windows%20 Go%20master%20branch/Geth-Win64- latest.zip 2. geth init genesis.json 3. geth account new 4. C:Users使用者 AppDataRoamingEthereumstatic- nodes.json 5. 連接私有鏈
  • 9. 私有鏈設定:MAC 重置  delete  ~/Library/Ethereum  ~/.ethash 設定 1. brew  tap ethereum/Ethereum  install Ethereum 2. geth init genesis.json 3. geth account new 4. ~/Library/Ethereum/static-nodes.json 5. 連接私有鏈
  • 10. 私有鏈設定:LINUX 重置  delete  ~/.ethereum  ~/.ethash 設定 1. https://github.com/ethereum/go- ethereum/wiki/Building-Ethereum 2. geth init genesis.json 3. geth account new 4. ~/.Ethereum/static-nodes.json 5. 連接私有鏈
  • 11. GETH 指令 Enode  進入本地端 geth 命令列控制介面  geth attach  加入 peer (於命令列控制介面)  admin.addPeer("enode://ADDRESS@IP:PORT")  設定 peer:static-nodes.json  ["enode://ADDRESS@ IP:PORT"] Account  新增帳戶  geth account new  列出帳戶  geth account list
  • 13. BLOCKS & TRANSACTIONS Blocks  資料庫 (Blockchain) 的狀態  帳戶餘額  智能合約中的狀態變數  交易的對象  個人帳號(External Account)  合約帳號Contract Account  公鑰私鑰  私鑰:創立帳號時輸入的密碼  公鑰:Account address Transactions  Message  from  To  Value:以太幣  binary data:合約的 bytecode,其他資料  預設最大值 89kb
  • 14. PHASES Contract • 合約部署 Execution • 合約執行 State Transition • 狀態改變 Commit • 提交共識
  • 15. 智能合約設計 公開鏈  資料公開透明,私密資料請自行加密  鏈外 (off-chain) 流程設計 私有鏈  same networkid  same genesis block  mixhash  nonce  extradata
  • 16. 交易(TXS) & 訊息(MSG) 交易(TXs)  交易包含訊息 (Message)  External Account傳送交易 訊息(MSG)  內部交易 (Internal Transaction)  Contract Account 傳送訊息 (Message)  訊息不會被記錄
  • 17. TRANSACTIONS & CALLS Transactions  異動資料:帳戶餘額、合約變數  一般函式 Call  查詢資料  常數函式:Constant Function
  • 19. SOLIDITY 程式特性  類似 JavaScript  強型別  var 型別推論 開發環境建置  Solc 編譯器(Compiler)  npm install solc -g  solcjs --help  solcjs contract.sol  文字編輯器套件  https://github.com/juanfranblanco/vscode-solidity  線上 IDE  http://ethereum.github.io/browser-solidity/
  • 20. SOLIDITY Hello world contract HelloWorld { string public greeting = ""; function setHelloWorld() { greeting = "hello, world"; } } 基本架構  狀態變數 (State Variable)  狀態機 (State Machine)  函式  函式描述子 (Function Modifier)  建構式  異動資料、呼叫其他合約  事件  與鏈外互動互動: Web3.js
  • 21. 資料型別 實值型別  bool  int / int256, uint  uint constant HEX_NUM = 0x123A1;  address  20 byte value (size of an Ethereum address)  bytesN (1 <= N <= 32)  fixed-size byte arrays  常數修飾詞  constant 參考型別  string  implicitly convertible to bytesN  UTF-8 supported  Arrays (if T is a value type)  T[] t; // Dynamic-length array  T[N] t; // N-length array  T[N][M] t; // M x N array (there is M T[N])  Mappings  mapping (Ktype => Vtype) myMap;  K can be almost any type except mapping  V can be any type  if K does not exist, V is zero  in fatct, it uses sha3(K) to look up its value
  • 22. 實值型別 地址(address)  合約帳戶(Contract Account)  address public owner;  外部帳戶(External Account)  owner.balance  mapping (string => uint) public balances;  balances["Bob"] = 10 ether;  靜態陣列  bytes32[5] nicknames;  動態陣列  bytes32[] names;  陣列長度  names.length; bytesN
  • 23. 參考型別 & 自訂型別 參考型別:Structs struct Bank { address owner; uint balance; } Bank bank = Bank ({ owner: "0x692a70d2e424a56d2c6c27aa97d1a86395877b3a", balance: 5 }); 自訂型別  enums  enum Direction { Left, Right, Up, Down }  Direction myDirection = Direction.Up;
  • 24. 其他型別 全域變數  block  block.blockhash(uint blockNumber) returns (bytes32)  block.coinbase // miner's address  block.gaslimit // current block gaslimit  block.number // current block number  block.timestamp // current block time (before commit)  msg  msg.sender // sender of the message (current call)  msg.value // how much wei sent with the message  tx  tx.origin // sender of the transaction (full chain call)  now  alias for block.timestamp 型別轉換  隱含轉換  uint8 -> uint16 (O)  int8 -> int16 (O)  int8 -> uint8 (X)  明確轉換  int8 y = -3; uint x = uint(y); // x is now 0xfffff..fd  uint32 a = 0x12345678; uint16 b = uint16(a); // b is now 0x5678
  • 25. 流程控制  邏輯  If、else、?:  迴圈  while 、for 、break 、continue  函式  return; 、  return VALUE,..;  function NAME(ARG,..) VISIBILITY returns (TYPE,...) {}  能見度控制 (封裝)  external、public 、 internal 、 private  賦值 function f() returns (uint, bool, uint) { return (7, true, 2); } var (x, b, y) = f();  例外  throw;  復原資料狀態的改變
  • 27. GAS GAS  fee = gas (fuel) * gasPrice  合約傳送以太幣補助 (stipend) 2300 gas  帳戶傳送以太幣花費 21000 gas  每個 EVM 指令有相對應的 gas  程式愈複雜愈貴  防止惡意攻擊及維護公開鏈的系統效能  Gas 不夠時會發生 Error  throw 會強制花光所有 gas 以防繼續執行下去 Transation  成功  fee:獎勵 fuel x gasPrice 給 miner  fuel :剩餘的 fuel x gasPrice 退回給 originator  失敗  fee :miner 全拿  fuel :因為 gas (fuel) 不夠或被 throw
  • 28. 函式描述子(MODIFIER)  描述子  function onlyOwnerCanDoThis() isOwner { ... }  參數  function aFunctionNeedingEther costsAtLeast(10 ether) { ... }  payable  為保留字,附加傳送以太幣
  • 30. 密碼函式  addmod(uint x, uint y, uint k) returns (uint)  (x + y) % k  mulmod(uint x, uint y, uint k) returns (uint)  (x * y) % k  sha3(...) returns (bytes32)  ... means tightly packed so sha3("abc") == sha3("ab", "c")  faster in EVM (special bytecode)  sha256(...) returns (bytes32)  ripemd160(...) returns (bytes20)  ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)  利用橢圓加密復原從簽章反推出當初簽章者的 address  hash 為 secp256k1.sign(msg hash, privatekey) 之產物 (Tx hash 被外部帳戶 sign)  v 為 signature.復原參數 + 27 (ethereum 橢圓參數)  r 為 signature[0-31],s 為 signature[32-63]
  • 31. ADDRESS 函式  address.send(uint wei) returns (bool)  ALWAYS check if sending process is successful with returned boolean  address.balance // return wei in uint  this // this contract's address // 傳 10 以太幣 給呼叫合約函式者 (msg.sender) msg.sender.send(10 ether); // 傳 此合約擁有的所有錢 給呼叫合約函式者 msg.sender.send(this.balance);
  • 32. 合約(CONTRACT)函式  this  此 contract 的位址  selfdestruct(address recipient)  合約自殺時,把合約帳戶裡的餘額退還到指定帳戶  假如合約中沒有撰寫此方法或其他傳送以太幣的方法,合約的錢永遠拿不回來  function () {}  被稱為 Fallback Function,沒有名字的函式  當從外部合約呼叫此合約的方法時發生錯誤(例如函式名稱不對或參數個數放錯), 就會進到此函式,有點像是其他語言的 switch 中的 default (solidity 沒有 switch)  當有帳戶想要單純送錢 至合約時,也會進入這個函式(因為單純送錢的函式沒有名字)  function () payable {}  沒有加上 payable 描述子的話將無法被 .send(),要讓其他帳戶能送錢進來的話 必須加上此描述子,並實作此 Fallback Function ( {} 內留空白亦可)
  • 33. 呼叫合約 import  介面  function F() [modifiers...] [contant] returns(T…,) {}  狀態變數  T [public, external] t; 呼叫合約  Contract contract= Contract(address);  確定 address type  明確轉換 (Explicit Conversion)
  • 34. 呼叫合約  呼叫方法  contract.function(arg…,);  單純送錢  contract.send(uint wei);  gas stipend 2300  呼叫方法順便送錢  contract.function.value(uint wei)(arg…,);  設定 gas  contract.function.gas(uint gas)(arg…,);  Refection  副作用極大,未來版本將逐漸移除
  • 37. WEB3.JS (CONT’D) : ARCH-GRAPH Network Web3.js  部署合約  交易物件 (Transaction Object)  Reflection (反映) 方法  ABI  呼叫合約方法 (Contract Functions)  Call  Transaction  聽取事件  過濾事件  全域事件 enode enode enode enode Web3.js Web3.js
  • 38. 通訊協定  RPC :較彈性,目前只有 HTTP,較不安全  Web3.js  IPC :較快且安全  geth attach  WS:WebSocket ,可以高迸發處理客戶端  適合實作網頁即時服務用
  • 39. TRANSACTIONS & BLOCK  pending transactions  本地 enode 中還沒被放進 pending block 來mining 的交易  pending block  本地 enode 正在 mining 的 block  latest block  chain 上最新的 block  transactionReceipt  指 transaction 執行過後 在 chain 中 的記錄
  • 40. ABI, APPLICATION BLOCKCHAIN INTERFACE  eth  用來透過 Enode 向 Ethereum 鏈操作、感知 Ethereum 鏈上發生的事情  admin  管理 Enode 的元件服務  miner  管理挖礦元件  personal  管理帳戶:解鎖、鎖定帳戶,及以指定帳戶的名義簽署交易
  • 41. 事件監聽 設定物件 var block = eth.filter('latest’, { from: Number | String, to: Number | String, address: String }); 開始/停止 block .watch(function(err, latestBlockHash) {}); block .stopWatching();
  • 42. 取得物件  block  eth.getBlock('latest’)  eth.getBlock('pending’)  eth.getBlock(NUM)  transaction  eth.getTransaction(HASH)  eth.getTransactionReceipt(HASH)  eth.pendingTransactions  address  eth.getBalance(addressString);  enode  eth.accounts  eth.coinbase == eth.accounts[0] //挖擴者  web3  web3.fromWei  web3.toWei  minter  miner.start(N)  miner.stop()  eth.mining  eth.syncing
  • 43. 惰性節點 function work() { if (eth.getBlock("pending").transactions.length > 0) { if (eth.mining) { return; } miner.start(threads); } else { miner.stop(); } } var threads = 1 eth.filter("latest", function(err, block) {work(); }); eth.filter("pending", function(err, block) {work(); }); work();
  • 44. SAFE USAGE  Signing transactions  https://github.com/ethereumjs/ethereumjs-tx  HTTPS  Node.js  Proxy
  • 45. GETTING STARTED  https://github.com/ethereum/wiki/wiki/JavaScript-API  npm install web3  var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  • 46. 部署合約  推薦使用 browser-solidity 自動產生的 web3 deploy code  編譯後,可以得到 bytecode 及 ABI  經由 sendTransaction 搭上 data (bytecode)  eth.sendTransaction ({ from: eth.coinbase, data: BYTECODE, gas: 1234567 });  eth.getTransactionReceipt(TxHash).contractAddress
  • 47. TRANSACTION OBJECT personal.unlockAccount('帳戶位址', '密碼', 幾秒); eth.sendTransaction ({ from: , //從什麼帳戶位址 to: , //從什麼帳戶位址,假如要部署合約可以忽略 gas: , //多少 wei,預設 90000沒用完的會退回來 gasPrice: , //多少 gas,gas 單價,Enode設定 value: , //多少 wei 要傳 data: , //附加資料:部署合約或呼叫合約,或也可以儲存資料,最大值為 89kb nonce: , // 用於標示 Transaction 的順序,所以可以以相同的 nonce 覆蓋同 nonce 的交易 });
  • 48. 呼叫智能合約 Transaction storageContract.setData("區塊鏈!", { from: eth.coinbase, gas: 1234567 });  TxHash:回傳值,後續用來追蹤區塊 Block  eth.getTransactionReceipt(TxHash)  gasUsed:真實使用的gas值,可用來判斷是否執行成功 Call var data = storageContract.getData(); storageContract.getData(function(err, data) { console.log(err, data); })  Transaction vs Call  被 mine vs 不會被 mine  花到錢 vs 不會花到錢  會影響資料庫 (Blockchain) vs 不會影響資料庫  慢 vs 快
  • 50. 事件:SOLIDITY contract event { event fire(address indexed sender, uint indexed value); function fire() { fire(msg.sender, msg.value); } }
  • 51. 事件:WEB3.JS Transaction // var watcher = contract.fire({},{from:?, to:?}); watcher.get(function(err, eventLog) { console.log(JSON.stringify(eventLog, null, 2)); }); // indexed var watcher = contract.fire({num: 1}); watcher.watch(function(e, r){console.log('1')}); watcher.stopWatching(); Call contract.fire({}, function(err, eventLog) { console.log(JSON.stringify(eventLog, null, 2)); });
  • 52. EXAMPLE pragma solidity ^0.4.2; contract event { string public data; event transaction(string input, address from, uint time); function call() constant returns(string) {return data;} function transaction(string input) { data = input; transaction(input, msg.sender, now); } }
  • 54. 常見漏洞:RE-ENTRANCY var share = shares[msg.sender]; shares[msg.sender] = 0; if (!msg.sender.send(share)) { throw; }  Re-Entrancy  Reflection 有可能會造成回呼,形成邏輯漏洞  身分驗證  tx.origin:交易發送者,不要使用於驗證  msg.sender:訊息發送者,可能等於 tx.origin
  • 55. 常見漏洞: SELFDESTRUCT  合約帳戶  回收合約中的錢,摧毀合約並將以太幣轉至特定帳號  堆疊深度(Call stack Depth)  目前最深深度為 1024  溢位  因重要的數字記得檢查溢位檢查

Editor's Notes

  1. 為了效率!
  2. admin, miner, personal 不應該、不建議 在 RPCAPI 中開放 private key 都儲存在本機 enode 然後被 passphrase 所加密 所以我們要以 本機 enode 不存在的 account 的名義來發起交易的話,必須要用 那個 account 的 private key 來 sign (因為一個 public key 只有一個 private key 可以匹配)
  3. admin, miner, personal 不應該、不建議 在 RPCAPI 中開放 private key 都儲存在本機 enode 然後被 passphrase 所加密 所以我們要以 本機 enode 不存在的 account 的名義來發起交易的話,必須要用 那個 account 的 private key 來 sign (因為一個 public key 只有一個 private key 可以匹配)
  4. oraclize: https://docs.google.com/presentation/d/1u6PyAwsm3sCuZqV2n5HrFZkOCTDV4jsruU3wus2M304/edit#slide=id.p