geth的java开发之使用web3j

maven引用geth的web3j包

		<dependency>
			<groupId>org.web3j</groupId>
			<artifactId>core</artifactId>
			<version>3.2.0</version>
		</dependency>
/**
 * 对geth节点的操作
 */

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;

import org.apache.log4j.Logger;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Bool;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.admin.methods.response.BooleanResponse;
import org.web3j.protocol.admin.methods.response.NewAccountIdentifier;
import org.web3j.protocol.admin.methods.response.PersonalUnlockAccount;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthAccounts;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
import org.web3j.protocol.core.methods.response.EthCall;
import org.web3j.protocol.core.methods.response.EthEstimateGas;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.geth.Geth;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;




public class EthService {
	
	/**
	* geth节点可调用的json-rpc接口地址和端口
	*/
	private static final String URL = "http://192.168.1.88:8545";//你的全节点服务器,挖矿节点

	private static final String PASSWORD = "yourpassword";//公共私钥的密码,不安全,最好每个账号设置一个
	
//	private static final  String contractAddress ="0x8279c18240f1b0354093c0dfbf8d7577156da712";//以太坊发布的合约地址
	
//	BigInteger nonce = web3j.ethGetTransactionCount(address , DefaultBlockParameterName.PENDING).send().getTransactionCount();
	
	private final static Logger logger = Logger.getLogger(EthService.class);
	
	private static  String clientVersion = null;
	
	static {
		Web3j web3 = initWeb3j();
		try {
		  Web3ClientVersion	web3ClientVersion = web3.web3ClientVersion().send();
		  clientVersion = web3ClientVersion.getWeb3ClientVersion();//连接测试
		} catch (Exception e) {
		  e.printStackTrace();
		}finally {
			web3.shutdown();
		}
	}
	/**
	* 通过http连接到geth节点
	* @return
	*/
	private static HttpService getService(){
		HttpService service =	new HttpService(URL);
		service.addHeader("connection","close");
		return service;
	}

	/**
	* 初始化web3j普通api调用
	* @return web3j
	*/
	public static Web3j initWeb3j() {
		return Web3j.build(getService());
	}
	
	/**
	* 初始化personal级别的操作对象
	* @return Geth
	*/
	public static Geth initGeth(){
		return Geth.build(getService());
	}
	
	/**
	* 初始化admin级别操作的对象
	* @return Admin
	*/
	public static Admin initAdmin(){
		return Admin.build(getService());
	}
	
	/**
	* 创建地址 Ethereum: 
	* @param password 密码(建议同一个平台的地址使用一个相同的,且复杂度较高的密码)
	* @return 地址hash
	* @throws IOException
	*/
	public static String newAccount() throws IOException {
		 try {
			Admin admin = initAdmin();
			Request<?, NewAccountIdentifier> request = admin.personalNewAccount(PASSWORD);
			NewAccountIdentifier result = request.send();
			return result.getAccountId();
		 } catch (IOException e) {
			e.printStackTrace();
			return null;
		 }
	}
	

	/**
	* 已创建的用户地址数组
	* @return 地址数组
	* @throws IOException
	*/
	public static List<String> getAccounts() throws IOException {
		Web3j web3 = initWeb3j();		
		Request<?, EthAccounts> request = web3.ethAccounts();
		EthAccounts result = request.send();
		return result.getAccounts();
	}
	
	/**
	* 解锁账户,发送交易前需要对账户进行解锁
	* @param address 地址
	* @param password 密码
	* @param duration 解锁有效时间,单位秒
	* @return
	* @throws IOException
	*/
	public static Boolean unlockAccount(String address, BigInteger duration) throws IOException {
		Admin admin = initAdmin();
		Request<?, PersonalUnlockAccount> request = admin.personalUnlockAccount(address, PASSWORD, duration);
		PersonalUnlockAccount account = request.send();
		return account.accountUnlocked();
	}
	
