본문 바로가기

나 어제 배웠다/Solidity

우분투 geth Solidity 사용하기

* 우분투 Solidity
1. Compile install
$ sudo add-apt-repository ppa:ethereum/ethereum

gpg: keyring `/tmp/tmpvlp_x0v1/secring.gpg' created
gpg: keyring `/tmp/tmpvlp_x0v1/pubring.gpg' created
gpg: requesting key 923F6CA9 from hkp server keyserver.ubuntu.com
gpg: /tmp/tmpvlp_x0v1/trustdb.gpg: trustdb created
gpg: key 923F6CA9: public key "Launchpad PPA for Ethereum" imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)
OK

$ sudo apt-get update
$ sudo apte-get install solc
패키지 목록을 읽는 중입니다... 완료
의존성 트리를 만드는 중입니다
상태 정보를 읽는 중입니다... 완료
The following additional packages will be installed:
  libz3-dev
다음 새 패키지를 설치할 것입니다:
  libz3-dev solc
0개 업그레이드, 2개 새로 설치, 0개 제거 및 3개 업그레이드 안 함.
7,711 k바이트 아카이브를 받아야 합니다.
이 작업 후 33.1 M바이트의 디스크 공간을 더 사용하게 됩니다.
계속 하시겠습니까? [Y/n] y


2. 경로 설정
2.1 경로 확인
$ which solc
/usr/bin/solc

2.2 geth 경로 설정
 JSON-RPC
$ nohup geth --networkid 4649 --nodiscover --maxpeers 0 --datadir /home/owthit/test_data_geth  --mine --minerthreads 1 --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --rpccorsdomain "*" --rpcapi "admin,db,eth,degub,miner,netshh,txpool,personal,web3" 2 >> /home/owthit/test_data_geth/geth_rpc.log &
$ geth attach rpc:http://localhost:8545
> admin.setSolc("/usr/bin/solc")
"solc, the solidity compiler commandline interface\nVersion: 0.4.19+commit.c4cbbb05.Linux.g++\n"
> eth.getCompilers()
["Solidity"]


3. Compile
스크립트 작성
$ mkdir test_data_solc
$ cd test_data_solc
$ vi HelloWorldOrg.sol
$ cat HelloWorldOrg.sol | tr -d '\n' > HelloWorld.sol
$ cat HelloWorld.sol
pragma solidity ^0.4.8; // 버전 프라그마 반드시 작성// 계약 선언contract HelloWorld {  // 상태 변수  string public greeting;    // 생성자  function HelloWorld(string _greeting){    greeting = _greeting;  }  // 메서드 선언  function setGreeting(string _greeting){    greeting = _greeting;  }    function say() constant returns(string){    return greeting;  }  }

3.1 컴파일(주석은 반드시 제거 후 작성)
$ geth attach rpc:http://localhost:8545
> source='pragma solidity ^0.4.8; contract HelloWorld {  string public greeting;    function HelloWorld(string _greeting){    greeting = _greeting;  } function setGreeting(string _greeting){    greeting = _greeting;  }    function say() constant returns(string){    return greeting;  }  }'
> sourceCompiled=eth.compile.solidity(source)
{
  /tmp/geth-compile-solidity025162961:HelloWorld: {
    code: "0x606
:
:
 info: {
      abiDefinition: [{...}, {...}, {...}, {...}],
      compilerOptions: "--combined-json bin,abi,userdoc,devdoc --add-std --optimize",
      compilerVersion: "0.4.19",
      developerDoc: {
        methods: {}
      },
      language: "Solidity",
      languageVersion: "0.4.19",
      source: "pragma solidity ^0.4.8; contract HelloWorld {  string public greeting;    function HelloWorld(string _greeting){    greeting = _greeting;  } function setGreeting(string _greeting){    greeting = _greeting;  }    function say() constant returns(string){    return greeting;  }  }",
      userDoc: {
        methods: {}
      }
    }
  }
}


4. 계약 배포
4.1 ABI(Application Binary Interface) 취득
> contractAbiDefinition=sourceCompiled['/tmp/geth-compile-solidity025162961:HelloWorld'].info.abiDefinition
[{
    constant: true,
    inputs: [],
    name: "say",
    outputs: [{
        name: "",
        type: "string"
    }],
    payable: false,
    stateMutability: "view",
    type: "function"
}, {
    constant: false,
    inputs: [{
        name: "_greeting",
        type: "string"
    }],
    name: "setGreeting",
    outputs: [],
    payable: false,
    stateMutability: "nonpayable",
    type: "function"
}, {
    constant: true,
    inputs: [],
    name: "greeting",
    outputs: [{
        name: "",
        type: "string"
    }],
    payable: false,
    stateMutability: "view",
    type: "function"
}, {
    inputs: [{
        name: "_greeting",
        type: "string"
    }],
    payable: false,
    stateMutability: "nonpayable",
    type: "constructor"
}]


