Geth - 기본 명령어

CHOYEAH·2023년 11월 25일
0

Go ethreume

목록 보기
2/11

0 datadir - 사용자 정의 데이터 저장위치

 ./geth --datadir "/path/to/custom/data/folder"

--datadir 옵션은 Ethereum의 Geth 클라이언트에서 사용되며, Geth가 데이터를 저장할 디렉토리의 위치를 지정하는 데 사용된다. 이 디렉토리에는 블록체인 데이터, 키, 설정 파일 등 Geth 노드 운영에 필요한 모든 정보가 저장된다.

  1. 블록체인 데이터 저장: Ethereum 블록체인의 모든 블록과 트랜잭션 데이터가 이 디렉토리에 저장
  2. 계정 정보 저장: 사용자의 개인 키와 관련 계정 정보가 저장되는 위치
  3. 노드 설정: Geth 노드의 구성 파일과 네트워크 관련 정보 등이 저장

이 옵션을 통해 사용자는 데이터를 원하는 위치에 저장하거나, 다른 드라이브 또는 외부 저장소에 데이터를 보관할 수 있다.

  • 보안: 개인 키와 같은 중요한 정보가 포함되어 있으므로, 해당 디렉토리의 보안에 주의를 기울여야 한다
  • 저장 공간: --datadir로 지정된 디렉토리에는 많은 양의 데이터가 저장될 수 있으므로, 충분한 공간을 갖춘 저장소를 선택하는 것이 좋다.

1 account - 계정 관련

1-1 account new - 계정 생성


./geth account new
INFO [11-25|02:12:05.159] Maximum peer count                       ETH=50 LES=0 total=50
Your new account is locked with a password. Please give a password. Do not forget this password.
Password:
Repeat password:

Your new key was generated

Public address of the key:   0x14f981E1BFEbc42C4De6d035Cf60C4532077E6c0
Path of the secret key file: /Users/choyeah/Library/Ethereum/keystore/UTC--2023-11-24T17-12-17.982933000Z--14f981e1bfebc42c4de6d035cf60c4532077e6c0

- You can share your public address with anyone. Others need it to interact with you.
- You must NEVER share the secret key with anyone! The key controls access to your funds!
- You must BACKUP your key file! Without the key, it's impossible to access account funds!
- You must REMEMBER your password! Without the password, it's impossible to decrypt the key!
./geth --datadir ./data account new
INFO [11-25|02:13:50.791] Maximum peer count                       ETH=50 LES=0 total=50
Your new account is locked with a password. Please give a password. Do not forget this password.
Password:
Repeat password:

Your new key was generated

Public address of the key:   0x6730aE899D1b135f13544543c88F354b5D79A715
Path of the secret key file: data/keystore/UTC--2023-11-24T17-13-56.296462000Z--6730ae899d1b135f13544543c88f354b5d79a715

- You can share your public address with anyone. Others need it to interact with you.
- You must NEVER share the secret key with anyone! The key controls access to your funds!
- You must BACKUP your key file! Without the key, it's impossible to access account funds!
- You must REMEMBER your password! Without the password, it's impossible to decrypt the key!

1-2 account update {index} - 계정 비밀번호 변경

./geth --datadir ./data account update 0
INFO [11-25|02:17:29.265] Maximum peer count                       ETH=50 LES=0 total=50
INFO [11-25|02:17:29.267] Set global gas cap                       cap=50,000,000
WARN [11-25|02:17:29.267] -------------------------------------------------------------------
WARN [11-25|02:17:29.267] Referring to accounts by order in the keystore folder is dangerous!
WARN [11-25|02:17:29.267] This functionality is deprecated and will be removed in the future!
WARN [11-25|02:17:29.267] Please use explicit addresses! (can search via `geth account list`)
WARN [11-25|02:17:29.267] -------------------------------------------------------------------
Unlocking account 0 | Attempt 1/3
Password:
INFO [11-25|02:17:31.672] Unlocked account                         address=0x6730aE899D1b135f13544543c88F354b5D79A715
Please give a new password. Do not forget this password.
Password:
Repeat password:

