以太坊私有链合约部署及访问

547 阅读3分钟

#创建区块链文件目录

mkdir -P /chain  /chain1
cd /chain

初始化配置

#开启一个以太坊节点

geth  --datadir  /chain   --rpc.enabledeprecatedpersonal console

#创建以太坊账户(重复执行可创建多个账号)

personal.newAccount()

命令执行后会生成以下账号 "0x1b292368598c777d339bef873dfb150ae4f93dff"

#创建配置文件

vi genesis.json 
{
        "alloc": {
                "0x1b292368598c777d339bef873dfb150ae4f93dff": {
                        "balance": "999000000000000000000"
                },
                "0x948fadcff967e2e6437d3cdd3670e869c0c3e5ff": {
                        "balance": "999000000000000000000"
                },
                "0x0f17f080c815bae5fb4304aab75825e60d0dd066": {
                        "balance": "999000000000000000000"
                } 
 
        },
        "config": {
                "chainId": 10,
                "homesteadBlock": 0,
                "eip150Block": 0,
                "eip155Block": 0,
                "eip158Block": 0
        },
        "nonce": "0x0000000000000042",
        "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "difficulty": "0x2000",
        "coinbase": "0x0000000000000000000000000000000000000000",
        "timestamp": "0x00",
        "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "extraData": "",
        "gasLimit": "0xffffffff"
}

#初始化(如果失败 则执行geth removedb、并删除当前文件夹下的所有文件 及root文件夹下的相关以太坊文件)

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

#启动目录 chain1中的以太坊、并启动personal命令

geth --datadir ./chain1/ --networkid 10  --nodiscover --http  --http.api 'web3,eth,net,debug,personal'   console
或
geth --datadir ./chain1/ --networkid 10    --rpc.enabledeprecatedpersonal     --nodiscover   console

#设置默认挖矿账号

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

#解锁账号

personal.unlockAccount(eth.accounts[1])
personal.unlockAccount(eth.accounts[0])

#交易转账

eth.sendTransaction({from: eth.accounts[1],to: eth.accounts[0],value: 100})
eth.sendTransaction({from: eth.accounts[1], to: eth.accounts[0], value: 100, gas: 999999999})

#启动打包区块,--挖矿

miner.start()
miner.stop()

#查看交易是否执行

eth.getTransactionReceipt("0xc2386b384e243f02392787d9aa41349897ff5d910c6fae9335bebf034ed81d13")

eth.getBalance(eth.accounts[1])
eth.getBalance(eth.accounts[0])

#安装solc 1、从Solidity官网下载solc的可执行文件:solidity.readthedocs.io/en/v0.5.16/… 2. 将可执行文件复制到/usr/local/bin/solc目录中:

 sudo cp solc-static-linux /usr/local/bin/solc
 solc -version

#编写合约

vi MyContract.sol 
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.2 <0.9.0;

contract MyContract {
   uint public firstArgument;
   uint public secondArgument;

   function heyue(uint _firstArgument, uint _secondArgument) public {
       firstArgument = _firstArgument;
       secondArgument = _secondArgument;
   }
}

#编译合约

 solc --bin --abi --optimize -o CONTRACTS MyContract.sol

#部署合约 使用geth命令部署合约:

geth --exec 'eth.sendTransaction({from: eth.coinbase, data: "0x[二进制代码]"})' attach

使用geth命令查询合约部署情况:

geth --exec 'eth.getTransactionReceipt("[交易Hash]")' attach
eth.sendTransaction({from: eth.coinbase, data: "0x608060405234801561001057600080fd5b5060d28061001f6000396000f3fe6080604052348015600f57600080fd5b5060043610603c5760003560e01c8063256d43c81460415780638fefd8ea14605b578063a92a9dd0146073575b600080fd5b604960005481565b60405190815260200160405180910390f35b60716066366004607b565b600091909155600155565b005b604960015481565b60008060408385031215608d57600080fd5b5050803592602090910135915056fea2646970667358221220a895bdc098738b80abcd1f5c94e8a8535d0446ed9c5f48edea5f07aa675886a964736f6c63430008130033"})
eth.getTransactionReceipt("0x4e7f1d0be7039fae7e2c66339310034cd3583b36ca18249271cb9e8743c9a79f")

web3调用合约

#调用那个账号的合约
web3.eth.defaultAccount=web3.eth.accounts[1]
#通过地址初始化合约实例 var
var MyContract = web3.eth.contract(abiArray); 
contractInstance = MyContract.at(address);


 
// 直接调用,自动按函数类型决定用 sendTransaction 还是 call
myContractInstance.myMethod(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]); 
// 显式以消息调用形式 call 该函数
myContractInstance.myMethod.call(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]); 
// 显式以发送交易形式调用该函数
myContractInstance.myMethod.sendTransaction(param1 [, param2, ...] [, transactionObject] [, callback]);

#调用那个账号的合约
web3.eth.defaultAccount=web3.eth.accounts[1]

usercontract=web3.eth.contract([{"inputs":[{"internalType":"uint256","name":"_firstArgument","type":"uint256"},{"internalType":"uint256","name":"_secondArgument","type":"uint256"}],"name":"check","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"firstArgument","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"secondArgument","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}])

mycontract=usercontract.at(0x4e7f1d0be7039fae7e2c66339310034cd3583b36ca18249271cb9e8743c9a79f)

mycontract.check(11,11)

java调用合约--暂未验证

import org.web3j.protocol.Web3j; 
import org.web3j.protocol.core.methods.response.TransactionReceipt; 
import org.web3j.protocol.http.HttpService; 
import org.web3j.tx.Contract; 
public class MyContract { 
    public static void main(String[] args) { 
    // Create a connection to the Ethereum client 
    Web3j web3j = Web3j.build(new HttpService()); 
    // Create the contract wrapper object 
    MyContract contract = MyContract.load( contractAddress, web3j, credentials, gasPrice, gasLimit); 
    // Call the contract 
    TransactionReceipt receipt = contract.myFunction().send(); 
    // Get the return value from the contract 
    String returnValue = contract.myFunction().send().getValue(); 
    }
}

调用合约--暂未验证

let web3 = new Web3(new Web3.providers.HttpProvider("<http://localhost:8545>")); 
let contractAddress = "0x4e7f1d0be7039fae7e2c66339310034cd3583b36ca18249271cb9e8743c9a79f"; 
let myContractInstance = new web3.eth.Contract(abi, contractAddress); 
// 然后可以调用合约中的方法,例如: 
myContractInstance.methods.heyue(param1, param2).call().then(
result => { console.log(result); 
});