Java以太坊开发入门

2023-06-02区块链6 分钟124 次阅读
AI 摘要salmon-ai

本

前言

教程

首先打开Idea新建一个gradle项目,我的版本是<SpringBoot2.7.12 + Gradle7.6.1 + Java11>

1、引入依赖

gradle 复制代码
plugins {
    id 'java-library'
    id 'org.springframework.boot' version '2.7.12'
    id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

group = 'com.eth'
version = '0.0.1-SNAPSHOT'
targetCompatibility = JavaVersion.VERSION_11
sourceCompatibility = JavaVersion.VERSION_11
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    maven {
        url "https://maven.aliyun.com/repository/central"
    }
    mavenCentral()
}

dependencies {

    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'

    annotationProcessor 'org.projectlombok:lombok:1.18.26'
    compileOnly 'org.projectlombok:lombok:1.18.26'
    testImplementation 'org.projectlombok:lombok:1.18.26'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'junit:junit:4.13.1'

    implementation 'org.springframework.boot:spring-boot-starter-validation'

    implementation 'mysql:mysql-connector-java:8.0.32'
    implementation 'com.baomidou:mybatis-plus-boot-starter:3.5.3.1'
    implementation 'com.baomidou:mybatis-plus-generator:3.2.0'
    implementation 'org.freemarker:freemarker:2.3.30'

    implementation 'com.alibaba:fastjson:1.2.83'

    implementation 'org.apache.httpcomponents:httpcore:4.4.12'
    implementation('org.apache.httpcomponents:httpclient:4.5.13') {
        exclude(module: 'commons-logging')
    }
    implementation 'com.github.briandilley.jsonrpc4j:jsonrpc4j:1.0'
    implementation('org.web3j:core:4.8.7')
    implementation('org.web3j:geth:4.8.7')

    implementation 'io.springfox:springfox-boot-starter:3.0.0'
    api 'org.springframework.boot:spring-boot-starter-jdbc'
}

test {
    useJUnitPlatform()
}

2、定义配置

java 复制代码
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配置
 *
 * @author Salmon
 * @since 2023-06-01
 */
@Configuration
@Data
@Slf4j
public class Config {

    @Value("${spring.config.activate.on-profile}")
    private String env;

    @Value("${is_test}")
    private Boolean isTest;

    @Value("${config.chain_url}")
    private String chainUrl;

    @Value("${config.md5_salt}")
    private String md5Salt;

    @Value("${config.password}")
    private String password;

    @Value("${config.keystore_file_path}")
    private String keystoreFilePath;

    @Value("${config.from_address}")
    private String fromAddress;

    @Value("${config.to_address}")
    private String toAddress;

    @ApiModelProperty(value = "凭证")
    private Credentials credentials;

    @Value("${config.default_gas_price}")
    private BigDecimal defaultGasPrice;

    @Value("${config.max_gas_price}")
    private BigDecimal maxGasPrice;

    @Value("${config.min_notify_eth}")
    private Double minNotifyEth;

    @Value("${config.hook_url}")
    private String hookUrl;

    @Value("${config.chain_id}")
    private Long chainId;

    private Web3j web3j;

    private List<String> addresses;

    private Map<String, BigInteger> nonceMap = new HashMap<>();

    @PostConstruct
    public void init() throws IOException, CipherException {
        web3j = Web3j.build(new HttpService(chainUrl));
        File file = null;
        if ("local".equals(this.env)) {
            file = ResourceUtils.getFile(this.getKeystoreFilePath());
        } else {
            try {
                Resource resource = new FileSystemResource(this.getKeystoreFilePath());
                file = resource.getFile();
            } catch (Exception e) {
                log.error("", e);
            }
        }
        // 使用密码和 Keystore 文件路径加载钱包
        credentials = WalletUtils.loadCredentials(this.getPassword(), file);
        // 获取私钥
        String privateKey = credentials.getEcKeyPair().getPrivateKey().toString(16);
        log.info("privateKey:{}", privateKey);
        //初始化地址
        addresses = new ArrayList<>();
        addresses.add(fromAddress);
        addresses.add(toAddress);
        //初始化nonce
        for (String address : addresses) {
            nonceMap.put(address, BigInteger.ZERO);
        }
    }

}

3、编写代码

定义controller

java 复制代码
package com.salmon.controller;

import com.alibaba.fastjson.JSON;
import com.salmon.config.Config;
import com.salmon.service.IEthService;
import com.salmon.vo.resp.ResVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;

import static com.salmon.constants.Constants.*;

/**
 * 交易控制器
 *
 * @author Salmon
 * @since 2023-06-02
 */
@RequestMapping("/eth")
@RestController
@Slf4j
@RequiredArgsConstructor
public class EthController {

    private final Config config;
    private final IEthService ethService;

