From 63703d1af496034004009cdee0f4d3e15c614239 Mon Sep 17 00:00:00 2001 From: sulc <1985972071@qq.com> Date: Tue, 27 Aug 2024 22:28:08 +0800 Subject: [PATCH 1/4] pr push --- .../antchain-bridge-plugin-tester/pom.xml | 66 ++ .../java/com/ali/antchain/EthPluginsTest.java | 25 + .../java/com/ali/antchain/PluginsTest.java | 57 ++ .../Test/ETHQuerySDPMessageSeqTest.java | 82 ++ .../ETHSetAmContractAndLocalDomainTest.java | 63 ++ .../ali/antchain/Test/ETHSetProtocolTest.java | 50 ++ .../com/ali/antchain/Test/GetContextTest.java | 98 +++ .../com/ali/antchain/Test/RelayAmPrepare.java | 74 ++ .../Test/SetupAuthMessageContractTest.java | 39 + .../Test/SetupSDPMessageContractTest.java | 38 + .../com/ali/antchain/Test/ShutDownTest.java | 31 + .../com/ali/antchain/Test/StartUpTest.java | 33 + .../config/BlockHeightPolicyEnum.java | 20 + .../ali/antchain/config/EthereumConfig.java | 72 ++ .../antchain/service/EthereumBBCService.java | 699 ++++++++++++++++++ .../test/java/com/ali/antchain/EthTest.java | 58 ++ .../test/java/com/ali/antchain/TestPlugs.java | 46 ++ 17 files changed, 1551 insertions(+) create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/EthPluginsTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/PluginsTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHQuerySDPMessageSeqTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetAmContractAndLocalDomainTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetProtocolTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/GetContextTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/RelayAmPrepare.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupAuthMessageContractTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupSDPMessageContractTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ShutDownTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/StartUpTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/BlockHeightPolicyEnum.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/EthereumConfig.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/service/EthereumBBCService.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/EthTest.java create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/TestPlugs.java diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml new file mode 100644 index 00000000..8b98a9e6 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + + + com.ali.antchain + antchain-bridge-plugin-tester + 0.1.0 + jar + + PlugsTest + http://maven.apache.org + + + UTF-8 + + + + + com.alipay.antchain.bridge + antchain-bridge-plugin-lib + 0.2.3 + + + com.alipay.antchain.bridge + antchain-bridge-spi + 0.2.3 + provided + + + org.web3j + core + 4.9.8 + + + org.slf4j + slf4j-api + + + + + junit + junit + 4.13.2 + test + + + org.projectlombok + lombok + 1.18.24 + compile + + + org.slf4j + slf4j-api + 1.7.28 + provided + + + ch.qos.logback + logback-classic + 1.2.11 + test + + + diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/EthPluginsTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/EthPluginsTest.java new file mode 100644 index 00000000..e00de567 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/EthPluginsTest.java @@ -0,0 +1,25 @@ +package com.ali.antchain; + +import com.ali.antchain.Test.GetContextTest; +import com.ali.antchain.Test.ShutDownTest; +import com.ali.antchain.Test.StartUpTest; +import com.ali.antchain.config.EthereumConfig; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.commons.bbc.DefaultBBCContext; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; + +public class EthPluginsTest extends PluginsTest { + public EthPluginsTest(AbstractBBCContext context, AbstractBBCService service) { + super(context, service); + } + EthereumConfig config; + public void EthConfigInit(String url,String key,long gasPrice,long gasLimit) { + this.config = new EthereumConfig(); + config.setUrl(url); + config.setPrivateKey(key); + config.setGasPrice(gasPrice); + config.setGasLimit(gasLimit); + this.context = new DefaultBBCContext(); + context.setConfForBlockchainClient(config.toJsonString().getBytes()); + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/PluginsTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/PluginsTest.java new file mode 100644 index 00000000..c3a1dbc1 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/PluginsTest.java @@ -0,0 +1,57 @@ +package com.ali.antchain; + +import com.ali.antchain.Test.GetContextTest; +import com.ali.antchain.Test.ShutDownTest; +import com.ali.antchain.Test.StartUpTest; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; + +public class PluginsTest { + + AbstractBBCContext context; + AbstractBBCService service; + + public PluginsTest(AbstractBBCContext context, AbstractBBCService service) { + this.context = context; + this.service = service; + } + + public void startup() throws Exception { + StartUpTest.run(context, service); + } + + public void shutdown() throws Exception { + ShutDownTest.run(context,service); + } + + public void getcontext() throws Exception { + GetContextTest.run(context,service); + } + + public void setupamcontract() throws Exception {} + + public void setupsdpcontract() throws Exception {} + + public void querysdpmessageseq() throws Exception {} + + public void setprotocol() throws Exception { + + } + + public void setamcontractandlocaldomain() throws Exception { + + } + + +// public static void main(String[] args) throws Exception{ +// String url = "http://127.0.0.1:7545"; +// String key = "0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"; +// long gasPrice = 2300000000L; +// long gasLimit = 3000000; +// PlugsTest test = new PlugsTest(url,key,gasPrice,gasLimit); +//// test.ethinit.init(); +// test.startup(); +// } + + +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHQuerySDPMessageSeqTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHQuerySDPMessageSeqTest.java new file mode 100644 index 00000000..683a3a36 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHQuerySDPMessageSeqTest.java @@ -0,0 +1,82 @@ +package com.ali.antchain.Test; + +import cn.hutool.crypto.digest.DigestUtil; +import com.ali.antchain.service.EthereumBBCService; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; + +public class ETHQuerySDPMessageSeqTest { + + boolean setupBBC; + + + public static void run(AbstractBBCContext context) throws Exception { + ETHQuerySDPMessageSeqTest ETHQuerySDPMessageSeqTest = new ETHQuerySDPMessageSeqTest(); + ETHQuerySDPMessageSeqTest.querysdpmessageseq(context); + } + + public void querysdpmessageseq(AbstractBBCContext context) throws Exception { + EthereumBBCService ethereumBBCService = new EthereumBBCService(); + ethereumBBCService.startup(context); + + if (setupBBC) { + System.out.println("The BBC has already been set up."); + }else { + RelayAmPrepare.relayamprepare(context); + } +// //set up am +// ethereumBBCService.setupAuthMessageContract(); +// +// // set up sdp +// ethereumBBCService.setupSDPMessageContract(); +// +// ethereumBBCService.setProtocol( +// context.getSdpContract().getContractAddress(), +// "0"); +// +// // set am to sdp +// ethereumBBCService.setAmContract(context.getAuthMessageContract().getContractAddress()); +// +// // set local domain to sdp +// ethereumBBCService.setLocalDomain("receiverDomain"); +// +// // check contract ready +// AbstractBBCContext ctxCheck = ethereumBBCService.getContext(); +// +// System.out.println(ctxCheck.getAuthMessageContract().getStatus()); +// System.out.println(ctxCheck.getSdpContract().getStatus()); +// +// Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:7545")); +// Credentials credentials = Credentials.create("0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"); +// +// RawTransactionManager rawTransactionManager = new RawTransactionManager( +// web3j, credentials, web3j.ethChainId().send().getChainId().longValue()); +// +// AppContract appContract = AppContract.deploy( +// web3j, +// rawTransactionManager, +// new DefaultGasProvider() +// ).send(); +// +// TransactionReceipt receipt = appContract.setProtocol(ethereumBBCService.getBbcContext().getSdpContract().getContractAddress()).send(); +// if (receipt.isStatusOK()) { +// System.out.println("set protocol(" + appContract.getContractAddress()+ ") to app contract(" +ethereumBBCService.getBbcContext().getSdpContract().getContractAddress()+ ")"); +// } else { +// throw new Exception(String.format("failed to set protocol(%s) to app contract(%s)", +// appContract.getContractAddress(), +// ethereumBBCService.getBbcContext().getSdpContract().getContractAddress())); +// } +// System.out.println(receipt); +// } + + // query seq + long seq = ethereumBBCService.querySDPMessageSeq( + "senderDomain", + DigestUtil.sha256Hex("senderID"), + "receiverDomain", + DigestUtil.sha256Hex("receiverID") + ); + System.out.println(seq); + + } + +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetAmContractAndLocalDomainTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetAmContractAndLocalDomainTest.java new file mode 100644 index 00000000..f9204dea --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetAmContractAndLocalDomainTest.java @@ -0,0 +1,63 @@ +package com.ali.antchain.Test; + +import cn.hutool.core.util.HexUtil; +import com.ali.antchain.abi.SDPMsg; +import com.ali.antchain.service.EthereumBBCService; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import org.web3j.tx.gas.DefaultGasProvider; + +public class ETHSetAmContractAndLocalDomainTest { + + public static void run(AbstractBBCContext context) throws Exception { + ETHSetAmContractAndLocalDomainTest ETHSetAmContractAndLocalDomainTest = new ETHSetAmContractAndLocalDomainTest(); + ETHSetAmContractAndLocalDomainTest.setamcontractandlocaldomain(context); + } + public void setamcontractandlocaldomain(AbstractBBCContext context) throws Exception { + EthereumBBCService ethereumBBCService = new EthereumBBCService(); + // start up + ethereumBBCService.startup(context); + + // set up am + ethereumBBCService.setupAuthMessageContract(); + + // set up sdp + ethereumBBCService.setupSDPMessageContract(); + + // get context + AbstractBBCContext ctx = ethereumBBCService.getContext(); + + System.out.println(ctx.getAuthMessageContract().getStatus()); + System.out.println(ctx.getSdpContract().getStatus()); + + // set am to sdp + ethereumBBCService.setAmContract(ctx.getAuthMessageContract().getContractAddress()); + + String amAddr = SDPMsg.load( + ethereumBBCService.getBbcContext().getSdpContract().getContractAddress(), + ethereumBBCService.getWeb3j(), + ethereumBBCService.getCredentials(), + new DefaultGasProvider() + ).getAmAddress().send(); + System.out.println("amAddr: {"+amAddr+"}"); + + // check contract status + ctx = ethereumBBCService.getContext(); + System.out.println(ctx.getSdpContract().getStatus()); + + // set the domain + ethereumBBCService.setLocalDomain("receiverDomain"); + + byte[] rawDomain = SDPMsg.load( + ethereumBBCService.getBbcContext().getSdpContract().getContractAddress(), + ethereumBBCService.getWeb3j(), + ethereumBBCService.getCredentials(), + new DefaultGasProvider() + ).getLocalDomain().send(); + System.out.println("domain: {"+HexUtil.encodeHexStr(rawDomain)+ "}"); + + // check contract status + ctx = ethereumBBCService.getContext(); + System.out.println(ctx.getSdpContract().getStatus()); + + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetProtocolTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetProtocolTest.java new file mode 100644 index 00000000..f2ae4aff --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetProtocolTest.java @@ -0,0 +1,50 @@ +package com.ali.antchain.Test; + +import com.ali.antchain.abi.AuthMsg; +import com.ali.antchain.service.EthereumBBCService; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import org.web3j.tx.gas.DefaultGasProvider; + +import java.math.BigInteger; + +public class ETHSetProtocolTest { + + public static void run(AbstractBBCContext context) throws Exception { + ETHSetProtocolTest ETHSetProtocolTest = new ETHSetProtocolTest(); + ETHSetProtocolTest.setprotocol(context); + } + public void setprotocol(AbstractBBCContext context) throws Exception { + EthereumBBCService ethereumBBCService = new EthereumBBCService(); + // start up + ethereumBBCService.startup(context); + + // set up am + ethereumBBCService.setupAuthMessageContract(); + + // set up sdp + ethereumBBCService.setupSDPMessageContract(); + + // get context + AbstractBBCContext ctx = ethereumBBCService.getContext(); + System.out.println(ctx.getAuthMessageContract().getStatus()); + System.out.println(ctx.getSdpContract().getStatus()); + + // set protocol to am (sdp type: 0) + ethereumBBCService.setProtocol( + ctx.getSdpContract().getContractAddress(), + "0"); + + String addr = AuthMsg.load( + ethereumBBCService.getBbcContext().getAuthMessageContract().getContractAddress(), + ethereumBBCService.getWeb3j(), + ethereumBBCService.getCredentials(), + new DefaultGasProvider() + ).getProtocol(BigInteger.ZERO).send(); + System.out.println("protocol: {" + addr + "}"); + + // check am status + ctx = ethereumBBCService.getContext(); + System.out.println(ctx.getAuthMessageContract().getStatus()); + + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/GetContextTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/GetContextTest.java new file mode 100644 index 00000000..6316e017 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/GetContextTest.java @@ -0,0 +1,98 @@ +package com.ali.antchain.Test; + +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.commons.bbc.syscontract.AuthMessageContract; +import com.alipay.antchain.bridge.commons.bbc.syscontract.SDPContract; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GetContextTest { + + private static final Logger log = LoggerFactory.getLogger(GetContextTest.class); + AbstractBBCService service; + + public GetContextTest(AbstractBBCService service) { + this.service = service; + } + public static void run(AbstractBBCContext context, AbstractBBCService service){ + GetContextTest getctx = new GetContextTest(service); + getctx.getcontext(context); + } + public void getcontext(AbstractBBCContext context){ + if (service == null) { + throw new IllegalStateException("Service is not initialized."); + } + try { + // 启动服务 + service.startup(context); + // 获取上下文 + AbstractBBCContext ctx = service.getContext(); + // 检查上下文是否为空 + if (ctx != null) { + log.info( "Context: {}", ctx); + + // 打印 AM 合约 + processAuthMessageContract(ctx); + + // 打印 SDP 合约 + processSDPContract(ctx); + + } else { + log.warn( "Context is null."); + } + } catch (Exception e) { + // 处理异常 + log.error("An error occurred: ", e); + } + } + private void processAuthMessageContract(AbstractBBCContext ctx) { + AuthMessageContract authMessageContract = ctx.getAuthMessageContract(); + if (authMessageContract != null) { + log.info("Auth Message Contract: {}", authMessageContract); + } + } + + private void processSDPContract(AbstractBBCContext ctx) { + SDPContract sdpContract = ctx.getSdpContract(); + if (sdpContract != null) { + log.info("SDP Contract: {}", sdpContract); + } + } +} + +//public class GetContextTest { +// +// private static final Logger log = LoggerFactory.getLogger(GetContextTest.class); +// +// private AbstractBBCService service; +// +// public GetContextTest(AbstractBBCService service) { +// this.service = service; +// } +// +// public static void run(AbstractBBCContext context){ +// getcontext(context); +// } +// +// public void getcontext(AbstractBBCContext context){ +// if (service == null) { +// throw new IllegalStateException("Service is not initialized."); +// } +// try { +// service.startup(context); +// AbstractBBCContext ctx = service.getContext(); +// if (ctx != null) { +// log.info("Context: {}", ctx); +// processAuthMessageContract(ctx); +// processSDPContract(ctx); +// } else { +// log.warn("Context is null."); +// } +// } catch (Exception e) { +// log.error("An unexpected error occurred: ", e); +// } +// } +// +// +//} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/RelayAmPrepare.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/RelayAmPrepare.java new file mode 100644 index 00000000..edf95712 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/RelayAmPrepare.java @@ -0,0 +1,74 @@ +package com.ali.antchain.Test; + +import com.ali.antchain.abi.AppContract; +import com.ali.antchain.service.EthereumBBCService; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.protocol.http.HttpService; +import org.web3j.tx.RawTransactionManager; +import org.web3j.tx.gas.DefaultGasProvider; + +public class RelayAmPrepare { + + static boolean setupBBC; + static AppContract appContract; + + public static void relayamprepare(AbstractBBCContext context) throws Exception { + if (setupBBC) { + return; + } + + // start up + EthereumBBCService ethereumBBCService = new EthereumBBCService(); + ethereumBBCService.startup(context); + + // set up am + ethereumBBCService.setupAuthMessageContract(); + + // set up sdp + ethereumBBCService.setupSDPMessageContract(); + + // set protocol to am (sdp type: 0) + ethereumBBCService.setProtocol( + context.getSdpContract().getContractAddress(), + "0"); + + // set am to sdp + ethereumBBCService.setAmContract(context.getAuthMessageContract().getContractAddress()); + + // set local domain to sdp + ethereumBBCService.setLocalDomain("receiverDomain"); + + // check contract ready + AbstractBBCContext ctxCheck = ethereumBBCService.getContext(); + + System.out.println(ctxCheck.getAuthMessageContract().getStatus()); + System.out.println(ctxCheck.getSdpContract().getStatus()); + + Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:7545")); + Credentials credentials = Credentials.create("0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"); + + RawTransactionManager rawTransactionManager = new RawTransactionManager( + web3j, credentials, web3j.ethChainId().send().getChainId().longValue()); + + appContract = AppContract.deploy( + web3j, + rawTransactionManager, + new DefaultGasProvider() + ).send(); + + TransactionReceipt receipt = appContract.setProtocol(ethereumBBCService.getBbcContext().getSdpContract().getContractAddress()).send(); + if (receipt.isStatusOK()) { + System.out.println("set protocol(" + appContract.getContractAddress()+ ") to app contract(" +ethereumBBCService.getBbcContext().getSdpContract().getContractAddress()+ ")"); + } else { + throw new Exception(String.format("failed to set protocol(%s) to app contract(%s)", + appContract.getContractAddress(), + ethereumBBCService.getBbcContext().getSdpContract().getContractAddress())); + } + System.out.println(receipt); + + setupBBC = true; + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupAuthMessageContractTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupAuthMessageContractTest.java new file mode 100644 index 00000000..327b5de7 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupAuthMessageContractTest.java @@ -0,0 +1,39 @@ +package com.ali.antchain.Test; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; + + + +public class SetupAuthMessageContractTest { + + private static final Logger log = LoggerFactory.getLogger(SetupAuthMessageContractTest.class); + AbstractBBCService service; + + public SetupAuthMessageContractTest(AbstractBBCService service) { + this.service = service; + } + + public static void run(AbstractBBCContext context, AbstractBBCService service){ + SetupAuthMessageContractTest SetupAm = new SetupAuthMessageContractTest(service); + SetupAm.setupamcontract(context); + } + + public void setupamcontract(AbstractBBCContext context) { + try { + service.startup(context); + service.setupAuthMessageContract(); + + // 获取上下文 + AbstractBBCContext ctx = service.getContext(); + + // 打印AM合约状态 + log.info("The status of the auth message contract is: {}", ctx.getAuthMessageContract().getStatus()); + } catch (Exception e) { + // 异常信息 + log.error("Failed to setup authentication message contract", e); + } + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupSDPMessageContractTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupSDPMessageContractTest.java new file mode 100644 index 00000000..6825c874 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupSDPMessageContractTest.java @@ -0,0 +1,38 @@ +package com.ali.antchain.Test; + +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SetupSDPMessageContractTest { + + private static final Logger log = LoggerFactory.getLogger(SetupAuthMessageContractTest.class); + AbstractBBCService service; + + public SetupSDPMessageContractTest(AbstractBBCService service) { + this.service = service; + } + + public static void run(AbstractBBCContext context, AbstractBBCService service){ + SetupSDPMessageContractTest SetupSDP = new SetupSDPMessageContractTest(service); + SetupSDP.setupsdpcontract(context); + } + + public void setupsdpcontract(AbstractBBCContext context) { + if (service == null) { + throw new IllegalStateException("Service is not initialized."); + } + try { + service.startup(context); + service.setupAuthMessageContract(); + // set up sdp + service.setupSDPMessageContract(); + // get context + AbstractBBCContext ctx = service.getContext(); + log.info("SDP contract status: {}", ctx.getSdpContract().getStatus()); + } catch (Exception e) { + log.error("Error setting up SDP contract", e); + } + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ShutDownTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ShutDownTest.java new file mode 100644 index 00000000..d82da61a --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ShutDownTest.java @@ -0,0 +1,31 @@ +package com.ali.antchain.Test; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; + +public class ShutDownTest { + + private static final Logger log = LoggerFactory.getLogger(ShutDownTest.class); + AbstractBBCService service; + + public ShutDownTest(AbstractBBCService service) { + this.service = service; + } + + public static void run(AbstractBBCContext context, AbstractBBCService service){ + ShutDownTest shutdown = new ShutDownTest(service); + shutdown.shutdown(context); + } + + public void shutdown(AbstractBBCContext context){ + try { + // 调用 shutdown关闭服务 + service.shutdown(); + } catch (Exception e) { + // 异常 + log.error("Failed to setup authentication message contract", e.getMessage()); + } + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/StartUpTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/StartUpTest.java new file mode 100644 index 00000000..19f28a13 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/StartUpTest.java @@ -0,0 +1,33 @@ +package com.ali.antchain.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; + +public class StartUpTest { + + private static final Logger log = LoggerFactory.getLogger(StartUpTest.class); + AbstractBBCService service; + + public StartUpTest(AbstractBBCService service) { + this.service = service; + } + + public static void run(AbstractBBCContext context, AbstractBBCService service){ + StartUpTest startUpTest = new StartUpTest(service); + startUpTest.startuptest_success(context); + } + + public void startuptest_success(AbstractBBCContext context) { + try { + service.startup(context); + // 使用日志框架记录信息 + log.info("Context: {}", service.getContext()); + log.info("AuthMessageContract: {}", service.getContext().getAuthMessageContract()); + log.info("SdpContract: {}", service.getContext().getSdpContract()); + } catch (Exception e) { + // 异常处理 + log.error("Error during startup test", e); + } + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/BlockHeightPolicyEnum.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/BlockHeightPolicyEnum.java new file mode 100644 index 00000000..51917f06 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/BlockHeightPolicyEnum.java @@ -0,0 +1,20 @@ +package com.ali.antchain.config; + +import lombok.Getter; +import org.web3j.protocol.core.DefaultBlockParameterName; + +@Getter +public enum BlockHeightPolicyEnum { + + LATEST(DefaultBlockParameterName.LATEST), + + SAFE(DefaultBlockParameterName.SAFE), + + FINALIZED(DefaultBlockParameterName.FINALIZED); + + BlockHeightPolicyEnum(DefaultBlockParameterName defaultBlockParameterName) { + this.defaultBlockParameterName = defaultBlockParameterName; + } + + private final DefaultBlockParameterName defaultBlockParameterName; +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/EthereumConfig.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/EthereumConfig.java new file mode 100644 index 00000000..a6f5b54e --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/EthereumConfig.java @@ -0,0 +1,72 @@ +/* + * Copyright 2023 Ant Group + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.ali.antchain.config; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import lombok.Getter; +import lombok.Setter; +import org.web3j.tx.gas.DefaultGasProvider; + +import java.io.IOException; + +/** + * Ethereum's configuration information + * - Url for Ethereum node rpc + * - Private key + */ +@Getter +@Setter +public class EthereumConfig { + + /** + * 从json字符串反序列化 + * + * @param jsonString raw json + */ + public static EthereumConfig fromJsonString(String jsonString) throws IOException { + return JSON.parseObject(jsonString, EthereumConfig.class); + } + + @JSONField + private String url; + + @JSONField + private String privateKey; + + @JSONField + private long gasLimit = DefaultGasProvider.GAS_LIMIT.longValue(); + + @JSONField + private long gasPrice = DefaultGasProvider.GAS_PRICE.longValue(); + + @JSONField + private String amContractAddressDeployed; + + @JSONField + private String sdpContractAddressDeployed; + + @JSONField + private BlockHeightPolicyEnum blockHeightPolicy = BlockHeightPolicyEnum.LATEST; + + /** + * json序列化为字符串 + */ + public String toJsonString() { + return JSON.toJSONString(this); + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/service/EthereumBBCService.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/service/EthereumBBCService.java new file mode 100644 index 00000000..329bb6f6 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/service/EthereumBBCService.java @@ -0,0 +1,699 @@ +/* + * Copyright 2023 Ant Group + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.ali.antchain.service; + +import cn.hutool.core.collection.ListUtil; +import cn.hutool.core.util.HexUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.ali.antchain.abi.AuthMsg; +import com.ali.antchain.abi.SDPMsg; +import com.ali.antchain.config.EthereumConfig; +import com.alibaba.fastjson.JSON; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.commons.bbc.syscontract.AuthMessageContract; +import com.alipay.antchain.bridge.commons.bbc.syscontract.ContractStatusEnum; +import com.alipay.antchain.bridge.commons.bbc.syscontract.SDPContract; +import com.alipay.antchain.bridge.commons.core.base.CrossChainMessage; +import com.alipay.antchain.bridge.commons.core.base.CrossChainMessageReceipt; + +import com.alipay.antchain.bridge.plugins.lib.BBCService; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; +import lombok.Getter; +import org.web3j.abi.EventEncoder; +import org.web3j.abi.FunctionEncoder; +import org.web3j.abi.datatypes.DynamicBytes; +import org.web3j.abi.datatypes.Function; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.DefaultBlockParameterName; +import org.web3j.protocol.core.DefaultBlockParameterNumber; +import org.web3j.protocol.core.methods.request.EthFilter; +import org.web3j.protocol.core.methods.request.Transaction; +import org.web3j.protocol.core.methods.response.*; +import org.web3j.protocol.http.HttpService; +import org.web3j.tx.RawTransactionManager; +import org.web3j.tx.gas.StaticGasProvider; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import static com.ali.antchain.abi.AuthMsg.SENDAUTHMESSAGE_EVENT; + +@BBCService(products = "simple-ethereum", pluginId = "plugin-simple-ethereum") +@Getter +public class EthereumBBCService extends AbstractBBCService { + + private EthereumConfig config; + + private Web3j web3j; + + private Credentials credentials; + + private AbstractBBCContext bbcContext; + + private RawTransactionManager rawTransactionManager; + + @Override + public void startup(AbstractBBCContext abstractBBCContext) { + getBBCLogger().info("ETH BBCService startup with context: {}", new String(abstractBBCContext.getConfForBlockchainClient())); + + if (ObjectUtil.isNull(abstractBBCContext)) { + throw new RuntimeException("null bbc context"); + } + if (ObjectUtil.isEmpty(abstractBBCContext.getConfForBlockchainClient())) { + throw new RuntimeException("empty blockchain client conf"); + } + + // 1. Obtain the configuration information + try { + config = EthereumConfig.fromJsonString(new String(abstractBBCContext.getConfForBlockchainClient())); + } catch (IOException e) { + throw new RuntimeException(e); + } + + if(StrUtil.isEmpty(config.getPrivateKey())){ + throw new RuntimeException("private key is empty"); + } + + if(StrUtil.isEmpty(config.getUrl())){ + throw new RuntimeException("ethereum url is empty"); + } + + // 2. Connect to the Ethereum network + BigInteger chainId; + try { + web3j = Web3j.build(new HttpService(config.getUrl())); + chainId = web3j.ethChainId().send().getChainId(); + } catch (Exception e) { + throw new RuntimeException(String.format("failed to connect ethereum (url: %s)", config.getUrl()), e); + } + + // 3. Connect to the specified wallet account + this.credentials = Credentials.create(config.getPrivateKey()); + + // 4. Create tx manager with web3j and credentials + this.rawTransactionManager = new RawTransactionManager(this.web3j, this.credentials, chainId.longValue()); + + // 5. set context + this.bbcContext = abstractBBCContext; + + // 6. set the pre-deployed contracts into context + if (ObjectUtil.isNull(abstractBBCContext.getAuthMessageContract()) + && StrUtil.isNotEmpty(this.config.getAmContractAddressDeployed())) { + AuthMessageContract authMessageContract = new AuthMessageContract(); + authMessageContract.setContractAddress(this.config.getAmContractAddressDeployed()); + authMessageContract.setStatus(ContractStatusEnum.CONTRACT_DEPLOYED); + this.bbcContext.setAuthMessageContract(authMessageContract); + } + + if (ObjectUtil.isNull(abstractBBCContext.getSdpContract()) + && StrUtil.isNotEmpty(this.config.getSdpContractAddressDeployed())) { + SDPContract sdpContract = new SDPContract(); + sdpContract.setContractAddress(this.config.getSdpContractAddressDeployed()); + sdpContract.setStatus(ContractStatusEnum.CONTRACT_DEPLOYED); + this.bbcContext.setSdpContract(sdpContract); + } + } + + @Override + public void shutdown() { + getBBCLogger().info("shut down ETH BBCService!"); + this.web3j.shutdown(); + } + + @Override + public AbstractBBCContext getContext() { + if (ObjectUtil.isNull(this.bbcContext)){ + throw new RuntimeException("empty bbc context"); + } + + getBBCLogger().debug("ETH BBCService context (amAddr: {}, amStatus: {}, sdpAddr: {}, sdpStatus: {})", + this.bbcContext.getAuthMessageContract() != null ? this.bbcContext.getAuthMessageContract().getContractAddress() : "", + this.bbcContext.getAuthMessageContract() != null ? this.bbcContext.getAuthMessageContract().getStatus() : "", + this.bbcContext.getSdpContract() != null ? this.bbcContext.getSdpContract().getContractAddress() : "", + this.bbcContext.getSdpContract() != null ? this.bbcContext.getSdpContract().getStatus() : "" + ); + + return this.bbcContext; + } + + @Override + public CrossChainMessageReceipt readCrossChainMessageReceipt(String txHash) { + // 1. Obtain Ethereum receipt according to transaction hash + TransactionReceipt transactionReceipt; + + try { + transactionReceipt = web3j.ethGetTransactionReceipt(txHash) + .send().getTransactionReceipt().orElse(null); + } catch (IOException e) { + throw new RuntimeException( + String.format( + "failed to read cross chain message receipt (txHash: %s)", txHash + ), e + ); + } + + // 2. Construct cross-chain message receipt + CrossChainMessageReceipt crossChainMessageReceipt = getCrossChainMessageReceipt(transactionReceipt); + getBBCLogger().info("cross chain message receipt for txhash {} : {}", txHash, JSON.toJSONString(crossChainMessageReceipt)); + + return crossChainMessageReceipt; + } + + private CrossChainMessageReceipt getCrossChainMessageReceipt(TransactionReceipt transactionReceipt) { + CrossChainMessageReceipt crossChainMessageReceipt = new CrossChainMessageReceipt(); + if (transactionReceipt == null) { + // If the transaction is not packaged, the return receipt is empty + crossChainMessageReceipt.setConfirmed(false); + crossChainMessageReceipt.setSuccessful(false); + crossChainMessageReceipt.setTxhash(""); + crossChainMessageReceipt.setErrorMsg(""); + return crossChainMessageReceipt; + } + + BigInteger currHeight = queryLatestBlockHeight(); + if (transactionReceipt.getBlockNumber().compareTo(currHeight) > 0) { + crossChainMessageReceipt.setConfirmed(false); + crossChainMessageReceipt.setSuccessful(true); + crossChainMessageReceipt.setTxhash(transactionReceipt.getTransactionHash()); + crossChainMessageReceipt.setErrorMsg(""); + return crossChainMessageReceipt; + } + + List receiveMessageEventResponses = SDPMsg.getReceiveMessageEvents(transactionReceipt); + if (ObjectUtil.isNotEmpty(receiveMessageEventResponses)) { + SDPMsg.ReceiveMessageEventResponse response = receiveMessageEventResponses.get(0); + crossChainMessageReceipt.setConfirmed(true); + crossChainMessageReceipt.setSuccessful(transactionReceipt.isStatusOK() && response.result); + crossChainMessageReceipt.setTxhash(transactionReceipt.getTransactionHash()); + crossChainMessageReceipt.setErrorMsg( + transactionReceipt.isStatusOK() ? StrUtil.format( + "SDP calls biz contract: {}", response.result ? "SUCCESS" : response.errMsg + ) : StrUtil.emptyToDefault(transactionReceipt.getRevertReason(), "") + ); + getBBCLogger().info( + "event receiveMessage from SDP contract is found in no.{} tx {} of block {} : " + + "( send_domain: {}, sender: {}, receiver: {}, biz_call: {}, err_msg: {} )", + transactionReceipt.getTransactionIndex().toString(), transactionReceipt.getTransactionHash(), transactionReceipt.getBlockHash(), + response.senderDomain, HexUtil.encodeHexStr(response.senderID), response.receiverID, response.result.toString(), + response.errMsg + ); + return crossChainMessageReceipt; + } + + crossChainMessageReceipt.setConfirmed(true); + crossChainMessageReceipt.setSuccessful(transactionReceipt.isStatusOK()); + crossChainMessageReceipt.setTxhash(transactionReceipt.getTransactionHash()); + crossChainMessageReceipt.setErrorMsg(StrUtil.emptyToDefault(transactionReceipt.getRevertReason(), "")); + + return crossChainMessageReceipt; + } + + @Override + public List readCrossChainMessagesByHeight(long height) { + if (ObjectUtil.isNull(this.bbcContext)){ + throw new RuntimeException("empty bbc context"); + } + + if (ObjectUtil.isNull(this.bbcContext.getAuthMessageContract())){ + throw new RuntimeException("empty am contract in bbc context"); + } + + try { + // 1. get eth logs + List logs = web3j.ethGetLogs( + new EthFilter( + new DefaultBlockParameterNumber(BigInteger.valueOf(height)), + new DefaultBlockParameterNumber(BigInteger.valueOf(height)), + this.bbcContext.getAuthMessageContract().getContractAddress() + ).addSingleTopic(EventEncoder.encode(SENDAUTHMESSAGE_EVENT)) + ).send().getLogs(); + + // 2. get block + EthBlock.Block block = web3j.ethGetBlockByNumber(new DefaultBlockParameterNumber(height), false).send().getBlock(); + + // 3. get crosschain msgs + List messageList = ListUtil.toList(); + for (EthLog.LogResult logResult : logs) { + // 3.1 get log obj + EthLog.LogObject logObject = (EthLog.LogObject) logResult.get(); + + // 3.2 get receipt + TransactionReceipt transactionReceipt; + transactionReceipt = web3j.ethGetTransactionReceipt(logObject.getTransactionHash()).send().getResult(); + + // 3.3 create crosschain msg + messageList.addAll(AuthMsg.getSendAuthMessageEvents(transactionReceipt).stream().map( + response -> CrossChainMessage.createCrossChainMessage( + CrossChainMessage.CrossChainMessageType.AUTH_MSG, + logObject.getBlockNumber().longValue(), + block.getTimestamp().longValue(), + HexUtil.decodeHex(StrUtil.removePrefix(logObject.getBlockHash().trim(), "0x")), + response.pkg, + // todo: put ledger data, for SPV or other attestations + // this time we need no verify. it's ok to set it with empty bytes + "".getBytes(), + // todo: put proof data + // this time we need no proof data. it's ok to set it with empty bytes + "".getBytes(), + HexUtil.decodeHex(logObject.getTransactionHash().replaceFirst("^0x", "")) + ) + ).collect(Collectors.toList())); + } + + if (!messageList.isEmpty()) { + getBBCLogger().info("read cross chain messages (height: {}, msg_size: {})", height, messageList.size()); + getBBCLogger().debug("read cross chain messages (height: {}, msgs: {})", + height, + messageList.stream().map(JSON::toJSONString).collect(Collectors.joining(",")) + ); + } + + return messageList; + } catch (Exception e) { + throw new RuntimeException( + String.format( + "failed to readCrossChainMessagesByHeight (Height: %d, contractAddr: %s, topic: %s)", + height, + this.bbcContext.getAuthMessageContract().getContractAddress(), + SENDAUTHMESSAGE_EVENT + ), e + ); + } + } + + @Override + public Long queryLatestHeight() { + Long l = queryLatestBlockHeight().longValue(); + getBBCLogger().debug("latest height: {}", l); + return l; + } + + private BigInteger queryLatestBlockHeight() { + BigInteger l; + try { + l = web3j.ethGetBlockByNumber(config.getBlockHeightPolicy().getDefaultBlockParameterName(), false) + .send() + .getBlock() + .getNumber(); + } catch (IOException e) { + throw new RuntimeException("failed to query latest height", e); + } + return l; + } + + @Override + public void setupAuthMessageContract() { + // 1. check context + if (ObjectUtil.isNull(this.bbcContext)){ + throw new RuntimeException("empty bbc context"); + } + if (ObjectUtil.isNotNull(this.bbcContext.getAuthMessageContract()) + && StrUtil.isNotEmpty(this.bbcContext.getAuthMessageContract().getContractAddress())) { + // If the contract has been pre-deployed and the contract address is configured in the configuration file, + // there is no need to redeploy. + return; + } + + // 2. deploy contract + AuthMsg authMsg; + try { + authMsg = AuthMsg.deploy( + web3j, + rawTransactionManager, + new StaticGasProvider( + BigInteger.valueOf(this.config.getGasPrice()), + BigInteger.valueOf(this.config.getGasLimit()) + ) + ).send(); + } catch (Exception e) { + throw new RuntimeException("failed to deploy authMsg", e); + } + + // 3. get tx receipt + TransactionReceipt transactionReceipt = authMsg.getTransactionReceipt().orElse(null); + + // 4. check whether the deployment is successful + if (!ObjectUtil.isNull(transactionReceipt) && transactionReceipt.getStatus().equals("0x1")) { + AuthMessageContract authMessageContract = new AuthMessageContract(); + authMessageContract.setContractAddress(authMsg.getContractAddress()); + authMessageContract.setStatus(ContractStatusEnum.CONTRACT_DEPLOYED); + bbcContext.setAuthMessageContract(authMessageContract); + + getBBCLogger().info("setup am contract successful: {}", authMsg.getContractAddress()); + } else { + throw new RuntimeException("failed to get deploy authMsg tx receipt"); + } + } + + @Override + public void setupSDPMessageContract() { + // 1. check context + if (ObjectUtil.isNull(this.bbcContext)){ + throw new RuntimeException("empty bbc context"); + } + if (ObjectUtil.isNotNull(this.bbcContext.getSdpContract()) + && StrUtil.isNotEmpty(this.bbcContext.getSdpContract().getContractAddress())) { + // If the contract has been pre-deployed and the contract address is configured in the configuration file, + // there is no need to redeploy. + return; + } + + // 2. deploy contract + SDPMsg sdpMsg; + try { + sdpMsg = SDPMsg.deploy( + web3j, + rawTransactionManager, + new StaticGasProvider( + BigInteger.valueOf(this.config.getGasPrice()), + BigInteger.valueOf(this.config.getGasLimit()) + ) + ).send(); + } catch (Exception e) { + throw new RuntimeException("failed to deploy sdpMsg", e); + } + + // 3. get tx receipt + TransactionReceipt transactionReceipt = sdpMsg.getTransactionReceipt().orElse(null); + + // 4. check whether the deployment is successful + if (!ObjectUtil.isNull(transactionReceipt) && transactionReceipt.getStatus().equals("0x1")) { + SDPContract sdpContract = new SDPContract(); + sdpContract.setContractAddress(sdpMsg.getContractAddress()); + sdpContract.setStatus(ContractStatusEnum.CONTRACT_DEPLOYED); + bbcContext.setSdpContract(sdpContract); + getBBCLogger().info("setup sdp contract successful: {}", sdpMsg.getContractAddress()); + } else { + throw new RuntimeException("failed to get deploy sdpMsg tx receipt"); + } + } + + @Override + public long querySDPMessageSeq(String senderDomain, String senderID, String receiverDomain, String receiverID) { + // 1. check context + if (ObjectUtil.isNull(this.bbcContext)){ + throw new RuntimeException("empty bbc context"); + } + if (ObjectUtil.isNull(this.bbcContext.getSdpContract())){ + throw new RuntimeException("empty sdp contract in bbc context"); + } + + // 2. load sdpMsg + SDPMsg sdpMsg = SDPMsg.load( + bbcContext.getSdpContract().getContractAddress(), + web3j, + rawTransactionManager, + new StaticGasProvider( + BigInteger.valueOf(this.config.getGasPrice()), + BigInteger.valueOf(this.config.getGasLimit()) + ) + ); + + // 3. query sequence + long seq; + try { + seq = sdpMsg.querySDPMessageSeq( + senderDomain, + HexUtil.decodeHex(senderID), + receiverDomain, + HexUtil.decodeHex(receiverID) + ).send().longValue(); + + getBBCLogger().info("sdpMsg seq: {} (senderDomain: {}, senderID: {}, receiverDomain: {}, receiverID: {})", + seq, + senderDomain, + senderID, + receiverDomain, + receiverID + ); + } catch (Exception e) { + throw new RuntimeException(String.format( + "failed to query sdpMsg seq (senderDomain: %s, senderID: %s, receiverDomain: %s, receiverID: %s)", + senderDomain, + senderID, + receiverDomain, + receiverID + ), e); + } + + return seq; + } + + @Override + public void setProtocol(String protocolAddress, String protocolType) { + // 1. check context + if (ObjectUtil.isNull(this.bbcContext)) { + throw new RuntimeException("empty bbc context"); + } + if (ObjectUtil.isNull(this.bbcContext.getAuthMessageContract())){ + throw new RuntimeException("empty am contract in bbc context"); + } + + // 2. load am contract + AuthMsg am = AuthMsg.load( + this.bbcContext.getAuthMessageContract().getContractAddress(), + this.web3j, + this.rawTransactionManager, + new StaticGasProvider( + BigInteger.valueOf(this.config.getGasPrice()), + BigInteger.valueOf(this.config.getGasLimit()) + ) + ); + + // 3. set protocol to am + try { + TransactionReceipt receipt = am.setProtocol(protocolAddress, BigInteger.valueOf(Long.parseLong(protocolType))).send(); + getBBCLogger().info( + "set protocol (address: {}, type: {}) to AM {} by tx {} ", + protocolAddress, protocolType, + this.bbcContext.getAuthMessageContract().getContractAddress(), + receipt.getTransactionHash() + ); + } catch (Exception e) { + throw new RuntimeException( + String.format( + "failed to set protocol (address: %s, type: %s) to AM %s", + protocolAddress, protocolType, this.bbcContext.getAuthMessageContract().getContractAddress() + ), e + ); + } + + // 4. update am contract status + try { + if (!StrUtil.isEmpty(am.getProtocol(BigInteger.ZERO).send())){ + this.bbcContext.getAuthMessageContract().setStatus(ContractStatusEnum.CONTRACT_READY); + } + } catch (Exception e) { + throw new RuntimeException( + String.format( + "failed to update am contract status (address: %s)", + this.bbcContext.getAuthMessageContract().getContractAddress() + ), e); + } + } + + @Override + public void setAmContract(String contractAddress) { + // 1. check context + if (ObjectUtil.isNull(this.bbcContext)) { + throw new RuntimeException("empty bbc context"); + } + if (ObjectUtil.isNull(this.bbcContext.getSdpContract())){ + throw new RuntimeException("empty sdp contract in bbc context"); + } + + // 2. load sdp contract + SDPMsg sdp = SDPMsg.load( + this.bbcContext.getSdpContract().getContractAddress(), + this.web3j, + this.rawTransactionManager, + new StaticGasProvider( + BigInteger.valueOf(this.config.getGasPrice()), + BigInteger.valueOf(this.config.getGasLimit()) + ) + ); + + // 3. set am to sdp + try { + TransactionReceipt receipt = sdp.setAmContract(contractAddress).send(); + getBBCLogger().info( + "set am contract (address: {}) to SDP {} by tx {}", + contractAddress, + this.bbcContext.getSdpContract().getContractAddress(), + receipt.getTransactionHash() + ); + } catch (Exception e) { + throw new RuntimeException( + String.format( + "failed to set am contract (address: %s) to SDP %s", + contractAddress, + this.bbcContext.getSdpContract().getContractAddress() + ), e + ); + } + + // 4. update sdp contract status + try { + if (!StrUtil.isEmpty(sdp.getAmAddress().send()) && !isByteArrayZero(sdp.getLocalDomain().send())){ + this.bbcContext.getSdpContract().setStatus(ContractStatusEnum.CONTRACT_READY); + } + } catch (Exception e) { + throw new RuntimeException( + String.format( + "failed to update sdp contract status (address: %s)", + this.bbcContext.getSdpContract().getContractAddress() + ), e); + } + } + + private boolean isByteArrayZero(byte[] bytes) { + for (byte b : bytes) { + if (b != 0x00) { + return false; + } + } + return true; + } + + @Override + public void setLocalDomain(String domain) { + // 1. check context + if (ObjectUtil.isNull(this.bbcContext)) { + throw new RuntimeException("empty bbc context"); + } + if (StrUtil.isEmpty(this.bbcContext.getSdpContract().getContractAddress())) { + throw new RuntimeException("none sdp contract address"); + } + + // 2. load sdp contract + SDPMsg sdp = SDPMsg.load( + this.bbcContext.getSdpContract().getContractAddress(), + this.web3j, + this.rawTransactionManager, + new StaticGasProvider( + BigInteger.valueOf(this.config.getGasPrice()), + BigInteger.valueOf(this.config.getGasLimit()) + ) + ); + + // 3. set domain to sdp + try { + TransactionReceipt receipt = sdp.setLocalDomain(domain).send(); + getBBCLogger().info( + "set domain ({}) to SDP {} by tx {}", + domain, + this.bbcContext.getSdpContract().getContractAddress(), + receipt.getTransactionHash() + ); + } catch (Exception e) { + throw new RuntimeException( + String.format( + "failed to set domain (%s) to SDP %s", + domain, + this.bbcContext.getSdpContract().getContractAddress() + ), e + ); + } + + // 4. update sdp contract status + try { + if (!StrUtil.isEmpty(sdp.getAmAddress().send()) && !ObjectUtil.isEmpty(sdp.getLocalDomain().send())){ + this.bbcContext.getSdpContract().setStatus(ContractStatusEnum.CONTRACT_READY); + } + } catch (Exception e) { + throw new RuntimeException( + String.format( + "failed to update sdp contract status (address: %s)", + this.bbcContext.getSdpContract().getContractAddress() + ), e); + } + } + + @Override + public CrossChainMessageReceipt relayAuthMessage(byte[] rawMessage) { + // 1. check context + if (ObjectUtil.isNull(this.bbcContext)) { + throw new RuntimeException("empty bbc context"); + } + if (ObjectUtil.isNull(this.bbcContext.getAuthMessageContract())){ + throw new RuntimeException("empty am contract in bbc context"); + } + + getBBCLogger().info("relay AM {} to {} ", + HexUtil.encodeHexStr(rawMessage), this.bbcContext.getAuthMessageContract().getContractAddress()); + + // 2. creat Transaction + try { + // 2.1 create function + Function function = new Function( + AuthMsg.FUNC_RECVPKGFROMRELAYER, // funtion name + Collections.singletonList(new DynamicBytes(rawMessage)), // inputs + Collections.emptyList() // outputs + ); + String encodedFunc = FunctionEncoder.encode(function); + + // 2.2 pre-execute before commit tx + EthCall call = this.web3j.ethCall( + Transaction.createEthCallTransaction( + this.credentials.getAddress(), + this.bbcContext.getAuthMessageContract().getContractAddress(), + encodedFunc + ), + DefaultBlockParameterName.LATEST + ).send(); + + // 2.3 set `confirmed` and `successful` to false if reverted + CrossChainMessageReceipt crossChainMessageReceipt = new CrossChainMessageReceipt(); + if (call.isReverted()) { + crossChainMessageReceipt.setSuccessful(false); + crossChainMessageReceipt.setConfirmed(false); + crossChainMessageReceipt.setErrorMsg(call.getRevertReason()); + return crossChainMessageReceipt; + } + + // 2.4 async send tx + EthSendTransaction ethSendTransaction = rawTransactionManager.sendTransaction( + BigInteger.valueOf(this.config.getGasPrice()), + BigInteger.valueOf(this.config.getGasLimit()), + this.bbcContext.getAuthMessageContract().getContractAddress(), + encodedFunc, + BigInteger.ZERO + ); + + // 2.5 return crossChainMessageReceipt + crossChainMessageReceipt.setConfirmed(false); + crossChainMessageReceipt.setSuccessful(true); + crossChainMessageReceipt.setTxhash(ethSendTransaction.getTransactionHash()); + crossChainMessageReceipt.setErrorMsg(""); + + getBBCLogger().info("relay tx {}", ethSendTransaction.getTransactionHash()); + + return crossChainMessageReceipt; + } catch (Exception e) { + throw new RuntimeException( + String.format("failed to relay AM %s to %s", + HexUtil.encodeHexStr(rawMessage), this.bbcContext.getAuthMessageContract().getContractAddress() + ), e + ); + } + } +} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/EthTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/EthTest.java new file mode 100644 index 00000000..4bccdbf9 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/EthTest.java @@ -0,0 +1,58 @@ +package com.ali.antchain; + +import com.ali.antchain.service.EthereumBBCService; +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.commons.bbc.DefaultBBCContext; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; + +public class EthTest extends TestCase { + EthPluginsTest ethtest; + AbstractBBCService service; + AbstractBBCContext context; + String url = "http://127.0.0.1:7545"; + String key = "0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"; + long gasPrice = 2300000000L; + long gasLimit = 3000000; + @Before + public void setUp() throws Exception { + service = new EthereumBBCService(); + context = new DefaultBBCContext(); + ethtest = new EthPluginsTest(context,service); + ethtest.EthConfigInit(url,key,gasPrice,gasLimit); + } + @Test + public void testStartup() throws Exception { + ethtest.startup(); + } + + public void testShutdown() throws Exception { + ethtest.shutdown(); + } + + public void testGetcontext() throws Exception { + ethtest.getcontext(); + } + + public void testSetupAmContract() throws Exception { + ethtest.setupamcontract(); + } + + public void testSetupSDPContract() throws Exception { + ethtest.setupsdpcontract(); + } + + public void testQuerySDPMessageSeq() throws Exception { + ethtest.querysdpmessageseq(); + } + + public void testSetAmContractAndLocalDomain() throws Exception { + ethtest.setamcontractandlocaldomain(); + } + + public void testSetProtocol() throws Exception { + ethtest.setamcontractandlocaldomain(); + } +} \ No newline at end of file diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/TestPlugs.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/TestPlugs.java new file mode 100644 index 00000000..e4d7e639 --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/TestPlugs.java @@ -0,0 +1,46 @@ +package com.ali.antchain; + +import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; +import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; +import junit.framework.TestCase; + +public class TestPlugs extends TestCase { + +// String url = "http://127.0.0.1:7545"; +// String key = "0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"; +// long gasPrice = 2300000000L; +// long gasLimit = 3000000; + AbstractBBCContext context; + AbstractBBCService service; + + PluginsTest plugsTest = new PluginsTest(context,service); + + public void testStartup() throws Exception { + plugsTest.startup(); + } + + public void testShutdown() throws Exception { + plugsTest.shutdown(); + } + + public void testGetcontext() throws Exception { + plugsTest.getcontext(); + } + + public void testSetupamcontract() throws Exception { + plugsTest.setupamcontract(); + } + + public void testQuerysdpmessageseq() throws Exception { + plugsTest.querysdpmessageseq(); + } + + public void testSetprotocol() throws Exception { + plugsTest.setprotocol(); + } + + + public void testSetamcontractandlocaldomain() throws Exception { + plugsTest.setamcontractandlocaldomain(); + } +} \ No newline at end of file From 9e94e32bf596ae09dc1b942f599093f466f62894 Mon Sep 17 00:00:00 2001 From: sulc <1985972071@qq.com> Date: Tue, 27 Aug 2024 22:37:41 +0800 Subject: [PATCH 2/4] [feat][test-framework][v0.1.0] add plugin test framework --- .../antchain-bridge-plugin-tester/.gitignore | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/.gitignore diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/.gitignore b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/.gitignore new file mode 100644 index 00000000..5ff6309b --- /dev/null +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/.gitignore @@ -0,0 +1,38 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file From 15b8550d5a4fb16494a3077f558093cb92ea9981 Mon Sep 17 00:00:00 2001 From: sulc <1985972071@qq.com> Date: Tue, 27 Aug 2024 22:38:12 +0800 Subject: [PATCH 3/4] [feat][test-framework][v0.1.0] add plugin test framework --- .../antchain-bridge-plugin-tester/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml index 8b98a9e6..cab60067 100644 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml +++ b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml @@ -2,7 +2,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.ali.antchain antchain-bridge-plugin-tester 0.1.0 From 40893da3c27589fd26e52bfb4086a8a3995b6257 Mon Sep 17 00:00:00 2001 From: sulc <1985972071@qq.com> Date: Wed, 11 Sep 2024 22:13:05 +0800 Subject: [PATCH 4/4] [feat][test-framework][v0.1.0] add plugin test framework --- .../antchain-bridge-plugin-tester/.gitignore | 38 - .../antchain-bridge-plugin-tester/pom.xml | 65 -- .../java/com/ali/antchain/EthPluginsTest.java | 25 - .../java/com/ali/antchain/PluginsTest.java | 57 -- .../Test/ETHQuerySDPMessageSeqTest.java | 82 -- .../ETHSetAmContractAndLocalDomainTest.java | 63 -- .../ali/antchain/Test/ETHSetProtocolTest.java | 50 -- .../com/ali/antchain/Test/GetContextTest.java | 98 --- .../com/ali/antchain/Test/RelayAmPrepare.java | 74 -- .../Test/SetupAuthMessageContractTest.java | 39 - .../Test/SetupSDPMessageContractTest.java | 38 - .../com/ali/antchain/Test/ShutDownTest.java | 31 - .../com/ali/antchain/Test/StartUpTest.java | 33 - .../config/BlockHeightPolicyEnum.java | 20 - .../ali/antchain/config/EthereumConfig.java | 72 -- .../antchain/service/EthereumBBCService.java | 699 ------------------ .../test/java/com/ali/antchain/EthTest.java | 58 -- .../test/java/com/ali/antchain/TestPlugs.java | 46 -- 18 files changed, 1588 deletions(-) delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/.gitignore delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/EthPluginsTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/PluginsTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHQuerySDPMessageSeqTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetAmContractAndLocalDomainTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetProtocolTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/GetContextTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/RelayAmPrepare.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupAuthMessageContractTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupSDPMessageContractTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ShutDownTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/StartUpTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/BlockHeightPolicyEnum.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/EthereumConfig.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/service/EthereumBBCService.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/EthTest.java delete mode 100644 antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/TestPlugs.java diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/.gitignore b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/.gitignore deleted file mode 100644 index 5ff6309b..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/.gitignore +++ /dev/null @@ -1,38 +0,0 @@ -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### IntelliJ IDEA ### -.idea/modules.xml -.idea/jarRepositories.xml -.idea/compiler.xml -.idea/libraries/ -*.iws -*.iml -*.ipr - -### Eclipse ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ - -### Mac OS ### -.DS_Store \ No newline at end of file diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml deleted file mode 100644 index cab60067..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - 4.0.0 - - com.ali.antchain - antchain-bridge-plugin-tester - 0.1.0 - jar - - PlugsTest - http://maven.apache.org - - - UTF-8 - - - - - com.alipay.antchain.bridge - antchain-bridge-plugin-lib - 0.2.3 - - - com.alipay.antchain.bridge - antchain-bridge-spi - 0.2.3 - provided - - - org.web3j - core - 4.9.8 - - - org.slf4j - slf4j-api - - - - - junit - junit - 4.13.2 - test - - - org.projectlombok - lombok - 1.18.24 - compile - - - org.slf4j - slf4j-api - 1.7.28 - provided - - - ch.qos.logback - logback-classic - 1.2.11 - test - - - diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/EthPluginsTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/EthPluginsTest.java deleted file mode 100644 index e00de567..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/EthPluginsTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ali.antchain; - -import com.ali.antchain.Test.GetContextTest; -import com.ali.antchain.Test.ShutDownTest; -import com.ali.antchain.Test.StartUpTest; -import com.ali.antchain.config.EthereumConfig; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.commons.bbc.DefaultBBCContext; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; - -public class EthPluginsTest extends PluginsTest { - public EthPluginsTest(AbstractBBCContext context, AbstractBBCService service) { - super(context, service); - } - EthereumConfig config; - public void EthConfigInit(String url,String key,long gasPrice,long gasLimit) { - this.config = new EthereumConfig(); - config.setUrl(url); - config.setPrivateKey(key); - config.setGasPrice(gasPrice); - config.setGasLimit(gasLimit); - this.context = new DefaultBBCContext(); - context.setConfForBlockchainClient(config.toJsonString().getBytes()); - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/PluginsTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/PluginsTest.java deleted file mode 100644 index c3a1dbc1..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/PluginsTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.ali.antchain; - -import com.ali.antchain.Test.GetContextTest; -import com.ali.antchain.Test.ShutDownTest; -import com.ali.antchain.Test.StartUpTest; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; - -public class PluginsTest { - - AbstractBBCContext context; - AbstractBBCService service; - - public PluginsTest(AbstractBBCContext context, AbstractBBCService service) { - this.context = context; - this.service = service; - } - - public void startup() throws Exception { - StartUpTest.run(context, service); - } - - public void shutdown() throws Exception { - ShutDownTest.run(context,service); - } - - public void getcontext() throws Exception { - GetContextTest.run(context,service); - } - - public void setupamcontract() throws Exception {} - - public void setupsdpcontract() throws Exception {} - - public void querysdpmessageseq() throws Exception {} - - public void setprotocol() throws Exception { - - } - - public void setamcontractandlocaldomain() throws Exception { - - } - - -// public static void main(String[] args) throws Exception{ -// String url = "http://127.0.0.1:7545"; -// String key = "0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"; -// long gasPrice = 2300000000L; -// long gasLimit = 3000000; -// PlugsTest test = new PlugsTest(url,key,gasPrice,gasLimit); -//// test.ethinit.init(); -// test.startup(); -// } - - -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHQuerySDPMessageSeqTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHQuerySDPMessageSeqTest.java deleted file mode 100644 index 683a3a36..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHQuerySDPMessageSeqTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.ali.antchain.Test; - -import cn.hutool.crypto.digest.DigestUtil; -import com.ali.antchain.service.EthereumBBCService; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; - -public class ETHQuerySDPMessageSeqTest { - - boolean setupBBC; - - - public static void run(AbstractBBCContext context) throws Exception { - ETHQuerySDPMessageSeqTest ETHQuerySDPMessageSeqTest = new ETHQuerySDPMessageSeqTest(); - ETHQuerySDPMessageSeqTest.querysdpmessageseq(context); - } - - public void querysdpmessageseq(AbstractBBCContext context) throws Exception { - EthereumBBCService ethereumBBCService = new EthereumBBCService(); - ethereumBBCService.startup(context); - - if (setupBBC) { - System.out.println("The BBC has already been set up."); - }else { - RelayAmPrepare.relayamprepare(context); - } -// //set up am -// ethereumBBCService.setupAuthMessageContract(); -// -// // set up sdp -// ethereumBBCService.setupSDPMessageContract(); -// -// ethereumBBCService.setProtocol( -// context.getSdpContract().getContractAddress(), -// "0"); -// -// // set am to sdp -// ethereumBBCService.setAmContract(context.getAuthMessageContract().getContractAddress()); -// -// // set local domain to sdp -// ethereumBBCService.setLocalDomain("receiverDomain"); -// -// // check contract ready -// AbstractBBCContext ctxCheck = ethereumBBCService.getContext(); -// -// System.out.println(ctxCheck.getAuthMessageContract().getStatus()); -// System.out.println(ctxCheck.getSdpContract().getStatus()); -// -// Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:7545")); -// Credentials credentials = Credentials.create("0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"); -// -// RawTransactionManager rawTransactionManager = new RawTransactionManager( -// web3j, credentials, web3j.ethChainId().send().getChainId().longValue()); -// -// AppContract appContract = AppContract.deploy( -// web3j, -// rawTransactionManager, -// new DefaultGasProvider() -// ).send(); -// -// TransactionReceipt receipt = appContract.setProtocol(ethereumBBCService.getBbcContext().getSdpContract().getContractAddress()).send(); -// if (receipt.isStatusOK()) { -// System.out.println("set protocol(" + appContract.getContractAddress()+ ") to app contract(" +ethereumBBCService.getBbcContext().getSdpContract().getContractAddress()+ ")"); -// } else { -// throw new Exception(String.format("failed to set protocol(%s) to app contract(%s)", -// appContract.getContractAddress(), -// ethereumBBCService.getBbcContext().getSdpContract().getContractAddress())); -// } -// System.out.println(receipt); -// } - - // query seq - long seq = ethereumBBCService.querySDPMessageSeq( - "senderDomain", - DigestUtil.sha256Hex("senderID"), - "receiverDomain", - DigestUtil.sha256Hex("receiverID") - ); - System.out.println(seq); - - } - -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetAmContractAndLocalDomainTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetAmContractAndLocalDomainTest.java deleted file mode 100644 index f9204dea..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetAmContractAndLocalDomainTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.ali.antchain.Test; - -import cn.hutool.core.util.HexUtil; -import com.ali.antchain.abi.SDPMsg; -import com.ali.antchain.service.EthereumBBCService; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import org.web3j.tx.gas.DefaultGasProvider; - -public class ETHSetAmContractAndLocalDomainTest { - - public static void run(AbstractBBCContext context) throws Exception { - ETHSetAmContractAndLocalDomainTest ETHSetAmContractAndLocalDomainTest = new ETHSetAmContractAndLocalDomainTest(); - ETHSetAmContractAndLocalDomainTest.setamcontractandlocaldomain(context); - } - public void setamcontractandlocaldomain(AbstractBBCContext context) throws Exception { - EthereumBBCService ethereumBBCService = new EthereumBBCService(); - // start up - ethereumBBCService.startup(context); - - // set up am - ethereumBBCService.setupAuthMessageContract(); - - // set up sdp - ethereumBBCService.setupSDPMessageContract(); - - // get context - AbstractBBCContext ctx = ethereumBBCService.getContext(); - - System.out.println(ctx.getAuthMessageContract().getStatus()); - System.out.println(ctx.getSdpContract().getStatus()); - - // set am to sdp - ethereumBBCService.setAmContract(ctx.getAuthMessageContract().getContractAddress()); - - String amAddr = SDPMsg.load( - ethereumBBCService.getBbcContext().getSdpContract().getContractAddress(), - ethereumBBCService.getWeb3j(), - ethereumBBCService.getCredentials(), - new DefaultGasProvider() - ).getAmAddress().send(); - System.out.println("amAddr: {"+amAddr+"}"); - - // check contract status - ctx = ethereumBBCService.getContext(); - System.out.println(ctx.getSdpContract().getStatus()); - - // set the domain - ethereumBBCService.setLocalDomain("receiverDomain"); - - byte[] rawDomain = SDPMsg.load( - ethereumBBCService.getBbcContext().getSdpContract().getContractAddress(), - ethereumBBCService.getWeb3j(), - ethereumBBCService.getCredentials(), - new DefaultGasProvider() - ).getLocalDomain().send(); - System.out.println("domain: {"+HexUtil.encodeHexStr(rawDomain)+ "}"); - - // check contract status - ctx = ethereumBBCService.getContext(); - System.out.println(ctx.getSdpContract().getStatus()); - - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetProtocolTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetProtocolTest.java deleted file mode 100644 index f2ae4aff..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ETHSetProtocolTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ali.antchain.Test; - -import com.ali.antchain.abi.AuthMsg; -import com.ali.antchain.service.EthereumBBCService; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import org.web3j.tx.gas.DefaultGasProvider; - -import java.math.BigInteger; - -public class ETHSetProtocolTest { - - public static void run(AbstractBBCContext context) throws Exception { - ETHSetProtocolTest ETHSetProtocolTest = new ETHSetProtocolTest(); - ETHSetProtocolTest.setprotocol(context); - } - public void setprotocol(AbstractBBCContext context) throws Exception { - EthereumBBCService ethereumBBCService = new EthereumBBCService(); - // start up - ethereumBBCService.startup(context); - - // set up am - ethereumBBCService.setupAuthMessageContract(); - - // set up sdp - ethereumBBCService.setupSDPMessageContract(); - - // get context - AbstractBBCContext ctx = ethereumBBCService.getContext(); - System.out.println(ctx.getAuthMessageContract().getStatus()); - System.out.println(ctx.getSdpContract().getStatus()); - - // set protocol to am (sdp type: 0) - ethereumBBCService.setProtocol( - ctx.getSdpContract().getContractAddress(), - "0"); - - String addr = AuthMsg.load( - ethereumBBCService.getBbcContext().getAuthMessageContract().getContractAddress(), - ethereumBBCService.getWeb3j(), - ethereumBBCService.getCredentials(), - new DefaultGasProvider() - ).getProtocol(BigInteger.ZERO).send(); - System.out.println("protocol: {" + addr + "}"); - - // check am status - ctx = ethereumBBCService.getContext(); - System.out.println(ctx.getAuthMessageContract().getStatus()); - - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/GetContextTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/GetContextTest.java deleted file mode 100644 index 6316e017..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/GetContextTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.ali.antchain.Test; - -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.commons.bbc.syscontract.AuthMessageContract; -import com.alipay.antchain.bridge.commons.bbc.syscontract.SDPContract; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class GetContextTest { - - private static final Logger log = LoggerFactory.getLogger(GetContextTest.class); - AbstractBBCService service; - - public GetContextTest(AbstractBBCService service) { - this.service = service; - } - public static void run(AbstractBBCContext context, AbstractBBCService service){ - GetContextTest getctx = new GetContextTest(service); - getctx.getcontext(context); - } - public void getcontext(AbstractBBCContext context){ - if (service == null) { - throw new IllegalStateException("Service is not initialized."); - } - try { - // 启动服务 - service.startup(context); - // 获取上下文 - AbstractBBCContext ctx = service.getContext(); - // 检查上下文是否为空 - if (ctx != null) { - log.info( "Context: {}", ctx); - - // 打印 AM 合约 - processAuthMessageContract(ctx); - - // 打印 SDP 合约 - processSDPContract(ctx); - - } else { - log.warn( "Context is null."); - } - } catch (Exception e) { - // 处理异常 - log.error("An error occurred: ", e); - } - } - private void processAuthMessageContract(AbstractBBCContext ctx) { - AuthMessageContract authMessageContract = ctx.getAuthMessageContract(); - if (authMessageContract != null) { - log.info("Auth Message Contract: {}", authMessageContract); - } - } - - private void processSDPContract(AbstractBBCContext ctx) { - SDPContract sdpContract = ctx.getSdpContract(); - if (sdpContract != null) { - log.info("SDP Contract: {}", sdpContract); - } - } -} - -//public class GetContextTest { -// -// private static final Logger log = LoggerFactory.getLogger(GetContextTest.class); -// -// private AbstractBBCService service; -// -// public GetContextTest(AbstractBBCService service) { -// this.service = service; -// } -// -// public static void run(AbstractBBCContext context){ -// getcontext(context); -// } -// -// public void getcontext(AbstractBBCContext context){ -// if (service == null) { -// throw new IllegalStateException("Service is not initialized."); -// } -// try { -// service.startup(context); -// AbstractBBCContext ctx = service.getContext(); -// if (ctx != null) { -// log.info("Context: {}", ctx); -// processAuthMessageContract(ctx); -// processSDPContract(ctx); -// } else { -// log.warn("Context is null."); -// } -// } catch (Exception e) { -// log.error("An unexpected error occurred: ", e); -// } -// } -// -// -//} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/RelayAmPrepare.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/RelayAmPrepare.java deleted file mode 100644 index edf95712..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/RelayAmPrepare.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.ali.antchain.Test; - -import com.ali.antchain.abi.AppContract; -import com.ali.antchain.service.EthereumBBCService; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import org.web3j.crypto.Credentials; -import org.web3j.protocol.Web3j; -import org.web3j.protocol.core.methods.response.TransactionReceipt; -import org.web3j.protocol.http.HttpService; -import org.web3j.tx.RawTransactionManager; -import org.web3j.tx.gas.DefaultGasProvider; - -public class RelayAmPrepare { - - static boolean setupBBC; - static AppContract appContract; - - public static void relayamprepare(AbstractBBCContext context) throws Exception { - if (setupBBC) { - return; - } - - // start up - EthereumBBCService ethereumBBCService = new EthereumBBCService(); - ethereumBBCService.startup(context); - - // set up am - ethereumBBCService.setupAuthMessageContract(); - - // set up sdp - ethereumBBCService.setupSDPMessageContract(); - - // set protocol to am (sdp type: 0) - ethereumBBCService.setProtocol( - context.getSdpContract().getContractAddress(), - "0"); - - // set am to sdp - ethereumBBCService.setAmContract(context.getAuthMessageContract().getContractAddress()); - - // set local domain to sdp - ethereumBBCService.setLocalDomain("receiverDomain"); - - // check contract ready - AbstractBBCContext ctxCheck = ethereumBBCService.getContext(); - - System.out.println(ctxCheck.getAuthMessageContract().getStatus()); - System.out.println(ctxCheck.getSdpContract().getStatus()); - - Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:7545")); - Credentials credentials = Credentials.create("0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"); - - RawTransactionManager rawTransactionManager = new RawTransactionManager( - web3j, credentials, web3j.ethChainId().send().getChainId().longValue()); - - appContract = AppContract.deploy( - web3j, - rawTransactionManager, - new DefaultGasProvider() - ).send(); - - TransactionReceipt receipt = appContract.setProtocol(ethereumBBCService.getBbcContext().getSdpContract().getContractAddress()).send(); - if (receipt.isStatusOK()) { - System.out.println("set protocol(" + appContract.getContractAddress()+ ") to app contract(" +ethereumBBCService.getBbcContext().getSdpContract().getContractAddress()+ ")"); - } else { - throw new Exception(String.format("failed to set protocol(%s) to app contract(%s)", - appContract.getContractAddress(), - ethereumBBCService.getBbcContext().getSdpContract().getContractAddress())); - } - System.out.println(receipt); - - setupBBC = true; - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupAuthMessageContractTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupAuthMessageContractTest.java deleted file mode 100644 index 327b5de7..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupAuthMessageContractTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.ali.antchain.Test; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; - - - -public class SetupAuthMessageContractTest { - - private static final Logger log = LoggerFactory.getLogger(SetupAuthMessageContractTest.class); - AbstractBBCService service; - - public SetupAuthMessageContractTest(AbstractBBCService service) { - this.service = service; - } - - public static void run(AbstractBBCContext context, AbstractBBCService service){ - SetupAuthMessageContractTest SetupAm = new SetupAuthMessageContractTest(service); - SetupAm.setupamcontract(context); - } - - public void setupamcontract(AbstractBBCContext context) { - try { - service.startup(context); - service.setupAuthMessageContract(); - - // 获取上下文 - AbstractBBCContext ctx = service.getContext(); - - // 打印AM合约状态 - log.info("The status of the auth message contract is: {}", ctx.getAuthMessageContract().getStatus()); - } catch (Exception e) { - // 异常信息 - log.error("Failed to setup authentication message contract", e); - } - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupSDPMessageContractTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupSDPMessageContractTest.java deleted file mode 100644 index 6825c874..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/SetupSDPMessageContractTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.ali.antchain.Test; - -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SetupSDPMessageContractTest { - - private static final Logger log = LoggerFactory.getLogger(SetupAuthMessageContractTest.class); - AbstractBBCService service; - - public SetupSDPMessageContractTest(AbstractBBCService service) { - this.service = service; - } - - public static void run(AbstractBBCContext context, AbstractBBCService service){ - SetupSDPMessageContractTest SetupSDP = new SetupSDPMessageContractTest(service); - SetupSDP.setupsdpcontract(context); - } - - public void setupsdpcontract(AbstractBBCContext context) { - if (service == null) { - throw new IllegalStateException("Service is not initialized."); - } - try { - service.startup(context); - service.setupAuthMessageContract(); - // set up sdp - service.setupSDPMessageContract(); - // get context - AbstractBBCContext ctx = service.getContext(); - log.info("SDP contract status: {}", ctx.getSdpContract().getStatus()); - } catch (Exception e) { - log.error("Error setting up SDP contract", e); - } - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ShutDownTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ShutDownTest.java deleted file mode 100644 index d82da61a..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/ShutDownTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ali.antchain.Test; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; - -public class ShutDownTest { - - private static final Logger log = LoggerFactory.getLogger(ShutDownTest.class); - AbstractBBCService service; - - public ShutDownTest(AbstractBBCService service) { - this.service = service; - } - - public static void run(AbstractBBCContext context, AbstractBBCService service){ - ShutDownTest shutdown = new ShutDownTest(service); - shutdown.shutdown(context); - } - - public void shutdown(AbstractBBCContext context){ - try { - // 调用 shutdown关闭服务 - service.shutdown(); - } catch (Exception e) { - // 异常 - log.error("Failed to setup authentication message contract", e.getMessage()); - } - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/StartUpTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/StartUpTest.java deleted file mode 100644 index 19f28a13..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/Test/StartUpTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ali.antchain.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; - -public class StartUpTest { - - private static final Logger log = LoggerFactory.getLogger(StartUpTest.class); - AbstractBBCService service; - - public StartUpTest(AbstractBBCService service) { - this.service = service; - } - - public static void run(AbstractBBCContext context, AbstractBBCService service){ - StartUpTest startUpTest = new StartUpTest(service); - startUpTest.startuptest_success(context); - } - - public void startuptest_success(AbstractBBCContext context) { - try { - service.startup(context); - // 使用日志框架记录信息 - log.info("Context: {}", service.getContext()); - log.info("AuthMessageContract: {}", service.getContext().getAuthMessageContract()); - log.info("SdpContract: {}", service.getContext().getSdpContract()); - } catch (Exception e) { - // 异常处理 - log.error("Error during startup test", e); - } - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/BlockHeightPolicyEnum.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/BlockHeightPolicyEnum.java deleted file mode 100644 index 51917f06..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/BlockHeightPolicyEnum.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ali.antchain.config; - -import lombok.Getter; -import org.web3j.protocol.core.DefaultBlockParameterName; - -@Getter -public enum BlockHeightPolicyEnum { - - LATEST(DefaultBlockParameterName.LATEST), - - SAFE(DefaultBlockParameterName.SAFE), - - FINALIZED(DefaultBlockParameterName.FINALIZED); - - BlockHeightPolicyEnum(DefaultBlockParameterName defaultBlockParameterName) { - this.defaultBlockParameterName = defaultBlockParameterName; - } - - private final DefaultBlockParameterName defaultBlockParameterName; -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/EthereumConfig.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/EthereumConfig.java deleted file mode 100644 index a6f5b54e..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/config/EthereumConfig.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2023 Ant Group - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.ali.antchain.config; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.annotation.JSONField; -import lombok.Getter; -import lombok.Setter; -import org.web3j.tx.gas.DefaultGasProvider; - -import java.io.IOException; - -/** - * Ethereum's configuration information - * - Url for Ethereum node rpc - * - Private key - */ -@Getter -@Setter -public class EthereumConfig { - - /** - * 从json字符串反序列化 - * - * @param jsonString raw json - */ - public static EthereumConfig fromJsonString(String jsonString) throws IOException { - return JSON.parseObject(jsonString, EthereumConfig.class); - } - - @JSONField - private String url; - - @JSONField - private String privateKey; - - @JSONField - private long gasLimit = DefaultGasProvider.GAS_LIMIT.longValue(); - - @JSONField - private long gasPrice = DefaultGasProvider.GAS_PRICE.longValue(); - - @JSONField - private String amContractAddressDeployed; - - @JSONField - private String sdpContractAddressDeployed; - - @JSONField - private BlockHeightPolicyEnum blockHeightPolicy = BlockHeightPolicyEnum.LATEST; - - /** - * json序列化为字符串 - */ - public String toJsonString() { - return JSON.toJSONString(this); - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/service/EthereumBBCService.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/service/EthereumBBCService.java deleted file mode 100644 index 329bb6f6..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/main/java/com/ali/antchain/service/EthereumBBCService.java +++ /dev/null @@ -1,699 +0,0 @@ -/* - * Copyright 2023 Ant Group - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.ali.antchain.service; - -import cn.hutool.core.collection.ListUtil; -import cn.hutool.core.util.HexUtil; -import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.StrUtil; -import com.ali.antchain.abi.AuthMsg; -import com.ali.antchain.abi.SDPMsg; -import com.ali.antchain.config.EthereumConfig; -import com.alibaba.fastjson.JSON; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.commons.bbc.syscontract.AuthMessageContract; -import com.alipay.antchain.bridge.commons.bbc.syscontract.ContractStatusEnum; -import com.alipay.antchain.bridge.commons.bbc.syscontract.SDPContract; -import com.alipay.antchain.bridge.commons.core.base.CrossChainMessage; -import com.alipay.antchain.bridge.commons.core.base.CrossChainMessageReceipt; - -import com.alipay.antchain.bridge.plugins.lib.BBCService; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; -import lombok.Getter; -import org.web3j.abi.EventEncoder; -import org.web3j.abi.FunctionEncoder; -import org.web3j.abi.datatypes.DynamicBytes; -import org.web3j.abi.datatypes.Function; -import org.web3j.crypto.Credentials; -import org.web3j.protocol.Web3j; -import org.web3j.protocol.core.DefaultBlockParameterName; -import org.web3j.protocol.core.DefaultBlockParameterNumber; -import org.web3j.protocol.core.methods.request.EthFilter; -import org.web3j.protocol.core.methods.request.Transaction; -import org.web3j.protocol.core.methods.response.*; -import org.web3j.protocol.http.HttpService; -import org.web3j.tx.RawTransactionManager; -import org.web3j.tx.gas.StaticGasProvider; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import static com.ali.antchain.abi.AuthMsg.SENDAUTHMESSAGE_EVENT; - -@BBCService(products = "simple-ethereum", pluginId = "plugin-simple-ethereum") -@Getter -public class EthereumBBCService extends AbstractBBCService { - - private EthereumConfig config; - - private Web3j web3j; - - private Credentials credentials; - - private AbstractBBCContext bbcContext; - - private RawTransactionManager rawTransactionManager; - - @Override - public void startup(AbstractBBCContext abstractBBCContext) { - getBBCLogger().info("ETH BBCService startup with context: {}", new String(abstractBBCContext.getConfForBlockchainClient())); - - if (ObjectUtil.isNull(abstractBBCContext)) { - throw new RuntimeException("null bbc context"); - } - if (ObjectUtil.isEmpty(abstractBBCContext.getConfForBlockchainClient())) { - throw new RuntimeException("empty blockchain client conf"); - } - - // 1. Obtain the configuration information - try { - config = EthereumConfig.fromJsonString(new String(abstractBBCContext.getConfForBlockchainClient())); - } catch (IOException e) { - throw new RuntimeException(e); - } - - if(StrUtil.isEmpty(config.getPrivateKey())){ - throw new RuntimeException("private key is empty"); - } - - if(StrUtil.isEmpty(config.getUrl())){ - throw new RuntimeException("ethereum url is empty"); - } - - // 2. Connect to the Ethereum network - BigInteger chainId; - try { - web3j = Web3j.build(new HttpService(config.getUrl())); - chainId = web3j.ethChainId().send().getChainId(); - } catch (Exception e) { - throw new RuntimeException(String.format("failed to connect ethereum (url: %s)", config.getUrl()), e); - } - - // 3. Connect to the specified wallet account - this.credentials = Credentials.create(config.getPrivateKey()); - - // 4. Create tx manager with web3j and credentials - this.rawTransactionManager = new RawTransactionManager(this.web3j, this.credentials, chainId.longValue()); - - // 5. set context - this.bbcContext = abstractBBCContext; - - // 6. set the pre-deployed contracts into context - if (ObjectUtil.isNull(abstractBBCContext.getAuthMessageContract()) - && StrUtil.isNotEmpty(this.config.getAmContractAddressDeployed())) { - AuthMessageContract authMessageContract = new AuthMessageContract(); - authMessageContract.setContractAddress(this.config.getAmContractAddressDeployed()); - authMessageContract.setStatus(ContractStatusEnum.CONTRACT_DEPLOYED); - this.bbcContext.setAuthMessageContract(authMessageContract); - } - - if (ObjectUtil.isNull(abstractBBCContext.getSdpContract()) - && StrUtil.isNotEmpty(this.config.getSdpContractAddressDeployed())) { - SDPContract sdpContract = new SDPContract(); - sdpContract.setContractAddress(this.config.getSdpContractAddressDeployed()); - sdpContract.setStatus(ContractStatusEnum.CONTRACT_DEPLOYED); - this.bbcContext.setSdpContract(sdpContract); - } - } - - @Override - public void shutdown() { - getBBCLogger().info("shut down ETH BBCService!"); - this.web3j.shutdown(); - } - - @Override - public AbstractBBCContext getContext() { - if (ObjectUtil.isNull(this.bbcContext)){ - throw new RuntimeException("empty bbc context"); - } - - getBBCLogger().debug("ETH BBCService context (amAddr: {}, amStatus: {}, sdpAddr: {}, sdpStatus: {})", - this.bbcContext.getAuthMessageContract() != null ? this.bbcContext.getAuthMessageContract().getContractAddress() : "", - this.bbcContext.getAuthMessageContract() != null ? this.bbcContext.getAuthMessageContract().getStatus() : "", - this.bbcContext.getSdpContract() != null ? this.bbcContext.getSdpContract().getContractAddress() : "", - this.bbcContext.getSdpContract() != null ? this.bbcContext.getSdpContract().getStatus() : "" - ); - - return this.bbcContext; - } - - @Override - public CrossChainMessageReceipt readCrossChainMessageReceipt(String txHash) { - // 1. Obtain Ethereum receipt according to transaction hash - TransactionReceipt transactionReceipt; - - try { - transactionReceipt = web3j.ethGetTransactionReceipt(txHash) - .send().getTransactionReceipt().orElse(null); - } catch (IOException e) { - throw new RuntimeException( - String.format( - "failed to read cross chain message receipt (txHash: %s)", txHash - ), e - ); - } - - // 2. Construct cross-chain message receipt - CrossChainMessageReceipt crossChainMessageReceipt = getCrossChainMessageReceipt(transactionReceipt); - getBBCLogger().info("cross chain message receipt for txhash {} : {}", txHash, JSON.toJSONString(crossChainMessageReceipt)); - - return crossChainMessageReceipt; - } - - private CrossChainMessageReceipt getCrossChainMessageReceipt(TransactionReceipt transactionReceipt) { - CrossChainMessageReceipt crossChainMessageReceipt = new CrossChainMessageReceipt(); - if (transactionReceipt == null) { - // If the transaction is not packaged, the return receipt is empty - crossChainMessageReceipt.setConfirmed(false); - crossChainMessageReceipt.setSuccessful(false); - crossChainMessageReceipt.setTxhash(""); - crossChainMessageReceipt.setErrorMsg(""); - return crossChainMessageReceipt; - } - - BigInteger currHeight = queryLatestBlockHeight(); - if (transactionReceipt.getBlockNumber().compareTo(currHeight) > 0) { - crossChainMessageReceipt.setConfirmed(false); - crossChainMessageReceipt.setSuccessful(true); - crossChainMessageReceipt.setTxhash(transactionReceipt.getTransactionHash()); - crossChainMessageReceipt.setErrorMsg(""); - return crossChainMessageReceipt; - } - - List receiveMessageEventResponses = SDPMsg.getReceiveMessageEvents(transactionReceipt); - if (ObjectUtil.isNotEmpty(receiveMessageEventResponses)) { - SDPMsg.ReceiveMessageEventResponse response = receiveMessageEventResponses.get(0); - crossChainMessageReceipt.setConfirmed(true); - crossChainMessageReceipt.setSuccessful(transactionReceipt.isStatusOK() && response.result); - crossChainMessageReceipt.setTxhash(transactionReceipt.getTransactionHash()); - crossChainMessageReceipt.setErrorMsg( - transactionReceipt.isStatusOK() ? StrUtil.format( - "SDP calls biz contract: {}", response.result ? "SUCCESS" : response.errMsg - ) : StrUtil.emptyToDefault(transactionReceipt.getRevertReason(), "") - ); - getBBCLogger().info( - "event receiveMessage from SDP contract is found in no.{} tx {} of block {} : " + - "( send_domain: {}, sender: {}, receiver: {}, biz_call: {}, err_msg: {} )", - transactionReceipt.getTransactionIndex().toString(), transactionReceipt.getTransactionHash(), transactionReceipt.getBlockHash(), - response.senderDomain, HexUtil.encodeHexStr(response.senderID), response.receiverID, response.result.toString(), - response.errMsg - ); - return crossChainMessageReceipt; - } - - crossChainMessageReceipt.setConfirmed(true); - crossChainMessageReceipt.setSuccessful(transactionReceipt.isStatusOK()); - crossChainMessageReceipt.setTxhash(transactionReceipt.getTransactionHash()); - crossChainMessageReceipt.setErrorMsg(StrUtil.emptyToDefault(transactionReceipt.getRevertReason(), "")); - - return crossChainMessageReceipt; - } - - @Override - public List readCrossChainMessagesByHeight(long height) { - if (ObjectUtil.isNull(this.bbcContext)){ - throw new RuntimeException("empty bbc context"); - } - - if (ObjectUtil.isNull(this.bbcContext.getAuthMessageContract())){ - throw new RuntimeException("empty am contract in bbc context"); - } - - try { - // 1. get eth logs - List logs = web3j.ethGetLogs( - new EthFilter( - new DefaultBlockParameterNumber(BigInteger.valueOf(height)), - new DefaultBlockParameterNumber(BigInteger.valueOf(height)), - this.bbcContext.getAuthMessageContract().getContractAddress() - ).addSingleTopic(EventEncoder.encode(SENDAUTHMESSAGE_EVENT)) - ).send().getLogs(); - - // 2. get block - EthBlock.Block block = web3j.ethGetBlockByNumber(new DefaultBlockParameterNumber(height), false).send().getBlock(); - - // 3. get crosschain msgs - List messageList = ListUtil.toList(); - for (EthLog.LogResult logResult : logs) { - // 3.1 get log obj - EthLog.LogObject logObject = (EthLog.LogObject) logResult.get(); - - // 3.2 get receipt - TransactionReceipt transactionReceipt; - transactionReceipt = web3j.ethGetTransactionReceipt(logObject.getTransactionHash()).send().getResult(); - - // 3.3 create crosschain msg - messageList.addAll(AuthMsg.getSendAuthMessageEvents(transactionReceipt).stream().map( - response -> CrossChainMessage.createCrossChainMessage( - CrossChainMessage.CrossChainMessageType.AUTH_MSG, - logObject.getBlockNumber().longValue(), - block.getTimestamp().longValue(), - HexUtil.decodeHex(StrUtil.removePrefix(logObject.getBlockHash().trim(), "0x")), - response.pkg, - // todo: put ledger data, for SPV or other attestations - // this time we need no verify. it's ok to set it with empty bytes - "".getBytes(), - // todo: put proof data - // this time we need no proof data. it's ok to set it with empty bytes - "".getBytes(), - HexUtil.decodeHex(logObject.getTransactionHash().replaceFirst("^0x", "")) - ) - ).collect(Collectors.toList())); - } - - if (!messageList.isEmpty()) { - getBBCLogger().info("read cross chain messages (height: {}, msg_size: {})", height, messageList.size()); - getBBCLogger().debug("read cross chain messages (height: {}, msgs: {})", - height, - messageList.stream().map(JSON::toJSONString).collect(Collectors.joining(",")) - ); - } - - return messageList; - } catch (Exception e) { - throw new RuntimeException( - String.format( - "failed to readCrossChainMessagesByHeight (Height: %d, contractAddr: %s, topic: %s)", - height, - this.bbcContext.getAuthMessageContract().getContractAddress(), - SENDAUTHMESSAGE_EVENT - ), e - ); - } - } - - @Override - public Long queryLatestHeight() { - Long l = queryLatestBlockHeight().longValue(); - getBBCLogger().debug("latest height: {}", l); - return l; - } - - private BigInteger queryLatestBlockHeight() { - BigInteger l; - try { - l = web3j.ethGetBlockByNumber(config.getBlockHeightPolicy().getDefaultBlockParameterName(), false) - .send() - .getBlock() - .getNumber(); - } catch (IOException e) { - throw new RuntimeException("failed to query latest height", e); - } - return l; - } - - @Override - public void setupAuthMessageContract() { - // 1. check context - if (ObjectUtil.isNull(this.bbcContext)){ - throw new RuntimeException("empty bbc context"); - } - if (ObjectUtil.isNotNull(this.bbcContext.getAuthMessageContract()) - && StrUtil.isNotEmpty(this.bbcContext.getAuthMessageContract().getContractAddress())) { - // If the contract has been pre-deployed and the contract address is configured in the configuration file, - // there is no need to redeploy. - return; - } - - // 2. deploy contract - AuthMsg authMsg; - try { - authMsg = AuthMsg.deploy( - web3j, - rawTransactionManager, - new StaticGasProvider( - BigInteger.valueOf(this.config.getGasPrice()), - BigInteger.valueOf(this.config.getGasLimit()) - ) - ).send(); - } catch (Exception e) { - throw new RuntimeException("failed to deploy authMsg", e); - } - - // 3. get tx receipt - TransactionReceipt transactionReceipt = authMsg.getTransactionReceipt().orElse(null); - - // 4. check whether the deployment is successful - if (!ObjectUtil.isNull(transactionReceipt) && transactionReceipt.getStatus().equals("0x1")) { - AuthMessageContract authMessageContract = new AuthMessageContract(); - authMessageContract.setContractAddress(authMsg.getContractAddress()); - authMessageContract.setStatus(ContractStatusEnum.CONTRACT_DEPLOYED); - bbcContext.setAuthMessageContract(authMessageContract); - - getBBCLogger().info("setup am contract successful: {}", authMsg.getContractAddress()); - } else { - throw new RuntimeException("failed to get deploy authMsg tx receipt"); - } - } - - @Override - public void setupSDPMessageContract() { - // 1. check context - if (ObjectUtil.isNull(this.bbcContext)){ - throw new RuntimeException("empty bbc context"); - } - if (ObjectUtil.isNotNull(this.bbcContext.getSdpContract()) - && StrUtil.isNotEmpty(this.bbcContext.getSdpContract().getContractAddress())) { - // If the contract has been pre-deployed and the contract address is configured in the configuration file, - // there is no need to redeploy. - return; - } - - // 2. deploy contract - SDPMsg sdpMsg; - try { - sdpMsg = SDPMsg.deploy( - web3j, - rawTransactionManager, - new StaticGasProvider( - BigInteger.valueOf(this.config.getGasPrice()), - BigInteger.valueOf(this.config.getGasLimit()) - ) - ).send(); - } catch (Exception e) { - throw new RuntimeException("failed to deploy sdpMsg", e); - } - - // 3. get tx receipt - TransactionReceipt transactionReceipt = sdpMsg.getTransactionReceipt().orElse(null); - - // 4. check whether the deployment is successful - if (!ObjectUtil.isNull(transactionReceipt) && transactionReceipt.getStatus().equals("0x1")) { - SDPContract sdpContract = new SDPContract(); - sdpContract.setContractAddress(sdpMsg.getContractAddress()); - sdpContract.setStatus(ContractStatusEnum.CONTRACT_DEPLOYED); - bbcContext.setSdpContract(sdpContract); - getBBCLogger().info("setup sdp contract successful: {}", sdpMsg.getContractAddress()); - } else { - throw new RuntimeException("failed to get deploy sdpMsg tx receipt"); - } - } - - @Override - public long querySDPMessageSeq(String senderDomain, String senderID, String receiverDomain, String receiverID) { - // 1. check context - if (ObjectUtil.isNull(this.bbcContext)){ - throw new RuntimeException("empty bbc context"); - } - if (ObjectUtil.isNull(this.bbcContext.getSdpContract())){ - throw new RuntimeException("empty sdp contract in bbc context"); - } - - // 2. load sdpMsg - SDPMsg sdpMsg = SDPMsg.load( - bbcContext.getSdpContract().getContractAddress(), - web3j, - rawTransactionManager, - new StaticGasProvider( - BigInteger.valueOf(this.config.getGasPrice()), - BigInteger.valueOf(this.config.getGasLimit()) - ) - ); - - // 3. query sequence - long seq; - try { - seq = sdpMsg.querySDPMessageSeq( - senderDomain, - HexUtil.decodeHex(senderID), - receiverDomain, - HexUtil.decodeHex(receiverID) - ).send().longValue(); - - getBBCLogger().info("sdpMsg seq: {} (senderDomain: {}, senderID: {}, receiverDomain: {}, receiverID: {})", - seq, - senderDomain, - senderID, - receiverDomain, - receiverID - ); - } catch (Exception e) { - throw new RuntimeException(String.format( - "failed to query sdpMsg seq (senderDomain: %s, senderID: %s, receiverDomain: %s, receiverID: %s)", - senderDomain, - senderID, - receiverDomain, - receiverID - ), e); - } - - return seq; - } - - @Override - public void setProtocol(String protocolAddress, String protocolType) { - // 1. check context - if (ObjectUtil.isNull(this.bbcContext)) { - throw new RuntimeException("empty bbc context"); - } - if (ObjectUtil.isNull(this.bbcContext.getAuthMessageContract())){ - throw new RuntimeException("empty am contract in bbc context"); - } - - // 2. load am contract - AuthMsg am = AuthMsg.load( - this.bbcContext.getAuthMessageContract().getContractAddress(), - this.web3j, - this.rawTransactionManager, - new StaticGasProvider( - BigInteger.valueOf(this.config.getGasPrice()), - BigInteger.valueOf(this.config.getGasLimit()) - ) - ); - - // 3. set protocol to am - try { - TransactionReceipt receipt = am.setProtocol(protocolAddress, BigInteger.valueOf(Long.parseLong(protocolType))).send(); - getBBCLogger().info( - "set protocol (address: {}, type: {}) to AM {} by tx {} ", - protocolAddress, protocolType, - this.bbcContext.getAuthMessageContract().getContractAddress(), - receipt.getTransactionHash() - ); - } catch (Exception e) { - throw new RuntimeException( - String.format( - "failed to set protocol (address: %s, type: %s) to AM %s", - protocolAddress, protocolType, this.bbcContext.getAuthMessageContract().getContractAddress() - ), e - ); - } - - // 4. update am contract status - try { - if (!StrUtil.isEmpty(am.getProtocol(BigInteger.ZERO).send())){ - this.bbcContext.getAuthMessageContract().setStatus(ContractStatusEnum.CONTRACT_READY); - } - } catch (Exception e) { - throw new RuntimeException( - String.format( - "failed to update am contract status (address: %s)", - this.bbcContext.getAuthMessageContract().getContractAddress() - ), e); - } - } - - @Override - public void setAmContract(String contractAddress) { - // 1. check context - if (ObjectUtil.isNull(this.bbcContext)) { - throw new RuntimeException("empty bbc context"); - } - if (ObjectUtil.isNull(this.bbcContext.getSdpContract())){ - throw new RuntimeException("empty sdp contract in bbc context"); - } - - // 2. load sdp contract - SDPMsg sdp = SDPMsg.load( - this.bbcContext.getSdpContract().getContractAddress(), - this.web3j, - this.rawTransactionManager, - new StaticGasProvider( - BigInteger.valueOf(this.config.getGasPrice()), - BigInteger.valueOf(this.config.getGasLimit()) - ) - ); - - // 3. set am to sdp - try { - TransactionReceipt receipt = sdp.setAmContract(contractAddress).send(); - getBBCLogger().info( - "set am contract (address: {}) to SDP {} by tx {}", - contractAddress, - this.bbcContext.getSdpContract().getContractAddress(), - receipt.getTransactionHash() - ); - } catch (Exception e) { - throw new RuntimeException( - String.format( - "failed to set am contract (address: %s) to SDP %s", - contractAddress, - this.bbcContext.getSdpContract().getContractAddress() - ), e - ); - } - - // 4. update sdp contract status - try { - if (!StrUtil.isEmpty(sdp.getAmAddress().send()) && !isByteArrayZero(sdp.getLocalDomain().send())){ - this.bbcContext.getSdpContract().setStatus(ContractStatusEnum.CONTRACT_READY); - } - } catch (Exception e) { - throw new RuntimeException( - String.format( - "failed to update sdp contract status (address: %s)", - this.bbcContext.getSdpContract().getContractAddress() - ), e); - } - } - - private boolean isByteArrayZero(byte[] bytes) { - for (byte b : bytes) { - if (b != 0x00) { - return false; - } - } - return true; - } - - @Override - public void setLocalDomain(String domain) { - // 1. check context - if (ObjectUtil.isNull(this.bbcContext)) { - throw new RuntimeException("empty bbc context"); - } - if (StrUtil.isEmpty(this.bbcContext.getSdpContract().getContractAddress())) { - throw new RuntimeException("none sdp contract address"); - } - - // 2. load sdp contract - SDPMsg sdp = SDPMsg.load( - this.bbcContext.getSdpContract().getContractAddress(), - this.web3j, - this.rawTransactionManager, - new StaticGasProvider( - BigInteger.valueOf(this.config.getGasPrice()), - BigInteger.valueOf(this.config.getGasLimit()) - ) - ); - - // 3. set domain to sdp - try { - TransactionReceipt receipt = sdp.setLocalDomain(domain).send(); - getBBCLogger().info( - "set domain ({}) to SDP {} by tx {}", - domain, - this.bbcContext.getSdpContract().getContractAddress(), - receipt.getTransactionHash() - ); - } catch (Exception e) { - throw new RuntimeException( - String.format( - "failed to set domain (%s) to SDP %s", - domain, - this.bbcContext.getSdpContract().getContractAddress() - ), e - ); - } - - // 4. update sdp contract status - try { - if (!StrUtil.isEmpty(sdp.getAmAddress().send()) && !ObjectUtil.isEmpty(sdp.getLocalDomain().send())){ - this.bbcContext.getSdpContract().setStatus(ContractStatusEnum.CONTRACT_READY); - } - } catch (Exception e) { - throw new RuntimeException( - String.format( - "failed to update sdp contract status (address: %s)", - this.bbcContext.getSdpContract().getContractAddress() - ), e); - } - } - - @Override - public CrossChainMessageReceipt relayAuthMessage(byte[] rawMessage) { - // 1. check context - if (ObjectUtil.isNull(this.bbcContext)) { - throw new RuntimeException("empty bbc context"); - } - if (ObjectUtil.isNull(this.bbcContext.getAuthMessageContract())){ - throw new RuntimeException("empty am contract in bbc context"); - } - - getBBCLogger().info("relay AM {} to {} ", - HexUtil.encodeHexStr(rawMessage), this.bbcContext.getAuthMessageContract().getContractAddress()); - - // 2. creat Transaction - try { - // 2.1 create function - Function function = new Function( - AuthMsg.FUNC_RECVPKGFROMRELAYER, // funtion name - Collections.singletonList(new DynamicBytes(rawMessage)), // inputs - Collections.emptyList() // outputs - ); - String encodedFunc = FunctionEncoder.encode(function); - - // 2.2 pre-execute before commit tx - EthCall call = this.web3j.ethCall( - Transaction.createEthCallTransaction( - this.credentials.getAddress(), - this.bbcContext.getAuthMessageContract().getContractAddress(), - encodedFunc - ), - DefaultBlockParameterName.LATEST - ).send(); - - // 2.3 set `confirmed` and `successful` to false if reverted - CrossChainMessageReceipt crossChainMessageReceipt = new CrossChainMessageReceipt(); - if (call.isReverted()) { - crossChainMessageReceipt.setSuccessful(false); - crossChainMessageReceipt.setConfirmed(false); - crossChainMessageReceipt.setErrorMsg(call.getRevertReason()); - return crossChainMessageReceipt; - } - - // 2.4 async send tx - EthSendTransaction ethSendTransaction = rawTransactionManager.sendTransaction( - BigInteger.valueOf(this.config.getGasPrice()), - BigInteger.valueOf(this.config.getGasLimit()), - this.bbcContext.getAuthMessageContract().getContractAddress(), - encodedFunc, - BigInteger.ZERO - ); - - // 2.5 return crossChainMessageReceipt - crossChainMessageReceipt.setConfirmed(false); - crossChainMessageReceipt.setSuccessful(true); - crossChainMessageReceipt.setTxhash(ethSendTransaction.getTransactionHash()); - crossChainMessageReceipt.setErrorMsg(""); - - getBBCLogger().info("relay tx {}", ethSendTransaction.getTransactionHash()); - - return crossChainMessageReceipt; - } catch (Exception e) { - throw new RuntimeException( - String.format("failed to relay AM %s to %s", - HexUtil.encodeHexStr(rawMessage), this.bbcContext.getAuthMessageContract().getContractAddress() - ), e - ); - } - } -} diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/EthTest.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/EthTest.java deleted file mode 100644 index 4bccdbf9..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/EthTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.ali.antchain; - -import com.ali.antchain.service.EthereumBBCService; -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.commons.bbc.DefaultBBCContext; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Test; - -public class EthTest extends TestCase { - EthPluginsTest ethtest; - AbstractBBCService service; - AbstractBBCContext context; - String url = "http://127.0.0.1:7545"; - String key = "0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"; - long gasPrice = 2300000000L; - long gasLimit = 3000000; - @Before - public void setUp() throws Exception { - service = new EthereumBBCService(); - context = new DefaultBBCContext(); - ethtest = new EthPluginsTest(context,service); - ethtest.EthConfigInit(url,key,gasPrice,gasLimit); - } - @Test - public void testStartup() throws Exception { - ethtest.startup(); - } - - public void testShutdown() throws Exception { - ethtest.shutdown(); - } - - public void testGetcontext() throws Exception { - ethtest.getcontext(); - } - - public void testSetupAmContract() throws Exception { - ethtest.setupamcontract(); - } - - public void testSetupSDPContract() throws Exception { - ethtest.setupsdpcontract(); - } - - public void testQuerySDPMessageSeq() throws Exception { - ethtest.querysdpmessageseq(); - } - - public void testSetAmContractAndLocalDomain() throws Exception { - ethtest.setamcontractandlocaldomain(); - } - - public void testSetProtocol() throws Exception { - ethtest.setamcontractandlocaldomain(); - } -} \ No newline at end of file diff --git a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/TestPlugs.java b/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/TestPlugs.java deleted file mode 100644 index e4d7e639..00000000 --- a/antchain-bridge-plugin-test/antchain-bridge-plugin-tester/src/test/java/com/ali/antchain/TestPlugs.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.ali.antchain; - -import com.alipay.antchain.bridge.commons.bbc.AbstractBBCContext; -import com.alipay.antchain.bridge.plugins.spi.bbc.AbstractBBCService; -import junit.framework.TestCase; - -public class TestPlugs extends TestCase { - -// String url = "http://127.0.0.1:7545"; -// String key = "0x45cfa3b6addf98274bfd9e3482a695406c7dcc99e1588bd6e0127b8fc06ae916"; -// long gasPrice = 2300000000L; -// long gasLimit = 3000000; - AbstractBBCContext context; - AbstractBBCService service; - - PluginsTest plugsTest = new PluginsTest(context,service); - - public void testStartup() throws Exception { - plugsTest.startup(); - } - - public void testShutdown() throws Exception { - plugsTest.shutdown(); - } - - public void testGetcontext() throws Exception { - plugsTest.getcontext(); - } - - public void testSetupamcontract() throws Exception { - plugsTest.setupamcontract(); - } - - public void testQuerysdpmessageseq() throws Exception { - plugsTest.querysdpmessageseq(); - } - - public void testSetprotocol() throws Exception { - plugsTest.setprotocol(); - } - - - public void testSetamcontractandlocaldomain() throws Exception { - plugsTest.setamcontractandlocaldomain(); - } -} \ No newline at end of file