1-3 accout list - 계정 리스트

 ./geth --datadir ./data account list
INFO [11-25|02:20:59.008] Maximum peer count                       ETH=50 LES=0 total=50
INFO [11-25|02:20:59.012] Set global gas cap                       cap=50,000,000
Account #0: {6730ae899d1b135f13544543c88f354b5d79a715} keystore:///Users/choyeah/Study/blockchain/geth-1.10.26/data/keystore/UTC--2023-11-24T17-13-56.296462000Z--6730ae899d1b135f13544543c88f354b5d79a715
Account #1: {c51efd9613dac64386a8f6d26dd1b7c95effe74f} keystore:///Users/choyeah/Study/blockchain/geth-1.10.26/data/keystore/UTC--2023-11-24T17-20-41.833385000Z--c51efd9613dac64386a8f6d26dd1b7c95effe74f

2 attach

콘솔을 따로 띄워서 콘솔 사용이 용이함

 ./geth attach http://127.0.0.1:8545
Welcome to the Geth JavaScript console!

instance: Geth/v1.10.26-stable-e5eb32ac/darwin-amd64/go1.18.5
coinbase: 0x6730ae899d1b135f13544543c88f354b5d79a715
at block: 0 (Thu Jan 01 1970 09:00:00 GMT+0900 (WIT))
 datadir: /Users/choyeah/Study/blockchain/geth-1.10.26/data
 modules: admin:1.0 eth:1.0 personal:1.0 rpc:1.0 web3:1.0
 
 To exit, press ctrl-d or type exit
>

3 config

게스 실행 시 미리 설정해둔 설정 파일을 사용할 수 있음

./geth --config ./geth-config.toml

4 syncmode - 네트워크 참여 방식 지정

4-1 Full Sync Mode:

./geth --syncmode "full"
  • 데이터: 풀 모드에서는 블록체인의 모든 블록과 트랜잭션을 다운로드하고, 각 블록에 대한 상태를 계산하여 검증
  • 저장 공간: 상당한 양의 저장 공간 필요.
  • 시간: 동기화 시간이 가장 길며, 전체 Ethereum 블록체인을 처음부터 끝까지 검증하고 동기화해야 하기 때문에 초기 동기화에 상당한 시간이 소요
  • 용도: 높은 수준의 보안과 데이터 완전성이 필요한 경우, 예를 들어, 노드를 이용한 마이닝이나 개발 작업에 적합

4-2 Snap Sync Mode:

./geth --syncmode "snap"
  • 데이터: 블록체인의 전체 히스토리를 다운로드하지 않고, 체크 포인트로 지정된 블록부터 최근 128블록 까지의 스냅샷만 가져옴. 트랜잭션을 재실행해서 검증하지 않음.
  • 저장 공간: 풀 모드보다 적은 저장 공간 필요
  • 시간: 풀 모드보다 빠른 동기화를 제공하며, 사용자가 더 빨리 최신 상태에 도달할 수 있음
  • 용도: 빠른 동기화가 필요하고, 전체 블록체인 히스토리에 대한 접근이 필요하지 않은 사용자에게 적합

4-3 Light Sync Mode:

./geth --syncmode "light"
  • 데이터: 블록체인의 헤더만 다운로드하고, 필요한 특정 데이터는 네트워크의 다른 노드에 요청
  • 저장 공간: 매우 적은 저장 공간을 필요로함
  • 시간: 매우 빠른 동기화 시간을 제공
  • 용도: 제한된 리소스를 가진 장치나 빠른 설정이 필요한 사용자에게 적합. 경량 클라이언트나 모바일 디바이스에서 주로 사용.

2.0 부터 지원하지 않음

4-4 Archive 모드

