본문 바로가기
IT/이더리움 Ethereum

이더리움 geth JSON-RPC를 이용한 HTTP 웹으로 사용하기

by SidePower 2022. 9. 21.

 

리눅스에서 go-ethereum 클라이언트 설치 후 계속 Geth 콘솔을 통해

테스트넷 구성과 각종 명령어로 작업을 했었네요.

 

웹에서 geth를 접속해서 각종 명령어 작업을 할수 있다는걸 알게 되어네요.

 

go-ethereum 클라이언트가 설치하면

JSON-RPC 기능도 같이 설치된다고 합니다.

 

RPC란

remote procedure call, 리모트 프로시저 콜

원격의 다른 PC나 서버의 명령어나 기능(함수) 등을

마치 내 PC 로컬에서 실행하는거 처럼 처리해주는 프로세스간의 통신 기술입니다.

 

Geth에 HTTP로 RPC기능을 구현한 HTTP-RPC 서버가 내장되어 있어

geth에 console로 접속하지 않아도 이용할수 있을거 같네요.ㅋ

 

 HTTP-RPC 모드로 geth 기동 명령어

기존의 테스트넷 기동 명령어에서 HTTP-RPC 옵션들이 많이 추가되었고

리눅스 백그라운드로 실행해서 리눅스 서버가 다운되지 않는다면 

항상 채굴할수 있도록 합니다.

nohup geth --networkid 88 --nodiscover --allow-insecure-unlock --maxpeers 0
--datadir /home/tmach/gethmain/testnet_data --mine --miner.threads 1
--http --http.addr "0.0.0.0" --http.port 8545 --http.corsdomain "*"
--http.api "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" 2>>/home/tmach/gethmain/testnet_data/gethErr.log &

 옵션 

항목 설명
mine 채굴 기능 활성화
miner.threads 채굴에 사용되는 CPU 스레드 개수 . 디폴트 1
http HTTP-RPC 서버 활성화
http.addr HTTP-RPC 서버 IP 지정 . 디폴트 "localhost"
"0.0.0.0" 지정하면 제한없이 허용
http.port HTTP-RPC 서버 포트번호
http.corsdomain HTTP-RPC 기능 허용 IP 리스트
"*" 지정하면 제한없이 모든 IP 허용
http.api rpc 허용 명령어 . 디폴트 "eth,net,web3"
allow-insecure-unlock
 계정 잠금 해지 허용
http로 모든 사용자가 계정을 엑세스 할수 있게 되어
보안상 문제가 될수 있음.
테스트할때만 사용하길 권장.

 

 리눅스 백그라운드 

명령어 설명
nohup 리눅스에 접속한 계정이 로그아웃해도
계정으로 실행된 프로세스가 종료되지 않고 kill 될때까지 계속 수행.
& 실행 명령어 끝에 위치하며 백그라운드 모드 수행.
[tmach@localhost gethmain]$ nohup geth --networkid 88 --nodiscover --allow-insecure-unlock --maxpeers 0 --datadir /home/tmach/gethmain/testnet_data --mine --miner.threads 1 --http --http.addr "0.0.0.0" --http.port 8545 --http.corsdomain "*" --http.api "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" 2>>/home/tmach/gethmain/testnet_data/gethErr.log &
[1] 1837
 실행 결과로 나온 1837값은 프로세스ID입니다.

[tmach@localhost gethmain]$
[tmach@localhost gethmain]$ ps -ef|grep geth
tmach     1837  1510 88 23:36 pts/0    00:00:07 geth --networkid 88 --nodiscover --maxpeers 0 --datadir /home/tmach/gethmain/testnet_data --mine --miner.threads 1 --http --http.addr 0.0.0.0 --http.port 8545 --http.corsdomain * --http.api admin,db,eth,debug,miner,net,shh,txpool,personal,web3
[tmach@localhost gethmain]$

 

 HTTP 웹으로 Geth 사용하기

HTTP 호출을 위해 curl 명령어를 사용할게요.

JSON-RPC는 용어 그대로 JSON 형태로 명령어를 전송하고

실행 결과도 JSON 형태로 수신 받습니다.

curl -X POST -H "Content-Type: application/json" HTTP-RPC서버 URL
--data '{"jsonrpc":"2.0","method":"명령어","parms":[명령어 인자값],"id",10)'

