Blockchain Programming with Lisp
2017-11-11
한철희
hacker@lisp.ai
Agenda
• 이 세션의 범위
• 블록체인
• 이더리움
• 이더리움 스마트 컨트랙트 개발
• LLL, Lisp Like Language
• 예제 : simple Key-Value 저장소
• 결론
• 도움 되는 링크
• Q & A
이 세션의 범위
• 블록체인
• 이더리움
• 이더리움의 스마트 컨트랙트 개발
• LLL로 개발 하기
• 간단한 예제 : Key-Value Store
• 대상 외
• 가상화폐의 미래
• 채굴(마이닝)
• 개발 환경 세팅 Google it !!
Blockchain
• P2P를 이용하여 정보를 변조가 불가능한 형태로 공유하는 시스템
• 변조 발생시 바로 감지 가능한 데이터 구조
• 정보를 블록(block) 형태로 계속 이어서(chain) 검증하며 쌓아감. 이 작업을 채굴
(mining)이라 하고 보수가 지급됨
• 이 보수가 채굴자들(miners) 이 인프라를 유지시킬 명분
- 굳이 비유하자면, 비트토렌트 Seeder, Tracker 에게 페이를 지급하는 느낌
From https://upload.wikimedia.org/wikipedia/commons/5/55/Bitcoin_Block_Data.svg
Smart Contract
• 계약을 서면이 아닌 디지털화하여 자동 체결, 수행하는 개념
• Nick Szabo 1996년 제안
• 블록체인의 발전으로 실현 가능한 수준에 도달
• 비트코인도 스마트컨트랙트의 일종이라 할 수 있음
• ( A→B 송금하면 A의 코인이 줄어들고 B의 코인이 늘어남 )
Ethereum
• Bitcoin 다음으로 가장 알려진 가상화폐 (사실은 플랫폼)
• 스마트컨트랙트를 제대로 구현 및 실행 시킬 수 있는 플랫폼 (
Turing Complete )
• 블록체인 상에 저장된 바이트코드(컨트랙트 코드)가 EVM
(Ethereum Virtual Machine)에서 실행됨
• 실행 비용이 공짜는 아님 ( 코드 하나당 wei 를 소모, Gas라 부름 )
• 가상화폐 통화 단위는 ether ( ETH ) , wei 등을 사용
• 1 ether = 10 ^ 18 wei
Ethereum 스마트 컨트랙트 개발
• 비트토렌트가 여러 클라이언트 프로그램이 있듯 이더리움도 그러하
다
• go-lang으로 구현한 go-ethereum (통칭 Geth) 를 많이 사용
• 이더리움의 네트워크의 종류 : 웹서비스 개발 환경과 유사
1. Live Network https://etherscan.io
2. Test Network https://ropsten.etherscan.io
3. Local Network
• 개발 언어
• Solidity : Javascript-like
• Serpent : Python-like
• LLL : Lisp-like
• Mutan : C-like , deprecated
LLL,Lisp Like Language
• “Lisp Like Language (LLL) is a low level language similar to Assembly. It is
meant to be very simple and minimalistic; essentially just a tiny wrapper over
coding in EVM directly.” - Ethereum Homestead Documentation
• Low-level Lisp-like Language , LLLLL …
• 이더리움 플랫폼 초창기에 개발된 언어 (라고 합니다)
• Lisp의 명료한 문법 + EVM 어셈블리의 만남
• EVM Opcode를 다이렉트로(C의 인라인 어셈블리처럼) 코딩할 수 있다
• 실행 코드가 작다 ( = 컴퓨팅 비용 적다, Gas 비용 절감 )
• EVM 동작 원리를 잘 알 수 있다 ( C 프로그래머? )
• 개발 난이도 : 알면 알수록 쉬워짐
(seq
(def 'scratch 0x00)
(def 'identity 0xac37eebb)
(def 'function (function-hash code-body)
(when (= (div (calldataload 0x00) (exp 2 224)) function-hash)
code-body))
(returnlll
(function identity
(seq
(mstore scratch (calldataload 0x04))
(return scratch 32)))))
LLL의 특징
• 현재의 lllc ( LLL Compiler ) 기준으로
• 재귀 호출 불가 !!! : def 는 전부 인라인 매크로로 바뀌기 때문
- 사실 스마트 컨트랙트 하나는 그냥 하나의 루틴. 서브루틴 없음
JVM의 .class와는 명백하게 다른 점
- 대신 for, while , until 이 있다
• cons, list … 없음. lisp 맞나
• 포인터(레퍼런스)변수가 존재
- 예전 lllc 는 이것도 없어서 변수할당이 정말 수동?이었음
• Functional 지향보다는 저수준 C언어 스타일 지향
• 애초에 LLL은 플랫폼 초창기 개발됐음
• Serpent도 내부적으로 LLL로 컴파일됨
예제: Key-Value Store
• Java의 HashMap과 비슷하지만 저수준
• key : 0 ~ 255 정수. 범위 벗어나면 무시됨
• value : 32바이트 부호있는 정수 (int256)
- EVM은 기본 처리 단위가 32(0x20) 바이트
• 2가지 메쏘드
• put(uint256 k, int256 v)
• get(uint256 k)
• 개발 순서
• 인터페이스 정의 : ABI
• 코드 컴파일 : 바이트코드
• Geth 환경에 Deploy
• 테스트
예제:kv5.sol
> cat kv5.sol
pragma solidity ^0.4.8;
contract KV5 {
function put(uint key, int value) public;
function get(uint key) constant public returns (int);
}
> solc --hashes --abi kv5.sol
======= kv5.sol:KV5 =======
Function signatures:
9507d39a: get(uint256)
e2b5e968: put(uint256,int256)
Contract JSON ABI
[{"constant":true,"inputs":[{"name":"key","type":"uint256"}],"name":"
get","outputs":[{"name":"","type":"int256"}],"payable":false,"stateMu
tability":"view","type":"function"},{"constant":false,"inputs":[{"nam
e":"key","type":"uint256"},{"name":"value","type":"int256"}],"name":"
put","outputs":[],"payable":false,"stateMutability":"nonpayable","typ
e":"function"}]
예제:kv5.lll
(returnlll
(seq
(def 'range-max 0xff)
(def 'range-min 0x00)
(def 'check-range (v)
(if (or (s< v range-min) (s> v range-max)) (panic) 0))
; 변수 선언
(set 'key 0)
(set 'value 0)
(set '_funid (/ (calldataload 0x00) (exp 2 224))) ; 함수 시그니처 해시
; put(uint256,int256)
(when (= @_funid 0xe2b5e968 ) ; Keccak256("put(uint256,int256)") >>> 228
(seq
(mstore key (calldataload 0x04)) ; 첫번째 인자
(check-range (mload key))
(mstore value (calldataload 0x24)) ; 두번째 인자
[[@key]] : @value ; (sstore (mload key) (mload value))
(return 0) ; 그냥 빈 값 리턴
))
; get(uint256)
(when (= @_funid 0x9507d39a ) ; Keccak256("get(unit256") >>> 228
(seq
[key] (calldataload 0x04)
(check-range @key) ; (mload key) 단축형 @key
[value] (sload @key) ; (mstore a b) 단축형 [a] b
(return @value)
))
))
kv5 실행
// geth js 콘솔에서 수행
eth.defaultAccount = eth.coinbase
miner.start(1)
var c_kv5 = eth.contract(abi)
var kv5 = c_kv5.new({data:bin, from:eth.coinbase, gas:1000000})
eth.pendingTransactions.length // 0가 되면 Deploy 완료
kv5.get(1) // 0 리턴
kv5.put(1, 3141592)
kv5.put(2, 2718281828)
kv5.put(10000, -111)
eth.pendingTransactions.length // 0가 되면 Transaction 처리 완료
kv5.get(1) // 3141592 리턴
kv5.get(2) // 2717281828 리턴
kv5.get(10000) // 범위를 벗어나므로 0이 리턴
Conclusion
• Ethereum은 스마트 컨트랙트 지향 블록체인 플랫
폼
• 컨트랙트 개발 언어로 저수준 코딩이 가능한 LLL이
있다
• Lisp는 이런 곳에서도 활약 중이다
• LLL을 배우면 EVM이 내 머리 속에 임플란트 된다
관련 Links (1/2)
• https://github.com/ethereum/yellowpaper
- 이더리움 옐로페이퍼
• http://lll-docs.readthedocs.io/en/latest/index.html
- 현재로선 가장 잘 정리된 LLL 레퍼런스 문서
• https://github.com/ethereum/cpp-ethereum/wiki/LLL-PoC-
6/04fae9e627ac84d771faddcf60098ad09230ab58
- 공식 문서. 하지만 부실한 내용
관련 Links (2/2)
• https://media.consensys.net/an-introduction-to-lll-for-ethereum-smart-
contract-development-e26e38ea6c23
- 현재로서는 유일하고 친절한(비교적) step-by-step LLL 강좌
• http://blog.syrinx.net/the-resurrection-of-lll-part-1/
- EVM, LLL 지식이 요구됨
• https://github.com/ethereum/cpp-ethereum/wiki/LLL-Examples-for-PoC-
5/04fae9e627ac84d771faddcf60098ad09230ab58
- 예제 코드 ( deprecated? )
• https://github.com/drcode/clll
- Run Ethereum LLL contracts directly from Clojure
Q & A
부록 : 시간관계상 생략했던 부분
• Geth 설치
Google에서 “Geth 설치” 로 검색하면 여러 설치법이 나옵니다
• 컴파일러 설치
https://media.consensys.net/installing-ethereum-compilers-61d701e78f6
solc, lllc 설치
• Compile and Deploy
https://media.consensys.net/compiling-your-first-contract-in-lll-28d5a9dd2e3a
identity.lll 을 빌드, Deploy, Test 하면 성공

Blockchain Programming with Lisp

  • 1.
    Blockchain Programming withLisp 2017-11-11 한철희 hacker@lisp.ai
  • 2.
    Agenda • 이 세션의범위 • 블록체인 • 이더리움 • 이더리움 스마트 컨트랙트 개발 • LLL, Lisp Like Language • 예제 : simple Key-Value 저장소 • 결론 • 도움 되는 링크 • Q & A
  • 3.
    이 세션의 범위 •블록체인 • 이더리움 • 이더리움의 스마트 컨트랙트 개발 • LLL로 개발 하기 • 간단한 예제 : Key-Value Store • 대상 외 • 가상화폐의 미래 • 채굴(마이닝) • 개발 환경 세팅 Google it !!
  • 4.
    Blockchain • P2P를 이용하여정보를 변조가 불가능한 형태로 공유하는 시스템 • 변조 발생시 바로 감지 가능한 데이터 구조 • 정보를 블록(block) 형태로 계속 이어서(chain) 검증하며 쌓아감. 이 작업을 채굴 (mining)이라 하고 보수가 지급됨 • 이 보수가 채굴자들(miners) 이 인프라를 유지시킬 명분 - 굳이 비유하자면, 비트토렌트 Seeder, Tracker 에게 페이를 지급하는 느낌 From https://upload.wikimedia.org/wikipedia/commons/5/55/Bitcoin_Block_Data.svg
  • 5.
    Smart Contract • 계약을서면이 아닌 디지털화하여 자동 체결, 수행하는 개념 • Nick Szabo 1996년 제안 • 블록체인의 발전으로 실현 가능한 수준에 도달 • 비트코인도 스마트컨트랙트의 일종이라 할 수 있음 • ( A→B 송금하면 A의 코인이 줄어들고 B의 코인이 늘어남 )
  • 6.
    Ethereum • Bitcoin 다음으로가장 알려진 가상화폐 (사실은 플랫폼) • 스마트컨트랙트를 제대로 구현 및 실행 시킬 수 있는 플랫폼 ( Turing Complete ) • 블록체인 상에 저장된 바이트코드(컨트랙트 코드)가 EVM (Ethereum Virtual Machine)에서 실행됨 • 실행 비용이 공짜는 아님 ( 코드 하나당 wei 를 소모, Gas라 부름 ) • 가상화폐 통화 단위는 ether ( ETH ) , wei 등을 사용 • 1 ether = 10 ^ 18 wei
  • 7.
    Ethereum 스마트 컨트랙트개발 • 비트토렌트가 여러 클라이언트 프로그램이 있듯 이더리움도 그러하 다 • go-lang으로 구현한 go-ethereum (통칭 Geth) 를 많이 사용 • 이더리움의 네트워크의 종류 : 웹서비스 개발 환경과 유사 1. Live Network https://etherscan.io 2. Test Network https://ropsten.etherscan.io 3. Local Network • 개발 언어 • Solidity : Javascript-like • Serpent : Python-like • LLL : Lisp-like • Mutan : C-like , deprecated
  • 8.
    LLL,Lisp Like Language •“Lisp Like Language (LLL) is a low level language similar to Assembly. It is meant to be very simple and minimalistic; essentially just a tiny wrapper over coding in EVM directly.” - Ethereum Homestead Documentation • Low-level Lisp-like Language , LLLLL … • 이더리움 플랫폼 초창기에 개발된 언어 (라고 합니다) • Lisp의 명료한 문법 + EVM 어셈블리의 만남 • EVM Opcode를 다이렉트로(C의 인라인 어셈블리처럼) 코딩할 수 있다 • 실행 코드가 작다 ( = 컴퓨팅 비용 적다, Gas 비용 절감 ) • EVM 동작 원리를 잘 알 수 있다 ( C 프로그래머? ) • 개발 난이도 : 알면 알수록 쉬워짐 (seq (def 'scratch 0x00) (def 'identity 0xac37eebb) (def 'function (function-hash code-body) (when (= (div (calldataload 0x00) (exp 2 224)) function-hash) code-body)) (returnlll (function identity (seq (mstore scratch (calldataload 0x04)) (return scratch 32)))))
  • 9.
    LLL의 특징 • 현재의lllc ( LLL Compiler ) 기준으로 • 재귀 호출 불가 !!! : def 는 전부 인라인 매크로로 바뀌기 때문 - 사실 스마트 컨트랙트 하나는 그냥 하나의 루틴. 서브루틴 없음 JVM의 .class와는 명백하게 다른 점 - 대신 for, while , until 이 있다 • cons, list … 없음. lisp 맞나 • 포인터(레퍼런스)변수가 존재 - 예전 lllc 는 이것도 없어서 변수할당이 정말 수동?이었음 • Functional 지향보다는 저수준 C언어 스타일 지향 • 애초에 LLL은 플랫폼 초창기 개발됐음 • Serpent도 내부적으로 LLL로 컴파일됨
  • 10.
    예제: Key-Value Store •Java의 HashMap과 비슷하지만 저수준 • key : 0 ~ 255 정수. 범위 벗어나면 무시됨 • value : 32바이트 부호있는 정수 (int256) - EVM은 기본 처리 단위가 32(0x20) 바이트 • 2가지 메쏘드 • put(uint256 k, int256 v) • get(uint256 k) • 개발 순서 • 인터페이스 정의 : ABI • 코드 컴파일 : 바이트코드 • Geth 환경에 Deploy • 테스트
  • 11.
    예제:kv5.sol > cat kv5.sol pragmasolidity ^0.4.8; contract KV5 { function put(uint key, int value) public; function get(uint key) constant public returns (int); } > solc --hashes --abi kv5.sol ======= kv5.sol:KV5 ======= Function signatures: 9507d39a: get(uint256) e2b5e968: put(uint256,int256) Contract JSON ABI [{"constant":true,"inputs":[{"name":"key","type":"uint256"}],"name":" get","outputs":[{"name":"","type":"int256"}],"payable":false,"stateMu tability":"view","type":"function"},{"constant":false,"inputs":[{"nam e":"key","type":"uint256"},{"name":"value","type":"int256"}],"name":" put","outputs":[],"payable":false,"stateMutability":"nonpayable","typ e":"function"}]
  • 12.
    예제:kv5.lll (returnlll (seq (def 'range-max 0xff) (def'range-min 0x00) (def 'check-range (v) (if (or (s< v range-min) (s> v range-max)) (panic) 0)) ; 변수 선언 (set 'key 0) (set 'value 0) (set '_funid (/ (calldataload 0x00) (exp 2 224))) ; 함수 시그니처 해시 ; put(uint256,int256) (when (= @_funid 0xe2b5e968 ) ; Keccak256("put(uint256,int256)") >>> 228 (seq (mstore key (calldataload 0x04)) ; 첫번째 인자 (check-range (mload key)) (mstore value (calldataload 0x24)) ; 두번째 인자 [[@key]] : @value ; (sstore (mload key) (mload value)) (return 0) ; 그냥 빈 값 리턴 )) ; get(uint256) (when (= @_funid 0x9507d39a ) ; Keccak256("get(unit256") >>> 228 (seq [key] (calldataload 0x04) (check-range @key) ; (mload key) 단축형 @key [value] (sload @key) ; (mstore a b) 단축형 [a] b (return @value) )) ))
  • 13.
    kv5 실행 // gethjs 콘솔에서 수행 eth.defaultAccount = eth.coinbase miner.start(1) var c_kv5 = eth.contract(abi) var kv5 = c_kv5.new({data:bin, from:eth.coinbase, gas:1000000}) eth.pendingTransactions.length // 0가 되면 Deploy 완료 kv5.get(1) // 0 리턴 kv5.put(1, 3141592) kv5.put(2, 2718281828) kv5.put(10000, -111) eth.pendingTransactions.length // 0가 되면 Transaction 처리 완료 kv5.get(1) // 3141592 리턴 kv5.get(2) // 2717281828 리턴 kv5.get(10000) // 범위를 벗어나므로 0이 리턴
  • 14.
    Conclusion • Ethereum은 스마트컨트랙트 지향 블록체인 플랫 폼 • 컨트랙트 개발 언어로 저수준 코딩이 가능한 LLL이 있다 • Lisp는 이런 곳에서도 활약 중이다 • LLL을 배우면 EVM이 내 머리 속에 임플란트 된다
  • 15.
    관련 Links (1/2) •https://github.com/ethereum/yellowpaper - 이더리움 옐로페이퍼 • http://lll-docs.readthedocs.io/en/latest/index.html - 현재로선 가장 잘 정리된 LLL 레퍼런스 문서 • https://github.com/ethereum/cpp-ethereum/wiki/LLL-PoC- 6/04fae9e627ac84d771faddcf60098ad09230ab58 - 공식 문서. 하지만 부실한 내용
  • 16.
    관련 Links (2/2) •https://media.consensys.net/an-introduction-to-lll-for-ethereum-smart- contract-development-e26e38ea6c23 - 현재로서는 유일하고 친절한(비교적) step-by-step LLL 강좌 • http://blog.syrinx.net/the-resurrection-of-lll-part-1/ - EVM, LLL 지식이 요구됨 • https://github.com/ethereum/cpp-ethereum/wiki/LLL-Examples-for-PoC- 5/04fae9e627ac84d771faddcf60098ad09230ab58 - 예제 코드 ( deprecated? ) • https://github.com/drcode/clll - Run Ethereum LLL contracts directly from Clojure
  • 17.
  • 18.
    부록 : 시간관계상생략했던 부분 • Geth 설치 Google에서 “Geth 설치” 로 검색하면 여러 설치법이 나옵니다 • 컴파일러 설치 https://media.consensys.net/installing-ethereum-compilers-61d701e78f6 solc, lllc 설치 • Compile and Deploy https://media.consensys.net/compiling-your-first-contract-in-lll-28d5a9dd2e3a identity.lll 을 빌드, Deploy, Test 하면 성공