Creating an Ethereum Private Chain and Deploying/Smart Contract Interaction

·

Step-by-Step Guide to Setting Up a Local Private Blockchain

Blockchain technology fundamentally consists of linked blocks forming a chain-like structure. To create a private Ethereum chain, we start by generating the genesis block (the first block in the chain). Below is the genesis.json configuration:

{
  "nonce": "0x0000000000000042",
  "difficulty": "0x020000",
  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "timestamp": "0x00",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
  "gasLimit": "0x4c4b40",
  "alloc": {}
}

Key Parameters Explained:

Initializing the Genesis Block

Run the following command to initialize:

geth --identity "PrivateChain" --datadir ./data init genesis.json

Starting the Private Chain

Use this script (startup.sh):

geth --identity "PrivateChain" --datadir data --networkid 123456 --rpc --rpcaddr="0.0.0.0" --rpccorsdomain "*" --port "30303" --rpcapi "db,eth,net,web3" --nodiscover console

Essential Commands


Deploying a Smart Contract

Sample Token Contract (Solidity)

pragma solidity ^0.4.2;
contract Token {
  address issuer;
  mapping (address => uint) balances;
  event Issue(address account, uint amount);
  event Transfer(address from, address to, uint amount);
  
  function Token() { issuer = msg.sender; }
  
  function issue(address account, uint amount) {
    if (msg.sender != issuer) throw;
    balances[account] += amount;
  }
  
  function transfer(address to, uint amount) {
    if (balances[msg.sender] < amount) throw;
    balances[msg.sender] -= amount;
    balances[to] += amount;
    Transfer(msg.sender, to, amount);
  }
  
  function getBalance(address account) constant returns (uint) {
    return balances[account];
  }
}

Deployment Steps

  1. Compile using Remix IDE.
  2. Deploy via Geth console:

    var tokenContract = web3.eth.contract([...ABI...]);
    var token = tokenContract.new({from: eth.accounts[0], data: '0x...bytecode...', gas: '4300000'});
  3. Mine to confirm deployment:

    miner.start(1); miner.stop();

Interacting with the Contract

Methods


External API Interaction (JSON-RPC)

Use eth_sendTransaction for transactions and eth_call for queries.

Example: Query Balance

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0xCONTRACT_ADDRESS","data":"0xf8b2cb4f..."},"latest"],"id":1}' http://localhost:8545

👉 Explore more Ethereum tools


FAQ

1. How do I reset my private chain?

Delete the data folder and reinitialize genesis.json.

2. Why is my transaction pending?

Ensure mining is active to process transactions.

3. How can I change the mining account?

Use:

miner.setEtherbase(eth.accounts[1]);

👉 Advanced Ethereum development guide