기타

Go-ethereum(geth) 투표 예제 (Windows)

돌맹96 2023. 12. 11. 23:06
728x90
반응형

1. 공식사이트에서 Geth를 다운로드 받는다.

https://geth.ethereum.org/downloads

2. Geth를 설치한다.

3. 사설 네트워크(private network) 생성 

geth --dev --datadir "C:\geth\data" --networkid 1593 --http --http.addr "0.0.0.0" --http.port 8545 --http.corsdomain "*" --http.api "admin,eth,net,web3,miner,personal" --allow-insecure-unlock --nodiscover console

 

4. 투표 스마트계약 작성 다음과 같이 Voting 프로그램을 작성한다. (파일 이름은 "Voting.sol")

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract Voting {
 string[] public candidateList;
 mapping (string => uint8) public votesReceived;
 constructor(string[] memory candidates) {
 candidateList = candidates;
 }
 function voteForCandidate(string memory candidate) public {
 require(validCandidate(candidate));
 votesReceived[candidate] += 1;
 }
 function totalVotesFor(string memory candidate) view public returns(uint8) {
 require(validCandidate(candidate));
 return votesReceived[candidate];
 }
 function validCandidate(string memory candidate) view public returns (bool) {
 for(uint i=0; i < candidateList.length; i++) {
 if (keccak256(abi.encodePacked(candidateList[i])) ==
 keccak256(abi.encodePacked(candidate))) {
 return true;
 }
 }
 return false;
 }
}

5. 다음의 사이트에 접속한다. https://remix.ethereum.org/

 

Remix - Ethereum IDE

 

remix.ethereum.org

 

6. 화면에 보이는 "Open File"을 클릭한다. Voting.sol을 선택하고, "열기"를 클릭한다.

7. 왼편 목록에 "Voting.sol"이 나타난다.

8. 왼편의 "Compile" 아이콘을 선택한 후, "Compile Voting.sol"을 클릭한다.

9. 왼편의 "Deploy" 아이콘을 선택한 후, geth와 연결한다.

10. "OK"를 클릭한다.

11. "Deploy" 버튼 옆의 을 클릭한다.

12. 나타나는 창에 다음의 내용을 입력한다. [ "Kim", "Lee", "John", "Smith" ]

13. "transact" 버튼을 클릭한다. 다음과 같이 나타나면, 스마트 컨트랙트가 블록체인에 올라 간 상태이다.

14. 다음의 화면을 참고하여 "voteForCandidate" 기능을 실행한다. 후보자의 이름에 "Lee"를 입력한 후에, "transact" 버튼을 클릭한다.

15. 다음의 화면을 참고하여 "totalVotesFor" 기능을 실행한다. 후보자의 이름에 "Lee"를 입력한 후에, "call" 버튼을 클릭한다. "1"이 나타나는지를 확인한다.

16. 한번 더 "voteForCandidate" 기능을 실행한다. 후보자의 이름에 "Lee"를 입력한 후에, "transact" 버튼을 클릭한다.

17. "totalVotesFor" 기능으로 "Lee"에 투표한 수를 확인한다. 후보자의 이름에 "Lee"를 입력한 후에, "call" 버튼을 클릭한다. "2"가 나타나는지를 확인한다.

728x90
반응형