IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 区块链 -> 区块链之以太坊(ETH)和波场币(TRX)钱包开源项目 -> 正文阅读

[区块链]区块链之以太坊(ETH)和波场币(TRX)钱包开源项目

? ?一.介绍:

? ? ? ? ?本项目主要是为了方便开发人员开发钱包时快速对接以太坊(ETH)和波场币(TRX)公链,以及快速开发与之对应的ERC20和TRC20代币的项目而准备的;

? ? ? ? ?以太坊项目地址:https://gitee.com/stupdee/blockchain.git

? ? ? ? ?波场币项目(本地签名广播交易)地址:https://gitee.com/stupdee/trident-java.git

? ? ? ? ?波场币项目(搭建FUll节点调用交易)地址:https://gitee.com/stupdee/tron-trc20.git

注:欢迎star

? 二.项目简介:

? ? ? ?(1).以太坊项目主要功能源码:

? ? ? ? ??


    /*************创建一个钱包文件**************/
    public static String creatAccount(String walletFileBasePath, String password)
            throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, CipherException, IOException {
        String walletFileName0 = "";//文件名
        //钱包文件保持路径,请替换位自己的某文件夹路径
        walletFileName0 = WalletUtils.generateNewWalletFile(password, new File(walletFileBasePath), false);
        return walletFileName0;
    }

    public static Credentials getCredentials(String walleFilePath, String passWord) throws Exception{
        Credentials credentials = WalletUtils.loadCredentials(passWord, walleFilePath);
        return credentials;
    }

    /********加载钱包文件**********/
    public static Map<String, Object> loadWallet(Credentials credentials) throws IOException, CipherException {
        String address = credentials.getAddress();
        BigInteger publicKey = credentials.getEcKeyPair().getPublicKey();
        BigInteger privateKey = credentials.getEcKeyPair().getPrivateKey();
        System.out.println(privateKey);
        String prikey = Numeric.toHexStringWithPrefixZeroPadded(privateKey, Keys.PRIVATE_KEY_LENGTH_IN_HEX);
        System.out.println(prikey);
        System.out.println("第二步: 加载钱包信息(如下):");
        System.out.println("-钱包地址:" + address);
        System.out.println("-私钥:" + prikey);
        System.out.println("-公钥:" + publicKey);
        Map<String, Object> map = new HashMap<>();
        map.put("address", address);
        map.put("privateKey", privateKey);
        map.put("publicKey", publicKey);
        return map;
    }

    /*******连接以太坊客户端**************/
    public static Web3j createETHclient(String token) throws IOException {
        //连接方式1:使用infura 提供的客户端
        // TODO: 2018/4/10 token更改为自己的
//        Web3j web3j = Web3j.build(new HttpService("https://mainnet.infura.io/v3/"+token));
        // 测试环境
        Web3j web3j = Web3j.build(new HttpService("https://ropsten.infura.io/v3/"+token));
        //连接方式2:使用本地客户端
//        Web3j web3j = Web3j.build(new HttpService("127.0.0.1:7545"));
        //测试是否连接成功
        String web3ClientVersion = web3j.web3ClientVersion().send().getWeb3ClientVersion();
        System.out.println("version:"+web3ClientVersion);
        return web3j;
    }

    /***********查询指定地址的余额***********/
    public static String getBlanceOf(Web3j web3j, String address) throws IOException {
        if (web3j == null){
            return "";
        }
        //第二个参数:区块的参数,建议选最新区块
        EthGetBalance balance = web3j.ethGetBalance(address, DefaultBlockParameter.valueOf("latest")).send();
        //格式转化 wei-ether
        String blanceETH = Convert.fromWei(balance.getBalance().toString(), Convert.Unit.ETHER).toPlainString().concat(" ether");
        System.out.println("余额:"+blanceETH);
        return blanceETH;
    }

    /**
     * 获取ERC-20 token指定地址余额
     *
     * @param address         查询地址
     * @param contractAddress 合约地址
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static String getERC20Balance(Web3j web3j, String address, String contractAddress) throws ExecutionException, InterruptedException {
        String methodName = "balanceOf";
        List<Type> inputParameters = new ArrayList<>();
        List<TypeReference<?>> outputParameters = new ArrayList<>();
        Address fromAddress = new Address(address);
        inputParameters.add(fromAddress);

        TypeReference<Uint256> typeReference = new TypeReference<Uint256>() {
        };
        outputParameters.add(typeReference);
        Function function = new Function(methodName, inputParameters, outputParameters);
        String data = FunctionEncoder.encode(function);
        Transaction transaction = Transaction.createEthCallTransaction(address, contractAddress, data);

        EthCall ethCall;
        BigDecimal balanceValue = BigDecimal.ZERO;
        try {
            ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
            List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
            Integer value = 0;
            if(results != null && results.size()>0){
                value = Integer.parseInt(String.valueOf(results.get(0).getValue()));
            }
            balanceValue = new BigDecimal(value).divide(WEI, 6, RoundingMode.HALF_DOWN);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return balanceValue.toString();
    }


    /****************交易*****************/
    public static String transErc10To(Web3j web3j, Credentials credentials, BigDecimal amount, String addressTo) throws Exception {
        if (web3j == null) return null;
        if (credentials == null) return null ;
        //开始发送0.01 =eth到指定地址
        TransactionReceipt send = Transfer.sendFunds(web3j, credentials, addressTo, amount, Convert.Unit.SZABO).sendAsync().get();
        log.info("Transaction complete:");
        log.info("trans hash=" + send.getTransactionHash());
        log.info("from :" + send.getFrom());
        log.info("to:" + send.getTo());
        log.info("gas used=" + send.getGasUsed());
        log.info("status: " + send.getStatus());
        return send.getTransactionHash();
    }

    /**
     * erc20代币转账
     *
     * @param from            转账地址
     * @param to              收款地址
     * @param value           转账金额
     * @param contractAddress 代币合约地址
     * @return 交易哈希
     */
    public static String transferERC20Token(Web3j web3j, String from, String to,
                                            BigDecimal value, Credentials credentials, String contractAddress)
            throws ExecutionException, InterruptedException, IOException {
        //获取nonce,交易笔数
        BigInteger nonce;
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(from, DefaultBlockParameterName.PENDING).send();
        if (ethGetTransactionCount == null) {
            return null;
        }
        nonce = ethGetTransactionCount.getTransactionCount();
        //gasPrice和gasLimit 都可以手动设置
        BigInteger gasPrice;
        EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
        if (ethGasPrice == null) {
            return null;
        }
        gasPrice = ethGasPrice.getGasPrice();
        //BigInteger.valueOf(4300000L) 如果交易失败 很可能是手续费的设置问题
        BigInteger gasLimit = BigInteger.valueOf(60000L);
        //ERC20代币合约方法
//        value = value.multiply(VALUE);
        final Uint256 uint256 = new Uint256(value.multiply(BigDecimal.TEN.pow(18)).toBigInteger());
        Function function = new Function(
                TRANSFER,
                Arrays.asList(new Address(to), uint256),
                Collections.singletonList(new TypeReference<Type>() {
                }));
        //创建RawTransaction交易对象
        String encodedFunction = FunctionEncoder.encode(function);
        RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
                contractAddress, encodedFunction);

        //签名Transaction
        byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        String hexValue = Numeric.toHexString(signMessage);
        //发送交易
        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
        String hash = ethSendTransaction.getTransactionHash();
        if (hash != null) {
            System.out.println("交易成功:  HASH: " + hash);
            return hash;
        }
        return null;
    }

