본문 바로가기

블럭체인

이더리움 스마트 컨트랙트 개발환경 셋업, 솔리디티 컴파일 & Deploy

셋업 환경

OS: MacOS 10.15.6

이 글 포스트 날짜: 2020년 9월 5일

유저 계정이 staff 그룹에 포함되어 있다. 그렇지 않을 경우 sudo 를 써야 할 수 있다.

 

$ brew install git

$ brew install golang

 

주의: npm이 설치되어 있다고 가정한다.

geth 소스 다운로드 및 빌드

$ git clone https://github.com/ethereum/go-ethereum.git

$ cd go-ethereum

master branch에서 바로 빌드해 보았다.

$ make geth

별 문제 없이 ./build/bin 아래에 geth 바이너리 생성됨.

$ cp ./build/bin/geth /usr/local/bin

환경변수 $PATH에 포함된 경로에 복사.

 

geth로 로컬넷 생성

주의: extraData가 0x0이면 Parsing failure가 뜨면서 초기화에 실패한다.

$ mkdir -p ./ether_data/data_testnet
$ cd ./ether_data/data_testnet
$ cat genesis.json
{
    "config": {},
    "nonce": "0x0000000000000042",
    "timestamp": "0x0",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "0x00",
    "gasLimit": "0x8000000",
    "difficulty": "0x4000",
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "coinbase": "0x3333333333333333333333333333333333333333",
    "alloc": {}
}

$ geth --datadir ./ether_data/data_testnet init ./ether_data/data_testnet/genesis.json

INFO [09-05|13:04:51.713] Maximum peer count                       ETH=50 LES=0 total=50
INFO [09-05|13:04:51.731] Set global gas cap                       cap=25000000
INFO [09-05|13:04:51.731] Allocated cache and file handles         database=/Users/mole/source/blockchain/ethereum/ether_data/data_testnet/geth/chaindata cache=16.00MiB handles=16
INFO [09-05|13:04:51.762] Writing custom genesis block 
INFO [09-05|13:04:51.762] Persisted trie from memory database      nodes=0 size=0.00B time="15.53µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-05|13:04:51.763] Successfully wrote genesis state         database=chaindata hash="3b3326…f217d7"
INFO [09-05|13:04:51.763] Allocated cache and file handles         database=/Users/mole/source/blockchain/ethereum/ether_data/data_testnet/geth/lightchaindata cache=16.00MiB handles=16
INFO [09-05|13:04:51.795] Writing custom genesis block 
INFO [09-05|13:04:51.796] Persisted trie from memory database      nodes=0 size=0.00B time="5.736µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-05|13:04:51.796] Successfully wrote genesis state         database=lightchaindata hash="3b3326…f217d7"

$ geth --networkid 4649 --nodiscover --maxpeers 0 --datadir ./ether_data/data_testnet console 2>> ./ether_data/data_testnet/geth.log

Welcome to the Geth JavaScript console!

instance: Geth/v1.9.21-unstable-f86324ed-20200902/darwin-amd64/go1.15.1
at block: 0 (Thu Jan 01 1970 04:00:00 GMT+0400 (+04))
 datadir: /Users/mole/source/blockchain/ethereum/ether_data/data_testnet
 modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

> personal.newAccount("yourpasswd")
"0x7ccdb05618f00f391e1c18118ce13adf23e2ef50"
> eth.accounts
["0x7ccdb05618f00f391e1c18118ce13adf23e2ef50"]
> eth.getBalance(eth.accounts[0])
0
> eth.mining
false
> miner.start(1)
null
> eth.mining
true
> eth.getBalance(eth.accounts[0])
0
> eth.getBalance(eth.accounts[0])
0
> eth.hashrate
0
> eth.blockNumber
0
> eth.blockNumber
2
> eth.getBalance(eth.accounts[0])
20000000000000000000
> eth.hashrate
9549
> eth.blockNumber
15
> eth.mining
false
> miner.stop()
null
> eth.blockNumber
33
> eth.blockNumber
33
> 

geth 원격 접속 허용 기동

패스워드 파일 생성