./geth --gcmode "archive"
  • 데이터: Ethereum 블록체인의 모든 데이터를 완전히 저장하고, 모든 상태 변화를 영구적으로 보존하는 동기화 방식으로 이는 각 블록에서 일어난 모든 계정의 상태 변화를 추적할 수 있음을 의미합니다.
  • 저장 공간: 대략 12테라바이트 저장공간 필요. 모든 상태를 영구적으로 저장하기 때문에, 저장 공간 요구사항은 지속적으로 증가
  • 시간: 전체 블록체인 데이터와 상태를 저장하고 검증해야 하기 때문에, 초기 동기화에는 상당한 시간이 소요
  • 용도: 체인 익스플로러와 같이 모든 상태를 저장해야하는 경우 사용, 개발자나 연구자, 감사 기관 등이 과거의 모든 상태를 정밀하게 분석할 필요가 있을 때 유용, 일반적인 사용 사례에는 불필요하게 무겁고, 대부분의 사용자나 개발자에게는 풀 노드나 스냅 모드가 더 적합

5 Network

./geth --mainnet
./geth --goerli
./geth --sepolia

디폴트값은 메인넷

6 Unlock

  • 게스를 실행 시 특정 이더리움 계정의 잠금을 해제하는 데 사용
  • 잠긴 계정은 트랜잭션을 서명하거나 이더리움 네트워크에 데이터를 전송할 수 없음
  • 잠금 상태는 비밀번호나 개인 키가 노출되지 않도록 보호하여 보안을 강화
  • 트랜잭션을 보내거나 계정을 사용하기 위해서는 사용자가 수동으로 계정의 잠금을 해제해야함
  • JS 콘솔에서 personal.unlockAccount("0x123...", "계정의 비밀번호", 300(duration))와 같은 식으로도 사용 가능함
  • 필요한 경우에만 잠금을 해제하고, 사용이 끝난 후에는 다시 잠금 상태로 돌려두는 것이 좋음
./geth --unlock 0

# 패스워드를 파일로 사용 할 수 있음, 추천되지 않음, 곧 없어짐
./geth --unlock 0 --password ./password 

# 보안에 대한 경고를 무시하고 잠금 해제를 허용하는 옵션으로, 일반적으로 보안이 강화된 환경이 아닌 경우, 예를 들어 개발 또는 테스트 환경에서 사용
./geth --allow-insecure-unlock

7 통신 (http, ws)

./geth --http
./geth --ws

http, ws 옵션 모두 Geth 노드에 HTTP 기반의 JSON-RPC 서버를 활성화, 이를 통해 애플리케이션이 Geth 노드에 연결하고 Ethereum 네트워크와 상호 작용할 수 있음.

ws 옵션은 WebSocket 프로토콜을 사용하여 Geth 노드에 대한 실시간, 양방향 통신 채널을 제공하여 주로 실시간 업데이트가 필요한 애플리케이션에 적합(예: 실시간 트랜잭션 모니터링).

HTTP는 상태가 없는 요청-응답 패턴에 더 적합.

두 옵션은 설정할 수 있는 옵션들이 유사하나 일부 다른 옵션이 있음.

7-1 api

./geth --http.api "admin, debug, web3, eth, 
txpool, personal, ethash, miner, net"
./geth --ws.api "admin, debug, web3, eth, 
txpool, personal, ethash, miner, net"

api 옵션은 HTTP 인터페이스를 통해 사용할 수 있는 API 모듈을 지정가능.

  • admin: 노드 관리와 관련된 기능을 제공
  • debug: 디버깅 정보와 도구에 대한 접근을 제공
  • web3: Ethereum 블록체인과 상호 작용하는 데 사용되는 JavaScript API
  • eth: Ethereum 블록체인과 상호 작용하는 데 사용되는 표준 Ethereum JSON-RPC API
  • txpool: 트랜잭션 풀과 관련된 정보를 제공
  • personal: 개인 키 관리와 관련된 기능을 제공
  • ethash: Ethash 채굴 알고리즘과 관련된 정보를 제공
  • miner: 채굴과 관련된 기능을 제공
  • net: 네트워크 상태와 관련된 정보를 제공

7-2 crossdomain