(2)波场币项目主要源码:

? ? ? ? ?

//trx转账
    @GetMapping("/transferTrx")
    public String transferTrx(String toAddress, long amount) throws IllegalException {
        ApiWrapper client = ApiWrapper.ofNile(privateKey);
        //交易
        com.gkc.trx.proto.Response.TransactionExtention result = client.transfer(ownerAddress, toAddress, amount);
        //签名
        Chain.Transaction signedTransaction = client.signTransaction(result);
        //广播交易
        String txId = client.broadcastTransaction(signedTransaction);
        return txId;
    }

    //合约转账
    @GetMapping("/transferContract")
    public String transfer(String toAddress, long amount) {
        ApiWrapper client = ApiWrapper.ofNile(privateKey);
        Contract contract = client.getContract(contractAddress);
        Trc20Contract token = new Trc20Contract(contract, ownerAddress, client);
        String txid = token.transfer(toAddress, amount, "memo", 1000000000L);
        return txid;
    }
    //生成地址
    @GetMapping("/generateAddress")
    public List<String> generateAddress() {
        return ApiWrapper.generateAddress();
    }

    //获取trc20代币余额
    @GetMapping("/getBalance")
    public String getAccount(String address) {
        ApiWrapper client = ApiWrapper.ofNile(privateKey);//需要查询的用户的私钥,可以自己改
        Contract contract = client.getContract(contractAddress);
        Trc20Contract token = new Trc20Contract(contract, contractAddress, client);
        BigInteger balance = token.balanceOf(address);
        return balance.toString();
    }
