搭建以太坊私有链完整指南:从零实现数据存储API

发布于:2025-05-13 ⋅ 阅读:(11) ⋅ 点赞:(0)

一、项目背景

1.1 为什么需要私有链?

以太坊通过区块链技术构建了一个去中心化、不可篡改的平台,早期依赖工作证明和挖矿维护安全,现转向更环保的共识机制。其核心创新——智能合约——使自动化、去信任的应用成为可能,推动了DeFi、NFT等领域的爆发。这些技术共同支撑起一个无需中介、透明可信的数字经济体系。

以太坊公有链(如主网)虽然功能强大,但存在交易费用高、速度慢等问题。搭建私有链可以:

  • 完全控制网络环境
  • 免费进行交易测试
  • 自定义共识机制
  • 保护数据隐私

1.2 项目架构图

REST API服务
智能合约
节点1
节点2
Bootnode

二、环境准备

2.1 准备Docker镜像

我们使用Docker创建隔离的Linux环境,确保环境一致性。以下参数需要特别注意:

  • --privileged: 赋予容器完全系统权限
  • --net=host: 使用主机网络模式,方便节点间通信
  • -v $PWD:/home: 将当前目录挂载到容器/home目录
# 创建并进入容器
mkdir blockchain_workspace
cd blockchain_workspace
docker run -it --name blockchain --privileged --net=host \
        -v $PWD:/home \
		-w /home ubuntu:20.04 /bin/bash

2.2 依赖安装

软件包 作用
solc Solidity编译器
web3 以太坊Python接口库
flask REST API框架
geth Go语言以太坊客户端
apt-get update
# 配置以太坊PPA源
apt-get install -y software-properties-common
add-apt-repository -y ppa:ethereum/ethereum
apt-get update

# 安装开发工具链
apt install python3-pip wget curl git vim net-tools iputils-ping -y

# 安装核心组件
pip3 install flask web3 -i https://pypi.tuna.tsinghua.edu.cn/simple
apt install -y solc

2.3 编译go-ethereum

cd /home
wget https://go.dev/dl/go1.18.10.linux-amd64.tar.gz
rm go -rf
tar -xf go1.18.10.linux-amd64.tar.gz
export PATH=$PWD/go/bin:$PATH

git clone https://github.com/ethereum/go-ethereum.git
cd go-ethereum/
git checkout v1.10.17
rm /root/go -rf
make all
cp build/bin/* /usr/local/bin/ -vf
cd ..

2.4 保存镜像

exit #退出blockchain容器
docker commit blockchain ethereum/client-go:v1.10.17
docker save ethereum/client-go:v1.10.17 | gzip > ethereum-client-go-v1.10.17.tar.gz

三、网络架构搭建

3.1 节点角色说明

节点类型 作用 数量
Bootnode 节点发现服务 1
Miner Node 区块生成节点 2

3.1 创建Bootnode

Bootnode是节点发现服务器,帮助其它节点建立P2P连接。关键步骤:

  • 创建容器
cd blockchain_workspace
docker stop ethereum_bootnode
docker rm ethereum_bootnode
docker run -it --name ethereum_bootnode --privileged --net=host \
        -v $PWD:/home \
		-w /home --hostname ethereum_bootnode ethereum/client-go:v1.10.17 /bin/bash
  • 创建配置文件存储目录
cd /home
mkdir -p blockchain/bootnode
rm -rf blockchain/bootnode/*

# 生成节点密钥
bootnode -genkey=blockchain/bootnode/boot.key

# 启动发现服务
nohup bootnode --nodekey blockchain/bootnode/boot.key > /home/bootnode.log 2>&1 &

3.2 部署第一个节点

  • 创建容器
cd blockchain_workspace
docker stop ethereum_node_1
docker rm ethereum_node_1
docker run -it --name ethereum_node_1 --privileged  --net=host \
        -v