	/**
	* 获得账户余额eth
	* @param address 密码
	* @return 余额数量
	*/
	public static BigDecimal getBalance(String address) {
		Web3j web3j = initWeb3j();
        try {
            EthGetBalance ethGetBalance = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();
            return Convert.fromWei(new BigDecimal(ethGetBalance.getBalance()),Convert.Unit.ETHER);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
        	web3j.shutdown();
        }
    }
	
	
	/**
	* 获得代币账户余额
	* @param address 密码
	* @return 余额数量
	*/
	public static BigDecimal getTokenBalance(String fromAddress) {
		Web3j web3j = initWeb3j();		
        List<Type> inputParameters = new ArrayList<Type>();
        inputParameters.add(new Address(fromAddress));
        List<TypeReference<?>> outputParameters = new ArrayList<TypeReference<?>>();    
        outputParameters.add(new TypeReference<Uint256>() {});
        Function function = new Function("balanceOf",inputParameters,outputParameters);
        String data = FunctionEncoder.encode(function);
        Transaction transaction = Transaction.createEthCallTransaction(fromAddress, contractAddress, data);
        EthCall ethCall;
        BigInteger balanceValue = BigInteger.ZERO;
        try {
            ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
            List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
            balanceValue = (BigInteger) results.get(0).getValue();
            return  Convert.fromWei(new BigDecimal(balanceValue),Convert.Unit.ETHER);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
        	web3j.shutdown();
        }
       
    }
	