$ vi ./ether_data/data_testnet/passwd

yourpasswd

 

$ geth --networkid 4649 --nodiscover --maxpeers 0 --datadir ./ether_data/data_testnet --mine --minerthreads 1 --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --rpccorsdomain "*" --rpcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --unlock 0 --password ./ether_data/data_testnet/passwd --allow-insecure-unlock --verbosity 6 2>> ./ether_data/data_testnet/geth.log

 

Fatal: Account unlock with HTTP access is forbidden!

솔루션: --allow-insecure-unlock 옵션을 추가하면 된다.

 

Fatal: Could not list accounts: index 1 higher than number of accounts 1

솔루션: account를 하나만 추가했으므로 하나 더 추가를 하던지 그냥 --unlock 0,1을 --unlock 0으로 수정하면 된다.

 

$ geth attach rpc:http://localhost:8545

성공적으로 떴다면 로컬넷 접속 테스트를 해본다.

remix-project: solidity compile & deploy tool을 로컬 컴퓨터에 설치

주의: remix-project를 로컬컴퓨터에 설치하지 않고 온라인으로 사용하고 싶다면 https://remix.ethereum.org 접속하여 원격으로 컴파일 및 Deploy가 가능하다.

 

브라우저 기반 solidity compile & deploy 툴인 remix-project를 다운 받는다.

$ git clone https://github.com/ethereum/remix-project.git 

remix-project는 여러차례 이름을 바꿔왔는데 ethereum-solidity에서 remix-ide로 바뀌고 remix-ide에서 최근에 remix-project로 이름을 바꾸었다.

$ cd remix-project
$ npm install -g @nrwl/cli
$ npm install
$ nx build remix-ide --with-deps
$ nx serve

 

http://127.0.0.1:8080/

브라우저(크롬 브라우저 사용)에서 로컬호스트의 8080포트로 접속하면 remix IDE가 뜬다.

 

 

remix로 예제 코드 컴파일 및 Deploy

remix에서 FILE EXPLORERS > browser > 오른쪽 + 버튼을 눌러 소스코드 추가.

hello.sol 파일

pragma solidity ^0.4.8;     // (1) 버전 프라그마

// (2) 계약 선언
contract HelloWorld {
  // (3) 상태 변수 선언
  string public greeting;
  // (4) 생성자
  constructor(string _greeting) public {
    greeting = _greeting;
  }
  // (5) 메서드 선언
  function setGreeting(string _greeting) public {
    greeting = _greeting;
  }
  function say() public constant returns (string) {
    return greeting;
  }
}

SOLIDITY COMPILER 탭에서 Compile hello.sol 버튼을 눌러 컴파일한다.

인터넷에서 구한 소스코드로는 빌드 시 위와 같이 경고가 뜬다.

위에 붙여놓은 소스코드는 warning을 다 수정한 버전이다.

Deploy & Run Transactions 탭에서  environment를 Web3 Provider로 설정하고 

WARNING 메시지를 참고해서 --rpccorsdomain에 와일드카드를 설정하지 않고 직접 주소와 포트번호를 적어준다.

$ geth --networkid 4649 --nodiscover --maxpeers 0 --datadir ./ether_data/data_testnet --mine --minerthreads 1 --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --rpccorsdomain "http://127.0.0.1:8080" --rpcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --unlock 0 --password ./ether_data/data_testnet/passwd --allow-insecure-unlock --verbosity 6 2>> ./ether_data/data_testnet/geth.log

 

Deploy 후에 setGreeting 함수 호출도 해보고 몇가지 테스트를 해봤다.

 

메인넷에 Deploy하는 법

자신이 만든 스마트 컨트랙트를 메인넷에 올리고 싶다면 Injected Web3 선택으로 간단히 된다. 그리고, 메타마스크에서 메인넷으로 설정을 한다. 그리고 Deploy버튼을 누른다. 그러면 인스턴스가 생성되면서 트랜잭션을 발생시킨다.

테스트로 로컬호스트에 붙어봤지만 메인넷에 붙으면 적절한 수수료와 함께 트랜잭션이 발생하면서 스마트 컨트랙트 코드가 블럭에 추가된다.