./geth --http.corsdomain "*"

http.corsdomain 옵션은 HTTP 서버에 대한 Cross-Origin Resource Sharing (CORS) 접근을 설정, "*"는 보안상 위험할 수 있으므로 신중하게 사용.

ws는 없는 옵션

7-3 addr

./geth --http.addr "0.0.0.0"
./geth --ws.addr "0.0.0.0"

HTTP, ws 서비스가 바인딩될 IP 주소를 설정, "0.0.0.0"은 모든 주소에서 서버에 접근할 수 있도록 설정함. 이것은 네트워크 상의 모든 장치에서 현재 노드에 접근할 수 있게함.

7-4 port

./geth --http.port "8545"
./geth --ws.port "8546"

HTTP, ws 서비스를 위한 포트 번호를 설정. 8545, 8546은 Ethereum JSON-RPC 서버의 표준 포트임

7-5 http 옵션 조합으로 geth 실행

./geth --datadir ./data --http --http.api "admin, debug, web3, eth, txpool, personal, ethash, miner, net" --http.addr "0.0.0.0" --http.corsdomain "*" console

8 백업 & 복구

백업 및 복구 테스트를 위한 마이닝

> eth.blockNumber
0
> eth.blockNumber
0


> miner.start(1)
null


> eth.blockNumber
6
> eth.blockNumber
8
> eth.blockNumber
10


> miner.stop()
null


> eth.blockNumber
47
> eth.blockNumber
47
> eth.blockNumber
47

miner.start()를 하지 않으면 채굴이 되지 않음

8-1 export - 백업

 ./geth --datadir ./data export ./backup 0 47
 
INFO [11-25|20:45:22.159] Maximum peer count                       ETH=50 LES=0 total=50
INFO [11-25|20:45:22.162] Set global gas cap                       cap=50,000,000
INFO [11-25|20:45:22.163] Allocated cache and file handles         database=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata cache=512.00MiB handles=5120
INFO [11-25|20:45:22.309] Opened ancient database                  database=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata/ancient/chain readonly=false
INFO [11-25|20:45:22.310] Disk storage enabled for ethash caches   dir=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/ethash count=3
INFO [11-25|20:45:22.310] Disk storage enabled for ethash DAGs     dir=/Users/choyeah/Library/Ethash count=2
INFO [11-25|20:45:22.310] Loaded most recent local header          number=47 hash=f8deaf..5bd13a td=6,226,716 age=2m58s
INFO [11-25|20:45:22.310] Loaded most recent local full block      number=47 hash=f8deaf..5bd13a td=6,226,716 age=2m58s
INFO [11-25|20:45:22.310] Loaded most recent local fast block      number=47 hash=f8deaf..5bd13a td=6,226,716 age=2m58s
INFO [11-25|20:45:22.312] Exporting blockchain                     file=./backup
INFO [11-25|20:45:22.313] Exporting batch of blocks                count=48
INFO [11-25|20:45:22.314] Exported blockchain to                   file=./backup
Export done in 1.561084ms

export 명령어로 0~47 블록까지 백업

8-2 removedb

geth를 멈추고 removedb 명령어를 사용하여 데이터 초기화

./geth --datadir ./data removedb

INFO [11-25|20:48:38.038] Maximum peer count                       ETH=50 LES=0 total=50
INFO [11-25|20:48:38.042] Set global gas cap                       cap=50,000,000
Remove full node state database (/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata)? [y/n] y
INFO [11-25|20:48:40.233] Database successfully deleted            path=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata elapsed=2.817ms
Remove full node ancient database (/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata/ancient)? [y/n] y
INFO [11-25|20:48:42.538] Database successfully deleted            path=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata/ancient elapsed=2.707ms
Remove light node database (/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/lightchaindata)? [y/n] y
INFO [11-25|20:48:44.974] Database successfully deleted            path=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/lightchaindata elapsed=3.759ms

게스를 재실행 후 블록 넘버를 확인하면 0인것을 확인 가능

