Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
W
web3jdemo
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
duanjinfei
web3jdemo
Commits
505b674f
Commit
505b674f
authored
Aug 23, 2022
by
duanjinfei
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
init web3j demo
parents
Pipeline
#535
failed with stages
Changes
10
Pipelines
1
Hide whitespace changes
Inline
Side-by-side
Showing
10 changed files
with
413 additions
and
0 deletions
+413
-0
.gitignore
.gitignore
+2
-0
pom.xml
pom.xml
+32
-0
CustomizeHttpService.java
src/main/java/com/wuban/signDemo/CustomizeHttpService.java
+165
-0
SSLSocketClient.java
src/main/java/com/wuban/signDemo/SSLSocketClient.java
+52
-0
SignAndSubmit.java
src/main/java/com/wuban/signDemo/SignAndSubmit.java
+162
-0
tranSignDemo.kotlin_module
target/classes/META-INF/tranSignDemo.kotlin_module
+0
-0
CustomizeHttpService.class
target/classes/com/wuban/signDemo/CustomizeHttpService.class
+0
-0
SSLSocketClient$1.class
target/classes/com/wuban/signDemo/SSLSocketClient$1.class
+0
-0
SSLSocketClient.class
target/classes/com/wuban/signDemo/SSLSocketClient.class
+0
-0
SignAndSubmit.class
target/classes/com/wuban/signDemo/SignAndSubmit.class
+0
-0
No files found.
.gitignore
0 → 100644
View file @
505b674f
*.iml
/.idea
pom.xml
0 → 100644
View file @
505b674f
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns=
"http://maven.apache.org/POM/4.0.0"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
<modelVersion>
4.0.0
</modelVersion>
<groupId>
com.wuban
</groupId>
<artifactId>
tranSignDemo
</artifactId>
<version>
1.0-SNAPSHOT
</version>
<build>
<plugins>
<plugin>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-compiler-plugin
</artifactId>
<configuration>
<source>
8
</source>
<target>
8
</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>
org.web3j
</groupId>
<artifactId>
core
</artifactId>
<version>
4.8.7
</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
src/main/java/com/wuban/signDemo/CustomizeHttpService.java
0 → 100644
View file @
505b674f
package
com
.
wuban
.
signDemo
;
import
okhttp3.*
;
import
okhttp3.logging.HttpLoggingInterceptor
;
import
okio.Buffer
;
import
okio.BufferedSource
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.web3j.protocol.Service
;
import
org.web3j.protocol.exceptions.ClientConnectionException
;
import
java.io.BufferedInputStream
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.util.HashMap
;
import
java.util.Map
;
/**
* @ClassName customizeHttpService
* @Author DuanJinFei
* @Date 2022/8/23 15:04
* @Version 1.0
*/
public
class
CustomizeHttpService
extends
Service
{
public
static
final
MediaType
JSON_MEDIA_TYPE
=
MediaType
.
parse
(
"application/json; charset=utf-8"
);
public
static
final
String
DEFAULT_URL
=
"http://localhost:8545/"
;
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
CustomizeHttpService
.
class
);
private
OkHttpClient
httpClient
;
private
final
String
url
;
private
final
boolean
includeRawResponse
;
private
HashMap
<
String
,
String
>
headers
=
new
HashMap
<>();
public
CustomizeHttpService
(
String
url
,
OkHttpClient
httpClient
,
boolean
includeRawResponses
)
{
super
(
includeRawResponses
);
this
.
url
=
url
;
this
.
httpClient
=
httpClient
;
this
.
includeRawResponse
=
includeRawResponses
;
}
public
CustomizeHttpService
(
OkHttpClient
httpClient
,
boolean
includeRawResponses
)
{
this
(
DEFAULT_URL
,
httpClient
,
includeRawResponses
);
}
private
CustomizeHttpService
(
String
url
,
OkHttpClient
httpClient
)
{
this
(
url
,
httpClient
,
false
);
}
public
CustomizeHttpService
(
String
url
)
{
this
(
url
,
createOkHttpClient
());
}
public
CustomizeHttpService
(
String
url
,
boolean
includeRawResponse
)
{
this
(
url
,
createOkHttpClient
(),
includeRawResponse
);
}
public
CustomizeHttpService
(
OkHttpClient
httpClient
)
{
this
(
DEFAULT_URL
,
httpClient
);
}
public
CustomizeHttpService
(
boolean
includeRawResponse
)
{
this
(
DEFAULT_URL
,
includeRawResponse
);
}
public
CustomizeHttpService
()
{
this
(
DEFAULT_URL
);
}
private
static
OkHttpClient
createOkHttpClient
()
{
OkHttpClient
.
Builder
builder
=
new
OkHttpClient
.
Builder
()
.
sslSocketFactory
(
SSLSocketClient
.
getSSLSocketFactory
())
.
hostnameVerifier
(
SSLSocketClient
.
getHostnameVerifier
());
configureLogging
(
builder
);
return
builder
.
build
();
}
private
static
void
configureLogging
(
OkHttpClient
.
Builder
builder
)
{
if
(
log
.
isDebugEnabled
())
{
HttpLoggingInterceptor
logging
=
new
HttpLoggingInterceptor
(
log:
:
debug
);
logging
.
setLevel
(
HttpLoggingInterceptor
.
Level
.
BODY
);
builder
.
addInterceptor
(
logging
);
}
}
@Override
protected
InputStream
performIO
(
String
request
)
throws
IOException
{
RequestBody
requestBody
=
RequestBody
.
create
(
JSON_MEDIA_TYPE
,
request
);
Headers
headers
=
buildHeaders
();
okhttp3
.
Request
httpRequest
=
new
okhttp3
.
Request
.
Builder
()
.
url
(
url
)
.
headers
(
headers
)
.
post
(
requestBody
)
.
build
();
okhttp3
.
Response
response
=
httpClient
.
newCall
(
httpRequest
).
execute
();
if
(
response
.
isSuccessful
())
{
ResponseBody
responseBody
=
response
.
body
();
if
(
responseBody
!=
null
)
{
return
buildInputStream
(
responseBody
);
}
else
{
return
null
;
}
}
else
{
throw
new
ClientConnectionException
(
"Invalid response received: "
+
response
.
body
());
}
}
private
InputStream
buildInputStream
(
ResponseBody
responseBody
)
throws
IOException
{
InputStream
inputStream
=
responseBody
.
byteStream
();
if
(
includeRawResponse
)
{
// we have to buffer the entire input payload, so that after processing
// it can be re-read and used to populate the rawResponse field.
BufferedSource
source
=
responseBody
.
source
();
source
.
request
(
Long
.
MAX_VALUE
);
// Buffer the entire body
Buffer
buffer
=
source
.
buffer
();
long
size
=
buffer
.
size
();
if
(
size
>
Integer
.
MAX_VALUE
)
{
throw
new
UnsupportedOperationException
(
"Non-integer input buffer size specified: "
+
size
);
}
int
bufferSize
=
(
int
)
size
;
BufferedInputStream
bufferedinputStream
=
new
BufferedInputStream
(
inputStream
,
bufferSize
);
bufferedinputStream
.
mark
(
inputStream
.
available
());
return
bufferedinputStream
;
}
else
{
return
inputStream
;
}
}
private
Headers
buildHeaders
()
{
return
Headers
.
of
(
headers
);
}
public
void
addHeader
(
String
key
,
String
value
)
{
headers
.
put
(
key
,
value
);
}
public
void
addHeaders
(
Map
<
String
,
String
>
headersToAdd
)
{
headers
.
putAll
(
headersToAdd
);
}
public
HashMap
<
String
,
String
>
getHeaders
()
{
return
headers
;
}
@Override
public
void
close
()
throws
IOException
{
}
}
src/main/java/com/wuban/signDemo/SSLSocketClient.java
0 → 100644
View file @
505b674f
package
com
.
wuban
.
signDemo
;
import
javax.net.ssl.*
;
import
java.security.SecureRandom
;
import
java.security.cert.X509Certificate
;
public
class
SSLSocketClient
{
/**
* 获取这个SSLSocketFactory
* @return SocketFactory
*/
public
static
SSLSocketFactory
getSSLSocketFactory
()
{
try
{
SSLContext
sslContext
=
SSLContext
.
getInstance
(
"SSL"
);
sslContext
.
init
(
null
,
getTrustManager
(),
new
SecureRandom
());
return
sslContext
.
getSocketFactory
();
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
e
);
}
}
/**
* 获取TrustManager
*/
private
static
TrustManager
[]
getTrustManager
()
{
return
new
TrustManager
[]{
new
X509TrustManager
()
{
@Override
public
void
checkClientTrusted
(
X509Certificate
[]
chain
,
String
authType
)
{
}
@Override
public
void
checkServerTrusted
(
X509Certificate
[]
chain
,
String
authType
)
{
}
@Override
public
X509Certificate
[]
getAcceptedIssuers
()
{
return
new
X509Certificate
[]{};
}
}
};
}
/**
* 获取HostnameVerifier
* @return true
*/
public
static
HostnameVerifier
getHostnameVerifier
()
{
return
(
s
,
sslSession
)
->
true
;
}
}
\ No newline at end of file
src/main/java/com/wuban/signDemo/SignAndSubmit.java
0 → 100644
View file @
505b674f
package
com
.
wuban
.
signDemo
;
import
org.web3j.crypto.*
;
import
org.web3j.protocol.Web3j
;
import
org.web3j.protocol.core.DefaultBlockParameterName
;
import
org.web3j.protocol.core.methods.response.EthGetTransactionReceipt
;
import
org.web3j.protocol.core.methods.response.EthSendTransaction
;
import
org.web3j.tx.RawTransactionManager
;
import
org.web3j.utils.Numeric
;
import
java.math.BigInteger
;
import
java.util.Objects
;
import
java.util.concurrent.ExecutionException
;
/**
* @ClassName SignAndSubmit
* @Author DuanJinFei
* @Date 2022/8/22 17:58
* @Version 1.0
*/
public
class
SignAndSubmit
{
private
static
Web3j
web3j
;
public
SignAndSubmit
(
String
rpcUrl
)
{
web3j
=
Web3j
.
build
(
new
CustomizeHttpService
(
rpcUrl
));
}
/**
* 提交交易
* @param signedMessage 交易签名
*/
public
void
submitSign
(
byte
[]
signedMessage
)
{
try
{
String
hexValue
=
Numeric
.
toHexString
(
signedMessage
);
EthSendTransaction
ethSendTransaction
=
web3j
.
ethSendRawTransaction
(
hexValue
).
sendAsync
().
get
();
// 交易Hash
String
transactionHash
=
ethSendTransaction
.
getTransactionHash
();
System
.
out
.
println
(
"transactionHash:"
+
transactionHash
);
if
(
ethSendTransaction
.
hasError
())
{
String
message
=
ethSendTransaction
.
getError
().
getMessage
();
System
.
out
.
println
(
"transaction failed,info:"
+
message
);
}
else
{
EthGetTransactionReceipt
send
=
web3j
.
ethGetTransactionReceipt
(
transactionHash
).
send
();
if
(
send
!=
null
)
{
System
.
out
.
println
(
"交易成功"
);
}
}
}
catch
(
Exception
e
)
{
if
(
e
instanceof
ExecutionException
||
e
instanceof
InterruptedException
)
{
System
.
out
.
println
(
"----------获取Nonce异常-----------"
);
}
e
.
printStackTrace
();
}
}
/**
* 获取账户交易Nonce
* @param privateKey 账户地址
* @return 返回Nonce
*/
public
BigInteger
getAddressNonce
(
String
privateKey
)
{
try
{
String
fromAddress
=
Keys
.
toChecksumAddress
(
Keys
.
getAddress
(
ECKeyPair
.
create
(
Numeric
.
toBigInt
(
privateKey
))));
System
.
out
.
println
(
"fromAddress:"
+
fromAddress
);
return
web3j
.
ethGetTransactionCount
(
fromAddress
,
DefaultBlockParameterName
.
LATEST
).
send
().
getTransactionCount
();
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
BigInteger
.
valueOf
(-
1
);
}
}
/**
* 私钥交易
* @param fromPk 发送方私钥
* @param toAddress 接收方地址
* @param value 数量 单位wei
*/
public
byte
[]
offlineSign
(
String
fromPk
,
String
toAddress
,
BigInteger
value
)
{
try
{
BigInteger
nonce
=
getAddressNonce
(
fromPk
);
System
.
out
.
println
(
"Nonce:"
+
nonce
);
BigInteger
gasPrice
=
web3j
.
ethGasPrice
().
send
().
getGasPrice
();
BigInteger
gasLimit
=
new
BigInteger
(
"900000"
);
if
(
fromPk
.
startsWith
(
"0x"
)){
fromPk
=
fromPk
.
substring
(
2
);
}
Credentials
credentials
=
Credentials
.
create
(
fromPk
);
//生成RawTransaction交易对象
RawTransaction
rawTransaction
=
RawTransaction
.
createTransaction
(
nonce
,
gasPrice
,
gasLimit
,
toAddress
,
value
,
""
);
//使用私钥生成Credentials对象
System
.
out
.
println
(
"toAddress:"
+
toAddress
);
return
TransactionEncoder
.
signMessage
(
rawTransaction
,
512512
,
credentials
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 签名且提交
* @param fromPk 发送方私钥
* @param toAddress 接收方地址
* @param value 数量 单位wei
*/
public
boolean
signAndSend
(
String
fromPk
,
String
toAddress
,
BigInteger
value
)
{
try
{
BigInteger
nonce
=
getAddressNonce
(
fromPk
);
System
.
out
.
println
(
"Nonce:"
+
nonce
);
BigInteger
gasPrice
=
web3j
.
ethGasPrice
().
send
().
getGasPrice
();
BigInteger
gasLimit
=
new
BigInteger
(
"900000"
);
Credentials
credentials
=
Credentials
.
create
(
fromPk
);
//生成RawTransaction交易对象
RawTransactionManager
transactionManager
=
new
RawTransactionManager
(
web3j
,
credentials
,
512512
);
RawTransaction
rawTransaction
=
RawTransaction
.
createTransaction
(
nonce
,
gasPrice
,
gasLimit
,
toAddress
,
value
,
""
);
//使用私钥生成Credentials对象
System
.
out
.
println
(
"toAddress:"
+
toAddress
);
EthSendTransaction
ethSendTransaction
=
transactionManager
.
signAndSend
(
rawTransaction
);
String
transactionHash
=
ethSendTransaction
.
getTransactionHash
();
if
(
ethSendTransaction
.
hasError
())
{
String
message
=
ethSendTransaction
.
getError
().
getMessage
();
System
.
out
.
println
(
"transaction failed,info:"
+
message
);
}
else
{
EthGetTransactionReceipt
send
=
web3j
.
ethGetTransactionReceipt
(
transactionHash
).
send
();
if
(
send
!=
null
)
{
System
.
out
.
println
(
"交易成功"
);
}
}
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
public
static
void
main
(
String
[]
args
)
{
SignAndSubmit
signAndSubmit
=
new
SignAndSubmit
(
"https://galaxy.block.caduceus.foundation"
);
byte
[]
signMessage
=
signAndSubmit
.
offlineSign
(
"099ff81b635b2b08fef0cba973d65a2eceb66283fae4bdaabaad01e9d74124dd"
,
"0x16C07A5C1Be38D91Df5ba86D169588702F748612"
,
new
BigInteger
(
"1000000000000000000"
));
if
(
Objects
.
isNull
(
signMessage
)){
System
.
exit
(
0
);
}
signAndSubmit
.
submitSign
(
signMessage
);
web3j
.
shutdown
();
}
}
target/classes/META-INF/tranSignDemo.kotlin_module
0 → 100644
View file @
505b674f
File added
target/classes/com/wuban/signDemo/CustomizeHttpService.class
0 → 100644
View file @
505b674f
File added
target/classes/com/wuban/signDemo/SSLSocketClient$1.class
0 → 100644
View file @
505b674f
File added
target/classes/com/wuban/signDemo/SSLSocketClient.class
0 → 100644
View file @
505b674f
File added
target/classes/com/wuban/signDemo/SignAndSubmit.class
0 → 100644
View file @
505b674f
File added
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment