EOS의 RPC를 살려보자!

in #coinkorea8 years ago



들어가며


안녕하세요.

이번 시간에는 아래 글에서 build와 기본적인 블록 생성을 해보았고,
["EOS를 빌드해보자"]

이것에 이어서 RPC즉, restful API를 외부로 제공하는 것에 대해서 알아보도록 하겠습니다.

생각보다 간단한 부분이지만, 그래도 (저는) 설명을 찾을수 없어서 옵션을 공부하면서 했던거라,
다른 분들의 시간을 단축 시키기 위해서 이 글을 남깁니다.



RPC란?

https://eosio.github.io/eos/group__eosiorpc.html#details 에 나와 있는 것 처럼 HTTP기반의 remote procedure call을 의미합니다. 간단하게 HTTP만을 사용해서 procedure call을 할 수 있습니다.

또한 그 대답은 JSON format으로 return이 되어서 돌아오기 때문에 쉬운 처리 또한 할수 있습니다.

현재는 Chain API와 Wallet API만이 존재하고 있고, 앞으로 steem처럼 추가적인 API들이 더 나올것으로 기대하고 있습니다. 그리고 EOS는 open source이니 우리가 필요한 것을 만들어서 contribution할수도 있습니다.

사실 소스를 좀 더 뒤져보니 아직 문서화 되지 않은 API들이 있는 것 같습니다.(이것도 다음에 확인하는 글을 쓰겠습니다.)

ChainAPI는 bitshare에서도 같은 분류로 제공이 되고 있어, 예전 bitshare사용자라면 아주 쉽게 접근하실수 있을 것입니다.

ChainAPI : node의 정보를 가져오는 것 부터, account정보 block정보를 가져올 수 있습니다.
WalletAPI : 지갑을 생성하고, 지갑을 열고, 지갑의 lock을 해제하는 등의 API set이 있습니다. 사용은 아직 다 해보지 않았지만 일반적으로 chain API와 wallet API가 pair로 움직입니다. 예를 들어 특정 지갑의 transaction을 하기 전에 우선 wallet API로 지갑을 open해주는 절차를 거치게 됩니다.

이 부분은 별도의 dapp을 만들면서 세부 사용의 예를 보이도록 하겠습니다.



RPC를 위한 configuration


nodes가 동작을 하면 RPC가 옵션에 따라서 동작을 합니다. github문서에는 eosd와 eos-walletd라는 이름이 명시되어 있으나 지금은 쓰이지 않는 명칭이라고 생각됩니다.(아마도 예전버전)

nodes를 실행하면 default로 127.0.0.1:8888 port로 binding이 되고, 여기로 들어오는 http request를 처리하게 됩니다.

그런데 우리는 실제 서버에 이를 설정할 것이기 때문에 이를 서버의 IP주소로 바꾸어 주어야 합니다.

./nodeos -e -p eosio --plugin eosio::chain_api_plugin --plugin eosio::history_api_plugin   --http-server-address 204.48.17.76:8888 --plugin eosio::wallet_api_plugin --resync 

이렇게 실행을 해주면 됩니다. 위의 예시에서
"--http-server-address 204.48.17.76:8888 " 이 부분이 서버의 IP에 바인딩을 하는 부분입니다.

이렇게 하면 위의 IP의 8888번 포트로 들어오는 요청을 nodes가 처리하게 됩니다.



실제로 써보자.

curl http://204.48.17.76:8888/v1/chain/get_info

이렇게 하면 node의 정보를 보여 줍니다. 위의 command는 linux shell상에서 혹은 curl이 설치된 윈도우에서 해보시면 됩니다. 결과는..

{"server_version":"cd979827","head_block_num":451,"last_irreversible_block_num":450,"last_irreversible_block_id":"000001c22fbfa8f65923ce8e91d0352ac266b5c5f0c394bf1a97bf53123725c7","head_block_id":"000001c39f54bd8e983584259c4568bf156505de4f448a749415f7c96325d71d","head_block_time":"2018-05-24T05:11:27","head_block_producer":"eosio","virtual_block_cpu_limit":156589,"virtual_block_net_limit":1644587,"block_cpu_limit":99900,"block_net_limit":1048576}

이렇게 출력이 됩니다.

또는 다음과 같이 http로 확인하실수도 있습니다.

위의 IP는 당분간 열려있으니 다른 API도 시험하실수 있고 지갑도 생성하실수 있습니다. 제가 test하는 중간에는 접속이 안될수 있으니, 접속이 안된다면, 몇시간정도 후에 사용해 주세요.

curl http://204.28.17.76:8888/v1/wallet/create -X POST -d '"test"'

이렇게 시험 계정을 만들수도 있고, return값으로 private key가 돌아오게 됩니다.

http://204.48.17.76:8888/v1/wallet/list_wallets

혹은 지금 생성된 wallet의 list를 보여주기도 합니다.

사실 nodeos에는

nodeos --help

로 확인하시면 굉장히 많은 옵션이 있습니다.

Config Options for eosio::chain_plugin:
  --genesis-json arg (="genesis.json")  File to read Genesis State from
  --genesis-timestamp arg               override the initial timestamp in the
                                        Genesis State file
  --block-log-dir arg (="blocks")       the location of the block log (absolute
                                        path or relative to application data
                                        dir)
  -c [ --checkpoint ] arg               Pairs of [BLOCK_NUM,BLOCK_ID] that
                                        should be enforced as checkpoints.
  --wasm-runtime wavm/binaryen          Override default WASM runtime
  --shared-memory-size-mb arg (=1024)   Maximum size MB of database shared
                                        memory file

Command Line Options for eosio::chain_plugin:
  --replay-blockchain                   clear chain database and replay all
                                        blocks
  --resync-blockchain                   clear chain database and block log

Config Options for eosio::history_plugin:
  -f [ --filter_on_accounts ] arg       Track only transactions whose scopes
                                        involve the listed accounts. Default is
                                        to track all transactions.

Config Options for eosio::http_plugin:
  --http-server-address arg (=127.0.0.1:8888)
                                        The local IP and port to listen for
                                        incoming http connections; set blank to
                                        disable.
  --https-server-address arg            The local IP and port to listen for
                                        incoming https connections; leave blank
                                        to disable.
  --https-certificate-chain-file arg    Filename with the certificate chain to
                                        present on https connections. PEM
                                        format. Required for https.
  --https-private-key-file arg          Filename with https private key in PEM
                                        format. Required for https
  --access-control-allow-origin arg     Specify the Access-Control-Allow-Origin
                                        to be returned on each request.
  --access-control-allow-headers arg    Specify the Access-Control-Allow-Header
                                        s to be returned on each request.
  --access-control-allow-credentials    Specify if Access-Control-Allow-Credent
                                        ials: true should be returned on each
                                        request.

Config Options for eosio::net_plugin:
  --p2p-listen-endpoint arg (=0.0.0.0:9876)
                                        The actual host:port used to listen for
                                        incoming p2p connections.
  --p2p-server-address arg              An externally accessible host:port for
                                        identifying this node. Defaults to
                                        p2p-listen-endpoint.
  --p2p-peer-address arg                The public endpoint of a peer node to
                                        connect to. Use multiple
                                        p2p-peer-address options as needed to
                                        compose a network.
  --agent-name arg (="EOS Test Agent")  The name supplied to identify this node
                                        amongst the peers.
  --allowed-connection arg (=any)       Can be 'any' or 'producers' or
                                        'specified' or 'none'. If 'specified',
                                        peer-key must be specified at least
                                        once. If only 'producers', peer-key is
                                        not required. 'producers' and
                                        'specified' may be combined.
  --peer-key arg                        Optional public key of peer allowed to
                                        connect.  May be used multiple times.
  --peer-private-key arg                Tuple of [PublicKey, WIF private key]
                                        (may specify multiple times)
  --max-clients arg (=25)               Maximum number of clients from which
                                        connections are accepted, use 0 for no
                                        limit
  --connection-cleanup-period arg (=30) number of seconds to wait before
                                        cleaning up dead connections
  --network-version-match arg (=0)      True to require exact match of peer
                                        network version.
  --sync-fetch-span arg (=100)          number of blocks to retrieve in a chunk
                                        from any individual peer during
                                        synchronization
  --max-implicit-request arg (=1500)    maximum sizes of transaction or block
                                        messages that are sent without first
                                        sending a notice

Config Options for eosio::producer_plugin:

  -e [ --enable-stale-production ]      Enable block production, even if the
                                        chain is stale.
  --max-transaction-time arg (=30)      Limits the maximum time (in
                                        milliseconds) that is allowed a pushed
                                        transaction's code to execute before
                                        being considered invalid
  --required-participation arg (=33)    Percent of producers (0-100) that must
                                        be participating in order to produce
                                        blocks
  -p [ --producer-name ] arg            ID of producer controlled by this node
                                        (e.g. inita; may specify multiple
                                        times)

                                        Tuple of [public key, WIF private key]
                                        (may specify multiple times)

Config Options for eosio::txn_test_gen_plugin:
  --txn-reference-block-lag arg (=0)    Lag in number of blocks from the head
                                        block when selecting the reference
                                        block for transactions (-1 means Last
                                        Irreversible Block)

Config Options for eosio::wallet_plugin:
  --wallet-dir arg (=".")               The path of the wallet files (absolute
                                        path or relative to application data
                                        dir)
  --unlock-timeout arg (=900)           Timeout for unlocked wallet in seconds
                                        (default 900 (15 minutes)). Wallets
                                        will automatically lock after specified
                                        number of seconds of inactivity.
                                        Activity is defined as any wallet
                                        command e.g. list-wallets.
  --eosio-key arg                       eosio key that will be imported
                                        automatically when a wallet is created.

Application Config Options:
  --plugin arg                          Plugin(s) to enable, may be specified
                                        multiple times

Application Command Line Options:
  -h [ --help ]                         Print this help message and exit.
  -v [ --version ]                      Print version information.
  --print-default-config                Print default configuration template
  -d [ --data-dir ] arg                 Directory containing program runtime
                                        data
  --config-dir arg                      Directory containing configuration
                                        files such as config.ini
  -c [ --config ] arg (=config.ini)     Configuration file name relative to
                                        config-dir
  -l [ --logconf ] arg (=logging.json)  Logging configuration file name/path
                                        for library users

저는 이 중에서 HTTP설정을 바꾸어 준 것 뿐입니다. 왜냐구요? RPC를 위해서죠.

이를 통해서 예상해 보건데, API server는 peer 2 peer로 BP와 연결이 되고, RPC는 이 API server가 제공할것으로 보입니다.

또한 voting API를 통해서 BP들을 투표한 결과가 blockchain이 기록이 되고, 이를 통해서 BP를 선출하고(smart contract기반), 이렇게 BP가 선출이 되면 서로간의 peer key를 통해서 BP들이 서로 연결되는 구조가 아닐까 예측을 해봅니다. 실제 구성한 것은 아니라서 실험이 필요하지만요...

현재 확실한 것은 nodeos의 환경 설정을 통해서 제공하는 API의 set을 바꿀수 있고, 또한 옵션을 통해서 적절한 서버에 binding할수 있다는 것입니다.

그럼 다음 화에서는 multi node와 다른 option들에 대해서 알아보겠습니다.



마치며..


우연한 기회에 steem에서 타로점 프로그램을 짜게 되었고, 이후에 우연한 기회에 bitshare에서 자동 token배포 프로그램을 짜게 되었고, 정말 우연한 기회에 EOS로 넘어왔는데..

정말 우연히도 Dan이 모두 거쳐간, Dan이 만든 platform들입니다. 그들의 유사성으로 인해서 접근성이 매우 높아진것도 우연이라 하겠습니다.

다음의 영화 대사로 이번 글을 마칠까 합니다.

"My momma always said, "Life was like a box of chocolates. You never know what you're gonna get."
(source : forrest gump movie)

Sort:  

@neogia님께서 이 포스팅에 많은 관심을 가지고 있어요. 리스팀을 해주셨군요~!

신규 버전에서는 resync option이 없어졌습니다. 그런데 요상하게 replay도 먹지를 않네요. 이때에는

cd ~/.local/share/eosio/nodeos/
그리고 나서 data directory를 싹 지워주세요.

그럼 잘 실행이 됩니다. resync는 도대체 왜 빠진걸까요..어후.

@tradingideas님께서 이 포스팅에 많은 관심을 가지고 있어요. 리스팀을 해주셨군요~!

@eddieyi님께서 이 포스팅에 많은 관심을 가지고 있어요. 리스팀을 해주셨군요~!

보팅 꾹~! ㅎㅎ

@oalover님께서 이 포스팅에 많은 관심을 가지고 있어요. 리스팀을 해주셨군요~!

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.092
BTC 63142.90
ETH 1787.16
USDT 1.00
SBD 0.39