    @GetMapping("/balance")
    public ResVo<String> balance() throws IOException {
        BigInteger balance = ethService.getBalance(FROM_ADDRESS);
        log.info("balance:{}", balance);
        return ResVo.ok(balance.toString());
    }

    @GetMapping("/transaction")
    public ResVo<Object> transaction() throws ExecutionException, InterruptedException, IOException {
        Web3j web3j = config.getWeb3j();

        Credentials credentials = Credentials.create(FROM_PRIVATE_KEY);

        // 获取当前的交易数目(nonce)
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(FROM_ADDRESS, DefaultBlockParameterName.LATEST).sendAsync().get();
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();
        // 创建交易对象
        RawTransaction rawTransaction = RawTransaction.createTransaction(
                nonce,
                Convert.toWei(config.defaultGasPrice, Convert.Unit.GWEI).toBigInteger(),
                BigInteger.valueOf(210000L),
                TO_ADDRESS,
                BigInteger.ONE,
                Numeric.toHexString("{id:1,name:\"salmon\"}".getBytes(StandardCharsets.UTF_8))
        );
        String data = rawTransaction.getData();
        log.info("send before data:{}", data);
        //对交易对象进行签名
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, 0x3039, credentials);
        String hexValue = Numeric.toHexString(signedMessage);

        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();
        log.info("ethSendTransaction:{}", JSON.toJSONString(ethSendTransaction));
        String transactionHash = ethSendTransaction.getTransactionHash();
        // 获取交易收据
        // 等待一段时间,使交易被确认
        Thread.sleep(7000);
        EthTransaction ethTransaction = web3j.ethGetTransactionByHash(transactionHash).send();
        Transaction transaction = ethTransaction.getTransaction().get();
        String jsonString = JSON.toJSONString(transaction);
        log.info("json:{}", jsonString);
        //解析data
        // 将十六进制字符串转换为字节数组
        byte[] inputBytes = Numeric.hexStringToByteArray(transaction.getInput());
        // 将字节数组转换为普通字符串
        String s = new String(inputBytes, StandardCharsets.UTF_8);
        log.info("send after data:{}", s);
        return ResVo.ok(transaction);
    }
}

定义service

java 复制代码
package com.salmon.service;

import com.salmon.entity.MineTransaction;
import com.salmon.entity.MineBlock;
import org.web3j.protocol.core.methods.response.EthBlock;

import java.io.IOException;
import java.math.BigInteger;

/**
 * @author Salmon
 */
public interface IEthService {

    /**
     * 交易
     *
     * @param from  发送方
     * @param to    接收方
     * @param value 交易金额 单位:eth
     * @param data  携带的数据
     * @return 交易hash
     */
    String sendTransaction(String from, String to, BigInteger value, String data) throws Exception;

    /**
     * 获取指定账户余额
     *
     * @param address 指定账户的地址
     * @return BigInteger 余额
     */
    BigInteger getBalance(String address) throws IOException;

    /**
     * 获取当前最新区块
     *
     * @return 区块信息
     */
    MineBlock getLatestBlock() throws IOException;

    /**
     * 保存区块
     *
     * @param blockNum 区块编号
     */
    void saveBlock(Long blockNum) throws IOException;

    /**
     * 保存交易账本
     *
     * @param mineBlock 交易区块
     */
    void saveTransactions(MineBlock mineBlock);

    /**
     * 根据区块编号获取区块
     *
     * @param blockNumber 区块编号
     * @return 返回区块
     */
    EthBlock getBlock(Long blockNumber) throws IOException;

    /**
     * 获取当前地址的交易数量
     *
     * @param address 账户地址
     * @return 交易数量
     */
    BigInteger getNonce(String address) throws Exception;

    /**
     * 获取交易信息
     *
     * @param transactionHash 交易哈希
     * @return 交易信息
     */
    MineTransaction getTransaction(String transactionHash);

    /**
     * 获取解密后的Data
     *
     * @param data 待解密的数据
     * @return 解密后的数据
     */
    String getData(String data);

}

定义实现类

java 复制代码
package com.salmon.service.impl;

import com.alibaba.fastjson.JSON;
import com.salmon.config.env.Config;
import com.salmon.entity.MineTransaction;
import com.salmon.entity.MineBlock;
import com.salmon.service.IBlockService;
import com.salmon.service.IEthService;

import com.salmon.service.ITransactionService;
import com.salmon.utils.EthUtils;
import com.salmon.utils.HexUtils;
import com.salmon.utils.Utils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.methods.response.*;