> eth.blockNumber
0
> eth.blockNumber
0
> eth.blockNumber
0
> eth.blockNumber
0

8-3 완전한 삭제

완전한 삭제를 하려면 사용자가 지정한 데이터 디렉터리 안에있는 geth 디렉터리를 삭제

rm -rf ./data/geth

이후 제네시스 블록을 다시 생성

./geth --datadir ./data init ./genesis.json

INFO [11-25|20:56:31.608] Maximum peer count                       ETH=50 LES=0 total=50
INFO [11-25|20:56:31.613] Set global gas cap                       cap=50,000,000
INFO [11-25|20:56:31.613] Allocated cache and file handles         database=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata cache=16.00MiB handles=16
INFO [11-25|20:56:31.928] Opened ancient database                  database=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata/ancient/chain readonly=false
INFO [11-25|20:56:31.929] Writing custom genesis block
INFO [11-25|20:56:31.931] Persisted trie from memory database      nodes=3 size=397.00B time="584.167µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [11-25|20:56:31.933] Successfully wrote genesis state         database=chaindata hash=c3638c..f97051
INFO [11-25|20:56:31.933] Allocated cache and file handles         database=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/lightchaindata cache=16.00MiB handles=16
INFO [11-25|20:56:32.214] Opened ancient database                  database=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/lightchaindata/ancient/chain readonly=false
INFO [11-25|20:56:32.214] Writing custom genesis block
INFO [11-25|20:56:32.218] Persisted trie from memory database      nodes=3 size=397.00B time="443.834µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [11-25|20:56:32.219] Successfully wrote genesis state         database=lightchaindata hash=c3638c..f97051

재실행 후 블록 정보 확인


./geth --datadir ./data --http --http.api "admin, debug, web3, eth, txpool, personal, ethash, miner, net" --http.addr "0.0.0.0" --http.corsdomain "*" console

INFO [11-25|21:00:11.595] Starting Geth on Ethereum mainnet...
INFO [11-25|21:00:11.595] Bumping default cache on mainnet         provided=1024 updated=4096
INFO [11-25|21:00:11.597] Maximum peer count                       ETH=50 LES=0 total=50
INFO [11-25|21:00:11.603] Set global gas cap                       cap=50,000,000
INFO [11-25|21:00:11.604] Allocated trie memory caches             clean=614.00MiB dirty=1024.00MiB
.
.
.
> eth.blockNumber
0
> eth.blockNumber
0
> eth.blockNumber
0

8-4 import - 데이터 복구

실행중인 geth를 정지 후 이전에 저장한 backup 파일을 import 명령어로 복구

 ./geth --datadir ./data import ./backup
 
INFO [11-25|21:03:06.756] Maximum peer count                       ETH=50 LES=0 total=50
INFO [11-25|21:03:06.761] Set global gas cap                       cap=50,000,000
INFO [11-25|21:03:06.762] Allocated cache and file handles         database=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata cache=512.00MiB handles=5120
INFO [11-25|21:03:07.168] Opened ancient database                  database=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/chaindata/ancient/chain readonly=false
INFO [11-25|21:03:07.172] Disk storage enabled for ethash caches   dir=/Users/choyeah/Study/blockchain/geth-1.10.26/data/geth/ethash count=3
INFO [11-25|21:03:07.172] Disk storage enabled for ethash DAGs     dir=/Users/choyeah/Library/Ethash count=2
INFO [11-25|21:03:07.173] Loaded most recent local header          number=0 hash=c3638c..f97051 td=1 age=54y8mo6d
INFO [11-25|21:03:07.173] Loaded most recent local full block      number=0 hash=c3638c..f97051 td=1 age=54y8mo6d
INFO [11-25|21:03:07.173] Loaded most recent local fast block      number=0 hash=c3638c..f97051 td=1 age=54y8mo6d
INFO [11-25|21:03:07.174] Importing blockchain                     file=./backup
INFO [11-25|21:03:07.632] Imported new chain segment               blocks=47 txs=0 mgas=0.000 elapsed=457.519ms mgasps=0.000 number=47 hash=f8deaf..5bd13a age=20m43s   dirty=22.30KiB
INFO [11-25|21:03:07.633] Writing cached state to disk             block=47 hash=f8deaf..5bd13a root=60df70..066a11
INFO [11-25|21:03:07.633] Persisted trie from memory database      nodes=2 size=294.00B time="20.917µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=93 livesize=13.20KiB
INFO [11-25|21:03:07.633] Writing cached state to disk             block=46 hash=1b72a9..389f39 root=ee6cc1..ce66c0
INFO [11-25|21:03:07.633] Persisted trie from memory database      nodes=2 size=294.00B time="10µs"     gcnodes=0 gcsize=0.00B gctime=0s livenodes=91 livesize=12.91KiB
INFO [11-25|21:03:07.633] Writing snapshot state to disk           root=2cffac..e32dfc
INFO [11-25|21:03:07.633] Persisted trie from memory database      nodes=0 size=0.00B   time=583ns      gcnodes=0 gcsize=0.00B gctime=0s livenodes=91 livesize=12.91KiB
INFO [11-25|21:03:07.633] Blockchain stopped
Import done in 460.249667ms.