4.2 ABI 계약 객체 생성
> sourceCompiledContract=eth.contract(contractAbiDefinition)
{
  abi: [{
      constant: true,
      inputs: [],
      name: "say",
      outputs: [{...}],
      payable: false,
      stateMutability: "view",
      type: "function"
  }, {
      constant: false,
      inputs: [{...}],
      name: "setGreeting",
      outputs: [],
      payable: false,
      stateMutability: "nonpayable",
      type: "function"
  }, {
      constant: true,
      inputs: [],
      name: "greeting",
      outputs: [{...}],
      payable: false,
      stateMutability: "view",
      type: "function"
  }, {
      inputs: [{...}],
      payable: false,
      stateMutability: "nonpayable",
      type: "constructor"
  }],
  eth: {
    accounts: ["0x4f748372302fb177ea2036c13d064225f63021eb", "0xdfb6aa5643759ec1a1b3f31a1a78689645e2fa91", "0xd1d15cdfce6db3da12970d3c67216f14d1cd61bf", "0xc71d79251ad51ba6bd094521eae632957035fabd"],
    blockNumber: 1539,
    coinbase: "0x4f748372302fb177ea2036c13d064225f63021eb",
    compile: {
      lll: function(),
      serpent: function(),
      solidity: function()
    },
    defaultAccount: undefined,
    defaultBlock: "latest",
    gasPrice: 20000000000,
    hashrate: 211998,
    mining: true,
    pendingTransactions: [],
    syncing: false,
    call: function(),
    contract: function(abi),
    estimateGas: function(),
    filter: function(fil, callback),
    getAccounts: function(callback),
    getBalance: function(),
    getBlock: function(),
    getBlockNumber: function(callback),
    getBlockTransactionCount: function(),
    getBlockUncleCount: function(),
    getCode: function(),
    getCoinbase: function(callback),
    getCompilers: function(),
    getGasPrice: function(callback),
    getHashrate: function(callback),
    getMining: function(callback),
    getNatSpec: function(),
    getPendingTransactions: function(callback),
    getRawTransaction: function(),
    getRawTransactionFromBlock: function(),
    getStorageAt: function(),
    getSyncing: function(callback),
    getTransaction: function(),
    getTransactionCount: function(),
    getTransactionFromBlock: function(),
    getTransactionReceipt: function(),
    getUncle: function(),
    getWork: function(),
    iban: function(iban),
    icapNamereg: function(),
    isSyncing: function(callback),
    namereg: function(),
    resend: function(),
    sendIBANTransaction: function(),
    sendRawTransaction: function(),
    sendTransaction: function(),
    sign: function(),
    signTransaction: function(),
    submitTransaction: function(),
    submitWork: function()
  },
  at: function(address, callback),
  getData: function(),
  new: function()
}

4.3 이더리움 블록체인 배포
전달생성자 함께 전달(잠금 해제 후 진행 > personal.unlockAccount(eth.accounts[0],"bompapa"))
> _greeting="Hello, World!"
"Hello, World!"
> contract=sourceCompiledContract.new(_greeting, {from:eth.accounts[0], data:sourceCompiled['/tmp/geth-compile-solidity025162961:HelloWorld'].code, gas:'4700000'})
> contract
address:undefined => address:"0x18aa6bfa26f71bb34612f4122eec8d20903957e4" 변경 됨 이것이 계약 주소가 됨

4.4 계약 실행(동작)
메서드 실행 방법 : sendTransaction , call
> contract.say.call()
"Hello, World!"
> contract.greeting.call()
"Hello, World!"
상태변수 변경(잠금 해제 후 진행 > personal.unlockAccount(eth.accounts[0],"bompapa"))
> contract.setGreeting.sendTransaction("Hello, Ethereum!",{from:eth.accounts[0], gas:1000000})
"0xe256f23fb36b9b6bff33aa9c59d419c8b3a92b930aacb5e59faddece5e1994c1"
> contract.say.call()
"Hello, Ethereum!"
> contract.greeting.call()
"Hello, Ethereum!"

4.5 기존 계약 접근
$ geth attach rpc:http://localhost:8545
> source='pragma solidity ^0.4.8; contract HelloWorld {  string public greeting;    function HelloWorld(string _greeting){    greeting = _greeting;  } function setGreeting(string _greeting){    greeting = _greeting;  }    function say() constant returns(string){    return greeting;  }  }'
> sourceCompiled=eth.compile.solidity(source)
{
  /tmp/geth-compile-solidity079026684:HelloWorld: {
    code: "0x606
> contractAbiDefinition=sourceCompiled['/tmp/geth-compile-solidity079026684:HelloWorld'].info.abiDefinition
> contract=eth.contract(contractAbiDefinition).at("0x18aa6bfa26f71bb34612f4122eec8d20903957e4")

'나 어제 배웠다 > Solidity' 카테고리의 다른 글

로컬에서 Solidity 설치 하기  (0) 2018.01.31
우분투 geth 설치 Ethereum 사용하기  (0) 2018.01.31