▩ -X POST와 "jsonrpc":"2.0"는 생략 가능합니다.

▩ -H "Content-Type: application/json"

JSON 형태로 데이터를 주고받아야 되기때문에 JSON 형식이라고 알려줘야 되요.

 method:명령어는 geth 콘솔에서 사용했던 명령어인데요.

약간 차이가 있어요. ^^;;

블록 개수 확인할때 eth.blockNumber를 eth_blockNumber로 쓰셔야 되요.

이렇게 점을(.) 언더바(_)로 바꿔 입력해주세요.

 parms:명령어 인자값은 

잔고 확인할때 eth.getBalance(계정주소)에서 계정주소가 인자값입니다.

"method":"eth_getBalance","parms":[0x39d....7f9]

인자값이 없으면 대괄호 [] 열고 닫기로 비워두면 되요.

▩ id는 명령어 결과를 응답할때 key처럼 사용되므로

임의 숫자를 암거나 지정하시면 됩니다. 10으로 합니다.

 블록 개수 확인
eth.blockNumber → eth_blockNumber

   
[tmach@localhost test]$ curl -X POST -H "Content-Type: application/json" localhost:8545 --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":10}' 
{"jsonrpc":"2.0","id":10,"result":"0xe"}
[tmach@localhost test]$
 결과(result)가 16진수 0xe로 표현되었습니다.

16진수를 10진수로 변환. bc 명령어 이용
bc는 대문자 기입할수 있습니다. 
[tmach@localhost test]$ echo "ibase=16; E"|bc

14
 16진수 E는 10진수 14입니다.

 계정 목록 확인
eth.accounts → eth_accounts
[tmach@localhost test]$ curl -X POST -H "Content-Type: application/json" localhost:8545 --data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":10}'

{"jsonrpc":"2.0","id":10,"result":["0x39de79a7f186f84f03f3e832a3d80e7bbdd2a7f9","0xc6725761e6d790ef42f0bce2cec9b95577ef9cf8","0xcee6a5b6f45f7a0de0ec246783213a80e9428965"]}
[tmach@localhost test]$
 결과(result)로 계정 주소 3개가 표시되네요.

 계정 잔고 확인
eth.getBalance → eth_getBalance
http-rpc에서는 계정표현은 eth.accounts[0] 형식으로는 안되고
16진수 주소를 입력해야 됩니다.
[tmach@localhost test]$ curl -X POST -H "Content-Type: application/json" localhost:8545 --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x39de79a7f186f84f03f3e832a3d80e7bbdd2a7f9","latest"],"id":10}'
{"jsonrpc":"2.0","id":10,"result":"0x3cb71f51fc5580000"}

16진수를 10진수로 변환. bc 명령어 이용
[tmach@localhost test]$ echo "ibase=16; 3CB71F51FC5580000"|bc
70000000000000000000 . 7ether 네요.


 계정 Lock 해지
[tmach@localhost test]$ curl -X POST -H "Content-Type: application/json" localhost:8545 --data '{"jsonrpc":"2.0","method":"personal_unlockAccount","params":["0x39de79a7f186f84f03f3e832a3d80e7bbdd2a7f9","eth88-1",0],"id":10}'
{"jsonrpc":"2.0","id":10,"result":true}


 송금하기
0x39..f9(eth.accounts[0])에서  0xc6..f8(eth.accounts[1])로 10ether 보내기
[tmach@localhost test]$ curl -X POST -H "Content-Type: application/json" localhost:8545 --data '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x39de79a7f186f84f03f3e832a3d80e7bbdd2a7f9","value":"0x8AC7230489E80000","to":"0xc6725761e6d790ef42f0bce2cec9b95577ef9cf8"}],"id":10}'
{"jsonrpc":"2.0","id":10,"result":"0x4214d2b75c7a512588caa4ec9777280c91d425438ecc506dccfde7cd30008b90"}
 결과(result)로 트랜젝션ID가 표시되네요.

10진수를 16진수로 변환하기 . bc 명령어 이용
[tmach@localhost test]$ echo "obase=16; 10000000000000000000"|bc
8AC7230489E80000
 10진수 10000000000000000000는 16진수 8AC7230489E80000입니다.


 계정 잔고 확인
eth.getBalance → eth_getBalance
0xc6..f8(eth.accounts[1]) 계정의 잔고 확인