import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Salmon
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class EthServiceImpl implements IEthService {

    private final Config config;
    private final IBlockService blockService;
    private final ITransactionService transactionService;


    @Override
    public String sendTransaction(String from, String to, BigInteger value, String data) throws Exception {
        synchronized (from.intern()) {
            Web3j web3j = config.getWeb3j();
            BigInteger nonce = getNonce(from);
            //以太坊网络上的燃气价格,用于计算交易的手续费
            BigInteger gasPrice = EthUtils.convertGweiToWei(config.getDefaultGasPrice()).toBigInteger();
            //交易所使用的最大燃气量
            BigInteger gasLimit = EthUtils.convertGweiToWei(config.getMaxGasPrice()).toBigInteger();
            BigInteger amount = EthUtils.convertEthToWei(value).toBigInteger();
            log.info("from:{},to:{},nonce:{},gasPrice:{},gasLimit:{},amount:{}", from, to, nonce, gasPrice, gasLimit, amount);
            // 创建交易对象
            RawTransaction rawTransaction = RawTransaction.createTransaction(
                    nonce,
                    gasPrice,
                    gasLimit,
                    to,
                    amount,
                    HexUtils.toHexString(data) //字符串数据转换为字节数组,并将其转换为十六进制格式
            );
            //对交易对象进行签名
            byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, config.getChainId(), config.getCredentials());
            String hexValue = HexUtils.toHexString(signedMessage);

            EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();
            if (!StringUtils.hasText(ethSendTransaction.getTransactionHash())) {
                log.error("sendTransaction error,\n ethSendTransaction:{}", JSON.toJSONString(ethSendTransaction));
            } else {
                BigInteger targetNonce = config.getNonceMap().get(from).add(BigInteger.ONE);
                updateAddressNonce(from, targetNonce);
            }
            return ethSendTransaction.getTransactionHash();
        }
    }

    private void updateAddressNonce(String from, BigInteger nonce) {
        config.getNonceMap().put(from, nonce);
    }

    @Override
    public BigInteger getBalance(String address) throws IOException {
        Web3j web3j = config.getWeb3j();
        EthGetBalance ethGetBalance = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();
        return ethGetBalance.getBalance();
    }

    @Override
    public MineBlock getLatestBlock() throws IOException {
        Web3j web3j = config.getWeb3j();
        EthBlockNumber ethBlockNumber = web3j.ethBlockNumber().send();
        MineBlock mineBlock = new MineBlock();
        mineBlock.setBlockNum(ethBlockNumber.getBlockNumber().longValue() - 5);
        return mineBlock;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBlock(Long blockNum) throws IOException {
        EthBlock ethBlock = getBlock(blockNum);
        MineBlock mineBlock = new MineBlock();
        EthBlock.Block block = ethBlock.getBlock();
        BeanUtils.copyProperties(block, mineBlock);

        mineBlock.setBlockNum(block.getNumber().longValue());
        mineBlock.setBlockHash(block.getHash());
        mineBlock.setCreateTime(LocalDateTime.now());
        mineBlock.setUpdateTime(LocalDateTime.now());

        BigInteger timestamp = block.getTimestamp();  // 获取时间戳
        BigInteger difficulty = block.getDifficulty();  // 获取难度
        BigInteger totalDifficulty = block.getTotalDifficulty();  // 获取总难度
        BigInteger gasLimit = block.getGasLimit();  // 获取Gas限制
        BigInteger gasUsed = block.getGasUsed();  // 获取已使用的Gas量
        BigInteger size = block.getSize();  // 获取区块大小
        BigInteger nonce = block.getNonce(); //获取交易随机数

        mineBlock.setGasUsed(gasUsed);
        mineBlock.setGasLimit(gasLimit);
        mineBlock.setDifficulty(difficulty);
        mineBlock.setTotalDifficulty(totalDifficulty);
        mineBlock.setTimestamp(timestamp.longValue());
        mineBlock.setSize(size);
        mineBlock.setNonce(nonce.longValue());
        mineBlock.setTxCount(block.getTransactions().size());
        mineBlock.setTransactions(block.getTransactions());
        mineBlock.setBaseFeePerGas(block.getBaseFeePerGas());
        List<String> uncles = block.getUncles();
        mineBlock.setUncles(JSON.toJSONString(uncles));

        //查询数据库中是否已有改区块,无,插入
        if (!blockService.containsBlock(blockNum)) {
            blockService.save(mineBlock);
            if (!CollectionUtils.isEmpty(mineBlock.getTransactions())) {
                saveTransactions(mineBlock);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTransactions(MineBlock mineBlock) {
        List<MineTransaction> mineTransactions = new ArrayList<>();
        List<EthBlock.TransactionResult> transactions = mineBlock.getTransactions();
        if (!CollectionUtils.isEmpty(transactions)) {
            for (EthBlock.TransactionResult transaction : transactions) {
                EthBlock.TransactionObject transactionObject = (EthBlock.TransactionObject) transaction;
                MineTransaction mineTransaction = new MineTransaction(
                        transactionObject.getHash(),
                        transactionObject.getBlockNumber().longValue(),
                        transactionObject.getTransactionIndex().longValue(),
                        transactionObject.getNonce().longValue(),
                        transactionObject.getBlockHash(),
                        transactionObject.getFrom(),
                        transactionObject.getTo(),
                        transactionObject.getValue(),
                        transactionObject.getInput(),
                        transactionObject.getGasPrice(),
                        transactionObject.getGas(),
                        Utils.timestampToLocalTime(mineBlock.getTimestamp()),
                        transactionObject.getChainId(),
                        transactionObject.getType()
                );
                mineTransactions.add(mineTransaction);
            }
        }
        transactionService.saveBatch(mineTransactions);
    }

    @Override
    public EthBlock getBlock(Long blockNumber) throws IOException {
        Web3j web3j = config.getWeb3j();
        DefaultBlockParameter defaultBlockParameter = new DefaultBlockParameterNumber(blockNumber);
        EthBlock ethBlock = web3j.ethGetBlockByNumber(defaultBlockParameter, true).send();
        if (Objects.isNull(ethBlock)) {
            log.error("find block error: {}", blockNumber);
        }
        return ethBlock;
    }

    @Override
    public BigInteger getNonce(String address) throws Exception {
        synchronized (address.intern()) {
            BigInteger localNonce = config.getNonceMap().get(address);
            BigInteger remoteNonce = getNonceFromType(address, DefaultBlockParameterName.LATEST);
            log.info("remoteNonce: {}, localNonce: {}, from:{}", remoteNonce, localNonce, address);
            if (remoteNonce.compareTo(localNonce) > 0) { //不能判断不等于,因为本地已经增加了但是远程没增加的情况必然存在
                //下一次的nonce
                updateAddressNonce(address, remoteNonce);
                return remoteNonce;
            }
            return localNonce;
        }
    }

    private BigInteger getNonceFromType(String from, DefaultBlockParameter defaultBlockParameter) throws Exception {
        EthGetTransactionCount ethGetTransactionCount = config.getWeb3j().ethGetTransactionCount(from, defaultBlockParameter).sendAsync().get();
        return ethGetTransactionCount.getTransactionCount();
    }

    @Override
    public MineTransaction getTransaction(String transactionHash) {
        MineTransaction mineTransaction = new MineTransaction();
        Transaction transaction = null;
        try {
            Web3j web3j = config.getWeb3j();
            transaction = web3j.ethGetTransactionByHash(transactionHash).send().getTransaction().get();
            BeanUtils.copyProperties(transaction, mineTransaction);
            mineTransaction.setTxHash(transaction.getHash());
            mineTransaction.setData(transaction.getInput());
        } catch (Exception e) {
            log.error("getTransaction error hash:{}:{}", transactionHash, transaction, e);
        }
        return mineTransaction;
    }

    @Override
    public String getData(String data) {
        return HexUtils.hexStringToString(data);
    }

}

4、测试

测试获取余额

浏览器输入地址:http://localhost:8888/eth/balance,可以得到余额结果
image.png

测试交易

浏览器输入地址:http://localhost:8888/eth/transaction,可以得到交易的结果
image.png

json 复制代码
{
    "data": {
        "hash": "0xeb56313d02be495219cf552597cc71bafaa4b63365b41e6f5fb5e0465b0c798a",
        "nonce": 8,
        "blockHash": "0x332ee9c1a1dafec3242a75759c89c09ed71c1da5d916e41a2aaefc3ed05478f2",
        "blockNumber": 19233,
        "transactionIndex": 0,
        "from": "0x86336bb9981410feaeb1cb8957ce248b3e4ae413",
        "to": "0x6a6a62c388dd527f101b03538574d0a1953a55e7",
        "value": 1,
        "gasPrice": 2000000000,
        "gas": 210000,
        "input": "0x7b69643a312c6e616d653a2273616c6d6f6e227d",
        "creates": null,
        "publicKey": null,
        "raw": null,
        "r": "0x64aba6ac2eab8a3527ee265b37fba14b103f7ebc0803b754490b6af55c3fbe14",
        "s": "0x57ac6d36a20a54b19133437b8a3b66dfae402cedfefda60c1cfa6007b86fa63c",
        "v": 24725,
        "type": "0x0",
        "maxFeePerGas": null,
        "maxPriorityFeePerGas": null,
        "accessList": null,
        "valueRaw": "0x1",
        "gasPriceRaw": "0x77359400",
        "gasRaw": "0x33450",
        "chainId": 12345,
        "blockNumberRaw": "0x4b21",
        "nonceRaw": "0x8",
        "transactionIndexRaw": "0x0"
    },
    "code": 200,
    "msg": "操作成功"
}

image.png
查看目标账户的余额变化,可以发现+1
image.png

觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句