├── src ├── main │ ├── resources │ │ └── application.properties │ └── java │ │ └── com │ │ └── example │ │ └── demojavabtcsign │ │ ├── DemojavabtcsignApplication.java │ │ ├── DogecoinTestNet3Params.java │ │ ├── ChainAddressCheckDemo.java │ │ ├── DogecoinMainNetParams.java │ │ └── DogeSignBtcSignDemo.java └── test │ └── java │ └── com │ └── example │ └── demojavabtcsign │ └── DemojavabtcsignApplicationTests.java ├── README.md ├── .gitignore ├── .mvn └── wrapper │ └── maven-wrapper.properties ├── pom.xml ├── mvnw.cmd └── mvnw /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=demojavabtcsign 2 | -------------------------------------------------------------------------------- /src/test/java/com/example/demojavabtcsign/DemojavabtcsignApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demojavabtcsign; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class DemojavabtcsignApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 使用Java给BTC签名的DEMO 2 | 3 | ### 简单说明 4 | BTC签名逻辑,建议自己写,毕竟涉及到私钥,因此本项目仅供参考和拷贝。 5 | 6 | 主要逻辑在这里: 7 | [主要逻辑](src/main/java/com/example/demojavabtcsign/DogeSignBtcSignDemo.java) 8 | 9 | 当然由于我在开发时顺带也接了狗狗币dogecoin,因此这里也同样可以适用于狗狗币的签名(跟BTC签名共用逻辑,区别仅仅在于,链的网络参数不同)。 10 | 11 | ### 其它说明 12 | 当你需要 golang签名btc 或者 golang签名doge 时候,请参考 [这里](https://github.com/yyle88/gobtcsign) 13 | 14 | ### 特别注意 15 | 你需要确保你用的是 dogecoin 而不是 dogechain 或者其他狗链,因为同样是小狗头像图标的链有很多很多种。 16 | 17 | ### 其它说明 18 | 只是技术分享的,而不涉及别的,请理性对待。 19 | -------------------------------------------------------------------------------- /src/main/java/com/example/demojavabtcsign/DemojavabtcsignApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demojavabtcsign; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemojavabtcsignApplication { 8 | 9 | //这个项目不起服务,因此这里没用,不用管它,有用的在别的main里 10 | public static void main(String[] args) { 11 | SpringApplication.run(DemojavabtcsignApplication.class, args); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | wrapperVersion=3.3.2 18 | distributionType=only-script 19 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip 20 | -------------------------------------------------------------------------------- /src/main/java/com/example/demojavabtcsign/DogecoinTestNet3Params.java: -------------------------------------------------------------------------------- 1 | package com.example.demojavabtcsign; 2 | 3 | import com.google.common.base.Preconditions; 4 | import org.bitcoinj.core.Block; 5 | import org.bitcoinj.core.Sha256Hash; 6 | import org.bitcoinj.core.Utils; 7 | import org.bitcoinj.params.AbstractBitcoinNetParams; 8 | 9 | // 这个是从github里拷来的,你需要去找原作者的,搜 "DogecoinTestNet3Params",当然拷贝这里的也行 10 | public class DogecoinTestNet3Params extends AbstractBitcoinNetParams { 11 | public static final int TESTNET_MAJORITY_WINDOW = 1000; 12 | public static final int TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED = 750; 13 | public static final int TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE = 501; 14 | private static final long GENESIS_TIME = 1386325540L; 15 | private static final long GENESIS_NONCE = 99943L; 16 | private static final Sha256Hash GENESIS_HASH = Sha256Hash.wrap("bb0a78264637406b6360aad926284d544d7049f45189db5664f3c4d07350559e"); 17 | private static DogecoinTestNet3Params instance; 18 | 19 | public DogecoinTestNet3Params() { 20 | this.id = "org.dogecoin.testnet"; 21 | this.targetTimespan = 1209600; 22 | this.maxTarget = Utils.decodeCompactBits(0x1e0ffff0L); 23 | this.port = 44556; 24 | this.packetMagic = 0xfcc1b7dcL; 25 | this.dumpedPrivateKeyHeader = 158; 26 | this.addressHeader = 113; 27 | this.p2shHeader = 196; 28 | this.segwitAddressHrp = "tdge"; 29 | this.spendableCoinbaseDepth = 30; 30 | this.bip32HeaderP2PKHpub = 0x043587CF; 31 | this.bip32HeaderP2PKHpriv = 0x04358394; 32 | this.majorityEnforceBlockUpgrade = TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE; 33 | this.majorityRejectBlockOutdated = TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED; 34 | this.majorityWindow = TESTNET_MAJORITY_WINDOW; 35 | 36 | dnsSeeds = new String[]{"testseed.jrn.me.uk"}; 37 | } 38 | 39 | public static synchronized DogecoinTestNet3Params get() { 40 | if (instance == null) { 41 | instance = new DogecoinTestNet3Params(); 42 | } 43 | 44 | return instance; 45 | } 46 | 47 | public Block getGenesisBlock() { 48 | synchronized (GENESIS_HASH) { 49 | if (this.genesisBlock == null) { 50 | this.genesisBlock = Block.createGenesis(this); 51 | this.genesisBlock.setDifficultyTarget(0x1e0ffff0L); 52 | this.genesisBlock.setTime(1391503289L); 53 | this.genesisBlock.setNonce(997879); 54 | Preconditions.checkState(this.genesisBlock.getHash().equals(GENESIS_HASH), "Invalid genesis hash"); 55 | } 56 | } 57 | 58 | return this.genesisBlock; 59 | } 60 | 61 | public String getPaymentProtocolId() { 62 | return "org.dogecoin.testnet"; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.3.3 9 | 10 | 11 | com.example 12 | demojavabtcsign 13 | 0.0.1-SNAPSHOT 14 | demojavabtcsign 15 | demojavabtcsign 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 17 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-test 41 | test 42 | 43 | 44 | 45 | 46 | org.bitcoinj 47 | bitcoinj-core 48 | 0.16.2 49 | 50 | 51 | 52 | 53 | com.fasterxml.jackson.core 54 | jackson-core 55 | 2.17.2 56 | 57 | 58 | 59 | 60 | com.liferay 61 | com.fasterxml.jackson.databind 62 | 2.10.3.LIFERAY-PATCHED-1 63 | 64 | 65 | 66 | com.fasterxml.jackson.core 67 | jackson-databind 68 | 2.13.3 69 | 70 | 71 | 72 | org.projectlombok 73 | lombok 74 | provided 75 | 76 | 77 | 78 | 79 | 80 | 81 | org.springframework.boot 82 | spring-boot-maven-plugin 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /src/main/java/com/example/demojavabtcsign/ChainAddressCheckDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.demojavabtcsign; 2 | 3 | import org.bitcoinj.core.Address; 4 | import org.bitcoinj.params.MainNetParams; 5 | import org.bitcoinj.params.TestNet3Params; 6 | 7 | public class ChainAddressCheckDemo { 8 | 9 | //这里简单写个地址校验的逻辑 10 | //当然通过成熟第三方检查也行,把地址丢在这里 https://sochain.com/ 它就会自动跳转到对应的链对应的网络找到对应的内容 11 | public static void main(String[] args) { 12 | 13 | { 14 | String dogeMainNetAddress = "DNTDUFge2sGu54k5yRZhtxPV2n4pdFVdR1"; 15 | Address address = Address.fromString(DogecoinMainNetParams.get(), dogeMainNetAddress); 16 | System.out.println("DOGE mainnet:" + address.toString()); 17 | System.out.println(address.getOutputScriptType()); 18 | } 19 | 20 | { 21 | String dogeTestNetAddress = "nhRncWG1Exmnn6nSLxtjEbSoxLJa747j3C"; 22 | Address address = Address.fromString(DogecoinTestNet3Params.get(), dogeTestNetAddress); 23 | System.out.println("DOGE testnet:" + address.toString()); 24 | System.out.println(address.getOutputScriptType()); 25 | } 26 | 27 | { 28 | String dogeMainNetAddress = "DJ4bAxxPvoiZxTJD7KZs6jSGStPfRrzEJW"; 29 | //这里拿个主网的地址去匹配测试网肯定会报错 30 | try { 31 | Address address = Address.fromString(DogecoinTestNet3Params.get(), dogeMainNetAddress); 32 | System.out.println("DOGE testnet:" + address.toString()); 33 | } catch (Exception e) { 34 | System.out.println(e.getMessage()); //这里会报错 35 | } 36 | } 37 | 38 | { 39 | String dogeTestNetAddress = "nqNjvWut21qMKyZb4EPWBEUuVDSHuypVUa"; 40 | //这里拿个测试网的地址去匹配主网肯定会报错 41 | try { 42 | Address address = Address.fromString(DogecoinMainNetParams.get(), dogeTestNetAddress); 43 | System.out.println("DOGE mainnet:" + address.toString()); 44 | } catch (Exception e) { 45 | System.out.println(e.getMessage());//这里会报错 46 | } 47 | } 48 | 49 | { 50 | String btcMainNetAddress = "17xKNFapag74BgPRxdP7qcZE4j4nWyLFxT"; 51 | Address address = Address.fromString(MainNetParams.get(), btcMainNetAddress); 52 | System.out.println("BTC mainnet:" + address.toString()); 53 | System.out.println(address.getOutputScriptType()); 54 | } 55 | 56 | { 57 | String btcTestNetAddress = "mnXkBrKfxK3L9GKx6xaKDQXuxuBpinBR8v"; 58 | Address address = Address.fromString(TestNet3Params.get(), btcTestNetAddress); 59 | System.out.println("BTC testnet:" + address.toString()); 60 | System.out.println(address.getOutputScriptType()); 61 | } 62 | 63 | { 64 | String btcMainNetAddress = "1Kj1EydTHkhvkKPLz894QgH6PQS88Fp7iz"; 65 | //这里拿个BTC地址去匹配DOGE网络肯定会报错 66 | try { 67 | Address address = Address.fromString(DogecoinMainNetParams.get(), btcMainNetAddress); 68 | System.out.println("BTC mainnet:" + address.toString()); 69 | System.out.println(address.getOutputScriptType()); 70 | } catch (Exception e) { 71 | System.out.println(e.getMessage()); //这里会报错 72 | } 73 | } 74 | 75 | { 76 | String btcTestNetAddress = "myxFoPaLAT2k3zKdVfAegaF35VVMo5pWbx"; 77 | //这里拿个BTC地址去匹配DOGE网络肯定会报错 78 | try { 79 | Address address = Address.fromString(DogecoinTestNet3Params.get(), btcTestNetAddress); 80 | System.out.println("BTC testnet:" + address.toString()); 81 | System.out.println(address.getOutputScriptType()); 82 | } catch (Exception e) { 83 | System.out.println(e.getMessage()); //这里会报错 84 | } 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/example/demojavabtcsign/DogecoinMainNetParams.java: -------------------------------------------------------------------------------- 1 | package com.example.demojavabtcsign; 2 | 3 | import com.google.common.base.Preconditions; 4 | import org.bitcoinj.core.Block; 5 | import org.bitcoinj.core.Sha256Hash; 6 | import org.bitcoinj.core.Utils; 7 | import org.bitcoinj.params.AbstractBitcoinNetParams; 8 | 9 | // 这个是从github里拷来的,你需要去找原作者的,搜 "DogecoinMainNetParams",当然拷贝这里的也行 10 | public class DogecoinMainNetParams extends AbstractBitcoinNetParams { 11 | public static final int MAINNET_MAJORITY_WINDOW = 2000; 12 | public static final int MAINNET_MAJORITY_REJECT_BLOCK_OUTDATED = 1900; 13 | public static final int MAINNET_MAJORITY_ENFORCE_BLOCK_UPGRADE = 1500; 14 | private static final long GENESIS_TIME = 1386325540L; 15 | private static final long GENESIS_NONCE = 99943L; 16 | private static final Sha256Hash GENESIS_HASH = Sha256Hash.wrap("1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"); 17 | private static DogecoinMainNetParams instance; 18 | 19 | public DogecoinMainNetParams() { 20 | this.id = "org.dogecoin.production"; 21 | this.targetTimespan = 1209600; 22 | this.maxTarget = Utils.decodeCompactBits(0x1e0ffff0L); 23 | this.port = 22556; 24 | this.packetMagic = 0xc0c0c0c0L; 25 | this.dumpedPrivateKeyHeader = 158; 26 | this.addressHeader = 30; 27 | this.p2shHeader = 22; 28 | this.segwitAddressHrp = "doge"; 29 | this.spendableCoinbaseDepth = 100; 30 | this.bip32HeaderP2PKHpub = 0x02facafd; 31 | this.bip32HeaderP2PKHpriv = 0x02fac398; 32 | this.majorityEnforceBlockUpgrade = 750; 33 | this.majorityRejectBlockOutdated = 950; 34 | this.majorityWindow = MAINNET_MAJORITY_WINDOW; 35 | this.checkpoints.put( 0, Sha256Hash.wrap("1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691")); 36 | this.checkpoints.put( 42279, Sha256Hash.wrap("8444c3ef39a46222e87584ef956ad2c9ef401578bd8b51e8e4b9a86ec3134d3a")); 37 | this.checkpoints.put( 42400, Sha256Hash.wrap("557bb7c17ed9e6d4a6f9361cfddf7c1fc0bdc394af7019167442b41f507252b4")); 38 | this.checkpoints.put(104679, Sha256Hash.wrap("35eb87ae90d44b98898fec8c39577b76cb1eb08e1261cfc10706c8ce9a1d01cf")); 39 | this.checkpoints.put(128370, Sha256Hash.wrap("3f9265c94cab7dc3bd6a2ad2fb26c8845cb41cff437e0a75ae006997b4974be6")); 40 | this.checkpoints.put(145000, Sha256Hash.wrap("cc47cae70d7c5c92828d3214a266331dde59087d4a39071fa76ddfff9b7bde72")); 41 | this.checkpoints.put(165393, Sha256Hash.wrap("7154efb4009e18c1c6a6a79fc6015f48502bcd0a1edd9c20e44cd7cbbe2eeef1")); 42 | this.checkpoints.put(186774, Sha256Hash.wrap("3c712c49b34a5f34d4b963750d6ba02b73e8a938d2ee415dcda141d89f5cb23a")); 43 | this.checkpoints.put(199992, Sha256Hash.wrap("3408ff829b7104eebaf61fd2ba2203ef2a43af38b95b353e992ef48f00ebb190")); 44 | this.checkpoints.put(225000, Sha256Hash.wrap("be148d9c5eab4a33392a6367198796784479720d06bfdd07bd547fe934eea15a")); 45 | this.checkpoints.put(250000, Sha256Hash.wrap("0e4bcfe8d970979f7e30e2809ab51908d435677998cf759169407824d4f36460")); 46 | this.checkpoints.put(270639, Sha256Hash.wrap("c587a36dd4f60725b9dd01d99694799bef111fc584d659f6756ab06d2a90d911")); 47 | this.checkpoints.put(299742, Sha256Hash.wrap("1cc89c0c8a58046bf0222fe131c099852bd9af25a80e07922918ef5fb39d6742")); 48 | this.checkpoints.put(323141, Sha256Hash.wrap("60c9f919f9b271add6ef5671e9538bad296d79f7fdc6487ba702bf2ba131d31d")); 49 | this.checkpoints.put(339202, Sha256Hash.wrap("8c29048df5ae9df38a67ea9470fdd404d281a3a5c6f33080cd5bf14aa496ab03")); 50 | this.checkpoints.put(350000, Sha256Hash.wrap("2bdcba23a47049e69c4fec4c425462e30f3d21d25223bde0ed36be4ea59a7075")); 51 | this.checkpoints.put(370005, Sha256Hash.wrap("7be5af2c5bdcb79047dcd691ef613b82d4f1c20835677daed936de37a4782e15")); 52 | this.checkpoints.put(371337, Sha256Hash.wrap("60323982f9c5ff1b5a954eac9dc1269352835f47c2c5222691d80f0d50dcf053")); 53 | this.checkpoints.put(400002, Sha256Hash.wrap("a5021d69a83f39aef10f3f24f932068d6ff322c654d20562def3fac5703ce3aa")); 54 | this.dnsSeeds = new String[] { 55 | "seed.multidoge.org", 56 | "seed2.multidoge.org", 57 | "seed.doger.dogecoin.com" 58 | }; 59 | this.dnsSeeds = new String[]{"seed.bitcoin.sipa.be", "dnsseed.bluematt.me", "dnsseed.bitcoin.dashjr.org", "seed.bitcoinstats.com", "seed.bitcoin.jonasschnelli.ch", "seed.btc.petertodd.org", "seed.bitcoin.sprovoost.nl", "dnsseed.emzy.de", "seed.bitcoin.wiz.biz"}; 60 | } 61 | 62 | public static synchronized DogecoinMainNetParams get() { 63 | if (instance == null) { 64 | instance = new DogecoinMainNetParams(); 65 | } 66 | 67 | return instance; 68 | } 69 | 70 | public Block getGenesisBlock() { 71 | synchronized(GENESIS_HASH) { 72 | if (this.genesisBlock == null) { 73 | this.genesisBlock = Block.createGenesis(this); 74 | this.genesisBlock.setDifficultyTarget(0x1e0ffff0L); 75 | this.genesisBlock.setTime(1386325540L); 76 | this.genesisBlock.setNonce(99943L); 77 | Preconditions.checkState(this.genesisBlock.getHash().equals(GENESIS_HASH), "Invalid genesis hash"); 78 | } 79 | } 80 | 81 | return this.genesisBlock; 82 | } 83 | 84 | public String getPaymentProtocolId() { 85 | return "org.dogecoin.production"; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | <# : batch portion 2 | @REM ---------------------------------------------------------------------------- 3 | @REM Licensed to the Apache Software Foundation (ASF) under one 4 | @REM or more contributor license agreements. See the NOTICE file 5 | @REM distributed with this work for additional information 6 | @REM regarding copyright ownership. The ASF licenses this file 7 | @REM to you under the Apache License, Version 2.0 (the 8 | @REM "License"); you may not use this file except in compliance 9 | @REM with the License. You may obtain a copy of the License at 10 | @REM 11 | @REM https://www.apache.org/licenses/LICENSE-2.0 12 | @REM 13 | @REM Unless required by applicable law or agreed to in writing, 14 | @REM software distributed under the License is distributed on an 15 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | @REM KIND, either express or implied. See the License for the 17 | @REM specific language governing permissions and limitations 18 | @REM under the License. 19 | @REM ---------------------------------------------------------------------------- 20 | 21 | @REM ---------------------------------------------------------------------------- 22 | @REM Apache Maven Wrapper startup batch script, version 3.3.2 23 | @REM 24 | @REM Optional ENV vars 25 | @REM MVNW_REPOURL - repo url base for downloading maven distribution 26 | @REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 27 | @REM MVNW_VERBOSE - true: enable verbose log; others: silence the output 28 | @REM ---------------------------------------------------------------------------- 29 | 30 | @IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) 31 | @SET __MVNW_CMD__= 32 | @SET __MVNW_ERROR__= 33 | @SET __MVNW_PSMODULEP_SAVE=%PSModulePath% 34 | @SET PSModulePath= 35 | @FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( 36 | IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) 37 | ) 38 | @SET PSModulePath=%__MVNW_PSMODULEP_SAVE% 39 | @SET __MVNW_PSMODULEP_SAVE= 40 | @SET __MVNW_ARG0_NAME__= 41 | @SET MVNW_USERNAME= 42 | @SET MVNW_PASSWORD= 43 | @IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) 44 | @echo Cannot start maven from wrapper >&2 && exit /b 1 45 | @GOTO :EOF 46 | : end batch / begin powershell #> 47 | 48 | $ErrorActionPreference = "Stop" 49 | if ($env:MVNW_VERBOSE -eq "true") { 50 | $VerbosePreference = "Continue" 51 | } 52 | 53 | # calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties 54 | $distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl 55 | if (!$distributionUrl) { 56 | Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" 57 | } 58 | 59 | switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { 60 | "maven-mvnd-*" { 61 | $USE_MVND = $true 62 | $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" 63 | $MVN_CMD = "mvnd.cmd" 64 | break 65 | } 66 | default { 67 | $USE_MVND = $false 68 | $MVN_CMD = $script -replace '^mvnw','mvn' 69 | break 70 | } 71 | } 72 | 73 | # apply MVNW_REPOURL and calculate MAVEN_HOME 74 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 75 | if ($env:MVNW_REPOURL) { 76 | $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } 77 | $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" 78 | } 79 | $distributionUrlName = $distributionUrl -replace '^.*/','' 80 | $distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' 81 | $MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" 82 | if ($env:MAVEN_USER_HOME) { 83 | $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" 84 | } 85 | $MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' 86 | $MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" 87 | 88 | if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { 89 | Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" 90 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 91 | exit $? 92 | } 93 | 94 | if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { 95 | Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" 96 | } 97 | 98 | # prepare tmp dir 99 | $TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile 100 | $TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" 101 | $TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null 102 | trap { 103 | if ($TMP_DOWNLOAD_DIR.Exists) { 104 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 105 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 106 | } 107 | } 108 | 109 | New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null 110 | 111 | # Download and Install Apache Maven 112 | Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 113 | Write-Verbose "Downloading from: $distributionUrl" 114 | Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 115 | 116 | $webclient = New-Object System.Net.WebClient 117 | if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { 118 | $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) 119 | } 120 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 121 | $webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null 122 | 123 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 124 | $distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum 125 | if ($distributionSha256Sum) { 126 | if ($USE_MVND) { 127 | Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." 128 | } 129 | Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash 130 | if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { 131 | Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." 132 | } 133 | } 134 | 135 | # unzip and move 136 | Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null 137 | Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null 138 | try { 139 | Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null 140 | } catch { 141 | if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { 142 | Write-Error "fail to move MAVEN_HOME" 143 | } 144 | } finally { 145 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 146 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 147 | } 148 | 149 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 150 | -------------------------------------------------------------------------------- /src/main/java/com/example/demojavabtcsign/DogeSignBtcSignDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.demojavabtcsign; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import lombok.Data; 6 | import org.bitcoinj.core.*; 7 | import org.bitcoinj.crypto.TransactionSignature; 8 | import org.bitcoinj.script.*; 9 | import org.bouncycastle.util.encoders.Hex; 10 | 11 | import java.io.IOException; 12 | import java.nio.charset.StandardCharsets; 13 | import java.util.List; 14 | import java.util.Objects; 15 | 16 | //当你需要签名BTC主网时请使用: 17 | //import org.bitcoinj.params.MainNetParams; 18 | //当你需要签名BTC测试网时请使用: 19 | //import org.bitcoinj.params.TestNet3Params; 20 | //当你需要签名BTC测试网时请使用: 21 | //import org.bitcoinj.params.RegTestParams; 22 | 23 | 24 | public class DogeSignBtcSignDemo { 25 | 26 | public static void main(String[] args) { 27 | { 28 | byte[] privateKeyByte = Hex.decode("在这里放你的私钥"); 29 | //比如 30 | //privateKeyByte = Hex.decode("e9b36b68fb6de7f45cb3335bec08da3ba537957b9e56a9e2d9089713619ac7f5"); 31 | ECKey ecKey = ECKey.fromPrivate(privateKeyByte); 32 | NetworkParameters parameters = DogecoinTestNet3Params.get(); 33 | 34 | //第一步你需要放你的私钥,看看算出来的地址是不是你的钱包地址,只有地址完全相同时才是对的 35 | //假如不是就说明要么是网络参数不匹配,要么是地址类型不同,你就需要确定你的网络和地址类型 36 | Address address = Address.fromKey(parameters, ecKey, Script.ScriptType.P2PKH); 37 | System.out.println("address:" + address.toString()); 38 | } 39 | 40 | { 41 | UnsignedMsg param = new UnsignedMsg(); 42 | //这里是网络参数,当你需要签名DOGE测试网时,就用这个网络 43 | param.networkParameters = DogecoinTestNet3Params.get(); 44 | //这里是网络参数,当你需要签名BTC主网时,就用这个网络 45 | //param.networkParameters = MainNetParams.get(); 46 | param.privateKey = "在这里放你的私钥Hex字符串"; 47 | //比如 48 | //param.privateKey = "e9b36b68fb6de7f45cb3335bec08da3ba537957b9e56a9e2d9089713619ac7f5"; 49 | param.rawTransaction = "在这里放你的初始交易内容"; 50 | //比如 51 | //param.rawTransaction = "7b22496e7075744c697374223a5b7b2270726576696f75734f7574506f696e74223a7b2248617368223a2237346164656234323162373233323136643331363463366562363239613561323963306338366336656232633431363831633930373761376130393463666133222c22496e646578223a317d2c22706b536372697074223a2264716b5567696a51727969596c4e515a33637232326d65646a7038504667474972413d3d222c22616d6f756e74223a3133373737333539327d5d2c224f75747075744c697374223a5b7b2261646472657373223a226e593738614e796e5451394b6d5950347a587474755976575a455231744d444e4362222c22616d6f756e74223a353839373036397d2c7b2261646472657373223a226e6734503136616e584e5572517736564b486d6f4d57384e4873546b4642644e726e222c22616d6f756e74223a3133313833313132337d5d7d"; 52 | 53 | String signedHex = signBtcTxGetHex(param); 54 | 55 | String exceptedResult = "在这里放期望的签名结果"; 56 | if (Objects.equals(signedHex, exceptedResult)) { 57 | System.out.println("OK"); 58 | } else { 59 | System.out.println("WA"); 60 | } 61 | } 62 | } 63 | 64 | @Data 65 | public static class UnsignedMsg { 66 | NetworkParameters networkParameters; //网络配置 67 | String privateKey; 68 | String rawTransaction; 69 | } 70 | 71 | 72 | // 主类,表示一个未签名的交易 73 | @Data 74 | public static class UnsignedTx { 75 | @JsonProperty("InputList") 76 | private List inputList; 77 | 78 | @JsonProperty("OutputList") 79 | private List outputList; 80 | 81 | // 表示一个输入 82 | @Data 83 | static class Input { 84 | @JsonProperty("previousOutPoint") 85 | private PreviousOutPoint previousOutPoint; 86 | 87 | @JsonProperty("pkScript") 88 | private byte[] pkScript; 89 | 90 | @JsonProperty("amount") 91 | private long amount; 92 | 93 | // 表示前一个输出点 94 | @Data 95 | static class PreviousOutPoint { 96 | @JsonProperty("Hash") 97 | private String hash; 98 | 99 | @JsonProperty("Index") 100 | private int index; 101 | } 102 | } 103 | 104 | // 表示输出信息 105 | @Data 106 | static class Output { 107 | @JsonProperty("address") 108 | private String address; 109 | 110 | @JsonProperty("amount") 111 | private long amount; 112 | } 113 | } 114 | 115 | public static String signBtcTxGetHex(UnsignedMsg param) { 116 | byte[] privateKeyByte = Hex.decode(param.getPrivateKey()); 117 | // 把私钥放到私钥盒子里 118 | ECKey ecKey = ECKey.fromPrivate(privateKeyByte); 119 | 120 | NetworkParameters networkParameters = param.getNetworkParameters(); 121 | // 三种网络 mainnet testnet regtest 122 | Transaction tx = new Transaction(networkParameters); 123 | 124 | //ECKey ecKey = new ECKey(); 125 | 126 | // 第一步:Hex 解码 127 | byte[] rawTxBytes = Hex.decode(param.getRawTransaction()); 128 | 129 | String result = new String(rawTxBytes, StandardCharsets.UTF_8); 130 | System.out.println(result); // 打印 "Hello" 131 | 132 | // 第二步:JSON 转换 133 | UnsignedTx unsignedTx = null; 134 | try { 135 | final ObjectMapper objectMapper = new ObjectMapper(); 136 | unsignedTx = objectMapper.readValue(rawTxBytes, UnsignedTx.class); 137 | } catch (IOException e) { 138 | throw new RuntimeException(e); 139 | } 140 | 141 | for (UnsignedTx.Input input : unsignedTx.getInputList()) { 142 | // 添加input 143 | TransactionOutPoint transactionOutPoint = new TransactionOutPoint(networkParameters, input.getPreviousOutPoint().getIndex(), Sha256Hash.wrap(input.getPreviousOutPoint().getHash())); 144 | TransactionInput transactionInput = new TransactionInput(networkParameters, tx, new byte[0], transactionOutPoint, Coin.valueOf(input.getAmount())); 145 | // 设置RBF,这里设置的是固定值,也是网上通用的做法,当然你也可以设置别的,但不推荐不设置 146 | tx.addInput(transactionInput).setSequenceNumber(TransactionInput.NO_SEQUENCE - 2); 147 | } 148 | 149 | 150 | for (UnsignedTx.Output output : unsignedTx.getOutputList()) { 151 | // 添加output 152 | tx.addOutput(Coin.valueOf(output.getAmount()), Address.fromString(networkParameters, output.getAddress())); 153 | } 154 | 155 | // 对input进行签名 156 | for (int i = 0; i < tx.getInputs().size(); i++) { 157 | TransactionInput input = tx.getInput(i); 158 | UnsignedTx.Input unSignedTxInput = unsignedTx.inputList.get(i); 159 | Script scriptPubKey = new Script(unSignedTxInput.getPkScript()); 160 | 161 | 162 | TransactionSignature signature; 163 | if (ScriptPattern.isP2PK(scriptPubKey)) { 164 | signature = tx.calculateSignature(i, ecKey, scriptPubKey, Transaction.SigHash.ALL, false); 165 | input.setScriptSig(ScriptBuilder.createInputScript(signature)); 166 | input.setWitness((TransactionWitness) null); 167 | } else if (ScriptPattern.isP2PKH(scriptPubKey)) { 168 | signature = tx.calculateSignature(i, ecKey, scriptPubKey, Transaction.SigHash.ALL, false); 169 | input.setScriptSig(ScriptBuilder.createInputScript(signature, ecKey)); 170 | input.setWitness((TransactionWitness) null); 171 | } else if (ScriptPattern.isP2WPKH(scriptPubKey)) { 172 | 173 | Script scriptCode = ScriptBuilder.createP2PKHOutputScript(ecKey); 174 | signature = tx.calculateWitnessSignature(i, ecKey, scriptCode, input.getValue(), Transaction.SigHash.ALL, false); 175 | input.setScriptSig(ScriptBuilder.createEmpty()); 176 | input.setWitness(TransactionWitness.redeemP2WPKH(signature, ecKey)); 177 | } else { 178 | if (!ScriptPattern.isP2TR(scriptPubKey)) { 179 | throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey); 180 | } 181 | } 182 | } 183 | String signedHex = tx.toHexString(); 184 | System.out.println(signedHex); 185 | 186 | return signedHex; //这个结果就是可以往链上发交易的结果,使用各种语言比如Go/Java最终得到的结果都是相同的(而且要一模一样) 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Apache Maven Wrapper startup batch script, version 3.3.2 23 | # 24 | # Optional ENV vars 25 | # ----------------- 26 | # JAVA_HOME - location of a JDK home dir, required when download maven via java source 27 | # MVNW_REPOURL - repo url base for downloading maven distribution 28 | # MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 29 | # MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output 30 | # ---------------------------------------------------------------------------- 31 | 32 | set -euf 33 | [ "${MVNW_VERBOSE-}" != debug ] || set -x 34 | 35 | # OS specific support. 36 | native_path() { printf %s\\n "$1"; } 37 | case "$(uname)" in 38 | CYGWIN* | MINGW*) 39 | [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" 40 | native_path() { cygpath --path --windows "$1"; } 41 | ;; 42 | esac 43 | 44 | # set JAVACMD and JAVACCMD 45 | set_java_home() { 46 | # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched 47 | if [ -n "${JAVA_HOME-}" ]; then 48 | if [ -x "$JAVA_HOME/jre/sh/java" ]; then 49 | # IBM's JDK on AIX uses strange locations for the executables 50 | JAVACMD="$JAVA_HOME/jre/sh/java" 51 | JAVACCMD="$JAVA_HOME/jre/sh/javac" 52 | else 53 | JAVACMD="$JAVA_HOME/bin/java" 54 | JAVACCMD="$JAVA_HOME/bin/javac" 55 | 56 | if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then 57 | echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 58 | echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 59 | return 1 60 | fi 61 | fi 62 | else 63 | JAVACMD="$( 64 | 'set' +e 65 | 'unset' -f command 2>/dev/null 66 | 'command' -v java 67 | )" || : 68 | JAVACCMD="$( 69 | 'set' +e 70 | 'unset' -f command 2>/dev/null 71 | 'command' -v javac 72 | )" || : 73 | 74 | if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then 75 | echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 76 | return 1 77 | fi 78 | fi 79 | } 80 | 81 | # hash string like Java String::hashCode 82 | hash_string() { 83 | str="${1:-}" h=0 84 | while [ -n "$str" ]; do 85 | char="${str%"${str#?}"}" 86 | h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) 87 | str="${str#?}" 88 | done 89 | printf %x\\n $h 90 | } 91 | 92 | verbose() { :; } 93 | [ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } 94 | 95 | die() { 96 | printf %s\\n "$1" >&2 97 | exit 1 98 | } 99 | 100 | trim() { 101 | # MWRAPPER-139: 102 | # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. 103 | # Needed for removing poorly interpreted newline sequences when running in more 104 | # exotic environments such as mingw bash on Windows. 105 | printf "%s" "${1}" | tr -d '[:space:]' 106 | } 107 | 108 | # parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties 109 | while IFS="=" read -r key value; do 110 | case "${key-}" in 111 | distributionUrl) distributionUrl=$(trim "${value-}") ;; 112 | distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; 113 | esac 114 | done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" 115 | [ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" 116 | 117 | case "${distributionUrl##*/}" in 118 | maven-mvnd-*bin.*) 119 | MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ 120 | case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in 121 | *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; 122 | :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; 123 | :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; 124 | :Linux*x86_64*) distributionPlatform=linux-amd64 ;; 125 | *) 126 | echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 127 | distributionPlatform=linux-amd64 128 | ;; 129 | esac 130 | distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" 131 | ;; 132 | maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; 133 | *) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; 134 | esac 135 | 136 | # apply MVNW_REPOURL and calculate MAVEN_HOME 137 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 138 | [ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" 139 | distributionUrlName="${distributionUrl##*/}" 140 | distributionUrlNameMain="${distributionUrlName%.*}" 141 | distributionUrlNameMain="${distributionUrlNameMain%-bin}" 142 | MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" 143 | MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" 144 | 145 | exec_maven() { 146 | unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : 147 | exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" 148 | } 149 | 150 | if [ -d "$MAVEN_HOME" ]; then 151 | verbose "found existing MAVEN_HOME at $MAVEN_HOME" 152 | exec_maven "$@" 153 | fi 154 | 155 | case "${distributionUrl-}" in 156 | *?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; 157 | *) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; 158 | esac 159 | 160 | # prepare tmp dir 161 | if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then 162 | clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } 163 | trap clean HUP INT TERM EXIT 164 | else 165 | die "cannot create temp dir" 166 | fi 167 | 168 | mkdir -p -- "${MAVEN_HOME%/*}" 169 | 170 | # Download and Install Apache Maven 171 | verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 172 | verbose "Downloading from: $distributionUrl" 173 | verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 174 | 175 | # select .zip or .tar.gz 176 | if ! command -v unzip >/dev/null; then 177 | distributionUrl="${distributionUrl%.zip}.tar.gz" 178 | distributionUrlName="${distributionUrl##*/}" 179 | fi 180 | 181 | # verbose opt 182 | __MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' 183 | [ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v 184 | 185 | # normalize http auth 186 | case "${MVNW_PASSWORD:+has-password}" in 187 | '') MVNW_USERNAME='' MVNW_PASSWORD='' ;; 188 | has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; 189 | esac 190 | 191 | if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then 192 | verbose "Found wget ... using wget" 193 | wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" 194 | elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then 195 | verbose "Found curl ... using curl" 196 | curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" 197 | elif set_java_home; then 198 | verbose "Falling back to use Java to download" 199 | javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" 200 | targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" 201 | cat >"$javaSource" <<-END 202 | public class Downloader extends java.net.Authenticator 203 | { 204 | protected java.net.PasswordAuthentication getPasswordAuthentication() 205 | { 206 | return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); 207 | } 208 | public static void main( String[] args ) throws Exception 209 | { 210 | setDefault( new Downloader() ); 211 | java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); 212 | } 213 | } 214 | END 215 | # For Cygwin/MinGW, switch paths to Windows format before running javac and java 216 | verbose " - Compiling Downloader.java ..." 217 | "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" 218 | verbose " - Running Downloader.java ..." 219 | "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" 220 | fi 221 | 222 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 223 | if [ -n "${distributionSha256Sum-}" ]; then 224 | distributionSha256Result=false 225 | if [ "$MVN_CMD" = mvnd.sh ]; then 226 | echo "Checksum validation is not supported for maven-mvnd." >&2 227 | echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 228 | exit 1 229 | elif command -v sha256sum >/dev/null; then 230 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then 231 | distributionSha256Result=true 232 | fi 233 | elif command -v shasum >/dev/null; then 234 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then 235 | distributionSha256Result=true 236 | fi 237 | else 238 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 239 | echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 240 | exit 1 241 | fi 242 | if [ $distributionSha256Result = false ]; then 243 | echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 244 | echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 245 | exit 1 246 | fi 247 | fi 248 | 249 | # unzip and move 250 | if command -v unzip >/dev/null; then 251 | unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" 252 | else 253 | tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" 254 | fi 255 | printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" 256 | mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" 257 | 258 | clean || : 259 | exec_maven "$@" 260 | --------------------------------------------------------------------------------