오 이런! 돈이 없다. 로컬호스트에 생성된 계정에서 마이닝한 돈을 좀 보내야겠다.

 

$ geth --networkid 4649 --nodiscover --maxpeers 0 --datadir ./ether_data/data_testnet --mine --minerthreads 1 --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --rpccorsdomain "http://127.0.0.1:8080" --rpcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --unlock 0 --password ./ether_data/data_testnet/passwd --allow-insecure-unlock --verbosity 6 console 2>> ./ether_data/data_testnet/geth.log

 

콘솔입력을 하기위해 geth 실행 시 console 옵션을 추가했다.

 

> eth.getBalance(eth.accounts[0])
1.616e+22
> eth.sendTransaction({from: eth.accounts[0], to: "0x547c4d6C07A64E62e27df12957548133Ea29B091", value: web3.toWei(1, "ether")})
"0x9ef2077bfa21a1eaabf68d18d6c94bb0007444cb51189464153ab682b05834ca"
> eth.sendTransaction({from: eth.accounts[0], to: "0x547c4d6C07A64E62e27df12957548133Ea29B091", value: web3.toWei(100, "ether")})
"0xbdafa5f57ea9a24fe535294004c030c57e65a6246bae4abecbac918690ff6dc7"

위와 같이 잔고 확인 후에 메타마스크 주소로 1이더리움 전송 후 100이더리움 전송을 해봤다.

승인 버튼을 누르면 생성되어야 하는데 에러가 난다. 테스트 계정을 하나 더 만들어서 계정 리셋을 하더라도 동일하다.

스택오버플로우 검색 결과 메타마스크가 로컬호스트에 연결되었을 경우에는 스마트 컨트랙트 생성 에러가 난다는 이야기를 한다.

관련링크: stackoverflow.com/questions/56514352/i-get-an-error-metamask-rpc-error-error-error-ethjs-rpc-rpc-error-with

 

i get an error: "MetaMask - RPC Error: Error: Error: [ethjs-rpc] rpc error with payload"

I send the transaction from my javascript Metamask open the transfer-dialog i confirm i get an error message in metamask (inpage.js:1 MetaMask - RPC Error: Error: Error: [ethjs-rpc] rpc error with

stackoverflow.com

롭스텐 같은 테스트 네트워크를 이용해서 직접 올려봐야 확인이 가능할 듯 하다.

링크

github.com/ethereum/go-ethereum

 

ethereum/go-ethereum

Official Go implementation of the Ethereum protocol - ethereum/go-ethereum

github.com

opentutorials.org/course/2869/20676

 

개발환경 구축하기 Local Blockchain - 이타인클럽

솔리디티를 이용한 이더리움 스마트 컨트랙트 개발 강좌를 써오면서 저도 몇 번 새롭게 개발환경을 구축 할 필요가 있었습니다. 그런데 제일 중요한 초기 geth 설치 및 geth 실행에 대한 부분을 안

opentutorials.org

opentutorials.org/course/2869/19273

 

이더리움 스마트 컨트랙트 동작방식의 이해 - 이타인클럽

이전에 올린 참고 서적(블록체인 애플리케이션 개발 실전 입문)을 보면서 이더리움의 핵심 개념이 스마트 컨트랙트의 개념 및 동작방식이 종결되었습니다! 최근에 @feyee95님도 스마트 컨트랙의

opentutorials.org

github.com/ethereum/remix-project

 

ethereum/remix-project

Contribute to ethereum/remix-project development by creating an account on GitHub.

github.com

opentutorials.org/course/2869/18360

 

Ethereum Virtual Machine (EVM) 개요 - 이타인클럽

이타인클럽입니다. 스마트 컨트랙트 개발 포스팅 네번째입니다. 이전글 - Smart Contract 개발 #3 Mist Browser를 이용한 컨트랙트 Deploy 이번에는 이더리움의 핵심인 이더리움 가상 머신 (EVM, Ethereum Vritu

opentutorials.org

https://remix.ethereum.org

 

Remix - Ethereum IDE

 

remix.ethereum.org