[tmach@localhost test]$ curl -X POST -H "Content-Type: application/json" localhost:8545 --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0xc6725761e6d790ef42f0bce2cec9b95577ef9cf8","latest"],"id":10}'
{"jsonrpc":"2.0","id":10,"result":"0x8ac7230489e80000"}

16진수를 10진수로 변환. bc 명령어 이용
[tmach@localhost test]$ echo "ibase=16; 8AC7230489E80000"|bc
10000000000000000000
 16진수 8AC7230489E80000는 10진수 10000000000000000000입니다.
10ether 잘 받았네요.

HTTP-RPC 서버 활성화로

인터넷이 되는 어디에서나 geth 명령어를 날려 컨트롤 할수 있게 됩니다.

 

그리고 HTTP-RPC를 사용하다가 다시 console로 사용하고 싶을때는

attach 명령어로 console 접속할수 있습니다.

 실행중인 Geth에 콘솔로 접속하기

geth attach rpc:접속URL
[tmach@localhost gethmain]$ geth attach rpc:http://localhost:8545
Welcome to the Geth JavaScript console!

instance: Geth/v1.10.14-unstable-85064ed0-20211202/linux-amd64/go1.17.3
coinbase: 0x39de79a7f186f84f03f3e832a3d80e7bbdd2a7f9
at block: 14 (Wed Dec 08 2021 23:37:24 GMT-0500 (EST))
 datadir: /home/tmach/gethmain/testnet_data
 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

To exit, press ctrl-d or type exit
>
> miner.stop()
null
>
> eth.blockNumber
14
>

 

 

geth 테스트넷을 기동할때 옵션으로 모든 계정의 암호를 넘겨주면 

계정이 Geth에 접속할 경우 암호를 묻지 않게 할수 있습니다.

또 송금할때마다 계정 lock를 해제하는 작업을 했었는데요.

이것도 옵션 설정으로 잠금 해제 할 필요가 없게 할수 있어요.

 

솔직히 암호와 lock은 보안상 문제가 될수 있어 이렇게 하면 안되는데요.

사설 테스트넷에서만 테스트용으로 사용할때는 괜찮을거 같아서

귀차니즘 땜에 옵션을 설정하려고요.ㅋ

 

 계정 암호 자동 설정 옵션

설정에 앞서 먼저 준비해야 되는것은 암호 파일입니다.

--password 암호파일
▶ 현재 사설 테스트넷에 3개의 계정이 있는데요.
계정 eth.accounts[0] , 암호 eth88-1
계정 eth.accounts[1] , 암호 eth88-2
계정 eth.accounts[2] , 암호 eth88-3

♣ 암호 파일 생성
파일명을 testNet_pass로 정했어요.
계정 순서대로 한줄에 한개씩 암호를 넣어주세요.
[tmach@localhost testnet_data]$ vi testNet_pass
eth88-1
eth88-2
eth88-3

[tmach@localhost testnet_data]$ ll
total 144
-rw-rw-r--. 1 tmach tmach    515 Dec  8 03:12 genesis.json
drwx------. 6 tmach tmach    126 Dec  9 08:27 geth
-rw-rw-r--. 1 tmach tmach 137247 Dec  9 08:27 gethErr.log
srw-------. 1 tmach tmach      0 Dec  9 07:27 geth.ipc
drwx------. 2 tmach tmach    261 Dec  8 03:22 keystore
-rw-rw-r--. 1 tmach tmach     24 Dec 11 06:14 testNet_pass

--password /home/tmach/gethmain/testnet_data/testNet_pass

 

 계정 잠금 자동 해제하기 옵션

--unlock 계정 인덱스번호...
▶ 현재 사설 테스트넷에 3개의 계정이 있는데요.
계정 eth.accounts[0] 
계정 eth.accounts[1] 
계정 eth.accounts[2] 
순서대로 인덱스 번호가 0 1 2 입니다.

옵션 설정하실때 잠금 해제 할 인덱스번호를 여러개 지정할수 있습니다.

--unlock 0
--unlock 0,1,2
--unlock 1,2

 

추가로 로그레벨도 지정할수가 있는데요.

--verbosity 로그레벨번호
로그레벨번호 의미
0 silent
1 error
2 warn
3 info
4 debug
5 detail

default 기본값은 3 . info 모드입니다.

 

 

감사합니다.

반응형

댓글