├── .gitignore ├── pom.xml ├── src ├── main │ ├── java │ │ └── com │ │ │ └── yumiao │ │ │ └── usdttransfer │ │ │ ├── AppApplication.java │ │ │ ├── annotation │ │ │ ├── IgnoreAuth.java │ │ │ └── LoginUser.java │ │ │ ├── api │ │ │ ├── Base58Controller.java │ │ │ └── TrcController.java │ │ │ ├── base │ │ │ ├── BaseController.java │ │ │ └── JsonResponse.java │ │ │ ├── config │ │ │ ├── SwaggerConfig.java │ │ │ └── WebMvcConfigurer.java │ │ │ ├── constant │ │ │ ├── Constant.java │ │ │ ├── MessageTemplate.java │ │ │ ├── RegexConstant.java │ │ │ └── RespCode.java │ │ │ ├── domain │ │ │ ├── GoodInfoVo.java │ │ │ ├── GoodSaveDto.java │ │ │ ├── JwTUserInfo.java │ │ │ ├── NewAddressRespMsg.java │ │ │ ├── PageInfo.java │ │ │ ├── SignRawTxReqMsg.java │ │ │ ├── SignRawTxRespMsg.java │ │ │ ├── TransactionParam.java │ │ │ ├── UserInfo.java │ │ │ └── UserUserDto.java │ │ │ ├── enums │ │ │ └── BodyRecognitionStatusEnum.java │ │ │ ├── exception │ │ │ ├── BizException.java │ │ │ ├── GlobalExceptionHandler.java │ │ │ ├── ParamIsNullException.java │ │ │ └── ParamNotMatchException.java │ │ │ ├── feign │ │ │ ├── TronFullNodeFeign.java │ │ │ └── dt │ │ │ │ ├── ContractEvent.java │ │ │ │ ├── GetTransactionSign.java │ │ │ │ └── TriggerSmartContract.java │ │ │ ├── interceptor │ │ │ └── LogInterceptor.java │ │ │ ├── service │ │ │ └── TrcService.java │ │ │ ├── utils │ │ │ ├── Assert.java │ │ │ ├── Base58.java │ │ │ ├── ByteArray.java │ │ │ ├── CollectionUtil.java │ │ │ ├── CollectionUtils.java │ │ │ ├── DateUtils.java │ │ │ ├── DecimalUtil.java │ │ │ ├── EncrypDES.java │ │ │ ├── EncryptUtil.java │ │ │ ├── FileUtil.java │ │ │ ├── GeoUtil.java │ │ │ ├── HashUtils.java │ │ │ ├── HexUtils.java │ │ │ ├── HttpUtil.java │ │ │ ├── HttpUtils.java │ │ │ ├── I18nUtils.java │ │ │ ├── IdGenUtil.java │ │ │ ├── IdWorker.java │ │ │ ├── JSONUtil.java │ │ │ ├── JsonFormat.java │ │ │ ├── JwtUtil.java │ │ │ ├── NumberUtils.java │ │ │ ├── OrderSetter.java │ │ │ ├── PBKDF2Util.java │ │ │ ├── PageUtils.java │ │ │ ├── RandomUtils.java │ │ │ ├── RequestUtil.java │ │ │ ├── RestResponse.java │ │ │ ├── Sha256Hash.java │ │ │ ├── Sha512.java │ │ │ ├── SpringApplicationContextUtil.java │ │ │ ├── SpringUtils.java │ │ │ ├── StringUtils.java │ │ │ ├── StringUtilse.java │ │ │ ├── ThreeValues.java │ │ │ ├── TronUtils.java │ │ │ ├── TwoValues.java │ │ │ ├── ValidateUtil.java │ │ │ ├── redis │ │ │ │ ├── RedisLockUtil.java │ │ │ │ └── RedisSequenceUtil.java │ │ │ └── wcgPwdUtil.java │ │ │ └── wallet │ │ │ ├── AbstractWallet.java │ │ │ ├── TRXWallet.java │ │ │ └── Wallet.java │ └── resources │ │ ├── application-dev.properties │ │ ├── application.properties │ │ ├── generatorConfig.xml │ │ ├── lib │ │ ├── pad-core-1.2.0.jar │ │ ├── pad-crypto-1.2.0.jar │ │ ├── pad-parabox-1.2.0.jar │ │ ├── parabox-1.2.0-all.jar │ │ ├── tron-protobuf-1.0-SNAPSHOT.jar │ │ └── tron-wallet-cli.jar │ │ └── logback.xml └── test │ └── java │ └── com │ └── exchange │ └── userserver │ ├── GoodServiceTests.java │ ├── UserServerApplicationTests.java │ └── UserUserServiceTests.java └── 测试ETH网络.txt /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | .class 14 | 15 | ### IntelliJ IDEA ### 16 | .idea 17 | *.iws 18 | *.iml 19 | *.ipr 20 | *.workspace 21 | ### NetBeans ### 22 | /nbproject/private/ 23 | /nbbuild/ 24 | /dist/ 25 | /nbdist/ 26 | /.nb-gradle/ 27 | /build/ 28 | 29 | ### VS Code ### 30 | .vscode/ 31 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/AppApplication.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 6 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 7 | import org.springframework.boot.web.client.RestTemplateBuilder; 8 | import org.springframework.boot.web.servlet.MultipartConfigFactory; 9 | import org.springframework.cloud.client.loadbalancer.LoadBalanced; 10 | import org.springframework.cloud.openfeign.EnableFeignClients; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.ComponentScan; 13 | import org.springframework.util.unit.DataSize; 14 | import org.springframework.web.client.RestTemplate; 15 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 16 | 17 | import javax.servlet.MultipartConfigElement; 18 | import java.io.File; 19 | 20 | @SpringBootApplication( exclude = {DataSourceAutoConfiguration.class}) 21 | @EnableSwagger2 22 | @EnableConfigurationProperties 23 | @ComponentScan(basePackages = {"com.yumiao.usdttransfer.*", "com.yumiao.usdttransfer.config"}) 24 | public class AppApplication { 25 | 26 | 27 | public static void main(String[] args) { 28 | SpringApplication.run(AppApplication.class, args); 29 | } 30 | 31 | 32 | @Bean 33 | public RestTemplate restTemplate(RestTemplateBuilder builder){ 34 | return builder.build(); 35 | } 36 | 37 | 38 | /** 39 | * 文件上传配置 40 | * @return 41 | */ 42 | @Bean 43 | public MultipartConfigElement multipartConfigElement() { 44 | MultipartConfigFactory factory = new MultipartConfigFactory(); 45 | //单个文件大小200mb 46 | factory.setMaxFileSize(DataSize.ofMegabytes(200L)); 47 | //设置总上传数据大小1GB 48 | factory.setMaxRequestSize(DataSize.ofGigabytes(1L)); 49 | 50 | String location = System.getProperty("user.dir") + "/tmp"; 51 | File tmpFile = new File(location); 52 | if (!tmpFile.exists()) { 53 | tmpFile.mkdirs(); 54 | } 55 | factory.setLocation(location); 56 | return factory.createMultipartConfig(); 57 | } 58 | 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/annotation/IgnoreAuth.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | /** 6 | * 忽略Token验证 7 | * 8 | * @author lipengjun 9 | * @email 939961241@qq.com 10 | * @date 2017-03-23 15:44 11 | */ 12 | @Target(ElementType.METHOD) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Documented 15 | public @interface IgnoreAuth { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/annotation/LoginUser.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * 登录用户信息 10 | * 11 | * @author lipengjun 12 | * @email 939961241@qq.com 13 | * @date 2017-03-23 20:39 14 | */ 15 | @Target(ElementType.PARAMETER) 16 | @Retention(RetentionPolicy.RUNTIME) 17 | public @interface LoginUser { 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/api/Base58Controller.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.api; 2 | 3 | import com.yumiao.usdttransfer.base.BaseController; 4 | import com.yumiao.usdttransfer.utils.Base58; 5 | import com.yumiao.usdttransfer.utils.TronUtils; 6 | import com.yumiao.usdttransfer.wallet.TRXWallet; 7 | import io.swagger.annotations.Api; 8 | import io.swagger.annotations.ApiOperation; 9 | import io.swagger.annotations.ApiParam; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.web.bind.annotation.GetMapping; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RequestParam; 15 | import org.springframework.web.bind.annotation.RestController; 16 | import org.spongycastle.util.encoders.Hex; 17 | 18 | import java.io.UnsupportedEncodingException; 19 | 20 | @Api(tags = "base58") 21 | @RestController 22 | @RequestMapping("/base58") 23 | @Slf4j 24 | public class Base58Controller extends BaseController { 25 | 26 | @Autowired 27 | private TRXWallet trxWallet; 28 | 29 | 30 | 31 | @ApiOperation(value = "encode") 32 | @GetMapping("/encode") 33 | public Object encode( 34 | @ApiParam(value = "hexString", required = true) @RequestParam(value = "hexString", required = true) String hexString 35 | ) { 36 | String result = Base58.encode(Hex.decode(hexString)); 37 | return success(result); 38 | } 39 | @ApiOperation(value = "decode") 40 | @GetMapping("/decode") 41 | public Object decode( 42 | @ApiParam(value = "base58", required = true) @RequestParam(value = "base58", required = true) String base58) { 43 | byte[] base58Str= Base58.decode(base58); 44 | String result = Hex.toHexString(base58Str); 45 | return success(result); 46 | } 47 | 48 | 49 | @ApiOperation(value = "toViewAddress") 50 | @GetMapping("/toViewAddress") 51 | public Object toViewAddress( 52 | @ApiParam(value = "hexString", required = true) @RequestParam(value = "hexString", required = true) String hexString 53 | ) { 54 | String result =TronUtils.toViewAddress(hexString); 55 | //String hexFromAddress = trxWallet.castHexAddress(fromAddress); 56 | return success(result); 57 | } 58 | 59 | @ApiOperation(value = "toHexAddress") 60 | @GetMapping("/toHexAddress") 61 | public Object toHexAddress( 62 | @ApiParam(value = "base58", required = true) @RequestParam(value = "base58", required = true) String base58) { 63 | String result = TronUtils.toHexAddress(base58); 64 | return success(result); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/api/TrcController.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.api; 2 | 3 | 4 | import com.yumiao.usdttransfer.base.BaseController; 5 | import com.yumiao.usdttransfer.domain.PageInfo; 6 | import com.yumiao.usdttransfer.service.TrcService; 7 | import com.yumiao.usdttransfer.utils.Base58; 8 | import com.yumiao.usdttransfer.utils.PageUtils; 9 | import com.yumiao.usdttransfer.utils.StringUtils; 10 | import com.yumiao.usdttransfer.utils.TronUtils; 11 | import com.yumiao.usdttransfer.wallet.TRXWallet; 12 | import io.swagger.annotations.Api; 13 | import io.swagger.annotations.ApiOperation; 14 | import io.swagger.annotations.ApiParam; 15 | import lombok.extern.slf4j.Slf4j; 16 | import org.spongycastle.util.encoders.Hex; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.web.bind.annotation.*; 19 | 20 | import java.math.BigDecimal; 21 | import java.math.BigInteger; 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | @Api(tags = "usdt转账-trc") 26 | @RestController 27 | @RequestMapping("/trc") 28 | @Slf4j 29 | public class TrcController extends BaseController { 30 | 31 | @Autowired 32 | private TRXWallet trxWallet; 33 | 34 | @Autowired 35 | private TrcService trcService; 36 | 37 | 38 | @ApiOperation(value = "转账") 39 | @GetMapping("/createAddress") 40 | public Object createAddress() { 41 | Map result= trxWallet.createAddress(); 42 | return success(result); 43 | } 44 | 45 | @ApiOperation(value = "授权转账") 46 | @RequestMapping(value = "/usdttransferform",method ={RequestMethod.POST,RequestMethod.GET}) 47 | public Object transfer( 48 | @ApiParam(value = "from", required = false) @RequestParam(value = "from", required = false)String from, 49 | @ApiParam(value = "to", required = false) @RequestParam(value = "to", required = false)String to, 50 | @ApiParam(value = "privateKey", required = false) @RequestParam(value = "privateKey", required = false)String privateKey, 51 | @ApiParam(value = "tran_num", required = false) @RequestParam(value = "tran_num", required = false)String tran_num 52 | ) { 53 | String result= trcService.usdttransferFrom(from,to,privateKey,tran_num); 54 | return success(result); 55 | } 56 | 57 | @ApiOperation(value = "USDT转账") 58 | @GetMapping("/usdttransfer") 59 | public Object totransfer( 60 | @ApiParam(value = "privateKey", required = true) @RequestParam(value = "privateKey", required = true)String privateKey, 61 | @ApiParam(value = "to", required = true) @RequestParam(value = "to", required = true)String to, 62 | @ApiParam(value = "tran_num", required = true) @RequestParam(value = "tran_num", required = true)String tran_num 63 | ) { 64 | log.info("to:{},privateKey:{},tran_num:{}",to,privateKey,tran_num); 65 | String authAddress= TronUtils.getAddressByPrivateKey(privateKey); 66 | log.info("to:{},privateKey:{},tran_num:{},authAddress:{}",to,privateKey,tran_num,authAddress); 67 | String result= trxWallet.usdtSendTransaction(authAddress,privateKey,tran_num,to); 68 | return success(result); 69 | } 70 | 71 | @ApiOperation(value = "TRX转账") 72 | @GetMapping("/trxtransfer") 73 | public Object trxtransfer( 74 | @ApiParam(value = "privateKey", required = true) @RequestParam(value = "privateKey", required = true)String privateKey, 75 | @ApiParam(value = "to", required = true) @RequestParam(value = "to", required = true)String to, 76 | @ApiParam(value = "tran_num", required = true) @RequestParam(value = "tran_num", required = true)BigDecimal tranNum 77 | ) { 78 | log.info("to:{},privateKey:{},tran_num:{}",to,privateKey,tranNum); 79 | log.info("from:{},to:{},privateKey:{},tran_num:{}",to,privateKey,tranNum); 80 | String result= trxWallet.sendTransaction(privateKey,to, tranNum); 81 | return success(result); 82 | } 83 | 84 | 85 | @ApiOperation(value = "交易信息") 86 | @GetMapping("/getTransactionById") 87 | public Object getTransactionById( 88 | @ApiParam(value = "txId", required = true) @RequestParam(value = "txId", required = true)String txId) { 89 | String json=trcService.getTransactionById(txId); 90 | return success(json); 91 | } 92 | 93 | 94 | @ApiOperation(value = "余额") 95 | @GetMapping("/balance") 96 | public Object balance( 97 | @ApiParam(value = "address", required = true) @RequestParam(value = "address", required = true)String address) { 98 | Map result=new HashMap<>(); 99 | BigDecimal balance=trxWallet.usdtBalanceOf(address); 100 | result.put("usdt",balance); 101 | BigDecimal trx=trxWallet.balanceOfTron(address); 102 | result.put("trx",trx); 103 | return success(result); 104 | } 105 | 106 | @ApiOperation(value = "根据私钥获取地址") 107 | @GetMapping("/getAddressByPrivateKey") 108 | public Object getAddressByPrivateKey( 109 | @ApiParam(value = "privateKey", required = false) @RequestParam(value = "privateKey", required = false)String privateKey, 110 | @ApiParam(value = "privateKeybase58", required = false) @RequestParam(value = "privateKeybase58", required = false)String privateKeybase58) { 111 | String authAddress=""; 112 | if(StringUtils.isNotEmpty(privateKeybase58)){ 113 | byte[] base58Str= Base58.decode(privateKeybase58); 114 | privateKey = Hex.toHexString(base58Str); 115 | authAddress = TronUtils.getAddressByPrivateKey(privateKey); 116 | } 117 | else { 118 | authAddress = TronUtils.getAddressByPrivateKey(privateKey); 119 | } 120 | return success(authAddress); 121 | } 122 | 123 | 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/base/BaseController.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.base; 2 | 3 | import com.yumiao.usdttransfer.constant.Constant; 4 | import com.yumiao.usdttransfer.constant.RespCode; 5 | import com.yumiao.usdttransfer.domain.JwTUserInfo; 6 | import com.yumiao.usdttransfer.exception.BizException; 7 | import com.yumiao.usdttransfer.utils.DateUtils; 8 | import org.springframework.web.context.request.RequestAttributes; 9 | import org.springframework.web.context.request.RequestContextHolder; 10 | import org.springframework.web.context.request.ServletRequestAttributes; 11 | 12 | import javax.servlet.ServletException; 13 | import javax.servlet.http.Cookie; 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | import javax.servlet.http.HttpSession; 17 | import java.io.*; 18 | import java.util.Date; 19 | import java.util.Objects; 20 | 21 | public abstract class BaseController { 22 | 23 | protected Object success(Object data){ 24 | if(null==data){ 25 | return JsonResponse.success(""); 26 | }else { 27 | return JsonResponse.success(data); 28 | } 29 | } 30 | protected Object success(){ 31 | return JsonResponse.success(""); 32 | } 33 | 34 | protected void writeCokie(HttpServletRequest request, HttpServletResponse response, 35 | String name, String value, int days) throws ServletException, IOException { 36 | int day = 24 * 60 * 60; 37 | 38 | Cookie cookie = new Cookie(name, value); 39 | cookie.setPath("/"); 40 | response.addCookie(cookie); 41 | } 42 | protected void clearCokie(HttpServletRequest request, HttpServletResponse response, 43 | String name) throws ServletException, IOException { 44 | Cookie cookie = new Cookie(name, ""); 45 | cookie.setMaxAge(0); 46 | cookie.setPath("/"); 47 | response.addCookie(cookie); 48 | } 49 | 50 | /** 51 | * 获得登陆用户信息 52 | */ 53 | protected com.yumiao.usdttransfer.domain.JwTUserInfo getLoginUser() { 54 | HttpSession session = getSession(); 55 | if (Objects.isNull(session)) 56 | return null; 57 | 58 | Object userInfoObj = session.getAttribute(Constant.SESSION_KEY); 59 | if (Objects.isNull(userInfoObj)) 60 | return null; 61 | com.yumiao.usdttransfer.domain.JwTUserInfo userInfo=(com.yumiao.usdttransfer.domain.JwTUserInfo)userInfoObj; 62 | return userInfo; 63 | } 64 | 65 | /** 66 | * 获取客户端真实IP 67 | * 68 | * @param request 69 | * @return 70 | */ 71 | protected String getClientIpAddr(HttpServletRequest request) { 72 | String ip = request.getHeader("x-forwarded-for"); 73 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 74 | ip = request.getHeader("Proxy-Client-IP"); 75 | } 76 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 77 | ip = request.getHeader("WL-Proxy-Client-IP"); 78 | } 79 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 80 | ip = request.getRemoteAddr(); 81 | } 82 | if (ip.contains(",")) { 83 | return ip.split(",")[0]; 84 | } else { 85 | return ip; 86 | } 87 | } 88 | 89 | private ServletRequestAttributes getServletRequestAttributes() { 90 | RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); 91 | return (ServletRequestAttributes) requestAttributes; 92 | } 93 | 94 | protected HttpServletRequest getRequest() { 95 | return getServletRequestAttributes().getRequest(); 96 | } 97 | 98 | protected HttpServletResponse getResponse() { 99 | return getServletRequestAttributes().getResponse(); 100 | } 101 | 102 | protected HttpSession getSession() { 103 | return getRequest().getSession(); 104 | } 105 | 106 | protected String readCokie(HttpServletRequest request, 107 | String name) throws ServletException, IOException { 108 | String value = null; 109 | if (name != null) { 110 | Cookie cookies[] = request.getCookies(); 111 | if (cookies != null && cookies.length >= 0) { 112 | for (int i = 0; i < cookies.length; i++) { 113 | Cookie cookie = cookies[i]; 114 | if (name.equals(cookie.getName())) { 115 | value = cookie.getValue(); 116 | } 117 | } 118 | } 119 | } 120 | return value; 121 | } 122 | 123 | /** 124 | * 下载文件 125 | * @param response 126 | * @param fileName 下载文件名 127 | * @param path 文件服务器地址 128 | */ 129 | public void downloadFile(HttpServletResponse response, String fileName, String path){ 130 | if (fileName != null) { 131 | //设置文件路径 132 | File file = new File(path); 133 | if (file.exists()) { 134 | response.setHeader("content-type", "application/octet-stream"); 135 | response.setContentType("application/octet-stream"); 136 | try { 137 | response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"ISO-8859-1")); 138 | } catch (UnsupportedEncodingException e) { 139 | e.printStackTrace(); 140 | } 141 | byte[] buffer = new byte[1024]; 142 | FileInputStream fis = null; 143 | BufferedInputStream bis = null; 144 | try { 145 | fis = new FileInputStream(file); 146 | bis = new BufferedInputStream(fis); 147 | OutputStream os = response.getOutputStream(); 148 | int i = bis.read(buffer); 149 | while (i != -1) { 150 | os.write(buffer, 0, i); 151 | i = bis.read(buffer); 152 | } 153 | } catch (Exception e) { 154 | e.printStackTrace(); 155 | } finally { 156 | if (bis != null) { 157 | try { 158 | bis.close(); 159 | } catch (IOException e) { 160 | e.printStackTrace(); 161 | } 162 | } 163 | if (fis != null) { 164 | try { 165 | fis.close(); 166 | } catch (IOException e) { 167 | e.printStackTrace(); 168 | } 169 | } 170 | } 171 | } 172 | } 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/base/JsonResponse.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.base; 2 | 3 | import com.yumiao.usdttransfer.constant.RespCode; 4 | import io.swagger.annotations.ApiModel; 5 | import io.swagger.annotations.ApiModelProperty; 6 | 7 | @ApiModel("响应结果") 8 | public final class JsonResponse { 9 | 10 | /** 11 | * 成功 12 | */ 13 | public static final JsonResponse SUCCESS = new JsonResponse(RespCode.SUCCESS); 14 | 15 | /** 16 | * 失败 17 | */ 18 | public static final JsonResponse FAILURE = new JsonResponse(RespCode.FAILURE); 19 | 20 | /** 21 | * 系统错误 22 | */ 23 | public static final JsonResponse ERROR = new JsonResponse(RespCode.FAILURE); 24 | 25 | 26 | 27 | @ApiModelProperty("状态码") 28 | private int code; 29 | 30 | @ApiModelProperty("返回消息") 31 | private String msg = ""; 32 | 33 | @ApiModelProperty("返回数据") 34 | private T data = null; 35 | 36 | private JsonResponse(RespCode code) { 37 | this.code = code.getValue(); 38 | this.msg = code.getName(); 39 | } 40 | 41 | private JsonResponse(RespCode code, String msg) { 42 | this.code = code.getValue(); 43 | this.msg = msg; 44 | } 45 | 46 | private JsonResponse(RespCode code, T data) { 47 | this.code = code.getValue(); 48 | this.msg = code.getName(); 49 | this.data = data; 50 | } 51 | 52 | public JsonResponse(int code, String msg) { 53 | this.code = code; 54 | this.msg = msg; 55 | } 56 | 57 | public JsonResponse() { 58 | 59 | } 60 | 61 | public static JsonResponse success() { 62 | return new JsonResponse(RespCode.SUCCESS); 63 | } 64 | public static JsonResponse success(T data) { 65 | return new JsonResponse(RespCode.SUCCESS, data); 66 | } 67 | 68 | public static JsonResponse success(RespCode code, T data) { 69 | return new JsonResponse(code, data); 70 | } 71 | 72 | public static JsonResponse failure(String msg) { 73 | return new JsonResponse(RespCode.FAILURE, msg); 74 | } 75 | 76 | public static JsonResponse failure(RespCode code) { 77 | return new JsonResponse(code); 78 | } 79 | 80 | public static JsonResponse failure(RespCode code, String msg) { 81 | return new JsonResponse(code, msg); 82 | } 83 | 84 | public static JsonResponse failure(int code, String msg) { 85 | return new JsonResponse(code, msg); 86 | } 87 | 88 | public int getCode() { 89 | return code; 90 | } 91 | 92 | public void setCode(int code) { 93 | this.code = code; 94 | } 95 | 96 | public String getMsg() { 97 | return msg; 98 | } 99 | 100 | public void setMsg(String msg) { 101 | this.msg = msg; 102 | } 103 | 104 | public T getData() { 105 | return data; 106 | } 107 | 108 | public void setData(T data) { 109 | this.data = data; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.config; 2 | 3 | import com.yumiao.usdttransfer.constant.RespCode; 4 | import io.swagger.annotations.ApiOperation; 5 | import lombok.Setter; 6 | import org.springframework.boot.context.properties.ConfigurationProperties; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | import springfox.documentation.builders.ApiInfoBuilder; 11 | import springfox.documentation.builders.PathSelectors; 12 | import springfox.documentation.builders.RequestHandlerSelectors; 13 | import springfox.documentation.builders.ResponseMessageBuilder; 14 | import springfox.documentation.service.*; 15 | import springfox.documentation.spi.DocumentationType; 16 | import springfox.documentation.spi.service.contexts.SecurityContext; 17 | import springfox.documentation.spring.web.plugins.Docket; 18 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 19 | 20 | import java.util.ArrayList; 21 | import java.util.Collections; 22 | import java.util.List; 23 | import java.util.stream.Collectors; 24 | 25 | @SuppressWarnings("all") 26 | @Component 27 | @EnableSwagger2 28 | @ConfigurationProperties(prefix = "swagger") 29 | public class SwaggerConfig { 30 | @Bean 31 | public Docket api(){ 32 | return new Docket(DocumentationType.SWAGGER_2) 33 | .apiInfo(this.apiInfo()) 34 | .select() 35 | .apis(RequestHandlerSelectors.basePackage("com.yumiao.usdttransfer")) 36 | .paths(PathSelectors.any()) 37 | .build(); 38 | } 39 | 40 | 41 | private ApiInfo apiInfo(){ 42 | @SuppressWarnings("deprecation") 43 | ApiInfo info=new ApiInfo( 44 | "接口文档", 45 | "接口文档", 46 | "1.0", 47 | "urn:tos", 48 | "platform", 49 | "Apache 2.0", 50 | "http://www.apache.org/licenses/LICENSE-2.0"); 51 | return info; 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/config/WebMvcConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.config; 2 | 3 | import com.yumiao.usdttransfer.interceptor.LogInterceptor; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 7 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 8 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 9 | 10 | @Configuration 11 | public class WebMvcConfigurer implements org.springframework.web.servlet.config.annotation.WebMvcConfigurer { 12 | 13 | 14 | @Override 15 | public void addCorsMappings(CorsRegistry registry) { 16 | registry.addMapping("*") 17 | .allowedOrigins("*"); 18 | } 19 | 20 | @Override 21 | public void addInterceptors(InterceptorRegistry registry) { 22 | // registry.addInterceptor(new UserInfoInterceptor()).addPathPatterns("/**"); 23 | registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**"); 24 | 25 | } 26 | 27 | @Override 28 | public void addResourceHandlers(ResourceHandlerRegistry registry) { 29 | registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); 30 | 31 | registry.addResourceHandler("swagger-ui.html") 32 | .addResourceLocations("classpath:/META-INF/resources/"); 33 | 34 | registry.addResourceHandler("/webjars/**") 35 | .addResourceLocations("classpath:/META-INF/resources/webjars/"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/constant/Constant.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.constant; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.regex.Pattern; 5 | 6 | public final class Constant { 7 | 8 | /** 9 | * 授权header名字 10 | */ 11 | public static final String AUTH = "Authorization"; 12 | 13 | /** 14 | * 登录状态有效期天数 15 | */ 16 | public static final int JWTOUTTIME=30; 17 | 18 | 19 | /** 20 | *邀请码 21 | */ 22 | public static final String INVITATIONCODEKEY="invitationcode"; 23 | 24 | /** 25 | * 创建用户 26 | */ 27 | public static final String CREATEID = "SYSTEM"; 28 | 29 | 30 | public static final String GAODE_ADDRESS_LOCALHOST = "https://restapi.amap.com/v3/geocode/regeo"; 31 | 32 | public static final String GD_POI_ADDRESS_LOCALHOST = "https://restapi.amap.com/v3/place/around"; 33 | 34 | public static final String GAODE_LOCALHOST_BY_ADDRESS = "https://restapi.amap.com/v3/geocode/geo"; 35 | 36 | public static final String GD_POI_LOCALHOST_BY_ADDRESS = "https://restapi.amap.com/v3/place/text"; 37 | 38 | // 关键字搜索API服务地址 39 | public static final String GAODE_ADDRESS_AROUD = "https://restapi.amap.com/v3/place/text"; 40 | 41 | // 周边搜索API服务地址 42 | public static final String GAODE_ADDRESS_PLACE = "https://restapi.amap.com/v3/place/around"; 43 | 44 | public static final String DISTANCE_LOCATION = "https://restapi.amap.com/v4/direction/bicycling"; 45 | 46 | // 5公里经纬度最大偏差值 47 | public static final Double JINWEI = 0.05; 48 | 49 | // 3公里经纬度最大偏差值 50 | public static final Double DELIVERY_JINWEI = 0.03; 51 | 52 | /** 53 | * 请求t验证时间差 超过这个时间t无效 54 | */ 55 | public static final int TMINUTE=2; 56 | 57 | public static final String SESSION_KEY = "CURRENT_USER"; 58 | 59 | 60 | public static final String USER_REDIS_KEY_PREFIX = "userInfo:"; 61 | public static final String ONCE_TOKEN = "ONCE_TOKEN:"; 62 | public static final String PRE_LOGIN_TOKEN = "PRE_TOKEN:"; 63 | 64 | //用户登入游戏的key缓存 65 | public static final String USER_GAME_LOGIN_KEY = "GAME_KEY_CACHE:"; 66 | 67 | 68 | public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 69 | public static final String DATE_YM = "yyyy-MM"; 70 | public static final String DATE_YM_CN = "yyyy年MM月"; 71 | 72 | public static final String DATE_YMD = "yyyy-MM-dd"; 73 | public static final String DATE_YMD_CN = "yyyy年MM月dd日"; 74 | 75 | public static final String DATE_TIME = "yyyy-MM-dd HH:mm:ss"; 76 | public static final String TIME = "MM-dd HH:mm:ss"; 77 | public static final String DATE_TIME_CN = "yyyy年MM月dd日 HH:mm:ss"; 78 | 79 | public static final String DATE_YM_01 = "yyyy-MM-01"; 80 | 81 | public static final String MSEC_TIME = "yyyy-MM-dd HH:mm:ss.S"; 82 | 83 | public static final String DATE_TIME_YMDH_CN = "yyyy年MM月dd日HH点"; 84 | 85 | public static final String DATE_TIME_YMDHM_CN = "yyyy年MM月dd日 HH:mm"; 86 | 87 | public static final String TIMEZONE_CN = "GMT+8"; 88 | 89 | public static final String REGEXP_PHONE = "^1\\d{10}$"; 90 | 91 | public static final String REGEXP_EMAIL = "^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}$"; 92 | 93 | public static final String REGEXP_IMG = "^(.+?)\\.(png|jpg)$"; 94 | 95 | public static final String CNY_USDT = "CNYUSDT"; 96 | 97 | public static final String USDT_CNY = "USDTCNY"; 98 | 99 | public static final String USD_USDT = "USDUSDT"; 100 | 101 | public static final String CNY = "CNY"; 102 | 103 | public static final String USD = "USD"; 104 | 105 | public static final String USDT = "USDT"; 106 | 107 | public static final int STRING_LENGTH = 20; 108 | 109 | public static final Pattern GOOGLE_PATTERN = Pattern.compile("^\\d{6}$"); 110 | 111 | public static final String VOLUMEINCREASE_USER = "VOLUMEINCREASE_USER"; 112 | public static final String VOLUMEINCREASE_VALUE = "VOLUMEINCREASE_VALUE"; 113 | public static final String VOLUMEINCREASE = "volumeIncrease"; 114 | 115 | /** 116 | * 分页默认值 117 | */ 118 | public final static int DEFAULT_PAGE_NUM = 1; 119 | public final static int DEFAULT_LIMIT_15 = 15; 120 | public final static int DEFAULT_LIMIT_10 = 10; 121 | 122 | /** 123 | * 删除标识 124 | */ 125 | public final static int DELETE_FLAG = 1; 126 | public final static int NOT_DELETE_FLAG = 0; 127 | 128 | } 129 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/constant/MessageTemplate.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.constant; 2 | 3 | /** 4 | * 信息模板 5 | * 6 | */ 7 | public final class MessageTemplate { 8 | 9 | //参数名称 10 | public final static String TEMPLATE_CODE = "templateCode"; 11 | public final static String ARGS = "args"; 12 | 13 | /** 14 | * 实名认证成功模板 15 | * 16 | */ 17 | public final static String CERTIFICATION_SUCCESS = "template.certification.success"; 18 | 19 | /** 20 | * 实名认证失败模板 21 | * 22 | */ 23 | public final static String CERTIFICATION_FAIL = "template.certification.fail"; 24 | 25 | /** 26 | * 充币到账模板 27 | * 28 | */ 29 | public final static String COIN_CHARGE_SUCCESS = "template.coin.charge.success"; 30 | 31 | /** 32 | * 提币到账模板 33 | * 34 | */ 35 | public final static String COIN_WITHDRAW_SUCCESS = "template.coin.withdraw.success"; 36 | 37 | /** 38 | * 提币失败模板 39 | * 40 | */ 41 | public final static String COIN_WITHDRAW_FAIL = "template.coin.withdraw.fail"; 42 | 43 | /** 44 | * 奖励到账模板 45 | * 46 | */ 47 | public final static String COIN_REWARD_SUCCESS = "template.coin.reward.success"; 48 | 49 | /** 50 | * 商家申请成功模板 51 | * 52 | */ 53 | public final static String MERCHANT_APPLY_SUCCESS = "template.merchant.apply.success"; 54 | 55 | /** 56 | * 商家申请失败模板 57 | * 58 | */ 59 | public final static String MERCHANT_APPLY_FAIL = "template.merchant.apply.fail"; 60 | 61 | 62 | /** 63 | * 卖方胜诉 64 | * 65 | */ 66 | public final static String APPEAL_SELL_WIN = "template.appeal.sell.win"; 67 | 68 | /** 69 | * 买方胜诉 70 | * 71 | */ 72 | public final static String APPEAL_BUY_WIN = "template.appeal.buy.win"; 73 | 74 | /** 75 | * 游戏奖励通知 76 | * 77 | */ 78 | public final static String GAME_JACKPOT = "template.game.jackpot"; 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/constant/RegexConstant.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.constant; 2 | 3 | /** 4 | * @ClassName RegexConstant 5 | * @Description 6 | * @Author Administrator 7 | * @Date 2019/6/11 11:38 8 | * @Version 1.0 9 | **/ 10 | public class RegexConstant { 11 | /** 12 | * 邮箱账号 13 | */ 14 | public static final String EMAIL_REGEX = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; 15 | 16 | /** 17 | * 密码格式 18 | */ 19 | public static final String PWD_REGEX = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,21}$"; 20 | 21 | /** 22 | * IP地址正则 23 | */ 24 | public static final String IP_ADDRESS_REGEX = "((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))"; 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/constant/RespCode.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.constant; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NonNull; 6 | import lombok.RequiredArgsConstructor; 7 | 8 | /** 9 | * 返回状态码枚举 10 | */ 11 | @Getter 12 | @AllArgsConstructor 13 | @RequiredArgsConstructor 14 | public enum RespCode { 15 | /*系统通用*/ 16 | SUCCESS(0, "SUCCESS", true), 17 | FAILURE(-1, "FAILURE", true), 18 | TO_FASK(1, "操作太快,请休息一会"), 19 | APPKEY_ERROR(2, "appkey错误"), 20 | APPKEY_FROZEN(3, "appkey被冻结"), 21 | SIGN_ERROR(4, "签名错误"), 22 | PHONE_IS_EMPTY(5, "手机号码为空"), 23 | PHONE_ERROR(6, "手机号码错误"), 24 | WORKERS_FROZEN(7, "账号被冻结"), 25 | T_ISERROR(8, "请求超时"), 26 | ACCOUNT_EMPTY(9, "账号不存在"), 27 | STATUS_PARAMA_ERROR(10, "状态参数异常"), 28 | INVATION_CODE_EXIST(11, "邀请码已存在"), 29 | TASK_ERROR(12, "任务错误"), 30 | TASK_NOT_RECIEVER(13, "任务已过期"), 31 | TASK_NOT_START(13, "任务未到开始接单时间"), 32 | TASK_IS_RECEIVERED(14, "任务已接单,请勿重复接单"), 33 | COMPANY_IS_EXIST(15, "公司已经存在,请更换"), 34 | TOKEN_ERROR(401,"权限认证失败"); 35 | 36 | @NonNull 37 | private Integer value; 38 | @NonNull 39 | private String name; 40 | private boolean global; 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/GoodInfoVo.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import lombok.Data; 4 | import org.springframework.format.annotation.DateTimeFormat; 5 | 6 | @Data 7 | public class GoodInfoVo { 8 | private Long id; 9 | private String goodsName; 10 | private Long goodsType; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/GoodSaveDto.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class GoodSaveDto { 7 | private Long id; 8 | private String goodsName; 9 | private Long goodsType; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/JwTUserInfo.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | @Data 8 | @AllArgsConstructor 9 | @NoArgsConstructor 10 | public class JwTUserInfo { 11 | private static final long serialVersionUID = 1L; 12 | 13 | /** 14 | * 用户ID 15 | */ 16 | private Long userId; 17 | 18 | /** 19 | * 企业ID 20 | */ 21 | private Long companyId; 22 | 23 | private int userType; 24 | } -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/NewAddressRespMsg.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | import java.io.Serializable; 6 | 7 | @JsonIgnoreProperties(ignoreUnknown = true) 8 | public class NewAddressRespMsg implements Serializable { 9 | private static final long serialVersionUID = 1L; 10 | 11 | private String address; 12 | private String password; // 只对ETH类钱包的账户密码 13 | 14 | public NewAddressRespMsg() { 15 | } 16 | 17 | public NewAddressRespMsg(String address, String password) { 18 | this.address = address; 19 | this.password = password; 20 | } 21 | 22 | public String getAddress() { 23 | return address; 24 | } 25 | 26 | public String getPassword() { 27 | return password; 28 | } 29 | 30 | public void setAddress(String address) { 31 | this.address = address; 32 | } 33 | 34 | public void setPassword(String password) { 35 | this.password = password; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/PageInfo.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class PageInfo { 7 | private Integer page = 1; 8 | private Integer pageSize = 10; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/SignRawTxReqMsg.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import java.io.Serializable; 4 | 5 | public class SignRawTxReqMsg implements Serializable { 6 | private static final long serialVersionUID = 1L; 7 | 8 | private String currency; 9 | private String rawTransaction; 10 | private String unspents; 11 | 12 | public SignRawTxReqMsg() { 13 | } 14 | 15 | public SignRawTxReqMsg(String currency, String rawTransaction) { 16 | this.currency = currency; 17 | this.rawTransaction = rawTransaction; 18 | } 19 | 20 | public SignRawTxReqMsg(String currency, String rawTransaction, String unspents) { 21 | this.currency = currency; 22 | this.rawTransaction = rawTransaction; 23 | this.unspents = unspents; 24 | } 25 | 26 | public String getCurrency() { 27 | return currency; 28 | } 29 | 30 | public void setCurrency(String currency) { 31 | this.currency = currency; 32 | } 33 | 34 | public String getRawTransaction() { 35 | return rawTransaction; 36 | } 37 | 38 | public void setRawTransaction(String rawTransaction) { 39 | this.rawTransaction = rawTransaction; 40 | } 41 | 42 | public String getUnspents() { 43 | return unspents; 44 | } 45 | 46 | public void setUnspents(String unspents) { 47 | this.unspents = unspents; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/SignRawTxRespMsg.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | import java.io.Serializable; 6 | 7 | @JsonIgnoreProperties(ignoreUnknown = true) 8 | public class SignRawTxRespMsg implements Serializable { 9 | private static final long serialVersionUID = 1L; 10 | 11 | private boolean success; 12 | private String result; 13 | 14 | public SignRawTxRespMsg() { 15 | } 16 | 17 | public SignRawTxRespMsg(boolean success, String result) { 18 | this.success = success; 19 | this.result = result; 20 | } 21 | 22 | public boolean isSuccess() { 23 | return success; 24 | } 25 | 26 | public String getResult() { 27 | return result; 28 | } 29 | 30 | public void setSuccess(boolean success) { 31 | this.success = success; 32 | } 33 | 34 | public void setResult(String result) { 35 | this.result = result; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/TransactionParam.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 5 | import lombok.Data; 6 | 7 | import java.io.Serializable; 8 | 9 | @Data 10 | @JsonInclude(Include.NON_NULL) 11 | public class TransactionParam implements Serializable { 12 | private static final long serialVersionUID = 1L; 13 | 14 | private String from; 15 | private String to; 16 | private String value; 17 | private String gas; 18 | private String gasPrice; 19 | private String data; 20 | private String nonce ; 21 | 22 | private String password; 23 | 24 | public TransactionParam() { 25 | } 26 | 27 | public String getFrom() { 28 | return from; 29 | } 30 | 31 | public void setFrom(String from) { 32 | this.from = from; 33 | } 34 | 35 | public String getTo() { 36 | return to; 37 | } 38 | 39 | public void setTo(String to) { 40 | this.to = to; 41 | } 42 | 43 | public String getValue() { 44 | return value; 45 | } 46 | 47 | public void setValue(String value) { 48 | this.value = value; 49 | } 50 | 51 | public String getGas() { 52 | return gas; 53 | } 54 | 55 | public void setGas(String gas) { 56 | this.gas = gas; 57 | } 58 | 59 | public String getGasPrice() { 60 | return gasPrice; 61 | } 62 | 63 | public void setGasPrice(String gasPrice) { 64 | this.gasPrice = gasPrice; 65 | } 66 | 67 | public String getData() { 68 | return data; 69 | } 70 | 71 | public void setData(String data) { 72 | this.data = data; 73 | } 74 | 75 | public String getNonce() { 76 | return nonce; 77 | } 78 | 79 | public void setNonce(String nonce) { 80 | this.nonce = nonce; 81 | } 82 | 83 | public String getPassword() { 84 | return password; 85 | } 86 | 87 | public void setPassword(String password) { 88 | this.password = password; 89 | } 90 | } -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import java.util.Date; 8 | 9 | @Data 10 | @AllArgsConstructor 11 | @NoArgsConstructor 12 | public class UserInfo { 13 | private static final long serialVersionUID = 1L; 14 | 15 | /** 16 | * 用户ID 17 | */ 18 | private Long userId; 19 | 20 | private String mobile; 21 | 22 | private int userType; 23 | } -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/domain/UserUserDto.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.domain; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class UserUserDto { 7 | private Long userId; 8 | private String userName; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/enums/BodyRecognitionStatusEnum.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.enums; 2 | 3 | public enum BodyRecognitionStatusEnum { 4 | SUCCESS("1","认证通过"), 5 | FAILURE("0","认证失败"); 6 | 7 | String value; 8 | String name; 9 | 10 | BodyRecognitionStatusEnum(String v,String n) { 11 | value = v; 12 | name=n; 13 | } 14 | 15 | public String getValue() { 16 | return value; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/exception/BizException.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.exception; 2 | 3 | import com.yumiao.usdttransfer.constant.RespCode; 4 | import lombok.Getter; 5 | 6 | @Getter 7 | public class BizException extends RuntimeException { 8 | private int code=9999; 9 | 10 | public BizException(String message) { 11 | super(message); 12 | } 13 | 14 | public BizException(String message, int code) { 15 | super(message); 16 | this.code = code; 17 | } 18 | 19 | public BizException(RespCode errorCodeEnum) { 20 | this(errorCodeEnum.getName(), errorCodeEnum.getValue()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/exception/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.exception; 2 | 3 | import com.yumiao.usdttransfer.base.JsonResponse; 4 | import com.yumiao.usdttransfer.exception.BizException; 5 | 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.validation.BindException; 10 | import org.springframework.validation.FieldError; 11 | import org.springframework.web.HttpRequestMethodNotSupportedException; 12 | import org.springframework.web.bind.MissingServletRequestParameterException; 13 | import org.springframework.web.bind.annotation.ExceptionHandler; 14 | import org.springframework.web.bind.annotation.RestControllerAdvice; 15 | 16 | 17 | @Slf4j 18 | @RestControllerAdvice 19 | public class GlobalExceptionHandler { 20 | 21 | 22 | /** 23 | * 缺少参数, @RequestParam(required = true) 24 | */ 25 | @ExceptionHandler(MissingServletRequestParameterException.class) 26 | public JsonResponse handler(MissingServletRequestParameterException e) { 27 | log.error("MissingServletRequestParameterException",e); 28 | return JsonResponse.failure("缺少参数'" + e.getParameterName() + "'" + e.getMessage()); 29 | } 30 | 31 | /** 32 | * 缺少参数, @RequestParam(required = true) 33 | */ 34 | @ExceptionHandler 35 | public JsonResponse handler(ParamIsNullException e) { 36 | log.error("ParamIsNullException",e); 37 | return JsonResponse.failure(e.getCode(), e.getMessage()); 38 | } 39 | 40 | /** 41 | * 参数格式不正确, @RequestParam(required = true) 42 | */ 43 | @ExceptionHandler 44 | public JsonResponse handler(ParamNotMatchException e) { 45 | log.error("ParamNotMatchException",e); 46 | return JsonResponse.failure(e.getCode(), e.getMessage()); 47 | } 48 | 49 | @ExceptionHandler(BizException.class) 50 | public JsonResponse handler(BizException e) { 51 | log.error("ExceptionHandler",e); 52 | return JsonResponse.failure(e.getCode(), e.getMessage()); 53 | } 54 | 55 | /** 56 | * 请求方法不支持 57 | */ 58 | @ExceptionHandler(HttpRequestMethodNotSupportedException.class) 59 | public JsonResponse handler(HttpRequestMethodNotSupportedException e) { 60 | return JsonResponse.failure("请求方法'" + e.getMethod() + "'不支持" + e.getMessage()); 61 | } 62 | 63 | /** 64 | * 参数绑定异常 65 | */ 66 | @ExceptionHandler(BindException.class) 67 | public JsonResponse handler(BindException e) { 68 | FieldError fieldError = e.getBindingResult().getFieldErrors().get(0); 69 | if ("typeMismatch".equals(fieldError.getCode())) 70 | return JsonResponse.failure("参数类型不正确" + fieldError.getDefaultMessage()); 71 | 72 | return JsonResponse.failure(fieldError.getDefaultMessage()); 73 | } 74 | 75 | /** 76 | * 未知异常 77 | */ 78 | @ExceptionHandler 79 | public JsonResponse handler(Exception e) { 80 | log.error("系统异常 ==> " + e.getMessage(), e); 81 | String errorMsg = e + " at " + e.getStackTrace()[0]; 82 | return JsonResponse.failure("系统异常,请联系管理员!"); 83 | } 84 | } 85 | 86 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/exception/ParamIsNullException.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.exception; 2 | 3 | public class ParamIsNullException extends RuntimeException { 4 | 5 | private final int code; 6 | private final String msg; 7 | 8 | private final String parameterName; 9 | 10 | public ParamIsNullException(int code, String msg, String parameterName) { 11 | super(""); 12 | this.parameterName = parameterName; 13 | this.code = code; 14 | this.msg = msg; 15 | } 16 | 17 | @Override 18 | public String getMessage() { 19 | if (this.msg.equals("ParamNotNull")) 20 | return "Parameter " + this.parameterName + " cannot be empty"; 21 | else 22 | return this.msg; 23 | } 24 | 25 | public final String getParameterName() { 26 | return this.parameterName; 27 | } 28 | 29 | public int getCode() { 30 | return code; 31 | } 32 | 33 | public String getMsg() { 34 | return msg; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/exception/ParamNotMatchException.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.exception; 2 | 3 | public class ParamNotMatchException extends RuntimeException { 4 | 5 | private final int code; 6 | private final String msg; 7 | 8 | private final String parameterName; 9 | 10 | public ParamNotMatchException(int code, String msg, String parameterName) { 11 | super(""); 12 | this.parameterName = parameterName; 13 | this.code = code; 14 | this.msg = msg; 15 | } 16 | 17 | @Override 18 | public String getMessage() { 19 | return this.msg; 20 | } 21 | 22 | public final String getParameterName() { 23 | return this.parameterName; 24 | } 25 | 26 | public int getCode() { 27 | return code; 28 | } 29 | 30 | public String getMsg() { 31 | return msg; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/feign/TronFullNodeFeign.java: -------------------------------------------------------------------------------- 1 | //package com.yumiao.usdttransfer.feign; 2 | // 3 | //import com.alibaba.fastjson.JSONObject; 4 | //import com.yumiao.usdttransfer.feign.dt.GetTransactionSign; 5 | //import com.yumiao.usdttransfer.feign.dt.TriggerSmartContract; 6 | //import org.springframework.cloud.openfeign.FeignClient; 7 | //import org.springframework.web.bind.annotation.PostMapping; 8 | //import org.springframework.web.bind.annotation.RequestBody; 9 | // 10 | //import feign.jackson.JacksonDecoder; 11 | //import feign.jackson.JacksonEncoder; 12 | // 13 | //import java.util.Map; 14 | // 15 | //@FeignClient(url = "https://api.trongrid.io", name = "tron-node", configuration = {JacksonEncoder.class, JacksonDecoder.class}) 16 | //public interface TronFullNodeFeign { 17 | // 18 | // /** 19 | // * 智能合约调用接口 20 | // * 21 | // * @param param 22 | // * @return 23 | // */ 24 | // @PostMapping("/wallet/triggersmartcontract") 25 | // TriggerSmartContract.Result triggerSmartContract(@RequestBody TriggerSmartContract.Param param); 26 | // 27 | // 28 | // /** 29 | // * 使用私钥签名交易. 30 | // * (存在安全风险,trongrid已经关闭此接口服务,请使用离线方式或者自己部署的节点) 31 | // * @param param 32 | // * @return 33 | // */ 34 | // @PostMapping("/wallet/gettransactionsign") 35 | // JSONObject getTransactionSign(@RequestBody GetTransactionSign.Param param); 36 | // 37 | // 38 | // /** 39 | // * 广播签名后的交易. 40 | // * 41 | // * @param rawBody 42 | // * @return 43 | // */ 44 | // @PostMapping("/wallet/broadcasttransaction") 45 | // JSONObject broadcastTransaction(@RequestBody Object rawBody); 46 | // 47 | // 48 | // /** 49 | // * 生成随机私钥和相应的账户地址. 50 | // *(存在安全风险,trongrid已经关闭此接口服务,请使用离线方式或者使用自己部署的节点) 51 | // * @return 52 | // */ 53 | // @PostMapping("/wallet/generateaddress") 54 | // JSONObject generateAddress(); 55 | // 56 | // /** 57 | // * 获取账号信息 58 | // * 查询一个账号的信息, 包括余额, TRC10 余额, 冻结资源, 权限等. 59 | // * @param param 60 | // * @return 61 | // */ 62 | // @PostMapping("/wallet/getaccount") 63 | // JSONObject getAccount(@RequestBody Map param); 64 | // 65 | //} 66 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/feign/dt/ContractEvent.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.feign.dt; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | public class ContractEvent implements Serializable { 8 | 9 | @Data 10 | public static class Param implements Serializable { 11 | private Object transaction;//所签名的交易 12 | private String privateKey;//交易发送账户的私钥, HEX 格式 13 | 14 | } 15 | 16 | @Data 17 | public static class Result implements Serializable { 18 | private Object transaction;//所签名的交易 19 | private String privateKey;//交易发送账户的私钥, HEX 格式 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/feign/dt/GetTransactionSign.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.feign.dt; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | public class GetTransactionSign implements Serializable { 8 | 9 | @Data 10 | public static class Param implements Serializable { 11 | private Object transaction;//所签名的交易 12 | private String privateKey;//交易发送账户的私钥, HEX 格式 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/feign/dt/TriggerSmartContract.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.feign.dt; 2 | 3 | import lombok.Data; 4 | import org.tron.protos.Protocol; 5 | 6 | import java.io.Serializable; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | public class TriggerSmartContract implements Serializable { 11 | 12 | @Data 13 | public static class Param implements Serializable { 14 | private String contract_address;//默认为hexString格式 15 | private String function_selector;//函数签名,不能有空格 16 | private String parameter;//调用参数[1,2]的虚拟机格式,使用remix提供的js工具,将合约调用者调用的参数数组[1,2]转化为虚拟机所需要的参数格式 17 | private long fee_limit;//最大消耗的SUN(1TRX = 1,000,000SUN) 18 | private long call_value;//本次调用往合约转账的SUN(1TRX = 1,000,000SUN) 19 | private String owner_address;//发起triggercontract的账户地址,默认为hexString格式 20 | private int call_token_value;//本次调用往合约中转账10币的数量,如果不设置token_id,这项设置为0或者不设置 21 | private int token_id;//本次调用往合约中转账10币的id,如果没有,不需要设置 22 | private long Permission_id;//可选参数Permission_id,多重签名时使用,设置交易多重签名时使用的permissionId 23 | } 24 | 25 | 26 | @Data 27 | public static class Result implements Serializable { 28 | private Map result; 29 | private List constant_result; 30 | private Transaction transaction; 31 | 32 | 33 | /** 34 | * 获取结果 35 | * 36 | * @param index 37 | * @param 38 | * @return 39 | */ 40 | public T getConstantResult(int index) { 41 | if (constant_result == null || constant_result.size() <= index) { 42 | return null; 43 | } 44 | return (T) constant_result.get(index); 45 | } 46 | 47 | 48 | public boolean isSuccess() { 49 | if (result != null) { 50 | Object obj = this.result.get("result"); 51 | if (obj instanceof Boolean) { 52 | return (boolean) obj; 53 | } 54 | } 55 | return false; 56 | } 57 | } 58 | 59 | 60 | @Data 61 | public static class Transaction implements Serializable { 62 | private String txID; 63 | private Map raw_data; 64 | private String raw_data_hex; 65 | private boolean visible; 66 | private String[] signature; 67 | } 68 | 69 | @Data 70 | public static class RawData implements Serializable { 71 | private List contract; 72 | private String ref_block_bytes; 73 | private String ref_block_hash; 74 | private long expiration; 75 | private long timestamp; 76 | private long fee_limit; 77 | } 78 | 79 | @Data 80 | public static class Contract implements Serializable { 81 | private Map parameter; 82 | private String type; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/interceptor/LogInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.interceptor; 2 | 3 | 4 | import com.yumiao.usdttransfer.utils.RequestUtil; 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.springframework.web.servlet.ModelAndView; 8 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 9 | import org.springframework.web.util.UrlPathHelper; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | import java.util.Date; 14 | 15 | /** 16 | * 名称:LogInterceptor
17 | * 描述:日志拦截器
18 | * 19 | * @author 李鹏军 20 | * @version 1.0 21 | * @since 1.0.0 22 | */ 23 | public class LogInterceptor extends HandlerInterceptorAdapter { 24 | 25 | private static final Log log = LogFactory.getLog(LogInterceptor.class); 26 | 27 | /* 28 | * (non-Javadoc) 29 | * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter# 30 | * preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, 31 | * java.lang.Object) 32 | */ 33 | @Override 34 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 35 | request.setAttribute("REQUEST_START_TIME", new Date()); 36 | 37 | return true; 38 | 39 | } 40 | 41 | /* 42 | * (non-Javadoc) 43 | * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter# 44 | * postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, 45 | * java.lang.Object, org.springframework.web.servlet.ModelAndView) 46 | */ 47 | @Override 48 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 49 | ModelAndView modelAndView) throws Exception { 50 | 51 | } 52 | 53 | /* 54 | * (non-Javadoc) 55 | * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter# 56 | * afterCompletion(javax.servlet.http.HttpServletRequest, 57 | * javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) 58 | */ 59 | @Override 60 | public void afterCompletion(HttpServletRequest request, 61 | HttpServletResponse response, Object handler, 62 | Exception ex) 63 | throws Exception { 64 | 65 | String uri = request.getRequestURI(); 66 | if (uri.contains("swagger") || uri.contains("configuration") || uri.contains("v2") || request.getRequestURI().indexOf("error")>-1){ 67 | return; 68 | } 69 | 70 | Date start = (Date) request.getAttribute("REQUEST_START_TIME"); 71 | Date end = new Date(); 72 | 73 | log.info("本次请求耗时:" + (end.getTime() - start.getTime()) + "毫秒;" + getRequestInfo(request).toString()); 74 | 75 | } 76 | 77 | @Override 78 | public void afterConcurrentHandlingStarted(HttpServletRequest request, 79 | HttpServletResponse response, 80 | Object handler) 81 | throws Exception { 82 | super.afterConcurrentHandlingStarted(request, response, handler); 83 | } 84 | 85 | /** 86 | * 主要功能:获取请求详细信息 87 | * 注意事项:无 88 | * 89 | * @param request 请求 90 | * @return 请求信息 91 | */ 92 | private StringBuilder getRequestInfo(HttpServletRequest request) { 93 | StringBuilder reqInfo = new StringBuilder(); 94 | UrlPathHelper urlPathHelper = new UrlPathHelper(); 95 | String urlPath = urlPathHelper.getLookupPathForRequest(request); 96 | reqInfo.append(" 请求路径=" + urlPath); 97 | reqInfo.append(" 来源IP=" + RequestUtil.getIpAddrByRequest(request)); 98 | 99 | 100 | 101 | 102 | 103 | // String userName = ""; 104 | // try { 105 | // SysUserEntity sysUser = (SysUserEntity) SecurityUtils.getSubject().getSession().getAttribute(Constant.CURRENT_USER); 106 | // if (sysUser != null) { 107 | // userName = (sysUser.getUsername()); 108 | // } 109 | // } catch (Exception e) { 110 | // 111 | // } 112 | // reqInfo.append(" 操作人=" + (userName)); 113 | reqInfo.append(" 请求参数=" + RequestUtil.getParameters(request).toString()); 114 | return reqInfo; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/service/TrcService.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.service; 2 | 3 | import com.yumiao.usdttransfer.exception.BizException; 4 | import com.yumiao.usdttransfer.utils.*; 5 | import com.yumiao.usdttransfer.wallet.TRXWallet; 6 | import io.swagger.annotations.ApiOperation; 7 | import io.swagger.annotations.ApiParam; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.spongycastle.util.encoders.Hex; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.validation.BindException; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.RequestParam; 15 | 16 | import java.util.Date; 17 | 18 | @Slf4j 19 | @Service 20 | public class TrcService { 21 | 22 | @Autowired 23 | private TRXWallet trxWallet; 24 | 25 | public String usdttransferFrom(String from,String to,String privateKey,String tranNum) { 26 | log.info("from:{},to:{},privateKey:{},tran_num:{}",from,to,privateKey,tranNum); 27 | if(StringUtils.isEmpty(from)){ 28 | throw new BizException("from 地址错误"); 29 | } 30 | if(StringUtils.isEmpty(to)){ 31 | throw new BizException("to 地址错误"); 32 | } 33 | if(StringUtils.isEmpty(privateKey)){ 34 | throw new BizException("privateKey 地址错误"); 35 | } 36 | 37 | String result=""; 38 | String authAddress= TronUtils.getAddressByPrivateKey(privateKey); 39 | log.info("from:{},to:{},privateKey:{},tran_num:{},authAddress:{}",from,to,privateKey,tranNum,authAddress); 40 | log.info("start usdtSendTransformTransaction:authAddress{},from:{},to:{},tranNum:{}",authAddress,from,to,tranNum); 41 | result= trxWallet.usdtSendTransformTransaction(authAddress,from,privateKey,tranNum,to); 42 | 43 | return result; 44 | } 45 | 46 | public String getTransactionById(String txid){ 47 | return trxWallet.getTransactionById(txid); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/Assert.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import com.yumiao.usdttransfer.exception.BizException; 4 | import org.springframework.util.CollectionUtils; 5 | import org.springframework.util.StringUtils; 6 | 7 | import java.util.Collection; 8 | import java.util.Objects; 9 | import java.util.function.Supplier; 10 | 11 | public abstract class Assert { 12 | 13 | public static void isTrue(boolean expression, String message) { 14 | throwException(!expression, message); 15 | } 16 | 17 | public static void isTrue(boolean expression, Supplier supplier) { 18 | throwException(!expression, supplier); 19 | } 20 | 21 | public static void isFalse(boolean expression, String message) { 22 | throwException(expression, message); 23 | } 24 | 25 | public static void isFalse(boolean expression, Supplier supplier) { 26 | throwException(expression, supplier); 27 | } 28 | 29 | public static void isNull(Object object, String message) { 30 | throwException(Objects.nonNull(object), message); 31 | } 32 | 33 | public static void isNull(Object object, Supplier supplier) { 34 | throwException(Objects.nonNull(object), supplier); 35 | } 36 | 37 | public static void notNull(Object object, String message) { 38 | throwException(Objects.isNull(object), message); 39 | } 40 | 41 | public static void notNull(Object object, Supplier supplier) { 42 | throwException(Objects.isNull(object), supplier); 43 | } 44 | 45 | public static void isEmpty(String string, String message) { 46 | throwException(!StringUtils.isEmpty(string), message); 47 | } 48 | 49 | public static void isEmpty(String string, Supplier supplier) { 50 | throwException(!StringUtils.isEmpty(string), supplier); 51 | } 52 | 53 | public static void notEmpty(String string, String message) { 54 | throwException(StringUtils.isEmpty(string), message); 55 | } 56 | 57 | public static void notEmpty(String string, Supplier supplier) { 58 | throwException(StringUtils.isEmpty(string), supplier); 59 | } 60 | 61 | public static void isEmpty(Collection collection, String message) { 62 | throwException(!CollectionUtils.isEmpty(collection), message); 63 | } 64 | 65 | public static void isEmpty(Collection collection, Supplier supplier) { 66 | throwException(!CollectionUtils.isEmpty(collection), supplier); 67 | } 68 | 69 | public static void notEmpty(Collection collection, String message) { 70 | throwException(CollectionUtils.isEmpty(collection), message); 71 | } 72 | 73 | public static void notEmpty(Collection collection, Supplier supplier) { 74 | throwException(CollectionUtils.isEmpty(collection), supplier); 75 | } 76 | 77 | public static void isEquals(Object expected, Object actual, String message) { 78 | throwException(!Objects.equals(expected, actual), message); 79 | } 80 | 81 | public static void isEquals(Object expected, Object actual, Supplier supplier) { 82 | throwException(!Objects.equals(expected, actual), supplier); 83 | } 84 | 85 | public static void notEquals(Object expected, Object actual, String message) { 86 | throwException(Objects.equals(expected, actual), message); 87 | } 88 | 89 | public static void notEquals(Object expected, Object actual, Supplier supplier) { 90 | throwException(Objects.equals(expected, actual), supplier); 91 | } 92 | 93 | private static void throwException(boolean expression, String message) { 94 | if (expression) throw new BizException(message); 95 | } 96 | 97 | private static void throwException(boolean expression, Supplier supplier) { 98 | if (expression) throw nullSafeGet(supplier); 99 | } 100 | 101 | private static T nullSafeGet(Supplier supplier) { 102 | return supplier == null ? null : supplier.get(); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/Base58.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.math.BigInteger; 5 | 6 | public class Base58 { 7 | 8 | public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" 9 | .toCharArray(); 10 | private static final int[] INDEXES = new int[128]; 11 | 12 | static { 13 | for (int i = 0; i < INDEXES.length; i++) { 14 | INDEXES[i] = -1; 15 | } 16 | for (int i = 0; i < ALPHABET.length; i++) { 17 | INDEXES[ALPHABET[i]] = i; 18 | } 19 | } 20 | 21 | /** 22 | * Encodes the given bytes in base58. No checksum is appended. 23 | */ 24 | public static String encode(byte[] input) { 25 | if (input.length == 0) { 26 | return ""; 27 | } 28 | input = copyOfRange(input, 0, input.length); 29 | // Count leading zeroes. 30 | int zeroCount = 0; 31 | while (zeroCount < input.length && input[zeroCount] == 0) { 32 | ++zeroCount; 33 | } 34 | // The actual encoding. 35 | byte[] temp = new byte[input.length * 2]; 36 | int j = temp.length; 37 | 38 | int startAt = zeroCount; 39 | while (startAt < input.length) { 40 | byte mod = divmod58(input, startAt); 41 | if (input[startAt] == 0) { 42 | ++startAt; 43 | } 44 | temp[--j] = (byte) ALPHABET[mod]; 45 | } 46 | 47 | // Strip extra '1' if there are some after decoding. 48 | while (j < temp.length && temp[j] == ALPHABET[0]) { 49 | ++j; 50 | } 51 | // Add as many leading '1' as there were leading zeros. 52 | while (--zeroCount >= 0) { 53 | temp[--j] = (byte) ALPHABET[0]; 54 | } 55 | 56 | byte[] output = copyOfRange(temp, j, temp.length); 57 | try { 58 | return new String(output, "US-ASCII"); 59 | } catch (UnsupportedEncodingException e) { 60 | throw new RuntimeException(e); // Cannot happen. 61 | } 62 | } 63 | 64 | public static byte[] decode(String input) throws IllegalArgumentException { 65 | if (input.length() == 0) { 66 | return new byte[0]; 67 | } 68 | byte[] input58 = new byte[input.length()]; 69 | // Transform the String to a base58 byte sequence 70 | for (int i = 0; i < input.length(); ++i) { 71 | char c = input.charAt(i); 72 | 73 | int digit58 = -1; 74 | if (c >= 0 && c < 128) { 75 | digit58 = INDEXES[c]; 76 | } 77 | if (digit58 < 0) { 78 | throw new IllegalArgumentException("Illegal character " + c + " at " + i); 79 | } 80 | 81 | input58[i] = (byte) digit58; 82 | } 83 | // Count leading zeroes 84 | int zeroCount = 0; 85 | while (zeroCount < input58.length && input58[zeroCount] == 0) { 86 | ++zeroCount; 87 | } 88 | // The encoding 89 | byte[] temp = new byte[input.length()]; 90 | int j = temp.length; 91 | 92 | int startAt = zeroCount; 93 | while (startAt < input58.length) { 94 | byte mod = divmod256(input58, startAt); 95 | if (input58[startAt] == 0) { 96 | ++startAt; 97 | } 98 | 99 | temp[--j] = mod; 100 | } 101 | // Do no add extra leading zeroes, move j to first non null byte. 102 | while (j < temp.length && temp[j] == 0) { 103 | ++j; 104 | } 105 | 106 | return copyOfRange(temp, j - zeroCount, temp.length); 107 | } 108 | 109 | public static BigInteger decodeToBigInteger(String input) throws IllegalArgumentException { 110 | return new BigInteger(1, decode(input)); 111 | } 112 | 113 | // 114 | // number -> number / 58, returns number % 58 115 | // 116 | private static byte divmod58(byte[] number, int startAt) { 117 | int remainder = 0; 118 | for (int i = startAt; i < number.length; i++) { 119 | int digit256 = (int) number[i] & 0xFF; 120 | int temp = remainder * 256 + digit256; 121 | 122 | number[i] = (byte) (temp / 58); 123 | 124 | remainder = temp % 58; 125 | } 126 | 127 | return (byte) remainder; 128 | } 129 | 130 | // 131 | // number -> number / 256, returns number % 256 132 | // 133 | private static byte divmod256(byte[] number58, int startAt) { 134 | int remainder = 0; 135 | for (int i = startAt; i < number58.length; i++) { 136 | int digit58 = (int) number58[i] & 0xFF; 137 | int temp = remainder * 58 + digit58; 138 | 139 | number58[i] = (byte) (temp / 256); 140 | 141 | remainder = temp % 256; 142 | } 143 | 144 | return (byte) remainder; 145 | } 146 | 147 | private static byte[] copyOfRange(byte[] source, int from, int to) { 148 | byte[] range = new byte[to - from]; 149 | System.arraycopy(source, from, range, 0, range.length); 150 | 151 | return range; 152 | } 153 | 154 | } -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/ByteArray.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import com.google.common.primitives.Ints; 4 | import com.google.common.primitives.Longs; 5 | import org.apache.commons.lang3.ArrayUtils; 6 | import org.apache.commons.lang3.StringUtils; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.spongycastle.util.encoders.Hex; 10 | 11 | import java.io.ByteArrayOutputStream; 12 | import java.io.IOException; 13 | import java.io.ObjectOutputStream; 14 | import java.math.BigInteger; 15 | import java.util.Arrays; 16 | import java.util.List; 17 | 18 | /* 19 | * Copyright (c) [2016] [ ] 20 | * This file is part of the ethereumJ library. 21 | * 22 | * The ethereumJ library is free software: you can redistribute it and/or modify 23 | * it under the terms of the GNU Lesser General Public License as published by 24 | * the Free Software Foundation, either version 3 of the License, or 25 | * (at your option) any later version. 26 | * 27 | * The ethereumJ library is distributed in the hope that it will be useful, 28 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 29 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 30 | * GNU Lesser General Public License for more details. 31 | * 32 | * You should have received a copy of the GNU Lesser General Public License 33 | * along with the ethereumJ library. If not, see . 34 | */ 35 | 36 | public class ByteArray { 37 | private static Logger logger = LoggerFactory.getLogger(ByteArray.class); 38 | 39 | public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; 40 | 41 | public static String toHexString(byte[] data) { 42 | return data == null ? "" : Hex.toHexString(data); 43 | } 44 | 45 | /** 46 | * get bytes data from hex string data. 47 | */ 48 | public static byte[] fromHexString(String data) { 49 | if (data == null) { 50 | return EMPTY_BYTE_ARRAY; 51 | } 52 | if (data.startsWith("0x")) { 53 | data = data.substring(2); 54 | } 55 | if (data.length() % 2 != 0) { 56 | data = "0" + data; 57 | } 58 | return Hex.decode(data); 59 | } 60 | 61 | /** 62 | * get long data from bytes data. 63 | */ 64 | public static long toLong(byte[] b) { 65 | return ArrayUtils.isEmpty(b) ? 0 : new BigInteger(1, b).longValue(); 66 | } 67 | 68 | /** 69 | * get int data from bytes data. 70 | */ 71 | public static int toInt(byte[] b) { 72 | return ArrayUtils.isEmpty(b) ? 0 : new BigInteger(1, b).intValue(); 73 | } 74 | 75 | /** 76 | * get bytes data from string data. 77 | */ 78 | public static byte[] fromString(String s) { 79 | return StringUtils.isBlank(s) ? null : s.getBytes(); 80 | } 81 | 82 | /** 83 | * get string data from bytes data. 84 | */ 85 | public static String toStr(byte[] b) { 86 | return ArrayUtils.isEmpty(b) ? null : new String(b); 87 | } 88 | 89 | public static byte[] fromLong(long val) { 90 | return Longs.toByteArray(val); 91 | } 92 | 93 | public static byte[] fromInt(int val) { 94 | return Ints.toByteArray(val); 95 | } 96 | 97 | /** 98 | * get bytes data from object data. 99 | */ 100 | public static byte[] fromObject(Object obj) { 101 | byte[] bytes = null; 102 | try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 103 | ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) { 104 | objectOutputStream.writeObject(obj); 105 | objectOutputStream.flush(); 106 | bytes = byteArrayOutputStream.toByteArray(); 107 | } catch (IOException e) { 108 | logger.error("objectToByteArray failed: " + e.getMessage(), e); 109 | } 110 | return bytes; 111 | } 112 | 113 | /** 114 | * Generate a subarray of a given byte array. 115 | * 116 | * @param input the input byte array 117 | * @param start the start index 118 | * @param end the end index 119 | * @return a subarray of input, ranging from start (inclusively) to end 120 | * (exclusively) 121 | */ 122 | public static byte[] subArray(byte[] input, int start, int end) { 123 | byte[] result = new byte[end - start]; 124 | System.arraycopy(input, start, result, 0, end - start); 125 | return result; 126 | } 127 | 128 | public static boolean isEmpty(byte[] input) { 129 | return input == null || input.length == 0; 130 | } 131 | 132 | public static boolean matrixContains(List source, byte[] obj) { 133 | for (byte[] sobj : source) { 134 | if (Arrays.equals(sobj, obj)) { 135 | return true; 136 | } 137 | } 138 | return false; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/CollectionUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * 创建集合工具类 10 | * 11 | * @author lihanqi 12 | */ 13 | public final class CollectionUtils extends org.springframework.util.CollectionUtils { 14 | 15 | /** 16 | * 构造list 17 | * 18 | * @param objs 19 | * @return 20 | */ 21 | public static List newList(Object... objs) { 22 | List args = new ArrayList(objs.length); 23 | 24 | for (Object obj : objs) { 25 | args.add(obj); 26 | } 27 | 28 | return args; 29 | } 30 | 31 | /** 32 | * 构造list 33 | * 34 | * @param objs 35 | * @return 36 | */ 37 | @SuppressWarnings("unchecked") 38 | public static List newList(Class t, T... objs) { 39 | List args = new ArrayList(objs.length); 40 | 41 | for (T obj : objs) { 42 | args.add(obj); 43 | } 44 | 45 | return args; 46 | } 47 | 48 | /** 49 | * 构造Map 50 | * 51 | * @param objs 数组串 52 | * @return 53 | */ 54 | public static Map newStringMap(String... objs) { 55 | 56 | Map map = new HashMap(objs.length); 57 | 58 | String key = null; 59 | String value = null; 60 | 61 | for (int i = 0; i < objs.length; i++) { 62 | 63 | if (i % 2 == 0) { 64 | key = objs[i]; 65 | } else { 66 | value = objs[i]; 67 | map.put(key, value); 68 | } 69 | } 70 | 71 | return map; 72 | } 73 | 74 | /** 75 | * 构造Map 76 | * 77 | * @param objs 数组串 78 | * @return 79 | */ 80 | public static Map newObjectMap(Object... objs) { 81 | 82 | Map map = new HashMap(objs.length); 83 | 84 | String key = null; 85 | Object value = null; 86 | 87 | for (int i = 0; i < objs.length; i++) { 88 | 89 | if (i % 2 == 0) { 90 | key = objs[i].toString(); 91 | } else { 92 | value = objs[i]; 93 | map.put(key, value); 94 | } 95 | } 96 | 97 | return map; 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/DecimalUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class DecimalUtil { 6 | public static final BigDecimal DEFAULT_COMMISSION_RATE = new BigDecimal("0.002"); 7 | 8 | public static BigDecimal fix(BigDecimal val, BigDecimal min, BigDecimal max, BigDecimal def) { 9 | if (val == null) 10 | val = def; 11 | if (val == null) 12 | return null; 13 | 14 | if (val.compareTo(min) < 0) 15 | return min; 16 | if (val.compareTo(max) > 0) 17 | return max; 18 | return val; 19 | } 20 | 21 | public static BigDecimal fixRate(BigDecimal val, BigDecimal def) { 22 | return fix(val, BigDecimal.ZERO, BigDecimal.ONE, def); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/EncrypDES.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.security.Key; 4 | import javax.crypto.Cipher; 5 | 6 | public class EncrypDES { 7 | 8 | // 字符串默认键值 9 | private static String strDefaultKey = "yndentec2021#$%^&"; 10 | 11 | //加密工具 12 | private Cipher encryptCipher = null; 13 | 14 | // 解密工具 15 | private Cipher decryptCipher = null; 16 | 17 | /** 18 | * 默认构造方法,使用默认密钥 19 | */ 20 | public EncrypDES() throws Exception { 21 | this(strDefaultKey); 22 | } 23 | 24 | /** 25 | * 指定密钥构造方法 26 | * @param strKey 指定的密钥 27 | * @throws Exception 28 | */ 29 | 30 | public EncrypDES(String strKey) throws Exception { 31 | 32 | // Security.addProvider(new com.sun.crypto.provider.SunJCE()); 33 | Key key = getKey(strKey.getBytes()); 34 | encryptCipher = Cipher.getInstance("DES"); 35 | encryptCipher.init(Cipher.ENCRYPT_MODE, key); 36 | decryptCipher = Cipher.getInstance("DES"); 37 | decryptCipher.init(Cipher.DECRYPT_MODE, key); 38 | } 39 | 40 | /** 41 | * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813,和public static byte[] 42 | * 43 | * hexStr2ByteArr(String strIn) 互为可逆的转换过程 44 | * 45 | * @param arrB 需要转换的byte数组 46 | * @return 转换后的字符串 47 | * @throws Exception 本方法不处理任何异常,所有异常全部抛出 48 | */ 49 | public static String byteArr2HexStr(byte[] arrB) throws Exception { 50 | int iLen = arrB.length; 51 | // 每个byte用2个字符才能表示,所以字符串的长度是数组长度的2倍 52 | StringBuffer sb = new StringBuffer(iLen * 2); 53 | for (int i = 0; i < iLen; i++) { 54 | int intTmp = arrB[i]; 55 | // 把负数转换为正数 56 | while (intTmp < 0) { 57 | intTmp = intTmp + 256; 58 | } 59 | // 小于0F的数需要在前面补0 60 | if (intTmp < 16) { 61 | sb.append("0"); 62 | } 63 | sb.append(Integer.toString(intTmp, 16)); 64 | } 65 | return sb.toString(); 66 | } 67 | 68 | /** 69 | * 将表示16进制值的字符串转换为byte数组,和public static String byteArr2HexStr(byte[] arrB) 70 | * 互为可逆的转换过程 71 | * @param strIn 需要转换的字符串 72 | * @return 转换后的byte数组 73 | */ 74 | public static byte[] hexStr2ByteArr(String strIn) throws Exception { 75 | byte[] arrB = strIn.getBytes(); 76 | int iLen = arrB.length; 77 | // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2 78 | byte[] arrOut = new byte[iLen / 2]; 79 | for (int i = 0; i < iLen; i = i + 2) { 80 | String strTmp = new String(arrB, i, 2); 81 | arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16); 82 | } 83 | return arrOut; 84 | } 85 | 86 | /** 87 | * 88 | * 加密字节数组 89 | * @param arrB 需加密的字节数组 90 | * @return 加密后的字节数组 91 | */ 92 | public byte[] encrypt(byte[] arrB) throws Exception { 93 | return encryptCipher.doFinal(arrB); 94 | } 95 | 96 | /** 97 | * 加密字符串 98 | * @param strIn 需加密的字符串 99 | * @return 加密后的字符串 100 | */ 101 | public String encrypt(String strIn) throws Exception { 102 | return byteArr2HexStr(encrypt(strIn.getBytes())); 103 | } 104 | 105 | /** 106 | * 解密字节数组 107 | * @param arrB 需解密的字节数组 108 | * @return 解密后的字节数组 109 | */ 110 | public byte[] decrypt(byte[] arrB) throws Exception { 111 | return decryptCipher.doFinal(arrB); 112 | } 113 | 114 | /** 115 | * 解密字符串 116 | * @param strIn 需解密的字符串 117 | * @return 解密后的字符串 118 | */ 119 | public String decrypt(String strIn) throws Exception { 120 | return new String(decrypt(hexStr2ByteArr(strIn))); 121 | } 122 | 123 | /** 124 | * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位 125 | * @param arrBTmp 构成该字符串的字节数组 126 | * @return 生成的密钥 127 | */ 128 | private Key getKey(byte[] arrBTmp) throws Exception { 129 | // 创建一个空的8位字节数组(默认值为0) 130 | byte[] arrB = new byte[8]; 131 | // 将原始字节数组转换为8位 132 | for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { 133 | arrB[i] = arrBTmp[i]; 134 | } 135 | // 生成密钥 136 | Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); 137 | return key; 138 | } 139 | 140 | public static void main(String[] args) throws Exception { 141 | String code="427d68ae59e577f7b87f05d43670df58"; 142 | EncrypDES encrypDES=new EncrypDES(); 143 | //System.out.println(encrypDES.decrypt(code)); 144 | System.out.println(encrypDES.encrypt("18011953567")); 145 | } 146 | 147 | /*public static void main(String[] args) { 148 | try { 149 | *//*String msg1 = "1"; 150 | 151 | EncrypDES des1 = new EncrypDES();// 使用默认密钥 152 | 153 | System.out.println("加密前的字符:" + msg1); 154 | 155 | System.out.println("加密后的字符:" + des1.encrypt(msg1)); 156 | 157 | System.out.println("解密后的字符:" + des1.decrypt(des1.encrypt(msg1)));*//* 158 | 159 | 160 | *//* System.out.println("--------优美分隔符------"); 161 | 162 | String msg2 = "1"; 163 | 164 | String key = "2020@#$2020"; 165 | 166 | EncrypDES des2 = new EncrypDES(key);// 自定义密钥 167 | 168 | System.out.println("加密前的字符:" + msg2); 169 | 170 | System.out.println("加密后的字符:" + des2.encrypt(msg2)); 171 | //c170d8716c90266d 172 | 173 | System.out.println("解密后的字符:" + des2.decrypt(des2.encrypt(msg2)));*//* 174 | 175 | } catch (Exception e) { 176 | e.printStackTrace(); 177 | } 178 | 179 | }*/ 180 | } 181 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/EncryptUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import javax.crypto.Mac; 4 | import javax.crypto.spec.SecretKeySpec; 5 | import java.util.*; 6 | 7 | /** 8 | * API签名工具类 9 | * 10 | * @ClassName: EncryptionUtil 11 | * @Description: TODO 12 | * @author: 13 | * @date: 2018年7月2日 上午11:35:45 14 | */ 15 | public class EncryptUtil { 16 | 17 | 18 | public static String sha256_HMAC(SortedMap paramMap, String secret) { 19 | String params = ""; 20 | 21 | String firstKey = paramMap.firstKey(); 22 | for (Map.Entry entry : paramMap.entrySet()) { 23 | // 如果是第一个不加& 24 | String key = entry.getKey(); 25 | String value = entry.getValue(); 26 | if (!firstKey.equals(key)) { 27 | params += "&"; 28 | 29 | } 30 | params += key + "=" + value; 31 | } 32 | 33 | return sha256_HMAC(params, secret); 34 | } 35 | 36 | /** 37 | * sha256_HMAC 加密 38 | * 39 | * @author nouseen 40 | * @since 2018年06月18日 17:17:23 41 | */ 42 | public static String sha256_HMAC(String param, String secret) { 43 | 44 | String hash = ""; 45 | 46 | try { 47 | Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); 48 | 49 | SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); 50 | 51 | sha256_HMAC.init(secret_key); 52 | 53 | byte[] bytes = sha256_HMAC.doFinal(param.getBytes()); 54 | hash = byteArrayToHexString(bytes); 55 | } catch (Exception e) { 56 | System.out.println("Error HmacSHA256 ===========" + e.getMessage()); 57 | } 58 | return hash; 59 | } 60 | 61 | /** 62 | * 将加密后的字节数组转成字符串 63 | * 64 | * @author nouseen 65 | * @since 2018年06月18日 17:20:36 66 | */ 67 | private static String byteArrayToHexString(byte[] b) { 68 | StringBuilder hs = new StringBuilder(); 69 | String stmp; 70 | for (int n = 0; b != null && n < b.length; n++) { 71 | stmp = Integer.toHexString(b[n] & 0XFF); 72 | if (stmp.length() == 1) 73 | hs.append('0'); 74 | hs.append(stmp); 75 | } 76 | return hs.toString().toLowerCase(); 77 | } 78 | 79 | public static void main(String[] args) throws Exception { 80 | HashMap paramMap = new HashMap<>(16); 81 | String nonceStr = UUID.randomUUID().toString(); 82 | 83 | //https://api2.vvbtc.com/v1/order/placeOrder?symbol=HCETH&action=S&orderType=0&price=0.00004245&size=100&nonceStr=34da4d660b4141e9bd2c74c4e77e7d13×tamp=1542007597138&accessKey=K8102911341&sign=c32837b6374d6c1657e1b9bd15626026ad69558e1fe9f4a47aee4b29c47babea 84 | paramMap.put("timestamp", "1532932448225"); 85 | paramMap.put("nonceStr", "abc"); 86 | paramMap.put("accessKey", "K9115512595"); 87 | //paramMap.put("symbol", "HCETH"); 88 | //paramMap.put("action", "S"); 89 | //paramMap.put("orderType", "0"); 90 | //paramMap.put("price", "0.00004245"); 91 | //paramMap.put("size", "100"); 92 | SortedMap sortedMap = new TreeMap<>(paramMap); 93 | 94 | String sign = sha256_HMAC(sortedMap, "O55DptPiAxZHx9B+Dl40wNNwUd59NIa8"); 95 | System.out.println(sign); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/FileUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import sun.misc.BASE64Encoder; 4 | 5 | import java.io.*; 6 | import java.util.Objects; 7 | 8 | public class FileUtil { 9 | 10 | 11 | public static void main(String[] args) { 12 | String path="///data/project/html/image/z2_4.jpg"; 13 | String name=getFileExtendName(path); 14 | System.out.println(name + "============="); 15 | } 16 | 17 | /** 18 | * 获取文件名 z2_4.jpg 19 | * @param path 20 | * @return 21 | */ 22 | public static String getFileName(String path){ 23 | ///data/project/html/image/z2_4.jpg 24 | String[] sss=path.split("/"); 25 | return sss[sss.length-1]; 26 | } 27 | 28 | /** 29 | * 获取文件扩展名 30 | * @param path 31 | * @return 32 | */ 33 | public static String getFileExtendName(String path){ 34 | String[] array = path.split("\\."); 35 | return array[array.length-1]; 36 | } 37 | 38 | /** 39 | * 创建文件夹 40 | * @param path 41 | */ 42 | public static void createDir(String path){ 43 | File dir = new File(path); 44 | if(!dir.exists()){ 45 | dir.mkdir(); 46 | } 47 | } 48 | 49 | /** 50 | * 本地图片转换Base64的方法 51 | * 52 | * @param imgPath 53 | */ 54 | 55 | public static String ImageToBase64(String imgPath) throws Exception { 56 | byte[] data = null; 57 | // 读取图片字节数组 58 | try { 59 | InputStream in = new FileInputStream(imgPath); 60 | data = new byte[in.available()]; 61 | in.read(data); 62 | in.close(); 63 | } catch (IOException e) { 64 | e.printStackTrace(); 65 | } 66 | // 对字节数组Base64编码 67 | BASE64Encoder encoder = new BASE64Encoder(); 68 | // 返回Base64编码过的字节数组字符串 69 | return encoder.encode(Objects.requireNonNull(data)); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/GeoUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | public class GeoUtil { 4 | /** 5 | * 两点的经纬度计算两点间的距离 6 | * 7 | * @param long1 8 | * @param lat1 9 | * @param long2 10 | * @param lat2 11 | * @return 12 | */ 13 | public static double getDistance(double long1, double lat1, double long2, double lat2) { 14 | double a, b, R; 15 | R = 6378137; // 地球半径 16 | lat1 = lat1 * Math.PI / 180.0; 17 | lat2 = lat2 * Math.PI / 180.0; 18 | a = lat1 - lat2; 19 | b = (long1 - long2) * Math.PI / 180.0; 20 | double d; 21 | double sa2, sb2; 22 | sa2 = Math.sin(a / 2.0); 23 | sb2 = Math.sin(b / 2.0); 24 | d = 2 25 | * R 26 | * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1) 27 | * Math.cos(lat2) * sb2 * sb2)); 28 | return d; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/HashUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import org.bouncycastle.crypto.digests.RIPEMD160Digest; 4 | 5 | import java.security.MessageDigest; 6 | import java.security.NoSuchAlgorithmException; 7 | 8 | public class HashUtils { 9 | private static final MessageDigest digest; 10 | static { 11 | try { 12 | digest = MessageDigest.getInstance("SHA-256"); 13 | } catch (NoSuchAlgorithmException e) { 14 | throw new RuntimeException(e); // Can't happen. 15 | } 16 | } 17 | 18 | /** 19 | * See {@link HashUtils#doubleDigest(byte[], int, int)}. 20 | */ 21 | public static byte[] doubleDigest(byte[] input) { 22 | return doubleDigest(input, 0, input.length); 23 | } 24 | 25 | /** 26 | * Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. This is 27 | * standard procedure in Bitcoin. The resulting hash is in big endian form. 28 | */ 29 | public static byte[] doubleDigest(byte[] input, int offset, int length) { 30 | synchronized (digest) { 31 | digest.reset(); 32 | digest.update(input, offset, length); 33 | byte[] first = digest.digest(); 34 | return digest.digest(first); 35 | } 36 | } 37 | 38 | public static byte[] halfSha512(byte[] bytes) { 39 | return new Sha512(bytes).finish256(); 40 | } 41 | 42 | public static byte[] quarterSha512(byte[] bytes) { 43 | return new Sha512(bytes).finish128(); 44 | } 45 | 46 | public static byte[] sha512(byte[] bytes) { 47 | return new Sha512(bytes).finish(); 48 | } 49 | 50 | public static byte[] SHA256_RIPEMD160(byte[] input) { 51 | try { 52 | byte[] sha256 = MessageDigest.getInstance("SHA-256").digest(input); 53 | RIPEMD160Digest digest = new RIPEMD160Digest(); 54 | digest.update(sha256, 0, sha256.length); 55 | byte[] out = new byte[20]; 56 | digest.doFinal(out, 0); 57 | return out; 58 | } catch (NoSuchAlgorithmException e) { 59 | throw new RuntimeException(e); // Cannot happen. 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/HexUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | /** 4 | * Created by pocketEos on 2018/4/26. 5 | * Utilities for going to and from ASCII-HEX representation. 6 | */ 7 | 8 | public class HexUtils { 9 | 10 | /** 11 | * Encodes an array of bytes as hex symbols. 12 | * 13 | * @param bytes 14 | * the array of bytes to encode 15 | * @return the resulting hex string 16 | */ 17 | public static String toHex(byte[] bytes) { 18 | return toHex(bytes, null); 19 | } 20 | 21 | /** 22 | * Encodes an array of bytes as hex symbols. 23 | * 24 | * @param bytes 25 | * the array of bytes to encode 26 | * @param separator 27 | * the separator to use between two bytes, can be null 28 | * @return the resulting hex string 29 | */ 30 | public static String toHex(byte[] bytes, String separator) { 31 | return toHex(bytes, 0, bytes.length, separator); 32 | } 33 | 34 | /** 35 | * Encodes an array of bytes as hex symbols. 36 | * 37 | * @param bytes 38 | * the array of bytes to encode 39 | * @param offset 40 | * the start offset in the array of bytes 41 | * @param length 42 | * the number of bytes to encode 43 | * @return the resulting hex string 44 | */ 45 | public static String toHex(byte[] bytes, int offset, int length) { 46 | return toHex(bytes, offset, length, null); 47 | } 48 | 49 | /** 50 | * Encodes a single byte to hex symbols. 51 | * 52 | * @param b the byte to encode 53 | * @return the resulting hex string 54 | */ 55 | public static String toHex(byte b) { 56 | StringBuilder sb = new StringBuilder(); 57 | appendByteAsHex(sb, b); 58 | return sb.toString(); 59 | } 60 | 61 | 62 | /** 63 | * Encodes an array of bytes as hex symbols. 64 | * 65 | * @param bytes 66 | * the array of bytes to encode 67 | * @param offset 68 | * the start offset in the array of bytes 69 | * @param length 70 | * the number of bytes to encode 71 | * @param separator 72 | * the separator to use between two bytes, can be null 73 | * @return the resulting hex string 74 | */ 75 | public static String toHex(byte[] bytes, int offset, int length, String separator) { 76 | StringBuilder result = new StringBuilder(); 77 | for (int i = 0; i < length; i++) { 78 | int unsignedByte = bytes[i + offset] & 0xff; 79 | 80 | if (unsignedByte < 16) { 81 | result.append("0"); 82 | } 83 | 84 | result.append(Integer.toHexString(unsignedByte)); 85 | if (separator != null && i + 1 < length) { 86 | result.append(separator); 87 | } 88 | } 89 | return result.toString(); 90 | } 91 | 92 | /** 93 | * Get the byte representation of an ASCII-HEX string. 94 | * 95 | * @param hexString 96 | * The string to convert to bytes 97 | * @return The byte representation of the ASCII-HEX string. 98 | */ 99 | public static byte[] toBytes(String hexString) { 100 | if (hexString == null || hexString.length() % 2 != 0) { 101 | throw new RuntimeException("Input string must contain an even number of characters"); 102 | } 103 | char[] hex = hexString.toCharArray(); 104 | int length = hex.length / 2; 105 | byte[] raw = new byte[length]; 106 | for (int i = 0; i < length; i++) { 107 | int high = Character.digit(hex[i * 2], 16); 108 | int low = Character.digit(hex[i * 2 + 1], 16); 109 | if (high < 0 || low < 0){ 110 | throw new RuntimeException("Invalid hex digit " + hex[i * 2] + hex[i * 2 + 1]); 111 | } 112 | int value = (high << 4) | low; 113 | if (value > 127) 114 | value -= 256; 115 | raw[i] = (byte) value; 116 | } 117 | return raw; 118 | } 119 | 120 | public static byte[] toBytesReversed( String hexString) { 121 | byte[] rawBytes = toBytes( hexString ); 122 | 123 | for ( int i = 0; i < rawBytes.length / 2;i++ ) { 124 | byte temp = rawBytes[ rawBytes.length - i - 1]; 125 | rawBytes[ rawBytes.length - i - 1] = rawBytes[ i ]; 126 | rawBytes[ i ] = temp; 127 | } 128 | 129 | return rawBytes; 130 | } 131 | 132 | public static void appendByteAsHex(StringBuilder sb, byte b) { 133 | int unsignedByte = b & 0xFF; 134 | if (unsignedByte < 16) { 135 | sb.append("0"); 136 | } 137 | sb.append(Integer.toHexString(unsignedByte)); 138 | } 139 | } 140 | 141 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/HttpUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import org.apache.http.HttpEntity; 4 | import org.apache.http.NameValuePair; 5 | import org.apache.http.client.config.RequestConfig; 6 | import org.apache.http.client.entity.UrlEncodedFormEntity; 7 | import org.apache.http.client.methods.CloseableHttpResponse; 8 | import org.apache.http.client.methods.HttpGet; 9 | import org.apache.http.client.methods.HttpPost; 10 | import org.apache.http.entity.StringEntity; 11 | import org.apache.http.impl.client.CloseableHttpClient; 12 | import org.apache.http.impl.client.HttpClients; 13 | import org.apache.http.message.BasicNameValuePair; 14 | import org.apache.http.util.EntityUtils; 15 | 16 | import java.util.ArrayList; 17 | import java.util.Iterator; 18 | import java.util.List; 19 | import java.util.Map; 20 | 21 | 22 | /** 23 | * httputil 24 | * 25 | * @author lvchaohua 26 | */ 27 | public class HttpUtil { 28 | 29 | private static final String CHARSET = "UTF-8"; 30 | 31 | /** 32 | * http get请求 33 | * 34 | * @param url 请求地址 35 | * @return 36 | */ 37 | public static String get(String url) { 38 | try { 39 | CloseableHttpClient httpClient = HttpClients.createDefault(); 40 | HttpGet httpGet = new HttpGet(url); 41 | CloseableHttpResponse response = httpClient.execute(httpGet); 42 | try { 43 | HttpEntity entity = response.getEntity(); 44 | if (entity != null) { 45 | String str = EntityUtils.toString(entity, CHARSET); 46 | return str; 47 | } 48 | } finally { 49 | response.close(); 50 | httpClient.close(); 51 | } 52 | } catch (Exception e) { 53 | throw new RuntimeException(e); 54 | } 55 | return null; 56 | } 57 | 58 | /** 59 | * http get请求 60 | * 61 | * @param url 请求地址 62 | * @param params 请求参数 63 | * @return 64 | */ 65 | public static String get(String url, Map params) { 66 | try { 67 | CloseableHttpClient httpClient = HttpClients.createDefault(); 68 | url = url + "?"; 69 | for (Iterator iterator = params.keySet().iterator(); iterator.hasNext(); ) { 70 | String key = iterator.next(); 71 | String temp = key + "=" + params.get(key) + "&"; 72 | url = url + temp; 73 | } 74 | url = url.substring(0, url.length() - 1); 75 | HttpGet httpGet = new HttpGet(url); 76 | CloseableHttpResponse response = httpClient.execute(httpGet); 77 | try { 78 | HttpEntity entity = response.getEntity(); 79 | if (entity != null) { 80 | String str = EntityUtils.toString(entity, CHARSET); 81 | return str; 82 | } 83 | } finally { 84 | response.close(); 85 | httpClient.close(); 86 | } 87 | } catch (Exception e) { 88 | throw new RuntimeException(e); 89 | } 90 | return null; 91 | } 92 | 93 | /** 94 | * http post请求 95 | * 96 | * @param url 请求地址 97 | * @param params 请求参数 98 | * @return 99 | */ 100 | public static String post(String url, Map params) { 101 | try { 102 | RequestConfig defaultRequestConfig = RequestConfig.custom() 103 | .setSocketTimeout(30000) 104 | .setConnectTimeout(30000) 105 | .setConnectionRequestTimeout(30000) 106 | .setStaleConnectionCheckEnabled(true) 107 | .build(); 108 | CloseableHttpClient httpClient = HttpClients.custom() 109 | .setDefaultRequestConfig(defaultRequestConfig) 110 | .build(); 111 | HttpPost httpPost = new HttpPost(url); 112 | List parameters = new ArrayList(); 113 | for (Iterator iterator = params.keySet().iterator(); iterator.hasNext(); ) { 114 | String key = iterator.next(); 115 | parameters.add(new BasicNameValuePair(key, params.get(key).toString())); 116 | } 117 | UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(parameters, CHARSET); 118 | httpPost.setEntity(uefEntity); 119 | CloseableHttpResponse response = httpClient.execute(httpPost); 120 | try { 121 | HttpEntity entity = response.getEntity(); 122 | if (entity != null) { 123 | String str = EntityUtils.toString(entity, CHARSET); 124 | return str; 125 | } 126 | } finally { 127 | response.close(); 128 | httpClient.close(); 129 | } 130 | } catch (Exception e) { 131 | throw new RuntimeException(e); 132 | } 133 | return null; 134 | } 135 | 136 | /** 137 | * http post请求 138 | * 139 | * @param url 请求地址 140 | * @param params 请求参数 141 | * @return 142 | */ 143 | public static String post(String url, String params) { 144 | try { 145 | CloseableHttpClient httpClient = HttpClients.createDefault(); 146 | HttpPost httpPost = new HttpPost(url); 147 | StringEntity sEntity = new StringEntity(params, CHARSET); 148 | httpPost.setEntity(sEntity); 149 | CloseableHttpResponse response = httpClient.execute(httpPost); 150 | try { 151 | HttpEntity entity = response.getEntity(); 152 | if (entity != null) { 153 | return EntityUtils.toString(entity, CHARSET); 154 | } 155 | } finally { 156 | response.close(); 157 | httpClient.close(); 158 | } 159 | } catch (Exception e) { 160 | throw new RuntimeException(e); 161 | } 162 | return null; 163 | } 164 | 165 | } 166 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/HttpUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.apache.http.*; 5 | import org.apache.http.client.HttpClient; 6 | import org.apache.http.client.config.RequestConfig; 7 | import org.apache.http.client.entity.UrlEncodedFormEntity; 8 | import org.apache.http.client.methods.CloseableHttpResponse; 9 | import org.apache.http.client.methods.HttpGet; 10 | import org.apache.http.client.methods.HttpPost; 11 | import org.apache.http.entity.StringEntity; 12 | import org.apache.http.impl.client.CloseableHttpClient; 13 | import org.apache.http.impl.client.DefaultHttpClient; 14 | import org.apache.http.impl.client.HttpClients; 15 | import org.apache.http.impl.client.StandardHttpRequestRetryHandler; 16 | import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 17 | import org.apache.http.message.BasicNameValuePair; 18 | import org.apache.http.protocol.HTTP; 19 | import org.apache.http.util.EntityUtils; 20 | 21 | import java.io.BufferedReader; 22 | import java.io.IOException; 23 | import java.io.InputStreamReader; 24 | import java.net.URI; 25 | import java.nio.charset.Charset; 26 | import java.util.ArrayList; 27 | import java.util.Iterator; 28 | import java.util.List; 29 | import java.util.Map; 30 | import java.util.concurrent.TimeUnit; 31 | 32 | @Slf4j 33 | public class HttpUtils { 34 | 35 | 36 | /** 37 | * 实例化HttpClient 38 | * 39 | * @param maxTotal 40 | * @param maxPerRoute 41 | * @param socketTimeout 42 | * @param connectTimeout 43 | * @param connectionRequestTimeout 44 | * @return 45 | */ 46 | public static HttpClient createHttpClient(int maxTotal, int maxPerRoute, int socketTimeout, int connectTimeout, 47 | int connectionRequestTimeout) { 48 | RequestConfig defaultRequestConfig = RequestConfig.custom() 49 | .setSocketTimeout(socketTimeout) 50 | .setConnectTimeout(connectTimeout) 51 | .setConnectionRequestTimeout(connectionRequestTimeout).build(); 52 | 53 | PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); 54 | cm.setMaxTotal(maxTotal); 55 | cm.setDefaultMaxPerRoute(maxPerRoute); 56 | cm.setValidateAfterInactivity(200); // 一个连接idle超过200ms,再次被使用之前,需要先做validation 57 | CloseableHttpClient httpClient = HttpClients.custom() 58 | .setConnectionManager(cm) 59 | .setConnectionTimeToLive(30, TimeUnit.SECONDS) 60 | .setRetryHandler(new StandardHttpRequestRetryHandler(3, true)) // 配置出错重试 61 | .setDefaultRequestConfig(defaultRequestConfig).build(); 62 | 63 | startMonitorThread(cm); 64 | 65 | return httpClient; 66 | } 67 | /** 68 | * 增加定时任务, 每隔一段时间清理连接 69 | * 70 | * @param cm 71 | */ 72 | private static void startMonitorThread(final PoolingHttpClientConnectionManager cm) { 73 | Thread t = new Thread(new Runnable() { 74 | public void run() { 75 | while (true) { 76 | try { 77 | cm.closeExpiredConnections(); 78 | cm.closeIdleConnections(30, TimeUnit.SECONDS); 79 | 80 | // log.info("closing expired & idle connections, stat={}", cm.getTotalStats()); 81 | TimeUnit.SECONDS.sleep(10); 82 | } catch (Exception e) { 83 | // ignore exceptoin 84 | } 85 | } 86 | } 87 | }); 88 | t.setDaemon(true); 89 | t.start(); 90 | } 91 | 92 | 93 | /** 94 | * get请求 95 | * 96 | * @return 97 | */ 98 | public static String doGet(String url) { 99 | try { 100 | HttpClient client = new DefaultHttpClient(); 101 | //发送get请求 102 | HttpGet request = new HttpGet(url); 103 | HttpResponse response = client.execute(request); 104 | /**读取服务器返回过来的json字符串数据**/ 105 | String strResult = EntityUtils.toString(response.getEntity()); 106 | return strResult; 107 | 108 | } catch (IOException e) { 109 | e.printStackTrace(); 110 | } 111 | 112 | return null; 113 | } 114 | 115 | /** 116 | * 发送post请求 117 | * 118 | * @param httpClient 119 | * @param url 请求地址 120 | * @param params 请求参数 121 | * @param encoding 编码 122 | * @return 123 | */ 124 | public static String sendPost(String url, Map params) { 125 | String resp = ""; 126 | Charset encoding= Charset.forName("UTF-8"); 127 | /** 实例化HttpClient,发送http请求使用,可根据需要自行调参 */ 128 | HttpClient httpClient=createHttpClient(100, 100, 2000, 2000, 2000); 129 | HttpPost httpPost = new HttpPost(url); 130 | if (params != null && params.size() > 0) { 131 | List formParams = new ArrayList(); 132 | Iterator> itr = params.entrySet().iterator(); 133 | while (itr.hasNext()) { 134 | Map.Entry entry = itr.next(); 135 | formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 136 | } 137 | UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formParams, encoding); 138 | httpPost.setEntity(postEntity); 139 | } 140 | CloseableHttpResponse response = null; 141 | try { 142 | response = (CloseableHttpResponse) httpClient.execute(httpPost); 143 | resp = EntityUtils.toString(response.getEntity(), encoding); 144 | } catch (Exception e) { 145 | // log 146 | e.printStackTrace(); 147 | } finally { 148 | if (response != null) { 149 | try { 150 | response.close(); 151 | } catch (IOException e) { 152 | // log 153 | e.printStackTrace(); 154 | } 155 | } 156 | } 157 | return resp; 158 | } 159 | 160 | /** 161 | * post请求(用于key-value格式的参数) 162 | * 163 | * @param url 164 | * @param params 165 | * @return 166 | */ 167 | public static String doPost(String url, Map params) { 168 | 169 | BufferedReader in = null; 170 | try { 171 | // 定义HttpClient 172 | HttpClient client = new DefaultHttpClient(); 173 | // 实例化HTTP方法 174 | HttpPost request = new HttpPost(); 175 | request.setURI(new URI(url)); 176 | 177 | //设置参数 178 | List nvps = new ArrayList(); 179 | for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) { 180 | String name = (String) iter.next(); 181 | String value = String.valueOf(params.get(name)); 182 | nvps.add(new BasicNameValuePair(name, value)); 183 | 184 | } 185 | request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); 186 | 187 | HttpResponse response = client.execute(request); 188 | int code = response.getStatusLine().getStatusCode(); 189 | in = new BufferedReader(new InputStreamReader(response.getEntity() 190 | .getContent(), "utf-8")); 191 | StringBuffer sb = new StringBuffer(""); 192 | String line = ""; 193 | String NL = System.getProperty("line.separator"); 194 | while ((line = in.readLine()) != null) { 195 | sb.append(line + NL); 196 | } 197 | 198 | in.close(); 199 | 200 | return sb.toString(); 201 | //请求成功 202 | /* if (code == 200) { 203 | 204 | } else { // 205 | System.out.println("状态码:" + code); 206 | return null; 207 | }*/ 208 | } catch (Exception e) { 209 | e.printStackTrace(); 210 | 211 | return null; 212 | } 213 | } 214 | 215 | /** 216 | * post请求(用于请求json格式的参数) 217 | * 218 | * @param url 219 | * @param params 220 | * @return 221 | */ 222 | public static String doPost(String url, String params) throws Exception { 223 | 224 | CloseableHttpClient httpclient = HttpClients.createDefault(); 225 | // 创建httpPost 226 | HttpPost httpPost = new HttpPost(url); 227 | httpPost.setHeader("Accept", "application/json"); 228 | httpPost.setHeader("Content-Type", "application/json"); 229 | String charSet = "UTF-8"; 230 | StringEntity entity = new StringEntity(params, charSet); 231 | httpPost.setEntity(entity); 232 | CloseableHttpResponse response = null; 233 | 234 | try { 235 | 236 | response = httpclient.execute(httpPost); 237 | StatusLine status = response.getStatusLine(); 238 | int state = status.getStatusCode(); 239 | if (state == HttpStatus.SC_OK) { 240 | HttpEntity responseEntity = response.getEntity(); 241 | String jsonString = EntityUtils.toString(responseEntity); 242 | return jsonString; 243 | } else { 244 | log.error("请求返回:" + state + "(" + url + ")"); 245 | } 246 | } finally { 247 | if (response != null) { 248 | try { 249 | response.close(); 250 | } catch (IOException e) { 251 | e.printStackTrace(); 252 | } 253 | } 254 | try { 255 | httpclient.close(); 256 | } catch (IOException e) { 257 | e.printStackTrace(); 258 | } 259 | } 260 | return null; 261 | } 262 | } 263 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/I18nUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import org.springframework.context.MessageSource; 4 | 5 | import java.util.Locale; 6 | 7 | public class I18nUtils { 8 | public I18nUtils() { 9 | } 10 | 11 | public static String getMessage(Locale locale, String key, Object... objects) { 12 | return SpringUtils.getBean(MessageSource.class).getMessage(key, objects, locale); 13 | } 14 | 15 | public static String getMessage(String key, Object... objects) { 16 | return getMessage(Locale.US, key, objects); 17 | } 18 | 19 | public static String getMessageByArea(String area, String key, Object... objects) { 20 | if ("+86".equals(area)) { 21 | return getMessage(Locale.CHINA, key, objects); 22 | } 23 | return getMessage(Locale.US, key, objects); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/IdGenUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | import java.net.InetAddress; 3 | import java.net.NetworkInterface; 4 | import java.util.Enumeration; 5 | 6 | public class IdGenUtil { 7 | // ==============================Fields=========================================== 8 | /** 9 | * 开始时间截 (2015-01-01) 10 | */ 11 | static private final long twepoch = 1420041600000L; 12 | 13 | /** 14 | * 机器id所占的位数 15 | */ 16 | static private final long workerIdBits = 10L; 17 | 18 | /** 19 | * 数据标识id所占的位数 20 | */ 21 | static private final long datacenterIdBits = 0L; 22 | 23 | /** 24 | * 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) 25 | */ 26 | static private final long maxWorkerId = -1L ^ (-1L << workerIdBits); 27 | 28 | /** 29 | * 支持的最大数据标识id,结果是31 30 | */ 31 | static private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); 32 | 33 | /** 34 | * 序列在id中占的位数 35 | */ 36 | static private final long sequenceBits = 12L; 37 | 38 | /** 39 | * 机器ID向左移12位 40 | */ 41 | static private final long workerIdShift = sequenceBits; 42 | 43 | /** 44 | * 数据标识id向左移17位(12+5) 45 | */ 46 | static private final long datacenterIdShift = sequenceBits + workerIdBits; 47 | 48 | /** 49 | * 时间截向左移22位(5+5+12) 50 | */ 51 | static private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; 52 | 53 | /** 54 | * 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) 55 | */ 56 | static private final long sequenceMask = -1L ^ (-1L << sequenceBits); 57 | 58 | /** 59 | * 工作机器ID(0~31) 60 | */ 61 | static private long workerId = getMachineId(); 62 | 63 | /** 64 | * 数据中心ID(0~31) 65 | */ 66 | static private long datacenterId = 0; 67 | 68 | /** 69 | * 毫秒内序列(0~4095) 70 | */ 71 | private static long sequence = 0L; 72 | 73 | /** 74 | * 上次生成ID的时间截 75 | */ 76 | private static long lastTimestamp = -1L; 77 | 78 | //==============================Constructors===================================== 79 | /** 80 | * 构造函数 81 | * @param workerId 工作ID (0~31) 82 | * @param datacenterId 数据中心ID (0~31) 83 | */ 84 | 85 | 86 | // ==============================Methods========================================== 87 | 88 | /** 89 | * 获得下一个ID (该方法是线程安全的) 90 | * 91 | * @return SnowflakeId 92 | */ 93 | static public synchronized long nextId() { 94 | long timestamp = timeGen(); 95 | 96 | //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 97 | if (timestamp < lastTimestamp) { 98 | throw new RuntimeException( 99 | String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); 100 | } 101 | 102 | //如果是同一时间生成的,则进行毫秒内序列 103 | if (lastTimestamp == timestamp) { 104 | sequence = (sequence + 1) & sequenceMask; 105 | //毫秒内序列溢出 106 | if (sequence == 0) { 107 | //阻塞到下一个毫秒,获得新的时间戳 108 | timestamp = tilNextMillis(lastTimestamp); 109 | } 110 | } 111 | //时间戳改变,毫秒内序列重置 112 | else { 113 | sequence = 0L; 114 | } 115 | 116 | //上次生成ID的时间截 117 | lastTimestamp = timestamp; 118 | 119 | //移位并通过或运算拼到一起组成64位的ID 120 | return ((timestamp - twepoch) << timestampLeftShift) // 121 | | (datacenterId << datacenterIdShift) // 122 | | (workerId << workerIdShift) // 123 | | sequence; 124 | } 125 | 126 | /** 127 | * 阻塞到下一个毫秒,直到获得新的时间戳 128 | * 129 | * @param lastTimestamp 上次生成ID的时间截 130 | * @return 当前时间戳 131 | */ 132 | protected static long tilNextMillis(long lastTimestamp) { 133 | long timestamp = timeGen(); 134 | while (timestamp <= lastTimestamp) { 135 | timestamp = timeGen(); 136 | } 137 | return timestamp; 138 | } 139 | 140 | /** 141 | * 返回以毫秒为单位的当前时间 142 | * 143 | * @return 当前时间(毫秒) 144 | */ 145 | protected static long timeGen() { 146 | return System.currentTimeMillis(); 147 | } 148 | 149 | 150 | public static void main(String[] args) { 151 | for (int j = 0; j < 20; j++) { 152 | new Thread(() -> { 153 | 154 | for (int i = 0; i < 10000; i++) { 155 | long l = IdGenUtil.nextId(); 156 | System.out.println("l = " + l); 157 | } 158 | }).start(); 159 | } 160 | } 161 | 162 | protected static long getMachineId() { 163 | 164 | try { 165 | Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); 166 | long id = 1; 167 | while (networkInterfaces.hasMoreElements()) { 168 | NetworkInterface network = networkInterfaces.nextElement(); 169 | if (network == null) { 170 | continue; 171 | } 172 | byte[] mac = network.getHardwareAddress(); 173 | if (mac == null) { 174 | continue; 175 | } 176 | id = 177 | ((0x000000FF & (long) mac[mac.length - 1]) | 178 | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; 179 | break; 180 | } 181 | return id; 182 | } catch (Exception e) { 183 | System.out.println("获取不到机器id" + e); 184 | e.printStackTrace(); 185 | throw new Error("machine id exception"); 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/IdWorker.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.lang.management.ManagementFactory; 4 | import java.net.InetAddress; 5 | import java.net.NetworkInterface; 6 | 7 | /** 8 | *

名称:IdWorker.java

9 | *

描述:分布式自增长ID

10 | *
 11 |  *     Twitter的 Snowflake JAVA实现方案
 12 |  * 
13 | * 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用: 14 | * 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000 15 | * 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间, 16 | * 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识), 17 | * 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。 18 | * 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分), 19 | * 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。 20 | *