/**
     * 发送trc20交易
     *
     * @param address
     * @param amount
     * @param remark
     * @return
     */
    @RequestMapping("/send")
    public String sendTx(@RequestParam("address") String address, @RequestParam("amount") String amount, @RequestParam("remark") String remark) {
        String tx = trc20Service.sendTrc20Transaction(address, amount, remark);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("title", "发送Trc20交易");
        if (tx != null) {

            resultMap.put("result", "success");
            resultMap.put("txid", tx);
        } else {
            resultMap.put("result", "fail");
        }
        return JSONObject.toJSONString(resultMap);
    }

    /**
     * 查询额度
     *
     * @param address
     * @param contract
     * @return
     */
    @RequestMapping("/queryToken")
    public String queryToken(@RequestParam("address") String address, @RequestParam("contract") String contract) {
        Map<String, Object> map = new HashMap<>();
        map.put("title", "查询代币");
        map.put("address", address);
        map.put("contract", contract);
        BigInteger amount = trc20Service.balanceOf(contract, address);
        map.put("amount", amount);
        return JSONObject.toJSONString(map);
    }


    /**
     * 发起转账
     *
     * @param address
     * @param contract
     * @return
     */
    @RequestMapping("/sendToken")
    public String sendToken(@RequestParam("address") String address, @RequestParam("contract") String contract,
                            @RequestParam("amount") String amount, @RequestParam("remark") String remark,
                            @RequestParam("get") String get, @RequestParam("pk") String pk) {
        Map<String, Object> map = new HashMap<>();
        map.put("标题", "查询代币");
        map.put("付款地址", address);
        map.put("合约", contract);
        map.put("私钥", pk);
        map.put("收款地址", get);
        map.put("额度", amount);
        map.put("备注", remark);
        String tx = trc20Service.sendTokenTransaction(contract, address, pk, amount, get, remark);
        if (tx != null) {
            map.put("结果", "成功");
            map.put("交易id", tx);
        } else {
            map.put("结果", "失败");
        }
        return JSONObject.toJSONString(map);
    }


    /**
     * 获取波场币 trx的数量
     *
     * @param address
     * @return
     */
    @RequestMapping("/balanceOfTron")
    public String balanceOfTron(@RequestParam("address") String address) {
        Map<String, Object> map = new HashMap<>();
        map.put("标题", "获取波场币数量");
        map.put("地址", address);
        BigDecimal decimal = trc20Service.balanceOfTron(address);
        map.put("数量", decimal.toString());
        return JSONObject.toJSONString(map);
    }
    @RequestMapping("/easytransferbyprivate")
    public String easytransferbyprivate(@RequestParam("toAddress") String toAddress,@RequestParam("privateKey") String privateKey,@RequestParam("amount") String amount) {
        Map<String, Object> map = new HashMap<>();
        map.put("标题", "直接转账trx");
        map.put("目标地址", toAddress);
        String result = trc20Service.easytransferbyprivate(toAddress,privateKey,amount);
        map.put("数量", amount);
        return result;
    }

    /*获取一个新的trc20地址*/
    @GetMapping("address/{account}")
    public MessageResult getNewAddress(@PathVariable String account) {
        logger.info("create new account={}", account);
        try {
            String address;
            Account acct = accountService.findByName("TRX",account);
            if(acct != null){
                address = acct.getAddress();
                accountService.save(acct,"TRX");
            }
            else {
                address = service.createNewWallet(account);
            }
            MessageResult result = new MessageResult(0, "success");
            result.setData(address);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(500, "rpc error:" + e.getMessage());
        }
    }


    /**
     * 创建tron地址
     *
     * @return
     */
    @RequestMapping("/createAddress")
    public String createAddress() {
        JSONObject obj = trc20Service.createAddress();
        obj.put("title", "创建地址");
        return obj.toJSONString();
    }

? ? ? ? ?以太坊项目地址:https://gitee.com/stupdee/blockchain.git

? ? ? ? ?波场币项目(本地签名广播交易)地址:https://gitee.com/stupdee/trident-java.git

? ? ? ? ?波场币项目(搭建FUll节点调用交易)地址:https://gitee.com/stupdee/tron-trc20.git

注:欢迎star

如有任何问题请添加群:

  区块链 最新文章
盘点具备盈利潜力的几大加密板块,以及潜在
阅读笔记|让区块空间成为商品,打造Web3云
区块链1.0-比特币的数据结构
Team Finance被黑分析|黑客自建Token“瞒天
区块链≠绿色?波卡或成 Web3“生态环保”标
期货从入门到高深之手动交易系列D1课
以太坊基础---区块验证
进入以太坊合并的五个数字
经典同态加密算法Paillier解读 - 原理、实现
IPFS/Filecoin学习知识科普(四)
上一篇文章      下一篇文章      查看所有文章
加:2021-07-04 19:56:32  更:2021-07-04 19:57:21 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/26 10:58:06-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码