	/**
	 * 查询代币名称
	 * @param web3j
	 * @param contractAddress
	 * @return
	 */
	public static String getTokenName(String contractAddress) {
		Web3j web3j = initWeb3j();		
		String methodName = "name";
		String name = null;
		String fromAddr = emptyAddress;
		List<Type> inputParameters = new ArrayList<>();
		List<TypeReference<?>> outputParameters = new ArrayList<>();
		TypeReference<Utf8String> typeReference = new TypeReference<Utf8String>() {};
		outputParameters.add(typeReference);
		Function function = new Function(methodName, inputParameters, outputParameters);
		String data = FunctionEncoder.encode(function);
		Transaction transaction = Transaction.createEthCallTransaction(fromAddr, contractAddress, data);
		EthCall ethCall;
		try {
			ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).sendAsync().get();
			List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
			name = results.get(0).getValue().toString();
			return name;
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
			return name;
		}finally {
        	web3j.shutdown();
        }
		
	}
	
	/**
	* 获得当前区块高度
	* @return 当前区块高度
	* @throws IOException
	*/
	public static BigInteger getCurrentBlockNumber() throws IOException {
		Web3j web3j = initWeb3j();
		Request<?, EthBlockNumber>request = web3j.ethBlockNumber();
		return request.send().getBlockNumber();
	}
	
	/**
	* 账户解锁,使用完成之后需要锁定
	* @param address
	* @return
	* @throws IOException
	*/
	public static Boolean lockAccount(String address) throws IOException {
		Geth geth = initGeth();
		Request<?, BooleanResponse> request = geth.personalLockAccount(address);
		BooleanResponse response = request.send();
		return response.success();
	}
	
	
	/**
	* 获得ethblock
	* @param blockNumber 根据区块编号
	* @return
	* @throws IOException
	*/
	public static EthBlock getBlockEthBlock(Integer blockNumber) throws IOException {
		Web3j web3j = initWeb3j();
		DefaultBlockParameter defaultBlockParameter = new DefaultBlockParameterNumber(blockNumber);
		Request<?, EthBlock> request = web3j.ethGetBlockByNumber(defaultBlockParameter, true);
		EthBlock ethBlock = request.send();
		return ethBlock;
	}
	
	/**
	* eth发送交易并获得交易hash值
	* @param transaction
	*/
	public static String sendTransaction(String from,String to,BigInteger gasPrice,BigInteger value) throws IOException{
		Web3j web3j = initWeb3j();
		try {
			boolean unlockAccount = unlockAccount(from,BigInteger.valueOf(10));
			if (unlockAccount) {
				EthGetTransactionCount ethGetTransactionCount = null;
				ethGetTransactionCount = web3j.ethGetTransactionCount(from, DefaultBlockParameterName.PENDING).sendAsync().get();
				BigInteger nonce = ethGetTransactionCount.getTransactionCount();
				Transaction transaction = new Transaction(from,nonce,gasPrice,BigInteger.valueOf(60000),to,value,null);
				Request<?, EthSendTransaction> request = web3j.ethSendTransaction(transaction);
				EthSendTransaction ethSendTransaction = request.send();
				String txHash =ethSendTransaction.getTransactionHash();
				return  txHash;
			}else{
				return null;
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}finally {
        	web3j.shutdown();
        }
	}
		
	//gas值账代币
	public static String transferToken(String fromAddr, String toAddr, BigInteger gasPrice, BigInteger amount) {
		String txHash = null;
		Web3j web3j = initWeb3j();
		Geth admin = initGeth();
		try {
			PersonalUnlockAccount personalUnlockAccount = admin.personalUnlockAccount(
					fromAddr, PASSWORD, BigInteger.valueOf(10)).send();
			if (personalUnlockAccount.accountUnlocked()) {
				List<Type> inputParameters = new ArrayList<>();
				inputParameters.add(new Address(toAddr));
				inputParameters.add(new Uint256(amount));
				List<TypeReference<?>> outputParameters = new ArrayList<>();
				outputParameters.add(new TypeReference<Bool>() {});
				Function function = new Function("transfer", inputParameters, outputParameters);
				String data = FunctionEncoder.encode(function);
				EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(fromAddr, DefaultBlockParameterName.PENDING).sendAsync().get();
				BigInteger nonce = ethGetTransactionCount.getTransactionCount();
				// 获得eth余额
		        BigDecimal ethBalance = getBalance(fromAddr);
		        BigInteger balance = Convert.toWei(ethBalance, Convert.Unit.ETHER).toBigInteger();
		    	// 获得代币余额
		        BigDecimal tokenBalance = getTokenBalance(fromAddr);
		        BigInteger uencBlock = Convert.toWei(tokenBalance, Convert.Unit.ETHER).toBigInteger();
		        BigInteger gasLimit =BigInteger.valueOf(60000);
		        if (balance.compareTo(gasLimit) < 0) {
		            throw new RuntimeException("手续费不足,请核实");
		        }
		        if (uencBlock.compareTo(amount) < 0) {
		            throw new RuntimeException("代币不足,请核实");
		        }
		        Transaction transaction = Transaction.createFunctionCallTransaction(fromAddr, nonce, gasPrice,
		        		gasLimit, contractAddress, data);
				//不是必须的 可以使用默认值
				EthSendTransaction ethSendTransaction = web3j.ethSendTransaction(transaction).sendAsync().get();
				txHash = ethSendTransaction.getTransactionHash();
				return txHash;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return txHash;
		}finally {
        	web3j.shutdown();
        }
		return txHash;
		
    }
		
	/**
	 * 代币转账
	 */
	public static  String sendTokenTransaction(String fromAddress, String toAddress, BigInteger gasPrice, BigInteger amount) {
		String txHash = null;
		Web3j web3j = initWeb3j();
		Geth admin = initGeth();
		try {
			PersonalUnlockAccount personalUnlockAccount = admin.personalUnlockAccount(fromAddress, PASSWORD, BigInteger.valueOf(10)).send();
			if (personalUnlockAccount.accountUnlocked()) {
				Request<?, EthGasPrice> ethGasPrice = web3j.ethGasPrice();
//				BigInteger gasPrice =ethGasPrice.send().getGasPrice();//交易的gas价格,默认是网络gas价格的平均值
				List<Type> inputParameters = new ArrayList<>();
				inputParameters.add(new Address(toAddress));
				inputParameters.add(new Uint256(amount));
				List<TypeReference<?>> outputParameters = new ArrayList<>();
				outputParameters.add(new TypeReference<Bool>() {});
				Function function = new Function("transfer", inputParameters, outputParameters);
				String data = FunctionEncoder.encode(function);
				EthGetTransactionCount ethGetTransactionCount = web3j
						.ethGetTransactionCount(fromAddress, DefaultBlockParameterName.PENDING).sendAsync().get();
				BigInteger nonce = ethGetTransactionCount.getTransactionCount();
				// 获得eth余额
		        BigDecimal ethBalance = getBalance(fromAddress);
		        BigInteger balance = Convert.toWei(ethBalance, Convert.Unit.ETHER).toBigInteger();//转换过单位
		    	// 获得代币余额
		        BigDecimal tokenBalance = getTokenBalance(fromAddress);		       
		        BigInteger uencBlock = Convert.toWei(tokenBalance, Convert.Unit.ETHER).toBigInteger(); 
		        Transaction transaction = Transaction.createFunctionCallTransaction(fromAddress, nonce, gasPrice,
						BigInteger.valueOf(60000), contractAddress, data);
				if (gasPrice.compareTo(balance) > 0) {
		            throw new RuntimeException("手续费不足,请核实");
		        }
		        if (amount.compareTo(uencBlock) > 0) {
		            throw new RuntimeException("代币不足,请核实");
		        }
				transaction = Transaction.createFunctionCallTransaction(fromAddress, nonce, gasPrice,
						BigInteger.valueOf(60000), contractAddress, data);
				//不是必须的 可以使用默认值
				EthSendTransaction ethSendTransaction = web3j.ethSendTransaction(transaction).sendAsync().get();
				txHash = ethSendTransaction.getTransactionHash();
				return txHash;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("交易异常");
			 return txHash;
		}finally {
        	web3j.shutdown();
        }
		return txHash;

	}

	
	//估计手续上限Transaction transaction
	public static BigInteger getGasPrice() {
		Web3j web3j= initWeb3j();
        try {
			Request<?, EthGasPrice> ethGasPrice = web3j.ethGasPrice();
			BigInteger gasPrice =ethGasPrice.send().getGasPrice();//交易的gas价格,默认是网络gas价格的平均值
            return gasPrice;
        } catch (IOException e) {
            throw new RuntimeException("net error");
        }
    }

	/**
	* 指定地址发送交易所需nonce获取
	* @param address 待发送交易地址
	* @return
	* @throws IOException
	*/
	public static BigInteger getNonce(String address) throws IOException {
		Web3j web3j = initWeb3j();
		Request<?, EthGetTransactionCount> request = web3j.ethGetTransactionCount(address, DefaultBlockParameterName.LATEST);
		return request.send().getTransactionCount();
	}
	
	/**
	* 获得交易的信息
	* @param hash 交易的hash值
	* @return
	* @throws IOException
	*/
	public static Optional<TransactionReceipt> getReceipt(String hash) throws IOException {
		Web3j web3j = initWeb3j();
		Request<?, EthGetTransactionReceipt> request = web3j.ethGetTransactionReceipt(hash);
		Optional<TransactionReceipt> optional = request.send().getTransactionReceipt();
		if(!Optional.empty().equals(optional)) {
			logger.error("交易:optional:"+optional);
		}
		return optional;
	}
	
	/**
	 * 
	* 根据hash值获取交易
	* @param hash
	* @return
	* @throws IOException
	*/
	public static EthTransaction getTransactionByHash(String hash) throws IOException {
		Web3j web3j = initWeb3j();
		Request<?, EthTransaction> request = web3j.ethGetTransactionByHash(hash);
		return request.send();
	}
	
	
	//初始化单位
	public static String initWei(BigInteger gasMun) {
		BigInteger wei = new BigInteger("1000000000000000000");
		BigInteger[] remainder = gasMun.divideAndRemainder(wei);
		return remainder[0]+"."+remainder[1];
	}
	
	//初始化单位
	public String toDecimal(int decimal, BigInteger integer) {
		StringBuffer sbf = new StringBuffer("1"); 
		for(int i = 0; i < decimal; i++) { 
			sbf.append("0"); 
		} 
		String balance = new BigDecimal(integer).divide(new BigDecimal(sbf.toString()), 18, BigDecimal.ROUND_DOWN).toPlainString(); 
		return balance; 
	}
	
	public static void main(String[] agrs) throws IOException{

//		BigInteger gasPrice = getGasPrice();
//		System.out.println(gasPrice);
//		BigInteger value = getGasPrice();
//		System.out.println(value);
		//创建账户
//		String account=  newAccount();
//		System.out.println(account.toString());
//		查询所有钱包地址
//		List<String> accounts= getAccounts();
//		System.out.println(accounts.toString());
//		查询eth金额
//		BigDecimal d2 =getBalance("0x5e6fe581d629731088ceb7cd30c23317399b25a9");
//		System.out.println(d2);
		查询代币金额
//		BigDecimal detail2 =getTokenBalance("0x5e6fe581d629731088ceb7cd30c23317399b25a9");
//		System.out.println(detail2);

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值