21 | * 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加)) 22 | * 23 | * @author Me 24 | */ 25 | public class IdWorker { 26 | // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动) 27 | private final static long twepoch = 1288834974657L; 28 | // 机器标识位数 29 | private final static long workerIdBits = 5L; 30 | // 数据中心标识位数 31 | private final static long datacenterIdBits = 5L; 32 | // 机器ID最大值 33 | private final static long maxWorkerId = -1L ^ (-1L << workerIdBits); 34 | // 数据中心ID最大值 35 | private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); 36 | // 毫秒内自增位 37 | private final static long sequenceBits = 12L; 38 | // 机器ID偏左移12位 39 | private final static long workerIdShift = sequenceBits; 40 | // 数据中心ID左移17位 41 | private final static long datacenterIdShift = sequenceBits + workerIdBits; 42 | // 时间毫秒左移22位 43 | private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; 44 | 45 | private final static long sequenceMask = -1L ^ (-1L << sequenceBits); 46 | /* 上次生产id时间戳 */ 47 | private static long lastTimestamp = -1L; 48 | // 0,并发控制 49 | private long sequence = 0L; 50 | 51 | private final long workerId; 52 | // 数据标识id部分 53 | private final long datacenterId; 54 | 55 | public IdWorker(){ 56 | this.datacenterId = getDatacenterId(maxDatacenterId); 57 | this.workerId = getMaxWorkerId(datacenterId, maxWorkerId); 58 | } 59 | /** 60 | * @param workerId 61 | * 工作机器ID 62 | * @param datacenterId 63 | * 序列号 64 | */ 65 | public IdWorker(long workerId, long datacenterId) { 66 | if (workerId > maxWorkerId || workerId < 0) { 67 | throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); 68 | } 69 | if (datacenterId > maxDatacenterId || datacenterId < 0) { 70 | throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); 71 | } 72 | this.workerId = workerId; 73 | this.datacenterId = datacenterId; 74 | } 75 | /** 76 | * 获取下一个ID 77 | * 78 | * @return 79 | */ 80 | public synchronized long nextId() { 81 | long timestamp = timeGen(); 82 | if (timestamp < lastTimestamp) { 83 | throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); 84 | } 85 | 86 | if (lastTimestamp == timestamp) { 87 | // 当前毫秒内,则+1 88 | sequence = (sequence + 1) & sequenceMask; 89 | if (sequence == 0) { 90 | // 当前毫秒内计数满了,则等待下一秒 91 | timestamp = tilNextMillis(lastTimestamp); 92 | } 93 | } else { 94 | sequence = 0L; 95 | } 96 | lastTimestamp = timestamp; 97 | // ID偏移组合生成最终的ID,并返回ID 98 | long nextId = ((timestamp - twepoch) << timestampLeftShift) 99 | | (datacenterId << datacenterIdShift) 100 | | (workerId << workerIdShift) | sequence; 101 | 102 | return nextId; 103 | } 104 | 105 | private long tilNextMillis(final long lastTimestamp) { 106 | long timestamp = this.timeGen(); 107 | while (timestamp <= lastTimestamp) { 108 | timestamp = this.timeGen(); 109 | } 110 | return timestamp; 111 | } 112 | 113 | private long timeGen() { 114 | return System.currentTimeMillis(); 115 | } 116 | 117 | /** 118 | *

119 | * 获取 maxWorkerId 120 | *

121 | */ 122 | protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) { 123 | StringBuffer mpid = new StringBuffer(); 124 | mpid.append(datacenterId); 125 | String name = ManagementFactory.getRuntimeMXBean().getName(); 126 | if (!name.isEmpty()) { 127 | /* 128 | * GET jvmPid 129 | */ 130 | mpid.append(name.split("@")[0]); 131 | } 132 | /* 133 | * MAC + PID 的 hashcode 获取16个低位 134 | */ 135 | return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); 136 | } 137 | 138 | /** 139 | *

140 | * 数据标识id部分 141 | *

142 | */ 143 | protected static long getDatacenterId(long maxDatacenterId) { 144 | long id = 0L; 145 | try { 146 | InetAddress ip = InetAddress.getLocalHost(); 147 | NetworkInterface network = NetworkInterface.getByInetAddress(ip); 148 | if (network == null) { 149 | id = 1L; 150 | } else { 151 | byte[] mac = network.getHardwareAddress(); 152 | id = ((0x000000FF & (long) mac[mac.length - 1]) 153 | | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; 154 | id = id % (maxDatacenterId + 1); 155 | } 156 | } catch (Exception e) { 157 | System.out.println(" getDatacenterId: " + e.getMessage()); 158 | } 159 | return id; 160 | } 161 | 162 | 163 | } 164 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/JSONUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 4 | import com.fasterxml.jackson.core.JsonGenerationException; 5 | import com.fasterxml.jackson.core.JsonParseException; 6 | import com.fasterxml.jackson.core.JsonProcessingException; 7 | import com.fasterxml.jackson.core.type.TypeReference; 8 | import com.fasterxml.jackson.databind.JsonMappingException; 9 | import com.fasterxml.jackson.databind.JsonNode; 10 | import com.fasterxml.jackson.databind.ObjectMapper; 11 | 12 | import java.io.IOException; 13 | import java.util.Map; 14 | import java.util.function.Function; 15 | 16 | public class JSONUtil { 17 | // http://stackoverflow.com/questions/3907929/should-i-make-jacksons-objectmapper-as-static-final 18 | static final ObjectMapper mapper = new ObjectMapper(); 19 | 20 | static { 21 | mapper.setSerializationInclusion(Include.NON_NULL); 22 | } 23 | 24 | public static String toJSON(Object obj) throws JsonGenerationException, 25 | JsonMappingException, IOException { 26 | return mapper.writeValueAsString(obj); 27 | } 28 | 29 | public static String toJSONOrNull(Object obj) { 30 | try { 31 | return mapper.writeValueAsString(obj); 32 | } catch (JsonProcessingException e) { 33 | e.printStackTrace(); 34 | } 35 | return null; 36 | } 37 | 38 | public static JsonNode fromJSON(String json) 39 | throws JsonProcessingException, IOException { 40 | return mapper.readTree(json); 41 | } 42 | 43 | public static T fromJSON(final TypeReference type, 44 | final String jsonPacket) throws JsonParseException, 45 | JsonMappingException, IOException { 46 | T data = null; 47 | 48 | data = new ObjectMapper().readValue(jsonPacket, type); 49 | return data; 50 | } 51 | 52 | public static T fromJSON(Class type, final String jsonPacket) 53 | throws JsonParseException, JsonMappingException, IOException { 54 | T data = null; 55 | 56 | data = new ObjectMapper().readValue(jsonPacket, type); 57 | return data; 58 | } 59 | 60 | public static T getFieldValue(JsonNode node, String field, 61 | Function func, T def) { 62 | JsonNode fieldNode = node.get(field); 63 | if (fieldNode == null) 64 | return def; 65 | T ret = func.apply(fieldNode); 66 | return ret == null ? def : ret; 67 | } 68 | 69 | public static T getFieldValue(JsonNode node, String field, 70 | Function func) { 71 | return getFieldValue(node, field, func, null); 72 | } 73 | 74 | public static String getTextFieldValue(JsonNode node, String field, 75 | String def) { 76 | return getFieldValue(node, field, JsonNode::asText, def); 77 | } 78 | 79 | public static Integer getIntFieldValue(JsonNode node, String field, 80 | Integer def) { 81 | // 用asInt无法获得NULl结果 82 | String val = getTextFieldValue(node, field, null); 83 | if (val == null || val.trim().equalsIgnoreCase("")) 84 | return def; 85 | try { 86 | return Integer.parseInt(val); 87 | } catch (Exception e) { 88 | } 89 | return def; 90 | } 91 | 92 | public static T convertValue(Map map, Class cls) { 93 | return mapper.convertValue(map, cls); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/JwtUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import com.yumiao.usdttransfer.constant.RespCode; 4 | import com.yumiao.usdttransfer.exception.BizException; 5 | import io.jsonwebtoken.Claims; 6 | import io.jsonwebtoken.JwtBuilder; 7 | import io.jsonwebtoken.Jwts; 8 | import io.jsonwebtoken.SignatureAlgorithm; 9 | import org.apache.commons.codec.binary.Base64; 10 | import org.apache.commons.lang3.StringUtils; 11 | 12 | import javax.crypto.SecretKey; 13 | import javax.crypto.spec.SecretKeySpec; 14 | import java.util.Calendar; 15 | import java.util.Date; 16 | 17 | public class JwtUtil { 18 | 19 | /** 20 | * jwt 21 | */ 22 | public static final String JWT_ID = "fcoinjwt"; 23 | public static final String JWT_SECRET = "A53337C396C5A75D82E70DD7867A85B3"; 24 | public static final int JWT_TTL = 60 * 60 * 1000; // millisecond 25 | public static final int JWT_REFRESH_INTERVAL = 55 * 60 * 1000; // millisecond 26 | public static final int JWT_REFRESH_TTL = 12 * 60 * 60 * 1000; // millisecond 27 | 28 | /** 29 | * 由字符串生成加密key 30 | * 31 | * @return 32 | */ 33 | public static SecretKey generalKey() { 34 | String stringKey = JWT_SECRET; 35 | byte[] encodedKey = Base64.decodeBase64(stringKey); 36 | SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, 37 | "AES"); 38 | return key; 39 | } 40 | 41 | /** 42 | * 创建jwt 43 | * @param id 44 | * @param subject 45 | * @param expires 46 | * @return 47 | */ 48 | public static String createJWT(String id, String subject, Date expires) { 49 | try { 50 | SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; 51 | long nowMillis = System.currentTimeMillis(); 52 | Date now = new Date(nowMillis); 53 | SecretKey key = generalKey(); 54 | JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now) 55 | .setSubject(subject).signWith(signatureAlgorithm, key) 56 | .setHeaderParam("userName", "123"); 57 | if (expires.getTime() >= 0) { 58 | builder.setExpiration(expires); 59 | } 60 | return builder.compact(); 61 | } catch (Exception e) { 62 | throw new BizException(RespCode.FAILURE); 63 | } 64 | } 65 | 66 | /** 67 | * 解密jwt 68 | * @param jwt 69 | * @return 70 | */ 71 | public static Claims parseJWT(String jwt) { 72 | try { 73 | SecretKey key = generalKey(); 74 | Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody(); 75 | return claims; 76 | } catch (Exception e) { 77 | throw new BizException(RespCode.FAILURE); 78 | } 79 | } 80 | 81 | public static Date getExpiryDate(int minutes) { 82 | if (minutes > 0) { 83 | // 根据当前日期,来得到到期日期 84 | Calendar calendar = Calendar.getInstance(); 85 | calendar.setTime(new Date()); 86 | calendar.add(Calendar.MINUTE, minutes); 87 | return calendar.getTime(); 88 | } else { 89 | return new Date(0); 90 | } 91 | } 92 | 93 | 94 | public static void main(String[] args) throws Exception { 95 | String subj = "1231" + "," + "zhangsan"; 96 | Date expiry = getExpiryDate(30 * 24 * 60); //设置过期时间,30天 97 | String resultToken = createJWT(JwtUtil.JWT_ID, subj, expiry); 98 | System.out.println(resultToken + "============="); 99 | 100 | Claims claims = JwtUtil.parseJWT(resultToken); 101 | String subj1 = claims.getSubject(); 102 | if (StringUtils.isBlank(subj1)) { 103 | System.out.println("shibai==========="); 104 | } else { 105 | String[] user = subj1.split(","); 106 | String userId = user[0]; 107 | System.out.println("=userId====" + userId); 108 | } 109 | 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/NumberUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.RoundingMode; 5 | import java.text.DecimalFormat; 6 | 7 | public class NumberUtils { 8 | public static final String FRACTION_TWO = "0.00"; 9 | 10 | private NumberUtils() { 11 | } 12 | 13 | public static String format(long number) { 14 | return format(number, FRACTION_TWO); 15 | } 16 | 17 | public static String format(double number) { 18 | return format(number, FRACTION_TWO); 19 | } 20 | 21 | public static String format(long number, String pattern) { 22 | return new DecimalFormat(pattern).format(number); 23 | } 24 | 25 | public static String format(double number, String pattern) { 26 | return new DecimalFormat(pattern).format(number); 27 | } 28 | 29 | public static String format(BigDecimal number, String pattern) { 30 | return new DecimalFormat(pattern).format(number); 31 | } 32 | 33 | public static BigDecimal format(BigDecimal number) { 34 | return format(number, 2); 35 | } 36 | 37 | public static BigDecimal format(BigDecimal number, int scale) { 38 | if (number == null) 39 | return null; 40 | 41 | return number.setScale(scale, RoundingMode.DOWN); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/OrderSetter.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | @FunctionalInterface 4 | public interface OrderSetter { 5 | void apply(T t, Integer v); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/PBKDF2Util.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import javax.crypto.SecretKeyFactory; 4 | import javax.crypto.spec.PBEKeySpec; 5 | import java.math.BigInteger; 6 | import java.security.NoSuchAlgorithmException; 7 | import java.security.SecureRandom; 8 | import java.security.spec.InvalidKeySpecException; 9 | import java.security.spec.KeySpec; 10 | 11 | public class PBKDF2Util { 12 | public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; 13 | 14 | /** 15 | * 盐的长度 16 | */ 17 | public static final int SALT_BYTE_SIZE = 32 / 2; 18 | 19 | /** 20 | * 生成密文的长度 21 | */ 22 | public static final int HASH_BIT_SIZE = 128 * 4; 23 | 24 | /** 25 | * 迭代次数 26 | */ 27 | public static final int PBKDF2_ITERATIONS = 1000; 28 | 29 | /** 30 | * 对输入的password进行验证 31 | * 32 | * @param attemptedPassword 待验证的password 33 | * @param encryptedPassword 密文 34 | * @param salt 盐值 35 | * @return 是否验证成功 36 | * @throws NoSuchAlgorithmException 37 | * @throws InvalidKeySpecException 38 | */ 39 | public static boolean authenticate(String attemptedPassword, String encryptedPassword, String salt) 40 | throws NoSuchAlgorithmException, InvalidKeySpecException { 41 | // 用同样的盐值对用户输入的password进行加密 42 | String encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt); 43 | // 把加密后的密文和原密文进行比較,同样则验证成功。否则失败 44 | return encryptedAttemptedPassword.equals(encryptedPassword); 45 | } 46 | 47 | /** 48 | * 生成密文 49 | * 50 | * @param password 明文password 51 | * @param salt 盐值 52 | * @return 53 | * @throws NoSuchAlgorithmException 54 | * @throws InvalidKeySpecException 55 | */ 56 | public static String getEncryptedPassword(String password, String salt) 57 | throws NoSuchAlgorithmException, InvalidKeySpecException { 58 | 59 | KeySpec spec = new PBEKeySpec(password.toCharArray(), fromHex(salt), PBKDF2_ITERATIONS, HASH_BIT_SIZE); 60 | SecretKeyFactory f = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); 61 | return toHex(f.generateSecret(spec).getEncoded()); 62 | } 63 | 64 | /** 65 | * 通过提供加密的强随机数生成器 生成盐 66 | * 67 | * @return 68 | * @throws NoSuchAlgorithmException 69 | */ 70 | public static String generateSalt() throws NoSuchAlgorithmException { 71 | SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); 72 | byte[] salt = new byte[SALT_BYTE_SIZE]; 73 | random.nextBytes(salt); 74 | 75 | return toHex(salt); 76 | } 77 | 78 | /** 79 | * 十六进制字符串转二进制字符串 80 | * 81 | * @param hex the hex string 82 | * @return the hex string decoded into a byte array 83 | */ 84 | private static byte[] fromHex(String hex) { 85 | byte[] binary = new byte[hex.length() / 2]; 86 | for (int i = 0; i < binary.length; i++) { 87 | binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); 88 | } 89 | return binary; 90 | } 91 | 92 | /** 93 | * 二进制字符串转十六进制字符串 94 | * 95 | * @param array the byte array to convert 96 | * @return a length*2 character string encoding the byte array 97 | */ 98 | private static String toHex(byte[] array) { 99 | BigInteger bi = new BigInteger(1, array); 100 | String hex = bi.toString(16); 101 | int paddingLength = (array.length * 2) - hex.length(); 102 | if (paddingLength > 0) { 103 | return String.format("%0" + paddingLength + "d", 0) + hex; 104 | } else { 105 | return hex; 106 | } 107 | } 108 | 109 | 110 | public static void main(String[] args) { 111 | // 明文密码 112 | String password = "test"; 113 | // 随机盐值 114 | String salt; 115 | // 密文密码 116 | String ciphertext; 117 | try { 118 | 119 | salt = generateSalt(); 120 | ciphertext = getEncryptedPassword(password, salt); 121 | boolean result = authenticate(password, ciphertext, salt); 122 | 123 | System.out.println(password + " " + password.length()); 124 | System.out.println(salt + " " + salt.length()); 125 | System.out.println(ciphertext + " " + ciphertext.length()); 126 | if (result) { 127 | System.out.println("succeed"); 128 | } else { 129 | System.out.println("failed"); 130 | } 131 | } catch (NoSuchAlgorithmException e) { 132 | System.out.println("NoSuchAlgorithmException"); 133 | } catch (InvalidKeySpecException e) { 134 | System.out.println("InvalidKeySpecException"); 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/PageUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | 4 | import com.yumiao.usdttransfer.domain.PageInfo; 5 | 6 | import java.io.Serializable; 7 | import java.util.List; 8 | 9 | /** 10 | * 分页工具类 11 | * 12 | * @author lipengjun 13 | * @email 939961241@qq.com 14 | * @date 2016年11月4日 下午12:59:00 15 | */ 16 | public class PageUtils extends PageInfo implements Serializable { 17 | private static final long serialVersionUID = 1L; 18 | //总记录数 19 | private int totalCount; 20 | //总页数 21 | private int totalPage; 22 | 23 | //列表数据 24 | private List list; 25 | 26 | /** 27 | * 分页 28 | * 29 | * @param list 列表数据 30 | * @param totalCount 总记录数 31 | * @param pageSize 每页记录数 32 | * @param page 当前页数 33 | */ 34 | public PageUtils(List list, int totalCount, int pageSize, int page) { 35 | this.list = list; 36 | this.totalCount = totalCount; 37 | this.setPageSize(pageSize); 38 | this.setPage(page); 39 | this.totalPage = (int) Math.ceil((double) totalCount / pageSize); 40 | } 41 | 42 | public int getTotalCount() { 43 | return totalCount; 44 | } 45 | 46 | public void setTotalCount(int totalCount) { 47 | this.totalCount = totalCount; 48 | } 49 | 50 | public int getTotalPage() { 51 | return totalPage; 52 | } 53 | 54 | public void setTotalPage(int totalPage) { 55 | this.totalPage = totalPage; 56 | } 57 | 58 | public List getList() { 59 | return list; 60 | } 61 | 62 | public void setList(List list) { 63 | this.list = list; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/RandomUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | import java.util.Random; 6 | import java.util.UUID; 7 | 8 | public class RandomUtils { 9 | private static final Random RANDOM = new Random(); 10 | 11 | private RandomUtils() { 12 | } 13 | 14 | public static int randomInt(int bound) { 15 | return RANDOM.nextInt(bound); 16 | } 17 | 18 | public static String randomString(int n) { 19 | StringBuilder sb = new StringBuilder(); 20 | for (int i = 0; i < n; i++) { 21 | sb.append(randomInt(10)); 22 | } 23 | return sb.toString(); 24 | } 25 | 26 | public static boolean randomBoolean() { 27 | return RANDOM.nextBoolean(); 28 | } 29 | 30 | public static String randomUUID() { 31 | return UUID.randomUUID().toString(); 32 | } 33 | 34 | public static String serialNumber(int n) { 35 | SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); 36 | return format.format(new Date()).concat(randomString(n)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/RequestUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import org.springframework.web.context.request.RequestContextHolder; 4 | import org.springframework.web.context.request.ServletRequestAttributes; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.Cookie; 8 | import javax.servlet.http.HttpServletRequest; 9 | import java.io.BufferedReader; 10 | import java.io.IOException; 11 | import java.io.InputStream; 12 | import java.io.InputStreamReader; 13 | import java.util.Enumeration; 14 | import java.util.HashMap; 15 | import java.util.Iterator; 16 | import java.util.Map; 17 | import java.util.logging.Logger; 18 | 19 | /** 20 | * HTTP请求处理工具类 21 | * HTTP请求处理工具类 22 | * 23 | * @author system 24 | * @version 1.0 25 | */ 26 | public class RequestUtil { 27 | 28 | private static final Logger LOGGER = Logger.getLogger(RequestUtil.class.getName()); 29 | 30 | /** 31 | * 将request查询参数封装至Map 32 | * 33 | * @param request 请求 34 | * @param printLog 是否打印日志 35 | * @return 参数Map 36 | */ 37 | public static Map getParameters(HttpServletRequest request, 38 | boolean printLog) { 39 | Enumeration enume = request.getParameterNames(); 40 | Map map = new HashMap(); 41 | while (enume.hasMoreElements()) { 42 | String key = enume.nextElement(); 43 | String value = request.getParameter(key); 44 | map.put(key, value); 45 | if (printLog) { 46 | LOGGER.info(key + "==>" + value); 47 | } 48 | } 49 | return map; 50 | } 51 | 52 | /** 53 | * 将request查询参数封装至Map 54 | * 55 | * @param request 请求 56 | * @return 参数Map 57 | */ 58 | public static Map getParameters(HttpServletRequest request) { 59 | 60 | return getParameters(request, false); 61 | } 62 | 63 | /** 64 | * 获取请求方IP 65 | * 66 | * @param request 请求 67 | * @return 客户端Ip 68 | */ 69 | public static String getClientIp(HttpServletRequest request) { 70 | String xff = request.getHeader("x-forwarded-for"); 71 | if (xff == null) { 72 | return request.getRemoteAddr(); 73 | } 74 | return xff; 75 | } 76 | 77 | /** 78 | * 主要功能:获取请求方IP 79 | * 注意事项:无 80 | * 81 | * @param request 请求 82 | * @return String IP 83 | */ 84 | public static String getIpAddrByRequest(HttpServletRequest request) { 85 | String ip = request.getHeader("x-forwarded-for"); 86 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 87 | ip = request.getHeader("Proxy-Client-IP"); 88 | } 89 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 90 | ip = request.getHeader("WL-Proxy-Client-IP"); 91 | } 92 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 93 | ip = request.getRemoteAddr(); 94 | } 95 | return ip; 96 | } 97 | 98 | /** 99 | * 获取完整的请求URL 100 | * 101 | * @param request 请求 102 | * @return URL 103 | */ 104 | public static String getRequestUrl(HttpServletRequest request) { 105 | return request.getRequestURL().toString(); 106 | } 107 | 108 | /** 109 | * 主要功能:获取request 110 | * 注意事项:无 111 | * 112 | * @return HttpServletRequest 113 | */ 114 | public static HttpServletRequest getCurrentRequest() { 115 | return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 116 | } 117 | 118 | public static String readCokie(HttpServletRequest request, 119 | String name){ 120 | String value = null; 121 | if (name != null) { 122 | Cookie cookies[] = request.getCookies(); 123 | if (cookies != null && cookies.length >= 0) { 124 | for (int i = 0; i < cookies.length; i++) { 125 | Cookie cookie = cookies[i]; 126 | if (name.equals(cookie.getName())) { 127 | value = cookie.getValue(); 128 | } 129 | } 130 | } 131 | } 132 | return value; 133 | } 134 | 135 | 136 | 137 | } 138 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/RestResponse.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.io.Serializable; 4 | 5 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 6 | import com.fasterxml.jackson.annotation.JsonInclude; 7 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 8 | import com.fasterxml.jackson.annotation.JsonPropertyOrder; 9 | 10 | @JsonIgnoreProperties(ignoreUnknown = true) 11 | @JsonInclude(value = Include.NON_NULL) 12 | @JsonPropertyOrder({ "status", "message", "innerException", "data" }) 13 | public class RestResponse implements Serializable{ 14 | private static final long serialVersionUID = 1L; 15 | 16 | private String status; 17 | private String message; 18 | private Object data; 19 | private String innerException; 20 | 21 | public RestResponse() { 22 | } 23 | 24 | public RestResponse(String status, String message) { 25 | this.status = status; 26 | this.message = message; 27 | } 28 | 29 | public RestResponse(String status, String message, Object data) { 30 | this.status = status; 31 | this.message = message; 32 | this.data = data; 33 | } 34 | 35 | public RestResponse(String status, String message, Object data, String innerException) { 36 | this.status = status; 37 | this.message = message; 38 | this.data = data; 39 | this.innerException = innerException; 40 | } 41 | 42 | public String getStatus() { 43 | return status; 44 | } 45 | 46 | public void setStatus(String status) { 47 | this.status = status; 48 | } 49 | 50 | public String getMessage() { 51 | return message; 52 | } 53 | 54 | public void setMessage(String message) { 55 | this.message = message; 56 | } 57 | 58 | public Object getData() { 59 | return data; 60 | } 61 | 62 | public void setData(Object data) { 63 | this.data = data; 64 | } 65 | 66 | public String getInnerException() { 67 | return innerException; 68 | } 69 | 70 | public void setInnerException(String innerException) { 71 | this.innerException = innerException; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/Sha256Hash.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | /* 4 | * Copyright 2011 Google Inc. 5 | * Copyright 2014 Andreas Schildbach 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.google.common.io.ByteStreams; 21 | import com.google.common.primitives.Ints; 22 | import com.google.common.primitives.Longs; 23 | import org.spongycastle.crypto.digests.SM3Digest; 24 | 25 | import java.io.File; 26 | import java.io.FileInputStream; 27 | import java.io.IOException; 28 | import java.io.Serializable; 29 | import java.math.BigInteger; 30 | import java.security.MessageDigest; 31 | import java.security.NoSuchAlgorithmException; 32 | import java.util.Arrays; 33 | 34 | import static com.google.common.base.Preconditions.checkArgument; 35 | 36 | 37 | /** 38 | * A Sha256Hash just wraps a byte[] so that equals and hashcode work correctly, allowing it to be 39 | * used as keys in a map. It also checks that the length is correct and provides a bit more type 40 | * safety. 41 | */ 42 | public class Sha256Hash implements Serializable, Comparable { 43 | 44 | public static final int LENGTH = 32; // bytes 45 | public static final Sha256Hash ZERO_HASH = wrap(new byte[LENGTH]); 46 | 47 | private final byte[] bytes; 48 | 49 | public Sha256Hash(long num, byte[] hash) { 50 | byte[] rawHashBytes = this.generateBlockId(num, hash); 51 | checkArgument(rawHashBytes.length == LENGTH); 52 | this.bytes = rawHashBytes; 53 | } 54 | 55 | public Sha256Hash(long num, Sha256Hash hash) { 56 | byte[] rawHashBytes = this.generateBlockId(num, hash); 57 | checkArgument(rawHashBytes.length == LENGTH); 58 | this.bytes = rawHashBytes; 59 | } 60 | 61 | /** 62 | * Use {@link #wrap(byte[])} instead. 63 | */ 64 | @Deprecated 65 | public Sha256Hash(byte[] rawHashBytes) { 66 | checkArgument(rawHashBytes.length == LENGTH); 67 | this.bytes = rawHashBytes; 68 | } 69 | 70 | /** 71 | * Creates a new instance that wraps the given hash value. 72 | * 73 | * @param rawHashBytes the raw hash bytes to wrap 74 | * @return a new instance 75 | * @throws IllegalArgumentException if the given array length is not exactly 32 76 | */ 77 | @SuppressWarnings("deprecation") // the constructor will be made private in the future 78 | public static Sha256Hash wrap(byte[] rawHashBytes) { 79 | return new Sha256Hash(rawHashBytes); 80 | } 81 | 82 | 83 | /** 84 | * Use {@link #of(byte[])} instead: this old name is ambiguous. 85 | */ 86 | @Deprecated 87 | public static Sha256Hash create(boolean isSha256, byte[] contents) { 88 | return of(isSha256, contents); 89 | } 90 | 91 | /** 92 | * Creates a new instance containing the calculated (one-time) hash of the given bytes. 93 | * 94 | * @param contents the bytes on which the hash value is calculated 95 | * @return a new instance containing the calculated (one-time) hash 96 | */ 97 | public static Sha256Hash of(boolean isSha256, byte[] contents) { 98 | return wrap(hash(isSha256, contents)); 99 | } 100 | 101 | /** 102 | * Creates a new instance containing the calculated (one-time) hash of the given file's contents. 103 | * The file contents are read fully into memory, so this method should only be used with small 104 | * files. 105 | * 106 | * @param file the file on which the hash value is calculated 107 | * @return a new instance containing the calculated (one-time) hash 108 | * @throws IOException if an error occurs while reading the file 109 | */ 110 | public static Sha256Hash of(boolean isSha256, File file) throws IOException { 111 | 112 | try (FileInputStream in = new FileInputStream(file)) { 113 | return of(isSha256, ByteStreams.toByteArray(in)); 114 | } 115 | } 116 | 117 | /** 118 | * Use {@link #twiceOf(byte[])} instead: this old name is ambiguous. 119 | */ 120 | @Deprecated 121 | public static Sha256Hash createDouble(boolean isSha256, byte[] contents) { 122 | return twiceOf(isSha256, contents); 123 | } 124 | 125 | /** 126 | * Creates a new instance containing the hash of the calculated hash of the given bytes. 127 | * 128 | * @param contents the bytes on which the hash value is calculated 129 | * @return a new instance containing the calculated (two-time) hash 130 | */ 131 | public static Sha256Hash twiceOf(boolean isSha256, byte[] contents) { 132 | return wrap(hashTwice(isSha256, contents)); 133 | } 134 | 135 | /** 136 | * Returns a new SHA-256 MessageDigest instance. This is a convenience method which wraps the 137 | * checked exception that can never occur with a RuntimeException. 138 | * 139 | * @return a new SHA-256 MessageDigest instance 140 | */ 141 | public static MessageDigest newDigest() { 142 | try { 143 | return MessageDigest.getInstance("SHA-256"); 144 | } catch (NoSuchAlgorithmException e) { 145 | throw new RuntimeException(e); // Can't happen. 146 | } 147 | } 148 | 149 | /** 150 | * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the 151 | * checked exception that can never occur with a RuntimeException. 152 | * 153 | * @return a new SM3 MessageDigest instance 154 | */ 155 | public static SM3Digest newSM3Digest() { 156 | return new SM3Digest(); 157 | } 158 | 159 | /** 160 | * Calculates the SHA-256 hash of the given bytes. 161 | * 162 | * @param input the bytes to hash 163 | * @return the hash (in big-endian order) 164 | */ 165 | public static byte[] hash(boolean isSha256, byte[] input) { 166 | return hash(isSha256, input, 0, input.length); 167 | } 168 | 169 | /** 170 | * Calculates the SHA-256 hash of the given byte range. 171 | * 172 | * @param input the array containing the bytes to hash 173 | * @param offset the offset within the array of the bytes to hash 174 | * @param length the number of bytes to hash 175 | * @return the hash (in big-endian order) 176 | */ 177 | public static byte[] hash(boolean isSha256, byte[] input, int offset, int length) { 178 | if (isSha256) { 179 | MessageDigest digest = newDigest(); 180 | digest.update(input, offset, length); 181 | return digest.digest(); 182 | } else { 183 | SM3Digest digest = newSM3Digest(); 184 | digest.update(input, offset, length); 185 | byte[] eHash = new byte[digest.getDigestSize()]; 186 | digest.doFinal(eHash, 0); 187 | return eHash; 188 | } 189 | 190 | } 191 | 192 | /** 193 | * Calculates the SHA-256 hash of the given bytes, and then hashes the resulting hash again. 194 | * 195 | * @param input the bytes to hash 196 | * @return the double-hash (in big-endian order) 197 | */ 198 | public static byte[] hashTwice(boolean isSha256, byte[] input) { 199 | return hashTwice(isSha256, input, 0, input.length); 200 | } 201 | 202 | /** 203 | * Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. 204 | * 205 | * @param input the array containing the bytes to hash 206 | * @param offset the offset within the array of the bytes to hash 207 | * @param length the number of bytes to hash 208 | * @return the double-hash (in big-endian order) 209 | */ 210 | public static byte[] hashTwice(boolean isSha256, byte[] input, int offset, int length) { 211 | if (isSha256) { 212 | MessageDigest digest = newDigest(); 213 | digest.update(input, offset, length); 214 | return digest.digest(digest.digest()); 215 | } else { 216 | SM3Digest digest = newSM3Digest(); 217 | digest.update(input, offset, length); 218 | byte[] eHash = new byte[digest.getDigestSize()]; 219 | digest.doFinal(eHash, 0); 220 | digest.reset(); 221 | digest.update(eHash, 0, eHash.length); 222 | digest.doFinal(eHash, 0); 223 | return eHash; 224 | } 225 | 226 | } 227 | 228 | /** 229 | * Calculates the hash of hash on the given byte ranges. This is equivalent to concatenating the 230 | * two ranges and then passing the result to {@link #hashTwice(byte[])}. 231 | */ 232 | public static byte[] hashTwice(boolean isSha256, byte[] input1, int offset1, int length1, 233 | byte[] input2, int offset2, int length2) { 234 | if (isSha256) { 235 | MessageDigest digest = newDigest(); 236 | digest.update(input1, offset1, length1); 237 | digest.update(input2, offset2, length2); 238 | return digest.digest(digest.digest()); 239 | } else { 240 | SM3Digest digest = newSM3Digest(); 241 | digest.update(input1, offset1, length1); 242 | digest.update(input2, offset2, length2); 243 | byte[] eHash = new byte[digest.getDigestSize()]; 244 | digest.doFinal(eHash, 0); 245 | return eHash; 246 | } 247 | } 248 | 249 | private byte[] generateBlockId(long blockNum, Sha256Hash blockHash) { 250 | byte[] numBytes = Longs.toByteArray(blockNum); 251 | byte[] hash = new byte[blockHash.getBytes().length]; 252 | System.arraycopy(numBytes, 0, hash, 0, 8); 253 | System.arraycopy(blockHash.getBytes(), 8, hash, 8, blockHash.getBytes().length - 8); 254 | return hash; 255 | } 256 | 257 | private byte[] generateBlockId(long blockNum, byte[] blockHash) { 258 | byte[] numBytes = Longs.toByteArray(blockNum); 259 | byte[] hash = new byte[blockHash.length]; 260 | System.arraycopy(numBytes, 0, hash, 0, 8); 261 | System.arraycopy(blockHash, 8, hash, 8, blockHash.length - 8); 262 | return hash; 263 | } 264 | 265 | @Override 266 | public boolean equals(Object o) { 267 | if (this == o) { 268 | return true; 269 | } 270 | if (o == null || !(o instanceof Sha256Hash)) { 271 | return false; 272 | } 273 | return Arrays.equals(bytes, ((Sha256Hash) o).bytes); 274 | } 275 | 276 | @Override 277 | public String toString() { 278 | return ByteArray.toHexString(bytes); 279 | } 280 | 281 | /** 282 | * Returns the last four bytes of the wrapped hash. This should be unique enough to be a suitable 283 | * hash code even for blocks, where the goal is to try and get the first bytes to be zeros (i.e. 284 | * the value as a big integer lower than the target value). 285 | */ 286 | @Override 287 | public int hashCode() { 288 | // Use the last 4 bytes, not the first 4 which are often zeros in Bitcoin. 289 | return Ints 290 | .fromBytes(bytes[LENGTH - 4], bytes[LENGTH - 3], bytes[LENGTH - 2], bytes[LENGTH - 1]); 291 | } 292 | 293 | /** 294 | * Returns the bytes interpreted as a positive integer. 295 | */ 296 | public BigInteger toBigInteger() { 297 | return new BigInteger(1, bytes); 298 | } 299 | 300 | /** 301 | * Returns the internal byte array, without defensively copying. Therefore do NOT modify the 302 | * returned array. 303 | */ 304 | public byte[] getBytes() { 305 | return bytes; 306 | } 307 | // 308 | // /** 309 | // * For pb return ByteString. 310 | // */ 311 | // public ByteString getByteString() { 312 | // return ByteString.copyFrom(bytes); 313 | // } 314 | 315 | @Override 316 | public int compareTo(final Sha256Hash other) { 317 | for (int i = LENGTH - 1; i >= 0; i--) { 318 | final int thisByte = this.bytes[i] & 0xff; 319 | final int otherByte = other.bytes[i] & 0xff; 320 | if (thisByte > otherByte) { 321 | return 1; 322 | } 323 | if (thisByte < otherByte) { 324 | return -1; 325 | } 326 | } 327 | return 0; 328 | } 329 | } 330 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/Sha512.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import org.bouncycastle.jce.provider.BouncyCastleProvider; 4 | 5 | import java.security.MessageDigest; 6 | import java.security.NoSuchAlgorithmException; 7 | import java.security.NoSuchProviderException; 8 | import java.security.Security; 9 | 10 | public class Sha512 { 11 | MessageDigest messageDigest; 12 | 13 | static{ 14 | try{ 15 | Security.addProvider(new BouncyCastleProvider()); 16 | }catch(Exception e){ 17 | e.printStackTrace(); 18 | } 19 | } 20 | 21 | public Sha512() { 22 | try { 23 | messageDigest = MessageDigest.getInstance("SHA-512", "BC"); 24 | } catch (NoSuchAlgorithmException e) { 25 | throw new RuntimeException(e); 26 | } catch (NoSuchProviderException e) { 27 | throw new RuntimeException(e); 28 | } 29 | } 30 | 31 | public Sha512(byte[] start) { 32 | this(); 33 | add(start); 34 | } 35 | 36 | public Sha512 add(byte[] bytes) { 37 | messageDigest.update(bytes); 38 | return this; 39 | } 40 | 41 | public Sha512 addU32(int i) { 42 | messageDigest.update((byte) ((i >>> 24) & 0xFF)); 43 | messageDigest.update((byte) ((i >>> 16) & 0xFF)); 44 | messageDigest.update((byte) ((i >>> 8) & 0xFF)); 45 | messageDigest.update((byte) ((i) & 0xFF)); 46 | return this; 47 | } 48 | 49 | private byte[] finishTaking(int size) { 50 | byte[] hash = new byte[size]; 51 | System.arraycopy(messageDigest.digest(), 0, hash, 0, size); 52 | return hash; 53 | } 54 | 55 | public byte[] finish128() { 56 | return finishTaking(16); 57 | } 58 | 59 | public byte[] finish256() { 60 | return finishTaking(32); 61 | } 62 | 63 | public byte[] finish() { 64 | return messageDigest.digest(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/SpringApplicationContextUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class SpringApplicationContextUtil implements ApplicationContextAware { 10 | private static ApplicationContext applicationContext = null; 11 | 12 | 13 | public static String getActiveProfile() { 14 | return applicationContext.getEnvironment().getActiveProfiles()[0]; 15 | } 16 | 17 | 18 | @Override 19 | public void setApplicationContext(ApplicationContext applicationContext) 20 | throws BeansException { 21 | this.applicationContext = applicationContext; 22 | } 23 | 24 | //获取applicationContext 25 | public static ApplicationContext getApplicationContext() { 26 | return applicationContext; 27 | } 28 | 29 | //通过name获取 Bean. 30 | public static Object getBean(String name) { 31 | return getApplicationContext().getBean(name); 32 | 33 | } 34 | 35 | //通过class获取Bean. 36 | public static T getBean(Class clazz) { 37 | return getApplicationContext().getBean(clazz); 38 | } 39 | 40 | //通过name,以及Clazz返回指定的Bean 41 | public static T getBean(String name, Class clazz) { 42 | return getApplicationContext().getBean(name, clazz); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/SpringUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class SpringUtils implements ApplicationContextAware { 10 | private static ApplicationContext applicationContext; 11 | 12 | @Override 13 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 14 | SpringUtils.applicationContext = applicationContext; 15 | } 16 | 17 | public static ApplicationContext getApplicationContext() { 18 | return applicationContext; 19 | } 20 | 21 | public static Object getBean(String beanName) { 22 | return applicationContext.getBean(beanName); 23 | } 24 | 25 | public static T getBean(Class clazz) { 26 | return applicationContext.getBean(clazz); 27 | } 28 | 29 | public static T getBean(String className, Class clazz) { 30 | return applicationContext.getBean(className, clazz); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.util.Random; 4 | import java.util.UUID; 5 | import java.util.regex.Matcher; 6 | import java.util.regex.Pattern; 7 | import java.util.regex.PatternSyntaxException; 8 | 9 | /** 10 | * 字符串工具类 11 | * 12 | */ 13 | public class StringUtils extends org.springframework.util.StringUtils { 14 | 15 | 16 | /** 17 | * ^ 匹配输入字符串开始的位置 18 | * \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d 19 | * $ 匹配输入字符串结尾的位置 20 | */ 21 | public static final String CHINA_REGEX_EXP = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[0-9])|(18[0-9])|(19[1,8,9]))\\d{8}$"; 22 | public static final String HK_REGEX_EXP = "^(5|6|8|9)\\d{7}$"; 23 | 24 | 25 | private final static String[] chars = new String[]{"a", "b", "c", "d", "e", "f", 26 | "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", 27 | "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", 28 | "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", 29 | "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", 30 | "W", "X", "Y", "Z"}; 31 | 32 | //生成8位appKey 33 | public static String getAppKey() { 34 | StringBuffer shortBuffer = new StringBuffer(); 35 | //获取用户id进行字符串截取 36 | String uuid = UUID.randomUUID().toString().replace("-", ""); 37 | for (int i = 0; i < 8; i++) { 38 | String str = uuid.substring(i * 4, i * 4 + 4); 39 | int x = Integer.parseInt(str, 16); 40 | shortBuffer.append(chars[x % 0x3E]); 41 | } 42 | return shortBuffer.toString(); 43 | 44 | } 45 | 46 | //生成32位appSecret 47 | public static String getAppSecret(String appId){ 48 | String EncryoAppSecret=""; 49 | try { 50 | EncrypDES des1 = new EncrypDES();// 使用默认密钥 51 | EncryoAppSecret=des1.encrypt(appId); 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | } 55 | return EncryoAppSecret; 56 | } 57 | 58 | //length用户要求产生字符串的长度 59 | public static String getRandomString(int length){ 60 | String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 61 | Random random=new Random(); 62 | StringBuffer sb=new StringBuffer(); 63 | for(int i=0;i extends TwoValues { 6 | private K three; 7 | 8 | public ThreeValues(U u, V v, K k) { 9 | super(u, v); 10 | three = k; 11 | } 12 | 13 | public K getThree() { 14 | return three; 15 | } 16 | 17 | public void setThree(K three) { 18 | this.three = three; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/TwoValues.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | public class TwoValues { 4 | private U one; 5 | private V two; 6 | 7 | public TwoValues(U u, V v) { 8 | this.one = u; 9 | this.two = v; 10 | } 11 | 12 | public U getOne() { 13 | return this.one; 14 | } 15 | 16 | public void setOne(U one) { 17 | this.one = one; 18 | } 19 | 20 | public V getTwo() { 21 | return this.two; 22 | } 23 | 24 | public void setTwo(V two) { 25 | this.two = two; 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/ValidateUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import org.apache.commons.lang3.StringUtils; 4 | 5 | import java.util.Arrays; 6 | import java.util.Calendar; 7 | import java.util.Set; 8 | import java.util.regex.Matcher; 9 | import java.util.regex.Pattern; 10 | import java.util.stream.Collectors; 11 | 12 | public class ValidateUtil { 13 | static Pattern P_ID_15 = Pattern 14 | .compile("^(\\d{2})\\d{4}(\\d{2})(\\d{2})(\\d{2})\\d{3}$"); 15 | static Pattern P_ID_18 = Pattern 16 | .compile("^((\\d{2})\\d{4}(\\d{4})(\\d{2})(\\d{2})\\d{3})(\\w)$"); 17 | static int[] TIMES = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 18 | 5, 8, 4, 2}; 19 | static String[] VFCODES = new String[]{"1", "0", "X", "9", "8", "7", "6", 20 | "5", "4", "3", "2"}; 21 | static Set AREAS = Arrays 22 | .stream("11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65,71,81,82" 23 | .split(",")).collect(Collectors.toSet()); 24 | 25 | static boolean validateDate(int year, int month, int day) { 26 | if (year < 20) 27 | year += 2000; 28 | else if (year < 1900) 29 | year += 1900; 30 | if (year <= 1900 || year >= DateUtils.getCurrentGradeYear() - 10) 31 | return false; 32 | if (month > 12) 33 | return false; 34 | Calendar cal = Calendar.getInstance(); 35 | cal.set(Calendar.YEAR, year); 36 | cal.set(Calendar.MONTH, month - 1); 37 | if (day > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) 38 | return false; 39 | return true; 40 | } 41 | 42 | public static boolean id(String id) { 43 | if (id == null) 44 | return false; 45 | 46 | Matcher m = P_ID_18.matcher(id); 47 | if (m.find()) { // 18位身份证 48 | // 区域码 49 | if (!AREAS.contains(m.group(2))) 50 | return false; 51 | 52 | // 检查日期 53 | if (!validateDate(Integer.parseInt(m.group(3)), 54 | Integer.parseInt(m.group(4)), Integer.parseInt(m.group(5)))) 55 | return false; 56 | 57 | // 检查校验码 58 | int v = 0; 59 | char[] chars = m.group(1).toCharArray(); 60 | for (int i = 0; i < chars.length; i++) 61 | v += Integer.parseInt(Character.toString(chars[i])) * TIMES[i]; 62 | if (!m.group(6).equalsIgnoreCase(VFCODES[v % 11])) 63 | return false; 64 | 65 | return true; 66 | } 67 | 68 | m = P_ID_15.matcher(id); 69 | if (m.find()) { // 15位身份证 70 | // 区域码 71 | if (!AREAS.contains(m.group(1))) 72 | return false; 73 | 74 | // 检查日期 75 | if (!validateDate(Integer.parseInt(m.group(2)), 76 | Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)))) 77 | return false; 78 | 79 | return true; 80 | } 81 | 82 | return false; 83 | } 84 | 85 | static Pattern P_SIN = Pattern.compile("^\\d{9}$"); 86 | 87 | public static String plainId(String str) { 88 | return str == null ? "" : str.replaceAll("\\s?-?", ""); 89 | } 90 | 91 | public static boolean sin(String str) { 92 | if (str == null) 93 | return false; 94 | return P_SIN.matcher(plainId(str)).find(); 95 | } 96 | 97 | static Pattern P_SSN = Pattern.compile("^\\d{9}$"); 98 | 99 | public static boolean ssn(String str) { 100 | if (str == null) 101 | return false; 102 | return P_SSN.matcher(plainId(str)).find(); 103 | } 104 | 105 | // 短式手机号 106 | static Pattern P_PHONE_US_SHORT = Pattern.compile("^\\d{10}$"); 107 | static Pattern P_PHONE_CN_SHORT = Pattern.compile("^\\d{11,12}$"); 108 | static Pattern P_PHONE_HK_SHORT = Pattern.compile("^\\d{8}$"); 109 | 110 | // 全式手机号 111 | static Pattern P_PHONE_CN = Pattern.compile("^\\+86\\d{11,12}$"); 112 | static Pattern P_PHONE_US_CA = Pattern.compile("^\\+1\\d{10}$"); 113 | static Pattern P_PHONE_HK = Pattern.compile("^\\+852\\d{8}$"); 114 | 115 | public static String plainPhone(String str) { 116 | return str == null ? "" : str.replaceAll("\\s?-?\\+?\\(?\\)?", ""); 117 | } 118 | 119 | public static boolean isChina(String str) { 120 | if (str == null) 121 | return false; 122 | return P_PHONE_CN_SHORT.matcher(plainPhone(str)).find() || 123 | P_PHONE_CN.matcher(plainPhone(str)).find(); 124 | } 125 | 126 | public static boolean phone(String countryPrefix, String noPrefixPhone) { 127 | if (StringUtils.isEmpty(noPrefixPhone)) 128 | return false; 129 | 130 | if (countryPrefix.equals("+86")) 131 | return P_PHONE_CN_SHORT.matcher(noPrefixPhone).find(); 132 | if (countryPrefix.startsWith("+1")) 133 | return P_PHONE_US_SHORT.matcher(noPrefixPhone).find(); 134 | if (countryPrefix.startsWith("+852")) 135 | return P_PHONE_HK.matcher(noPrefixPhone).find(); 136 | 137 | return true; 138 | } 139 | 140 | public static boolean password(String str) { 141 | if (str == null) 142 | return false; 143 | return str.length() >= 6; 144 | } 145 | 146 | public static String passwordRequirement() { 147 | return "密码长度不应少于6位"; 148 | } 149 | 150 | static Pattern P_T_PWD = Pattern.compile("^\\d{6}$"); 151 | 152 | public static boolean transactionPassword(String str) { 153 | if (str == null) 154 | return false; 155 | return P_T_PWD.matcher(str).find(); 156 | } 157 | 158 | public static String transactionPasswordRequirement() { 159 | return "交易密码应为6位数字"; 160 | } 161 | 162 | static Pattern P_CA_POSTAL_CODE = Pattern 163 | .compile("[A-Za-z]\\d[A-Za-z]\\s*\\d[A-Za-z]\\d"); 164 | 165 | public static boolean caPostalCode(String str) { 166 | if (str == null) 167 | return false; 168 | return P_CA_POSTAL_CODE.matcher(str).find(); 169 | } 170 | 171 | static Pattern EMPLOYEE_NUM = Pattern.compile("^[A-Za-z0-9]+$"); 172 | 173 | public static boolean isEmployeeNum(String str) { 174 | if (str == null) 175 | return false; 176 | return EMPLOYEE_NUM.matcher(str).find(); 177 | } 178 | 179 | static Pattern USER_NICKNAME = Pattern.compile("^[\\u4e00-\\u9fa5a-zA-Z0-9]+$"); 180 | 181 | public static boolean isLegalNickname(String str) { 182 | if (str == null) 183 | return false; 184 | return USER_NICKNAME.matcher(str).find(); 185 | } 186 | 187 | public static boolean isMainlandChina(String country) { 188 | if (StringUtils.isBlank(country)) { 189 | return false; 190 | } 191 | String pattern = "CN,CH"; 192 | return pattern.contains(country.toUpperCase()); 193 | } 194 | 195 | public static boolean isMainlandChina(String country, Integer idType) { 196 | boolean[] ret = new boolean[]{false, false}; 197 | if (StringUtils.isNotBlank(country)) { 198 | ret[0] = "CN,CH".contains(country.toUpperCase()); 199 | } 200 | if (idType != null) { 201 | ret[1] = Integer.valueOf(1).equals(idType); 202 | } 203 | return ret[0] || ret[1]; 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/redis/RedisLockUtil.java: -------------------------------------------------------------------------------- 1 | //package com.yumiao.usdttransfer.utils.redis; 2 | // 3 | //import org.slf4j.Logger; 4 | //import org.slf4j.LoggerFactory; 5 | //import org.springframework.beans.factory.annotation.Autowired; 6 | //import org.springframework.dao.DataAccessException; 7 | //import org.springframework.data.redis.connection.RedisConnection; 8 | //import org.springframework.data.redis.core.RedisCallback; 9 | //import org.springframework.data.redis.core.RedisTemplate; 10 | //import org.springframework.data.redis.serializer.StringRedisSerializer; 11 | //import org.springframework.stereotype.Component; 12 | // 13 | //import java.util.concurrent.TimeUnit; 14 | // 15 | //@Component 16 | //public class RedisLockUtil { 17 | // 18 | // private static Logger logger = LoggerFactory.getLogger(RedisLockUtil.class); 19 | // 20 | // @Autowired 21 | // private RedisTemplate redisTemplate; 22 | // 23 | // private static final int DEFAULT_ACQUIRY_RESOLUTION_MILLIS = 100; 24 | // 25 | // /** 26 | // * Lock key path. 27 | // */ 28 | // private String lockKey; 29 | // 30 | // /** 31 | // * 锁超时时间,防止线程在入锁以后,无限的执行等待 32 | // */ 33 | // private int expireMsecs = 60 * 1000; 34 | // 35 | // /** 36 | // * 锁等待时间,防止线程饥饿 37 | // */ 38 | // private int timeoutMsecs = 10 * 1000; 39 | // 40 | // private volatile boolean locked = false; 41 | // 42 | // /** 43 | // * 获取互斥 44 | // * @param key 45 | // * @param expire 秒 46 | // * @return 47 | // */ 48 | // public boolean tryLock(String key,int expire ){ 49 | // boolean locked = redisTemplate.opsForValue().setIfAbsent(key, key); 50 | // if (locked) { 51 | // redisTemplate.expire(key, expire, TimeUnit.SECONDS); 52 | // } 53 | // return locked; 54 | // } 55 | // public RedisLockUtil() { 56 | // 57 | // } 58 | // 59 | // /** 60 | // * Detailed constructor with default acquire timeout 10000 msecs and lock expiration of 60000 msecs. 61 | // * 62 | // * @param lockKey lock key (ex. account:1, ...) 63 | // */ 64 | // public RedisLockUtil(RedisTemplate redisTemplate, String lockKey) { 65 | // this.redisTemplate = redisTemplate; 66 | // this.lockKey = lockKey + "_lock"; 67 | // } 68 | // 69 | // /** 70 | // * Detailed constructor with default lock expiration of 60000 msecs. 71 | // * 72 | // */ 73 | // public RedisLockUtil(RedisTemplate redisTemplate, String lockKey, int timeoutMsecs) { 74 | // this(redisTemplate, lockKey); 75 | // this.timeoutMsecs = timeoutMsecs; 76 | // } 77 | // 78 | // /** 79 | // * Detailed constructor. 80 | // * 81 | // */ 82 | // public RedisLockUtil(RedisTemplate redisTemplate, String lockKey, int timeoutMsecs, int expireMsecs) { 83 | // this(redisTemplate, lockKey, timeoutMsecs); 84 | // this.expireMsecs = expireMsecs; 85 | // } 86 | // 87 | // /** 88 | // * @return lock key 89 | // */ 90 | // public String getLockKey() { 91 | // return lockKey; 92 | // } 93 | // 94 | // private String get(final String key) { 95 | // Object obj = null; 96 | // try { 97 | // obj = redisTemplate.execute(new RedisCallback() { 98 | // @Override 99 | // public Object doInRedis(RedisConnection connection) throws DataAccessException { 100 | // StringRedisSerializer serializer = new StringRedisSerializer(); 101 | // byte[] data = connection.get(serializer.serialize(key)); 102 | // connection.close(); 103 | // if (data == null) { 104 | // return null; 105 | // } 106 | // return serializer.deserialize(data); 107 | // } 108 | // }); 109 | // } catch (Exception e) { 110 | // logger.error("get redis error, key : {}", key); 111 | // } 112 | // return obj != null ? obj.toString() : null; 113 | // } 114 | // 115 | // public boolean setNX(final String key, final String value) { 116 | // Object obj = null; 117 | // try { 118 | // obj = redisTemplate.execute(new RedisCallback() { 119 | // @Override 120 | // public Object doInRedis(RedisConnection connection) throws DataAccessException { 121 | // StringRedisSerializer serializer = new StringRedisSerializer(); 122 | // Boolean success = connection.setNX(serializer.serialize(key), serializer.serialize(value)); 123 | // connection.close(); 124 | // return success; 125 | // } 126 | // }); 127 | // } catch (Exception e) { 128 | // logger.error("setNX redis error, key : {}", key); 129 | // } 130 | // return obj != null ? (Boolean) obj : false; 131 | // } 132 | // 133 | // private String getSet(final String key, final String value) { 134 | // Object obj = null; 135 | // try { 136 | // obj = redisTemplate.execute(new RedisCallback() { 137 | // @Override 138 | // public Object doInRedis(RedisConnection connection) throws DataAccessException { 139 | // StringRedisSerializer serializer = new StringRedisSerializer(); 140 | // byte[] ret = connection.getSet(serializer.serialize(key), serializer.serialize(value)); 141 | // connection.close(); 142 | // return serializer.deserialize(ret); 143 | // } 144 | // }); 145 | // } catch (Exception e) { 146 | // logger.error("setNX redis error, key : {}", key); 147 | // } 148 | // return obj != null ? (String) obj : null; 149 | // } 150 | // 151 | // /** 152 | // * 获得 lock. 153 | // * 实现思路: 主要是使用了redis 的setnx命令,缓存了锁. 154 | // * reids缓存的key是锁的key,所有的共享, value是锁的到期时间(注意:这里把过期时间放在value了,没有时间上设置其超时时间) 155 | // * 执行过程: 156 | // * 1.通过setnx尝试设置某个key的值,成功(当前没有这个锁)则返回,成功获得锁 157 | // * 2.锁已经存在则获取锁的到期时间,和当前时间比较,超时的话,则设置新的值 158 | // * 159 | // * @return true if lock is acquired, false acquire timeouted 160 | // * @throws InterruptedException in case of thread interruption 161 | // */ 162 | // public synchronized boolean lock() throws InterruptedException { 163 | // int timeout = timeoutMsecs; 164 | // while (timeout >= 0) { 165 | // long expires = System.currentTimeMillis() + expireMsecs + 1; 166 | // String expiresStr = String.valueOf(expires); //锁到期时间 167 | // if (this.setNX(lockKey, expiresStr)) { 168 | // // lock acquired 169 | // locked = true; 170 | // return true; 171 | // } 172 | // 173 | // String currentValueStr = this.get(lockKey); //redis里的时间 174 | // if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) { 175 | // //判断是否为空,不为空的情况下,如果被其他线程设置了值,则第二个条件判断是过不去的 176 | // // lock is expired 177 | // 178 | // String oldValueStr = this.getSet(lockKey, expiresStr); 179 | // //获取上一个锁到期时间,并设置现在的锁到期时间, 180 | // //只有一个线程才能获取上一个线上的设置时间,因为jedis.getSet是同步的 181 | // if (oldValueStr != null && oldValueStr.equals(currentValueStr)) { 182 | // //防止误删(覆盖,因为key是相同的)了他人的锁——这里达不到效果,这里值会被覆盖,但是因为什么相差了很少的时间,所以可以接受 183 | // 184 | // //[分布式的情况下]:如过这个时候,多个线程恰好都到了这里,但是只有一个线程的设置值和当前值相同,他才有权利获取锁 185 | // // lock acquired 186 | // locked = true; 187 | // return true; 188 | // } 189 | // } 190 | // timeout -= DEFAULT_ACQUIRY_RESOLUTION_MILLIS; 191 | // 192 | // /* 193 | // 延迟100 毫秒, 这里使用随机时间可能会好一点,可以防止饥饿进程的出现,即,当同时到达多个进程, 194 | // 只会有一个进程获得锁,其他的都用同样的频率进行尝试,后面有来了一些进行,也以同样的频率申请锁,这将可能导致前面来的锁得不到满足. 195 | // 使用随机的等待时间可以一定程度上保证公平性 196 | // */ 197 | // Thread.sleep(DEFAULT_ACQUIRY_RESOLUTION_MILLIS); 198 | // 199 | // } 200 | // return false; 201 | // } 202 | // 203 | // 204 | // /** 205 | // * Acqurired lock release. 206 | // */ 207 | // public synchronized void unlock() { 208 | // if (locked) { 209 | // redisTemplate.delete(lockKey); 210 | // locked = false; 211 | // } 212 | // } 213 | // 214 | // public void unlock(String key) { 215 | // redisTemplate.delete(key); 216 | // 217 | // } 218 | // 219 | // 220 | //} 221 | // 222 | // 223 | //// RedisLock lock = new RedisLock(redisTemplate, key, 10000, 20000); 224 | //// try { 225 | //// if(lock.lock()) { 226 | //// //需要加锁的代码 227 | //// } 228 | //// } 229 | //// } catch (InterruptedException e) { 230 | //// e.printStackTrace(); 231 | //// }finally { 232 | //// //为了让分布式锁的算法更稳键些,持有锁的客户端在解锁之前应该再检查一次自己的锁是否已经超时,再去做DEL操作,因为可能客户端因为某个耗时的操作而挂起, 233 | //// //操作完的时候锁因为超时已经被别人获得,这时就不必解锁了。 ————这里没有做 234 | //// lock.unlock(); 235 | //// } 236 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/redis/RedisSequenceUtil.java: -------------------------------------------------------------------------------- 1 | //package com.yumiao.usdttransfer.utils.redis; 2 | // 3 | //import com.yumiao.usdttransfer.utils.DateUtils; 4 | //import org.springframework.beans.factory.annotation.Autowired; 5 | //import org.springframework.stereotype.Component; 6 | // 7 | //import java.util.Date; 8 | //import java.util.concurrent.TimeUnit; 9 | // 10 | // 11 | //@Component 12 | //public class RedisSequenceUtil { 13 | // 14 | // 15 | // @Autowired 16 | // private StringRedisTemplate stringRedisTemplate; 17 | // 18 | // @Autowired 19 | // private RedisTemplate redisTemplate; 20 | // 21 | // /** 22 | // * @param key 23 | // * @param value 24 | // * @param expireTime 25 | // * @Title: set 26 | // * @Description: set cache. 27 | // */ 28 | // public void set(String key, int value, Date expireTime) { 29 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 30 | // counter.set(value); 31 | // counter.expireAt(expireTime); 32 | // } 33 | // 34 | // /** 35 | // * @param key 36 | // * @param value 37 | // * @param timeout 38 | // * @param unit 39 | // * @Title: set 40 | // * @Description: set cache. 41 | // */ 42 | // public void set(String key, int value, long timeout) { 43 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 44 | // counter.set(value); 45 | // counter.expire(timeout, TimeUnit.SECONDS); 46 | // } 47 | // 48 | // /** 49 | // * @param key 50 | // * @param value 51 | // * @param timeout 52 | // * @param unit 53 | // * @Title: set 54 | // * @Description: set cache. 55 | // */ 56 | // public void set(String key, int value, long timeout, TimeUnit unit) { 57 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 58 | // counter.set(value); 59 | // counter.expire(timeout, unit); 60 | // } 61 | // /** 62 | // * @param key 63 | // * @return 64 | // * @Title: generate 65 | // * @Description: Atomically increments by one the current value. 66 | // */ 67 | // public long getAtomicLong(String key) { 68 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 69 | // return counter.get(); 70 | // } 71 | // 72 | // public void del(String key) { 73 | // redisTemplate.delete(key); 74 | // } 75 | // 76 | // public long incr(String key){ 77 | // long num= redisTemplate.getConnectionFactory().getConnection().incr( 78 | // redisTemplate.getKeySerializer().serialize(key) 79 | // ); 80 | // Date date= DateUtils.addDay(new Date(),1); 81 | // redisTemplate.expireAt(key,date); 82 | // return num; 83 | // } 84 | // public long incr(String key,int num){ 85 | // long numresult= redisTemplate.getConnectionFactory().getConnection().incrBy( 86 | // redisTemplate.getKeySerializer().serialize(key), num 87 | // ); 88 | // Date date=DateUtils.addDay(new Date(),1); 89 | // redisTemplate.expireAt(key,date); 90 | // return numresult; 91 | // } 92 | // 93 | // /** 94 | // * @param key 95 | // * @return 96 | // * @Title: generate 97 | // * @Description: Atomically increments by one the current value. 98 | // */ 99 | // public long generate(String key) { 100 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 101 | // return counter.incrementAndGet(); 102 | // } 103 | // 104 | // public long generateExpire(String key, int min) { 105 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 106 | // Date expireTime=new Date(); 107 | // expireTime=DateUtils.getAddMinuteDate(expireTime,min); 108 | // counter.expireAt(expireTime); 109 | // return counter.incrementAndGet(); 110 | // } 111 | // 112 | // /** 113 | // * @param key 114 | // * @return 115 | // * @Title: generate 116 | // * @Description: Atomically increments by one the current value. 117 | // */ 118 | // public long generate(String key, Date expireTime) { 119 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 120 | // counter.expireAt(expireTime); 121 | // return counter.incrementAndGet(); 122 | // } 123 | // 124 | // /** 125 | // * @param key 126 | // * @param increment 127 | // * @return 128 | // * @Title: generate 129 | // * @Description: Atomically adds the given value to the current value. 130 | // */ 131 | // public long generate(String key, int increment) { 132 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 133 | // return counter.addAndGet(increment); 134 | // } 135 | // 136 | // /** 137 | // * @param key 138 | // * @param increment 139 | // * @param expireTime 140 | // * @return 141 | // * @Title: generate 142 | // * @Description: Atomically adds the given value to the current value. 143 | // */ 144 | // public long generate(String key, int increment, Date expireTime) { 145 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 146 | // counter.expireAt(expireTime); 147 | // return counter.addAndGet(increment); 148 | // } 149 | // 150 | // public long generate(String key, int increment, int minute) { 151 | // RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); 152 | // Date date= DateUtils.getAddMinuteDate(new Date(),minute); 153 | // counter.expireAt(date); 154 | // return counter.addAndGet(increment); 155 | // } 156 | //} -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/utils/wcgPwdUtil.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.utils; 2 | 3 | import java.util.Random; 4 | 5 | public class wcgPwdUtil { 6 | 7 | public static String getRandomString(int length) { 8 | String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 9 | Random random = new Random(); 10 | StringBuffer sb = new StringBuffer(); 11 | 12 | for (int i = 0; i < length; ++i) { 13 | // int number = random.nextInt(62);// [0,62) 14 | sb.append(str.charAt(random.nextInt(52))); 15 | } 16 | return sb.toString(); 17 | } 18 | public static String getNumber(int length) { 19 | String str = "0123456789"; 20 | Random random = new Random(); 21 | StringBuffer sb = new StringBuffer(); 22 | for (int i = 0; i < length; ++i) { 23 | sb.append(str.charAt(random.nextInt(10))); 24 | } 25 | return sb.toString(); 26 | } 27 | 28 | public static String WcgPwd(int getRandomString, int getNumber, int lengths) { 29 | String WcgPwd = ""; 30 | String number = getNumber(getNumber); 31 | for (int i = 0; i < lengths; i++) { 32 | if (WcgPwd.equals("") && !String.valueOf(i).equals(number)) 33 | WcgPwd = getRandomString(getRandomString); 34 | else if (WcgPwd.equals("") && String.valueOf(i).equals(number)) 35 | WcgPwd = String.valueOf(System.currentTimeMillis()); 36 | else if (String.valueOf(i).equals(number)) 37 | WcgPwd += " " + System.currentTimeMillis(); 38 | else 39 | WcgPwd += " " + getRandomString(getRandomString); 40 | } 41 | 42 | return WcgPwd; 43 | } 44 | 45 | 46 | public static void main(String[] args) { 47 | /*System.out.println(getRandomString(8)); 48 | System.out.println(getNumber(10)); 49 | System.out.println(System.currentTimeMillis()); 50 | System.out.println(Calendar.getInstance().getTimeInMillis()); 51 | System.out.println(new Date().getTime());*/ 52 | for(int i = 0 ;i<100;i++) 53 | System.out.println(WcgPwd(5, 1, 10)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/wallet/AbstractWallet.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.wallet; 2 | 3 | 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.web3j.utils.Numeric; 6 | 7 | import java.math.BigDecimal; 8 | import java.math.BigInteger; 9 | import java.math.RoundingMode; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | import java.util.function.Function; 13 | 14 | 15 | public abstract class AbstractWallet implements Wallet { 16 | 17 | 18 | static BigDecimal toDecimal(String hex, Integer precis) { 19 | return toDecimal(Numeric.toBigInt(hex), precis); 20 | } 21 | 22 | static BigDecimal toDecimal(BigInteger i, Integer precis) { 23 | return new BigDecimal(i).divide(BigDecimal.valueOf(Math.pow(10, precis)), precis, RoundingMode.FLOOR); 24 | } 25 | 26 | static BigInteger toInteger(BigDecimal d, int precis) { 27 | return d.multiply(BigDecimal.valueOf(Math.pow(10, precis))).toBigInteger(); 28 | } 29 | 30 | static T convert(F from, Function get) { 31 | if (from == null) 32 | return null; 33 | return get.apply(from); 34 | } 35 | 36 | static T convert(F from, Function get, T def) { 37 | if (from == null) 38 | return def; 39 | return get.apply(from); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/yumiao/usdttransfer/wallet/Wallet.java: -------------------------------------------------------------------------------- 1 | package com.yumiao.usdttransfer.wallet; 2 | 3 | import org.web3j.utils.Numeric; 4 | import java.math.BigDecimal; 5 | import java.math.BigInteger; 6 | import java.math.RoundingMode; 7 | import java.util.function.Function; 8 | 9 | public interface Wallet { 10 | 11 | String REDIS_KEY_NEXT_SCAN_BLOCK = "WALLET_NEXT_SCAN_BLOCK"; 12 | String REDIS_KEY_FORCE_SCAN_BLOCK = "WALLET_FORCE_SCAN_BLOCK"; 13 | String REDIS_KEY_CURRENCY_ADDRESSES = "WALLET_ADDRESS_"; 14 | String REDIS_KEY_PENDING_DEPOSIT = "WALLET_PENDING_DEPOSIT_"; 15 | String REDIS_KEY_PENDING_WITHDRAW = "WALLET_PENDING_WITHDRAW_"; 16 | String REDIS_KEY_AMOUNT_UPDATE = "WALLET_AMOUNT_UPDATE"; 17 | String REDIS_KEY_GAS_LIMIT = "WALLET_GAS_LIMIT"; 18 | String REDIS_KEY_GAS_PRICE = "WALLET_GAS_PRICE"; 19 | String REDIS_WALLET_SEND_MSG_KEY = "WALLET_SEND_MSG_KEY"; 20 | 21 | /** 22 | * a9059cbb = sha3("transfer(address,uint256)") 23 | * 23b872dd = sha3("transferFrom(address,address,uint256)") 24 | * 095ea7b3 = sha3("approve(address,uint256)") 25 | * 70a08231 = sha3("balanceOf(address)") 26 | */ 27 | String erc20_transfer = "a9059cbb"; 28 | String erc20_transferFrom = "23b872dd"; 29 | String erc20_approve = "095ea7b3"; 30 | String erc20_balanceOf = "70a08231"; 31 | String erc20_decimals = "313ce567"; 32 | 33 | long MAX_TOKEN_APPROVE = 1_0000_0000; 34 | BigInteger MIN_GAS_LIMIT = new BigInteger("60000"); 35 | BigDecimal MAX_ETHER_APPROVE = new BigDecimal("0.1"); 36 | BigDecimal FIX_QTUM_APPROVE = new BigDecimal("0.1"); 37 | BigDecimal MIN_BALANCE_USER_WALLET = new BigDecimal("0.01"); 38 | BigDecimal MIN_BALANCE_HOT_MASTER_ACCOUNT = new BigDecimal("0.01"); 39 | 40 | 41 | 42 | 43 | static BigDecimal toDecimal(String hex, Integer precis) { 44 | return toDecimal(Numeric.toBigInt(hex), precis); 45 | } 46 | 47 | static BigDecimal toDecimal(BigInteger i, Integer precis) { 48 | return new BigDecimal(i).divide(BigDecimal.valueOf(Math.pow(10, precis)), precis, RoundingMode.FLOOR); 49 | } 50 | 51 | static BigInteger toInteger(BigDecimal d, int precis) { 52 | return d.multiply(BigDecimal.valueOf(Math.pow(10, precis))).toBigInteger(); 53 | } 54 | 55 | static T convert(F from, Function get) { 56 | if (from == null) 57 | return null; 58 | return get.apply(from); 59 | } 60 | 61 | static T convert(F from, Function get, T def) { 62 | if (from == null) 63 | return def; 64 | return get.apply(from); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingson88/trx-usdt/d2b45d0611d63a32ac69f9ab0c36b026df358b18/src/main/resources/application-dev.properties -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=dev 2 | 3 | server.port=5005 4 | server.servlet.context-path=/transfer 5 | spring.application.name=transfer-api 6 | spring.jackson.date-format =yyyy-MM-dd HH:mm:ss 7 | spring.jackson.time-zone = GMT+8 8 | -------------------------------------------------------------------------------- /src/main/resources/generatorConfig.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 48 | 49 | 50 | 52 | 53 | 55 | 56 | 59 | 60 | 61 |
62 |
63 | 64 | 65 |
-------------------------------------------------------------------------------- /src/main/resources/lib/pad-core-1.2.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingson88/trx-usdt/d2b45d0611d63a32ac69f9ab0c36b026df358b18/src/main/resources/lib/pad-core-1.2.0.jar -------------------------------------------------------------------------------- /src/main/resources/lib/pad-crypto-1.2.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingson88/trx-usdt/d2b45d0611d63a32ac69f9ab0c36b026df358b18/src/main/resources/lib/pad-crypto-1.2.0.jar -------------------------------------------------------------------------------- /src/main/resources/lib/pad-parabox-1.2.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingson88/trx-usdt/d2b45d0611d63a32ac69f9ab0c36b026df358b18/src/main/resources/lib/pad-parabox-1.2.0.jar -------------------------------------------------------------------------------- /src/main/resources/lib/parabox-1.2.0-all.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingson88/trx-usdt/d2b45d0611d63a32ac69f9ab0c36b026df358b18/src/main/resources/lib/parabox-1.2.0-all.jar -------------------------------------------------------------------------------- /src/main/resources/lib/tron-protobuf-1.0-SNAPSHOT.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingson88/trx-usdt/d2b45d0611d63a32ac69f9ab0c36b026df358b18/src/main/resources/lib/tron-protobuf-1.0-SNAPSHOT.jar -------------------------------------------------------------------------------- /src/main/resources/lib/tron-wallet-cli.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingson88/trx-usdt/d2b45d0611d63a32ac69f9ab0c36b026df358b18/src/main/resources/lib/tron-wallet-cli.jar -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | %d %X{request_uuid} [%t] %-5p %c %line - [%m]%n 10 | UTF-8 11 | 12 | 13 | 15 | ${LOG_HOME}/${APP_NAME}.log 16 | true 17 | 18 | 19 | ${LOG_HOME}/${APP_NAME}.log.%d{yyyyMMdd}.%i 20 | 22 | 23 | 200MB 24 | 25 | 26 | 27 | 28 | %d %X{request_uuid} [%t] %-5p %c %line - [%m]%n 29 | UTF-8 30 | 31 | 32 | 34 | ${LOG_HOME}/error_${APP_NAME}.log 35 | 36 | 37 | ${LOG_HOME}/error_${APP_NAME}.log.%d{yyyyMMdd}.%i 38 | 40 | 41 | 200MB 42 | 43 | 44 | 45 | 46 | %d %X{request_uuid} [%t] %-5p %c %line - [%m]%n 47 | UTF-8 48 | 49 | 50 | ERROR 51 | ACCEPT 52 | DENY 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /src/test/java/com/exchange/userserver/GoodServiceTests.java: -------------------------------------------------------------------------------- 1 | //package com.exchange.userserver; 2 | // 3 | //import com.alibaba.fastjson.JSON; 4 | //import com.yumiao.usdttransfer.AppApplication; 5 | //import com.yumiao.usdttransfer.domain.GoodInfoVo; 6 | //import org.junit.Test; 7 | //import org.junit.runner.RunWith; 8 | //import org.springframework.beans.factory.annotation.Autowired; 9 | //import org.springframework.boot.test.context.SpringBootTest; 10 | //import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 11 | // 12 | //@RunWith(SpringJUnit4ClassRunner.class) 13 | //@SpringBootTest(classes = AppApplication.class) 14 | //public class GoodServiceTests { 15 | // 16 | // @Autowired 17 | // private GoodService goodService; 18 | // 19 | // @Test 20 | // public void getUserInfoById() throws Exception { 21 | // GoodInfoVo goodInfoVo= goodService.getGoodInfoByGoodId(1L); 22 | // System.out.println(JSON.toJSONString(goodInfoVo)); 23 | // } 24 | // 25 | //} 26 | -------------------------------------------------------------------------------- /src/test/java/com/exchange/userserver/UserServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | //package com.exchange.userserver; 2 | // 3 | // 4 | //import org.junit.Test; 5 | //import org.junit.runner.RunWith; 6 | //import org.springframework.beans.factory.annotation.Autowired; 7 | //import org.springframework.boot.test.context.SpringBootTest; 8 | //import org.springframework.test.context.junit4.SpringRunner; 9 | // 10 | //import java.io.*; 11 | //import java.lang.reflect.Method; 12 | //import java.util.ArrayList; 13 | //import java.util.HashMap; 14 | //import java.util.List; 15 | //import java.util.Map; 16 | // 17 | //@RunWith(SpringRunner.class) 18 | //@SpringBootTest 19 | //public class UserServerApplicationTests { 20 | // 21 | // 22 | // @Test 23 | // public void contextLoads() throws Exception { 24 | // //captchaService.sendPhone("8618664329584", "18664329584", UserVerifyCodeOperation.A); 25 | // //genRespCodes(); 26 | // //captchaService.sendEmail("1428819869@qq.com",UserVerifyCodeOperation.A); 27 | // } 28 | // 29 | // public void genRespCodes() throws Exception { 30 | // List> list = getAllEnum("com.yumiao.usdttransfer.constant.RespCode"); 31 | // System.out.println(list); 32 | // 33 | // for (Map temp : list) { 34 | // write(temp.get("code") + "," + temp.get("value")); 35 | // } 36 | // } 37 | // 38 | // 39 | // public void write(String text) throws IOException { 40 | // try { 41 | // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("G:/RespCode.csv"), true), "UTF-8")); 42 | // 43 | // bw.write(text); 44 | // bw.newLine(); 45 | // 46 | // bw.close(); 47 | // } catch (Exception e) { 48 | // System.err.println("write errors :" + e); 49 | // } 50 | // } 51 | // 52 | // 53 | // /** 54 | // * 根据枚举的字符串获取枚举的值 55 | // * 56 | // * @param className 包名+类名 57 | // */ 58 | // public static List> getAllEnum(String className) throws Exception { 59 | // // 得到枚举类对象 60 | // Class clazz = (Class) Class.forName(className); 61 | // List> list = new ArrayList>(); 62 | // //获取所有枚举实例 63 | // Enum[] enumConstants = clazz.getEnumConstants(); 64 | // //根据方法名获取方法 65 | // Method getName = clazz.getMethod("getName"); 66 | // Method getValue = clazz.getMethod("getValue"); 67 | // Map map = null; 68 | // for (Enum enum1 : enumConstants) { 69 | // map = new HashMap(); 70 | // //执行枚举方法获得枚举实例对应的值 71 | // map.put("value", getName.invoke(enum1)); 72 | // map.put("code", getValue.invoke(enum1)); 73 | // list.add(map); 74 | // } 75 | // return list; 76 | // } 77 | // 78 | // 79 | //} 80 | -------------------------------------------------------------------------------- /src/test/java/com/exchange/userserver/UserUserServiceTests.java: -------------------------------------------------------------------------------- 1 | //package com.exchange.userserver; 2 | // 3 | // 4 | //import com.alibaba.fastjson.JSON; 5 | //import com.yumiao.usdttransfer.domain.UserUserDto; 6 | //import com.yumiao.usdttransfer.service.UserUserService; 7 | //import org.junit.Test; 8 | //import org.junit.runner.RunWith; 9 | //import org.springframework.beans.factory.annotation.Autowired; 10 | //import org.springframework.boot.test.context.SpringBootTest; 11 | //import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 12 | // 13 | //@RunWith(SpringJUnit4ClassRunner.class) 14 | //@SpringBootTest(classes = UserServerApplication.class) 15 | //public class UserUserServiceTests { 16 | // 17 | // @Autowired 18 | // private UserUserService userUserService; 19 | // 20 | // @Test 21 | // public void getUserInfoById() throws Exception { 22 | // UserUserDto userUserDto= userUserService.getUserInfoById(96L); 23 | // System.out.println(JSON.toJSONString(userUserDto)); 24 | // } 25 | // 26 | // 27 | //} 28 | -------------------------------------------------------------------------------- /测试ETH网络.txt: -------------------------------------------------------------------------------- 1 | 测试网络eth https://faucet.ropsten.be/ https://ropsten.etherscan.io/ 2 | --------------------------------------------------------------------------------