Compactions
 Level |   Tables   |    Size(MB)   |    Time(sec)  |    Read(MB)   |   Write(MB)
-------+------------+---------------+---------------+---------------+---------------
   0   |          3 |       0.00224 |       0.00000 |       0.00000 |       0.00000
-------+------------+---------------+---------------+---------------+---------------
 Total |          3 |       0.00224 |       0.00000 |       0.00000 |       0.00000

Read(MB):0.00299 Write(MB):0.04942
Object memory: 138.727 MB current, 130.784 MB peak
System memory: 280.841 MB current, 280.591 MB peak
Allocations:   0.139 million
GC pause:      559.707µs

Compacting entire database...
Compaction done in 120.107583ms.

Compactions
 Level |   Tables   |    Size(MB)   |    Time(sec)  |    Read(MB)   |   Write(MB)
-------+------------+---------------+---------------+---------------+---------------
   0   |          0 |       0.00000 |       0.05757 |       0.00000 |       0.02192
   1   |          1 |       0.01970 |       0.05806 |       0.02415 |       0.01970
-------+------------+---------------+---------------+---------------+---------------
 Total |          1 |       0.01970 |       0.11562 |       0.02415 |       0.04162

Read(MB):0.02433 Write(MB):0.09128

geth 재실행 후 블록넘버 확인

> eth.blockNumber
47
> eth.blockNumber
47
> eth.blockNumber
47

9 geth 콘솔 api

스페이스 두 번 + 탭 키를 누르면 콘솔에서 사용 가능한 api를 확인가능

>
AggregateError        Int32Array            String                _setInterval          eval                  propertyIsEnumerable
Array                 Int8Array             Symbol                _setTimeout           globalThis            require
ArrayBuffer           JSON                  SyntaxError           admin                 hasOwnProperty        rpc
BigNumber             Map                   TypeError             clearInterval         inspect               setInterval
Boolean               Math                  URIError              clearTimeout          isFinite              setTimeout
DataView              NaN                   Uint16Array           console               isNaN                 toLocaleString
Date                  Number                Uint32Array           constructor           isPrototypeOf         toString
Error                 Object                Uint8Array            debug                 jeth                  txpool
EvalError             Promise               Uint8ClampedArray     decodeURI             loadScript            undefined
Float32Array          Proxy                 WeakMap               decodeURIComponent    message               unescape
Float64Array          RangeError            WeakSet               encodeURI             miner                 valueOf
Function              ReferenceError        Web3                  encodeURIComponent    net                   web3
GoError               Reflect               XMLHttpRequest        escape                parseFloat
Infinity              RegExp                __proto__             eth                   parseInt
Int16Array            Set                   _consoleWeb3Transport ethash                personal
profile
Move fast & break things

0개의 댓글

관련 채용 정보