:2026-03-21 3:18 点击:2
内网搭建以太坊:私有链/测试链部署全指南**
在区块链开发、测试或特定内部应用场景中,我们常常需要一个与主网隔离的以太坊环境,搭建内网以太坊节点(无论是私有链还是测试链)能够让我们在不受主网高Gas费用、网络拥堵等因素影响的情况下,自由地进行智能合约开发、部署与调试,以及各种分布式应用的测试,本文将详细介绍如何在局域网内搭建一个以太坊私有链/测试链。
以下是使用Geth创建一个简单私有链的详细步骤:
在Ubuntu/Debian系统上:
# 安装依赖 sudo apt-get install -y build-essential software-properties-common # 添加以太坊PPA源(可选,但推荐获取最新稳定版) sudo add-apt-repository -y ppa:ethereum/ethereum sudo apt-get update # 安装Geth sudo apt-get install -y ethereum
在macOS上(使用Homebrew):
brew tap ethereum/ethereum brew install geth
从源码编译(适用于所有平台,需要Go环境):
# 克隆Geth源码 git clone https://github.com/ethereum/go-ethereum.git cd go-ethereum # 编译 make geth # 编译后的可执行文件在/build/bin目录下,可以将其添加到PATH中
私有链需要一个独特的创世区块配置文件,创建一个名为genesis.json的文件:
{
"config": {
"chainId": 15, // 私有链ID,确保与主网、测试网不同
"constantinopleBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158B
lock": 0,
"byzantiumBlock": 0,
"istanbulBlock": 0,
"berlinBlock": 0,
"londonBlock": 0,
"parisBlock": 0,
"shanghaiBlock": 0,
"cancunBlock": 0,
"terminalTotalDifficulty": 0,
"terminalTotalDifficultyPassed": true,
"ethash": {}
},
"alloc": {
// 预分配地址及其以太币,方便测试
"0x742d35Cc6634C0532925a3b844Bc454e4438f44e": {"balance": "1000000000000000000000000"},
"0x1234567890123456789012345678901234567890": {"balance": "1000000000000000000000000"}
},
"coinbase": "0x0000000000000000000000000000000000000000",
"difficulty": "0x40000", // 初始难度,私有链可以调低
"gasLimit": "0xffffffff", // Gas限制
"extraData": "",
"nonce": "0x0000000000000042",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp": "0x00"
}
chainId:非常重要,用于区分不同的链,避免交易广播到错误网络。alloc:预分配资金到指定地址,地址格式为以太坊地址。使用Geth的init命令来使用genesis.json文件初始化数据目录:
geth --datadir /path/to/your/datadir init /path/to/genesis.json
mkdir -p ~/ethereum/private_chain geth --datadir ~/ethereum/private_chain init ~/ethereum/private_chain/genesis.json
执行后,会在datadir下生成geth和keystore等文件夹。
geth --datadir /path/to/your/datadir --networkid 15 --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --rpcapi "eth,net,web3,personal" --nodiscover --maxpeers 0 console
参数解释:
--datadir:指定数据目录。--networkid:指定网络ID,与genesis.json中的chainId保持一致。--rpc:启用HTTP-RPC服务。--rpcaddr "0.0.0.0":允许任何IP地址访问RPC服务(内网环境下,可以设置为特定IP如168.1.100)。--rpcport 8545:指定RPC服务端口,默认8545。--rpcapi "eth,net,web3,personal":允许通过RPC访问的API接口。--nodiscover:禁止节点自动发现,因为是私有链,不需要连接其他节点。--maxpeers 0:限制最大连接节点数为0,即不连接其他节点(单节点私有链),如果需要多节点共识,可以设置大于0的值,并配置节点间发现。console:启动交互式JavaScript控制台,方便管理节点。启动成功后,你将进入Geth控制台。
eth.blockNumber // 应该返回0,因为刚初始化 net.version // 查看网络ID
personal.newAccount("your_password") // 输入密码,返回账户地址
// personal.newAccount("123456") -> "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" (与genesis.json中预分配的地址一致)
personal.unlockAccount(eth.accounts[0], "your_password")
eth.getBalance(eth.accounts[0])
miner.start(1) // 启动挖矿,参数为线程数,1即可 miner.stop() // 停止挖矿
挖矿成功后,eth.blockNumber会递增,预分配地址的余额也会增加(如果是矿工地址)。
// 假设账户0有余额,向账户1发送0.1 ETH personal.unlockAccount(
本文由用户投稿上传,若侵权请提供版权资料并联系删除!